language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
1,257
2.65625
3
[ "MIT" ]
permissive
import unittest from tests.basic_test import BasicTestCase, db from tests.crud import * class QueryOnClassMethod: @db.query(CREATE) def instance(self, user): pass @staticmethod @db.query(CREATE) def static_method(user): pass @db.bulk_query(CREATE) def bulk_query_instance(self, users): pass @staticmethod @db.bulk_query(CREATE) def bulk_query_static_method(users): pass class QueryOnClassMethodTestCase(BasicTestCase): def test_1_instance(self): instance = QueryOnClassMethod() instance.instance(user) result = select().first() self.assertEqual(result.name, 'leo1') def test_2_static_method(self): QueryOnClassMethod.static_method(user) result = select().first() self.assertEqual(result.name, 'leo1') def test_3_bulk_instance(self): instance = QueryOnClassMethod() instance.bulk_query_instance(users) results = select() self.assertEqual(len(results), 4) def test_4_bulk_static_method(self): QueryOnClassMethod.bulk_query_static_method(users) results = select() self.assertEqual(len(results), 6) if __name__ == '__main__': unittest.main()
Python
UTF-8
1,987
2.8125
3
[]
no_license
from socket import * import threading import sys ip = str(sys.argv[1]) port = int(sys.argv[2]) print('Chat Server started on port %d'%port) clients = [] def send_msg(msg, conn): print(msg) for client in clients: if client != conn: try: client.send(msg.encode()) except Exception as e: print(e) def send_all(msg): print(msg) for client in clients: try: client.send(msg.encode()) except Exception as e: print(e) def receive(connectionSocket, addr): user_flag = 'user' if len(clients) < 2 else 'users' enter_msg = '\n> New user %s:%s entered (%d %s online)'%(addr[0], addr[1], len(clients), user_flag) send_msg(enter_msg, connectionSocket) enter_msg2 = '\n> Connected to the chat server (%d %s online)'%(len(clients), user_flag) connectionSocket.send(enter_msg2.encode()) while True: data = connectionSocket.recv(1024) if data: string = data.decode() user_msg = "[%s:%s] %s"%(addr[0], addr[1], string) send_msg(user_msg, connectionSocket) else: clients.remove(connectionSocket) user_flag = 'user' if len(clients) < 2 else 'users' leave_msg = '\n< The user %s:%s left (%d %s online)'%(addr[0], addr[1], len(clients), user_flag) send_all(leave_msg) break connectionSocket.close() serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) serverSocket.bind((ip, port)) serverSocket.listen(5) while True: try: connectionSocket, addr = serverSocket.accept() except KeyboardInterrupt: for client in clients: client.close() serverSocket.close() print('\nexit') break clients.append(connectionSocket) t = threading.Thread(target=receive, args=(connectionSocket, addr)) t.daemon = True t.start()
Python
UTF-8
3,422
2.703125
3
[ "MIT" ]
permissive
import requests import json class Client(): def __init__(self, school=""): self.session = requests.Session() if school != "": self.endpoint = "https://{}.zportal.nl/api".format(school) else: raise ValueError("School is not defined.") def authenticate(self, code=""): if code == "": raise ValueError("Code is not defined.") url = "{}/v3/oauth/token".format(self.endpoint) data = { "grant_type": "authorization_code", "code": code.replace(" ", "") } res = self.session.post(url=url, data=data) if res.status_code == 400: raise ValueError("Parsed code is not active.") elif res.status_code == 404: raise ValueError("School does not exist.") elif res.status_code == 200: return json.loads(res.text) def get_user(self, token=""): if token == "": raise ValueError("Token is not defined.") url = "{}/v3/users/~me".format(self.endpoint) params = {"access_token": token} res = self.session.get(url=url, params=params) if res.status_code == 401: raise ValueError("Token not active.") elif res.status_code == 200: return json.loads(res.text) def get_appointments(self, token="", start_unix="", end_unix=""): if token == "": raise ValueError("Token is not defined.") elif start_unix == "": raise ValueError("Start unix timestamp is not defined.") elif end_unix == "": raise ValueError("End unix timestamp is not defined.") url = "{}/v3/appointments/".format(self.endpoint) params = { "user": "~me", "start": start_unix, "end": end_unix, "access_token": token } res = self.session.get(url=url, params=params) if res.status_code == 403: raise ValueError( "Start unix timestamp and / or end unix timestamp make no sense.") elif res.status_code == 401: raise ValueError("Token not active.") elif res.status_code == 200: return json.loads(res.text) def get_announcements(self, token=""): if token == "": raise ValueError("Token is not defined.") url = "{}/v2/announcements".format(self.endpoint) params = { "user": "~me", "access_token": token } res = self.session.get(url=url, params=params) if res.status_code == 401: raise ValueError("Token not active.") elif res.status_code == 200: return json.loads(res.text) def get_liveschedule(self, token="", week: str = None, usercode: str = None): if token == "": raise ValueError("Token is not defined.") if week == None: raise ValueError("Week is not defined.") if usercode == None: raise ValueError("Usercode is not defined.") url = f"{self.endpoint}/v3/liveschedule?student={usercode}&week={week}" params = { "access_token": token } res = self.session.get(url, params=params) if res.status_code == 401: raise ValueError("Token not active.") elif res.status_code == 200: return json.loads(res.text)
Java
UTF-8
5,454
1.734375
2
[]
no_license
/* * Decompiled with CFR 0.151. */ package com.google.android.gms.internal.measurement; import com.google.android.gms.internal.measurement.zzgs; import com.google.android.gms.internal.measurement.zzhi; import com.google.android.gms.internal.measurement.zzhu; import com.google.android.gms.internal.measurement.zzia; import com.google.android.gms.internal.measurement.zzie; import com.google.android.gms.internal.measurement.zzix; import com.google.android.gms.internal.measurement.zzjl; import com.google.android.gms.internal.measurement.zzjs; import com.google.android.gms.internal.measurement.zzko; import com.google.android.gms.internal.measurement.zzkp; import java.util.ArrayList; import java.util.List; public final class zzhj { private static final zzhj zzd; public final zzjs zza; private boolean zzb; private boolean zzc; static { zzhj zzhj2; zzd = zzhj2 = new zzhj(true); } private zzhj() { zzjl zzjl2 = new zzjl(16); this.zza = zzjl2; } private zzhj(boolean bl2) { zzjl zzjl2 = new zzjl(0); this.zza = zzjl2; this.zzb(); this.zzb(); } public static zzhj zza() { throw null; } private static final void zzd(zzhi object, Object object2) { Object[] objectArray; Object object3; block13: { block14: { object3 = object.zzb(); zzia.zza(object2); objectArray = zzko.zza; objectArray = zzkp.zza; object3 = ((zzko)((Object)object3)).zza(); int n10 = ((Enum)object3).ordinal(); switch (n10) { default: { break block13; } case 8: { n10 = object2 instanceof zzix; if (n10 == 0 && (n10 = object2 instanceof zzie) == 0) break block13; break block14; } case 7: { n10 = object2 instanceof Integer; if (n10 == 0 && (n10 = object2 instanceof zzhu) == 0) break block13; break block14; } case 6: { n10 = object2 instanceof zzgs; if (n10 == 0 && (n10 = object2 instanceof byte[]) == 0) break block13; break block14; } case 5: { n10 = object2 instanceof String; break; } case 4: { n10 = object2 instanceof Boolean; break; } case 3: { n10 = object2 instanceof Double; break; } case 2: { n10 = object2 instanceof Float; break; } case 1: { n10 = object2 instanceof Long; break; } case 0: { n10 = object2 instanceof Integer; } } if (n10 == 0) break block13; } return; } objectArray = new Object[3]; Integer n11 = object.zza(); objectArray[0] = n11; object = object.zzb().zza(); objectArray[1] = object; objectArray[2] = object2 = object2.getClass().getName(); object = String.format("Wrong object type used with protocol message reflection.\nField number: %d, field java type: %s, value type: %s\n", objectArray); object3 = new IllegalArgumentException((String)object); throw object3; } public final boolean equals(Object object) { if (this == object) { return true; } boolean bl2 = object instanceof zzhj; if (!bl2) { return false; } object = (zzhj)object; zzjs zzjs2 = this.zza; object = ((zzhj)object).zza; return zzjs2.equals(object); } public final int hashCode() { return this.zza.hashCode(); } public final void zzb() { boolean bl2 = this.zzb; if (bl2) { return; } this.zza.zza(); this.zzb = true; } /* * Enabled aggressive block sorting */ public final void zzc(zzhi object, Object list) { boolean bl2 = object.zzc(); if (bl2) { bl2 = list instanceof List; if (!bl2) { object = new IllegalArgumentException("Wrong object type used with protocol message reflection."); throw object; } ArrayList arrayList = new ArrayList(); list = list; arrayList.addAll(list); int n10 = arrayList.size(); for (int i10 = 0; i10 < n10; ++i10) { Object e10 = arrayList.get(i10); zzhj.zzd((zzhi)object, e10); } list = arrayList; } else { zzhj.zzd((zzhi)object, list); } bl2 = list instanceof zzie; if (bl2) { this.zzc = bl2 = true; } this.zza.zzf((Comparable)object, list); } }
Java
UTF-8
241
1.6875
2
[]
no_license
package com.shop.shop.domain.user.dto; import lombok.Builder; import lombok.Data; @Data @Builder public class UpdateUser { private int id; private String email; private String phone; private String address; private String password; }
Python
UTF-8
1,160
2.875
3
[]
no_license
import argparse import socket import sys contents = { 1: ("content1_1", "content1_2", "10.0.1.100", 10001), 2: ("content2_1", "content2_2", "10.0.2.100", 10002), 3: ("content3_1", "content3_2", "10.0.3.100", 10003), 4: ("content4_1", "content4_2", "10.0.4.100", 10004), } parser = argparse.ArgumentParser(description="Determine host.") parser.add_argument( "host_num", type=int, help="integer representing host number" ) args = parser.parse_args() serving_contents = contents[args.host_num] # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the socket to the port server_address = (serving_contents[2], serving_contents[3]) print "starting up on %s port %s" % server_address sock.bind(server_address) num_requests = 0 while True: print "\nwaiting to receive message" data, address = sock.recvfrom(4096) num_requests += 1 print "Request %d: received %s bytes from %s" % ( num_requests, len(data), address ) print data if data in serving_contents[:2]: sent = sock.sendto(data, address) print "sent %s bytes back to %s" % (sent, address)
Markdown
UTF-8
1,739
2.9375
3
[]
no_license
## EXCEL 如果需要进行计算,在输入公式时不想输入等号,可以点击文件-》选项-》高级-》转换Lotus 1-2-3公式选项,即可实现,使用完毕后记得取消该选项 Excel 2010 1.交换两列数据的位置 选中整列,按shift,拖动到目标列右侧 (若不按shift,会问是否替换!数据可能被覆盖) 2.插入列或行 都是在选中的列或行前面插入 插入多行或列:选中多个。 如:选中n列,右键插入,则在前面插入n列。 3.选中底层多个工作表 选中第一个,按shift,选中目标的最后一个 4.列宽度 双击ABCDEFG,自动调整列宽度 选择多列,在边框线双击,即可自动调整多列宽度。 选择多列,再调整列宽度,可以同时调整多列宽,并且他们是被一致调整的。 5.迅速到达表格最后或最前 选中任一单元格,鼠标在下(上)边线变成方向标志,双击,即可到达最后(前)。 或者Ctrl+ 上下方向键。 6.冻结窗格 冻结首行: 视图☞冻结窗格☞冻结首行 即可实现滚动表格,而首行不动。 冻结多行: 以冻结前3行为例,选中第4行首个单元格,选择冻结拆分窗格命令。 同时冻结行和列: 选中某一单元格,选择冻结拆分窗格格命令。选中的单元格操作符合下面的规律: 规律:总是冻结选择单元格上面和左面的窗格。 7.填充柄 鼠标实心加号拖拽自动填充数据,这个功能叫做填充柄。 按住Ctrl再左键拖拽,可以反转自动填充的逻辑。例如,顺序填充变复制填充。 按右键拖拽,会弹出快捷菜单,提供丰富的填充选项。 自定义序列:选项☞高级☞编辑自定义列表
C++
UTF-8
1,561
2.578125
3
[]
no_license
#include <iostream> #include <vector> #include <cstdio> #include <algorithm> #include <queue> using namespace std; int cost[1001]; int dp[1001]; int indegree[1001]; queue<int> searchQue; vector<vector<int> > arr(1001); int main() { int t; cin >> t; while(t--) { int n,k; scanf("%d %d",&n,&k); for(int i = 1 ; i <= n ; i++) { scanf("%d", &cost[i]); dp[i] = cost[i]; } int start, finish; for(int i = 0 ; i < k ; i++) { scanf("%d %d",&start,&finish); arr[start].push_back(finish); indegree[finish]++; } int winNum; scanf("%d",&winNum); for(int i = 1 ; i <= n ; i++) { if(indegree[i] == 0) { searchQue.push(i); } } while(indegree[winNum]) { if(searchQue.size()) { int tmp = searchQue.front(); for(int i = 0 ; i < arr[tmp].size() ; i++) { indegree[arr[tmp][i]]--; if(indegree[arr[tmp][i]] == 0) { searchQue.push(arr[tmp][i]); } dp[arr[tmp][i]] = max(dp[arr[tmp][i]], dp[tmp] + cost[arr[tmp][i]]); } searchQue.pop(); } } printf("%d\n", dp[winNum]); for(int i = 1 ; i <= n ; i++) { cost[i] = 0; dp[i] = 0; indegree[i] = 0; arr[i].clear(); } while (searchQue.size()) searchQue.pop(); } return 0; } // int solve(int winNum, int cost[], vector<vector<int> > arr, int dp[]) { // if(dp[winNum] > 0) { // return dp[winNum]; // } // int result = 0; // for(int i = 0 ; i < arr[winNum].size() ; i++) { // result = max(result, solve(arr[winNum][i],cost,arr,dp)); // } // return dp[winNum] = result + cost[winNum]; // }
C
UTF-8
167
3.515625
4
[]
no_license
#include "isUpper.h" int isUpper(char c) { if (c >= 'A' && c<= 'Z') return 1; return 0; /* If an uppercase, return true (1). Otherwise, return false (0) */ }
Java
UTF-8
7,117
3.203125
3
[]
no_license
import java.util.*; import java.util.concurrent.*; class Log { int count; int id; public Log(int id) { this.id = id; } } enum Granularity { YEAR, MONTH, DAY, HOUR, MINUTE, SECOND; } interface LogStorage { void put(int logId, long timestamp); List<Integer> get(long timeStampStart, long timeStampEnd, Granulary granularity); /** Key learnings: -> Finding a range of nodes within a well ordered linked structure such as BST, Trie, Heap, etc. -> Similarities between representing a String in a trie and that of representing a Log with varying timestamps per granuarity in a Trie. **/ } class TimeStampSpliter { public Map<Granularity,Long> splitByGranularity(long timeStamp) { } public Map<Granularity, Long> splitByGranularityV2(long timeStamp) { } } class LogStorageTrie implements LogStorage { TimeStampSplitter splitter; TrieNode root; class TrieNode { Log log; long timeStamp; TrieNode[] family; public TrieNode(int logId, long timeStamp) { log = new Log(logId); this.timeStamp = timeStamp; } public void increment() { log.count+=1; } public int logId() { return log.id; } } private static final Granularity[] granularities = new Granularity[] { Granularity.YEAR, Granularity.MONTH, Granularity.DAY, Granularity.HOUR, Granularity.MINUTE, Granularity.SECOND }; public LogStorageTrie() { splitter = new TimeStampSplitter(); } @Override public void put(int logId, long timeStamp) { Map<Granularity, Long> timeStampPerGranularity = splitter.splitByGranularity(timeStamp); root = insert(root, logId, granularities, timeStampPerGranularity, 0); } private TrieNode insert(TrieNode current, int logId, Granularity[] granularities, Map<Granularity, Long> timeStampMap, int curr) { Granularity currentGranularity = granularities[curr]; long currentTimeStamp = timeStampMap.get(currentGranularity); if (current == null) current = new TrieNode(logId, currentTimeStamp); if (current.timeStamp > currentTimeStamp) current.family[0] = insert(current.family[0], logId, granularities, timeStampMap, curr); else if (current.timeStamp < currentTimeStamp) current.family[2] = insert(current.family[2], logId, granularities, timeStampMap, curr); else if (curr == granularities.length - 1) current.increment(); else current.family[1] = insert(current.family[1], logId, granularities, timeStampMap, curr+1); return current; } @Override public List<Integer> get(long timeStampStart, long timeStampEnd, Granulary granularity) { Map<Granularity, Long> timeStampPerGranularityStart = splitter.splitByGranularity(timeStampStart); Map<Granularity, Long> timeStampPerGranularityEnd = splitter.splitByGranularity(timeStampEnd); List<Integer> desiredLogs = new ArrayList<>(); TrieNode firstValidNode = findFirstValidNode(timeStampStart, timeStampEnd); findAll(firstValidNode, timeStampStart, timeStampPerGranularityStart, timeStampPerGranularityStartEnd, 0, desiredLogs); return desiredLogs; } private void findAll(TrieNode current, Map<Granularity, Long> timeStampMapStart, Map<Granularity, Long> timeStampMapEnd, Granularity[] granularities, int curr, List<Integer> desiredLogs) { Queue<TrieNode> bfsSiblingTraversal = new LinkedList<>(); long timeStampStart = timeStampMapStart.get(granularites[curr]); long timeStampEnd = timeStampMapEnd.get(granularites[curr]); bfsSiblingTraversal.add(current); while (!bfsSiblingTraversal.isEmpty()) { TrieNode current = bfsSiblingTraversal.poll(); if (current.family[0] != null && current.family[0].timeStamp >= timeStampStart && current.family[0].timeStamp <= timeStampEnd) { bfsSiblingTraversal.add(current.family[0]); } if (current.family[2] != null && current.family[2].timeStamp >= timeStampStart && current.family[2].timeStamp <= timeStampEnd) { bfsSiblingTraversal.add(current.family[2]); } if (curr == granularites.length - 1) { desiredLogs.add(current.logId()); } else { findAll(current.family[1], timeStampMapStart, timeStampMapEnd, granularities, curr + 1, desiredLogs); } } } } class LogStorageBst implements LogStorage { TimeStampSplitter splitter; Map<Granularity, Logs> logsPerGranularity; private static final Granularity[] granularities = new Granularity[] { Granularity.YEAR, Granularity.MONTH, Granularity.DAY, Granularity.HOUR, Granularity.MINUTE, Granularity.SECOND }; class Logs { class BstNode { Log log; long timeStamp; BstNode left, right; public BstNode(int logId, long timeStamp) { log = new Log(logId); this.timeStamp = timeStamp; } public void increment() {log.count += 1;} } BstNode root; public void add(int logId, long timestamp) { BstNode runner = root; while (runner.left != null || runner.right != null) { if (runner.timestamp > timestamp) runner = runner.left; else if (runner.timestamp <= timestamp) runner = runner.right; } if (timestamp < runner.timestamp) runner.left = new BstNode(logId, timestamp); else runner.right = new BstNode(logId, timestamp); } public List<Integer> findAll(long timeStampStart, long timeStampEnd) { //TODO List<Integer> allNodes = new ArrayList<>(); findAll(root, timeStampStart, timeStampEnd, allNodes); } private void findAll(BstNode current, long timeStampStart, long timeStampEnd, List<Integer> desiredLogs) { if (current != null) { if (current.timeStamp >= timeStampStart && current.timeStamp <= timeStampEnd) { desiredLogs.add(current.log.id); } if (current.left != null && current.timeStamp >= timeStampStart) findAll(current.left, timeStampStart, timeStampEnd, desiredLogs); if (current.right != null && current.timeStamp <= timeStampEnd) findAll(current.right, timeStampStart, timeStampEnd, desiredLogs); } } } @Override public void put(int logId, long timeStamp) { Map<Granularity, Long> timeStampPerGranularity = splitter.splitByGranularityV2(timeStamp); for (Granularity granularity : granularities) { long timestamp = timeStampPerGranularity.get(granularity); Logs logs = logsPerGranularity.get(granularity); logs.add(logId, timestamp); } } @Override public List<Integer> get(long timeStampStart, long timeStampEnd, Granulary granularity) { Map<Granularity, Long> timeStampPerGranularityStart = splitter.splitByGranularityV2(timeStampStart); Map<Granularity, Long> timeStampPerGranularityEnd = splitter.splitByGranularityV2(timeStampEnd); long timestamp = timeStampPerGranularity.get(granularity); Logs logs = logsPerGranularity.get(granularity); List<Integer> desiredLogs = logs.findAll(timeStampPerGranularityStart.get(granularity), timeStampPerGranularityEnd.get(granularity)); return desiredLogs; } } public class LogStorageClient { public static void main(String[] args) { //Log storage implemented via a Trie LogStorage logStorageTrie = new LogStorageTrie(); //Log storage system implemented via a Map and BST LogStorage logStorageBst = new LogStorageBst(); } }
TypeScript
UTF-8
1,068
2.734375
3
[ "MIT" ]
permissive
import chalk from "chalk"; import * as ip from "ip" const divider = chalk.gray('-----------------------------------'); export const logger = { // Called when express.js app starts on given port w/o errors appStarted: (port: string | number, title = 'Server started ') => { console.log(chalk.underline.bold(title) + ` ${chalk.green('✓')}`); console.log(` ${chalk.bold('Access URLs:')} ${divider} Localhost: ${chalk.magenta(`http://localhost:${port}`)} LAN: ${chalk.magenta(`http://${ip.address()}:${port}`)} ${divider} `); }, error(message: string, error: any) { let errString = "" try { errString = JSON.stringify(error, null, 2); } catch (e) { errString = String(error); } console.error(chalk.bold.red(`[ERROR] -> ${message}`), errString); } }; export function sanitizeHeaders(headers: { [name: string]: string }) { if (headers.Authorization) { const [authType, authToken] = headers.Authorization.split(" "); headers.Authorization = `${authType} *****` } return headers; }
Markdown
UTF-8
1,640
3.21875
3
[]
no_license
--- layout: layouts/recipe.njk title: Mushroom and Leek Pie permalink: /food/mushroom-leek-pie/ image: mushroom-leek-pie.jpg serves: 4 time: 35 mins challenge: 1 intro: I recently discovered that the grocery store right near us sells vegan (notably dairy free) puff pastry. As a lover of pie, here's a leek, asparagus and mushroom pie - which I made without dairy, but you could easily include if you wished. ingredients: - filling: [2 leeks (chopped into 1-2cm circles), 200g of asparagus (remove the woody parts then cut into halves), olive oil, 3 garlic cloves (crushed), 400g mushrooms, a couple of sprigs of fresh rosemary and thyme, salt and pepper] - white sauce: [40g butter, 2 tbsp flour, 350ml of almond, oat or other alternative milk] - pastry: [1 270g sheet of ready-made pastry, 1 egg or some milk for brushing] --- - Sauté the leeks and asparagus in olive oil with the crushed garlic cloves, for only a couple of minutes or until the leek just starts to soften. - Add the mushrooms (cutting the larger ones into smaller pieces), fresh mixed herbs (rosemary thyme), and season. Cover and cook for another 8 minutes. - Make a white sauce in a saucepan; mix the butter and flour into a paste at a low heat, add the milk and continue stirring until the sauce thickens. - Add in the vegetables and leave to cool down in the pan. Whilst you wait for this, preheat the oven to 200C. - Put your filling into a pie dish, top with the pastry and press the edges down with a fork, brush with egg or more milk, then criss-cross with a knife. - Cook for 25 minutes, serve with some lightly steamed or boiled veg & baby potatoes.
C++
UTF-8
1,371
3.5625
4
[]
no_license
#include <iostream> enum class CardRank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE, MAX_CARDS }; enum class CardSuit { CLUB, SPADES, HEARTS, DIAMONDS, MAX_SUITS }; struct card { CardSuit suit{}; CardRank rank{}; }; void PrintDeck(const card& card) { switch (card.rank) { case CardRank::TWO: std::cout << '2'; break; case CardRank::THREE: std::cout << '3'; break; case CardRank::FOUR: std::cout << '4'; break; case CardRank::FIVE: std::cout << '5'; break; case CardRank::SIX: std::cout << '6'; break; case CardRank::SEVEN: std::cout << '7'; break; case CardRank::EIGHT: std::cout << '8'; break; case CardRank::NINE: std::cout << '9'; break; case CardRank::TEN: std::cout << '10'; break; case CardRank::JACK: std::cout << 'J'; break; case CardRank::QUEEN: std::cout << 'Q'; break; case CardRank::KING: std::cout << 'K'; break; case CardRank::ACE: std::cout << 'A'; break; default: std::cout << '?'; break; break; } switch (card.suit) { case CardSuit::CLUB: std::cout << 'C'; break; case CardSuit::SPADES: std::cout << 'S'; break; case CardSuit::HEARTS: std::cout << 'H'; break; case CardSuit::DIAMONDS: std::cout << 'D'; break; default: std::cout << '?'; break; break; } } int main() { return 0; }
Java
UTF-8
4,829
2.328125
2
[ "MIT" ]
permissive
package main.java.controller; import main.java.model.Cancion; import main.java.model.Usuario; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; @WebServlet(urlPatterns = "/uploadSong", name = "UploadSongController") public class UploadSongController extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); Usuario username = (Usuario) session.getAttribute("username"); username.setConexion(); // Actualiza estado de conexion del usuario username.saveUser(); Usuario User = (Usuario) session.getAttribute("username"); String UA = request.getHeader("User-Agent"); try { //Modificaciones en la base de datos. String nombre = request.getParameter("nombre"); String genero = request.getParameter("album"); String album = "error"; //Almacenamiento de ficheros. File file; int maxFileSize = 10000 * 1024; int maxMemSize = 10000 * 1024; String filePath = "/contenido/imagenes/usuarios/"; String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File("/contenido")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); //Encontramos campos. while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fieldName = fi.getFieldName(); if (fi.isFormField()) { //Recuperamos parametros. if (fieldName.equals("nombre")) nombre = fi.getString(); if (fieldName.equals("genero")) genero = fi.getString(); if (fieldName.equals("album")) album = fi.getString(); } } Cancion cancion = Cancion.addCancion(nombre, genero, User); i = fileItems.iterator(); //Subimos ficheros. while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fieldName = fi.getFieldName(); if (!fi.isFormField()) { //Almacenamos ficheros. if (fieldName.equals("cancion")) { filePath = "/contenido/canciones/"; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); file = new File(filePath + Integer.toString(cancion.getIdCancion()) + ".mp3"); fi.write(file); } else { filePath = "/contenido/imagenes/canciones/"; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); file = new File(filePath + Integer.toString(cancion.getIdCancion()) + ".png"); fi.write(file); } } } } if (UA.contains("Mobile")) { response.sendRedirect("/movil/usuario.jsp"); } else { response.sendRedirect("/escritorio/usuario.jsp"); } } catch (Exception e) { RequestDispatcher rd; e.printStackTrace(); request.setAttribute("error", e.getMessage()); if (UA.contains("Mobile")) { rd = request.getRequestDispatcher("/movil/subirCancion.jsp"); } else { rd = request.getRequestDispatcher("/escritorio/subirMusica.jsp"); } rd.forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
JavaScript
UTF-8
2,979
3.875
4
[]
no_license
// Returns a random DNA base const returnRandBase = () => { const dnaBases = ['A', 'T', 'C', 'G']; return dnaBases[Math.floor(Math.random() * 4)]; }; // Returns a random single stand of DNA containing 15 bases const mockUpStrand = () => { const newStrand = []; for (let i = 0; i < 15; i++) { newStrand.push(returnRandBase()); } return newStrand; }; /** * pAequor Factory * return an object that contains the properties * specimenNum and dna that correspond to the parameters provided. * * @param int number : no two organisms should have the same number * @param array arr : array of 15 DNA bases */ const pAequorFactory = (number, arr) => { return { specimenNum: number, dna: arr, // change one randomly selected element in dna array mutate() { // select a base in the dna property let select = Math.floor(Math.random() * this.dna.length); let newBase = returnRandBase(); // generated new based value while (this.dna[select] === newBase) { newBase = returnRandBase(); } this.dna[select] = newBase; }, // compare dna of two different pAequor compareDNA(pAequor) { let curr = this.dna; let past = pAequor.dna; let cnt = 0; for(let i = 0; i < curr.length; i++) { if(curr[i] === past[i]) { cnt++; } } let perc = (cnt/(curr.length) * 100).toFixed(2); console.log(`specimen #1 and specimen #2 have ${perc}% DNA in common`); }, // check if it will likely survive willLikelySurvive() { let cnt = 0; for(let each of this.dna) { if (each === 'C' || each === 'G') { cnt++; } } let perc = (cnt/this.dna.length) * 100; // console.log(`percent of survival: ${perc}`); if (perc >= 60) { return true; } else { return false; } }, // look for complement strands that match DNA strand // https://discoveringthegenome.org/discovering-genome/dna-sequencing/dna-complementary-base-pairing complementStrand() { let compleDNA = this.dna.map(strand => { switch(strand) { case 'A': return 'T'; break; case 'T': return 'A'; break; case 'C': return 'G'; break; case 'G': return 'C'; break; default: break; } }); return compleDNA; }, }; } /** * Testing */ let x = pAequorFactory(1, mockUpStrand()); console.log(x.dna); console.log(x.complementStrand()); // x.mutate(); // console.log(x.dna); // let y = pAequorFactory(2, mockUpStrand()); // console.log(y.dna); // x.compareDNA(y); // console.log(x.willLikelySurvive()); /** * Create 30 survived instance of pAequor * */ function survival30() { let cnt = 0; let spec = 0; let survived = []; while (cnt < 30) { let dna = mockUpStrand(); let newpAe = pAequorFactory(spec, dna); if (newpAe.willLikelySurvive()) { survived.push(newpAe); cnt++; } spec++; } console.log(survived); console.log(cnt); } // survival30();
C#
UTF-8
7,080
2.828125
3
[]
no_license
using System; using System.Windows.Forms; namespace Tema1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } bool isNewEntry = false, isRepeatLastOperation = false; double result = 0, operand = 0; char previousOperator = new char(); public void disable() { txtBox.Enabled = false; btnOff.Hide(); btnOn.Show(); btn0.Enabled = false; btn1.Enabled = false; btn2.Enabled = false; btn3.Enabled = false; btn4.Enabled = false; btn5.Enabled = false; btn6.Enabled = false; btn7.Enabled = false; btn8.Enabled = false; btn9.Enabled = false; btnPercent.Enabled = false; btnPow.Enabled = false; btnReverse.Enabled = false; btnSqrt.Enabled = false; btnAddition.Enabled = false; btnClear.Enabled = false; btnDelete.Enabled = false; btnDivison.Enabled = false; btnEqual.Enabled = false; btnMinus.Enabled = false; btnMultiplication.Enabled = false; btnNegative.Enabled = false; btnPoint.Enabled = false; } public void enable() { txtBox.Enabled = true; btnOff.Show(); btnOn.Hide(); btn0.Enabled = true; btn1.Enabled = true; btn2.Enabled = true; btn3.Enabled = true; btn4.Enabled = true; btn5.Enabled = true; btn6.Enabled = true; btn7.Enabled = true; btn8.Enabled = true; btn9.Enabled = true; btnPercent.Enabled = true; btnPow.Enabled = true; btnReverse.Enabled = true; btnSqrt.Enabled = true; btnAddition.Enabled = true; btnClear.Enabled = true; btnDelete.Enabled = true; btnDivison.Enabled = true; btnEqual.Enabled = true; btnMinus.Enabled = true; btnMultiplication.Enabled = true; btnNegative.Enabled = true; btnPoint.Enabled = true; } private void btnOn_Click(object sender, EventArgs e) { enable(); } private void btnOff_Click(object sender, EventArgs e) { disable(); } private void UpdateOperand(object sender, EventArgs e) { if (isNewEntry) { txtBox.Text = "0"; isNewEntry = false; } if (isRepeatLastOperation) { previousOperator = '\0'; result = 0; } if (!(txtBox.Text == "0" && (Button)sender == btn0) && !(((Button)sender) == btnPoint && txtBox.Text.Contains("."))) txtBox.Text = (txtBox.Text == "0" && ((Button)sender) == btnPoint) ? "0." : ((txtBox.Text == "0") ? ((Button)sender).Text : txtBox.Text + ((Button)sender).Text); } private void btnEqual_Click(object sender, EventArgs e) { if (!isRepeatLastOperation) { operand = double.Parse(txtBox.Text); isRepeatLastOperation = true; } operate(result, previousOperator, operand); isNewEntry = true; } private void btnClear_Click(object sender, EventArgs e) { operand = result = 0; txtBox.Text = "0"; lbl.Text = ""; isRepeatLastOperation = false; previousOperator = '\0'; isNewEntry = true; } private void btnDelete_Click(object sender, EventArgs e) { txtBox.Text = txtBox.Text.Remove(txtBox.Text.Length - 1); result = double.Parse(txtBox.Text); } private void btnNegative_Click(object sender, EventArgs e) { txtBox.Text = (float.Parse(txtBox.Text) * -1).ToString(); result = double.Parse(txtBox.Text); } private void btnPow_Click(object sender, EventArgs e) { lbl.Text = txtBox.Text + " ^ 2 = "; txtBox.Text = (result = Math.Pow(double.Parse(txtBox.Text), 2)).ToString(); } private void btnReverse_Click(object sender, EventArgs e) { lbl.Text = "1 / " + txtBox.Text + " ="; txtBox.Text = (result = 1 / double.Parse(txtBox.Text)).ToString(); } private void btnSqrt_Click(object sender, EventArgs e) { lbl.Text = "sqrt "+ txtBox.Text + " = "; txtBox.Text = (result = Math.Sqrt(double.Parse(txtBox.Text))).ToString(); } private void OperatorFound(object sender, EventArgs e) { if (previousOperator == '\0') { previousOperator = ((Button)sender).Text[0]; result = double.Parse(txtBox.Text); } else if (isNewEntry) //daca apas din greseala pe + de ex si vreau - atunci e ok previousOperator = ((Button)sender).Text[0]; else { operate(result, previousOperator, double.Parse(txtBox.Text)); previousOperator = ((Button)sender).Text[0]; } isNewEntry = true; isRepeatLastOperation = false; } void operate(double dblPreviousResult, char chPreviousOperator, double dblOperand) { switch (chPreviousOperator) { case '+': lbl.Text = dblPreviousResult + "+" +dblOperand + "=" ; txtBox.Text = (result = (dblPreviousResult + dblOperand)).ToString(); break; case '-': lbl.Text = dblPreviousResult + "-" + dblOperand + "="; txtBox.Text = (result = (dblPreviousResult - dblOperand)).ToString(); break; case '*': lbl.Text = dblPreviousResult + "*" + dblOperand + "="; txtBox.Text = (result = (dblPreviousResult * dblOperand)).ToString(); break; case '%': lbl.Text = dblPreviousResult + "%" + dblOperand + "="; txtBox.Text = (result = (dblPreviousResult / 100 * dblOperand)).ToString(); break; case '/': lbl.Text = dblPreviousResult + "/" + dblOperand + "="; if (dblOperand == 0) { txtBox.Text = "Cannot divide by zero"; result = 0; } if(dblOperand != 0) txtBox.Text = (result = (dblPreviousResult / dblOperand)).ToString(); break; } } } }
JavaScript
UTF-8
2,262
2.796875
3
[]
no_license
import React, {Component} from "react" class Field extends Component { constructor(props){ super(props); this.state={ hasClass:false } this.handleInputChange = this.handleInputChange.bind(this); this.passWordChange = this.passWordChange.bind(this); } passWordChange(){ console.log(this.input.getAttribute("type")); if(this.input.getAttribute("type")==="password"){ this.input.setAttribute("type","text"); this.setState({ hasClass:true }) }else{ this.input.setAttribute("type","password"); this.setState({ hasClass:false }) } } handleInputChange(ev) { const {name, onChange} = this.props const target = ev.target; const value = target.type === "checkbox" ? target.checked : target.value } _renderInput() { const {type,label} = this.props; return (<span className="field-container"> <input className="field-input-type" type="text" onChange={this.handleInputChange} placeholder={label}/> </span>) } _renderInputPassWord(){ const {type,label} = this.props; return (<span className="field-container"> <input className="field-input-type" type="password" ref={(input)=>this.input=input} onChange={this.handleInputChange} placeholder={label}/> <span className={`iconTab iconEyeClose ${this.state.hasClass ? "iconEysOpen":""}`} onClick={this.passWordChange}></span> </span>) } _renderCheckbox() { const {type, label, name, value} = this.props return (<label className="field-checkbox"> <input type="checkbox" name={name} checked={value} onChange={this.handleInputChange} /> <span className="checkbox"></span> <span className="checkbox-label">{label}</span> </label>) } render() { const {type} = this.props let domNode switch(type) { case "text": domNode = this._renderInput() break case "password": domNode = this._renderInputPassWord() break case "checkbox": domNode = this._renderCheckbox() break default: domNode = this._renderInput() break } return domNode } } export default Field
Python
UTF-8
4,537
2.78125
3
[]
no_license
import unittest from unittest.mock import patch from ..menu import Menu from ..task_container import TaskContainer from ..task import Task, TaskNotFound, NotValidStatus class TestMenu(unittest.TestCase): def setUp(self): self.menu = Menu() self.task = self.menu.task_container.new_task("A task") def test_Menu_initialized_with_TaskContainer_object(self): self.assertIsInstance(self.menu.task_container, TaskContainer) def test_Menu_initialized_with_dict_of_choices(self): self.assertIsInstance(self.menu.choices, dict) @patch('builtins.input', side_effect=["New task", "This is a note", "2019"]) def test_Menu_option_add_new_task(self, mock_inputs): task = self.menu.add_new_task() self.assertEqual(self.menu.task_container.tasks, {1: self.task, 2: task}) @patch('builtins.input', side_effect=["New task", "This is a note", "2019"]) def test_is_working_my_patch_function(self, mock_inputs): task = self.menu.add_new_task() note = self.menu.task_container.get_task_note(task.id) self.assertEqual(note, task.message.note) @patch('builtins.input', side_effect=[1, 'Editing task']) def test_change_task(self, mock_inputs): changed_task = self.menu.change_task() self.assertEqual(changed_task.id, 1) @patch('builtins.input', return_value=1) def test_delete_task(self, mock_id): self.menu.delete_task() self.assertEqual(self.menu.task_container.tasks, {}) @patch('builtins.input', return_value=2) def test_delete_task_raise_TaskNotFound_if_id_not_found(self, mock_id): with self.assertRaises(TaskNotFound): self.menu.delete_task() @patch('builtins.input', return_value=1) def test_search_task_by_id(self, mock_id): task_name = self.menu.search_task() self.assertTrue(task_name, self.task.name) @patch('builtins.input', return_value=2) def test_search_task_by_id_raises_TaskNotFound_if_wrong_id(self, mock_id): with self.assertRaises(TaskNotFound): self.menu.search_task() @patch('builtins.input', return_value='task') def test_search_task_by_word(self, mock_word): self.assertEqual(self.menu.search_task_by_word(), ["A task"]) @patch('builtins.input', side_effect=[1, 'finished']) def test_edit_task_status(self, mock_inputs): self.menu.edit_task_status() self.assertTrue(self.task.status =='finished') @patch('builtins.input', side_effect=[2, 'finished']) def test_edit_task_status_raise_TaskNotFound_if_wrong_id(self, mock_inputs): with self.assertRaises(TaskNotFound): self.menu.edit_task_status() @patch('builtins.input', side_effect=[1, "changing this note"]) def test_edit_task_note(self, mock_inputs): self.menu.edit_task_note() self.assertTrue(self.task.get_note() == "changing this note") @patch('builtins.input', side_effect=[2, "changing this note"]) def test_edit_task_note_raises_TaskNotFound_if_wrong_id(self, mock_inputs): with self.assertRaises(TaskNotFound): self.menu.edit_task_note() def test_show_finished_tasks(self): task_2 = self.menu.task_container.new_task("Adding one more task") self.task.change_status('finished') self.assertEqual(self.menu.show_finished_tasks(), [self.task.name]) def test_show_finished_tasks_return_empty_list_if_no_finished_task(self): self.assertEqual(self.menu.show_finished_tasks(), []) def test_show_unfinished_tasks(self): task_2 = self.menu.task_container.new_task("Adding one more task", "This is a note", "2019, 1, 7") self.assertEqual(self.menu.show_unfinished_tasks_with_due_date(), [self.task.name, task_2.name]) @patch('builtins.input', return_value=2) def test_show_task_note(self, mock_id): task_2 = self.menu.task_container.new_task("Adding one more task", "This is a note", "2019, 1, 7") note = self.menu.show_task_note() self.assertTrue(task_2.get_note() == note == "This is a note") def test_quit(self): with self.assertRaises(SystemExit): self.menu.quit() def tearDown(self): self.menu.task_container.tasks.clear() Task.id = 1
Java
UTF-8
1,633
2.484375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package csg.data; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ObservableBooleanValue; /** * * @author Alvaro Quintanilla, ID: 110289649 */ public class SitePage { private final BooleanProperty isUsed; private final StringProperty navbarTitle; private final StringProperty fileName; private final StringProperty script; public SitePage(boolean isUsed, String navbarTitle, String fileName, String script) { this.isUsed = new SimpleBooleanProperty(isUsed); this.navbarTitle = new SimpleStringProperty(navbarTitle); this.fileName = new SimpleStringProperty(fileName); this.script = new SimpleStringProperty(script); } public ObservableBooleanValue isUsed() { return isUsed; } public boolean getIsUsed() { return isUsed.get(); } public String getNavbarTitle() { return navbarTitle.get(); } public String getFileName() { return fileName.get(); } public String getScript() { return script.get(); } public void setUsed(Boolean value) { isUsed.set(value); } public String toString() { return isUsed.get() + " " + navbarTitle.get() + " " + fileName.get() + " " + script.get(); } }
Markdown
UTF-8
2,899
3.03125
3
[ "MIT" ]
permissive
#Strangeness Strangeness is a small puzzle game about a man whose world is falling apart. The puzzles are similar is style to those of games like Chip's Challenge or The Adventures of Lolo, but enemies only move when you do. Currently features: * Push boulders, grab keys, press buttons teleport across 19 levels! * Throw rocks to stun enemies! * Take all the time you need to think: nothing moves until you do. * Programmer art! * Auto-generated tracker music! The original version of Strangeness was developed in 72 hours for Ludum Dare 38 - A Small World. This version is substantially improved from the Jam version. For more information, see [the game's homepage](https://philomory.itch.io/strangeness) on [itch.io](http://itch,io/) For the source code to the game, see [the game's repository](https://bitbucket.org/philomory/ld38/) on [BitBucket](http://bitbucket.org) ## Running the Game To run the game from source, you'll need to have [Ruby 2.3.x](http://ruby-lang.org) installed. You'll also need the gem [bundler](http://bundler.io). Once you have those, use `bundle install` to install the gem dependencies, and `ruby ld38.rb` to run the game. Windows and Mac users may prefer to download double-clickable versions of the game from [itch.io](https://philomory.itch.io/strangeness). ## Playing the Game The objective of the game is to navigate from the start of the level to the exit, marked by a swirling blue portal. Along the way you must avoid deadly creatures, collect keys to open locks, push boulders onto switches, and more. To navigate the menu: * Use the up and down arrow keys to select menu options * Use Space or Enter to select a menu option The default controls in the game are: * WASD or Arrow Keys to move * Hold Shift and use WASD or Arrow Keys to throw a rock (if you have one) * Escape to pause the game * U to undo a move * R to restart the level Keybindings can be changed from the settings menu; this includes support for most gamepads. Additionally, there is an alternate control mode available in the options menu, under which one set of directional keys moves (by default, WASD), and another is used to throw rocks (by default, the Arrow Keys). ## Tools The following tools were used to create this game: * Language: [Ruby](http://ruby-lang.org/) * GameDev Library: [Gosu](http://libgosu.org/) * Editor: [Textmate 2](https://macromates.com) * Graphics: [Pyxel Edit](http://pyxeledit.com), [Pixen](http://pixenapp.com) * Map: [Tiled](http://mapeditor.org) * SFX: [bfxr](http://bfxr.net) * Music: [Autotracker-bu](https://github.com/iamgreaser/it2everything/blob/master/atrk-bu.py) * Fonts: [Alagard](http://pix3m.deviantart.com/art/Bitmap-font-Alagard-381110713) and [Romulus](http://pix3m.deviantart.com/art/Bitmap-font-Romulus-380739406) by Pix3M ## License This game is released under the MIT license. See the LICENSE file for more information.
Java
UTF-8
640
1.804688
2
[]
no_license
package com.xzb.showcase.system.service; import javax.transaction.Transactional; import org.springframework.stereotype.Component; import com.xzb.showcase.base.datapermission.DataPermission; import com.xzb.showcase.base.service.BaseService; import com.xzb.showcase.system.dao.SystemLogDao; import com.xzb.showcase.system.entity.SystemLog; /** * 系统日志Service类 * * @author wj * @date 2014-11-18 18:17:00 * */ @Component @Transactional @DataPermission public class SystemLogService extends BaseService<SystemLog, SystemLogDao> { public SystemLog log(SystemLog t) { return dao.save(t); } }
SQL
UTF-8
6,623
3.71875
4
[]
no_license
DROP SCHEMA RULE_ENGINE; CREATE SCHEMA RULE_ENGINE; SET SCHEMA "RULE_ENGINE" DROP TABLE RULE_SET_CONF; DROP TABLE RULE_CONDITION_MAP; DROP TABLE RULE_SET; DROP TABLE RULE; DROP TABLE "CONDITION"; CREATE TABLE "CONDITION" ( CONDITION_ID INTEGER NOT NULL, DESCRIPTION VARCHAR(200) NOT NULL, "PARAMETER_NAME" VARCHAR(200), EXPRESSION VARCHAR(500), CONDITION_CLASS VARCHAR(200), PRIMARY KEY (CONDITION_ID) ); CREATE TABLE RULE ( RULE_ID INTEGER NOT NULL, "NAME" VARCHAR(200) NOT NULL, DESCRIPTION VARCHAR(500) NOT NULL, CONSEQUENCE VARCHAR(5000) NOT NULL, LOGICAL_OPERATOR VARCHAR(10) NOT NULL, PRIMARY KEY (RULE_ID) ); CREATE TABLE RULE_CONDITION_MAP ( RULE_ID INTEGER NOT NULL, CONDITION_ID INTEGER NOT NULL, PRIMARY KEY (RULE_ID, CONDITION_ID) ); CREATE TABLE RULE_SET ( RULE_SET_ID INTEGER NOT NULL, "NAME" VARCHAR(200) NOT NULL, PRIMARY KEY (RULE_SET_ID) ); CREATE TABLE RULE_SET_CONF ( RULE_SET_ID INTEGER NOT NULL, RULE_ID INTEGER NOT NULL, PRIORITY INTEGER NOT NULL, PRIMARY KEY (RULE_SET_ID, RULE_ID) ); ALTER TABLE RULE_CONDITION_MAP ADD CONSTRAINT RULE_CONDITION_MAP_FK_1 FOREIGN KEY (CONDITION_ID) REFERENCES CONDITION (CONDITION_ID); ALTER TABLE RULE_CONDITION_MAP ADD CONSTRAINT RULE_CONDITION_MAP_FK_2 FOREIGN KEY (RULE_ID) REFERENCES RULE (RULE_ID); ALTER TABLE RULE_SET_CONF ADD CONSTRAINT RULE_SET_CONF_FK_1 FOREIGN KEY (RULE_SET_ID) REFERENCES RULE_SET (RULE_SET_ID); ALTER TABLE RULE_SET_CONF ADD CONSTRAINT RULE_SET_CONF_FK_2 FOREIGN KEY (RULE_ID) REFERENCES RULE (RULE_ID); INSERT INTO RULE_SET (RULE_SET_ID, "NAME") VALUES (1, 'GO MVNO Decision'); INSERT INTO RULE (RULE_ID, "NAME", DESCRIPTION, CONSEQUENCE, LOGICAL_OPERATOR) VALUES (1, 'IMSI and MSISDN check', 'Either IMSI or MSISDN have to be specified', 'SET-UNSUCCESSFUL|ADD-MESSAGE Either IMSI or MSISDN have to be specified', 'AND'); INSERT INTO RULE (RULE_ID, "NAME", DESCRIPTION, CONSEQUENCE, LOGICAL_OPERATOR) VALUES (2, 'IMSI Finder', 'Find IMSI from the MSISDN parameter', 'RUN mt.com.go.rule.engine.consequence.IMSIFinder|SET-PARAM notes=Imsi found from msisdn|RESUBMIT 5', 'AND'); INSERT INTO RULE (RULE_ID, "NAME", DESCRIPTION, CONSEQUENCE, LOGICAL_OPERATOR) VALUES (3, 'GO IMSI', 'Mark the request as GO', 'RUN mt.com.go.rule.engine.consequence.GoMobileIMSI', 'AND'); INSERT INTO RULE (RULE_ID, "NAME", DESCRIPTION, CONSEQUENCE, LOGICAL_OPERATOR) VALUES (4, 'MVNO 1 IMSI', 'Mark the request as MVNO 1', 'RUN mt.com.go.rule.engine.consequence.Mvno1IMSI', 'AND'); INSERT INTO RULE (RULE_ID, "NAME", DESCRIPTION, CONSEQUENCE, LOGICAL_OPERATOR) VALUES (5, 'MVNO 2 IMSI', 'Mark the request as MVNO 2', 'RUN mt.com.go.rule.engine.consequence.Mvno2IMSI', 'AND'); INSERT INTO RULE (RULE_ID, "NAME", DESCRIPTION, CONSEQUENCE, LOGICAL_OPERATOR) VALUES (6, 'MNVO 3 N/A', 'Warn that MVNO 3 is not yet available', 'RUN mt.com.go.rule.engine.consequence.Mvno3IMSI', 'OR'); INSERT INTO RULE (RULE_ID, "NAME", DESCRIPTION, CONSEQUENCE, LOGICAL_OPERATOR) VALUES (7, 'Operator not found', 'The operator code was not found', 'SET-UNSUCCESSFUL|ADD-MESSAGE The operator code was not derived', 'AND'); INSERT INTO RULE_SET_CONF (RULE_SET_ID, RULE_ID, PRIORITY) VALUES (1,1,1); INSERT INTO RULE_SET_CONF (RULE_SET_ID, RULE_ID, PRIORITY) VALUES (1,2,2); INSERT INTO RULE_SET_CONF (RULE_SET_ID, RULE_ID, PRIORITY) VALUES (1,3,3); INSERT INTO RULE_SET_CONF (RULE_SET_ID, RULE_ID, PRIORITY) VALUES (1,4,4); INSERT INTO RULE_SET_CONF (RULE_SET_ID, RULE_ID, PRIORITY) VALUES (1,5,5); INSERT INTO RULE_SET_CONF (RULE_SET_ID, RULE_ID, PRIORITY) VALUES (1,6,6); INSERT INTO RULE_SET_CONF (RULE_SET_ID, RULE_ID, PRIORITY) VALUES (1,7,7); INSERT INTO "CONDITION" (CONDITION_ID, DESCRIPTION, "PARAMETER_NAME", EXPRESSION, CONDITION_CLASS) VALUES (1, 'IMSI not in Parameter list', 'imsi', '!exists', NULL); INSERT INTO "CONDITION" (CONDITION_ID, DESCRIPTION, "PARAMETER_NAME", EXPRESSION, CONDITION_CLASS) VALUES (2, 'MSISDN not in Parameter list', 'msisdn', '!exists', NULL); INSERT INTO "CONDITION" (CONDITION_ID, DESCRIPTION, "PARAMETER_NAME", EXPRESSION, CONDITION_CLASS) VALUES (3, 'GO Mobile IMSI Condition', 'imsi', '500A\d{5}', NULL); INSERT INTO "CONDITION" (CONDITION_ID, DESCRIPTION, "PARAMETER_NAME", EXPRESSION, CONDITION_CLASS) VALUES (4, 'MVNO 1 IMSI Condition', 'imsi', '500B\d{5}', NULL); INSERT INTO "CONDITION" (CONDITION_ID, DESCRIPTION, "PARAMETER_NAME", EXPRESSION, CONDITION_CLASS) VALUES (5, 'MVNO 2 IMSI Condition', 'imsi', '500C\d{5}', NULL); INSERT INTO "CONDITION" (CONDITION_ID, DESCRIPTION, "PARAMETER_NAME", EXPRESSION, CONDITION_CLASS) VALUES (6, 'MVNO 3 IMSI Condition', NULL, NULL, 'mt.com.go.rule.engine.condition.Mvno3NotAvailableCondition'); INSERT INTO "CONDITION" (CONDITION_ID, DESCRIPTION, "PARAMETER_NAME", EXPRESSION, CONDITION_CLASS) VALUES (7, 'True', NULL, NULL, 'mt.com.go.rule.engine.condition.TrueCondition'); INSERT INTO RULE_CONDITION_MAP (RULE_ID, CONDITION_ID) VALUES (1, 1); INSERT INTO RULE_CONDITION_MAP (RULE_ID, CONDITION_ID) VALUES (1, 2); INSERT INTO RULE_CONDITION_MAP (RULE_ID, CONDITION_ID) VALUES (2, 1); INSERT INTO RULE_CONDITION_MAP (RULE_ID, CONDITION_ID) VALUES (3, 3); INSERT INTO RULE_CONDITION_MAP (RULE_ID, CONDITION_ID) VALUES (4, 4); INSERT INTO RULE_CONDITION_MAP (RULE_ID, CONDITION_ID) VALUES (5, 5); INSERT INTO RULE_CONDITION_MAP (RULE_ID, CONDITION_ID) VALUES (6, 6); INSERT INTO RULE_CONDITION_MAP (RULE_ID, CONDITION_ID) VALUES (7, 7); DROP VIEW RULE_ENGINE_CONFIG_V; CREATE VIEW RULE_ENGINE_CONFIG_V AS SELECT RULE_SET.RULE_SET_ID RULE_SET_ID, RULE_SET."NAME" RULE_SET_NAME, RULE.RULE_ID RULE_ID, RULE_SET_CONF.PRIORITY RULE_SET_PRIORITY, RULE."NAME" RULE_NAME, RULE.DESCRIPTION RULE_DESCRIPTION, RULE.CONSEQUENCE RULE_CONSEQUENCE, RULE.LOGICAL_OPERATOR RULE_OPERATOR, CONDITION.CONDITION_ID CONDITION_ID, CONDITION.DESCRIPTION CONDITION_DESCRIPTION, CONDITION."PARAMETER_NAME" CONDITION_PARAMETER_NAME, CONDITION.EXPRESSION CONDITION_EXPRESSION, CONDITION.CONDITION_CLASS CONDITION_CLASS FROM "CONDITION", RULE, RULE_CONDITION_MAP, RULE_SET, RULE_SET_CONF WHERE RULE_CONDITION_MAP.RULE_ID = RULE.RULE_ID AND RULE_CONDITION_MAP.CONDITION_ID = "CONDITION".CONDITION_ID AND RULE_SET_CONF.RULE_ID = RULE.RULE_ID AND RULE_SET.RULE_SET_ID = RULE_SET_CONF.RULE_SET_ID; SELECT * FROM RULE_ENGINE_CONFIG_V ORDER BY RULE_SET_ID, RULE_SET_PRIORITY, CONDITION_ID;
C
UTF-8
1,271
2.671875
3
[ "MIT-Modern-Variant", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/* This file contains the cmd_struct to contain the details of a command from * the parsing * * Team: Shir, Steven, Reggie */ #ifndef MYSH_H #define MYSH_H #include <stdbool.h> #include <stdint.h> // Define maximum command length #define MAX_CMD_LENGTH 1024 // This struct holds all the details from a command necessary for executing that // the parser determines typedef struct { uint8_t** arg_array; // Array of arguments uint8_t* input; // input filename, NULL defaults for stdin uint8_t* output; // ouptut filename, NULL defaults for stdout uint8_t redir_desc1; // File descriptor 1 for >&, defaults 0 uint8_t redir_desc2; // File descriptor 2 for >&, defaults 0 bool redir_desc_first; // Determines if >& or > was first bool pipe_flag; // Determines if output was piped, def false bool trun_flag; // Determines if >> was given, default true bool bkgd_flag; // Determines if run in background, def false uint8_t history_num; // History number for ! command, default 0 uint8_t error_code; // Error code from parser, default 0 } cmd_struct; #endif
Python
UTF-8
4,258
3.765625
4
[]
no_license
import pojos """ File that contains the game instructions """ def deal(deck, player1, comp1): deck.shuffle() # Get player & comp hand for i in range(2): player1.hand.append(deck.cards.pop()) comp1.hand.append(deck.cards.pop()) # print(f'ZZZZZZZ {player1.hand[0].name} {comp1.hand[0].name})') printGameStatusCompHidden(player1, comp1) def printGameStatus(player1, comp1): print("\n**************") print("GAME STATUS") print("**************") print("- PLAYER HAND -") for ph in player1.hand: print(ph.name) print("\n- COMPUTER HAND -") for ph in comp1.hand: print(ph.name) print("\n- BET (Bankroll) -") print(f'{player1.bet} ({player1.bankroll}) ') def printGameStatusCompHidden(player1, comp1): print("\n**************") print("GAME STATUS") print("**************") print("- PLAYER HAND -") for ph in player1.hand: print(ph.name) print("\n- COMPUTER HAND -") print(f'{comp1.hand[0].name} - XX') print("\n- Bet (Bankroll) -") print(f'{player1.bet} ({player1.bankroll}) ') def playAgain(p1): while True: playagain = input(f"You got {p1.bankroll} in bank. Wanna play again (y/n) ? ") if playagain == 'y': print(chr(27) + "[2J") g = Game() p1.hand = [] g.start(p1) break elif playagain == 'n': break else: print("Try again") def computerTurn(p1, c1, deck, gameON): print("--------------- COMPUTER TURN --------------------") totalP1 = pojos.calculateTotal(p1.hand) totalC1 = pojos.calculateTotal(c1.hand) while totalC1 <= totalP1 and totalC1 < 21 and gameON: printGameStatus(p1, c1) # computer hit if c1.hit(deck) == -1: gameON = False printGameStatus(p1, c1) p1.bankroll = p1.bankroll + 2*p1.bet p1.bet = 0 print(f'--------- Computer Bust. THE WINNER IS {p1.name}. CONGRATS! ----------------') playAgain(p1) break else: totalC1 = pojos.calculateTotal(c1.hand) else: printGameStatus(p1, c1) p1.bet = 0 print(f'--------- Computer wins, GG, go learn how to play! ----------------') playAgain(p1) class Game: def __init__(self): pass def start(self,p1): # start game if p1.bankroll == 0: print("Go work, make money, and then come and play!") else: self.gameON = True deck = pojos.Deck() # Player bet while p1.placeBet(input(f"\nHow much do you bet: (upto {p1.bankroll}) ")) in [-1,-2]: print("Try again") # Deal c1 = pojos.Computer([]) deal(deck, p1, c1) # Choice of hit or check while True: choice = input("Would you like to hit? (y/n) ") if choice not in ['y','n']: # try again print("Try again") if choice == 'n': # check total = p1.check() if total == 21: p1.bankroll = p1.bankroll + 2*p1.bet p1.bet = 0 print(f'--------- Computer Bust. THE WINNER IS {p1.name}. CONGRATS! ----------------') playAgain(p1) else: print(f"Total value is {total}") break if choice == 'y': if p1.hit(deck) == -1: self.gameON = False printGameStatusCompHidden(p1, c1) print("BUST!!!! GAME OVER!!! YOU LOSE, HAHAHA!") playAgain(p1) break else: printGameStatusCompHidden(p1, c1) # Computer turn if self.gameON: computerTurn(p1, c1, deck, self.gameON) print(chr(27) + "[2J") print("\n##########################") print("# LETS PLAY BLACKJACK #") print("##########################") g = Game() g.start(pojos.Player("Harold",[],0))
Python
UTF-8
383
2.859375
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- # 写点中文注释 with open(__file__, "rb") as bf: bytes = bf.read() print("Decode By UTF-8\n{}\n".format(bytes.decode("UTF-8"))) print("Decode By ISO8859-1\n{}\n".format(bytes.decode("ISO8859-1"))) try: print("Decode By GB18030\n{}\n".format(bytes.decode("GB18030"))) except UnicodeDecodeError as e: print(e)
Java
UTF-8
2,238
3.078125
3
[]
no_license
package reuo.resources.io; import java.util.Iterator; /** * A {@link Loader} that has an index. The index is a set of * {@link Entry entries} that describe the {@link Resource}s. * <h3>Entries</h3> * Entries describe resources and share the same identifier. This index * typically describes where the resource is, but may include other * meta-information. Any entry may be invalid in the index. The identifiers for * entries may be sparse because some entries may be invalid. This class * implements {@link Iterable} which provides an iterator for valid entry * identifiers. * <h3>Stored and Generated Indexes</h3> * An index may exist from a data source or generated in memory. Generated * indexes are typically small, while indexes from data sources are large and * usually mapped to a file. * * @author Kristopher Ives * @param <E> the type of entries * @param <R> the type of the resources * @see MemoryIndexedLoader * @see StoredIndexedLoader */ public abstract class IndexedLoader<E extends Entry, R> extends Loader<R> implements Iterable<Integer>{ /** * Gets the entry for the specified resource from the index. * * @param id the resource identifier * @return the index entry */ public abstract E getEntry(int id); /** * Gets an iteration of the valid entry identifiers in the index. * Implementing classes may override this, but by default this will iterate * from <code>0</code> to {@link #getCapacity()} only returning valid * entries. */ public Iterator<Integer> iterator(){ return new ValidIndexIterator(); } protected class ValidIndexIterator implements Iterator<Integer>{ int start, limit; int index; public ValidIndexIterator(){ this(0, getCapacity()); } public ValidIndexIterator(int start, int limit){ this.start = start; this.limit = limit; this.index = start - 1; } public boolean hasNext(){ E entry = null; do{ index++; if(index >= limit){ return false; } entry = getEntry(index - start); }while(entry == null || !entry.isValid()); return true; } public Integer next(){ return index - start; } public void remove(){ throw new UnsupportedOperationException(); } } }
Java
UTF-8
2,338
1.84375
2
[]
no_license
package com.iyeed.core.entity.form.vo; import java.io.Serializable; import java.util.Date; /** * 功能描述: * * @Auther guanghua.deng * @Date 2018/8/21 17:15 */ public class GetDisposeFormListBean implements Serializable { private Integer id; private String storeNo; private String storeName; private String applyNo; private java.util.Date applyDate; private Integer formType; private java.util.Date inputDate; private Integer disposeStatus; private String disposeStatusDesc; private Integer isBack; private String applyUserNo; public Integer getIsBack() { return isBack; } public void setIsBack(Integer isBack) { this.isBack = isBack; } public String getApplyUserNo() { return applyUserNo; } public void setApplyUserNo(String applyUserNo) { this.applyUserNo = applyUserNo; } public String getDisposeStatusDesc() { return disposeStatusDesc; } public void setDisposeStatusDesc(String disposeStatusDesc) { this.disposeStatusDesc = disposeStatusDesc; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStoreNo() { return storeNo; } public void setStoreNo(String storeNo) { this.storeNo = storeNo; } public String getStoreName() { return storeName; } public void setStoreName(String storeName) { this.storeName = storeName; } public String getApplyNo() { return applyNo; } public void setApplyNo(String applyNo) { this.applyNo = applyNo; } public Date getApplyDate() { return applyDate; } public void setApplyDate(Date applyDate) { this.applyDate = applyDate; } public Integer getFormType() { return formType; } public void setFormType(Integer formType) { this.formType = formType; } public Date getInputDate() { return inputDate; } public void setInputDate(Date inputDate) { this.inputDate = inputDate; } public Integer getDisposeStatus() { return disposeStatus; } public void setDisposeStatus(Integer disposeStatus) { this.disposeStatus = disposeStatus; } }
Java
UTF-8
18,642
2.09375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package utp.misiontic2022.c2.p77.unidad4.vista; import java.awt.HeadlessException; import java.sql.SQLException; import javax.swing.JOptionPane; import javax.swing.ListSelectionModel; import utp.misiontic2022.c2.p77.unidad4.controlador.Controlador; import utp.misiontic2022.c2.p77.unidad4.modelo.vo.Book; /** * * @author 3mer */ public class Bookshop_GUI extends javax.swing.JFrame { private Controlador controlador; private BooksTM bookTM; /** * Creates new form Bookshop_GUI */ public Bookshop_GUI() { controlador = new Controlador(); initComponents(); cargarLibros(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { tpPrincipal = new javax.swing.JTabbedPane(); pBooks = new javax.swing.JPanel(); lBooks = new javax.swing.JLabel(); jSplitPane1 = new javax.swing.JSplitPane(); pCBook = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); txtIsbn = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtTitle = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtYear = new javax.swing.JTextField(); btnGuardarLibro = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); idBook = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); btnCrearLibro = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tblBooks = new javax.swing.JTable(); pStock = new javax.swing.JPanel(); pSale = new javax.swing.JPanel(); jMenuBar1 = new javax.swing.JMenuBar(); jmApp = new javax.swing.JMenu(); miSalir = new javax.swing.JMenuItem(); jmVentanas = new javax.swing.JMenu(); miBook = new javax.swing.JMenuItem(); miSock = new javax.swing.JMenuItem(); miSale = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setTitle("BookShop"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); pBooks.setLayout(new java.awt.BorderLayout()); lBooks.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lBooks.setText("Gestión de Libros"); pBooks.add(lBooks, java.awt.BorderLayout.PAGE_START); jSplitPane1.setDividerLocation(35); jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); jSplitPane1.setEnabled(false); jSplitPane1.setMinimumSize(new java.awt.Dimension(160, 239)); pCBook.setPreferredSize(new java.awt.Dimension(632, 15)); jLabel1.setText("Libro:"); jLabel2.setText("ISBN:"); jLabel3.setText("Año:"); btnGuardarLibro.setText("Guardar"); btnGuardarLibro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGuardarLibroActionPerformed(evt); } }); jLabel4.setText("ID:"); javax.swing.GroupLayout pCBookLayout = new javax.swing.GroupLayout(pCBook); pCBook.setLayout(pCBookLayout); pCBookLayout.setHorizontalGroup( pCBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pCBookLayout.createSequentialGroup() .addGap(9, 9, 9) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(idBook, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtIsbn, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtYear, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnGuardarLibro, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(86, 86, 86)) ); pCBookLayout.setVerticalGroup( pCBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(pCBookLayout.createSequentialGroup() .addContainerGap() .addGroup(pCBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(txtIsbn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(txtYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnGuardarLibro) .addComponent(jLabel4) .addComponent(idBook, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(7, Short.MAX_VALUE)) ); jSplitPane1.setTopComponent(pCBook); jPanel2.setLayout(new java.awt.BorderLayout()); jPanel3.setForeground(new java.awt.Color(204, 204, 204)); jPanel3.setLayout(new java.awt.FlowLayout(2)); btnCrearLibro.setText("Nuevo"); btnCrearLibro.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCrearLibroActionPerformed(evt); } }); jPanel3.add(btnCrearLibro); jButton2.setText("Eliminar"); jPanel3.add(jButton2); jPanel2.add(jPanel3, java.awt.BorderLayout.PAGE_END); tblBooks.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(tblBooks); jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER); jSplitPane1.setRightComponent(jPanel2); pBooks.add(jSplitPane1, java.awt.BorderLayout.CENTER); tpPrincipal.addTab("Books", pBooks); javax.swing.GroupLayout pStockLayout = new javax.swing.GroupLayout(pStock); pStock.setLayout(pStockLayout); pStockLayout.setHorizontalGroup( pStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 929, Short.MAX_VALUE) ); pStockLayout.setVerticalGroup( pStockLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 495, Short.MAX_VALUE) ); tpPrincipal.addTab("Stock", pStock); javax.swing.GroupLayout pSaleLayout = new javax.swing.GroupLayout(pSale); pSale.setLayout(pSaleLayout); pSaleLayout.setHorizontalGroup( pSaleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 929, Short.MAX_VALUE) ); pSaleLayout.setVerticalGroup( pSaleLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 495, Short.MAX_VALUE) ); tpPrincipal.addTab("Sale", pSale); getContentPane().add(tpPrincipal, java.awt.BorderLayout.CENTER); jmApp.setText("Archivo"); miSalir.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.CTRL_DOWN_MASK)); miSalir.setText("Salir"); miSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { miSalirActionPerformed(evt); } }); jmApp.add(miSalir); jMenuBar1.add(jmApp); jmVentanas.setText("Edit"); miBook.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_DOWN_MASK)); miBook.setText("Book"); miBook.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { miBookActionPerformed(evt); } }); jmVentanas.add(miBook); miSock.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_DOWN_MASK)); miSock.setText("Stock"); miSock.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { miSockActionPerformed(evt); } }); jmVentanas.add(miSock); miSale.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_DOWN_MASK)); miSale.setText("Sale"); miSale.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { miSaleActionPerformed(evt); } }); jmVentanas.add(miSale); jMenuBar1.add(jmVentanas); setJMenuBar(jMenuBar1); pack(); }// </editor-fold>//GEN-END:initComponents private void miSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSalirActionPerformed exit_app(); }//GEN-LAST:event_miSalirActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing exit_app(); }//GEN-LAST:event_formWindowClosing private void miBookActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miBookActionPerformed tpPrincipal.setSelectedIndex(0); }//GEN-LAST:event_miBookActionPerformed private void miSockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSockActionPerformed tpPrincipal.setSelectedIndex(1); }//GEN-LAST:event_miSockActionPerformed private void miSaleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSaleActionPerformed tpPrincipal.setSelectedIndex(2); }//GEN-LAST:event_miSaleActionPerformed private void exit_app() throws HeadlessException { if (JOptionPane.showConfirmDialog(this, "Desea cerrar la aplicación?", getTitle(), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { dispose(); } } private void cargarLibros() { try { var books = controlador.findAllBooks(); bookTM = new BooksTM(books); tblBooks.setModel(bookTM); tblBooks.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tblBooks.getSelectionModel().addListSelectionListener((e) -> { var row = tblBooks.getSelectedRow(); if (row == -1) { idBook.setText(""); txtTitle.setText(""); txtIsbn.setText(""); txtYear.setText(""); } else { var book = bookTM.getBook(row); cargarCamposLibro(book); } }); } catch (SQLException e) { } } private void cargarCamposLibro(Book book) { idBook.setText(String.valueOf(book.getId())); txtTitle.setText(book.getTitle()); txtIsbn.setText(book.getIsbn()); txtYear.setText(String.valueOf(book.getYear())); } private void btnCrearLibroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCrearLibroActionPerformed // Limpiar selección de la tabla tblBooks.clearSelection(); // Lipiar form idBook.setText(""); txtTitle.setText(""); txtIsbn.setText(""); txtYear.setText(""); // Obtener foco txtTitle.requestFocus(); }//GEN-LAST:event_btnCrearLibroActionPerformed private void btnGuardarLibroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarLibroActionPerformed // Validar campos (title, isbn) if (txtTitle.getText().trim().isBlank()) { JOptionPane.showMessageDialog(this, "El titulo es obligatorio!", getTitle(), JOptionPane.WARNING_MESSAGE); txtTitle.requestFocus(); } if (txtIsbn.getText().trim().isBlank()) { JOptionPane.showMessageDialog(this, "El isbn es obligatorio!", getTitle(), JOptionPane.WARNING_MESSAGE); txtIsbn.requestFocus(); } // Enviar datos al controlador try { String id = idBook.getText(); String title = txtTitle.getText().trim(); String isbn = txtIsbn.getText().trim(); Integer year = Integer.valueOf(txtYear.getText().trim()); if (id.isBlank()) { var book = controlador.createBook(title, isbn, year); bookTM.addBook(book); } else { var row = tblBooks.getSelectedRow(); var book = controlador.updateBook(isbn, title, year); bookTM.setBook(row, book); } JOptionPane.showMessageDialog(this, "Se ha guardado el libro!"); } catch (SQLException e) { JOptionPane.showMessageDialog(this, e.getMessage()); } }//GEN-LAST:event_btnGuardarLibroActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Bookshop_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Bookshop_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Bookshop_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Bookshop_GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Bookshop_GUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCrearLibro; private javax.swing.JButton btnGuardarLibro; private javax.swing.JTextField idBook; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JMenu jmApp; private javax.swing.JMenu jmVentanas; private javax.swing.JLabel lBooks; private javax.swing.JMenuItem miBook; private javax.swing.JMenuItem miSale; private javax.swing.JMenuItem miSalir; private javax.swing.JMenuItem miSock; private javax.swing.JPanel pBooks; private javax.swing.JPanel pCBook; private javax.swing.JPanel pSale; private javax.swing.JPanel pStock; private javax.swing.JTable tblBooks; private javax.swing.JTabbedPane tpPrincipal; private javax.swing.JTextField txtIsbn; private javax.swing.JTextField txtTitle; private javax.swing.JTextField txtYear; // End of variables declaration//GEN-END:variables }
Java
UTF-8
995
2.828125
3
[]
no_license
package Commands; import Classes.User; import com.company.Command; import com.company.CommandReciever; import java.io.IOException; public class Register extends Command { private static final long serialVersionUID = 32L; transient private CommandReciever commandReciever; public Register (CommandReciever commandReciever) { this.commandReciever = commandReciever; } public Register() { } @Override protected void writeInfo() { System.out.println("register <login> <password>: регистрация нового пользователя"); } @Override protected void execute(String[] args, User user) throws IOException, ClassNotFoundException, InterruptedException { if (args.length != 3) { System.out.println("Что-то пошло не так (недостаточно аргументов).\nregister <login> <password>"); } commandReciever.register(new User(args[1], args[2])); } }
C
UTF-8
3,456
4.03125
4
[]
no_license
//----------------------------------------------------------------------------// // Name: Brian Tong // // Student ID: 276042 // // Assignment: 4 // //----------------------------------------------------------------------------// //calculating investment gain and sorting it from a file # include <stdio.h> # include <string.h> # include <stdlib.h> //structure struct stocks { char name[25]; char symbol[6]; float gain, price, year, increase; }; //prototype void readFile(struct stocks data[]); void displayInfo(struct stocks ordered[]); void rewriteFile(struct stocks ordered[]); void bubblesort(struct stocks ordered[]); //call other functions int main(void) { struct stocks data[1000]; readFile(data); bubblesort(data); displayInfo(data); rewriteFile(data); return 0; } //sort the info void bubblesort(struct stocks ordered[]) { int pass; struct stocks temp; size_t j; for(pass = 0; pass < 1000; pass++) { for(j = 0; j < 1000 - 1; j++) { if(ordered[j].gain < ordered[j + 1].gain) { temp = ordered[j+1]; ordered[j+1] = ordered[j]; ordered[j] = temp; } } } return; } //reading file void readFile(struct stocks data[]) { int count = 0; char stockData[80]; char *trash; FILE *stocksFile; if((stocksFile = fopen("C:\\Users\\Brian Tong\\Desktop\\stocks.txt", "r")) == NULL) { puts("File could not be opened."); } else { fgets(stockData, 80, stocksFile); while(!feof(stocksFile)) { trash = strtok(stockData, ","); strcpy(data[count].name, trash); trash = strtok(NULL, ","); strcpy(data[count].symbol, trash); trash = strtok(NULL, ","); data[count].price = (float) atof(trash); trash = strtok(NULL, ","); data[count].year = (float) atof(trash); trash = strtok(NULL, ","); data[count].increase = (float) atof(trash); data[count].gain = 25000 / data[count].price * data[count].year * (data[count].increase / 1000 + 1); count++; fgets(stockData, 80, stocksFile); } } fclose(stocksFile); return; } //top ten investment gains void displayInfo(struct stocks ordered[]) { int i; printf("%-25s%-8s%-22s\n", "Stock Name", "Symbol", "Investment Gain ($)"); for( i = 0; i < 10; i++) { printf("%-25s%-8s%.2f\n", ordered[i].name, ordered[i].symbol, ordered[i].gain); } return; } //display inputs into a file void rewriteFile(struct stocks ordered[]) { int i; FILE *pFile; if((pFile = fopen("C:\\Users\\Brian Tong\\Desktop\\new.txt", "w")) == NULL) { puts("File could not be opened\n:"); } else { fprintf(pFile, "%-25s%-8s%-22s\n", "Stock Name", "Symbol", "Investment Gain ($)"); for( i = 0; i < 100; i++) { fprintf(pFile, "%-25s%-8s%.2f\n", ordered[i].name, ordered[i].symbol, ordered[i].gain); } } fclose(pFile); return; } /* Stock Name Symbol Investment Gain ($) ADTRAN Inc ADTN 2209.27 EntreMed Inc ENMD 2185.73 Blucora Inc BCOR 1837.99 CME Group Inc CME 1658.95 Preferred Bank PFBC 1657.55 Landstar System Inc LSTR 1472.11 Entegris Inc ENTG 1447.43 Plumas Bancorp PLBC 1430.49 Atmel Corporation ATML 1389.02 Acxiom Corporation ACXM 1382.38 Press any key to continue . . . */
PHP
UTF-8
735
2.78125
3
[]
no_license
<?php namespace Serve\Interfaces; /** * Interface IJob * @package Serve\Interfaces * @author twomiao:<995200452@qq.com> */ interface IJob { /** * @param $queue * @return string|null * Redis 延时队列获取数据返回给Serve处理 * 注意: 一般不需要更改 */ public function getData($queue): ?string; /** * @param $pdo 数据库客户端句柄 * @param $data getData() 取出来的数据 * 业务逻辑操作 */ public function doJob(array $data): ?string; /** * @param $data * @return mixed * doJob处理完成后,接下来后面的工作 * swoole url:https://wiki.swoole.com/wiki/page/135.html */ public function finish($data); }
Markdown
UTF-8
6,014
2.921875
3
[]
no_license
# FastCampus_WPS ### :exclamation: This repository is about *FastCampus Web Programming School* and my story there. #### :wink: I will cover all contents here in English. Contact me anyone with interests in Python, Korea, and even with my typos. --- <br> ## :door: INDEX of contents. > ### :grey_question: What is FastCampus? > ### :grey_question: Curriculum and course introduction into WPS school. > ### :grey_question: Contents of this repository. <br><br><br><br> ![FastCampus logo](http://cdn.www.fastcampus.co.kr/wp-content/uploads/2016/01/fastcampus_logo_345x76.png) ### :white_check_mark: What is [Fast Campus](http://www.fastcampus.co.kr/)? > **Fast Campus is an organization for IT-concentrated education.** They have many curriculums from language to web-full stack career. > They also have data science, marketing, UX design curriculums and most of curriculums are very job-oriented. > **Curriculums can be divided into two groups: `camp` and `school`.** > *`Camp`* is for business men who wants better performance at their work. Lessons are at late afternoon or at the weekend. > *`School`*, the other, is a 3 months-compact education with a major purpose of employment. > It aims at a specific field and hard-educate skills and concepts and almost everything about the field to students. > This course is 8 hours a day and 5 days a week for about 2-3 months. Hard coding begins. ~~MAYDAY~~ > And I'm taking `Web Programming School` course. It covers python, Django, basic front-end skills. <br><br> ![Python, Django logo](http://cfile26.uf.tistory.com/image/121FBE0F4B7613886BD426) ### :white_check_mark: Curriculum and course introduction into [WPS school](http://www.fastcampus.co.kr/dev_school_wps/). > :scroll: WPS stands for Web Programming School and this school is dedicated to back-end develop with python and django. And also covers DB, server and network and basic front-end develop. > :calendar: **Date** > - **2016/09/05 - 2016/12/09, weekdays.** > :watch: **Time** > - 09:00 ~ 10:00 : Scrum, code battle and etc. > - 10:00 ~ 12:00 : Lecture > - 12:00 ~ 13:00 : Lunch time. ~~have-fun time~~ > - 13:00 ~ 18:00 : Lecture > - 18:00 ~ 22:00 : Study and review time. <br> > :books: **Curriculum** > * Basic Python > - [PythonBasic_Day1 : Basic](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/Python%20Basics/PythonBasic_Day1%20Basic-1.md) > - [PythonBasic_Day2: Packing and list comprehension](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/Python%20Basics/PythonBasic_Day2%20Packing%20and%20list%20comprehension.md) > - [PythonBasic_Day3: Decorator and OOP](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/Python%20Basics/PythonBasic_Day3%20Decorator%20and%20OOP.md) > * Basic HTML, CSS > - [HTML_CSS Day1: Basic](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/HTML%2BCSS/HTML%20%2B%20CSS_Day1%20Html%20basic-1.md) > - [HTML_CSS Day2: CSS](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/HTML%2BCSS/HTML%20%2B%20CSS_Day2%20CSS.md) > - [HTML_CSS Day3: Form and SASS](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/HTML%2BCSS/HTML%20%2B%20CSS_Day3%20Form%20and%20SASS.md) > - [HTML_CSS Day4: Bootstrap example](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/HTML%2BCSS/HTML%20%2B%20CSS_Day4%20Bootstrap%20example.md) > * Django and back-end > - [Django Day1: Setting and tutorial 1-2](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%201%20Setting%20and%20tutorial%201-2.md) > - [Django Day2: Tutorial 3-4](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%202%20Tutorial%203-4.md) > - [Django Day3: Model](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%203%20Model.md) > - [Django Day4: Model and field](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%204%20Model%20and%20field.md) > - [Django Day5: Tag and filter](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%205%20Tag%20and%20filter.md) > - [Django Day7: Youtube model,view](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%207%20Youtube%20video%20model%20and%20view.md) > - [Django Day9: Humanize and others](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%209%20Humanize%20and%20others.md) > - [Django Day12: Mail and sms](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%2012%20Mail%20and%20sms.md) > - [Django Day13: Private configuration](https://github.com/shoark7/FastCampus_WPS/blob/master/FC_Study/django/Django_Day%2013%20Private%20configuration.md) > * Javascript and JQuery > * git Expert > * Software Development engineering. <br><br> ### :white_check_mark: Contents of this repository > #### :open_file_folder: [FC_Study](https://github.com/shoark7/FastCampus_WPS/tree/master/FC_Study) > I will summarize and abridge everyday's stuff I will have learned in this folder. And if possible stuff there will be linked from README.md, this page, at the Curriculum section. > #### :open_file_folder: [FC_Homework](https://github.com/shoark7/FastCampus_WPS/tree/master/FC_Homework) > There will be lots of homework for almost 3 months from now on. This folder is an uploading place for my homework and teachers and assistants will check it. > #### :open_file_folder: [FC_Friends' code](https://github.com/shoark7/FastCampus_WPS/tree/master/FC_Friends'%20code) > In Eastern world, human being has been called a `micro universe`. There are so many kinds of people with different thoughts and thinking. Even if we learn same things in WPS school, some outliers come up with a very breathtaking, marvelous idea that we should share with. In this folder, I will put some my friends' outstanding codes, compare to mine and leave some comments on them. I hope this repository would be creative and innovative.
C#
UTF-8
2,216
2.609375
3
[ "MIT" ]
permissive
using System.ComponentModel; using System.Runtime.CompilerServices; namespace Workplace1c { public class Base : INotifyPropertyChanged { private string title = "", folder = "", user = "", password = "", repositoryPath = "", repositoryUser = "", repositoryPass = "", telegram = ""; private bool isServer = false, isRepository = false; public int Id { get; set; } public string Title { get => title; set { title = value; OnPropertyChanged(nameof(Title)); } } public string Folder { get => folder; set { folder = value; OnPropertyChanged(nameof(Folder)); } } public string User { get => user; set { user = value; OnPropertyChanged(nameof(User)); } } public string Password { get => password; set { password = value; OnPropertyChanged(nameof(Password)); } } public string RepositoryPath { get => repositoryPath; set { repositoryPath = value; OnPropertyChanged(nameof(RepositoryPath)); } } public string RepositoryUser { get => repositoryUser; set { repositoryUser = value; OnPropertyChanged(nameof(RepositoryUser)); } } public string RepositoryPass { get => repositoryPass; set { repositoryPass = value; OnPropertyChanged(nameof(RepositoryPass)); } } public bool IsServer { get => isServer; set { isServer = value; OnPropertyChanged(nameof(IsServer)); } } public bool IsRepository { get => isRepository; set { isRepository = value; OnPropertyChanged(nameof(IsRepository)); } } public string Telegram { get => telegram; set { telegram = value; OnPropertyChanged(nameof(Telegram)); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName]string prop = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop)); } }
C#
UTF-8
1,906
3.6875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _13_DynamicQueue { class LinkedQueue<T> { LinkedQueueNode<T> firstItem; LinkedQueueNode<T> lastItem; int count; public void Push(T value) { if (firstItem == null) { lastItem = new LinkedQueueNode<T>(value); firstItem = lastItem; } else { lastItem.PreviousItem = new LinkedQueueNode<T>(value); lastItem = lastItem.PreviousItem; } count++; } public T Peek() { return firstItem.Value; } public T Pop() { if (firstItem == null) { throw new InvalidOperationException("Queue is empty."); } T valueToReturn = firstItem.Value; firstItem = firstItem.PreviousItem; count--; return valueToReturn; } public int Count { get { return count; } } } class LinkedQueueNode<T> { T value; LinkedQueueNode<T> previousItem; public LinkedQueueNode() { } public LinkedQueueNode(T value) { this.Value = value; } public T Value { get { return this.value; } set { this.value = value; } } public LinkedQueueNode<T> PreviousItem { get { return this.previousItem; } set { this.previousItem = value; } } } }
PHP
UTF-8
386
3.109375
3
[]
no_license
<?php class TipoQuartoBean{ private $id; private $nome; private $preco; //Metodos magicos para atribuir/buscar propriedades public function __construct() {} public function __set($name, $value) { $this->$name = $value; } public function __get($name) { return $this->$name; } }
Java
UTF-8
353
2.203125
2
[]
no_license
package specificstep.com.ui.signIn; import dagger.Module; import dagger.Provides; @Module public class SignInPresenterModule { private SignInContract.View view; public SignInPresenterModule(SignInContract.View view) { this.view = view; } @Provides SignInContract.View providesSignInView() { return view; } }
TypeScript
UTF-8
393
2.71875
3
[]
no_license
import { Expose } from 'class-transformer'; import { IsNotEmpty, IsString, Matches } from 'class-validator'; /** * Defines the schema of the request header. */ export class HeaderDto { @Matches(/application\/json$/, { message: 'content-type should be application/json' }) @IsNotEmpty() @IsString() @Expose({ name: 'content-type' }) 'content-type': string; }
C++
UTF-8
2,392
2.65625
3
[]
no_license
#include <iostream> #include <vector> #include <set> using namespace std; struct seg{ int start; int end; int mid; seg(int s,int e){ start = s; end = e; mid = (s + e)/2; } }; struct cmp{ bool operator()(const seg&L, const seg&R)const{ int l_len = (L.end - L.start)/2; int r_len = (R.end - R.start)/2; if(l_len != r_len){ return l_len > r_len; } else{ return L.start < R.start; } } }; set<seg,cmp> swag; set<int> pos; vector<int> id2pos; int main(){ int n,m,s; cin>>n>>m>>s; int min_dis = n+1; pos.insert(0); pos.insert(n+1); swag.insert(seg(0,n+1)); id2pos.resize(m + 1, 1); for(int i=0;i<2*m;i++){ char oder; int num; cin>>oder>>num; if(oder=='i'){ auto pick = swag.begin(); //cout<<"seg("<<pick->start<<","<<pick->end<<")\n"; if(pick->start != 0){ min_dis = min(pick->mid - pick->start , min_dis); //cout<<"f\n"; } if(pick->end != n+1){ min_dis = min(pick->end - pick->mid , min_dis); //cout<<"z\n"; } seg f1(pick->start,pick->mid); seg f2(pick->mid,pick->end); id2pos[num] = pick->mid; pos.insert(pick->mid); swag.erase(pick); //cout<<"f1seg("<<f1.start<<","<<f1.end<<")\n"; //cout<<"f2seg("<<f2.start<<","<<f2.end<<")\n"; swag.insert(f1); swag.insert(f2); } else if(oder=='o'){ int mid = id2pos[num]; auto it = pos.find(mid); auto L_it = it; auto R_it = it; int L = *(--L_it); int R = *(++R_it); swag.erase(seg(L,mid)); swag.erase(seg(mid,R)); swag.insert(seg(L,R)); id2pos[num] = -1; pos.erase(mid); } } if(min_dis >= s) cout<<"YES\n"; else cout<<"NO\n"; if(min_dis == n+1) cout<<"INF\n"; else cout<<min_dis<<"\n"; return 0; }
TypeScript
UTF-8
1,321
3.203125
3
[ "MIT" ]
permissive
export const enum MouseButton { Left, Middle, Right, Back, // osx unsupported Forward, // osx unsupported } export interface IButtonStates { [key: number]: boolean; } export class Mouse { public x: number = 0; public y: number = 0; public deltaX: number = 0; public deltaY: number = 0; public wheelDelta: number = 0; public buttonStates: IButtonStates = { 0: false, 1: false, 2: false, 3: false, 4: false, }; public lastButtonStates: IButtonStates = { 0: false, 1: false, 2: false, 3: false, 4: false, }; public tmpButtonStates: IButtonStates = { 0: false, 1: false, 2: false, 3: false, 4: false, }; public tmpXDelta: number = 0; public tmpYDelta: number = 0; public tmpX: number = 0; public tmpY: number = 0; public tmpWheelDelta: number = 0; } export namespace Mouse { /** Is given button currently pressed? */ export function isPressed(mouse: Mouse, button: MouseButton) { return mouse.buttonStates[button]; } /** Was a given button pressed in this update? */ export function wasPressed(mouse: Mouse, button: MouseButton): boolean { const isPressedNow = mouse.buttonStates[button]; const wasPressedLast = mouse.lastButtonStates[button]; return isPressedNow && !wasPressedLast; } }
Java
UTF-8
1,326
2.953125
3
[ "MIT" ]
permissive
package com.benawad.gui; import com.benawad.models.Book; import javax.swing.table.AbstractTableModel; import java.util.List; /** * Created by benawad on 8/5/15. */ public class BookTableModel extends AbstractTableModel { private static final int TITLE_COL = 0; private static final int AUTHORS_COL = 1; private String[] columnNames = { "Title", "Authors" }; private List<Book> books; public BookTableModel(List<Book> bookList){ books = bookList; } @Override public int getRowCount() { return books.size(); } @Override public int getColumnCount() { return columnNames.length; } @Override public String getColumnName(int col){ return columnNames[col]; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if(books.size() == 0){ return null; } Book book = books.get(rowIndex); switch (columnIndex){ case TITLE_COL: return book.getTitle(); case AUTHORS_COL: return Book.authorsToString(book.getAuthors()); default: return book.getTitle(); } } // @Override // public Class getColumnClass(int c){ // return getValueAt(0, c).getClass(); // } }
Markdown
UTF-8
790
2.515625
3
[ "BSD-3-Clause" ]
permissive
# Brdgd Brdgd (read bridged) is an extremely simple P2P file transfer webapp. It depends on [PeerJS](http://peerjs.com) to manage the P2P connections. The webapp, in rare cases, uses a turn server to relay the connection in case where the peers cannot reach each other due to certain obvious reasons. ## Deploy The webapp can be deployed to Heroku as long as the following information are provided via environment variables: - `PEERJS_HOST`: PeerJS host - `PEERJS_PORT`: PeerJS port - `PEERJS_PATH`: PeerJS path - `PEERJS_KEY`: PeerJS API key - `PEERJS_LOG`: PeerJS log level - `STUN_HOST`: STUN server host - `STUN_PORT`: STUN server port - `TURN_HOST`: TURN server host - `TURN_PORT`: TURN server port - `TURN_USER`: TURN server username - `TURN_SECRET`: TURN server secret
Python
UTF-8
1,378
4.125
4
[]
no_license
""" 給多個會議時間區間, 如都可參加回傳True, 反之False 1. Input: [[0,30],[5,10],[15,20]] Output: False 2. Input: [[7,10],[2,4]] Output: True 思路 1.簡單暴力兩倆互相比對a, b, 如a[0] <= b[0] and b[0] <= a[1] 代表overlap, return False 比完後將a, b互換(不然下面這種情況會漏) a = [4, 6] b = [1, 10] 2.先排序, 從i = 1開始往前一個比 如i的起始值小於i-1的終止值代表有overlap """ def solve1(A): for i in range(len(A)-1): for j in range(i + 1, len(A)): if A[i][0] <= A[j][0] and A[j][0] <= A[i][1] or \ A[j][0] <= A[i][0] and A[i][0] <= A[j][1]: return False return True def solve2(A): B = sorted(A, key=lambda it: it[0]) for i in range(1, len(B)): if B[i-1][0] <= B[i][0] and B[i][0] <= B[i-1][1]: return False return True if __name__ == "__main__": # print(solve1([[0, 30], [5, 10], [15, 20]])) # False # print(solve1([[0, 30], [15, 35], [35, 50]])) # False # print(solve1([[0, 30], [31, 50], [51, 59]])) # True # print(solve1([[7, 10], [2, 4]])) # True print(solve2([[0, 30], [5, 10], [15, 20]])) # False print(solve2([[0, 30], [15, 35], [35, 50]])) # False print(solve2([[0, 30], [31, 50], [51, 59]])) # True print(solve2([[7, 10], [2, 4]])) # True
Java
UTF-8
3,421
2.171875
2
[]
no_license
package com.itzwf.mobilesafe.service; import java.lang.reflect.Method; import com.android.internal.telephony.ITelephony; import com.itzwf.mobilesafe.db.BlackDao; import com.itzwf.mobilesafe.domail.BlackInfo; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.net.Uri; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; public class SrljService extends Service { private static final String TAG = "SrljService"; private TelephonyManager mTm; private BlackDao mDao; //电话状态监听 private PhoneStateListener listener = new PhoneStateListener(){ public void onCallStateChanged(int state, final String incomingNumber) { //state表示接收电话的状态 //incomingNumber 打进来的电话号码 // * @see TelephonyManager#CALL_STATE_IDLE 搁浅状态 // * @see TelephonyManager#CALL_STATE_RINGING 响铃状态 // * @see TelephonyManager#CALL_STATE_OFFHOOK 接听状态 switch (state) { case TelephonyManager.CALL_STATE_IDLE: break; case TelephonyManager.CALL_STATE_RINGING: //响铃状态,判断是否在黑名单内,如果在就手动挂掉 int type = mDao.findType(incomingNumber); if(type==BlackInfo.TYPE_CALL || type==BlackInfo.TYPE_ALL){ //挂掉电话 因为系统把服务隐藏了.所以要用反射的方法去实现 // Context.TELEPHONY_SERVICE // ITelephony.Stub.asInterface(ServiceManager.getService(Context.TELEPHONY_SERVICE)); try { Class<?> clazz = Class .forName("android.os.ServiceManager"); Method method = clazz.getDeclaredMethod("getService", String.class); IBinder binder = (IBinder) method.invoke(null, Context.TELEPHONY_SERVICE); ITelephony telephony = ITelephony.Stub .asInterface(binder); telephony.endCall(); //删除通话记录 //创建内容管理者 final ContentResolver cr = getContentResolver(); final Uri uri = Uri.parse("Content://call_log/calls"); //注册内容管理者 cr.registerContentObserver(uri, true, new ContentObserver(new Handler()) { public void onChange(boolean selfChange) { String where = "number = ?"; String[] selectionArgs = new String[]{incomingNumber}; cr.delete(uri, where, selectionArgs); }; }); // } catch (Exception e) { e.printStackTrace(); } } break; case TelephonyManager.CALL_STATE_OFFHOOK: break; default: break; } }; }; @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); //开启服务 Log.d(TAG, "开启拦截服务"); mTm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); mDao = new BlackDao(this); //开启电话拦截 mTm.listen(listener,PhoneStateListener.LISTEN_CALL_STATE); } @Override public void onDestroy() { super.onDestroy(); //关闭服务 Log.d(TAG, "关闭拦截服务"); mTm.listen(listener, PhoneStateListener.LISTEN_NONE); } }
C
UTF-8
657
3.234375
3
[]
no_license
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <limits.h> int main() { uint64_t i = LLONG_MAX; uint64_t divisor = 7; uint64_t sum = 1; uint64_t count = divisor; printf("sizeof int %d, value = %llu\n", sizeof(int64_t), i); while (count < i) { count = count << 1; sum = sum << 1; /*if (count > LLONG_MAX) printf("%llu",count -LLONG_MAX);*/ } if (count == i){ printf("output = %llu", sum); return 0; } ////if we got here then we over shot our target count = count >> 1; sum = sum >> 1; while (count < i){ count = count + divisor; sum = sum + 1; } printf("output = %llu", sum); return 0; }
JavaScript
UTF-8
2,663
2.625
3
[]
no_license
import React, { Component } from "react"; import { getStudents } from "../services/studentService"; import { createFullName, getAvg } from "./utils/initialCalculation"; import { filterStudents } from "./utils/filterStudents"; import SearchBox from "./common/searchBox"; import InfoList from "./infoList"; class Students extends Component { state = { students: [], grades: [], nameSearchQuery: "", tagSearchQuery: "" }; async componentDidMount() { const { data } = await getStudents(); let students = data.students; const fullName = students.map(student => createFullName(student)); const grades = students.map(student => student.grades); const avg = grades.map(grade => getAvg(grade)); students.map(student => { student.avg = avg[student.id - 1]; student.fullName = fullName[student.id - 1]; student.tags = []; return student; }); this.setState({ students, grades }); } handleNameSearch = query => { this.setState({ nameSearchQuery: query }); this.setState({ tagSearchQuery: "" }); }; handleTagSearch = query => { this.setState({ tagSearchQuery: query }); this.setState({ nameSearchQuery: "" }); }; handleClick = student => { let students = [...this.state.students]; const index = students.indexOf(student); if (students[index].expanded === true) { students[index].expanded = false; } else { students[index].expanded = true; } this.setState({ students }); }; createTag = (value, student) => { console.log(value); const newTag = value; const students = [...this.state.students]; const index = students.indexOf(student); let selectedStudent = students[index]; selectedStudent.tags = [...selectedStudent.tags, newTag]; this.setState({ students }); }; render() { const { students, nameSearchQuery, tagSearchQuery } = this.state; const filteredStudents = filterStudents( students, nameSearchQuery, tagSearchQuery ); return ( <div id="student-list" className="list-container"> <SearchBox name="nameSearch" onChange={this.handleNameSearch} value={nameSearchQuery} placeholder="Search by name" /> <SearchBox name="tagSearch" onChange={this.handleTagSearch} value={tagSearchQuery} placeholder="Search by tag" /> <InfoList filteredStudents={filteredStudents} onClick={this.handleClick} tags={filteredStudents.tags} onCreateTag={this.createTag} /> </div> ); } } export default Students;
C#
UTF-8
1,044
2.515625
3
[]
no_license
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace EFCoreCodeFirstScaffolding.Models { public sealed class AircraftFlightOrFlightPlan : BaseModel { public AircraftFlightOrFlightPlan() {} public AircraftFlightOrFlightPlan(string referencedTable, Aircraft aircraft, Users createdBy, Users modifiedBy, Flight flight = null, FlightPlan flightPlan = null) : base(createdBy, modifiedBy) { ReferencedTable = referencedTable; Aircraft = aircraft; Flight = flight; FlightPlan = flightPlan; } [Key] public int AircraftFlightOrFlightPlanId { get; set; } public string ReferencedTable { get; set; } [ForeignKey("AircraftId")] public Aircraft Aircraft { get; set; } [ForeignKey("FlightId")] public Flight Flight { get; set; } [ForeignKey("FlightPlanId")] public FlightPlan FlightPlan { get; set; } } }
Java
UTF-8
1,076
3.34375
3
[]
no_license
package com.jonyn; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; public class MultiThreadedServer { public static void main (String[] args) { Alumno.alumnos.add(new Alumno("Jose", "1234A")); Alumno.alumnos.add(new Alumno("Antonio", "5678B")); try { // 1.- Creamos un socket esperando clientes ServerSocket serverSocket = new ServerSocket(9090); boolean stop = false; while(!stop) { System.out.println("Esperando clientes..."); // cliente intenta conectar con el servidor Socket clientSocket = serverSocket.accept(); System.out.println("El cliente se ha conectado"); //Usamos la clase ClientThread ClientThread clientThread = new ClientThread(clientSocket); clientThread.start(); } } catch (IOException e){ System.out.println(e); } } }
C++
UTF-8
2,143
2.75
3
[]
no_license
#include <opencv.hpp> #include <ctime> using namespace cv; using namespace std; //#define debug int main() { #ifndef debug string picPath1, picPath2; cout << "enter the paths of the picture" << endl; cout << "pay attention to the length and width of the pictures" << endl; cout << "because the bigger one will be scaled down" << endl; cout << "The first picture:"; cin >> picPath1; cout << "The second picture:"; cin >> picPath2; cout << "the picture will change in 1 second" << endl; Mat pic1 = imread(picPath1); Mat pic2 = imread(picPath2); #endif #ifdef debug Mat pic1 = imread("/Users/shizi9/Desktop/PicBefore.png"); Mat pic2 = imread("/Users/shizi9/Desktop/PicAfter.png"); #endif if (pic1.empty() || pic2.empty()) { cout << "Couldn't open image" << endl; return -1; } Mat picBefore, picAfter; if (pic1.cols < pic2.cols) { resize(pic2, picAfter, Size(pic1.cols,pic1.rows)); picBefore = pic1; } else{ resize(pic1, picBefore, Size(pic2.cols,pic2.rows)); picAfter = pic2; } cout << "press Enter on picture to start" << endl; imshow("img", picBefore); waitKey(); int i = 100; Mat img = picBefore.clone(); clock_t start_t, end_t; int num = i; start_t = clock(); while (i > 0) { end_t = clock(); if (end_t - start_t > 10000) { --i; for (size_t row = 0; row < picBefore.rows; ++row) { for (size_t col = 0; col < picBefore.cols; ++col) { Scalar color1 = picBefore.at<Vec3b>(col,row); Scalar color2 = picAfter.at<Vec3b>(col,row); img.at<Vec3b>(col,row) = Vec3b (color1(0)*i/num+color2(0)*(num-i)/num, color1(1)*i/num+color2(1)*(num-i)/num, color1(2)*i/num+color2(2)*(num-i)/num); } } imshow("img", img); waitKey(1); start_t = end_t; } } cout << "press Enter to exit" << endl; waitKey(); return 0; }
Ruby
UTF-8
447
2.71875
3
[]
no_license
def beep(wav, chan) (s = SawOsc.new(:freq => 440, :gain => 0.25)) >> wav.in(chan) 10.times do play 0.1.seconds s.freq *= 1.2 end s << wav end wav = WavOut.new(:filename => "ex01.wav", :num_channels => 2) SinOsc.new(:freq => 440, :gain => 0.25) >> wav SinOsc.new(:freq => 880, :gain => 0.25) >> wav wav >> blackhole chan = 0 10.times do play 0.7.seconds chan = (chan + 1) % 2 spork { beep(wav, chan) } end play 2.seconds
Java
UTF-8
807
1.9375
2
[]
no_license
package com.example.toshiba.airbnb.Profile.BecomeAHost.BasicQuestions.POJOMap.GMapsAutoComplete; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by Owner on 2017-07-08. */ public class POJOPredictions { @SerializedName("predictions") @Expose private List<POJOPrediction> predictions = null; @SerializedName("status") @Expose private String status; public List<POJOPrediction> getPredictions() { return predictions; } public void setPredictions(List<POJOPrediction> predictions) { this.predictions = predictions; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
C++
UTF-8
1,643
3.15625
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <math.h> void computeSum (long long int *a, long long int SIZE_Z, long long int SIZE_X, long long int SIZE_Y){ int x, y, z, s; for( z = 0; z < SIZE_Z; z++ ) { for( y = 0; y < SIZE_Y; y++ ) { for( x = 0; x < SIZE_X; x++ ) { int valueToAdd = x + y - z; for (s = 0; s < SIZE_Z * SIZE_X * SIZE_Y; ++s) { valueToAdd += sqrt(s); } if (valueToAdd > 20) valueToAdd = sqrt(x + y - z); if( x == 0 || x == SIZE_X-1 || y == 0 || y == SIZE_Y-1 || z == 0 || z == SIZE_Z-1 ) { int offset = x + SIZE_X * y + z * (SIZE_X * SIZE_Y); a[offset] += x + y + z + valueToAdd; } else { if( (z == 1 || z == SIZE_Z-2) && x > 1 && x < SIZE_X-2 && y > 1 && y < SIZE_Y-2 ) { int offset = x + SIZE_X * y + z * (SIZE_X * SIZE_Y); a[offset] += x + y - z + valueToAdd; } } } } } } int main (int argc, char *argv[]){ /* * Check the inputs. */ if (argc < 2){ fprintf(stderr, "USAGE: %s LOOP_ITERATIONS\n", argv[0]); return -1; } auto iterations = atoll(argv[1]); if (iterations == 0) return 0; long long int *array = (long long int *) calloc(iterations * iterations * iterations, sizeof(long long int)); if (array == NULL){ fprintf(stderr, "Cannot allocate memory\n"); return 0; } auto nearEnd = (iterations * iterations * iterations) - 5; if (nearEnd < 0) nearEnd = 0; array[nearEnd] = argc; computeSum(array, iterations, iterations, iterations); auto s = *array; printf("%lld, %lld\n", s, array[nearEnd]); return 0; }
Java
UTF-8
2,066
2.625
3
[]
no_license
package chattylabs.android.commons; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; public abstract class PermissionsHelper { public static void check(Activity activity, String[] permissions, Runnable onPermissionsNotNeeded, int requestCode) { if (required(activity.getApplicationContext(), permissions)) { // Should we show an explanation? if (needsExplanation(activity, permissions)) { ActivityCompat.requestPermissions(activity, permissions, requestCode); // TODO // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(activity, permissions, requestCode); } } else { onPermissionsNotNeeded.run(); } } public static boolean required(Context context, String[] permissions) { for (String permission : permissions) { if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) return true; } return false; } public static boolean allGranted(@NonNull int[] grantResults) { for (int perm : grantResults) if (perm == PackageManager.PERMISSION_DENIED) return false; return true; } private static boolean needsExplanation(Activity activity, String[] permissions) { for (String permission : permissions) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) return true; } return false; } }
C
UTF-8
8,416
2.578125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> /* Model: MODEL_IDEAL_GAS Ideal gas MODEL_COULOMB Coulomb's interaction MODEL_LENNARD_JONES Lennard Jones potential MODEL_EXT_FORCE Add external force to the problem Initial conditions: INIT_RAND_PART n random particles INIT_RUTHERFORD two particles Rutherford scattering Boundary conditions: BOUND_OFF no boundary conditions BOUND_WALLS Hard walls BOUND_PERIODIC Periodic Output: OUT_FILE print results to file OUT_GNUPLOT_VIS using gnuplot interactive terminal OUT_ENERGY outputs energy over time in a separate file OUT_GNUPLOT_ENERGY plot enery along in the interactive terminal */ // Model #define MODEL_LENNARD_JONES //#define MODEL_EXT_FORCE // Initial conditions #define INIT_RAND_PART // Boundary conditions #define BOUND_WALLS // Output #define OUT_GNUPLOT_VIS #define OUT_ENERGY typedef double real; // Global // Constants const real pi = 3.14159265359; const real k_B = 1.38064852e-23; // Number of dimensions const size_t dim = 3; // Number of particles #ifdef INIT_RAND_PART const size_t n = 100; #endif #ifdef INIT_RUTHERFORD const size_t n = 2; #endif // Generate random real in a range real randreal(real, real); // Generate random integer in a range int randint(int, int); // Calculate acceleration using Coulombs law real * accel(real [n][dim], real [n], real [n], size_t); // Maxwell-Boltzmann distribution real v_max_boltz(real, real); int main(){ // Number of time iterations #ifdef OUT_FILE const size_t nt = 10000; #endif // Box size real space[dim][2]; // Spatial and time step size const real dx = 1e-6, dt = 1e-3; // Particle properties real m[n], q[n]; // Particle state real x[n][dim], v[n][dim], *a[n], *a_next[n]; // Auxiliary vars size_t i, j, k; #ifdef OUT_FILE // Open output file FILE * data; data = fopen("particles.dat", "w"); if (data == NULL){ printf("\nError opening file.\n"); exit (EXIT_FAILURE); } #endif #ifdef OUT_ENERGY // Variable to store energy real energy, energy0; // Open output file FILE * energydata; energydata = fopen("energy.dat", "w"); if (energydata == NULL){ printf("\nError opening file.\n"); exit (EXIT_FAILURE); } #endif // Spatial limits for (k = 0; k < dim; k++) { space[k][0] = -10; space[k][1] = 10; } #ifdef INIT_RAND_PART // Generate random particles srand (time ( NULL)); for (i = 0; i < n; i++) { do m[i] = 5;//randreal(0, 10); while (fabs(m[i]) < 0.1); q[i] = (float)randint(-1, 1); for (k = 0; k < dim; k++) { x[i][k] = randreal(space[k][0], space[k][1]); v[i][k] = randreal(-10, 10); } } #endif #ifdef INIT_RUTHERFORD // Setup particles for (i = 0; i < n; i++){ m[i] = 1; q[i] = 1; } for (k = 0; k < dim; k++) { // Target x[0][k] = 0; v[0][k] = 0; // Projectile x[1][k] = -10; v[1][0] = 1; } #endif // Initial energy calculation #ifdef OUT_ENERGY energy0 = 0; for (i = 0; i < n; i++) { for (k = 0; k < dim; k++) { energy0 += 0.5*m[i]*pow(v[i][k],2); } } #endif // First acceleration calculation for (i = 0; i < n; i++) a[i] = accel(x, m, q, i); // Velocity Verlet #ifdef OUT_FILE // Loop with time limit for (j = 0; j < nt; j++){ #endif #ifdef OUT_GNUPLOT_VIS // Loop indefinetely while (1){ j++; #endif #ifdef OUT_FILE // Print time fprintf(data, "%f", j*dt); #endif #ifdef OUT_ENERGY // Calculate the total energy in the system energy = 0; for (i = 0; i < n; i++) { for (k = 0; k < dim; k++) { energy += 0.5*m[i]*pow(v[i][k],2); } } energy = (energy-energy0)/energy0; // Print data fprintf(energydata, "%f\t%f\n", j*dt, energy); #endif #ifdef OUT_GNUPLOT_VIS // Setup GNUPLOT printf("set key off\n"); #ifdef OUT_GNUPLOT_ENERGY printf("set multiplot layout 1,2\n"); printf("set xrange [0:1]\n"); printf("set yrange [-100:100]\n"); printf("plot \"energy.dat\" w l\n"); #endif printf("set xrange [%f:%f]\n", space[0][0], space[0][1]); printf("set yrange [%f:%f]\n", space[1][0], space[1][1]); if (dim == 3){ printf("set zrange [%f:%f]\n", space[2][0], space[2][1]); printf("set view equal xyz\n"); // Call interactive terminal printf("splot \"-\" w p pt 9 ps 1\n"); } else // Call interactive terminal printf("plot \"-\" w p pt 9 ps 1\n"); #endif // Loop on particles for (i = 0; i < n; i++){ // Particle style in plot #ifdef OUT_GNUPLOT_VIS //printf("set style w p pt 7 ps 0.5"); //if (q[i] > 0) printf(" lc rgb \"red\" \n"); //else if (q[i] < 0) printf(" lc rgb \"blue\" \n"); //else printf(" lc rgb \"black\" \n"); #endif // Loop on dimensions for (k = 0; k < dim; k++){ // Print positions #ifdef OUT_FILE fprintf(data, "\t%f", x[i][k]); #endif #ifdef OUT_GNUPLOT_VIS printf("%f\t", x[i][k]); #endif // Update positions x[i][k] = x[i][k] + v[i][k]*dt + 0.5*dt*dt*a[i][k]; // Boundary conditions // Hard walls #ifdef BOUND_WALLS if (x[i][k] < space[k][0]){ x[i][k] = 2*space[k][0] - x[i][k]; v[i][k] = -v[i][k]; } else if (x[i][k] > space[k][1]){ x[i][k] = 2*space[k][1] - x[i][k]; v[i][k] = -v[i][k]; } #endif // Periodic condition #ifdef BOUND_PERIODIC if (x[i][k] < space[k][0]) x[i][k] = space[k][1] - (x[i][k] - space[k][0]); else if (x[i][k] > space[k][1]) x[i][k] = space[k][0] - (x[i][k] - space[k][1]); #endif } #ifdef OUT_GNUPLOT_VIS printf("\n"); #endif } // Update acceleration and speed for (i = 0; i < n; i++){ a_next[i] = accel(x, m, q, i); for (k = 0; k < dim; k++){ v[i][k] = v[i][k] + 0.5*(a[i][k]+a_next[i][k])*dt; a[i][k] = a_next[i][k]; } } // Finish time step #ifdef OUT_FILE fprintf(data, "\n"); #endif #ifdef OUT_GNUPLOT_VIS printf("e\n"); #endif } #ifdef OUT_FILE // Close output file fclose(data); #endif return 0; } real randreal(real min, real max){ real range = (max - min); real divisor = RAND_MAX / range; return min + (rand() / divisor); } int randint(int min, int max){ return (rand()%(max-min+1) + min); } real v_max_boltz(real T, real m){ real x1, x2, w, y, sigma; do{ x1 = randreal(-1.0, 1.0); x1 = randreal(-1.0, 1.0); w = x1*x1 + x2*x2; } while (w >= 1.0); w = sqrt( (-2.0 * log( w ) ) / w ); y = x1 * w; sigma = sqrt(k_B*T/m); return y*sigma; } real * accel(real x[n][dim], real m[n], real q[n], size_t r){ real *a = malloc(sizeof(real)*dim); real *extf = malloc(sizeof(real)*dim); real d, s[dim]; size_t i, k; #ifdef MODEL_IDEAL_GAS return a; #endif #ifdef MODEL_COULOMB // Check particle charge if (q[r] == 0) return a; // Interaction intensity real kcoulomb = 10; // Loop on the other particles for (i = 0; i < n; i++) { if (i != r) { // Check particle charge if (q[i] != 0){ // Calculate separation vector and distance in between d = 0; for (k = 0; k < dim; k++) { s[k] = x[r][k] - x[i][k]; d += pow(s[k], 2); } d = pow(d, 1.5); // Calcuate acceleration for (k = 0; k < dim; k++) { a[k] += kcoulomb*q[r]*q[i]*s[k]/(d*m[r]); } } }} #endif #ifdef MODEL_LENNARD_JONES // Interaction constants real epsilon = 1, sigma = 1; // Loop on the other particles for (i = 0; i < n; i++) { if (i != r) { // Calculate separation vector and distance in between d = 0; for (k = 0; k < dim; k++) { s[k] = x[r][k] - x[i][k]; d += pow(s[k], 2); } // Calcuate acceleration for (k = 0; k < dim; k++) { a[k] += (48*epsilon*s[k]/(d*m[r]))*((pow(sigma,12)/pow(d,6)) - (0.5*pow(sigma,6)/pow(d,3))); } }} #endif #ifdef MODEL_EXT_FORCE for (k = 0; k < dim; k++) { extf[k] = 10*(5 - x[r][k]); } a[k] += extf[k]/m[r]; #endif return a; }
C#
UTF-8
1,900
2.671875
3
[]
no_license
/** * Description: Utility methods used by other scripts. * Authors: Kornel * Copyright: © 2019 Kornel. All rights reserved. For license see: 'LICENSE.txt' **/ using UnityEngine; using UnityEngine.UI; public class Utilities : MonoBehaviour { /// <summary> /// Draws a line. /// </summary> /// <param name="start">Start point.</param> /// <param name="end">End point.</param> /// <param name="color">Line color.</param> /// <param name="width">Width of the line.</param> /// <param name="duration">Duration before it vanishes.</param> /// <returns>Returns reference to the line's GameObject.</returns> static public GameObject DrawLine( Vector3 start, Vector3 end, Color color, float width = 0.1f, float duration = 0.5f ) { GameObject line = new GameObject( "Line " + Random.Range( 1, 1000 ) ); line.transform.position = start; LineRenderer lr = line.AddComponent<LineRenderer>( ); lr.material = new Material( Shader.Find( "Sprites/Default" ) ); lr.startColor = color; lr.endColor = color; lr.startWidth = width; lr.endWidth = width; lr.SetPosition( 0, start ); lr.SetPosition( 1, end ); Destroy( line, duration ); return line; } /// <summary> /// Return a signed angle between 2 vectors. /// </summary> /// <param name="vector1">First vector.</param> /// <param name="vector2">Second vector.</param> /// <returns>Signed angle.</returns> static public float AngleBetweenVectors( Vector2 vector1, Vector2 vector2 ) { Vector2 diference = vector2 - vector1; float sign = ( vector2.y < vector1.y ) ? -1.0f : 1.0f; return Vector2.Angle( Vector2.right, diference ) * sign; } static public float ConvertRange( float originalStart, float originalEnd, float newStart, float newEnd, float value ) { float scale = ( newEnd - newStart ) / ( originalEnd - originalStart ); return ( newStart + ( ( value - originalStart ) * scale ) ); } }
Markdown
UTF-8
1,563
2.6875
3
[ "MIT" ]
permissive
# remote-home ### Abstract This project proposes the development of a system of control and monitoring of lighting and energy based on Internet of Things concept that consists in a module capable of controlling and monitoring the energy consumption of the equipment to which it is coupled, providing daily, weekly or monthly reports about individual or total consumption, as well as notifications about excessive consumption. Unlike most of the available solutions, each module has an ID and is independent, communicating directly with a cloud server. The system is controlled by an iOS app, being able to control the equipment manually or automatically, via modules based on user’s default behavior or location of smartphone. ### Resumo No presente trabalho propõe-se o desenvolvimento de um sistema de controle e monitoramento de iluminação e energia baseado no conceito de internet das coisas, que consiste em um módulo capaz de controlar e monitorar o consumo de energia dos equipamentos aos quais for acoplado, disponibilizando relatórios diários, semanais ou mensais sobre o consumo individual ou total, além de notificações sobre um consumo excessivo. Diferente da grande maioria das soluções presentes no mercado, cada módulo possui um identificador único e é independente, comunicando- se diretamente com um servidor em nuvem. O sistema é controlado via aplicativo iOS, sendo possível acionar os equipamentos manualmente ou automaticamente, via módulos baseados no comportamento padrão do usuário ou localização do smartphone.
Java
UTF-8
145
2.171875
2
[]
no_license
interface ITest { static final int k=100; } class Interface1 { public static void main(String[] args) { System.out.println("k: "+ITest.k); } }
Markdown
UTF-8
1,085
2.6875
3
[]
no_license
# Golang Image Edit the files to fit version your application you want to publish and the version of the Alpine Linux you want to use to embed it. For example, to set it to embed version 0.8 of your application on Alpine Linux 3.7 ``` spec: output: to: kind: ImageStreamTag name: inventory:0.8 source: dockerfile: |- FROM alpine:3.7 images: - from: kind: ImageStreamTag name: inventory-artifacts:0.8 strategy: dockerStrategy: from: kind: ImageStreamTag name: alpine-s2i:3.7 ``` otherwise, if the defined version are the ones you want, simply leave it unmodified Switch to the project you created, for example ``` oc project shop ``` Create the imagestream ``` oc apply -f imagestream.yaml ``` Create The build configuration ``` oc apply -f buildconfig.yaml ``` Build should automatically start Wait until it completes ``` oc get builds NAME TYPE FROM STATUS STARTED DURATION inventory-1 Docker Dockerfile Complete 35 seconds ago 7s ```
Java
UTF-8
2,852
2.328125
2
[]
no_license
package kkook.team.projectswitch.util; import android.content.Context; import android.util.Log; import android.widget.EditText; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import kkook.team.projectswitch.R; /** * Created by Askai on 2015-12-04. */ public class ThreadGCMSender extends Thread { private static final String TAG = "[GCM] ThreadGCMSender"; Context context; String msg; ArrayList<String> targetUsers; // public ThreadGCMSender(Context context) { // this(context, null, null); // } public ThreadGCMSender(Context context, String msg, ArrayList<String> targetUsers) { this.context = context; this.msg = msg; this.targetUsers = targetUsers; } public void sendMessage() { sendMessage(this.msg); } public void sendMessage(String msg) { if(this.msg == null) this.msg = msg; start(); } @Override public void run() { try { // Prepare JSON containing the GCM message content. What to send and where to send. JSONObject jGcmData = new JSONObject(); JSONObject jData = new JSONObject(); jData.put("message", msg); // Where to send GCM message. if(targetUsers != null && targetUsers.size() > 0) { // FIXME: Prepare target users for multicast jGcmData.put("registration_ids", new JSONArray(targetUsers)); } else { // FIXME: Shouldn't work by broadcast jGcmData.put("to", "/topics/global"); } // What to send in GCM message. jGcmData.put("data", jData); // Create connection to send GCM Message request. URL url = new URL("https://android.googleapis.com/gcm/send"); HttpURLConnection conn = null; conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "key=" + context.getString(R.string.gcm_serverAPIKey)); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod("POST"); conn.setDoOutput(true); // Send GCM message content. Log.i(TAG, "Send this message= " + jGcmData.toString()); OutputStream outputStream = conn.getOutputStream(); outputStream.write(jGcmData.toString().getBytes()); // Read GCM response. InputStream inputStream = conn.getInputStream(); String resp = IOUtils.toString(inputStream); Log.i(TAG, "Response of the server = " + resp + "\n" + "Check your device/emulator for notification or logcat for " + "confirmation of the receipt of the GCM message."); } catch (JSONException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Swift
UTF-8
1,828
2.515625
3
[]
no_license
// // TweetPile.swift // V2-Trumpagotchi // // Created by Daniel Walder on 8/5/20. // Copyright © 2020 Daniel Walder. All rights reserved. // import Foundation import SpriteKit class TweetPile: SKSpriteNode { let officeScene: OfficeScene var isMoving = false var tweetPost: TweetPost! init(screenSize: CGSize, startPos: CGPoint, endPos: CGPoint, officeScene: OfficeScene) { self.officeScene = officeScene let texture = SKTexture(imageNamed: "tweetPile") let scaleRatio = (screenSize.width / scaleToScreenDict["tweetPile"]!) / texture.size().width let spriteSize = CGSize(width: screenSize.width / scaleToScreenDict["tweetPile"]!, height: texture.size().height * scaleRatio) super.init(texture: texture, color: UIColor.clear, size: spriteSize) self.position = endPos self.zPosition = 4 officeScene.tweetPiles.append(self) let tweetContent = getRandomTweetContent() tweetPost = TweetPost(screenSize: officeScene.size, text: tweetContent.text, date: tweetContent.date) officeScene.addChild(tweetPost) tweetPost.isHidden = true } func moveTo(location: CGPoint) { self.run(SKAction.move(to: location, duration: 0.01)) isMoving = true } func showTweet() { tweetPost.isHidden = false } func throwAway() { officeScene.trump.changeNumTweets(value: -1) tweetPost.removeFromParent() self.removeFromParent() } func getRandomTweetContent() -> TweetContent { let index = Int(arc4random() % UInt32(tweetContents.count)) return tweetContents[index] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
Python
UTF-8
7,379
2.59375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Ed Mountjoy # import sys import os import argparse import pandas as pd import numpy as np from sklearn.preprocessing import quantile_transform import seaborn as sns import matplotlib.pyplot as plt from matplotlib import rcParams # from scipy.stats import rankdata def main(): # Parse args args = parse_args() # Source aggregate weights source_weights = { 'vep': 1, 'javierre2016': 1, 'andersson2014': 1, 'thurman2012': 1, 'gtex_v7': 1, 'sun2018': 1 } # # Load data ---------------------------------------------------------------- # # Load data data = load_slice(args.v2g_slice, nrows=None) print('Total rows: ', data.shape[0]) print('size (bp) : ', data.position.max() - data.position.min()) # Load vep map vep_map = load_vep_map() # # Derive features ---------------------------------------------------------- # print('Preprocessing...') # Add score column data['score'] = data.apply(create_score_column, vep_map=vep_map, axis=1) # Wipe VEP features data.loc[data.type_id == 'vep', 'feature'] = 'not_a_feature' # Remove rows with null scores data = data.loc[~pd.isnull(data.score), :] # Calculate quantiles per feature data['score_scaled'] = ( data.groupby(('source_id', 'feature')) .score .transform(lambda x: quantiles(x, n=10)) ) outf = '{0}.preprocessed.tsv.gz'.format(args.outpref) data.to_csv(outf, sep='\t', index=None, compression='gzip') # Print stats print('Num unique varids: ', data.variant_id.nunique()) # # Get score per source ----------------------------------------------------- # # Aggregate per source, calculate max feature score print('Creating max and count scores per feature...') per_source_scores = ( data.groupby(['variant_id', 'source_id', 'gene_name']) .score_scaled .agg([np.max]) .rename(columns={'amax':'ft_max'}) ) # Melt into long format per_source_scores = ( per_source_scores.stack() .reset_index() .rename(columns={'level_3':'score_type', 0:'score'}) ) outf = '{0}.per_source_scores.tsv'.format(args.outpref) per_source_scores.to_csv(outf, sep='\t', index=None) # # Get score per variant_id ------------------------------------------------- # # Average over source_ids using per source weights print('Weighted mean over source types...') per_varid = ( per_source_scores.groupby(['variant_id', 'gene_name']) .apply(weighted_mean_src, score_col='score', weight_map=source_weights) .reset_index() .rename(columns={0:'src_agg'}) ) outf = '{0}.per_variant_scores.tsv'.format(args.outpref) per_varid.to_csv(outf, sep='\t', index=None) # # With variant fixed, make heatmaps ---------------------------------------- # # Set matplotlib to auto layout rcParams.update({'figure.autolayout': True}) # args.varid = '16_53563398_C_A' # Stop here if varid is not specified if not args.varid: sys.exit() elif not args.varid in data.variant_id.unique(): sys.exit('--varid {0} not found in data'.format(args.varid)) # Make one heatmap per source_id for name, grp in data.loc[data.variant_id == args.varid, :].groupby('source_id'): plot_data = grp.pivot_table(index='gene_name', columns='feature', values='score_scaled') ax = sns.heatmap(plot_data, cmap=sns.color_palette("Blues"), annot=True) ax.set_title('{0}\n{1}'.format(args.varid, name)) out_plot = '{0}.plot.{1}.per_tissue.png'.format(args.outpref, name) ax.figure.savefig(out_plot) plt.clf() # Make heatmap summarising source_ids, using aggregate score plot_data = ( per_source_scores.loc[(per_source_scores.variant_id == args.varid), :] .pivot_table(index='gene_name', columns='source_id',) # values='score') ) ax = sns.heatmap(plot_data, cmap=sns.color_palette("Blues"), annot=True) ax.set_title('{0}\n{1}\n{2}'.format(args.varid, 'source_id_summary', 'aggregate_score')) out_plot = '{0}.plot.per_source.png'.format(args.outpref) ax.figure.savefig(out_plot) plt.clf() return 0 def weighted_mean_src(grp, score_col, weight_map): ''' Calculate weighted mean using source_id specific weights. Args: grp (pd df): group from pd.groupby().apply() weight_map (dict): dict of weights source_id->weight Returns: Weighted mean across score_types ''' weights = [weight_map[source] for source in grp.source_id] weighted_mean = np.average(grp[score_col], weights=weights) return weighted_mean def quantiles(l, n=10): ''' Converts a list/series of values to quantiles of same shape. sklearn.quantile_transform() requires data to be reshaped ''' qt = quantile_transform(X=l.as_matrix().reshape(-1, 1), n_quantiles=n) return qt.reshape(1, -1)[0] def create_score_column(row, vep_map): ''' Returns a score specific to type_id ''' if row.type_id == 'pchic': if row.interval_score != 0: return row.interval_score else: return np.nan elif row.type_id == 'fantom5': if row.interval_score != 0: return row.interval_score else: return np.nan elif row.type_id == 'dhscor': if row.interval_score != 0: return row.interval_score else: return np.nan elif row.type_id == 'vep': return vep_map[row.feature] elif row.type_id == 'eqtl': return 1 - row.qtl_pval else: sys.exit('Error: type_id not recognised {0}'.format(row.type_id)) def load_slice(inf, nrows=None): ''' Args: inf (str): file containing slice of v2g Returns: pd.df ''' df = pd.read_csv(inf, sep='\t', header=None, nrows=nrows) df.columns = [ 'chr_id', 'position', 'ref_allele', 'alt_allele', 'variant_id', 'rs_id', 'gene_chr', 'gene_id', 'gene_start', 'gene_end', 'gene_name', 'feature', 'type_id', 'source_id', 'csq_counts', 'qtl_beta', 'qtl_se', 'qtl_pval', 'interval_score'] return df def load_vep_map(): vm_df = pd.read_csv('docs/vep_consequences_180807.tsv', sep='\t', header=0) vep_map = dict(zip(vm_df['SO term'], vm_df['v2g_score'])) return vep_map def parse_args(): """ Load command line args """ parser = argparse.ArgumentParser() parser.add_argument('--v2g_slice', metavar="<file>", type=str, required=True) parser.add_argument('--varid', metavar="<file>", type=str) parser.add_argument('--outpref', metavar="<str>", help='Output prefix', type=str, required=True) args = parser.parse_args() return args if __name__ == '__main__': main()
Java
UTF-8
238
2.703125
3
[]
no_license
/** * @author Viacheslav Oleshko */ public class WavPlayer implements AudioPlayer { @Override public void play(AudioTrack track) { System.out.println(String.format( "Playing Wav: %s...", track.getTitle())); } }
Markdown
UTF-8
3,497
4.1875
4
[]
no_license
[TOC] # Tree Problems for Practice ## Easy ### 1. Write a binary tree class Here you will define a simple binary tree class. ### 2. Check if the tree is empty Here we are not looking at whether a given node is empty, rather if the entire tree is empty. ### 3. Write the basic tree traversal: pre-, post-, in-order Write these are three separate functions. Should they be methods? ### 4. Write a method to insert a value in a BST Where would this method be? In BST class or Node class? ### 5. Write a method to search for a value in BST So, given a value, the method should return either true or false based on whether the value exists or not. ### 6. Delete A Leaf Node Write a method to delete a leaf node in a given tree ## Medium # Solutions ## Easy ### 1. Write a Binary Tree class ```python class Node(): def __init__(self, data=None): self.data = data self.left = None self.right = None class BST(): def __init__(self, data): self.root = Node(data) ``` ### 2. Check if the tree is empty To check that we will use a method in the `BST` class: ```python def isEmpty(self): if self.root == None: return True return False ``` Here we use `self.root.left` instead of `self.left` because the `BST()` class does not have `self.left`. But `root` which is a node has it. ### 3. Write the basic tree traversal: pre-, post-, in-order These tree traversal are written in the `BST` class: ```python # This would be in the BST class: def preorder(self, node): if node is not None: print(node.data) self.preorder(node.left) self.preorder(node.right) else: return '' def inorder(self, node): if node is not None: self.inorder(node.left) print(node.data) self.inorder(node.right) else: return '' def postorder(): if node is not None: self.postorder(node.left) self.postorder(node.right) print(node.data) else: return '' def tree_traversal(self, flag): if flag == 'pre': return self.preorder(self.root) elif flag == 'in': return self.inorder(self.root) elif flag == 'post': return self.postorder(self.root) ``` ### 4. Write a method to insert a value in a BST ```python # This would be in node class def insert(self, value): if value < self.data: if self.left is not None: self.insert(value) else: node.left = Node(value) elif value > node.data: if self.right is not None: self.insert(value) else: self.right = Node(value) else: print('Value already in BST') # This would be in the BST Class: def insert(self, value): if self.root: self.root.insert(value) else: self.root = Node(value)Write a method to search for a value in BST ``` ### 5. Write a method to search for a value in BST ```python # In BST Class: def search(self, value): if not self.isEmpty(): return self.root.search(value) else: return False # In Node Class: def search(self, value): if value == self.data: return True elif value < self.data: if self.left: return self.left.search(value) else: return False elif value > self.data: if self.right: return self.right.search(value) else: return False ```
Python
UTF-8
2,326
2.875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 19 19:43:02 2019 @author: cynthia """ import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import Dense from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split df=pd.read_csv( './housing.data', sep=" +", header=None, names=['CRIM', 'ZN', 'INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT','A'] ) df=df[~df['A'].isin([50])] df=df[~df['RM'].isin([8.78])] X=df[['RM','LSTAT','PTRATIO']] X=X.values y=df['A'] y=y.values train_x,test_x,train_y,test_y = train_test_split(X,y,test_size=0.1,random_state=0) sc = StandardScaler() train_x = sc.fit_transform(train_x) test_x = sc.fit_transform(test_x) n_hidden_1 = 64 #隐藏层1的神经元个数 n_hidden_2 = 64 #隐藏层2的神经元个数 n_input = 3 #输入层的个数 n_classes = 1 #输出层的个数 training_epochs = 200 #训练次数,总体数据需要循环多少次 batch_size = 5 #每批次要取的数据的量,这里是提取10条数据 model = Sequential() model.add(Dense(n_hidden_1, activation='relu', input_dim=n_input)) model.add(Dense(n_hidden_2, activation='relu')) model.add(Dense(n_classes)) #自定义评价函数 import keras.backend as K def r2(y_true, y_pred): a = K.square(y_pred - y_true) b = K.sum(a) c = K.mean(y_true) d = K.square(y_true - c) e = K.sum(d) f = 1 - b/e return f model.compile(loss='mse', optimizer='rmsprop', metrics=['mae',r2]) history = model.fit(train_x, train_y, batch_size=batch_size, epochs=training_epochs) pred_test_y = model.predict(test_x) print(pred_test_y) from sklearn.metrics import r2_score pred_acc = r2_score(test_y, pred_test_y) print('pred_acc',pred_acc) #绘图 import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 设置图形大小 plt.figure(figsize=(8, 4), dpi=80) plt.plot(range(len(test_y)), test_y, ls='-.',lw=2,c='r',label='ture') plt.plot(range(len(pred_test_y)), pred_test_y, ls='-',lw=2,c='b',label='predict') # 绘制网格 plt.grid(alpha=0.4, linestyle=':') plt.legend() plt.xlabel('number') #设置x轴的标签文本 plt.ylabel('price') #设置y轴的标签文本 # 展示 plt.show()
Java
WINDOWS-1252
4,416
2.125
2
[]
no_license
package org.xpup.hafmis.syscollection.common.domain.entity; import java.io.Serializable; import java.math.BigDecimal; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.xpup.hafmis.syscommon.domain.entity.DomainObject; /** @author Hibernate CodeGenerator */ public class AdjustWrongAccountTail extends DomainObject { /** persistent field */ private AdjustWrongAccountHead adjustWrongAccountHead; /** persistent field */ private Emp emp = new Emp(); private Integer empId; /** persistent field */ private BigDecimal adjustMoney; private String empName; /** persistent field */ private String settDate; /**ѡa*/ private String reserveaA; private String reserveaB; private String reserveaC; private String reason = ""; private String remark = ""; public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } /** full constructor */ public AdjustWrongAccountTail(AdjustWrongAccountHead adjustWrongAccountHead,Integer empId, BigDecimal adjustHeadId, BigDecimal adjustMoney, String settDate,String reserveaA, String reserveaB, String reserveaC) { this.adjustWrongAccountHead = adjustWrongAccountHead; this.empId = empId; this.adjustMoney = adjustMoney; this.settDate = settDate; this.reserveaA = reserveaA; this.reserveaB = reserveaB; this.reserveaC = reserveaC; } /** default constructor */ public AdjustWrongAccountTail() { } /** minimal constructor */ public AdjustWrongAccountTail(AdjustWrongAccountHead adjustWrongAccountHead,Integer empId, BigDecimal adjustHeadId, BigDecimal adjustMoney, String settDate) { this.adjustWrongAccountHead = adjustWrongAccountHead; this.empId = empId; this.adjustMoney = adjustMoney; this.settDate = settDate; } public AdjustWrongAccountHead getAdjustWrongAccountHead() { return adjustWrongAccountHead; } public void setAdjustWrongAccountHead( AdjustWrongAccountHead adjustWrongAccountHead) { this.adjustWrongAccountHead = adjustWrongAccountHead; } public Emp getEmp() { return emp; } public void setEmp(Emp emp) { this.emp = emp; } public BigDecimal getAdjustMoney() { return this.adjustMoney; } public void setAdjustMoney(BigDecimal adjustMoney) { this.adjustMoney = adjustMoney; } public String getSettDate() { return this.settDate; } public void setSettDate(String settDate) { this.settDate = settDate; } public String toString() { return new ToStringBuilder(this) .append("id", getId()) .toString(); } public boolean equals(Object other) { if ( !(other instanceof AdjustWrongAccountTail) ) return false; AdjustWrongAccountTail castOther = (AdjustWrongAccountTail) other; return new EqualsBuilder() .append(this.getId(), castOther.getId()) .isEquals(); } public int hashCode() { return new HashCodeBuilder() .append(getId()) .toHashCode(); } public String getReserveaA() { return reserveaA; } public void setReserveaA(String reserveaA) { this.reserveaA = reserveaA; } public String getReserveaB() { return reserveaB; } public void setReserveaB(String reserveaB) { this.reserveaB = reserveaB; } public String getReserveaC() { return reserveaC; } public void setReserveaC(String reserveaC) { this.reserveaC = reserveaC; } public Integer getEmpId() { return empId; } public void setEmpId(Integer empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } }
C#
UTF-8
7,913
2.703125
3
[ "MIT" ]
permissive
using Xamarin.Forms; namespace XF.Material.Forms.Resources { /// <summary> /// Class that provides color theme configuration based on https://material.io/design/color. /// </summary> public sealed class MaterialColorConfiguration : BindableObject { /// <summary> /// Backing field for the bindable property <see cref="Background"/>. /// </summary> public static readonly BindableProperty BackgroundProperty = BindableProperty.Create(nameof(Background), typeof(Color), typeof(Color), Color.FromHex("#EAEAEA")); /// <summary> /// Backing field for the bindable property <see cref="Error"/>. /// </summary> public static readonly BindableProperty ErrorProperty = BindableProperty.Create(nameof(Error), typeof(Color), typeof(Color), Color.FromHex("#B00020")); /// <summary> /// Backing field for the bindable property <see cref="OnBackground"/>. /// </summary> public static readonly BindableProperty OnBackgroundProperty = BindableProperty.Create(nameof(OnBackground), typeof(Color), typeof(Color), Color.FromHex("#000000")); /// <summary> /// Backing field for the bindable property <see cref="OnError"/>. /// </summary> public static readonly BindableProperty OnErrorProperty = BindableProperty.Create(nameof(OnError), typeof(Color), typeof(Color), Color.FromHex("#FFFFFF")); /// <summary> /// Backing field for the bindable property <see cref="OnPrimary"/>. /// </summary> public static readonly BindableProperty OnPrimaryProperty = BindableProperty.Create(nameof(OnPrimary), typeof(Color), typeof(Color), Color.FromHex("#FFFFFF")); /// <summary> /// Backing field for the bindable property <see cref="OnSecondary"/>. /// </summary> public static readonly BindableProperty OnSecondaryProperty = BindableProperty.Create(nameof(OnSecondary), typeof(Color), typeof(Color), Color.FromHex("#FFFFFF")); /// <summary> /// Backing field for the bindable property <see cref="OnSurface"/>. /// </summary> public static readonly BindableProperty OnSurfaceProperty = BindableProperty.Create(nameof(OnSurface), typeof(Color), typeof(Color), Color.FromHex("#000000")); /// <summary> /// Backing field for the bindable property <see cref="Primary"/>. /// </summary> public static readonly BindableProperty PrimaryProperty = BindableProperty.Create(nameof(Primary), typeof(Color), typeof(Color), Color.FromHex("#6200EE")); /// <summary> /// Backing field for the bindable property <see cref="PrimaryVariant"/>. /// </summary> public static readonly BindableProperty PrimaryVariantProperty = BindableProperty.Create(nameof(PrimaryVariant), typeof(Color), typeof(Color), Color.FromHex("#6200EE")); /// <summary> /// Backing field for the bindable property <see cref="Secondary"/>. /// </summary> public static readonly BindableProperty SecondaryProperty = BindableProperty.Create(nameof(Secondary), typeof(Color), typeof(Color), default(Color)); /// <summary> /// Backing field for the bindable property <see cref="SecondaryVariant"/>. /// </summary> public static readonly BindableProperty SecondaryVariantProperty = BindableProperty.Create(nameof(SecondaryVariant), typeof(Color), typeof(Color), Color.FromHex("#0400BA")); /// <summary> /// Backing field for the bindable property <see cref="Surface"/>. /// </summary> public static readonly BindableProperty SurfaceProperty = BindableProperty.Create(nameof(Surface), typeof(Color), typeof(Color), Color.FromHex("#FFFFFF")); /// <summary> /// The underlying color of an app’s content. /// Typically the background color of scrollable content. /// </summary> public Color Background { get => (Color)this.GetValue(BackgroundProperty); set => this.SetValue(BackgroundProperty, value); } /// <summary> /// The color used to indicate error status. /// </summary> public Color Error { get => (Color)this.GetValue(ErrorProperty); set => this.SetValue(ErrorProperty, value); } /// <summary> /// A color that passes accessibility guidelines for text/iconography when drawn on top of <see cref="Background"/>. /// </summary> public Color OnBackground { get => (Color)this.GetValue(OnBackgroundProperty); set => this.SetValue(OnBackgroundProperty, value); } /// <summary> /// A color that passes accessibility guidelines for text/iconography when drawn on top of <see cref="Error"/>. /// </summary> public Color OnError { get => (Color)this.GetValue(OnErrorProperty); set => this.SetValue(OnErrorProperty, value); } /// <summary> /// A color that passes accessibility guidelines for text/iconography when drawn on top of <see cref="Primary"/>. /// </summary> public Color OnPrimary { get => (Color)this.GetValue(OnPrimaryProperty); set => this.SetValue(OnPrimaryProperty, value); } /// <summary> /// A color that passes accessibility guidelines for text/iconography when drawn on top of <see cref="Secondary"/>. /// </summary> public Color OnSecondary { get { var color = (Color)this.GetValue(OnSecondaryProperty); return color.IsDefault ? this.OnPrimary : color; } set => this.SetValue(OnSecondaryProperty, value); } /// <summary> /// A color that passes accessibility guidelines for text/iconography when drawn on top of <see cref="Surface"/> /// </summary> public Color OnSurface { get => (Color)this.GetValue(OnSurfaceProperty); set => this.SetValue(OnSurfaceProperty, value); } /// <summary> /// Displayed most frequently across your app. /// </summary> public Color Primary { get => (Color)this.GetValue(PrimaryProperty); set => this.SetValue(PrimaryProperty, value); } /// <summary> /// A tonal variation of <see cref="Primary"/>. /// </summary> public Color PrimaryVariant { get => (Color)this.GetValue(PrimaryVariantProperty); set => this.SetValue(PrimaryVariantProperty, value); } /// <summary> /// Accents select parts of your UI. /// If not provided, use <see cref="Primary"/>. /// </summary> public Color Secondary { get { var color = (Color)this.GetValue(SecondaryProperty); if(color.IsDefault && this.Primary.IsDefault) { return Color.Accent; } return color.IsDefault ? this.Primary : color; } set => this.SetValue(SecondaryProperty, value); } /// <summary> /// A tonal variation of <see cref="Secondary"/>. /// </summary> public Color SecondaryVariant { get => (Color)this.GetValue(SecondaryVariantProperty); set => this.SetValue(SecondaryVariantProperty, value); } /// <summary> /// The color of surfaces such as cards, sheets, menus. /// </summary> public Color Surface { get => (Color)this.GetValue(SurfaceProperty); set => this.SetValue(SurfaceProperty, value); } } }
Python
UTF-8
6,332
3.34375
3
[]
no_license
#!/usr/bin/env python3.6 from account import Account#Importing the account class from credential import Credential#Importing the credential class def create_account(users_name,password): ''' Function to create a new account ''' new_account =Account(users_name,password) return new_account def save_accounts(account): ''' Function to save account ''' account.save_account() def display_accounts(): ''' Function that returns all the saved accounts ''' return Account.display_accounts() def del_account(account): ''' Function to delete a account ''' account.delete_account() def login_account(users_name,password): """ login_account method to check a user and then sign in they exist """ check_account = Account.login_account(users_name,password) return check_account def create_credential(account_name,user_name,password): ''' Function to create a new credential ''' new_credential = Credential(account_name,user_name,password) return new_credential def save_credentials(credential): ''' Function to save credential ''' credential.save_credential() def display_credentials(): ''' Function that returns all the saved credentials ''' return Credential.display_credentials() def del_credentials(credential): ''' Function that to delete a credential ''' return Credential.delete_credentials() def main(): print("&"*80) while True: print("Use these short codes :\n cc - create a new account, \n dd - display accounts,\nlg- login your account") short_code = input().lower() if short_code == 'cc': print("New Account") print("-"*10) print ("User name ....") users_name = input() print(" password ...") password= input() save_accounts(create_account(users_name,password)) # create and save new account. print ('\n') print(f"New Account {users_name} {password} created") print ('\n') elif short_code == 'dd': if display_accounts(): print("Here is a list of all your accounts") print('\n') for account in display_accounts(): print(f"Username:{account.users_name} \n Password:{account.password} ") print('\n') else: print('\n') print("You dont seem to have any accounts saved yet") print('\n') elif short_code=='lg': user_name1=input ("users_name:") # login=login_account(users_name,password) if user_name1!= users_name: continue else: print() password1=input ("password:") if password1 !=password : continue else: pass while True: print("Use these short codes : cc - create a new credential, dc - display credentials") short_code = input().lower() if short_code == 'cc': print("New Credential") print("-"*10) print ("Account name ....") account_name = input() print("User name...") user_name = input() print("Password ...") password = input() save_credentials(create_credential(account_name,user_name,password)) # create and save new credential. print ('\n') print(f"New Credential {account_name} {user_name} created") print ('\n') elif short_code == 'dc': if display_credentials(): print("Here is a list of all your credentials") print('\n') for credential in display_credentials(): print(f"Account name:{credential.account_name}\n Username: {credential.user_name}\n Password:{credential.password}") else: print('\n') print("You dont seem to have any credentials saved yet") print('\n') if __name__ == '__main__': main()
TypeScript
UTF-8
814
2.65625
3
[]
no_license
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; @Injectable({ providedIn: 'root' }) export class TaskServiceService { //this file will be used to connect to the API that will provide data to the component tasks: Array<any> = [ {id:1, title: 'SLASH', completed: false}, {id:2, title: 'BURN', completed: false}, {id:3, title: 'KILL', completed: false} ] constructor(private _http: Http) { // console.log(_http); } getTasks(){ //console.log(this._http); } retreveAll(){ return this.tasks; } add(task: any){ this.tasks.push(task); } remove(task: any){ //find given task and remove from tasks } getNote(){ //this._http.get('/notes').map((response: Response) => response.json()) } ngOnInit(){ } }
C++
UTF-8
1,256
3.703125
4
[]
no_license
/* An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. Declaration: int arr[10]; //Declares an array named arr of size 10, i.e; you can store 10 integers. Accessing elements of an array: Indexing in arrays starts from 0.So the first element is stored at arr[0],the second element at arr[1]...arr[9] You'll be given an array of N integers and you have to print the integers in the reverse order. Input Format The first line of the input contains N,where N is the number of integers.The next line contains N integers separated by a space. Constraints 1<= N <= 1000 1<= Ai <= 10000 where Ai is the ith integer in the array. Output Format Print the N integers of the array in the reverse order in a single line separated by a space. */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #define MAX 10000 using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int a[MAX], N,i; cin>>N; for(i=1;i<=N;i++) { cin>>a[i]; } for(i=0;i<N;i++) { cout<<a[N-i]<<" "; } return 0; }
Ruby
UTF-8
6,121
2.609375
3
[]
no_license
require 'rails_helper' RSpec.shared_examples 'removes various common terms from the end of company name' do |term| it "Removes variations of #{term} from the end of company name" do parser = ApiParser::GoogleJSON.new(query: "test query, #{term.upcase}.") expect(parser.query).to eql('test query') parser = ApiParser::GoogleJSON.new(query: "test query #{term.downcase}.") expect(parser.query).to eql('test query') parser = ApiParser::GoogleJSON.new(query: "test query #{term.titleize}") expect(parser.query).to eql('test query') parser = ApiParser::GoogleJSON.new(query: "#{term.titleize} test query") expect(parser.query).to eql("#{term.titleize} test query") end end RSpec.describe ApiParser::GoogleJSON do it_should_behave_like 'removes various common terms from the end of company name', 'inc' it_should_behave_like 'removes various common terms from the end of company name', 'llc' it_should_behave_like 'removes various common terms from the end of company name', 'corp' describe '#pages_total' do it 'returns an accurate page count for results_total not divisible by RESULTS_PER_PAGE' do results_total = ApiParser::GoogleJSON::RESULTS_PER_PAGE + 1 allow_any_instance_of(ApiParser::GoogleJSON).to receive(:results_total).and_return(results_total) parser = ApiParser::GoogleJSON.new(query: 'test query') expect(parser.pages_total).to eql(2) end it 'returns an accurate page count for results_total divisible by RESULTS_PER_PAGE' do results_total = ApiParser::GoogleJSON::RESULTS_PER_PAGE allow_any_instance_of(ApiParser::GoogleJSON).to receive(:results_total).and_return(results_total) parser = ApiParser::GoogleJSON.new(query: 'test query') expect(parser.pages_total).to eql(1) end end context 'private methods' do let(:query) { 'test company' } let(:parser) { ApiParser::GoogleJSON.new(query: query) } let(:y2k_timestamp) { '1999-12-31 12:59:59' } let(:y2k) { Time.parse(y2k_timestamp) } let(:empty_result) do { 'pagemap' => {}, 'snippet' => '' } end describe '#parse_date' do it 'parses metatags from the result' do allow(parser).to receive(:parse_date_from_metatags).and_return(y2k) expect(parser.send(:parse_date, empty_result)).to eql(y2k) end it 'parses offset from words when metatags are fruitless' do allow(parser).to receive(:parse_date_from_metatags).and_return(nil) allow(parser).to receive(:parse_offset_from_words).and_return(y2k) expect(parser.send(:parse_date, empty_result)).to eql(y2k) end it 'parses time from words when no offset' do allow(parser).to receive(:parse_date_from_metatags).and_return(nil) allow(parser).to receive(:parse_offset_from_words).and_return(nil) result = empty_result result['snippet'] = "#{y2k_timestamp} ... Some story a long time ago ..." expect(parser.send(:parse_date, result)).to eql(y2k) end it 'returns now as a last resort' do allow(parser).to receive(:parse_date_from_metatags).and_return(nil) allow(parser).to receive(:parse_offset_from_words).and_return(nil) allow(Time).to receive(:now).and_return(y2k) expect(parser.send(:parse_date, empty_result)).to eql(y2k) end end describe '#parse_date_from_metatags' do it 'returns nil when metatags is nil' do expect(parser.send(:parse_date_from_metatags, nil)).to be_nil end it 'parses for pubdate' do metatags = { 'pubdate' => y2k_timestamp, 'revision_date' => nil } expect(parser.send(:parse_date_from_metatags, metatags)).to eql(y2k) end it 'parses for revision_date when pubdate fails' do metatags = { 'pubdate' => nil, 'revision_date' => y2k_timestamp } expect(parser.send(:parse_date_from_metatags, metatags)).to eql(y2k) end it 'returns nil when both revision_date and pubdate fail' do metatags = { 'pubdate' => nil, 'revision_date' => nil } expect(parser.send(:parse_date_from_metatags, metatags)).to be_nil end end describe '#parse_offset_from_words' do it 'returns nil if words arent formatted properly' do words = 'something improper' expect(parser.send(:parse_offset_from_words, words)).to be_nil end it 'returns nil if count is 0' do words = '0 days ago ... a story four days ago ...' expect(parser.send(:parse_offset_from_words, words)).to be_nil end it 'returns nil if count is numeric but units is invalid' do words = '12 parsecs away ... a story four days ago ...' expect(parser.send(:parse_offset_from_words, words)).to be_nil end it 'returns the correct time if words are formatted properly' do now = Time.now expected = now - 4.days allow(Time).to receive(:now).and_return(now) words = '4 days ago ... a story four days ago ...' expect(parser.send(:parse_offset_from_words, words)).to eql(expected) end end describe 'parse_meta' do it 'returns nil if searchInformation is empty' do meta = { 'searchInformation' => nil } allow(parser).to receive(:raw_feed_json).and_return meta expect(parser.send(:parse_meta)).to be_nil end context 'valid meta' do let!(:valid_meta) do { 'searchInformation' => { 'totalResults' => 123_456, 'searchTime' => 1.21 } } end before do allow(parser).to receive(:raw_feed_json).and_return valid_meta parser.send(:parse_meta) end it 'sets results_total' do expect(parser.instance_variable_get(:@results_total)).not_to be_nil end it 'sets results_time' do expect(parser.instance_variable_get(:@results_time)).not_to be_nil end end end end end
Java
UTF-8
770
1.773438
2
[]
no_license
package com.archives.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.archives.pojo.Docborrowdetail; public interface DocborrowdetailDao { int deleteByPrimaryKey(Integer guid); int insert(Docborrowdetail record); int insertSelective(Docborrowdetail record); Docborrowdetail selectByPrimaryKey(Integer guid); int updateByPrimaryKeySelective(Docborrowdetail record); int updateByPrimaryKey(Docborrowdetail record); public List selectByBorrowId(String borrowId); public List<Docborrowdetail> findDocborrowdetailForPage(@Param("paraMap") Map paraMap); public int findCountDocborrowdetailForPage(@Param("paraMap") Map paraMap); public int selectListTail(int borrowId); }
Java
UTF-8
1,352
2.453125
2
[]
no_license
import java.awt.AWTException; import java.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class img extends message { private BufferedImage img; public img() { // TODO Auto-generated constructor stub } public img(BufferedImage img) { this.img=img; } public img(String path) throws Exception{ img= ImageIO.read(new File(path)); } public BufferedImage getImg() { return img; } public void setImg(BufferedImage img) { this.img = img; } static BufferedImage takess() throws Exception{ return new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); } /*public static void main(String[] args){ JFrame frame = new JFrame(); frame.getContentPane().setLayout(new FlowLayout()); try { frame.getContentPane().add(new JLabel(new ImageIcon(takess()))); } catch (HeadlessException e) { e.printStackTrace(); } catch (AWTException e) { e.printStackTrace(); } frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }*/ }
C#
UTF-8
3,213
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "LGPL-3.0-only", "MIT" ]
permissive
using Ryujinx.Graphics.GAL.Multithreading.Resources.Programs; using System; using System.Collections.Generic; using System.Threading; namespace Ryujinx.Graphics.GAL.Multithreading.Resources { /// <summary> /// A structure handling multithreaded compilation for programs. /// </summary> class ProgramQueue { private const int MaxConcurrentCompilations = 8; private readonly IRenderer _renderer; private readonly Queue<IProgramRequest> _toCompile; private readonly List<ThreadedProgram> _inProgress; public ProgramQueue(IRenderer renderer) { _renderer = renderer; _toCompile = new Queue<IProgramRequest>(); _inProgress = new List<ThreadedProgram>(); } public void Add(IProgramRequest request) { lock (_toCompile) { _toCompile.Enqueue(request); } } public void ProcessQueue() { for (int i = 0; i < _inProgress.Count; i++) { ThreadedProgram program = _inProgress[i]; ProgramLinkStatus status = program.Base.CheckProgramLink(false); if (status != ProgramLinkStatus.Incomplete) { program.Compiled = true; _inProgress.RemoveAt(i--); } } int freeSpace = MaxConcurrentCompilations - _inProgress.Count; for (int i = 0; i < freeSpace; i++) { // Begin compilation of some programs in the compile queue. IProgramRequest program; lock (_toCompile) { if (!_toCompile.TryDequeue(out program)) { break; } } if (program.Threaded.Base != null) { ProgramLinkStatus status = program.Threaded.Base.CheckProgramLink(false); if (status != ProgramLinkStatus.Incomplete) { // This program is already compiled. Keep going through the queue. program.Threaded.Compiled = true; i--; continue; } } else { program.Threaded.Base = program.Create(_renderer); } _inProgress.Add(program.Threaded); } } /// <summary> /// Process the queue until the given program has finished compiling. /// This will begin compilation of other programs on the queue as well. /// </summary> /// <param name="program">The program to wait for</param> public void WaitForProgram(ThreadedProgram program) { Span<SpinWait> spinWait = stackalloc SpinWait[1]; while (!program.Compiled) { ProcessQueue(); if (!program.Compiled) { spinWait[0].SpinOnce(-1); } } } } }
Java
UTF-8
389
2.34375
2
[ "Apache-2.0" ]
permissive
package io.semla.reflect; import java.lang.reflect.Type; import static io.semla.reflect.Types.rawTypeOf; import static io.semla.reflect.Types.typeArgumentOf; public abstract class TypeReference<E> { public Type getType() { return typeArgumentOf(this.getClass().getGenericSuperclass()); } public Class<E> getRawType() { return rawTypeOf(getType()); } }
Shell
UTF-8
22,986
3.296875
3
[ "BSD-2-Clause" ]
permissive
#!/bin/sh # # Part of XigmaNAS (https://www.xigmanas.com). # Copyright (c) 2018-2019 XigmaNAS <info@xigmanas.com>. # All rights reserved. # # samba service # # PROVIDE: nmbd smbd winbindd # REQUIRE: NETWORKING SERVERS DAEMON resolv # BEFORE: LOGIN # KEYWORD: shutdown # XQUERY: --if "count(//samba/enable) > 0" --output "0" --else --output "1" --break # RCVAR: samba . /etc/rc.subr . /etc/configxml.subr . /etc/util.subr name="samba" desc="samba service" rcvar=samba_enable load_rc_config "${name}" # Custom commands extra_commands="reload status mkconf" start_precmd="samba_start_precmd" start_cmd="samba_cmd" stop_cmd="samba_cmd" status_cmd="samba_cmd" reload_cmd="samba_reload_cmd" rcvar_cmd="samba_rcvar_cmd" mkconf_cmd="samba_mkconf_cmd" # Defaults samba_enable="${samba_enable:=NO}" samba_config_default="/var/etc/smb4.conf" samba_config="${samba_config:-${samba_config_default}}" command_args="${samba_config:+-s "${samba_config}"}" samba_daemons="nmbd smbd winbindd" smbcontrol_command="/usr/local/bin/smbcontrol" samba_logdir="${samba_logdir:-/var/log/samba4}" samba_lockdir="${samba_lockdir:-/var/db/samba4}" samba_piddir="${samba_piddir=/var/run/samba4}" samba_recycle_repository="${samba_recycle_repository:-".recycle/%U"}" samba_recycle_directory_mode="${samba_recycle_directory_mode:-"0777"}" samba_recycle_subdir_mode="${samba_recycle_subdir_mode:-"0700"}" samba_idmap_range="${samba_idmap_range:-"10000-39999"}" samba_idmap_uid="${samba_idmap_uid:-"10000-39999"}" samba_idmap_gid="${samba_idmap_gid:-"10000-39999"}" samba_socket_options="${samba_socket_options:-"TCP_NODELAY IPTOS_LOWDELAY"}" samba_create_mask="${samba_create_mask:-"0666"}" samba_directory_mask="${samba_directory_mask:-"0777"}" # Check if 'Active Directory' is enabled? configxml_isset //ad/enable samba_idmap=$? # Check if 'LDAP' is enabled? configxml_isset //ldap/enable samba_ldap=$? # Disable AD if LDAP enabled: if [ 0 -eq ${samba_ldap} ]; then samba_idmap=1 fi # Check Samba AD configxml_isset //sambaad/enable sambaad=$? if [ 0 -eq ${sambaad} ]; then samba_daemons="samba" mkconf_cmd="sambaad_mkconf_cmd" fi # Create required directories. [ ! -d "${samba_piddir}" ] && mkdir "${samba_piddir}" [ ! -d "${samba_logdir}" ] && mkdir "${samba_logdir}" [ ! -d "${samba_lockdir}" ] && mkdir "${samba_lockdir}" [ ! -d "${samba_lockdir}/private" ] && mkdir "${samba_lockdir}/private" # Setup dependent variables if [ -n "${rcvar}" ] && checkyesno "${rcvar}"; then nmbd_enable="${nmbd_enable=YES}" smbd_enable="${smbd_enable=YES}" # Check that winbindd is actually configured if [ 0 -eq ${samba_idmap} ]; then winbindd_enable="${winbindd_enable=YES}" fi fi # Hack to work around name change of pid file with non-default config pid_extra= if [ -n "${samba_config}" -a "${samba_config}" != "${samba_config_default}" ]; then pid_extra="-$(basename "${samba_config}")" fi # Hack to enable check of dependent variables eval real_${rcvar}="\${${rcvar}:=NO}" ${rcvar}="YES" # Defaults for dependent variables nmbd_enable="${nmbd_enable:=NO}" nmbd_flags="${nmbd_flags=\"-D\"}" smbd_enable="${smbd_enable:=NO}" smbd_flags="${smbd_flags=\"-D\"}" winbindd_enable="${winbindd_enable:=NO}" winbindd_flags="${winbindd_flags=''}" # Requirements required_files="${samba_config}" required_dirs="${samba_lockdir}" samba_mkconf_user_shares() { /usr/local/bin/xml sel --template \ --match '//samba/share' \ --if 'string-length(name) > 0' \ --value-of 'concat("[",name,"]")' --nl \ --if 'string-length(comment) > 0' \ --value-of 'concat("comment = ",comment)' --nl \ --break \ --if 'string-length(path) > 0' \ --value-of 'concat("path = ",path)' --nl \ --break \ --if 'count(readonly) = 0' \ --output 'writeable = yes' --nl \ --break \ --output 'printable = no' --nl \ --output 'veto files = /.snap/.sujournal/' --nl \ --if 'count(hidedotfiles) > 0' \ --output 'hide dot files = yes' --nl \ --else \ --output 'hide dot files = no' --nl \ --break \ --if '//samba/security[. = "share"]' \ --output 'guest ok = yes' --nl \ --elif 'count(guest) > 0' \ --output 'guest ok = yes' --nl \ --else \ --output 'guest ok = no' --nl \ --break \ --if 'count(browseable) = 0' \ --output 'browseable = no' --nl \ --break \ --if 'count(inheritpermissions) > 0' \ --output 'inherit permissions = yes' --nl \ --break \ --if 'count(inheritacls) > 0' \ --output 'inherit acls = yes' --nl \ --break \ --output 'vfs objects =' \ --if 'count(shadowcopy) > 0' \ --output ' shadow_copy2' \ --break \ --if 'count(zfs_space) > 0' \ --output ' zfs_space' \ --break \ --if 'count(zfsacl) > 0' \ --output ' zfsacl' \ --break \ --if 'count(afpcompat) > 0' \ --output ' catia' \ --break \ --if 'count(afpcompat) > 0' \ --output ' fruit' \ --break \ --if 'count(storealternatedatastreams) > 0 or count(afpcompat) > 0' \ --output ' streams_xattr' \ --break \ --if 'count(storentfsacls) > 0' \ --output ' acl_xattr' \ --break \ --if 'count(recyclebin) > 0' \ --output ' recycle' \ --break \ --if 'count(//samba/aio) > 0' \ --output ' aio_pthread' \ --break \ --nl \ --if 'count(zfsacl) > 0' \ --output 'nfs4:mode = special' --nl \ --output 'nfs4:acedup = merge' --nl \ --output 'nfs4:chown = yes' --nl \ --break \ --if 'count(recyclebin) > 0' \ --output "recycle:repository = ${samba_recycle_repository}" --nl \ --output 'recycle:keeptree = yes' --nl \ --output 'recycle:versions = yes' --nl \ --output 'recycle:touch = yes' --nl \ --output "recycle:directory_mode = ${samba_recycle_directory_mode}" --nl \ --output "recycle:subdir_mode = ${samba_recycle_subdir_mode}" --nl \ --break \ --if 'count(shadowcopy) > 0' \ --if 'string-length(shadowformat) > 0' \ --value-of 'concat("shadow:format = ", shadowformat)' --nl \ --break \ --output 'shadow:snapdir = .zfs/snapshot' --nl \ --output 'shadow:snapdirseverywhere = yes' --nl \ --output 'shadow:sort = desc' --nl \ --output 'shadow:localtime = yes' --nl \ --break \ --if 'count(zfsacl) > 0' \ --output 'veto files = /.zfs/' --nl \ --break \ --if 'count(afpcompat) > 0' \ --if 'string-length(vfs_fruit_resource) > 0' \ --value-of 'concat("fruit:resource = ",vfs_fruit_resource)' --nl \ --else \ --output 'fruit:resource = file' --nl \ --break \ --if 'string-length(vfs_fruit_metadata) > 0' \ --value-of 'concat("fruit:metadata = ",vfs_fruit_metadata)' --nl \ --else \ --output 'fruit:metadata = netatalk' --nl \ --break \ --if 'string-length(vfs_fruit_locking) > 0' \ --value-of 'concat("fruit:locking = ",vfs_fruit_locking)' --nl \ --else \ --output 'fruit:locking = netatalk' --nl \ --break \ --if 'string-length(vfs_fruit_encoding) > 0' \ --value-of 'concat("fruit:encoding = ",vfs_fruit_encoding)' --nl \ --else \ --output 'fruit:encoding = native' --nl \ --break \ --if 'string-length(vfs_fruit_time_machine) > 0' \ --value-of 'concat("fruit:time machine = ",vfs_fruit_time_machine)' --nl \ --break \ --break \ --if 'string-length(hostsallow) > 0' \ --value-of 'concat("hosts allow = ",hostsallow)' --nl \ --break \ --if 'string-length(hostsdeny) > 0' \ --value-of 'concat("hosts deny = ",hostsdeny)' --nl \ --break \ --match 'auxparam' \ --value-of '.' --nl \ --break \ --nl \ --break \ --break \ ${configxml_file} | /usr/local/bin/xml unesc >> ${samba_config} } samba_mkconf_cmd() { # Create smb4.conf file /usr/local/bin/xml sel --template \ --output "[global]" --nl \ --output "server role = standalone" --nl \ --output "encrypt passwords = yes" --nl \ --if 'string-length(//samba/netbiosname) > 0' \ --value-of "concat('netbios name = ',//samba/netbiosname)" --nl \ --break \ --if 'string-length(//samba/workgroup) > 0' \ --value-of "concat('workgroup = ',//samba/workgroup)" --nl \ --break \ --if 'string-length(//samba/serverdesc) > 0' \ --value-of "concat('server string = ',//samba/serverdesc)" --nl \ --break \ --if 'string-length(//samba/security) > 0' \ --value-of "concat('security = ',//samba/security)" --nl \ --break \ --if "string-length(//samba/maxprotocol) > 0" \ --value-of "concat('server max protocol = ',//samba/maxprotocol)" --nl \ --break \ --if "string-length(//samba/minprotocol) > 0" \ --value-of "concat('server min protocol = ',//samba/minprotocol)" --nl \ --break \ --if "string-length(//samba/clientmaxprotocol) > 0" \ --value-of "concat('client max protocol = ',//samba/clientmaxprotocol)" --nl \ --break \ --if "string-length(//samba/clientminprotocol) > 0" \ --value-of "concat('client min protocol = ',//samba/clientminprotocol)" --nl \ --break \ --output 'dns proxy = no' --nl \ --output '# Settings to enhance performance:' --nl \ --output 'strict locking = no' --nl \ --output 'read raw = yes' --nl \ --output 'write raw = yes' --nl \ --output 'oplocks = yes' --nl \ --output 'max xmit = 65536' --nl \ --output 'deadtime = 15' --nl \ --output 'getwd cache = yes' --nl \ --output "socket options = ${samba_socket_options}" \ --output ' SO_SNDBUF=' \ --if 'string-length(//samba/sndbuf) > 0' \ --value-of '//samba/sndbuf' \ --else \ --output '65536' \ --break \ --output ' SO_RCVBUF=' \ --if 'string-length(//samba/rcvbuf) > 0' \ --value-of '//samba/rcvbuf' \ --else \ --output '65536' \ --break \ --nl \ --output '# End of performance section' --nl \ --if 'string-length(//samba/pwdsrv) > 0' \ --value-of "concat('password server = ',//samba/pwdsrv)" --nl \ --break \ --if 'string-length(//samba/winssrv) > 0' \ --value-of "concat('wins server = ',//samba/winssrv)" --nl \ --break \ --if 'string-length(//samba/unixcharset) > 0' \ --value-of "concat('unix charset = ',//samba/unixcharset)" --nl \ --break \ --if "string-length(//samba/unixcharset) = 0" \ --output "unix charset = UTF-8" --nl \ --break \ --if "count(//samba/largereadwrite) = 0" \ --output "large readwrite = no" --nl \ --break \ --if "count(//samba/easupport) > 0" \ --output "ea support = yes" --nl \ --break \ --if "count(//samba/storedosattributes) > 0" \ --output "store dos attributes = yes" --nl \ --break \ --if "count(//samba/storedosattributes) = 0 and count(//samba/mapdosattributes) > 0" \ --output 'create mask = 0755' --nl \ --output 'map hidden = yes' --nl \ --output 'map system = yes' --nl \ --break \ --if '//samba/localmaster[. = "yes"]' \ --output 'local master = yes' --nl \ --output 'domain master = yes' --nl \ --output 'preferred master = yes' --nl \ --output 'os level = 35' --nl \ --elif '//samba/localmaster[. = "no"]' \ --output 'local master = no' --nl \ --output 'domain master = no' --nl \ --output 'preferred master = no' --nl \ --output 'os level = 0' --nl \ --break \ --if 'string-length(//samba/timesrv) > 0' \ --value-of "concat('time server = ',//samba/timesrv)" --nl \ --break \ --if 'string-length(//samba/guestaccount) > 0' \ --value-of 'concat("guest account = ",//samba/guestaccount)' --nl \ --else \ --output 'guest account = ftp' --nl \ --break \ --if 'string-length(//samba/maptoguest) > 0' \ --value-of "concat('map to guest = ',//samba/maptoguest)" --nl \ --break \ --if 'count(//samba/nullpasswords) > 0' \ --output 'null passwords = yes' --nl \ --break \ --output 'max log size = 100' --nl \ --output 'logging = syslog' --nl \ --if 'string-length(//samba/loglevel) > 0' \ --value-of 'concat("loglevel = ",//samba/loglevel)' --nl \ --break \ --output 'load printers = no' --nl \ --output 'printing = bsd' --nl \ --output 'printcap cache time = 0' --nl \ --output 'printcap name = /dev/null' --nl \ --output 'disable spoolss = yes' --nl \ --if 'string-length(//samba/doscharset) > 0' \ --value-of "concat('dos charset = ',//samba/doscharset)" --nl \ --break \ --output "smb passwd file = /var/etc/private/smbpasswd" --nl \ --output "private dir = /var/etc/private" --nl \ --if '//samba/security[. = "ads"]' \ --output "passdb backend = tdbsam" --nl \ --if "count(//samba/trusteddomains) > 0" \ --output "allow trusted domains = yes" --nl \ --break \ --if "count(//samba/trusteddomains) = 0" \ --output "allow trusted domains = no" --nl \ --break \ --output "idmap config * : backend = tdb" --nl \ --output "idmap config * : range = ${samba_idmap_range}" --nl \ --if 'string-length(//ad/domainname_netbios) > 0' \ --value-of "concat('idmap config ',//ad/domainname_netbios,' : backend = rid')" --nl \ --value-of "concat('idmap config ',//ad/domainname_netbios,' : range = ${samba_idmap_range}')" --nl \ --break \ --if 'string-length(//ad/domainname_dns) > 0' \ --value-of "concat('realm = ',//ad/domainname_dns)" --nl \ --break \ --output 'winbind enum users = yes' --nl \ --output 'winbind enum groups = yes' --nl \ --output 'winbind use default domain = yes' --nl \ --output 'winbind normalize names = yes' --nl \ --output 'template homedir = /mnt' --nl \ --output 'template shell = /bin/sh' --nl \ --elif '//samba/security[. = "user"]' \ --if 'count(//ldap/enable) > 0' \ --if 'string-length(//ldap/hostname) > 0' \ --value-of "concat('passdb backend = ldapsam:\"',//ldap/hostname,'\"')" --nl \ --break \ --if 'string-length(//ldap/rootbinddn) > 0' \ --value-of "concat('ldap admin dn = ',//ldap/rootbinddn)" --nl \ --break \ --if 'string-length(//ldap/base) > 0' \ --value-of "concat('ldap suffix = ',//ldap/base)" --nl \ --break \ --if 'string-length(//ldap/user_suffix) > 0' \ --value-of "concat('ldap user suffix = ',//ldap/user_suffix)" --nl \ --break \ --if 'string-length(//ldap/group_suffix) > 0' \ --value-of "concat('ldap group suffix = ',//ldap/group_suffix)" --nl \ --break \ --if 'string-length(//ldap/machine_suffix) > 0 ' \ --value-of "concat('ldap machine suffix = ',//ldap/machine_suffix)" --nl \ --break \ --output 'ldap replication sleep = 1000' --nl \ --output 'ldap passwd sync = yes' --nl \ --output 'ldap ssl = no' --nl \ --output 'ldapsam:trusted = yes' --nl \ --output 'idmap config * : backend = tdb' --nl \ --output "idmap config * : range = ${samba_idmap_range}" --nl \ --else \ --output 'passdb backend = tdbsam' --nl \ --output 'idmap config * : backend = tdb' --nl \ --output "idmap config * : range = ${samba_idmap_range}" --nl \ --break \ --break \ --if 'count(//samba/aio) > 0' \ --if 'string-length(//samba/aiorsize) > 0' \ --value-of "concat('aio read size = ',//samba/aiorsize)" --nl \ --break \ --if 'string-length(//samba/aiowsize) > 0' \ --value-of "concat('aio write size = ',//samba/aiowsize)" --nl \ --break \ --break \ --if "//samba/if[. = 'lan']" \ --output 'bind interfaces only = yes' --nl \ --output 'interfaces =' \ --match '//interfaces/lan/if' \ --if 'string-length() > 0' \ --output ' ' \ --value-of '.' \ --break \ --break \ --nl \ --elif "//samba/if[. = 'opt']" \ --output 'bind interfaces only = yes' --nl \ --output 'interfaces =' \ --match "//interfaces/*[contains(name(),'opt')]/if" \ --if 'string-length() > 0' \ --output ' ' \ --value-of '.' \ --break \ --break \ --nl \ --elif "//samba/if[. = 'carp']" \ --output 'bind interfaces only = yes' --nl \ --output 'interfaces =' \ --match '//vinterfaces/carp/if' \ --if 'string-length() > 0' \ --output ' ' \ --value-of '.' \ --break \ --break \ --nl \ --break \ --match '//samba/auxparam' \ --value-of '.' --nl \ --break \ --nl \ ${configxml_file} | /usr/local/bin/xml unesc > ${samba_config} samba_mkconf_user_shares } sambaad_mkconf_cmd() { local _dns_domain _netbios_domain _path _hostname _realm _domain _name _dns_domain=`configxml_get "//sambaad/dns_domain"` _netbios_domain=`configxml_get "//sambaad/netbios_domain"` _path=`configxml_get "//sambaad/path"` _hostname=`configxml_get "//system/hostname"` _realm=`echo ${_dns_domain} | tr '[:lower:]' '[:upper:]'` _domain=`echo ${_netbios_domain} | tr '[:lower:]' '[:upper:]'` _name=`echo ${_hostname} | tr '[:lower:]' '[:upper:]'` # Create smb4.conf file /usr/local/bin/xml sel -t \ --output "[global]" --nl \ --output "server role = active directory domain controller" --nl \ --output "workgroup = ${_domain}" --nl \ --output "realm = ${_realm}" --nl \ --output "netbios name = ${_name}" --nl \ --output "cache directory = ${_path}" --nl \ --output "lock directory = ${_path}" --nl \ --output "state directory = ${_path}" --nl \ --output "private dir = ${_path}/private" --nl \ --output "smb passwd file = ${_path}/private/smbpasswd" --nl \ --output "usershare path = ${_path}/usershares" --nl \ --if 'string-length(//sambaad/dns_forwarder) > 0' \ --value-of "concat('dns forwarder = ',//sambaad/dns_forwarder)" --nl \ --break \ --output "idmap_ldb:use rfc2307 = yes" --nl \ --output "nsupdate command = /usr/local/bin/samba-nsupdate -g" --nl \ --nl \ --match "//sambaad/auxparam" \ --value-of '.' --nl \ --break \ --nl \ --output "[netlogon]" --nl \ --output "path = ${_path}/sysvol/${_dns_domain}/scripts" --nl \ --output "read only = No" --nl \ --nl \ --output '[sysvol]' --nl \ --output "path = ${_path}/sysvol" --nl \ --output 'read only = No' --nl \ ${configxml_file} | /usr/local/bin/xml unesc > ${samba_config} # Append shares to smb4.conf configxml_isset //sambaad/user_shares user_share=$? if [ 0 -eq $user_share ]; then samba_mkconf_user_shares fi } sambaad_resolv() { # Update resolv.conf for AD DC _ipaddress=`configxml_get "//interfaces/lan/ipaddr"` if [ "dhcp" != "${_ipaddress}" ]; then #echo "Updating resolv.conf." # Set the domain, IP4 and IP6 DNS servers. /usr/local/bin/xml sel --template \ --output 'domain ' \ --value-of '//system/domain' \ --nl \ --match "//system/dnsserver" \ --if "string-length() > 0" \ --output 'nameserver ' \ --value-of '.' \ --nl \ --break \ --break \ --if "count(//interfaces/*[enable]/ipv6_enable) > 0" \ --match "//system/ipv6dnsserver" \ --if "string-length() > 0" \ --output 'nameserver ' \ --value-of '.' \ --nl \ --break \ --break \ --break \ ${configxml_file} | /usr/local/bin/xml unesc > /etc/resolv.conf fi } samba_start_precmd() { # XXX: Never delete winbindd_idmap, winbindd_cache and group_mapping if [ -n "${samba_lockdir}" -a -d "${samba_lockdir}" ]; then echo -n "Removing stale Samba tdb files: " for file in brlock.tdb browse.dat connections.tdb gencache.tdb \ locking.tdb messages.tdb namelist.debug sessionid.tdb \ unexpected.tdb do rm "${samba_lockdir}/${file}" </dev/null 2>/dev/null && echo -n '.' done echo " done" fi # AIO module check if configxml_isset //samba/aio; then if ! /sbin/kldstat -q -m aio; then echo "Load AIO module" /sbin/kldload aio.ko fi fi } samba_rcvar_cmd() { local name rcvar rcvar=${name}_enable # Prevent recursive calling unset "${rc_arg}_cmd" "${rc_arg}_precmd" "${rc_arg}_postcmd" # Check master variable echo "# ${name}" if [ -n "${rcvar}" ]; then # Use original configured value if checkyesno "real_${rcvar}"; then echo "\$${rcvar}=YES" else echo "\$${rcvar}=NO" fi fi # Check dependent variables samba_cmd "${_rc_prefix}${rc_arg}" ${rc_extra_args} } samba_reload_cmd() { local name rcvar command pidfile local _enable _role _enable=`configxml_get_count "//hast/enable"` _role=`get_hast_role` if [ "$_enable" != "0" -a "$_role" != "primary" -a "$_rc_prefix" != "force" ]; then return 0; fi # Prevent recursive calling unset "${rc_arg}_cmd" "${rc_arg}_precmd" "${rc_arg}_postcmd" # Apply to all daemons for name in ${samba_daemons}; do rcvar=${name}_enable command="/usr/local/sbin/${name}" pidfile="${samba_piddir}/${name}${pid_extra}.pid" # Daemon should be enabled and running if [ -n "${rcvar}" ] && checkyesno "${rcvar}"; then if [ -n "$(check_pidfile "${pidfile}" "${command}")" ]; then debug "reloading ${name} configuration" echo "Reloading ${name}." # XXX: Hack with pid_extra if [ "$name" != "samba" ]; then ${smbcontrol_command} "${name}${pid_extra}" 'reload-config' ${command_args} >/dev/null 2>&1 fi fi fi done } safe_shellquote() { local _result # replace inside quote &<>| => \X, ' => '\'' #_result=`echo "$@" | sed -e "s/\([\&\<\>\|]\)/\\\\\\\\\1/g" -e "s/'/'\\\\\\''/g"` _result=`echo "$@" | sed -e 's/"/"\\\\\\\\\\\\""/g'` # return quoted string echo "${_result}" } samba_cmd() { local name rcvar command pidfile samba_daemons all_status local _enable _role _enable=`configxml_get_count "//hast/enable"` _role=`get_hast_role` if [ "${rc_arg}" != "status" -a "$_enable" != "0" -a "$_role" != "primary" -a "$_rc_prefix" != "force" ]; then return 0; fi # Prevent recursive calling unset "${rc_arg}_cmd" "${rc_arg}_precmd" "${rc_arg}_postcmd" # Stop processes in the reverse to order if [ "${rc_arg}" = "stop" ]; then samba_daemons=$(reverse_list ${samba_daemons}) fi # Start additional processes when starting if [ "${rc_arg}" = "start" ]; then if [ 0 -eq ${samba_idmap} ]; then local _srvname=`configxml_get "//ad/domaincontrollername"` local _username=`configxml_get "//ad/username"` local _password=`configxml_get "//ad/password"` local _up=`safe_shellquote "${_username}%${_password}"` /usr/local/bin/net rpc join -S ${_srvname} -U "${_up}" fi if [ 0 -eq ${samba_ldap} ]; then local _password=`configxml_get "//ldap/rootbindpw"` local _p=`safe_shellquote "${_password}"` /usr/local/bin/smbpasswd -w "${_p}" fi fi # Create local userdb if [ "${rc_arg}" = "start" ]; then /etc/rc.d/passdb fi # Apply to all daemons all_status=0 for name in ${samba_daemons}; do rcvar=${name}_enable command="/usr/local/sbin/${name}" pidfile="${samba_piddir}/${name}${pid_extra}.pid" # Daemon should be enabled and running if [ -n "${rcvar}" ] && checkyesno "${rcvar}"; then run_rc_command "${_rc_prefix}${rc_arg}" ${rc_extra_args} all_status=1 fi done if [ "${rc_arg}" = "status" ]; then if [ 0 -eq $all_status ]; then # all disabled return 1 fi fi } # Create required config file if [ 0 -eq ${sambaad} ]; then sambaad_mkconf_cmd if [ "${BOOTING}" = "1" ]; then sambaad_resolv fi else samba_mkconf_cmd fi run_rc_command "$1"
C
UTF-8
2,366
3.09375
3
[ "MIT" ]
permissive
// // Buffer.c // PSPL // // Created by Jack Andersen on 5/1/13. // // #define PSPL_INTERNAL #include <string.h> #include <stdlib.h> #include <errno.h> #include "Driver.h" #include <PSPL/PSPLBuffer.h> /* Check buffer capacity (realloc if needed) */ static void pspl_buffer_check_cap(pspl_buffer_t* buf, size_t need_sz) { // Check the current buffer size_t cur_diff = buf->buf_cur - buf->buf; if ((cur_diff+need_sz) > buf->buf_cap) { // Make a larger buffer void* new_buf = realloc(buf->buf, (buf->buf_cap)*2); if (!new_buf) pspl_error(-1, "Unable to reallocate data buffer", "Attempted to reallocate %lu bytes; errno %d: %s", (buf->buf_cap)*2, errno, strerror(errno)); // Update buffer state with larger buffer buf->buf = new_buf; buf->buf_cur = new_buf + cur_diff; } } /* Init a buffer with specified initial capacity */ void pspl_buffer_init(pspl_buffer_t* buf, size_t cap) { buf->buf = malloc(cap); if (!buf->buf) pspl_error(-1, "Unable to allocate data buffer", "Attempted to allocate %zu bytes; errno %d: %s", cap, errno, strerror(errno)); buf->buf_cur = buf->buf; buf->buf_cap = cap; *buf->buf_cur = '\0'; } /* Append a copied string */ void pspl_buffer_addstr(pspl_buffer_t* buf, const char* str) { size_t str_len = strlen(str); if (!str_len) return; pspl_buffer_check_cap(buf, str_len+1); strncpy(buf->buf_cur, str, str_len); buf->buf_cur += str_len; *buf->buf_cur = '\0'; } void pspl_buffer_addstrn(pspl_buffer_t* buf, const char* str, size_t str_len) { # ifndef _WIN32 str_len = strnlen(str, str_len); # endif if (!str_len) return; pspl_buffer_check_cap(buf, str_len+1); strncpy(buf->buf_cur, str, str_len); buf->buf_cur += str_len; *buf->buf_cur = '\0'; } /* Append a single character */ void pspl_buffer_addchar(pspl_buffer_t* buf, char ch) { pspl_buffer_check_cap(buf, 2); *buf->buf_cur = ch; ++buf->buf_cur; *buf->buf_cur = '\0'; } /* Free memory used by the buffer */ void pspl_buffer_free(pspl_buffer_t* buf) { free(buf->buf); buf->buf = NULL; buf->buf_cur = NULL; buf->buf_cap = 0; }
Shell
UTF-8
842
2.890625
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env bash SING_VERSION="v3.0.1" apt-get update && apt-get -y dist-upgrade apt-get install -y build-essential libssl-dev uuid-dev libgpgme11-dev export VERSION=1.11 OS=linux ARCH=amd64 cd /tmp wget https://dl.google.com/go/go$VERSION.$OS-$ARCH.tar.gz tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz echo 'export GOPATH=${HOME}/go' >> ~/.bashrc echo 'export PATH=/usr/local/go/bin:${PATH}:${GOPATH}/bin' >> ~/.bashrc export GOPATH=${HOME}/go export PATH=/usr/local/go/bin:${PATH}:${GOPATH}/bin mkdir -p $GOPATH/src/github.com/sylabs cd $GOPATH/src/github.com/sylabs git clone https://github.com/sylabs/singularity.git git fetch git checkout ${SING_VERSION} cd singularity go get -u github.com/golang/dep/cmd/dep ./mconfig cd ./builddir make && sudo make install cp etc/bash_completion.d/singularity /etc/bash_completion.d/
Java
WINDOWS-1252
896
2.234375
2
[]
no_license
package server; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import enity.UserFriend; import utils.JsonUtil; public class Test { public static void main(String[] args) throws JSONException{ String info = "{\"type\":\"2\",\"id\":\"1471281\",\"password\":\"123456\"}"; String message = "{\"message\":\"\",\"receivers\":[\"1\",\"2\",\"3\"],\"type\":\"3\",\"sender\":\"111\"}"; String test = "{\"receivers\":[{\"id\":\"1\"}]}"; List<UserFriend> userFriends = new ArrayList<UserFriend>(); for(int i = 0; i < 5; i++){ UserFriend userFriend = new UserFriend(); userFriend.setFriendId(i + ""); userFriends.add(userFriend); } JSONObject jsonObject = new JSONObject(userFriends); JSONArray jsonArray = new JSONArray(userFriends); System.out.println(jsonArray); } }
C#
UTF-8
2,534
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.IO; using BasicElements; namespace FirstWindows.View.InitialDialog { /// <summary> /// Interaktionslogik für SpracheWählen.xaml /// </summary> public partial class SpracheWählenWindow : Window { public SpracheWählenWindow(Action continueMeth) { Continue = continueMeth; try { InitializeComponent(); Sprache_Wählen.Text = "Bitte, wählen Sie ihre Sprache\nPor favor, elija su idioma\nPlease choose your language"; } catch (Exception e) { string CurrentDirectory = System.Environment.CurrentDirectory; string Directory = CurrentDirectory.Substring(0, 2); FileStream filest = new FileStream(Directory + "\\Miguel.txt", FileMode.Create); BinaryWriter BinWriter = new BinaryWriter(filest); BinWriter.Seek(0, SeekOrigin.Begin); BinWriter.Write("Sprache Wählen \n Exception: " + e + "\nMessage: " + e.Message + "\nSource: " + e.Source + "\nTarget: " + e.TargetSite + "\nData: " + e.Data); BinWriter.Close(); throw e; } } Action Continue; private void Ok_Click(object sender, RoutedEventArgs e) { byte Byte = 0; switch (ComboboxSprache.Text) { case "English": Byte = Convert.ToByte(BasicElements.Language.English); break; case "Deutsch": Byte = Convert.ToByte(BasicElements.Language.German); break; case "Español": Byte = Convert.ToByte(BasicElements.Language.Spanish); break; } FileStream filest = new FileStream(System.Environment.CurrentDirectory + "\\Daten.dat", FileMode.Open); BinaryWriter BinWriter = new BinaryWriter(filest); BinWriter.Seek(0, SeekOrigin.Begin); BinWriter.Write(Byte); BinWriter.Close(); this.Close(); Continue(); } } }
Python
UTF-8
4,499
3.140625
3
[]
no_license
import os import re import tempfile from argparse import ArgumentParser from datetime import datetime, date, timedelta import pandas as pd import yfinance as yf from google.cloud import storage class YFinanceCollector: name = 'yfinance' columns = [ 'datetime', 'open', 'high', 'low', 'close', 'volume', 'dividends', 'stock_splits' ] def __init__(self, collecting_interval='1m'): self.interval = collecting_interval.lower() def collect(self, ticker: str, date: date) -> pd.DataFrame: start_date = date.strftime('%Y-%m-%d') end_date = (date + timedelta(days=1)).strftime('%Y-%m-%d') data = yf.Ticker(ticker) prices = data.history(start=start_date, end=end_date, interval=self.interval) prices = prices.reset_index() prices.columns = self.columns return prices class Resampler: agg_dict = { 'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'volume': 'sum', 'dividends': 'sum', 'stock_splits': 'sum' } @staticmethod def format_interval(interval: str) -> str: if re.match('^\dM$', interval): return interval.replace('M', 'T') return interval @classmethod def resample(cls, data: pd.DataFrame, interval: str) -> pd.DataFrame: interval = cls.format_interval(interval) df = data.set_index('datetime') df = df.resample(interval).agg(cls.agg_dict) df = df.reset_index() return df class GCSManager: def __init__(self, bucket_name: str): self.bucket_name = bucket_name self.storage_client = storage.Client.from_service_account_json( 'service-key-dinero.json' ) self.bucket = self.storage_client.bucket(bucket_name) def upload(self, data, destination_blob_name): blob = self.bucket.blob(destination_blob_name) blob.upload_from_file(data, content_type='text/csv') class Collector: date_format = '%Y%m%d' filename_format ='{date}.csv' collect_interval = '1M' intervals = ['1M', '5M', '1H', '1D'] def __init__( self, tickers: list, bucket: str, path: str ): self.tickers = tickers self.upload_path = path self.resampler = Resampler() self.data_collector = YFinanceCollector(self.collect_interval) self.data_uploader = GCSManager(bucket) def collect(self, date: date): for ticker in self.tickers: data = self.data_collector.collect(ticker, date) for interval in self.intervals: if interval != self.collect_interval: data = self.resampler.resample(data, interval) self.save_ticker_data(data, date, ticker, interval) def save_ticker_data(self, data, date, ticker, interval): filename = self.filename_format.format( date=date.strftime(self.date_format), ) save_path = f'{self.upload_path}/{ticker}/{interval}/{filename}' print('Saving', date, ticker, interval, save_path, data.shape[0]) self.save(data, save_path) def collect_many(self, dates: list): for date in dates: self.collect(date) def save(self, data, path): with tempfile.NamedTemporaryFile(delete=False) as temp: data.to_csv(temp.name, index=False) self.data_uploader.upload(temp, path) temp.close() os.remove(temp.name) if __name__ == '__main__': parser = ArgumentParser(description='Collector for stock tickers') parser.add_argument( '--tickers', '-t', dest='tickers', required=True, type=str, help='Tickers to be collected in space seperated list form. Ex: AMZN AAPL MSFT' ) parser.add_argument( '--bucket', '-b', dest='bucket', required=True, type=str, help='Bucket to save data in Google Cloud Storage' ) parser.add_argument( '--path', '-p', dest='path', default='dinero-collector/yfinance', type=str, help='Path in bucket where to save data' ) args = parser.parse_args() tickers = args.tickers.split(' ') collector = Collector(tickers, args.bucket, args.path) collector.collect(datetime.now().date() - timedelta(days=1))
C#
UTF-8
1,114
2.828125
3
[]
no_license
using model.Project_Final; using Project_Final.entity; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Web; namespace Project_Final.model { public class NewsDAO : DAL { public List<News> getAllNews() { List<News> list = new List<News>(); string sql = "SELECT [Id] ,[Content] ,[Title] ,[Url] FROM [dbo].[News]"; SqlCommand command = new SqlCommand(sql, connection); command.Connection.Open(); SqlDataReader data = command.ExecuteReader(); if (data.HasRows) { while (data.Read()) { News nt = new News(); nt.ID = Convert.ToInt32(data["Id"].ToString()); nt.Content = data["Content"].ToString(); nt.Title = data["Title"].ToString(); nt.Url = data["Url"].ToString(); list.Add(nt); } } command.Connection.Close(); return list; } } }
Java
UTF-8
356
2.703125
3
[]
no_license
package com.alonsol.demo.design.abstractfactory; public abstract class AbstractFactory { /** * 创建产品A的方法 * @return 产品A对象 */ public abstract AbstractProductA createProductA(); /** * 创建产品B的方法 * @return 产品B对象 */ public abstract AbstractProductB createProductB(); }
Swift
UTF-8
1,423
2.921875
3
[]
no_license
// // Router.swift // SNY // // Created by Thanh-Tam Le on 15/11/2018. // Copyright © 2018 Thanh-Tam Le. All rights reserved. // import UIKit /// RouterType represent the type of router /// In conjunction with Router for handling the flow of whole app appropriately /// /// - mainController: MainController /// - authentication: AuthenticationController enum RouterType { case mainController case authentication } // MARK: - Router // All flow controller will be defined here class AppRouter { // MARK: - Variables // MARK: - Init init() { } // MARK: - Public func initMainWindow() -> UIWindow { let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = handleRouter(type: .mainController) window.makeKeyAndVisible() return window } } // MARK: - Private extension AppRouter { /// Defind the core of router /// /// - Parameter type: RouterType's instance /// - Returns: Desised controller private func handleRouter(type: RouterType) -> UIViewController { switch type { case .mainController: // Get from XIB let controller = UINavigationController(rootViewController: LandingVC()) return controller default: // Didn't support yet return UIViewController() } } }
Markdown
UTF-8
3,006
3.484375
3
[]
no_license
1-31-20 # Lecture 4 - Object-Oriented Design ## Mutable vs Immutable Immutable means that the object can not be changed. A class with private data fields, has no setters, but does have a getter is then mutable. A reference to the object is all you need for it to be mutable. ## Class Abstractions and Encapsulation Class abstraction is seperation of class implementation from the use of a class. It is like a contract between your program and a client. Is a promise to provide some type of service (through methods). These classes are known as **Abstract Data Types** (ADT). ## Stepwise Refinement Begin by using method abstraction to isolate details from design and only later implement the details. Breaking large problems into multiple, small, manageable problems, each subproblem implemented using a single method. ## Class Relationships Common relationships among classes are association, aggregation, composition and inheritance: * Association * A general binary relationship that describes that there is some type of activity (method calling) between the two classes. * **Mulitplicity** can be used to define upper and lower bound of number of entitites that can participate in the activity. * Aggregation and Composition * **Aggregation** is a form of association that representes an ownership relationship between two objects. * **Composition** is a strict form of aggregation, implying exclusive ownership. * If a class A has strict ownership of class B, then if A is deleted so will be B. There are some examples to refer to: * Designing the Course Class * Desgining the Stack Class You want to minimize **coupling** or, *messy association lines*, so that design is not too complicated and so that classes can easily be removed or added without comprimising the design. ## Processing Primitive Data Type Values as Objects Package **java.lang** provides a wrapper for primitive data types to allow them to be passed by reference to an Object. #### Boxing and autoboxing and autounboxing Wrapping the primitive data type as an object is boxing. String is immutable - once created you can not change the value.<br> A char array can be used to instantitate a String object.<br> String literals can also be assigned String variables. String literals will compare by === as true. Though objects instatiated will not. This is because repeated string literals will be saved in the same location. An object instantiated with `new` will always be stored in a new address. StringBuilder allows us to handle more complicated features with String. ## Inheritance 1. Reuse common features 2. Extend functionality (with change in software) ### Superclasses and Subclasses Implementation of generalization of common properties and behaviors of a class. A subclass is used to introduce a new property or behavior. Java enforces single inheritance - no multiple inheritance (The way around this is java Interfaces) In Generalization, white triangle points to superclass
C#
UTF-8
1,496
2.75
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ManagedOT.Buffers.Internal; namespace ManagedOT.Buffers { public class MessageComposer { private const int DefaultExpectedNumberOfComponents = 4; private List<IMessageComponent> _components; private int _length; public MessageComposer() : this(DefaultExpectedNumberOfComponents) { } public MessageComposer(int expectedNumberOfComponents) { _components = new List<IMessageComponent>(expectedNumberOfComponents); _length = 0; } public void Write(byte[] buffer) { AddComponent(new BufferMessageComponent(buffer)); } public void Write(int value) { AddComponent(new IntMessageComponent(value)); } private void AddComponent(IMessageComponent component) { _components.Add(component); _length += component.Length; } public byte[] Compose() { byte[] messageBuffer = new byte[_length]; int offset = 0; foreach (IMessageComponent component in _components) component.WriteToBuffer(messageBuffer, ref offset); return messageBuffer; } public int Length { get { return _length; } } } }
Markdown
UTF-8
2,221
2.578125
3
[]
no_license
<p align="center"> <img src="frontend.png"> </p> <hr> - <h2>👋 Hi there, I’m Marko</h2> - 👀 I’m interested in <b>WebDesign and Networking</b>... - 🌱 I’m currently learning React.js, I am learning as much as I can about WebDesign and about Networking... - 💞️ I’m looking to collaborate on ... - 📫 How to reach me<h5>markobegdev@gmail.com</h5> My website take a look into it: https://markobeg.github.io/React-Personal-Website/ ## Languages and Tools: <i>Good tools for WebDev:</i> <br> **Frontend Mentor** <br> <b>Style Stage</b> <br> **Frontend Practice** <br> <b>Free CSS</b> <br> and of course YouTube, stackoverflow. <hr> <p align="center"> <a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank"><img src="https://img.icons8.com/color/48/000000/html-5--v1.png"/></a> <a href="https://getbootstrap.com/docs/5.0/getting-started/introduction/" target="_blank"><img src="https://img.icons8.com/color/48/000000/bootstrap.png"/></a> <a href="https://developer.mozilla.org/en-US/docs/Web/CSS" target="_blank"><img src="https://img.icons8.com/color/48/000000/css3.png"/></a> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank"><img src="https://img.icons8.com/color/48/000000/javascript.png"/></a> <a href="https://www.figma.com/?fuid="><img src="https://img.icons8.com/fluent/48/000000/figma.png"/></a> <a href="https://reactjs.org/"><img src="https://img.icons8.com/officel/48/000000/react.png"/></a> <a href='https://firebase.google.com/'><img src="https://img.icons8.com/color/48/000000/firebase.png"/></a> <a href="https://mui.com/"><img src="https://img.icons8.com/color/48/000000/material-ui.png"/></a> <a href="https://redux.js.org/"><img src="https://img.icons8.com/color/48/000000/redux.png"/></a> <hr> <hr> <h3>Connect with me:</h3> <p align="left"> <a href="mailto:markobegdev@gmail.com" ><img src="https://img.icons8.com/fluent/48/000000/gmail.png"/></a> <!--- MarkoPolo125/MarkoPolo125 is a ✨ special ✨ repository because its `README.md` (this file) appears on your GitHub profile. You can click the Preview link to take a look at your changes. ---> <p align="center"> ![Css](https://media.giphy.com/media/13FrpeVH09Zrb2/source.gif) </p> <hr>
Java
UTF-8
196
2.09375
2
[]
no_license
package com.scorpiowf.filevisit; import java.io.File; public interface IFileVisitor { public String visitFile(File file, FileInfo info); public String visitFolder(File file, FileInfo info); }
Java
UTF-8
2,905
1.976563
2
[]
no_license
package com.bea.olp; import java.math.BigDecimal; public class BAT_XW_INTER_DEDU_HIS { private String loanNo; private Short totalTerms; private Short termNo; private String deduDate; private BigDecimal oriRate; private String intDeduType; private BigDecimal intAmt; private BigDecimal intDeduAmt; private BigDecimal intAfterAmt; private BigDecimal deduRate; private String inputDate; private String inputTime; private String dataDate; public String getLoanNo() { return loanNo; } public void setLoanNo(String loanNo) { this.loanNo = loanNo == null ? null : loanNo.trim(); } public Short getTotalTerms() { return totalTerms; } public void setTotalTerms(Short totalTerms) { this.totalTerms = totalTerms; } public Short getTermNo() { return termNo; } public void setTermNo(Short termNo) { this.termNo = termNo; } public String getDeduDate() { return deduDate; } public void setDeduDate(String deduDate) { this.deduDate = deduDate == null ? null : deduDate.trim(); } public BigDecimal getOriRate() { return oriRate; } public void setOriRate(BigDecimal oriRate) { this.oriRate = oriRate; } public String getIntDeduType() { return intDeduType; } public void setIntDeduType(String intDeduType) { this.intDeduType = intDeduType == null ? null : intDeduType.trim(); } public BigDecimal getIntAmt() { return intAmt; } public void setIntAmt(BigDecimal intAmt) { this.intAmt = intAmt; } public BigDecimal getIntDeduAmt() { return intDeduAmt; } public void setIntDeduAmt(BigDecimal intDeduAmt) { this.intDeduAmt = intDeduAmt; } public BigDecimal getIntAfterAmt() { return intAfterAmt; } public void setIntAfterAmt(BigDecimal intAfterAmt) { this.intAfterAmt = intAfterAmt; } public BigDecimal getDeduRate() { return deduRate; } public void setDeduRate(BigDecimal deduRate) { this.deduRate = deduRate; } public String getInputDate() { return inputDate; } public void setInputDate(String inputDate) { this.inputDate = inputDate == null ? null : inputDate.trim(); } public String getInputTime() { return inputTime; } public void setInputTime(String inputTime) { this.inputTime = inputTime == null ? null : inputTime.trim(); } public String getDataDate() { return dataDate; } public void setDataDate(String dataDate) { this.dataDate = dataDate == null ? null : dataDate.trim(); } }
C++
WINDOWS-1251
513
3.078125
3
[]
no_license
/*! \file Solution.h \brief \author Kiselev Kirill \date 15.01.2013 */ #ifndef Solution_H #define Solution_H /*! \class Solution \brief */ class Solution { public: enum Action { Fold, Call, Raise, Bet, Check, Nope }; //! Solution(){action_ = Nope;} //! virtual ~Solution() {} Action action() const {return action_;} void setAction(Action a) {action_ = a;} protected: Action action_; }; #endif
Markdown
UTF-8
5,237
2.515625
3
[ "MIT" ]
permissive
--- hrs_structure: division: '3' volume: '12' title: '31' chapter: '571' section: 571-48.5 type: hrs_section tags: - Property - Family menu: hrs: identifier: HRS_0571-0048_0005 parent: HRS0571 name: 571-48.5 Probation supervision requirements weight: 85245 title: Probation supervision requirements full_title: 571-48.5 Probation supervision requirements --- **[§571-48.5] Probation supervision requirements.** Every child placed on probation pursuant to section 571-48(1)(A) shall be supervised in accordance with the following requirements: (1) Supervision levels, frequency of contacts with probation officers and the court, and referrals to treatment and programs under section 571-31.4(c)(7) shall be established using, among other factors, the results of the risk and needs assessment conducted pursuant to section 571-45; (2) A case plan, as defined in section 571-2, shall be developed for each child and submitted to the court. The case plan shall be developed in consultation with the child and the child's parent, legal guardian, or custodian. The probation officer assigned to each child shall keep the child's parent, legal guardian, or custodian informed regarding development of and progress toward the case plan, the child's conduct, compliance with the conditions of probation, and any other relevant matter in the child's case; (3) A child whose probation term and case plan require in-person visits with a probation officer shall receive at least one home visit; provided that the first visit shall take place within forty-five days of the child's placement on probation; provided further that a home visit shall not be required when the probation officer has reasonable perceptions of risks to the probation officer's safety due to known factors of violent criminal activity or isolation of the child's place of residence. The probation officer shall immediately report any reasonable perceptions of risks to a supervisor and may receive permission to waive the home visit requirement for the child or to conduct the home visit accompanied by another; (4) Probation officers shall have the authority to impose graduated sanctions in response to a violation of the rules and conditions of probation, as an alternative to judicial modification or revocation pursuant to section 571-50, or to award incentives or rewards for positive behavior exhibited by the child. The graduated sanctions and incentives shall be established as follows: (A) The judiciary shall adopt guidelines and procedures for the development and application of a statewide graduated sanctions and incentives system in accordance with this section, and the deputy chief court administrator in each judicial circuit, or the administrator's designee, shall adopt policies or procedures for the implementation of the adopted graduated sanctions and incentives system to guide probation officers in imposing sanctions and awarding incentives; (B) The system shall include a series of presumptive sanctions for the most common types of probation violations but shall allow for a child's risk level and seriousness of violation to be taken into consideration. The system shall also identify incentives that a child may receive as a reward for compliance with the rules and conditions of probation, completion of benchmarks, or positive behavior exceeding expectations, at the discretion of the probation officer; (C) The system shall be developed with the following objectives: (i) To respond quickly, consistently, and proportionally to violations of the rules and conditions of probation; (ii) To reduce the time and resources expended by the court in responding to violations with judicial modification; (iii) To reduce the likelihood of a new delinquent act; and (iv) To encourage positive behavior; (D) At a child's first meeting with a probation officer after being adjudicated and disposed to a probation term, the probation officer shall provide written and oral notification to the child regarding the graduated sanctions and incentives system to ensure the child is aware of the sanctions and incentives that may be imposed or rewarded; (E) When issuing a sanction or incentive, the probation officer shall provide written notice to the child of the nature and date of the relevant behavior, the sanction or incentive imposed or rewarded, and, in the case of sanctions, any applicable time period in which the sanction will be in effect or by which corrective behavior must be taken. The probation officer shall provide this information to the court at the next regularly scheduled review hearing and inform the court of the child's response to the sanction or incentive; and (F) Each administrator of the juvenile client services branch in each judicial circuit shall report annually to the board of family court judges and the Hawaii juvenile justice state advisory council, the number and the per cent of children on probation who received a graduated sanction or incentive, the types of sanctions and incentives used, and the child's current probation status. [L 2014, c 201, pt of §3] Note Section applies to delinquent behavior committed on or after November 1, 2014\. L 2014, c 201, §21(2).
C++
UTF-8
2,580
2.984375
3
[ "MIT" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <atomic> #include <chrono> #include <condition_variable> #include <mutex> #include <queue> #include <thread> #include <type_traits> #include <unordered_set> #include "tasks/task.h" #include "utils.h" namespace flash { template<typename T> class ConcurrentQueue { typedef std::chrono::milliseconds chrono_ms_t; typedef std::unique_lock<std::mutex> mutex_locker; std::queue<T> q; std::mutex mut; std::mutex push_mut; std::mutex pop_mut; std::condition_variable push_cv; std::condition_variable pop_cv; T null_T; public: ConcurrentQueue() { this->null_T = static_cast<T>(0); } ConcurrentQueue(T nullT) { this->null_T = nullT; } ~ConcurrentQueue() { this->push_cv.notify_all(); this->pop_cv.notify_all(); } // queue stats uint64_t size() { mutex_locker lk(this->mut); uint64_t ret = q.size(); lk.unlock(); return ret; } bool empty() { return (this->size() == 0); } // PUSH BACK void push(T& new_val) { mutex_locker lk(this->mut); this->q.push(new_val); lk.unlock(); } template<class Iterator> void insert(Iterator iter_begin, Iterator iter_end) { mutex_locker lk(this->mut); for (Iterator it = iter_begin; it != iter_end; it++) { this->q.push(*it); } lk.unlock(); } // POP FRONT T pop() { mutex_locker lk(this->mut); if (this->q.empty()) { lk.unlock(); return this->null_T; } else { T ret = this->q.front(); this->q.pop(); lk.unlock(); return ret; } } // register for notifications void wait_for_push_notify(chrono_ms_t wait_time = chrono_ms_t{100}) { mutex_locker lk(this->push_mut); this->push_cv.wait_for(lk, wait_time); lk.unlock(); } void wait_for_pop_notify(chrono_ms_t wait_time = chrono_ms_t{100}) { mutex_locker lk(this->pop_mut); this->pop_cv.wait_for(lk, wait_time); lk.unlock(); } // just notify functions void push_notify_one() { this->push_cv.notify_one(); } void push_notify_all() { this->push_cv.notify_all(); } void pop_notify_one() { this->pop_cv.notify_one(); } void pop_notify_all() { this->pop_cv.notify_all(); } }; } // namespace flash
Java
UTF-8
260
2.359375
2
[ "Apache-2.0" ]
permissive
package io.chr1s.graph; /** * 最小生成树API */ public interface MST { /** * 最小生成树的所有边 * @return */ Iterable<Edge> edges(); /** * 最小生成树的权重 * @return */ double weight(); }
Java
UTF-8
1,931
3.15625
3
[]
no_license
package APTS; import desmoj.core.simulator.*; import java.util.concurrent.TimeUnit; /** * This class represents an entity (and event) source, which continually generates * trucks (and their arrival events) in order to keep the simulation running. * * It will create a new truck, schedule its arrival at the terminal (i.e. create * and schedule an arrival event) and then schedule itself for the point in * time when the next truck arrival is due. * @author Olaf Neidhardt, Ruth Meyer */ public class DeparturePassengerGeneratorEvent extends ExternalEvent { /** * Constructs a new TruckGeneratorEvent. * * @param owner the model this event belongs to * @param name this event's name * @param showInTrace flag to indicate if this event shall produce output for the trace */ public DeparturePassengerGeneratorEvent(Model owner, String name, boolean showInTrace) { super(owner, name, showInTrace); } /** * The eventRoutine() describes the generating of a new truck. * * It creates a new truck, a new TruckArrivalEvent * and schedules itself again for the next new truck generation. */ public void eventRoutine() { // get a reference to the model APTS model = (APTS)getModel(); // create a new passenger Passenger passenger = new Passenger(model, "Passenger", true, model.getRandomGate()); // create a new truck arrival event DeparturePassengerEvent passengerArrival = new DeparturePassengerEvent(model, "PassengerArrivalEvent", true); // and schedule it for the current point in time passengerArrival.schedule(passenger, new TimeSpan(0.0)); // schedule this truck generator again for the next truck arrival time schedule(new TimeSpan(model.getPassengerDepartureTime(), TimeUnit.MINUTES)); // from inside to outside... // draw a new inter-arrival time value // wrap it in a TimeSpan object // and schedule this event for the current point in time + the inter-arrival time } }
Java
UTF-8
9,942
2.265625
2
[]
no_license
package com.parabits.paranote.activities; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.RadioButton; import com.parabits.paranote.R; import com.parabits.paranote.data.models.Repetition; import com.parabits.paranote.data.models.RepetitionPattern; import com.parabits.paranote.views.SelectableButton; import java.util.ArrayList; import java.util.List; public class RepetitionDialog extends DialogFragment { private RadioButton m_weekly_radio_button; private RadioButton m_monthly_radio_button; private GridView m_grid_view; private SelectableButton m_last_day_button; private RepetitionAdapter m_adapter; private RepetitionPattern m_repetition_pattern; private Callback m_callback; public interface Callback{ void onDialogOk(List<Integer> selectedIndexList, boolean monthly); } public void setCallback(Callback callback) { m_callback = callback; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); init(); } private void init() { if(m_repetition_pattern == null) { m_repetition_pattern = new RepetitionPattern(); } } public void setRepetition(List<Integer> selected, boolean monthly) { m_repetition_pattern = new RepetitionPattern(selected, monthly); } private View getView(LayoutInflater inflater) { View view = inflater.inflate(R.layout.dialog_repetition, null); //TODO ustawienie kontrolek w przypadku kiedy wcześniej powtórzenie było już ustawione setupControls(view); return view; } private void setupControls(View view) { m_weekly_radio_button = view.findViewById(R.id.weekly_radio_button); m_monthly_radio_button = view.findViewById(R.id.monthly_radio_button); m_last_day_button = view.findViewById(R.id.last_day_button); m_grid_view = view.findViewById(R.id.days_grid_view); m_weekly_radio_button.setChecked(!m_repetition_pattern.isMonthly()); m_monthly_radio_button.setChecked(m_repetition_pattern.isMonthly()); m_weekly_radio_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { m_repetition_pattern.setDays(m_adapter.getSelected()); m_repetition_pattern.setMonthly(false); setupWeeklyGridView(); m_monthly_radio_button.setChecked(false); } }); m_monthly_radio_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { m_repetition_pattern.setDays(m_adapter.getSelected()); m_repetition_pattern.setMonthly(true); setupMonthlyGridView(); m_weekly_radio_button.setChecked(false); } }); setupGridView(); } private void setupGridView() { if(m_repetition_pattern.isMonthly()) { setupMonthlyGridView(); } else { setupWeeklyGridView(); } } private void setupWeeklyGridView() { if(m_adapter != null) { m_adapter.clear(); } String[] daysOfTheWeeks = getResources().getStringArray(R.array.days_of_the_week_abbr); m_adapter = new RepetitionAdapter(getActivity(), R.layout.dialog_repetition, daysOfTheWeeks); m_adapter.setSelectedIndexes(m_repetition_pattern.getDays()); m_grid_view.setAdapter(m_adapter); m_last_day_button.setVisibility(View.GONE); } private void setupMonthlyGridView() { if(m_adapter != null) { m_adapter.clear(); } final String[] daysOfTheMonth = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}; m_adapter = new RepetitionAdapter(getActivity(), R.layout.dialog_repetition, daysOfTheMonth); m_adapter.setSelectedIndexes(m_repetition_pattern.getDays()); m_grid_view.setAdapter(m_adapter); m_last_day_button.setVisibility(View.VISIBLE); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); dialogBuilder.setTitle(getString(R.string.repetition_2)); dialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { List<Integer> selectedIndexList = m_adapter.getSelected(); if(m_callback != null) { m_callback.onDialogOk(selectedIndexList, m_repetition_pattern.isMonthly()); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dismiss(); } }); View view = getView(LayoutInflater.from(getActivity())); dialogBuilder.setView(view); return dialogBuilder.create(); } private class RepetitionAdapter extends ArrayAdapter { private class Item { private String m_text; private boolean m_selected; public Item(String text) { m_text = text; m_selected = false; } public String getText() {return m_text;} public boolean isSelected() {return m_selected;} public void setText(String text){m_text = text;} public void setSelected(boolean selected) {m_selected = selected;} } private List<Item> m_items; private Context m_context; public RepetitionAdapter(@NonNull Context context, @LayoutRes int resource, String[] data) { super(context, resource); m_items = new ArrayList<>(); for(int i=0; i<data.length; i++) { m_items.add(new Item(data[i])); } m_context = context; } @Override public int getCount() { return m_items.size(); } @Override public String getItem(int position) { return m_items.get(position).getText(); } @Override public long getItemId(int position) { return position; } public boolean isSelected(int position) { return m_items.get(position).isSelected(); } public void setSelected(int position, boolean selected) { m_items.get(position).setSelected(selected); } public void setSelectedIndexes(List<Integer> selectedIndexes) { for(Integer i : selectedIndexes) { m_items.get(i).setSelected(true); } } public List<Integer> getSelected() { List<Integer> selectedIndexList = new ArrayList<>(); for(int i=0; i< m_items.size(); i++) { if(m_items.get(i).isSelected()) { selectedIndexList.add(i); } } return selectedIndexList; } @NonNull @Override public View getView(int position, View view, ViewGroup viewGroup) { View rowView = view; ViewHolder viewHolder; if(rowView == null) { LayoutInflater inflater = LayoutInflater.from(m_context); rowView = inflater.inflate(R.layout.item_repetition_dialog, null); viewHolder = new ViewHolder(rowView, position); rowView.setTag(viewHolder); } else { viewHolder = (ViewHolder)rowView.getTag(); } viewHolder.setButtonText(m_items.get(position).getText()); viewHolder.setSelected(m_items.get(position).isSelected()); return rowView; } private class ViewHolder { private Button m_button; ViewHolder(View view, final int position) { m_button = view.findViewById(R.id.button); m_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean selected = m_items.get(position).isSelected(); m_items.get(position).setSelected(!selected); notifyDataSetChanged(); } }); } void setButtonText(String text) { m_button.setText(text); } public String getButtonText() { return m_button.getText().toString(); } public boolean isSelected() { return m_button.isSelected(); } void setSelected(boolean selected) { m_button.setSelected(selected); } } } }
JavaScript
UTF-8
2,324
3.359375
3
[ "MIT" ]
permissive
'use strict'; //const util = require('util'); const LinkedList = require('../linked-list.js'); class HashTable { constructor(size) { this.size = size, this.map = new Array(size); } hash(key){ let hashedIndex = key.split('').reduce(function(p, c, i){ return p + (c.charCodeAt(0) + (c.charCodeAt(0) * i)); }, 0) % this.size; return hashedIndex; } // usually named 'set' but requirements specify 'add add(key, value) { let hash = this.hash(key); if (! this.map[hash] ) { let ll = new LinkedList(); this.map[hash] = ll; } this.map[hash].append({[key]:value}); } contains(key) { let hash = this.hash(key); let foundLL = this.map[hash]; if (!foundLL) { return false; } else { let current = foundLL.head; if(current && foundLL.length === 1) { if(current.value[key]) { return true; } } else if (current && current.next) { while(current.next) { if(current.value[key]) { return true; } current = current.next; } if(current.value[key]) { return true; } } } return false; } find(key) { let hash = this.hash(key); let foundLL = this.map[hash]; if (!foundLL) { return false; } for (let i = 0; i < foundLL.length; i++) { let currentNode = foundLL.find(i); if (currentNode.value[key]) { return currentNode.value; } } return false; } // takes in a key, returns the index (or hash) where that key is stored. Note that this does not indicate whether or not any other keys are stored at that index due to collisions. getHash(key) { let hash = this.hash(key); if(hash) { return hash; } return false; } delete(key) { let hash = this.hash(key); let foundLL = this.map[hash]; if(!foundLL) { return false; } let current = foundLL.head; let index = 0; while(current.next) { if(current.value[key]) { foundLL.remove(index); return; } current = current.next; index++; } if(current.value[key]) { foundLL.remove(index); return; } else { return false; } } } module.exports = HashTable;
C#
UTF-8
1,490
3.53125
4
[ "MIT" ]
permissive
using System; namespace HashTableRansomNote { using System.Collections.Generic; class Program { static void Main(string[] args) { string[] mn = Console.ReadLine().Split(' '); int m = Convert.ToInt32(mn[0]); int n = Convert.ToInt32(mn[1]); string[] magazine = Console.ReadLine().Split(' '); string[] note = Console.ReadLine().Split(' '); checkMagazine(magazine, note); } private static void checkMagazine(string[] magazine, string[] note) { if (magazine.Length < note.Length) { Console.WriteLine("No"); return; } var wordDict = new Dictionary<string, int>(); foreach (var word in magazine) { if (!wordDict.ContainsKey(word)) { wordDict.Add(word,0); } wordDict[word] += 1; } foreach (var wordNeeded in note) { if (!wordDict.ContainsKey(wordNeeded)) { Console.WriteLine("No"); return; } var count= wordDict[wordNeeded]--; if (count<0) { Console.WriteLine("No"); return; } } Console.WriteLine("Yes"); } } }
Markdown
UTF-8
1,083
2.890625
3
[]
no_license
# tidy-music Organize your music library according its tags. ## Building ```sh cd cli go build -o tidy-music ``` ## Usage ```sh ./tidy-music [-s] [-o] [-t] [-p] ``` ### Parameters - **s**: The source path. Its default value is `./`. - **o**: The output path. Its default value also is `./`. - **t**: Test mode. If true only show the expected output. Its default is `false`. - **p**: The output directory structure pattern. It follows the Golang's [text/template](https://golang.org/pkg/text/template/) guide. Available fields: - Artist - Album - Year - Track number - Title ## Output The default `p` value is `{{.Artist}}/[{{.Year}}] {{.Album}}/{{printf "%02d" .Track}} - {{.Title}}` so the generated output will be this following structure: ``` Artist └── [Year] Album └── # - Title.ext ``` Example: ``` Green Day ├── [1994] Dookie │ ├── 01 - Burnout.mp3 │ └── 02 - Having a Blast.mp3 └── [1995] Insomniac └── 01 - Armatage Shanks.wma ``` All the `/` and `:` in track and album names will be replaced by `-`.
JavaScript
UTF-8
1,887
3.40625
3
[]
no_license
document.addEventListener('keydown', changeHead, false); document.addEventListener('keydown', changeBody, false); document.addEventListener('keydown', changeShoes, false); document.addEventListener('keydown', helper, false); var headIndex = 0; var bodyIndex = 0; var shoesIndex = 0; var clothingIndex = 0; function changeHead(event) { var head = document.getElementById("head") head.src = "./images/head" + headIndex + ".png" if (clothingIndex == 0) { event = event || window.event; if (event.keyCode == '39') headIndex++ if (headIndex == 6) headIndex = 0 if (event.keyCode == '37') headIndex-- if (headIndex == -1) headIndex = 5; } } function changeBody(event) { var body = document.getElementById("body") body.src = "./images/body" + bodyIndex + ".png" if (clothingIndex == 1) { event = event || window.event; if (event.keyCode == '39') bodyIndex++ if (bodyIndex == 6) bodyIndex = 0 if (event.keyCode == '37') bodyIndex-- if (bodyIndex == -1) bodyIndex = 5; } } function changeShoes(event) { var shoes = document.getElementById("shoes") shoes.src = "./images/shoes" + shoesIndex + ".png" if (clothingIndex == 2) { event = event || window.event; if (event.keyCode == '39') shoesIndex++ if (shoesIndex == 6) shoesIndex = 0 if (event.keyCode == '37') shoesIndex-- if (shoesIndex == -1) shoesIndex = 5; } } function helper(event) { if (event.keyCode == '38') { changeBodyPart(-1) } else if (event.keyCode == '40') { changeBodyPart(1) } } function changeBodyPart(change) { clothingIndex += change if (clothingIndex == -1) clothingIndex = 2 if (clothingIndex == 3) clothingIndex = 0 }
Java
UTF-8
2,642
1.875
2
[]
no_license
package com.ningyang.os.controller.base; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ningyang.os.action.input.command.web.base.CodeImportTemplateCommand; import com.ningyang.os.action.input.condition.base.QueryCodeCondition; import com.ningyang.os.action.output.vo.web.base.CodeImportTemplateVo; import com.ningyang.os.action.utils.WebResult; import com.ningyang.os.service.ISerCodeImportTemplateInfoService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; import static com.ningyang.os.action.enums.SystemErrorEnum.DATA_ERROR; import static com.ningyang.os.action.enums.SystemErrorEnum.OPERATING_ERROR; /** * @Author: kaider * @Date:2018/11/14 14:16 * @描述:码模板 */ @RestController @RequestMapping("base/codeTemplate") public class CodeTemplateController { private static final Logger LOGGER = LoggerFactory.getLogger(CodeTemplateController.class); @Autowired private ISerCodeImportTemplateInfoService infoService; @GetMapping("getCodeTemplatePageList") public Map<String, Object> getCodeTemplatePageList( QueryCodeCondition condition ) { try { Page<CodeImportTemplateVo> pageVo = infoService.findCodeImportVoPageByCondition(condition); return WebResult.success().put("pageVo", pageVo).toMap(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return WebResult.failure(DATA_ERROR.getInfo()).toMap(); } } @PostMapping("addOrUpdate") public Map<String, Object> addOrUpdate( @RequestBody CodeImportTemplateCommand command ) { try { boolean flag = infoService.addOrUpdate(command); if (flag) { return WebResult.success().toMap(); } return WebResult.failure(OPERATING_ERROR.getInfo()).toMap(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return WebResult.failure(OPERATING_ERROR.getInfo()).toMap(); } } @GetMapping("findCodeImportTemplateVoList") public Map<String, Object> getCodeTemplateList() { try { List<CodeImportTemplateVo> listVo = infoService.findCodeImportTemplateVoList(); return WebResult.success().put("listVo", listVo).toMap(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return WebResult.failure(DATA_ERROR.getInfo()).toMap(); } } }
JavaScript
UTF-8
3,921
2.703125
3
[]
no_license
const puppeteer = require("puppeteer"); const userFactory = require("../factories/userFactory"); const sessionFactory = require("../factories/sessionFactory"); class CustomPage { constructor(page, browserUrl) { this.page = page; this.browserUrl = browserUrl; } // static function - so that we don't have to make a new instance of CustomClass and call 'build' function static async build(browserUrl) { const browser = await puppeteer.launch({ headless: true, // chromium uses multiple layers of sand-boxing to protect host environment from un-trusted we content, // if you trust the content you open inside of a browser, you can launch with '--no-sandbox' // will decrease the amount of time to run the tests args: ["--no-sandbox"] }); const page = await browser.newPage(); const customPage = new CustomPage(page, browserUrl); return new Proxy(customPage, { get: function(target, property) { // we include 'browser' because we always use browser instance just to create new page and close the browser // since we're calling 'close' function after each test case to close the browser // and 'browser' and 'page' both has this function, we move 'browser' // to 2nd check, so that we rather close browser and not page when running tests return customPage[property] || browser[property] || page[property]; } }); } async login(browserUrl) { const user = await userFactory(); const { session, sessionSig } = sessionFactory(user); const sessionCookies = [ { name: "session", value: session }, { name: "session.sig", value: sessionSig } ]; await this.page.setCookie(...sessionCookies); // fake 'login' oauth leaves on localhost:3000 after faking login // therefore we go to /blogs right away await this.page.goto(`${browserUrl}/blogs`); // so that page waits for a element to appear on the screen and then proceed the test await this.page.waitFor("a[href='/auth/logout']"); } async getContentsOf(selector) { return await this.page.$eval(selector, el => el.innerHTML); } get(path) { return this.page.evaluate(_path => { return fetch(_path, { method: "GET", credentials: "same-origin", headers: { "Content-Type": "application/json" } }).then(res => res.json()); // you have to pass 'path' as a argument, because inner function // forms a closure scope variable, therefore 'path' would be send // to chromium as a string, and be undefined, ...args fixes this problem }, path); } post(path, reqBody) { // you have to wrap 'fetch' inside a function to pass is to chromium to evaluate // puppeteer will then send it as a string to chromium and run it and // wait for the response (Promise) and then return it inside a test runner return this.page.evaluate( (_path, _reqBody) => { return fetch(_path, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify(_reqBody) // fetch responsive is in raw format, therefore you have to // transform it into a JSON format // after Promise is resolved, it will send the response back // to the test runner and save it to 'result' variable }).then(res => res.json()); }, path, reqBody ); } execRequests(actions) { return Promise.all( actions.map(({ method, path, reqBody }) => { // even if it's 'GET' request, reqBody param can be passed along // since it will be ignored anyway because it's undefined return this[method.toLowerCase()](path, reqBody); }) ); } } module.exports = CustomPage;
C
UTF-8
218
3.84375
4
[]
no_license
#include <stdio.h> /** * main - Print Hex * * Return: Always 0 (Success) */ int main(void) { char hex[16] = "0123456789abcdef"; int j; for (j = 0 ; j < 16 ; j++) { putchar (hex[j]); } putchar ('\n'); return (0); }