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
C++
UTF-8
478
2.765625
3
[]
no_license
#include "StdAfx.h" #include "Parametr.h" #include "size.h" Parametr::Parametr() { _size=Size(); _weight=0; } Parametr::Parametr(Size size,int weight) { _size=size; _weight=weight; } Parametr::Parametr(int height, int width, int weight) { Size size(height, width); _size=size; _weight=weight; } Size Parametr::GetSize() { return _size; } int Parametr::GetWeight() { return _weight; } void Parametr::SetWeight(int weight) { if(weight<0) weight=0; _weight=weight; }
Shell
UTF-8
724
3.375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash set -euo pipefail staffi_image="local/stafi:latest" NC='\033[0m' RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[0;33m' echo echo -e "${RED}Ensure you run the cleanup.sh script before running this script${NC}" echo echo -e "${GREEN}Starting stafi container...${NC}" docker run -d --restart=unless-stopped --name stafi_node \ --memory-reservation="5000m" \ --mount source=chain_data,target=/root/.local/ \ --entrypoint /opt/stafi-node/target/release/stafi \ ${staffi_image} $@ echo -e "${GREEN}Container Started.${NC}" echo echo -e "${YELLOW}You can check the log of your stafi container using `docker logs -f stafi_node --tail 100`" echo -e "Hit CTRL-C to abort the output." echo -e "${NC}"
JavaScript
UTF-8
1,668
3.375
3
[ "MIT" ]
permissive
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // ENUMERADOS EN TYPESCRIPT // Es una forma que tiene typescript para poder crear nuestros propios tipos de datos(datos reducidos) // Permite modificar el indice de cada enumerado // type Curso : string | number; (datos no reducidos, en number peermite agregar expresiones regulares) var Curso; (function (Curso) { Curso[Curso["JavaScript"] = 0] = "JavaScript"; Curso[Curso["TypeScript"] = 1] = "TypeScript"; Curso[Curso["Angular"] = 2] = "Angular"; //indice 2 })(Curso || (Curso = {})); var curso = Curso.JavaScript; console.log('Curso', curso); console.log('Curso', Curso[curso]); // Ejemmplo 2 var Dia; (function (Dia) { Dia[Dia["Lunes"] = 0] = "Lunes"; Dia[Dia["Martes"] = 1] = "Martes"; Dia[Dia["Miercoles"] = 2] = "Miercoles"; Dia[Dia["Jueves"] = 3] = "Jueves"; Dia[Dia["Viernes"] = 4] = "Viernes"; })(Dia || (Dia = {})); console.log('Viernes', Dia.Viernes); // Permite modificar el indice de cada enumerado y automaticamente el siguiente sera de acuerdo a lo que se tiene modificado var FinSemana; (function (FinSemana) { FinSemana[FinSemana["Sabado"] = 5] = "Sabado"; FinSemana[FinSemana["Domingo"] = 6] = "Domingo"; })(FinSemana || (FinSemana = {})); console.log('Sabado', FinSemana.Sabado); console.log('Domingo', FinSemana.Domingo); // Permite agaregar a los indices cadenas var Mes; (function (Mes) { Mes["Enero"] = "Ene"; Mes["Febrero"] = "Feb"; Mes["Marzo"] = "Mar"; Mes["Abril"] = "Abr"; })(Mes || (Mes = {})); console.log('Marzo', Mes.Marzo); // EJECUTAR EN LA CONSOLA // node dist/clase-03-tipo-de-datos-II/app-01.js
Python
UTF-8
288
3.59375
4
[]
no_license
funcionario = (input('Digite o seu nome: ')) qtd_horas = int(input('Digite a suas horas trabalhadas: ')) sal_valor = float(input('Digite o valor da sua hora de trabalho: ')) salario = qtd_horas * sal_valor print('O salário do funcinário ' + funcionario + ' é de R$: ' + str(salario))
Python
UTF-8
375
3.75
4
[]
no_license
#1) Import the random function and generate both a random number between 0 and 1 as well as a random number between 1 and 10. import random import datetime print(random.random()) print(random.randint(1,10)) #2) Use the datetime library together with the random number to generate a random, unique value. print(datetime.time(random.randint(1,10), random.randint(11,20)))
C#
UTF-8
988
3.734375
4
[]
no_license
using System; namespace Trie2 { class Program { static void Main(string[] args) { Console.WriteLine("Radix Tree \n"); Trie t = new Trie(); string phrase = "hack hackerrank"; string[] wordsFromPhrase = phrase.Split(" "); foreach (string s in wordsFromPhrase) { Console.WriteLine(string.Format("Inserting {0} ...", s)); t.Insert(s.ToLower()); } Console.WriteLine("Word to search: "); string prefix = Console.ReadLine(); Console.WriteLine(string.Format("{0} : {1}", prefix, t.Search(prefix))); var words = t.Matches2(prefix); Console.WriteLine("Count:" + words); //Console.WriteLine("\nSimilares"); //foreach (string s in words) //{ // Console.WriteLine(s.Trim()); //} Console.ReadKey(); } } }
C++
UTF-8
1,075
2.765625
3
[]
no_license
#pragma once #include <string> using namespace std; #include "Def.h" namespace tcp { // Tcp Service class TcpService { public: TcpService(const string& ip, const int& port, ETcpSrvType type); virtual ~TcpService(); protected: string strIp; // Ip int nPort; // Port ETcpSrvType type; // Tcp Service Type public: //************************************ // Method: Get Ip //************************************ string GetIp() const; //************************************ // Method: Get Port //************************************ int GetPort() const; //************************************ // Method: GetType //************************************ ETcpSrvType GetType() const; //************************************ // Method: Reset Addr // Parameter: string ip // Parameter: int port //************************************ virtual bool ResetAddr(string ip, int port); //************************************ // Method: Exit //************************************ virtual void Exit(); }; }
C++
UTF-8
2,109
4.03125
4
[]
no_license
/* Author: Veeupup 汉诺塔的非递归实现 我们先来说明汉诺塔问题 对于一个有 n 个盘子的汉诺塔,有 A,B,C 三个塔 如果需要将 n 个盘子从 A -> C 上 需要有三步: 1. 将 A 上的 n-1 个盘子以 C 为辅助塔,从 A 移动到 B 上 2. 将 A 上的最大的盘子从 A->C 上 3. 将 B 上的 n-1 个盘子以 A 为辅助塔,从 B 移动到 C 上 采用递归实现即可 非递归的实现方法: */ #include <iostream> #include <cstdio> #include <cstdint> #include <stack> using namespace std; // 递归实现汉诺塔 // n 为汉诺塔圆盘编号,从小到大为 1,2,3,…… void hanoi(int n, char A, char B, char C) { if(n == 1) { printf("%c -> %c\n", A, C); // 如果只有一个盘子,从 A 直接移动到 C }else { hanoi(n-1, A, C, B); // A 上的盘子,以 C 为辅助,移动到 B hanoi(1, A, B, C); // 移动 A 上的最大的盘子到 C 上 hanoi(n-1, B, A, C); // 将 B 上的盘子以 A 为辅助,移动到 C } } // 保存函数状态 struct Status { int n; char start, mid, end; // 初始塔,辅助中间塔,最终要移动到的塔 Status(int _n, char _A, char _B, char _C): n(_n), start(_A), mid(_B), end(_C) {} }; // 采用非递归实现汉诺塔问题 // 由于栈的特殊性质,FILO,所以我们需要将原来函数的调用方式反过来进行 void hanoiStack(int n, char A, char B, char C) { stack<Status> myS; myS.push(Status(n, A, B, C)); while (!myS.empty()) { Status ns = myS.top(); myS.pop(); if(ns.n == 1) { printf("%c -> %c\n", ns.start, ns.end); }else { myS.push(Status(ns.n-1, ns.mid, ns.start, ns.end)); myS.push(Status(1, ns.start, ns.mid, ns.end)); myS.push(Status(ns.n-1, ns.start, ns.end, ns.mid)); } } } int main() { int n; scanf("%d", &n); // hanoi(n, 'a', 'b', 'c'); // printf("====\n"); hanoiStack(n, 'a', 'b', 'c'); return 0; }
Markdown
UTF-8
4,084
2.625
3
[]
no_license
# 剧本是不是这样的:美军舰本想悄悄[过台海](http://news.sina.com.cn/c/2018-07-07/doc- ihexfcvm4000668.shtml),结果蔡英文太咋呼 美驱逐舰过台海是在搞心理游戏。 美国两艘驱逐舰昨天通过台湾海峡,这被普遍认为是美方针对中美关系及台海问题展示姿态的一个行动。目前因贸易战中美关系整体趋紧,台海方向因蔡英文当局不断挑衅风险在 增加,这个时候美国在西太平洋地区的舰队又出来表演了。 ![](http://n.sinaimg.cn/translate/102/w543h359/20180708/pih0-hezpzwt6310570.jpg) 上个月,五角大楼就通过媒体放风,表示美国军舰要过台湾海峡。当时舆论就猜:是航母过还是一般舰种过,以及挑什么样的日子过,是简单通过还是行进在台海时再搞出些什么 动作来。现在看来,美国军舰这一次的通过选择了相对低调的方式,即它选择了周末的普通日子,过的不是航母而是驱逐舰,通过的过程中没有搞演习等敏感活动,美国军方也没 有就此公开发正式通告,等等。 由于台湾海峡中间的很大一片水域是公海,属于国际水上通道,美国军舰如果就是老老实实地无害通过,北京也不好说什么。 然而在大多数情况下,美国军舰通过台湾海峡都是在释放政治信号,区别仅仅在于这些信号的强度。这一次华盛顿没怎么吱声,但是台湾那边从“总统府”到“国防部”一个声明 接一个声明,民进党当局显然从美方的这一姿态展示中受到了些许鼓舞。国际上的很多报道则把美舰过台海与中美贸易战导致的两国关系紧张联系了起来,分析界很关心这种紧张 是否会向更多领域扩散。 我们认为,大陆方面需要保持战略上的坦然和从容,按照既定的台海问题方略应对美方的姿态展示,多把美方的每一个行动对照国际法和我方实际利益,少受台湾当局和岛内舆论 及西方舆论的牵制,对美方每一个动作做出准确的评估和回应。 这次两艘美国驱逐舰以“安静”的方式通过,但它同时刺激了一些想象力,就是美国军舰今后有可能不那么安静地通过台海,它可以派更大的军舰通过,边过边搞训练和演习,甚 至与台军开展某种形式的协同,美方要把这些想象力变成对大陆的威慑,增加北京的压力感。 我们恰恰不能吃华盛顿的这一套。大陆要做的是让美国的这种心理战术对我们没用。大陆的实力今非昔比,我们的自信同样今非昔比。由于我们有能力反制美方在台海地区的任何 挑衅,我们用不着想象这些挑衅的可能到来而惶恐。 ![](http://n.sinaimg.cn/news/transform/784/w550h234/20180708/n4DA-hezpzwt6798998.jpg) 可以想见,大陆的实力也为我们未来有可能的行动提供了潜力。比如,解放军战机绕台飞行贴近台湾岛的距离是可以调整的,所谓台海中线是可以破掉的,大陆军机甚至可以在必 要时飞越台湾岛。另外美国军舰过海峡时可以自由通过,也可以被大陆军舰搞成“三明治”那样通过。这些也都会成为台美方面的想象。 中美博弈复杂而微妙,只要中国是有力量的,手段足够多,就不愁在管控台海局势中没有主动性。一方面,中方不会主动朝中美关系紧张迈第一步,与此同时台湾问题排在中国对 外宣誓的核心利益之首,中国的力量成长对台海问题是有所倾斜的,这里恰恰是华盛顿开展介入风险最大的地区,想必美方对此也很了解。 最后让我们把思绪拉回到当前的状态。美国两艘驱逐舰在7日通过了台海,没惹什么事,但在岛内留下了一堆言语泡沫,只是台当局应当知道,那两艘军舰的背影做不成它们与大 陆对抗展现自信的面具。 (本文系《环球时报》今日社评,# 美驱逐舰过台海是在搞心理游戏) 责任编辑:张义凌
Java
UTF-8
4,458
3.53125
4
[]
no_license
/* This is the driving engine of the program. It parses the command-line * arguments and calls the appropriate methods in the other classes. * * You should edit this file in two ways: * 1) Insert your database username and password in the proper places. * 2) Implement the three functions getInformation, registerStudent * and unregisterStudent. */ import java.sql.*; // JDBC stuff. import java.util.Properties; import java.util.Scanner; import java.io.*; // Reading user input. public class StudentPortal { /* TODO Here you should put your database name, username and password */ static final String USERNAME = ""; static final String PASSWORD = ""; /* Print command usage. * /!\ you don't need to change this function! */ public static void usage () { System.out.println("Usage:"); System.out.println(" i[nformation]"); System.out.println(" r[egister] <course>"); System.out.println(" u[nregister] <course>"); System.out.println(" q[uit]"); } /* main: parses the input commands. * /!\ You don't need to change this function! */ public static void main(String[] args) throws Exception { try { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://ate.ita.chalmers.se/"; Properties props = new Properties(); props.setProperty("user",USERNAME); props.setProperty("password",PASSWORD); Connection conn = DriverManager.getConnection(url, props); String student = args[0]; // This is the identifier for the student. Console console = System.console(); // In Eclipse. System.console() returns null due to a bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429) // In that case, use the following line instead: // BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); usage(); System.out.println("Welcome!"); while(true) { System.out.print("? > "); String mode = console.readLine(); String[] cmd = mode.split(" +"); cmd[0] = cmd[0].toLowerCase(); if ("information".startsWith(cmd[0]) && cmd.length == 1) { /* Information mode */ getInformation(conn, student); } else if ("register".startsWith(cmd[0]) && cmd.length == 2) { /* Register student mode */ registerStudent(conn, student, cmd[1]); } else if ("unregister".startsWith(cmd[0]) && cmd.length == 2) { /* Unregister student mode */ unregisterStudent(conn, student, cmd[1]); } else if ("quit".startsWith(cmd[0])) { break; } else usage(); } System.out.println("Goodbye!"); conn.close(); } catch (SQLException e) { System.err.println(e); System.exit(2); } } /* Given a student identification number, ths function should print * - the name of the student, the students national identification number * and their issued login name (something similar to a CID) * - the programme and branch (if any) that the student is following. * - the courses that the student has read, along with the grade. * - the courses that the student is registered to. (queue position if the student is waiting for the course) * - the number of mandatory courses that the student has yet to read. * - whether or not the student fulfills the requirements for graduation */ static void getInformation(Connection conn, String student) throws SQLException { // TODO: Your implementation here } /* Register: Given a student id number and a course code, this function * should try to register the student for that course. */ static void registerStudent(Connection conn, String student, String course) throws SQLException { // TODO: Your implementation here } /* Unregister: Given a student id number and a course code, this function * should unregister the student from that course. */ static void unregisterStudent(Connection conn, String student, String course) throws SQLException { // TODO: Your implementation here } }
C++
UTF-8
1,186
3.359375
3
[]
no_license
#pragma once #include "Common.h" #include "MyMutex.h" template<class T> class MyList { public: MyList(); virtual ~MyList(); public: void Push(T it); T Pop(); public: int Size(); bool Empty(); T Front(); T Back(); void Clear(); public: list<T> all; MyMutex* mtx; }; template<class T> MyList<T>::MyList() { mtx = new MyMutex; } template<class T> MyList<T>::~MyList() { Clear(); } template<class T> void MyList<T>::Push(T it) { MyAutoLock autoLock(mtx); all.push_back(it); } template<class T> T MyList<T>::Pop() { MyAutoLock autoLock(mtx); if(all.size() >= 1) { T it = all.front(); all.pop_front(); return it; } return T(); } template<class T> int MyList<T>::Size() { MyAutoLock autoLock(mtx); return all.size(); } template<class T> bool MyList<T>::Empty() { MyAutoLock autoLock(mtx); return all.empty(); } template<class T> T MyList<T>::Front() { MyAutoLock autoLock(mtx); return all.front(); } template<class T> T MyList<T>::Back() { MyAutoLock autoLock(mtx); return all.back(); } template<class T> void MyList<T>::Clear() { all.clear(); }
Markdown
UTF-8
5,837
3.203125
3
[]
no_license
# code-standards **This is a living document and subject to change.** Please Note: On Acquia we will not be using their feature "Live Development" which would allow you to directly edit code on dev or stage. ## Code Review & Standards For Drupal 8 we will generally refer to [Drupal 8 coding standards](https://www.drupal.org/docs/develop/standards) and [Acquia has a nice general list](https://docs.acquia.com/blt/developer/code-review/). In rare cases where blocks of text constructed dynamically in code utilize HEREDOC. PHP should not be used as a templating language. Utilize Twig. Search for and remove all dead code. Dead code is defined as: - Commented Methods - Uncalled(Unused) Methods - Unused Includes - Unused Variables (Local, Properties, Fields, etc.) - Unused References (plugins, Packages, libraries, etc.) - Unused Files (Classes, Resource Files, Style Sheets, JavaScript, etc.) Ternary operations should be limited to 80 characters. Do not stack ternary operations. If it is suitably complex, use a full if statement for clarity. ## Git Best practices New to Git? [Read chapters](https://git-scm.com/book/en/v2) [2](https://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository), [3](https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell), [7.3](https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning) Between every step it is advised to get in the habit of typing `git status`. This handy bit lets you know where and when you are in your repo. If you have files that are not committing correctly, or caching incorrectly `git status` will make it clear. The best practices for git should be followed from the [Aquia documentation on Git](https://docs.acquia.com/acquia-cloud/develop/repository/git/). ### Line Endings and Whitespace Windows likes to be helpful, sometimes too helpful. Please refer to [formatting whitespace](https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration#_formatting_and_whitespace) and run the global git command: `git config --global core.autocrlf true` If using a windows machine to program, the command will auto change carriage return line endings to linefeed on commit. Fairly certain this command only need be run once per windows developer machine. ### Committing branch changes suggestions Whenever you want to commit your changes back to the code repository for the branch you’re working on, run the following commands to commit the change locally: Stage all files using your preferred commands: - `git add -A` add all changed files - Or `git add <file path>` repeat for each file to be added Use `git status` here to confirm nothing went awry in adding files. After all files are staged for commit run `git commit` and do not use the `-m` tag unless it is truly a one line change. Running the commit command without the '-m' flag will open your text editor, usually vi or vim default on Unix. ### A note about commit messages In most cases one line commit messages are not comprehensive enough for what a peer must be reviewing. Good commit messages are part information part art. A message might have this kind of format ``` [SHORT SUBJECT - Ideally less than 80 char.] [SKIP A LINE] [Longer paragraph style explanation of the commit.] [If other developers need credit, skip a line and recognize their hard work] ``` Using words like "add", "fix", "Change", "update" in the summary can tell your code reviewer lots about what they should be reviewing. A list can be nice. [This article](https://chris.beams.io/posts/git-commit/) has some nice information about commit messages. Please give it a read. tldr: rules from above article: 1. Separate subject from body with a blank line 1. Limit the subject line to 50 characters Maximum 80 characters 1. Capitalize the subject line 1. Do not end the subject line with a period 1. Use the imperative mood in the subject line 1. Wrap the body at 72 characters 1. Use the body to explain what and why vs. how This recommendation on commit messages is not a set of hard and fast rules; No more than 1 paragraph in a commit. If a commit message becomes to large, it may be a sign that work needs to be committed more often to the repo. Large commit messages should be reserved for a squashed feature commit. Writing a good commit message makes reviewing code better for peers and in the event that commits are ever 'squashed' into a finalized feature the clear subjects can optionally become the new feature commit message. ## SASS over CSS One of the main problems with css is it can become messy and unmanageable over time. Solution? SASS. In a SASS we can write CSS in a hierarchical way. We can also create variables and mix-ins. No more having to hunt down 30 instances of `color: #cf0f12;` to change them all to `color: 336aaf;`. We can have a variable named `$gutter`, set it to 5px and ensure that every box has the right sized gutters on it. ### Installing [Sass](https://sass-lang.com/install) You can install Sass on Windows, Mac, or Linux by downloading the package for your operating system [from GitHub](https://github.com/sass/dart-sass/releases/tag/1.22.10) and adding it to your PATH. That’s all—there are no external dependencies and nothing else you need to install. PhpStorm can set up file watchers while you are making edits to your theme. ## Composer Composer is the PHP package manager these days. Arguably one of the best things that has happened to PHP. Drupal 8 and some Acquia products depend upon it. Composer is the NuGet of the php world. ### Install composer Acquia Dev desktop ships with composer and php. If you want to run Composer locally, install php 7.2+ and add php to your widnows PATH. Go to the composer page and download the windows exe and install. https://getcomposer.org/doc/00-intro.md#installation-windows
Python
UTF-8
1,292
2.953125
3
[ "MIT" ]
permissive
import glob import os import re import yaml from collections import namedtuple QuestionSet = namedtuple( 'QuestionSet', ['name', 'difficulty', 'coolness', 'time', 'questions'], ) Question = namedtuple( 'Question', ['content', 'time'], ) def sanitize(str): try: s = str.encode('ascii') str = str.lower() str = re.sub('-', ' ', str) str = re.sub('[^a-z0-9 ]', '', str) except UnicodeEncodeError: pass return str.strip() def all_files_with_extension(extensions = ['txt']): r = [] for root, dirs, files in os.walk('2021-hunt/hunt/special_puzzles/cafe_luge/puzzles'): for file in files: if any([file.endswith('.' + p) for p in extensions]): r.append(os.path.join(root, file)) return r def question_set_from_file(path): try: with open(path, 'r') as fd: r = yaml.safe_load(fd.read()) except Exception as e: raise Exception(f'Exception loading {path}') name = r['name'] difficulty = int(r['difficulty'].split('/')[0]) coolness = int(r['coolness'].split('/')[0]) time = r['time'] questions = [Question(k['question'], time) for k in r['questions']] return QuestionSet(name, difficulty, coolness, time, questions)
Java
UTF-8
510
2.5
2
[]
no_license
package net.upd4ting.uhcreloaded.task.tasks; import net.upd4ting.uhcreloaded.Game; import net.upd4ting.uhcreloaded.UHCReloaded; import net.upd4ting.uhcreloaded.task.Task; public class GameTask extends Task { private Integer time; public GameTask() { super("GameTask", 20); this.time = 0; } @Override public void tick() { Game game = UHCReloaded.getGame(); if (game.isInGame()) time++; } public String getDisplayTime() { return String.format("%02d:%02d", time / 60, time % 60); } }
Python
UTF-8
531
3.65625
4
[]
no_license
# -*- encoding: utf-8 -*- def find_num_in_partially_sorted_matrix(matrix, target): if not matrix or not matrix[0]: return False i = 0 j = len(matrix[0]) - 1 while i < len(matrix) and j >= 0: if matrix[i][j] == target: return True elif matrix[i][j] > target: j -= 1 else: i += 1 return False if __name__ == '__main__': print find_num_in_partially_sorted_matrix( [[1, 2, 8, 9], [2, 4, 9, 12], [4, 7, 10, 13], [6, 8, 11, 15]], 7)
PHP
UTF-8
1,517
2.546875
3
[]
no_license
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Home_model extends CI_Model { function __construct() { parent::__construct(); } // public function getAllProducts() // { // $q = $this->db->get('products'); // if($q->num_rows() > 0) { // foreach (($q->result()) as $row) { // $data[] = $row; // } // return $data; // } // } // public function getProductsQuantity($product_id, $warehouse = DEFAULT_WAREHOUSE) // { // $q = $this->db->get_where('warehouses_products', array('product_id' => $product_id, 'warehouse_id' => $warehouse), 1); // if( $q->num_rows() > 0 ) // { // return $q->row_array(); // } // return FALSE; // } function get_calendar_data($year, $month) { $query = $this->db->select('date, data')->from('calendar') ->like('date', "$year-$month", 'after')->get(); $cal_data = array(); foreach ($query->result() as $row) { $day = (int)substr($row->date,8,2); $cal_data[$day] = str_replace("|", "<br>", html_entity_decode($row->data)); } return $cal_data; } public function updateComment($comment) { if($this->db->update('comment', array('comment' => $comment))) { return true; } return false; } public function getComment() { $q = $this->db->get('comment'); if( $q->num_rows() > 0 ) { return $q->row(); } return FALSE; } } /* End of file home_model.php */ /* Location: ./sma/modules/home/models/home_model.php */
C#
UTF-8
1,804
3.28125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GrabTheScreen { public class Auto { // Du kannst die Eigenschaften des Modells mit C#-Properties darstellen. // Properties kannst du wie ein Feld benutzen, aber du musst die // get- und set-Methoden nicht von Hand schreiben; das private Feld wird automatisch angelegt! // Bsp.: (ersetzt den private String model und die get- und set-Methode mit einer Zeile code!) // public String model { get; set; } public String model; public String modelDescription; public String price; public String source; public Auto(String car_model, String car_modelDescription, String car_price, String car_source) { model = car_model; modelDescription = car_modelDescription; price = car_price; source = car_source; } public Auto() { } public void setModel(String model) { this.model = model; } public String getModel() { return this.model; } public void setModelDescription(String modelDescription) { this.modelDescription = modelDescription; } public String getModelDescription() { return this.modelDescription; } public void setPrice(String price) { this.price = price; } public String getPrice() { return this.price; } public void setSource(String source) { this.source = source; } public String getSource() { return this.source; } } }
PHP
UTF-8
1,911
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Policies; use App\Models\Project; use App\Models\Topic; use App\Models\User; use Illuminate\Auth\Access\HandlesAuthorization; class TopicPolicy { use HandlesAuthorization; /** * Grant all abilities to administrator. * * @param \App\Models\Models\User $user * @return bool */ public function before(User $user) { if ($user->role_id !== NULL) { return true; } } /** * Determine whether the user can create topic. * @param \App\Models\User $user * @return mixed */ public function create(User $user) { return true; } /** * Determine whether the user can update topic. * * @param \App\Models\User $user * @param \App\Models\Topic $topic * @return mixed */ public function update(User $user, Topic $topic) { return $user->id === $topic->user_id; } /** * Determine whether the user can destroy project. * * @param \App\Models\User $user * @param \App\Models\Project $project * @return mixed */ public function destroy(User $user, Topic $topic) { if ($user->role_id !== NULL) { return true; } } /** * Determine whether the user can answer to topic. * * @param \App\Models\User $user * @param \App\Models\Topic $topic * @return mixed */ public function answerToTopic(User $user, Topic $topic) { return $user->id === $topic->user_id || $user->id === $topic->topicable->user_id; } /** * Determine whether the user can report the topic. * * @param \App\Models\User $user * @param \App\Models\Topic $topic * @return mixed */ public function doReport(User $user, Topic $topic) { return $user->id !== $topic->user_id; } }
JavaScript
UTF-8
2,494
3.21875
3
[]
no_license
let numbers = document.querySelectorAll(".number"), operations = document.querySelectorAll(".operator"), clearBtns = document.querySelectorAll(".clear-btn"), decimalBtn = document.getElementById("decimal"), result = document.getElementById("result"), display = document.getElementById("display"), MemoryCurrentNumber = 0, MemoryNewNumber = false, MemoryPendingOperation = ""; for(let i = 0; i < numbers.length; i++) { let number = numbers[i]; number.addEventListener("click", function(e){ numberPress(e.target.textContent); }); } for(let i = 0; i < operations.length; i++) { let operationBtn = operations[i]; operationBtn.addEventListener("click", function(e){ operationPress(e.target.id); }); } for(let i = 0; i < clearBtns.length; i++) { let clearBtn = clearBtns[i]; clearBtn.addEventListener("click", function(e){ clear(e.target.textContent); }); } decimalBtn.addEventListener("click", decimal); function numberPress(number) { if ((MemoryNewNumber) || (display.value === "0")) { display.value = number; MemoryNewNumber = false; } else display.value += number; } function operationPress(op) { switch (MemoryPendingOperation) { case 'plus': MemoryCurrentNumber += parseFloat(display.value); break; case 'munus': MemoryCurrentNumber -= +display.value; break; case 'multiply': MemoryCurrentNumber *= +display.value; break; case 'devide': MemoryCurrentNumber /= +display.value; break; case 'rate': MemoryCurrentNumber = Math.pow(MemoryCurrentNumber, +display.value); console.log(MemoryCurrentNumber); break; default: MemoryCurrentNumber = +display.value; break; } display.value = MemoryCurrentNumber; MemoryPendingOperation = op; MemoryNewNumber = true; } function decimal() { if(display.value.indexOf(".") === -1) { display.value+= "."; } } function clear(id) { if(id === "c") { display.value = "0"; MemoryNewNumber = true; MemoryCurrentNumber = 0, MemoryPendingOperation = ""; } }
Java
UTF-8
6,938
2.3125
2
[]
no_license
package ssm.springmvc.crud; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.lang.Nullable; import org.springframework.stereotype.Controller; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.DispatcherServlet; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * 测试HttpEntity 和 ResponseEntity * @author Abraham * @create 21:03/周四/22/07/2021 */ @Controller public class EntityController { @ResponseBody @RequestMapping("/haha") public String getSomething(){ //它不会去success.jsp页面 return "success"; } /** * HttpEntity<String> str 比@ResponseBody 更强,这个拿到整个请求的数据 * @RequestHeader("")这个只是获取单个请求头参数 * @param str * @return */ @RequestMapping("/haha1") public String getSomething1(HttpEntity<String> str){ System.out.println(str); //<username=dd&password=123,[host:"localhost:8080", connection:"keep-alive", // content-length:"24", cache-control:"max-age=0", sec-ch-ua:"" Not; // A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"", sec-ch-ua-mobile:"?0", // upgrade-insecure-requests:"1", origin:"http://localhost:8080", // user-agent:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36", // accept:"text/html,application/xhtml+xml,application/xml; // q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange; // v=b3;q=0.9", sec-fetch-site:"same-origin", sec-fetch-mode:"navigate", // sec-fetch-user:"?1", sec-fetch-dest:"document", // referer:"http://localhost:8080/SpringMVC_CRUD/", // accept-encoding:"gzip, deflate, br", accept-language:"en-GB,en-US;q=0.9,en;q=0.8", // cookie:"JSESSIONID=BAB0DFAC17218B1BCBEFC1243561296E", // Content-Type:"application/x-www-form-urlencoded;charset=UTF-8"]> //它不会去success.jsp页面 return "success"; } /** * 泛型中的String表示:响应体中内容的类型 * @return */ @RequestMapping("haha2") public ResponseEntity<String> getSomething2(){ //响应体中的内容 String body="success"; //自定义响应头 MultiValueMap<String,String> headers=new HttpHeaders(); headers.add("Set-Cookie","birth=1995-3-20"); //HttpStatus.OK 响应状态 ResponseEntity<String> responseEntity = new ResponseEntity<>(body, headers, HttpStatus.OK); return responseEntity; } @RequestMapping("/load") public ResponseEntity<byte[]> getSomething3() throws IOException { FileInputStream is=null; try { is=new FileInputStream("C:\\Users\\Abraham\\Desktop\\图片\\th.jpg"); //响应体中的内容 byte[] body=new byte[is.available()]; is.read(body); //自定义响应头 MultiValueMap<String,String> headers=new HttpHeaders(); //Content-Disposition响应标头是指示内容是否预期在浏览器中内联显示的标题, // 即,作为网页或作为网页的一部分或作为附件下载并且本地保存。 headers.set("Content-Disposition","attachment;filename=th.jpg"); //HttpStatus.OK 响应状态 ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body, headers, HttpStatus.OK); return responseEntity; } catch (IOException e) { e.printStackTrace(); } finally { try { if(is!=null) is.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 用来接收上传的单个文件 * 形参:@RequestParam("filename")MultipartFile file 这个参数直接封装了文件信息,可以直接保存 * @return */ @RequestMapping("/upload") public String receive(@RequestParam("username") String username, @RequestParam("password")String password , @RequestParam("filename")MultipartFile file) throws IOException { System.out.println(file.getName());//filename System.out.println(file.getOriginalFilename());//夕阳.jpg file.transferTo(new File("C:\\Users\\Abraham\\Desktop\\1.jpg")); return "success"; } /** * 如果文件的name属性值一样,我们用一个MultipartFile[] file 数组来接收多个文件, * 只需要遍历每个MultipartFile即可 * @param username * @param password * @param file * @return */ @RequestMapping("/uploadMultip") public String recervese(@RequestParam("username") String username, @RequestParam("password")String password , @RequestParam("filename")MultipartFile[] file ) throws IOException { System.out.println("用户名:"+username+",密码:"+password); for (MultipartFile multipartFile : file) { if (!multipartFile.isEmpty()) { multipartFile.transferTo(new File("C:\\Users\\Abraham\\Desktop\\保存\\" + multipartFile.getOriginalFilename())); } } return "success"; } /** * 多文件上传,如果文件的name属性值不一样 * @param username * @param password * @return */ @RequestMapping("/uploadMultip2") public String recervese2(@RequestParam("username") String username, @RequestParam("password")String password , @RequestParam("filename1")MultipartFile file1, @RequestParam("filename2")MultipartFile file2, @RequestParam("filename3")MultipartFile file3 ) throws IOException { System.out.println("用户名:"+username+",密码:"+password); file1.transferTo(new File("C:\\Users\\Abraham\\Desktop\\保存\\" + file1.getOriginalFilename())); file2.transferTo(new File("C:\\Users\\Abraham\\Desktop\\保存\\" + file2.getOriginalFilename())); file3.transferTo(new File("C:\\Users\\Abraham\\Desktop\\保存\\" + file3.getOriginalFilename())); return "success"; } }
Markdown
UTF-8
2,010
2.59375
3
[]
no_license
# ReistijdenAPI App Engine API voor reistijden verkeerscentrum Deploying this to the Google App Engine enables the following API: ##Knooppunten Knooppunten: List all knooppunten in the Flemish verkeerscentrum network /knooppunten [{"name":" A12 Meise","verkeerscentrumName":" A12 Meise","xCo":50.943906,"yCo":4.324303},...] <strong>Name:</strong> Internal API Name <strong>verkeerscentrumName:</strong> Name of knooppunt on the verkeerscentrum. This is also the name that should be displayed in an application. The Name and verkeerscentrumName usually are consistent, however can differ when there are two ways to reach one knooppunt (eg. Ring Antwerpen Noord vs Zuid). <strong>xCo,yCo:</strong> coordinates in WGS 84 Web Mercator ##Knooppunt Knooppunt: Find the nearest knooppunt from a specific location /knooppunt?x=50,y=4 <strong>x:</strong> xCo in WGS 84 <strong>y:</strong> yCo in WGS 84 {"name":"Halle","verkeerscentrumName":"Halle","xCo":50.724021,"yCo":4.269115} <strong>Name:</strong> Internal API Name <strong>verkeerscentrumName:</strong> Name of knooppunt on the verkeerscentrum <strong>xCo,yCo:</strong> coordinates in WGS 84 Web Mercator ##Reistijden Reistijden: find the travelling time between two nodes /reistijden?nodes=[node1,node2] <strong>nodes:</strong> a json array of start and end node, node1 and node2 should be from the knooppunt(en) API [{"evolutie":"stabiel","filevrij":2,"from":{"name":"West","verkeerscentrumName":"West","xCo":51.214346,"yCo":4.357262},"nu":2,"to":{"name":"Centrum","verkeerscentrumName":"Centrum","xCo":51.19521,"yCo":4.385868},"vertraging":0},...] <strong>evolutie:</strong> Stabiel, Stijgend, Dalend: indication of future traffic on this section <strong>filevrij:</strong> Traveltime on section when there is no traffic <strong>from:</strong> Start node for section <strong>nu:</strong> Traveltime at the moment <strong>to:</strong> end node for section <strong>vertraging:</strong> Delay on the section now
Java
GB18030
1,137
1.820313
2
[]
no_license
/** * Copyright: Copyright (c)2015 * Company: Ϣ޹˾(jxhtxx.com) */ package com.kylinapp.service.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.kylinapp.model.TAB_WXBLOGCATEGORY; import com.kylinapp.service.ITAB_WXBLOGCATEGORYService; import com.kylinapp.dao.ITAB_WXBLOGCATEGORYDAO; /** * @authorQYW * @since201812289:37:41 * @description: * @version: 1.0 * @copyright: Copyright (c)2015 * @company: Ϣ޹˾(jxhtxx.com) */ @Service public class TAB_WXBLOGCATEGORYServiceImpl implements ITAB_WXBLOGCATEGORYService { @Resource private ITAB_WXBLOGCATEGORYDAO ITAB_WXBLOGCATEGORYDAO; public List<TAB_WXBLOGCATEGORY> getBolgCategoryList(Map<String, Object> map) { // TODO Auto-generated method stub try { List<TAB_WXBLOGCATEGORY> categoryList = ITAB_WXBLOGCATEGORYDAO.getBolgCategoryList(map); return categoryList; } catch (Exception e) { System.err.println(e.getMessage()); } return null; } }
Python
UTF-8
819
3.296875
3
[]
no_license
import re with open("input.txt") as f: inp = f.readlines() def parse(inp: list) -> dict: bags = {} for line in inp: line = line.split("contain") parent_bag = line[0].split("bags")[0].strip() bag_contents = {} for bag in line[1].split(','): bag = bag.split() key = bag[1] + " " + bag[2] if re.search('\d',bag[0]): count = int(bag[0]) bag_contents[key] = count else: bag_contents = None bags[parent_bag] = bag_contents return bags bags = parse(inp) def score(bag_name: str): root = bags[bag_name] if root is None: return 0 else: return sum([root[key]*score(key) + root[key] for key in root]) print(score('shiny gold'))
Markdown
UTF-8
4,980
3.15625
3
[]
no_license
# How to create a Docker for your Angular Project The idea here is to use a multiple build step using [node](https://nodejs.org/en/) image to create an optimized and compact build and [nginx](https://www.nginx.com/) image to serve the compiled files Here are the steps to create our Docker container with our Angular project First we will create a project using the [Angular cli](https://cli.angular.io/) ``` ng new --defaults my-project cd my-project ``` To see the running app: ``` ng serve ``` Then we can create a file with the name "Dockerfile"<br/> *yes, dockerfile's do **not** have any extension or dot in the name* ``` //Linux or Mac touch Dockerfile //Windows - Powershell New-Item Dockerfile -ItemType file ``` Copy the following content to you Dockerfile ```dockerfile FROM node:alpine as build WORKDIR /app COPY . . RUN npm install --silent RUN npx ng build --output-path ./dist FROM nginx:alpine COPY --from=build /app/dist /usr/share/nginx/html EXPOSE 80 ``` To test if your Dockerfile is correct you can run ``` docker build -t my-project-image . docker run --name my-project-container -d -p 4200:80 my-project-image ``` Then you can open your browser on the link: http://localhost:4200 and see your project running To see the configs from your running project you can execute ``` docker ps ``` #### Dockerfile explained So let's breakdown each part of the dockerfile: `FROM node:alpine as build`<br/> We are creating a first intermediate container using node and naming as 'build'. This container will be ditched when the build image has finished `WORKDIR /app`<br/> change the folder that we will apply the following commands for /app `COPY . .`<br/> copying all the files from our project(my-project) to the folder inside the container(/app) `RUN npm install --silent`<br/> running install in our missing dependencies, using silent to not show warnings `RUN npx ng build --output-path ./dist`<br/> building our project, in this step will be created the folder `./dist` `FROM nginx:alpine`<br/> Here we are creating the final container, using nginx to serve our project `COPY --from=build /app/dist /usr/share/nginx/html`<br/> copying the build folder from the node step(that we called build) to the default folder of nginx('/usr/share/nginx/html') `EXPOSE 80`<br/> we make explicit that our container will expose the 80 port ### Advanced #### Routes If you want to use **routes** you will need create a Nginx config file, because the default config file will not work to change routes Here are the steps to use a custom Nginx config file First let's create in our repository the nginx file called "nginx.conf" ``` //Linux or Mac touch nginx.conf //Windows - Powershell New-Item nginx.conf -ItemType file ``` Inside the nginx.conf file we will put this config ``` user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; server { listen 80; server_name localhost; location / { root /usr/share/nginx/html; try_files $uri /index.html; } } } ``` We will need to change our Dockerfile to copy our "nginx.conf" to the "/etc/nginx/nginx.conf" path ```dockerfile FROM node:alpine as build WORKDIR /app COPY . . RUN npm install --silent RUN npx ng build --output-path ./dist FROM nginx:alpine COPY --from=build /app/dist /usr/share/nginx/html # the next line will copy our created nginx conf file to the rightful place COPY ./nginx.conf /etc/nginx/nginx.conf EXPOSE 80 ``` To test if all configurations were done right, you can run<br/> *remember to stop and remove the container before you run again* ``` docker build -t my-project-image . docker run --name my-project-container -d -p 3000:80 my-project-image ``` #### Base Url Sometimes we want to run our application not on the root of our domain e.g. `http://kevynklava.com/my-project/` for this we going to have change the nginx.conf file and the Dockerfile. The nginx.conf will look like this: ``` user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; server { listen 80; server_name localhost; location /my-project/ { root /usr/share/nginx/html; try_files $uri /index.html; } } } ``` and we have to tell the Angular build project that he will be running with same base url, to do that we will add an Environment variable on the build stage<br/> Your Dockerfile will look like: ```dockerfile FROM node:alpine as build WORKDIR /app COPY . . RUN npm install --silent RUN npx ng build --output-path ./dist --prod --base-href /my-project/ FROM nginx:alpine COPY --from=build /app/dist /usr/share/nginx/html EXPOSE 80 ```
Java
UTF-8
726
2.8125
3
[]
no_license
package designPatterns.proxy.javaProxy.promotion; import designPatterns.proxy.javaProxy.core.InvocationHandler; import java.lang.reflect.Method; /** * @author he_guitang * @version [1.0 , 2018/5/22] */ public class TimeHandler implements InvocationHandler { private Object object; public TimeHandler(Object object){ // super(); this.object = object; } @Override public void invokeMethod(Object o, Method method) { System.out.println("时间管理器开始......"); try { method.invoke(object);//反射的实现 } catch (Exception e) { e.printStackTrace(); } System.out.println("时间管理器结束......"); } }
Markdown
UTF-8
1,400
2.515625
3
[ "Apache-2.0" ]
permissive
# JaPNaASite v3 --- link: / tags: website, japnaa, site author: by JaPNaA shortDesc: Yes, this is the third time, and there come many changes. Good or not? We'll see. timestamp: 1562115496056 backgroundCSS: linear-gradient(169deg, #00e573, #00e5a8), #00e58e accent: #fd908b --- JaPNaASite revision 3. Yes. I've re-programmed my site 3 times now. Third times a charm! Maybe this is going to be my last revision, but I doubt it. It certainly is my biggest project, currently totaling over 10k lines of code, and 300+ commits. If the site doesn't turn out well, I can easily make this website a template for future websites, so I still get _something_ out of it. You also should have noticed by now, that this 'description' is much longer than the other projects. This is because I also created a new format for me to write about my projects, combining [markdown](https://en.wikipedia.org/wiki/Markdown) and the power of scripts to generate several .json files. Also, the change that I'm most excited about, <!img src=/Thingy_2019/0p/JaPNaASiteV3.png --"A screenshot of the landing page"> No, not that image. **THIS**. You see that?! I can have text **after** my images!! It's amazing! That reason was probably one of the biggest factors when considering this new format. That, and also being able to use markdown. <small> and also the old format was so bad... what was I thinking?! </small>
Shell
UTF-8
337
2.765625
3
[]
no_license
# Installation script for all the libraries mentioned in the repository # Made by Vishal Sharma (https://github.com/VishalSharma0309) #! /bin/bash # script to install ROS-melodic directly into a linux system # tested on Ubuntu 18.04.02 #use sudo to run this command if [ "$(id -u)" -ne 0 ] then echo "Must be root" exit fi
Python
UTF-8
3,413
2.640625
3
[]
no_license
import os import cv2 from tqdm import tqdm import imghdr import pickle class ImageDataset(object): def __init__(self, test_dir, train_dir, mode, config_dir): super(ImageDataset, self).__init__() self.test_dir = os.path.expanduser(test_dir) self.train_dir = os.path.expanduser(train_dir) self.mode = mode self.config_dir = os.path.expanduser(config_dir) self.testpaths = self.__load_files_from_dir(self.test_dir) self.trainpaths = self.__load_files_from_dir(self.train_dir) if len(self.testpaths) != len(self.trainpaths): raise Exception('The total numbers of test and train cases should be same!') def __is_txtfile(self, filepath): filepath = os.path.expanduser(filepath) return filepath[-4:] == '.txt' def __if_pfile(self, filepath): filepath = os.path.expanduser(filepath) return filepath[-2:] == '.p' def __load_files_from_dir(self, dirpath): datapaths = [] dirpath = os.path.expanduser(dirpath) for path in os.listdir(dirpath): if self.mode == 'txt' and self.__is_txtfile(path): datapaths.append(path) return datapaths def __str2list(self, data): data = list(data) temp = '' res = [] for item in data: if item == ' ': res.append(float(temp)) temp = '' elif item == '\n': continue else: temp += item return res def Data_loader(self): res = [] test = [] train = [] final = [] if self.mode == 'txt': pbar = tqdm(total = len(self.testpaths), desc = 'loading valid data(txt mode)...') for i in range(len(self.testpaths)): testpath = os.path.join(self.test_dir, self.testpaths[i]) trainpath = os.path.join(self.train_dir, self.trainpaths[i]) #read test data f = open(testpath) temp = f.readline() while temp: temp = self.__str2list(temp) res.append(temp) temp = f.readline() test.append(res) res = [] f.close() #read train data f = open(trainpath) temp = f.readline() while temp: temp = self.__str2list(temp) res.append(temp) temp = f.readline() train.append(res) res = [] f.close() pbar.update() pbar.close() #final[0] is test data, final[1] is train data final.append(test) final.append(train) config_dir = os.path.expanduser(self.config_dir) #save .p file under txt mode if os.path.exists(config_dir) == False: os.makedirs(config_dir) cpath = config_dir + '\\final.p' with open(cpath, 'wb') as file: pickle.dump(final, file) elif self.mode == 'p': cpath = self.config_dir with open(cpath, mode = 'rb') as file: final = pickle.load(file) return final
Java
UTF-8
1,829
2.1875
2
[]
no_license
/* * Copyright (C) 2011 NATSRL @ UMD (University Minnesota Duluth) and * Software and System Laboratory @ KNU (Kangwon National University, Korea) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package edu.umn.natsrl.weatherRWIS.datas; /** * * @author Soobin Jeon <j.soobin@gmail.com> */ public enum SurfaceType { Date("DtTm"), Temperature("Temperature"), Condition("Cond"), FrzTemp("FrzTemp"), Chemical("Chem"), ChemicalPct("ChemPct"), Depth("Depth"), IcePct("IcePct"); String cname; SurfaceType(String _cname){ cname = _cname; } public String getColumnName(){ return cname; } public boolean isTemperature(){return this == Temperature;} public boolean isCondition(){return this == Condition;} public boolean isFrzTemp(){return this == FrzTemp;} public boolean isChemical(){return this == Chemical;} public boolean isChemicalPct(){return this == ChemicalPct;} public boolean isDepth(){return this == Depth;} public boolean isIcePct(){return this == IcePct;} }
JavaScript
UTF-8
1,053
3.328125
3
[]
no_license
let answer; let output; let deflauts = { display_info: "1. You have to know speed of the conveyour which can be found on Scada", display_info2: "2. If you have a speed write it to field named 'speed' and press 'calculate'" } function calculation(){ var speed = parseInt(document.getElementById('speedField').value); if (speed && typeof(speed) === 'number' && (speed.toString().length >= 3 && speed.toString().length <=4)) { // let wynik = ((speed * 80) / 3600) wynik = wynik.toFixed(0) answer = { result: `The pulse shoud be set to ${wynik} ` } } else { console.log('Error') let error = "wrong input, you should type integer" answer = { result: error } } }; document.getElementById('submit').onclick = () =>{ calculation(); $('#result').text(answer.result); } const redrawText = () => { $('#display_info').text(deflauts.display_info); $('#display_info2').text(deflauts.display_info2); }; redrawText();
Python
UTF-8
233
4.0625
4
[]
no_license
def find_max(): input_number = input("Enter the numbers: ") numbers = list(input_number) max_number = numbers[0] for item in numbers: if item > max_number: max_number = item return max_number
Java
UTF-8
1,174
2.0625
2
[ "MIT" ]
permissive
package com.example.cubeplatformer; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button btnStartGame; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnStartGame = findViewById(R.id.buttonStart); btnStartGame.setOnClickListener(MainActivity.this); boolean isRetry = getIntent().getBooleanExtra("retry", false); if (isRetry) { btnStartGame.performClick(); } } @Override public void onClick(View v) { GameFragment gameFragment = new GameFragment(); FragmentManager fm = getSupportFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); transaction.replace(R.id.placeHolder, gameFragment); transaction.commit(); } }
Python
UTF-8
2,716
2.65625
3
[]
no_license
# -*- coding: utf-8 -*- import re from django.utils.encoding import smart_unicode class LenkerValidateService(object): """ Service used to validate the handlebars template objects """ def __init__(self, ident, source, **kwargs): self.preprocessors = kwargs.pop('preprocessors') if 'preprocessors' in kwargs else [] self.ident = ident self.source = self.preprocess(source) self.errors = set() self.error_msg = u'' def preprocess(self, source): for c in self.preprocessors: instance = c(source_source=source) source = instance.render({}) return source def rex_tag(self, tag_name): rex = re.compile(r"(?P<tag>\{\{\#%s (?P<tag_attribs>.*?)\}\}(?P<tag_contents>.*?)\{\{\/%s\}\}.*?)" % (tag_name, tag_name,), re.MULTILINE&re.IGNORECASE&re.DOTALL) return rex.findall(self.source) def gen_sets(self): tag_names = set() tag_ends = set() tag_name_rex = re.compile(r"\{\{\#(?P<tag_name>.*?) (?P<tag_attribs>.*?)\}\}") # remove doc_* start end_tag_rex = re.compile(r"\{\{\/(?P<end_tag_name>.*?)\}\}") # remove /doc_* end option_rex = re.compile(r"\{option\}") #rex = re.compile(r"(?P<tag>\{\{\#(?P<tag_name>.*?) (?P<tag_attribs>.*?)\}\}(?P<tag_contents>.*?)\{\{\/(?P<end_tag_name>.*?)\}\}.*?)", re.MULTILINE&re.IGNORECASE&re.DOTALL) for i in tag_name_rex.findall(self.source): tag_name, tag_attribs = i tag_names.add(tag_name) for tag_end in end_tag_rex.findall(self.source): tag_ends.add(tag_end) return (tag_names, tag_ends,) def validate(self): """ extract all of the {{#doc_var}}content{{/doc_var}} where doc_var is a doc_* tag """ is_valid = True # sets for comparison tag_names, tag_ends = self.gen_sets() # ensure that the sets are the same assert tag_names.issubset(tag_ends), 'Unclosed tags: %s' % ', '.join([name for name in tag_names]) # ensure all doc_selects have an options # NOT REQRUIED: as a doc select can have only 1 value.. # if 'doc_select' in tag_names: # doc_selects = self.rex_tag('doc_select') # for s in doc_selects: # tag, attribs, content = s # assert '{option}' in content, 'doc_select must contain at least 2 items seperated by "{option}", error at: %s' % attribs def is_valid(self): try: self.validate() except AssertionError as e: self.errors.add(e.message) self.error_msg += '; '.join(self.errors) return False return True
C#
UTF-8
1,792
3.34375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; namespace Train { class Program { static void Main(string[] args) { List<long> wagons = Console.ReadLine().Split().Select(long.Parse).ToList(); long maxPassgerInWagon = long.Parse(Console.ReadLine()); string commands = null; while ((commands = Console.ReadLine()) != "end") { string[] command = commands.Split().ToArray(); if(command[0] == "Add") { long passager = long.Parse(command[1]); AddNewWagon(wagons, passager, maxPassgerInWagon); } else if (long.TryParse(command[0], out long l)) { InsurtPassagerInWagon(wagons, l, maxPassgerInWagon); } } Console.WriteLine(string.Join(" ", wagons)); } private static void InsurtPassagerInWagon(List<long> wagons, long passager, long maxPassgerInWagon) { if (passager >= 0 && passager <= maxPassgerInWagon) { for (int i = 0; i < wagons.Count; i++) { long currentPassager = wagons[i]; if (passager + currentPassager <= maxPassgerInWagon) { wagons[i] = passager + currentPassager; break; } } } } private static void AddNewWagon(List<long> wagons, long passager, long maxPassgerInWagon) { if (passager >= 0 && passager <= maxPassgerInWagon) { wagons.Add(passager); } } } }
Java
UTF-8
1,179
2.09375
2
[]
no_license
/** * */ package com.giants.decorator.html.block; import com.giants.decorator.config.element.Block; import com.giants.decorator.core.Element; import com.giants.decorator.core.TemplateEngine; import com.giants.decorator.core.block.TemplateBlock; import com.giants.decorator.core.exception.TemplateException; import com.giants.decorator.core.exception.analysis.TemplateAnalysisException; import com.giants.decorator.html.HtmlTag; /** * @author vencent.lu * */ public abstract class HtmlTemplateBlock extends TemplateBlock { private static final long serialVersionUID = -1706346141871302752L; protected HtmlTag headTag; public HtmlTemplateBlock(TemplateEngine templateEngine, String key, Block blockConf, String blockTemplate) throws TemplateAnalysisException { super(templateEngine, key, blockConf, blockTemplate); } public HtmlTag getHeadTag() { return headTag; } public Element getHead() throws TemplateException { return this.getElement("tag:head"); } public Element getBody() throws TemplateException { return this.getElement("tag:body"); } }
JavaScript
UTF-8
5,211
3.03125
3
[]
no_license
/*-------------------- CURRENT DATE ----------------------*/ //const options = {weekday: 'long', day: 'numeric', month: 'long', year:'numeric'}; //document.getElementById('currentdate').textContent = new Date().toLocaleDateString('en-US', options); // day names array const dayNames = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; // Long month names array const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; const todaysdate = new Date(); const dayName = dayNames[todaysdate.getDay()]; const monthName = months[todaysdate.getMonth()]; const currentdate = dayName + ", " + todaysdate.getDate() + " " + monthName + " " + todaysdate.getFullYear(); // document.getElementById('currentDate').textContent = currentdate; document.getElementById("copyrightYear").innerHTML = todaysdate.getFullYear(); /*-------------------- HAMBURGER MENU ----------------------*/ const hambutton = document.querySelector('.ham'); const mainnav = document.querySelector('.navigation'); const closebutton = document.querySelector('.alertclose'); // hambutton.addEventListener('click', () => {mainnav.classList.toggle('responsive')}, false); // put back line above // To solve the mid resizing issue with responsive class on window.onresize = () => {if (window.innerWidth > 760) mainnav.classList.remove('responsive')}; /*-------------------- WEB FONT LOADER ----------------------*/ WebFont.load({google: {families: ['Goblin One', 'Raleway']}}); /*----------------------- API live weather data ----------------------*/ locationid = 'lat=47.6813&lon=-117.2827'; //millwood, wa // locationid = 'lat=47.135178&lon=-115.876603'; //fish hook test const apiURL = `https://api.openweathermap.org/data/2.5/onecall?${locationid}&exclude=minutely,hourly&units=imperial&appid=9d82d746ab9b4a97a81f74aae8a3582b`; fetch(apiURL) .then((response) => response.json()) .then((jsObject) => { console.log(jsObject); const currdesc = document.querySelector('#currdesc'); const humidity = document.querySelector('#humidity'); const curtemp = document.querySelector('#currtemp'); currdesc.innerHTML = jsObject.current.weather[0].description; curtemp.innerHTML = Math.round(jsObject.current.temp); humidity.innerHTML = jsObject.current.humidity; // let day = 0; // const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; // document.getElementById(`dayofweek${day+1}`).textContent = weekdays[d.getDay()+1]; // document.getElementById(`dayofweek${day+2}`).textContent = weekdays[d.getDay()+2]; // document.getElementById(`dayofweek${day+3}`).textContent = weekdays[d.getDay()+3]; // document.getElementById(`forecast${day+1}`).textContent = Math.round(jsObject.daily[1].temp.day); // document.getElementById(`forecast${day+2}`).textContent = Math.round(jsObject.daily[2].temp.day); // document.getElementById(`forecast${day+3}`).textContent = Math.round(jsObject.daily[3].temp.day); // for reference // const forecast = jsObject.list.filter(x => x.dt_txt.includes('18:00:00')); // const forecast = jsObject.daily.filter(x => x.dt); const forecast = jsObject.daily; let day=1; forecast.forEach(x => { const d = new Date(jsObject.daily[day].dt*1000); const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; console.log(`test: ${weekdays[d.getDay()]}`); document.getElementById(`dayofweek${day}`).textContent = weekdays[d.getDay()]; document.getElementById(`forecast${day}`).textContent = Math.round(x.temp.day); day++; }); // goes with for each // const weathericon = document.querySelector(`icon${day+1}`); // const imagesrc = 'https://openweathermap.org/img/w/' + jsObject.weather[0].icon + '.png'; //rather do string interpolation below instead // const isrc = `https://openweathermap.org/img/w/${forecast[day].weather[0].icon}.png`; // const desc = forecast[day].weather[0].description; //delete // reference end /*-------------------- WEATHER ALERT SECTION ----------------------*/ // const alertaway = document.querySelector('.alerts'); // alertaway.addEventListener('.alerts', () => { // styleMedia.display = 'none'; // }); // document.querySelector('.alerts').style.display = 'none'; // onclick="this.parentElement.style.display='none';" // onclick=this.style.display='none'; // document.getElementsByClassName('.btn').addEventListener('click',() => {this.parentElement.style.display='none'}); // if close button clicked, or no alerts available (= null?) // display: none // else display: block; // document.querySelector(".message").style.backgroundColor = "pink"; // document.querySelector(".message").style.visibility = "visible"; // document.querySelector(".alerts").style.display = "block"; // document.querySelector(".alerts").textContent = 'no alerts today'; // document.querySelector(".alertmessage").textContent = jsObject.alerts[0].description; // put back });
PHP
UTF-8
1,611
2.578125
3
[]
no_license
<?php require_once './core/init.php'; error_reporting(0); $id = (isset($_GET['id']) && is_numeric($_GET['id'])) ? (integer) $_GET['id'] : null; $mode = (isset($_GET['mode']) && is_string($_GET['mode'])) ? (string) $_GET['mode'] : null; $cant = (isset($_GET['cant']) && is_numeric($_GET['cant'])) ? (integer) $_GET['cant'] : null; $type = (isset($_GET['type']) && is_string($_GET['type'])) ? (string) $_GET['type'] : 'sync'; if ($id !== null && $mode !== null) { switch ($mode) { case Session::_INSERT_: Session::addFlower(FlowersModel::getFlowerById($id), $cant); break; case Session::_DELETE_: Session::removeFlower(FlowersModel::getFlowerById($id)); break; case Session::_REMOVE_: Session::removeCard(); break; default: break; } //Session::removeCard(); //print_r($_SESSION['flowers']); echo "<script type='text/javascript'>window.location.href='". getSessionReferer()."'</script>"; //header('Location: ' . getSessionReferer()); } function getSessionReferer() { $referer = ""; // isset determina si una variable está definida y no es NULL. if (isset($_SESSION['referrer'])) { $referer = $_SESSION['referrer']; } elseif (isset($_SERVER['HTTP_REFERER'])) { $referer = $_SERVER['HTTP_REFERER']; } else { $url = 'http'; if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { $url .= 's'; } $referer = $url . '://' . $_SERVER['SERVER_NAME']; } return $referer; }
C#
UTF-8
1,689
3.859375
4
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace DP { class DivisorGameClass { /// <summary> /// the idea is that the player playing will want to make it odd for the next player /// so if even number is there just subtract it by 1 if odd number is there /// reduce the number by 2 till you find a divisor and divide it by the number /// </summary> /// <param name="n"></param> /// <returns></returns> public bool DivisorGame(int n) { int turn = 0;//alice turn do { if (n == 2) { return true; } else if (n == 2 && turn == 1) { return false; } if (n % 2 == 0 && n > 1) { n--; } else if (n % 2 != 0) { for (int i = n - 2; i >= 1; i -= 2) { if (n % i == 0) { n -= i; break; } } } if(turn==0) { turn = 1;//bobs turn } else { turn = 0; } } while (n != 1); if(turn ==1) { return false; } return true; } } }
Java
UTF-8
1,529
2.4375
2
[]
no_license
package App.Class.Model; //Classe bean Pedido Produto //Autores: // Lucas Gabriel, // Nicollas Ramires // Braian Maidame // João Marcelo public class Pedido_Produto { private int quantidade; private String observações; private Pedido pedido; private Produto produto; private Funcionario funcionario; public Pedido_Produto() { } public Pedido_Produto(int quantidade, String observações, Pedido pedido, Produto produto, Funcionario funcionario) { this.quantidade = quantidade; this.observações = observações; this.pedido = pedido; this.produto = produto; this.funcionario = funcionario; } public int getQuantidade() { return quantidade; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } public String getObservações() { return observações; } public void setObservações(String observações) { this.observações = observações; } public Pedido getPedido() { return pedido; } public void setPedido(Pedido pedido) { this.pedido = pedido; } public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } public Funcionario getFuncionario() { return funcionario; } public void setFuncionario(Funcionario funcionario) { this.funcionario = funcionario; } }
Python
UTF-8
1,395
4.09375
4
[]
no_license
""" Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: 1. The left subtree of a node contains only nodes with keys less than the node's key. 2. The right subtree of a node contains only nodes with keys greater than the node's key. 3. Both the left and right subtrees must also be binary search trees. Example 1: Input: 2 / \ 1 3 Output: true Example 2: 5 / \ 1 4 / \ 3 6 Output: false Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value is 5 but its right child's value is 4. 1120 -> 1134 (ac) 99.73% """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def is_valid_bst(self, root: TreeNode): if not root: return True return self._dfs(root, -float("inf"), float("inf")) def _dfs(self, node : TreeNode, lower_bound, upper_bound): if not (node.val < upper_bound and node.val > lower_bound): return False valid = True if node.left: valid = valid and self._dfs(node.left, lower_bound, node.val) if not valid: return False if node.right: valid = valid and self._dfs(node.right, node.val, upper_bound) return valid
Java
UTF-8
484
2.234375
2
[]
no_license
package cbir.envi; import java.io.IOException; public class EnviFormatException extends IOException { private static final long serialVersionUID = 1L; public EnviFormatException() { super(); } public EnviFormatException(String message, Throwable cause) { super(message, cause); } public EnviFormatException(String message) { super(message); } public EnviFormatException(Throwable cause) { super(cause); } }
Python
UTF-8
865
2.84375
3
[]
no_license
import serial import time #mport winsound def open_port(): ser = serial.Serial('/dev/ttyUSB0', 115200) # o "COM12" en windows return ser def close_port(port): port.close() def read_buffer(port): if (port.in_waiting != 0): string = str(port.read(port.in_waiting)) string = string.replace("b'", "") string = string.replace("'", "") return string else: return 0 def main(): port = open_port() port.write("\r".encode("utf-8")) ini = time.time() fin = time.time() delta = fin-ini while(delta < 3): time.sleep(0.1) data = read_buffer(port) if data != 0: print(data) # if (buff != 0): # port.write("GV\r".encode("utf-8")) delta = time.time()-ini close_port(port) if __name__ == "__main__": main()
Python
UTF-8
876
2.609375
3
[]
no_license
import sys import os import time import wx class MainWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(650,500), style=wx.DEFAULT_FRAME_STYLE) self.Centre() icon = wx.Icon() icon.CopyFromBitmap(wx.Bitmap("nutrient_icon.jpg", wx.BITMAP_TYPE_ANY)) self.SetIcon(icon) filesize = os.path.getsize("settings.txt") if filesize == 0: frame = Settings(None, "Settings") else: self.Show(True) class Settings(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(400,400), style=wx.DEFAULT_FRAME_STYLE) self.Centre() panel = wx.Panel(self) #gridSizer = wx.GridSizer(5, 2, 5, 5) t1 = wx.TextCtrl(panel) self.Show(True) if __name__ == "__main__": app = wx.App(True) frame = MainWindow(None, "Nutrient") app.MainLoop()
C
UTF-8
2,346
4.09375
4
[]
no_license
//program to implement Linked list only Insertion #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; typedef struct node * NODE; NODE getnode(); NODE insert_first(int item,NODE head); void insert_end(int item,NODE head); NODE insert_pos(NODE head,int item,int pos); void display(NODE head); int main() { NODE head=NULL; int ch,item,ch_q,pos; do { printf("Press 1: INSERT FIRST\nPress 2 : INSERT END\nPress 3: INSERT POSITION\nPress 4: DISPLAY\n"); printf("Enter your choice :"); scanf("%d",&ch); switch(ch) { case 1: printf("Enter the Element:\n"); scanf("%d",&item); head=insert_first(item,head); break; case 2: printf("Enter the Element:\n"); scanf("%d",&item); insert_end(item,head); break; case 3: printf("Enter the Element and Position :\n"); scanf("%d %d",&item,&pos); head=insert_pos(head,item,pos); break; case 4: display(head); break; default: printf("Invalid choice."); }; printf("Do you want to continue(1/0)?\n"); scanf(" %d",&ch_q); }while(ch_q!=0); return 0; } NODE getnode() { NODE p; p=(NODE)malloc(sizeof(struct node)); if(p!=NULL) return p; else { printf("Memory could not be allocated.\n"); exit(0); } } NODE insert_first(int item,NODE head) { NODE p; p=getnode(); p->data=item; p->next=head; head=p; return head; } void insert_end(int item,NODE head) { if(head==NULL) { printf("Cannot Insert at the End (NO NODE).\n"); return; } NODE p,q; q=getnode(); q->data=item; p=head; while(p->next!=NULL) p=p->next; p->next=q; q->next=NULL; } NODE insert_pos(NODE head,int item,int pos) { NODE q,p,newn; p=NULL; int c=1; newn=getnode(); newn->data=item; newn->next=NULL; if(head==NULL) { if(pos==1) return newn; else { printf("Invalid Position.\n"); return head; } } if(pos==1) { newn->next=head; head=newn; return head; } else{ q=head; while(q!=NULL && c!=pos) { p=q; q=q->next; c++; } if(c==pos) { p->next=newn; newn->next=q; return head; } else { printf("Invalid position.\n"); return head; } } } void display(NODE head) { NODE p; if(head==NULL) { printf("List is Empty.\n"); return; } p=head; printf("Contents of List are :\n"); while(p!=NULL) { printf("%d\n",p->data); p=p->next; } }
C++
UTF-8
473
2.734375
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> int main() { std::ios::sync_with_stdio(false); std::cout.tie(NULL); std::cin.tie(NULL); int N; int K; std::cin >> N >> K; std::vector<int> v(N); for (int i = 0; i < N; i++) { std::cin >> v[i]; } int max = -99999; for (int i = 0; i < N - K + 1; i++) { int sum = 0; for (int j = i; j < i + K; j++) { sum += v[j]; } max = std::max(sum, max); } std::cout << max << "\n"; return 0; }
Java
UTF-8
944
3.890625
4
[]
no_license
package step10.ex02; public class Stack { private Object[] list = new Object[100]; int pos; public int push(Object value) { // 값을 맨 마지막에 넣는다. if (pos == list.length) return -1; list[pos++] = value; return 0; } public Object pop() { // 맨 마지막 값을 꺼낸다.(제거한다) if (pos == 0) return null; return list[--pos]; } public Object get() { // 맨 마지막 값을 꺼낸다.(제거하지 않는다) if (pos == 0) return null; return list[pos-1]; } public int size() { return pos; } public static void main(String[] args) { Stack stack = new Stack(); stack.push("0000"); stack.push("1111"); stack.push("2222"); stack.push("3333"); int len = stack.size(); for (int i = 0; i < len; i++) { System.out.println(stack.pop()); } System.out.println(stack.pop()); } }
Java
UTF-8
2,965
2.5
2
[ "MIT" ]
permissive
// Copyright (c) 2017 The Authors of 'JWTS for Java' // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.auth0.jwt.interfaces; import java.util.Date; import java.util.List; import java.util.Map; /** * The Payload class represents the 2nd part of the JWT, where the Payload value is hold. */ public interface Payload { /** * Get the value(s) of the "iss" claim, or null if it's not available. * * @return the Issuer value or null. */ List<String> getIssuer(); /** * Get the value(s) of the "sub" claim, or null if it's not available. * * @return the Subject value or null. */ List<String> getSubject(); /** * Get the value(s) of the "aud" claim, or null if it's not available. * * @return the Audience value or null. */ List<String> getAudience(); /** * Get the value of the "exp" claim, or null if it's not available. * * @return the Expiration Time value or null. */ Date getExpiresAt(); /** * Get the value of the "nbf" claim, or null if it's not available. * * @return the Not Before value or null. */ Date getNotBefore(); /** * Get the value of the "iat" claim, or null if it's not available. * * @return the Issued At value or null. */ Date getIssuedAt(); /** * Get the value of the "jti" claim, or null if it's not available. * * @return the JWT ID value or null. */ String getId(); /** * Get a Claim given it's name. If the Claim wasn't specified in the Payload, a NullClaim will be returned. * * @param name the name of the Claim to retrieve. * @return a non-null Claim. */ Claim getClaim(String name); /** * Get the Claims defined in the Token. * * @return a non-null Map containing the Claims defined in the Token. */ Map<String, Claim> getClaims(); }
PHP
UTF-8
9,415
2.765625
3
[]
no_license
<?php class Employer extends AppModel { public $validate = array( //従業員の苗字の文字数をチェック 'staff_family_name' => array( 'rule' => array('between', 1, 30), 'message' => '苗字を30字以内で入力してください。' ), //従業員の名前の文字数をチェック 'staff_first_name' => array( 'rule' => array('between', 1, 30), 'message' => '名前を30字以内で入力してください。' ), //従業員のふりがなの文字数をチェック 'staff_furigana' => array( 'rule' => array('between', 1, 60), 'message' => 'ふりがなを60字以内で入力してください。' ), //部署名の文字数をチェック 'staff_department' => array( 'rule' => array('between', 1, 50), 'message' => '部署名を50字以内で入力してください。' ), //ポストの文字数をチェック 'staff_position' => array( 'rule' => array('between', 1, 50), 'message' => 'ポストを30字以内で入力してください。' ), //従業員の電話番号の桁数をチェック 'staff_mobile' => array( 'rule' => array('between', 10, 11), 'message' => '電話番号の桁が正しくありません。' ), //従業員のメールの形式をチェック 'staff_email' => array( array( 'rule' => array('email'), 'message' => 'メールの形式が正確ではありません。' ), array( 'rule' => array('between', 1, 255), 'message' => 'メールを255字以内で入力してください。' ), array( 'rule' => array('checkMail'), 'message' => 'このメールはすでに登録されています。' ) ), //会社名の文字数をチェック 'name' => array( 'rule' => array('between', 1, 50), 'message' => '会社名を50字以内で入力してください。' ), //会社のURLをチェック 'url' => array( array( 'rule' => array('between', 1, 255), 'message' => 'URLを255字以内で入力してください。' ), array( 'rule' => 'url', 'message' => 'URLの形式が正しくありません。' ) ), //ユーザーネームをチェック 'login_id' => array( array( 'rule' => array('between', 1, 50), 'message' => 'ユーザー名を50字以内で入力してください。' ), array( 'rule' => 'checkLoginId', 'message' => 'このユーザー名が既に登録されています、変更してください。' ) ), //パスワードをチェック 'password' => array( array( 'rule' => array('between', 8, 16), 'message' => 'パスワードを8~16字以内で入力してください。' ), array( 'rule' => array('checkPassword'), 'message' => '半角英数字と_のみ記入できます。英数字それぞれ1種類以上含んでください。', ), array( 'rule' => array('sameCheck'), 'message' => '入力されたパスワードが一致していません。' ) ), 'password_confirm' => array( 'rule' => 'notBlank', 'message' => 'パスワードを8~16字以内で入力してください。' ), 'foundation_date' => array( 'rule' => 'notBlank', 'message' => '必ず選択してください' ), 'employee_amount' => array( 'rule' => 'notBlank', 'message' => '必ず選択してください' ), 'capital' => array( 'rule' => 'notBlank', 'message' => '必ず選択してください' ), 'indusrty' => array( 'rule' => 'notBlank', 'message' => '必ず選択してください' ), 'category' => array( 'rule' => 'notBlank', 'message' => '必ず選択してください' ), 'postcode' => array( 'rule' => 'notBlank', 'message' => '必ず選択してください' ), 'province' => array( 'rule' => 'notBlank', 'message' => '必ず選択してください' ), 'address1' => array( 'rule' => array('between', 1, 255), 'message' => 'error もう一度確認してください' ), 'address2' => array( 'rule' => array('between', 1, 255), 'message' => 'error もう一度確認してください' ), 'fax' => array( 'rule' => array('between', 10, 11), 'message' => 'error もう一度確認してください' ), 'tel' => array( 'rule' => array( //数字を検索 'numeric', array('between', 10, 11) ), 'message' => '数字だけ入力してください' ), 'email' => array( array( 'rule' => array('between', 1, 255), 'message' => 'error もう一度確認してください' ), array( 'rule' => 'email', 'message' => 'メールの形式が正確ではありません。' ), ) /*'old_password' => array( array( 'rule' => array('between',8,16), 'message' => 'パスワードを8~16字以内で入力してください。' ), array( 'rule' => 'oldPasswordCheck', 'message' => '古いパスワードが正しくありません。' ) )*/ ); public function checkMail($data) { $employer = $this->find('first', array('conditions' => array('staff_email' => $data))); if($employer){ return false; }else{ return true; } } public function checkLoginId($data) { $employer = $this->find('first', array('conditions' => array('login_id' => $data))); if($employer){ return false; }else{ return true; } } //パスワードの同一性チェックをする。 public function sameCheck($data) { $confirm = $this->data['Employer']['password_confirm']; $password = $this->data['Employer']['password']; if ($confirm == $password){ //$this->data['Employer']['password'] = md5($this->data['Employer']['password']); return true; }else{ return false; } } public function checkPassword($data) { #exit(var_dump($data)); $password = $data['password']; $strlen = strlen($password); $standard = '0123456789abcdefghijklmnopqrstuvwxyz_'; $numbers = '0123456789'; $characters = 'abcdefghijklmnopqrstuvwxyz'; $numberNum = 0; $characterNum = 0; for( $i = 0; $i < $strlen; $i++ ) { $char = substr( $password, $i, 1 ); $result = strpos($standard, $char); if($result === false){ return false; } $resultNumber = strpos($numbers, $char); if($resultNumber !== false){ $numberNum++; } $resultCharacter = strpos($characters, $char); if($resultCharacter !== false){ $characterNum++; } } if( $numberNum == 0 || $characterNum == 0 ){ return false; } return true; } /*public function oldPasswordCheck($data) { $confirm = $this->data['Employer']['password']; $password = $this->data['Employer']['old_password']; $this->data['Employer']['old_password'] = md5($this->data['Employer']['old_password']); if ($confirm == $password){ return true; }else{ return false; } }*/ /*public function login($data){ $loginId = $data['Employer']['login_id']; $password = md5($data['Employer']['password']); $employer = $this->find('first', array('conditions'=> array('Employer.login_id' => $loginId, 'Employer.password' => $password, 'Employer.delete_flag' => 0))); return $employer? true: false; }*/ public function beforeSave($options = array()){ $this->data['Employer']['password'] = Security::hash($this->data['Employer']['password'], null, true); return true; } public function index($data){ $employerId = $data['Employer']['id']; $id = $this->find('first', array('conditions' => array('Employer.id' => $employerId, 'Employer.delete_flag' => 0))); return $id? true: false; } } ?>
Python
UTF-8
167
3.265625
3
[]
no_license
a=int(input()) b=int(input()) c=int(input()) d=int(input()) if((abs(a-c)==1)and(abs(b-d)==2))or((abs(a-c)==2)and(abs(b-d)==1)): print('YES') else: print('NO')
Python
UTF-8
271
2.984375
3
[]
no_license
from PIL import Image from pylab import * import os os.chdir('C:\\Users\\蔡静静\\Desktop') im = array(Image.open('empire.jpg')) imshow(im) x = [100, 200, 300, 400] y = [50, 150, 250, 350] plot(x, y, '.') plot(x[:2], y[:2]) title('Plotting: "empire.jpg"') show()
C#
UTF-8
672
2.671875
3
[]
no_license
private EventWaitHandle asyncWait = new ManualResetEvent(false); private Timer abortTimer = null; private bool success = false; public void ReadFromTwitter() { abortTimer = new Timer(AbortTwitter, null, 50000, System.Threading.Timeout.Infinite); asyncWait.Reset(); input.BeginRead(buffer, 0, buffer.Length, InputReadComplete, null); asyncWait.WaitOne(); } void AbortTwitter(object state) { success = false; // Redundant but explicit for clarity asyncWait.Set(); } void InputReadComplete() { // Disable the timer: abortTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); success = true; asyncWait.Set(); }
Python
UTF-8
320
3.609375
4
[]
no_license
def nan_expand(times): empty = '\"\"' once = 'Not a NaN' more = 'Not a ' result = '' if times == 0: return empty elif times == 1: return once else: for x in range(1,times): result += more result += once return result print(nan_expand(0)) print(nan_expand(1)) print(nan_expand(2)) print(nan_expand(3))
PHP
UTF-8
1,028
2.8125
3
[]
no_license
<?php /** * @category Cnnb * @package Cnnb_Gtm * @author Cnnb * @copyright Copyright © CNNB All rights reserved. * * DataLayer Class * For providing product's data */ namespace Cnnb\Gtm\DataLayer\ProductData; /** * ProductProvider | DataLayer Class */ class ProductProvider extends ProductAbstract { /** * @param array $productProviders */ public function __construct( array $productProviders = [] ) { $this->productProviders = $productProviders; } /** * @return array */ public function getData() { $data = $this->getProductData(); $arraysToMerge = []; /** @var ProductAbstract $productProvider */ foreach ($this->getProductProviders() as $productProvider) { $productProvider->setProduct($this->getProduct())->setProductData($data); $arraysToMerge[] = $productProvider->getData(); } return empty($arraysToMerge) ? $data : array_merge($data, ...$arraysToMerge); } }
Markdown
UTF-8
4,395
2.625
3
[ "MIT" ]
permissive
--- comments: true date: 2010-04-03 23:24:13 layout: post slug: blunt-c-sharp-1-auto-shutdown title: 'Blunt C# (1): 自动关机' wordpress_id: 148 categories: - Programing tags: - blunt - C# - WinAPI --- 开始好好整理毕业设计的代码,在硬盘里找出很多以前写的C#代码,很多自己写的小应用都蛮有趣的,比如自动关机啊,修改系统变量啊,计算周年纪念日啊之类的无聊的小东西~ 想着最近博客也没有什么值得更新的内容,要不就贴一些以前的这些程序的傻傻的代码吧~ 所以这个blunt C-sharp(钝的C锋利LOL)系列的文章就是贴这些代码的,欢迎大家讨论代码的好坏~ 骂我的时候Arthur会加上"被骂的是过去的我"这个前提的~ hoho~ 今天是自动关机的那个程序~ 还是2009-1-18的时候在学长的电脑上用SharpDevelop写的。当时和他一起租房子住在外面,后来有段时间他快毕业了,出去找工作了,于是我每天一个人看动画看到睡着,因为租房子要省电费,所以电脑开通宵很心疼,所以就自己写了一个自动关机的程序,其他东西都不是关键,关键还是代码。当时是不知道哪里找来了一段关机的代码,是用C#调用winapi的其实~ 截图和代码都放在下面吧~ ![](/images/uploads/zb/2010-04-03_bluntcsharp_autoshutdown.png) 话说这个程序现在看起来体验很好,因为时间匹配的时候不会直接把电脑关了,而会出来一个提示框,提示框上倒数30秒(足够我从被窝里爬出来去点取消),如果没点取消就关机~ 哈哈。当时不知道怎么想的,这么一个需求还要自己写个程序~ 果然有热情! ```c# // 这个结构体将会传递给API。使用StructLayout(...特性,确保其中的成员是按顺序排列的,C#编译器不会对其进行调整。 [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct TokPriv1Luid { public int Count; public long Luid; public int Attr; } // 以下使用DllImport特性导入了所需的Windows API。 // 导入的方法必须是static extern的,并且没有方法体。调用这些方法就相当于调用Windows API。 [DllImport("kernel32.dll", ExactSpelling = true)] internal static extern IntPtr GetCurrentProcess(); [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok); [DllImport("advapi32.dll", SetLastError = true)] internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid); [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen); [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool ExitWindowsEx(int flg, int rea); // 以下定义了在调用WinAPI时需要的常数。这些常数通常可以从Platform SDK的包含文件(头文件)中找到 internal const int SE_PRIVILEGE_ENABLED = 0x00000002; internal const int TOKEN_QUERY = 0x00000008; internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; internal const int EWX_LOGOFF = 0x00000000; internal const int EWX_SHUTDOWN = 0x00000001; internal const int EWX_REBOOT = 0x00000002; internal const int EWX_FORCE = 0x00000004; internal const int EWX_POWEROFF = 0x00000008; internal const int EWX_FORCEIFHUNG = 0x00000010; // 通过调用WinAPI实现关机,主要代码再最后一行ExitWindowsEx,这调用了同名的WinAPI,正好是关机用的。 private static void DoExitWin(int flg) { bool ok; TokPriv1Luid tp; IntPtr hproc = GetCurrentProcess(); IntPtr htok = IntPtr.Zero; ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok); tp.Count = 1; tp.Luid = 0; tp.Attr = SE_PRIVILEGE_ENABLED; ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid); ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero); ok = ExitWindowsEx(flg, 0); } ``` 坦率的说我也不知道是哪里找来的这个代码,如果您看了,知道这个代码的原作者,也请告诉我,并不是我不尊重他,是我年少无知 = = 以上~
Java
UTF-8
1,359
2.0625
2
[ "LicenseRef-scancode-free-unknown", "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
package integration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static com.codeborne.selenide.Condition.attribute; import static com.codeborne.selenide.Condition.visible; import static com.codeborne.selenide.Selectors.byText; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.closeWebDriver; import static com.codeborne.selenide.Selenide.open; import static com.codeborne.selenide.WebDriverRunner.isChrome; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; final class MobileEmulationTest extends IntegrationTest { @BeforeEach void setUp() { assumeThat(isChrome()).isTrue(); closeWebDriver(); assertThat(System.getProperty("chromeoptions.mobileEmulation")).isNull(); System.setProperty("chromeoptions.mobileEmulation", "deviceName=Nexus 5"); } @AfterEach void tearDown() { if (isChrome()) { closeWebDriver(); System.clearProperty("chromeoptions.mobileEmulation"); } } @Test void canOpenBrowserInMobileEmulationMode() { open("https://selenide.org"); $(".main-menu-pages").find(byText("Javadoc")) .shouldBe(visible) .shouldHave(attribute("href", "https://selenide.org/javadoc.html")); } }
JavaScript
UTF-8
126
3.640625
4
[]
no_license
// Easy level 8 Kata // Return a number's opposite without using conditionals function opposite(number) { return -number; }
Python
UTF-8
139
4.125
4
[]
no_license
weight_kg = float(input("Please enter your weight (kg): ")) weight_pound = weight_kg * 2.2 print(f"The weight in pounds is {weight_pound}")
Java
UTF-8
931
4.28125
4
[]
no_license
import java.util.Scanner; class Rectangle{ double length, breadth; public void read(){ Scanner s = new Scanner(System.in); length = s.nextDouble(); breadth = s.nextDouble(); } public double getArea(){ return (length*breadth); } } public class RectangleCheck{ public static void main(String args[]){ Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); System.out.println("Enter length and breadth of Rectangle 1 : "); r1.read(); System.out.println("Enter length and breadth of Rectangle 2 : "); r2.read(); if(r1.getArea() == r2.getArea()) System.out.println("Area of both rectangles are equal! "); else{ if(r1.getArea() < r2.getArea()) System.out.println("Area of Rectangle 1 is smaller than the area Rectangle 2! "); else System.out.println("Area of Rectangle 1 is greater than the area Rectangle 2! "); } } }
Java
UTF-8
3,108
2.34375
2
[]
no_license
package net.shreygupta.doctoronthego.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import net.shreygupta.doctoronthego.DatabaseHelper; import net.shreygupta.doctoronthego.R; /** * A simple {@link Fragment} subclass. */ public class PatientSignUpFragment extends Fragment { private EditText first_name; private EditText last_name; private EditText email; private EditText password; private EditText con_password; private Button patient_signup_button; public PatientSignUpFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_patient_sign_up, container, false); first_name = v.findViewById(R.id.patient_reg_first_name); last_name = v.findViewById(R.id.patient_reg_last_name); email = v.findViewById(R.id.patient_reg_email); password = v.findViewById(R.id.patient_reg_password); con_password = v.findViewById(R.id.patient_reg_con_pass); patient_signup_button = v.findViewById(R.id.patient_reg_sign_up); return v; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { patient_signup_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { patient_signup(); } }); super.onActivityCreated(savedInstanceState); } private void patient_signup() { String a = first_name.getText().toString(); String b = last_name.getText().toString(); String c = email.getText().toString(); String d = password.getText().toString(); String e = con_password.getText().toString(); if (d.equals(e)) { DatabaseHelper db_h = new DatabaseHelper(getActivity()); Long id = db_h.patient_insert_Data(a, b, c, d); if (id <= 0) { Toast.makeText(getActivity(), "Signup Unsuccessful.", Toast.LENGTH_SHORT).show(); first_name.setText(""); last_name.setText(""); email.setText(""); password.setText(""); con_password.setText(""); } else { Toast.makeText(getActivity(), "Signup Successful.", Toast.LENGTH_SHORT).show(); first_name.setText(""); last_name.setText(""); email.setText(""); password.setText(""); con_password.setText(""); } } else { Toast.makeText(getActivity(), "Password Mismatch!", Toast.LENGTH_SHORT).show(); } } }
Java
UTF-8
1,361
2.5625
3
[]
no_license
package hu.neuron.java.core.dto; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class UserDTO implements Serializable { private static final long serialVersionUID = -1265516570893529965L; private Long id; private String userName; private String password; public UserDTO() { } public UserDTO(Long id, String userName, String password) { super(); this.id = id; this.userName = userName; this.password = password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public String toString() { return "UserDTO [id=" + id + ", userName=" + userName + ", password=" + password + "]"; } public static final class UserDTOMapper implements RowMapper<UserDTO> { public UserDTO mapRow(ResultSet rs, int rowNum) throws SQLException { UserDTO userDTO = new UserDTO(); userDTO.setId(rs.getLong("id")); userDTO.setUserName(rs.getString("name")); userDTO.setPassword(rs.getString("password")); return userDTO; } } }
Markdown
UTF-8
593
2.84375
3
[]
no_license
# Pygame: Army Tank Create Python Pygame with Tank shooter game in 4 main steps 1. Game have 3 main sprites: Tanks, bullets and Enemy. 2. Tank can move with pygame.key.get_pressed() to UP, DOWN, RIGHT, LEFT. 3. Tank can shoot bullets to enemy and its disappear when bullets hit. 4. Game will be over if tank hit enemy. Additional option of Army Tank shooter game: 1. Add some background 2. Add image of tank, enemy and bullet from https://opengameart.org/ I use image from https://opengameart.org/content/tank-pack-80 and https://www.pinterest.com/pin/361554676325299815/ for Background
SQL
UTF-8
4,804
3.484375
3
[]
no_license
-- ---------------------------- -- Table structure for SYS_USER -- ---------------------------- DROP TABLE "SYS_USER"; CREATE TABLE "SYS_USER" ( "USERID" VARCHAR2(32 BYTE) NOT NULL , "USERNAME" VARCHAR2(100 BYTE) , "PASSWORD" VARCHAR2(100 BYTE) , "NICKNAME" VARCHAR2(100 BYTE) , "EMAIL" VARCHAR2(50 BYTE) , "PHONE" VARCHAR2(20 BYTE) , "SEX" CHAR(1 BYTE) , "BIRTHDAY" DATE , "IDCARD" VARCHAR2(20 BYTE) , "TEL" VARCHAR2(20 BYTE) , "ADDRESS" VARCHAR2(100 BYTE) , "HOMETEL" VARCHAR2(20 BYTE) , "USERTYPE" CHAR(3 BYTE) , "UPDATETIME" DATE , "DEPARTID" VARCHAR2(32 BYTE) , "NOTE" VARCHAR2(1000 BYTE) , "UPDATEPER" VARCHAR2(32 BYTE) , "ORGANID" VARCHAR2(32 BYTE) , "CHECKSTATES" CHAR(1 BYTE) , "USERSTATES" CHAR(1 BYTE) , "JOBTYPE" CHAR(1 BYTE) , "EXECCODE" VARCHAR2(20 BYTE) ) TABLESPACE "VGUARD" LOGGING NOCOMPRESS PCTFREE 10 INITRANS 1 STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 BUFFER_POOL DEFAULT ) PARALLEL 1 NOCACHE DISABLE ROW MOVEMENT ; COMMENT ON COLUMN "USERID" IS '用户id'; COMMENT ON COLUMN "USERNAME" IS '账户'; COMMENT ON COLUMN "PASSWORD" IS '密码'; COMMENT ON COLUMN "NICKNAME" IS '用户名字'; COMMENT ON COLUMN "EMAIL" IS '用户邮箱'; COMMENT ON COLUMN "PHONE" IS '移动电话'; COMMENT ON COLUMN "SEX" IS '性别'; COMMENT ON COLUMN "BIRTHDAY" IS '出生日期'; COMMENT ON COLUMN "IDCARD" IS '身份证'; COMMENT ON COLUMN "TEL" IS '办公电话'; COMMENT ON COLUMN "ADDRESS" IS '家庭住址'; COMMENT ON COLUMN "HOMETEL" IS '家庭电话'; COMMENT ON COLUMN "USERTYPE" IS '用户类型(常量定义暂定:企业:ENT,政府:GOV,系统:SYS)'; COMMENT ON COLUMN "UPDATETIME" IS '更新时间'; COMMENT ON COLUMN "DEPARTID" IS '部门id'; COMMENT ON COLUMN "NOTE" IS '备注'; COMMENT ON COLUMN "UPDATEPER" IS '更新人'; COMMENT ON COLUMN "ORGANID" IS '机构/企业id'; COMMENT ON COLUMN "CHECKSTATES" IS '审核状态'; COMMENT ON COLUMN "USERSTATES" IS '用户状态1:正常2:删除'; COMMENT ON COLUMN "JOBTYPE" IS '职务类型(1局长2科长3执法员)'; COMMENT ON COLUMN "EXECCODE" IS '执法编号'; COMMENT ON TABLE "SYS_USER" IS '系统用户'; -- ---------------------------- -- Table structure for LK_ROLE_PRIV -- ---------------------------- DROP TABLE "LK_ROLE_PRIV"; CREATE TABLE "LK_ROLE_PRIV" ( "CONID" VARCHAR2(32 BYTE) NOT NULL , "ROLEID" VARCHAR2(32 BYTE) , "PRIVID" VARCHAR2(32 BYTE) , "OPERID" VARCHAR2(32 BYTE) ) TABLESPACE "DOUBLESAFE" LOGGING NOCOMPRESS PCTFREE 10 INITRANS 1 STORAGE ( INITIAL 786432 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 BUFFER_POOL DEFAULT ) PARALLEL 1 NOCACHE DISABLE ROW MOVEMENT ; COMMENT ON COLUMN "LK_ROLE_PRIV"."CONID" IS '主键'; COMMENT ON COLUMN "LK_ROLE_PRIV"."ROLEID" IS '角色主键'; COMMENT ON COLUMN "LK_ROLE_PRIV"."PRIVID" IS '菜单主键'; COMMENT ON COLUMN "LK_ROLE_PRIV"."OPERID" IS '操作ID'; COMMENT ON TABLE "LK_ROLE_PRIV" IS '角色权限中间表'; -- ---------------------------- -- Checks structure for table LK_ROLE_PRIV -- ---------------------------- ALTER TABLE "LK_ROLE_PRIV" ADD CONSTRAINT "SYS_C0027250" CHECK ("CONID" IS NOT NULL) NOT DEFERRABLE INITIALLY IMMEDIATE NORELY VALIDATE; ALTER TABLE "LK_ROLE_PRIV" ADD CONSTRAINT "SYS_C0027251" CHECK ("CONID" IS NOT NULL) NOT DEFERRABLE INITIALLY IMMEDIATE NORELY VALIDATE; - ---------------------------- -- Table structure for SYS_ROLE -- ---------------------------- DROP TABLE "SYS_ROLE"; CREATE TABLE "SYS_ROLE" ( "ROLEID" VARCHAR2(32 BYTE) NOT NULL , "ROLENAME" VARCHAR2(50 BYTE) , "NOTE" VARCHAR2(1000 BYTE) , "UPDATETIME" DATE , "UPDATEPER" VARCHAR2(32 BYTE) , "USERTYPE" CHAR(3 BYTE) , "ORGID" VARCHAR2(32 BYTE) , "ISMEMBER" CHAR(1 BYTE) , "USERLEVEL" CHAR(1 BYTE) ) TABLESPACE "DOUBLESAFE" LOGGING NOCOMPRESS PCTFREE 10 INITRANS 1 STORAGE ( INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645 BUFFER_POOL DEFAULT ) PARALLEL 1 NOCACHE DISABLE ROW MOVEMENT ; COMMENT ON COLUMN "SYS_ROLE"."ROLEID" IS '角色id'; COMMENT ON COLUMN "SYS_ROLE"."ROLENAME" IS '角色名称'; COMMENT ON COLUMN "SYS_ROLE"."NOTE" IS '备注'; COMMENT ON COLUMN "SYS_ROLE"."UPDATETIME" IS '更新时间'; COMMENT ON COLUMN "SYS_ROLE"."UPDATEPER" IS '更新人'; COMMENT ON COLUMN "SYS_ROLE"."USERTYPE" IS '用户类型(常量定义暂定:企业:ENT,政府:GOV,系统:SYS)'; COMMENT ON COLUMN "SYS_ROLE"."ORGID" IS '机构ID'; COMMENT ON COLUMN "SYS_ROLE"."ISMEMBER" IS '是否成员单位'; COMMENT ON COLUMN "SYS_ROLE"."USERLEVEL" IS '用户级别 0:厂区;1:车间/部门; 2:班组;3:其他'; COMMENT ON TABLE "SYS_ROLE" IS '角色表';
Python
UTF-8
622
3.078125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Jan 24 13:15:34 2017 @author: jb2428 """ import numpy as np import pandas as pd import string N = 100 L = np.random.choice([a for a in string.ascii_uppercase[:3]],size=(N,2),replace=True) L = pd.DataFrame(L,columns=['col1','col2']) L['fun1'] = list(map(lambda x, y: x+'.'+y,L['col1'], L['col2'])) print(L.head(n=6)) L['col3'] = np.random.randint(0,3,size=(N,1)) L['fun2'] = list(map(lambda x, y: (x not in ['B', 'C']) & (y==1.).item(), L['col1'], L['col3'])) L['fun3'] = L.apply(lambda x: (x['col1'] not in ['B', 'C']) & (x['col3']==1.), axis=1) print(L.head(n=6))
Markdown
UTF-8
863
2.53125
3
[]
no_license
<h1>ML Algorithms</h1> <h3>Decision Tree, Random Forest, Boosting Techniques (AdaBoost)</h3> <b>Course Number :</b> BITS F464 <b>Contributors : </b> <ul> <li>G V Sandeep</li> <li>Kushagra Agrawal</li> <li>Snehal Wadhwani</li> <li>Tanmaya Dabral</li> </ul> <h3>Instructions to use</h3> <ul> <li>Install the eclipse version directly and import the project directly into your workspace.</li> <li>OR go to Deliverable and then compile & run ID3.java </li> </ul> <h3>Comparison</h3> <table> <thead> <tr> <th></th> <th>ID3</th> <th>Random Forest</th> <th>AdaBoost</th> </tr> </thead> <tbody> <tr> <td>Running Time</td> <td>10 Seconds</td> <td>250 Seconds</td> <td>150 Seconds</td> </tr> <tr> <td>Accuracy</td> <td>81.32%</td> <td>83.45%</td> <td>84.6%</td> </tr> </tbody> </table> <p><b>Note :</b> Kindly view the ml-1.pdf for more details.</p>
Java
UTF-8
178
1.898438
2
[]
no_license
package epam.jmp.muha.service.inter; import epam.jmp.muha.entity.User; public interface IUserService { void save(User user); User findByUsername(String username); }
Python
UTF-8
2,865
3.0625
3
[]
no_license
def formula_for_single_coeff(coeff, x_in, y_in): temp = 0. temp += coeff[0] temp += coeff[1] * y_in temp += coeff[2] * x_in temp += coeff[3] * x_in * y_in return temp def formula_for_single_coeff_merger(coeff, x_in): temp = 0. x_in_sqd = x_in*x_in temp += coeff[0] + coeff[1] * x_in + coeff[2] * x_in_sqd + coeff[3] * x_in_sqd*x_in + coeff[4] * x_in_sqd * x_in_sqd temp = x_in / temp return temp def formula_for_single_coeff_degr(coeff, x_in, y_in): temp = 0. temp += coeff[0] temp += coeff[1] * y_in temp += coeff[2] * x_in temp += coeff[3] * x_in * y_in temp += coeff[4] * x_in * x_in temp += coeff[5] * x_in * x_in * y_in return temp def formula_for_uncertainty(coeff, z_c, x_in, y_in, z): temp = 0. x_in_sqd = x_in*x_in x_in_trd = x_in_sqd * x_in y_in_sqd = y_in*y_in y_in_trd = y_in_sqd * y_in temp += coeff[0] temp += coeff[1] * y_in temp += coeff[2] * y_in_sqd temp += coeff[3] * y_in_trd temp += coeff[4] * x_in temp += coeff[5] * x_in * y_in temp += coeff[6] * x_in * y_in_sqd temp += coeff[7] * x_in * y_in_trd temp += coeff[8] * x_in_sqd temp += coeff[9] * x_in_sqd * y_in temp += coeff[10] * x_in_sqd * y_in_sqd temp += coeff[11] * x_in_sqd * y_in_trd temp += coeff[12] * x_in_trd temp += coeff[13] * x_in_trd * y_in temp += coeff[14] * x_in_trd * y_in_sqd temp += coeff[15] * x_in_trd *y_in_trd return temp + z_c*(z-0.5)*( 1./(0.25*z + 0.25)) def formula_for_uncertainty_merger(coeff, x_in, y_in): temp = 0. x_in_sqd = x_in*x_in x_in_trd = x_in_sqd * x_in y_in_sqd = y_in*y_in y_in_trd = y_in_sqd * y_in temp = coeff[0] temp += coeff[1] * x_in temp += coeff[2] * y_in temp += coeff[3] * x_in_sqd temp += coeff[4] * y_in_sqd temp += coeff[5] * x_in_trd temp += coeff[6] * y_in_trd temp += coeff[7] * x_in * y_in temp += coeff[8] * x_in_sqd * y_in temp += coeff[9] * x_in * y_in_sqd return temp def formula_for_uncertainty_degr(coeff, z_c, x_in, y_in, z): temp = 0. x_in_sqd = x_in*x_in x_in_trd = x_in_sqd * x_in y_in_sqd = y_in*y_in y_in_trd = y_in_sqd * y_in temp += coeff[0] temp += coeff[1] * y_in temp += coeff[2] * y_in_sqd temp += coeff[3] * y_in_trd temp += coeff[4] * x_in temp += coeff[5] * x_in * y_in temp += coeff[6] * x_in * y_in_sqd temp += coeff[7] * x_in * y_in_trd temp += coeff[8] * x_in_sqd temp += coeff[9] * x_in_sqd * y_in temp += coeff[10] * x_in_sqd * y_in_sqd temp += coeff[11] * x_in_sqd * y_in_trd temp += coeff[12] * x_in_trd temp += coeff[13] * x_in_trd * y_in temp += coeff[14] * x_in_trd * y_in_sqd temp += coeff[15] * x_in_trd *y_in_trd return temp + z_c*(z-1.)*( 1./(0.25*z + 0.25))
Python
UTF-8
703
2.890625
3
[]
no_license
from qualifier.input_data import InputData import os if __name__ == "__main__": THIS_PATH = os.path.abspath(os.path.dirname(__file__)) directory = os.path.join(THIS_PATH, 'inputs') print(f'Optimal scores') for file_name in [ 'a.txt', # instant 'b.txt', # 26s 'c.txt', # 17s 'd.txt', # 2m09s 'e.txt', # instant 'f.txt', # 4s ]: input_data = InputData(os.path.join(directory, file_name)) score = 0 for car in input_data.cars: penalty = sum([street.time for street in car.path[1:]]) score += input_data.duration - penalty + input_data.bonus print(f'{file_name}: {score}')
C
UTF-8
1,568
3.046875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* test.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: adi-rosa <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/05 13:42:31 by adi-rosa #+# #+# */ /* Updated: 2019/02/05 13:45:47 by adi-rosa ### ########.fr */ /* */ /* ************************************************************************** */ #include <tenvv.h> static char *get_equal(char *name, char *value) { char *tmp; char *ret; ret = NULL; if (!(tmp = ft_strjoin(name, "="))) return (NULL); ret = ft_strjoin(tmp, value); ft_strdel(&tmp); return (ret); } static int envv_len(t_envv *envv) { int i; i = 0; while (envv) { i++; envv = envv->next; } return (i + 1); } char **tenvv_to_tab(t_envv *envv) { char **t; int i; i = 0; if (!envv || !(t = (char **)malloc(sizeof(char *) * envv_len(envv)))) return (NULL); while (envv) { if ((t[i] = get_equal(envv->name, envv->value))) i++; envv = envv->next; } t[i] = NULL; if (i == 0) { free(t); return (NULL); } return (t); }
PHP
UTF-8
567
3
3
[]
no_license
<?php interface WPNotify_RecipientFactory { /** * Create a new instance of a notification recipient. * * @param mixed $value Value of the recipient. * @param string $type Optional. Type of the recipient. Defaults to 'user'. * * @return WPNotify_Recipient */ public function create( $value, $type = 'user' ); /** * Whether the factory accepts a given type for instantiation. * * @param string $type Type that should be instantiated. * * @return bool Whether the factory accepts the given type. */ public function accepts( $type ); }
C++
UTF-8
723
2.84375
3
[]
no_license
// // Task.hpp // cpp-concurrency // // Created by Vladislav Voinov on 28.06.20. // #pragma once #include <future> #include <functional> #include "cpp-concurrency-lib/AbstractTask.hpp" namespace task { template<typename TaskType> class Task: public AbstractTask { using PackagedTask = std::packaged_task<TaskType()>; using Lambda = std::function<TaskType()>; private: PackagedTask _packed_task; public: Task(const Lambda& fn): AbstractTask(), _packed_task(fn) {} ~Task() {} Task& execute() override { _packed_task(); _is_done = true; return *this; } Task& operator ()() override { return execute(); }; std::future<TaskType> getFuture() { return _packed_task.get_future(); } }; }
C++
UTF-8
604
3.546875
4
[]
no_license
/*Program to make an array of ten nubers display sum of odd nubers and product of even numbers*/ #include<iostream.h> #include<conio.h> void main() { clrscr(); int x[10]; //Size of array int sum=0; float prod=1; for (int j=0;j<=9;j++) { cout<<"\nPlease enter number :"; cin>>x[j]; //accaeptance of element } for (int z=0;z<=9;z++) { if (x[z]%2==0) //if the number is even prod=prod*x[z]; if(x[z]%2!=0) //if the number is odd sum=sum+x[z]; } cout<<"\nSum of odd elements =="<<sum; cout<<"\nProduct of even elements =="<<prod; getch(); }
Markdown
UTF-8
1,117
4.40625
4
[]
no_license
# Min Stack [Leetcode](https://leetcode.com/problems/min-stack/) 題意: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. - push(x) -- Push element x onto stack. - pop() -- Removes the element on top of the stack. - top() -- Get the top element. - getMin() -- Retrieve the minimum element in the stack. 解題思路: ```java class MinStack { Stack<Integer> stack = new Stack<>(); Stack<Integer> mStack = new Stack<>(); public void push(int x) { stack.push(x); if (mStack.isEmpty() || mStack.peek() >= x) { mStack.push(x); } } public void pop() { if (!stack.isEmpty()) { int val = stack.pop(); if (!mStack.isEmpty() && val == mStack.peek()) { mStack.pop(); } } } public int top() { if (!stack.isEmpty()) { return stack.peek(); } return -1; } public int getMin() { if (!mStack.isEmpty()) { return mStack.peek(); } return -1; } } ```
Java
UTF-8
2,983
2.390625
2
[]
no_license
/* 1: */ package org.spacehq.mc.protocol.packet.ingame.server.scoreboard; /* 2: */ /* 3: */ import java.io.IOException; /* 4: */ import org.spacehq.packetlib.io.NetInput; /* 5: */ import org.spacehq.packetlib.io.NetOutput; /* 6: */ import org.spacehq.packetlib.packet.Packet; /* 7: */ /* 8: */ public class ServerUpdateScorePacket /* 9: */ implements Packet /* 10: */ { /* 11: */ private String entry; /* 12: */ private Action action; /* 13: */ private String objective; /* 14: */ private int value; /* 15: */ /* 16: */ private ServerUpdateScorePacket() {} /* 17: */ /* 18: */ public ServerUpdateScorePacket(String entry) /* 19: */ { /* 20:21 */ this.entry = entry; /* 21:22 */ this.action = Action.REMOVE; /* 22: */ } /* 23: */ /* 24: */ public ServerUpdateScorePacket(String entry, String objective, int value) /* 25: */ { /* 26:26 */ this.entry = entry; /* 27:27 */ this.objective = objective; /* 28:28 */ this.value = value; /* 29:29 */ this.action = Action.ADD_OR_UPDATE; /* 30: */ } /* 31: */ /* 32: */ public String getEntry() /* 33: */ { /* 34:33 */ return this.entry; /* 35: */ } /* 36: */ /* 37: */ public Action getAction() /* 38: */ { /* 39:37 */ return this.action; /* 40: */ } /* 41: */ /* 42: */ public String getObjective() /* 43: */ { /* 44:41 */ return this.objective; /* 45: */ } /* 46: */ /* 47: */ public int getValue() /* 48: */ { /* 49:45 */ return this.value; /* 50: */ } /* 51: */ /* 52: */ public void read(NetInput in) /* 53: */ throws IOException /* 54: */ { /* 55:50 */ this.entry = in.readString(); /* 56:51 */ this.action = Action.values()[in.readByte()]; /* 57:52 */ if (this.action == Action.ADD_OR_UPDATE) /* 58: */ { /* 59:53 */ this.objective = in.readString(); /* 60:54 */ this.value = in.readInt(); /* 61: */ } /* 62: */ } /* 63: */ /* 64: */ public void write(NetOutput out) /* 65: */ throws IOException /* 66: */ { /* 67:60 */ out.writeString(this.entry); /* 68:61 */ out.writeByte(this.action.ordinal()); /* 69:62 */ if (this.action == Action.ADD_OR_UPDATE) /* 70: */ { /* 71:63 */ out.writeString(this.objective); /* 72:64 */ out.writeInt(this.value); /* 73: */ } /* 74: */ } /* 75: */ /* 76: */ public boolean isPriority() /* 77: */ { /* 78:70 */ return false; /* 79: */ } /* 80: */ /* 81: */ public static enum Action /* 82: */ { /* 83:74 */ ADD_OR_UPDATE, REMOVE; /* 84: */ } /* 85: */ } /* Location: C:\Users\User\Desktop\spam.jar * Qualified Name: org.spacehq.mc.protocol.packet.ingame.server.scoreboard.ServerUpdateScorePacket * JD-Core Version: 0.7.0.1 */
Markdown
UTF-8
416
3.1875
3
[]
no_license
# Lab 5: BSTs, Time Formatting, and Queues Start a new notebook on your virtual machine, then complete the three parts of the lab: 1. practice with [binary search trees](part1.md) -- good prep for P2 2. convert [dates to strings](part2.md) -- will also need this for P2 3. learn about [queues](part3.md) -- a fast data structure for modifying beginning of list Have fun, and let us know if you have any questions!
Java
UTF-8
675
1.78125
2
[]
no_license
package com.funi.platform.lshc.service; import com.funi.platform.lshc.dto.WorkLogDto; import com.funi.platform.lshc.entity.sys.JobAccept; import com.funi.platform.lshc.entity.sys.JobLog; import java.util.List; /** * @author 3 */ public interface JobLogService { /** * 创建受理信息 * @param jobAccept * @return */ String createJobAccept(JobAccept jobAccept); /** * 创建日志明细 * @param jobLog */ void createJobLog(JobLog jobLog); /** * 修改当前状态 * @param jobAccept */ void modifyCurStatus(JobAccept jobAccept); List<WorkLogDto> findByServiceNum(String serviceNum); }
C++
UTF-8
553
2.59375
3
[]
no_license
#pragma once using namespace System; ref class Investment { public: Investment(); //set methods void setDate(String^); void setEpic(String^); void setBuyPrice(double); void setSellPrice(double); void setStopLoss(double); //get methods String^ getDate(); String^ getEpic(); double getBuyPrice(); double getSellPrice(); double getStopLoss(); // double computeSellPrice(); // double computereStopLoss(); private: double buyPrice ; double sellPrice; double stopLoss; String^ epic; String^ date; };
JavaScript
UTF-8
834
2.59375
3
[ "MIT" ]
permissive
const zlib = require('zlib') // for some reason plain writeHead refuses to dump all the header items // so we need to use setHead one by one function writeHead (remoteRes, res) { let { headers } = remoteRes Object.keys(headers).forEach(key => res.setHeader(key, headers[key])) res.writeHead(remoteRes.statusCode, remoteRes.statusMessage, remoteRes.headers) } // we won't care about deflate, br or quality, just do the minimum // and trust that both the browser and the server know what they do function modifyCompression (req, res) { let wasZip = /gzip/.test(res.headers['content-encoding']) let acceptEncoding = req.headers['accept-encoding'] let prefersZip = /gzip/.test(acceptEncoding) if (wasZip && prefersZip) { res.body = zlib.gzipSync(res.body) } } module.exports = { writeHead, modifyCompression }
Python
UTF-8
2,151
3.171875
3
[]
no_license
import psycopg2 import configparser from sql_queries import create_table_queries, drop_table_queries def create_connection(): """ - Read configuration to get database parameters - Connects to the Redshift database - Returns the connection and cursor """ # read configuration config = configparser.ConfigParser() #Normally this file should be in ~/.aws/credentials config.read_file(open('../aws/credentials.cfg')) DWH_DB = config.get("DWH","DWH_DB") DWH_PORT = config.get("DWH","DWH_PORT") DWH_DB_USER = config.get("DWH","DWH_DB_USER") DWH_DB_PASSWORD = config.get("DWH","DWH_DB_PASSWORD") DWH_ENDPOINT = config.get("RedShift","DWH_ENDPOINT") # connect to default database try: conn=psycopg2.connect(dbname= DWH_DB, host=DWH_ENDPOINT, port= DWH_PORT, user= DWH_DB_USER, password= DWH_DB_PASSWORD) except psycopg2.Error as e: print("Error: Could not make connection to the Redshift database") print(e) conn.set_session(autocommit=True) try: cur = conn.cursor() except psycopg2.Error as e: print("Error: Could not get curser to the Database") print(e) return cur, conn def drop_tables(cur): """ Drops each table using the queries in `drop_table_queries` list. """ for query in drop_table_queries: cur.execute(query) def create_tables(cur): """ Creates each table using the queries in `create_table_queries` list. """ for query in create_table_queries: cur.execute(query) def main(): """ - Establishes connection with the redshift database and gets a cursor to it. - Drops all the tables. - Creates all tables needed. - Finally, closes the connection. """ print("- Establishing connection") cur, conn = create_connection() print("- Dropping tables") drop_tables(cur) print("- Creating tables") create_tables(cur) print("- Closing connection") cur.close() conn.close() print("- All done") if __name__ == "__main__": main()
Markdown
UTF-8
2,183
3.53125
4
[]
no_license
# foobar-solns My solutions to googles old foobar challenges, lotta fun so far! Reduced questions: 1. make a string of primes concatenated one after the other till it has length i+5 then return the last 5 digits of the string 2. take a list of positive and negative integers, find the maximum product of their entries 3. If a knight is on square x_ij, what's the minimum number of moves to get to y_kl 4. given a list of integers find all tuples (x,y,z) st. x|y|z and the indices of x and z are less than or greater than y's respectively 5. given an integer n (that we can: add 1 to, subtract 1 from, or divide by 2) what's the smallest number of operations needed to reach 1 6. what's the probability of eric remembering anything to do with markov chains Deglazed solutions: 1. start with a few primes (2 to 31 in this case) and greedy primality testing (max length of string was only 10,000) 2. sort em, find a midpoint between positive and negative entries, if theres an odd number of negative entries make the last occuring negative number '1' and return the product of the list 3. look at a chessboard for a bit, write a terrible solution then remember good ol' [dijkstra](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm) 4. for each y count how many divisors it has preceeding it in the list and how many multiples following it, then for each y add to the total the product of y's divisor and multiples count (that's p|ab right there bb) 5. my fav! (love anything related to [collatz](https://en.wikipedia.org/wiki/Collatz_conjecture)) write down any 9 sequential integers and then their equivalence modulo 4 :) 6. This one is _really fun_ if you're a cowboy: * ignore the matrix structure of the input and try to create your own insane spaghetti solution (4 hours) * assume the Fraction lib pasta in python will not be as tasty as homemade (another 4 hours) * assume your very ugly bolognese code has rounding errors somewhere and scrap it all (repeat above 1.5 times or until pasta smells of burnt hair) * realize you're stirring your pasta with an old toothbrush (leased common mistake), swap it out for a spoon (least common multiple) and enjoy the rich lasagna
Java
UTF-8
1,585
2.125
2
[]
no_license
package com.share.model; import java.util.Arrays; /** * Created by max on 2016/11/22. */ public class CityVo { public String status; public String info; public String infocode; public String count; public Suggestion suggestion; public District[] districts; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String getInfocode() { return infocode; } public void setInfocode(String infocode) { this.infocode = infocode; } public String getCount() { return count; } public void setCount(String count) { this.count = count; } public Suggestion getSuggestion() { return suggestion; } public void setSuggestion(Suggestion suggestion) { this.suggestion = suggestion; } public District[] getDistricts() { return districts; } public void setDistricts(District[] districts) { this.districts = districts; } @Override public String toString() { return "CityVo{" + "status='" + status + '\'' + ", info='" + info + '\'' + ", infocode='" + infocode + '\'' + ", count='" + count + '\'' + ", suggestion=" + suggestion + ", districts=" + Arrays.toString(districts) + '}'; } }
JavaScript
UTF-8
228
2.515625
3
[]
no_license
var readfile = require('./helper.js') var fileName = 'sometext.txt' var fileName1 = 'test.txt' readfile(fileName).then((message) => { readfile(fileName1).then((message1) => { console.log(message); console.log(message1); }); });
Python
UTF-8
2,047
3.140625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Apr 24 19:22:21 2016 @author: covingtonjg Jessica Covington """ import numpy as np def jacobi(A, b, x_init, kmax, tol): n = len(A) y = np.zeros(n) y[:] = x_init[:] x = np.zeros(n) err = tol for k in range(kmax): for i in range(n): total = b[i] diagonal = A[i,i] if (abs(diagonal) < tol): print("diagonal too small") for j in range(n): if (j != i): total -= A[i,j]*y[j] x[i] = total / diagonal if (np.linalg.norm(x-y,np.inf) < err): return k, x y[:] = x[:] return k, x def gaussSeidel(A, b, x_init, kmax, tol): n = len(A) y = np.zeros(n) y[:] = x_init[:] x = np.zeros(n) err = tol for k in range(kmax): for i in range(n): total = b[i] diagonal = A[i,i] if (abs(diagonal) < tol): print("diagonal too small") for j in range(i): total -= A[i,j]*x[j] for j in range(i+1, n): total -= A[i,j]*y[j] x[i] = total / diagonal if (np.linalg.norm(x-y,np.inf) < err): return k, x y[:] = x[:] return k, x def SOR(A, b, x_init, w, kmax, tol): n = len(A) y = np.zeros(n) y[:] = x_init[:] x = np.zeros(n) err = tol for k in range(kmax): for i in range(n): total = b[i] diagonal = A[i,i] if (abs(diagonal) < tol): print("diagonal too small") for j in range(i): total -= A[i,j]*x[j] for j in range(i+1, n): total -= A[i,j]*x[j] x[i] = total/diagonal x[i] = w*x[i] + (1-w)*y[i] if (np.linalg.norm(x-y,np.inf) < err): return k, x y[:] = x[:] return k, x
C++
UTF-8
504
2.640625
3
[]
no_license
// Terry Lorber // tgl@rideside.net // U61244526 // MET CS341 // Fall 2009 // Maslanka // Homework #2 #include "Node.h" // class implemented Node::Node(const double& data, Node* link) : _user_data(data), _link(link) { }// Node void Node::set_data(const double& data) { _user_data = data; }// set_data void Node::set_link(Node* link) { _link = link; }// set_link double Node::data() const { return _user_data; }; Node* Node::link() { return _link; }; const Node* Node::link() const { return _link; };
JavaScript
UTF-8
922
2.90625
3
[]
no_license
const uniquePathsWithObstacles = (obstacleGrid) => { if (obstacleGrid[0][0] == 1) return 0; // 出发点就被障碍堵住 const m = obstacleGrid.length; const n = obstacleGrid[0].length; // dp数组初始化 const dp = new Array(m); for (let i = 0; i < m; i++) dp[i] = new Array(n); // base case dp[0][0] = 1; // 终点就是出发点 for (let i = 1; i < m; i++) { // 第一列其余的case dp[i][0] = obstacleGrid[i][0] == 1 || dp[i - 1][0] == 0 ? 0 : 1; } for (let i = 1; i < n; i++) { // 第一行其余的case dp[0][i] = obstacleGrid[0][i] == 1 || dp[0][i - 1] == 0 ? 0 : 1; } // 迭代 for (let i = 1; i < m; i++) { for (let j = 1; j < n; j++) { dp[i][j] = obstacleGrid[i][j] == 1 ? 0 : dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; // 到达(m-1,n-1)的路径数 };
Java
UTF-8
953
2.015625
2
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0" ]
permissive
package com.sequenceiq.cloudbreak.service.stack.flow; import java.util.List; import com.sequenceiq.ambari.client.AmbariClient; import com.sequenceiq.cloudbreak.domain.stack.Stack; import com.sequenceiq.cloudbreak.service.StackContext; public class AmbariStartupPollerObject extends StackContext { private String ambariIp; private List<AmbariClient> ambariClients; public AmbariStartupPollerObject(Stack stack, String ambariIp, List<AmbariClient> ambariClients) { super(stack); this.ambariIp = ambariIp; this.ambariClients = ambariClients; } public String getAmbariAddress() { return ambariIp; } public void setAmbariIp(String ambariIp) { this.ambariIp = ambariIp; } public Iterable<AmbariClient> getAmbariClients() { return ambariClients; } public void setAmbariClients(List<AmbariClient> ambariClient) { ambariClients = ambariClient; } }
Markdown
UTF-8
691
2.546875
3
[]
no_license
# Article L5213-21 Les associations ayant pour objet principal la défense des intérêts des bénéficiaires du présent chapitre peuvent exercer une action civile fondée sur l'inobservation des dispositions des articles L. 5213-7 et L. 5213-9 à L. 5213-12, lorsque cette inobservation porte un préjudice certain à l'intérêt collectif qu'elles représentent. **Nota:** **Liens relatifs à cet article** **Codifié par**: - Ordonnance 2007-329 2007-03-12 JORF 13 mars 2007 **Anciens textes**: - Code du travail - art. L323-8-7 (V) - Code du travail L323-8-7 V2 **Cite**: - Code du travail - art. L5213-7 (VD) - Code du travail L5213-7, L5213-9 à L5213-12
Java
UTF-8
381
1.835938
2
[]
no_license
package bookstoreapi.bookstoreapi.repository; import bookstoreapi.bookstoreapi.model.BookToCartItem; import bookstoreapi.bookstoreapi.model.CartItem; import org.springframework.data.repository.CrudRepository; /** * Created by @kmartin62 */ public interface BookToCartItemRepository extends CrudRepository<BookToCartItem, Long> { void deleteByCartItem(CartItem cartItem); }
Java
UTF-8
5,468
2.859375
3
[ "Apache-2.0" ]
permissive
package org.tinos.emotion.test; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import org.tinos.emotion.estimation.EmotionSample; import org.tinos.emotion.estimation.RatioMap; import org.tinos.emotion.estimation.imp.RatioMapImp; import org.tinos.emotion.ortho.fhmm.EmotionMap; import org.tinos.emotion.ortho.fhmm.imp.EmotionMapImp; import org.tinos.engine.analysis.Analyzer; import org.tinos.engine.analysis.imp.CogsBinaryForestAnalyzerImp; import org.tinos.view.obj.WordFrequency; public class EnvironmentTest{ public static void main(String[] argv) throws IOException { //init EmotionMap emotionMap = new EmotionMapImp(); emotionMap.initMotivationMap(); emotionMap.initNegativeMap(); emotionMap.initPositiveMap(); emotionMap.initTrendingMap(); emotionMap.initPredictionMap(); emotionMap.initDistinctionMap(); //get sentence String text = "关于成瘾性的戒除方式,上瘾在医学上普遍定义为一种具有精神依赖并长期导致健康危害性的行为。\r\n" + "关于成瘾的溯源有很多因素,其中最重要的是依赖。因为长期的依赖导致自身某种缺陷逐渐丧失而\r\n" + "对成瘾物体产生不可替代性。通过这个推论,可以初步来定义戒断瘾欲,最有效的方式是替代和引导。\r\n" + "替代物,本身也是有强烈制瘾性,和危害性,但是危害要小于原物。通过替代和强制减少剂量和精洗\r\n" + "脑教育,通过一个时间周期达到戒除。中间有戒断反应,需要观察。引导,是在对没有成瘾并属于易\r\n" + "感染群体进行教育和传授方式,提高群体的免疫力和排斥力。上瘾不是欲望。欲望是生物的应激性进\r\n" + "化的产物,是与生俱来的。上瘾是一种外力干涉造成的依赖。上瘾的级别有很多种。医学有相关严谨\r\n" + "的打分段,其中毒瘾大于烟瘾大于网瘾。最有效的戒除手段就是环境和生活方式的选择。很多时候\r\n" + "环境不是很美好,生活方式充满了隐患,人的精神会产生误差,这个时候受体为不稳定态,极易接触\r\n" + "成瘾源。当环境无法改变的时候,我们需要改变自己,选择一个愉悦的生活方式,进行自我心里疏导,\r\n" + "很容易排斥上瘾源。其中这些词汇是非常有价值的精神药物:自信,豁达,友善,分享 等等。\r\n" + "一些成瘾的受体,普遍有某种倾向: 奢靡,闭塞,强迫,空虚 等等。这里不是贬义,只是因为长期的环境\r\n" + "因素不是那么美好导致了一些思维误差。所以引导是非常重要的。改变人的不是能力,而是选择和环境。\r\n" + "如果环境不是很完美,那么选择一个健康的生活方式,是非常重要的。"; //parser sentence Analyzer analyzer = new CogsBinaryForestAnalyzerImp(); analyzer.init(); Map<String, Object> positive = emotionMap.getPositiveMap(); Map<String, Object> negative = emotionMap.getNegativeMap(); Map<String, Object> motivation = emotionMap.getMotivationMap(); Map<String, Object> trending = emotionMap.getTrendingMap(); Map<String, Object> prediction = emotionMap.getPredictionMap(); Map<String, Object> distinction = emotionMap.getDistinctionMap(); //map List<String> sets = analyzer.parserString(text); Map<Integer, WordFrequency> wordFrequencyMap = analyzer.getWordFrequencyByReturnSortMap(sets); RatioMap rationMap = new RatioMapImp(); Map<String, EmotionSample> emotionSampleMap = rationMap.getEmotionSampleMap(wordFrequencyMap, positive, negative); rationMap.getMotivation(emotionSampleMap, motivation); rationMap.getTrending(emotionSampleMap, trending); rationMap.getPrediction(emotionSampleMap, prediction); rationMap.getDistinction(emotionSampleMap, distinction); //reduce System.out.println("环 境:"); Iterator<String> Iterator = emotionSampleMap.keySet().iterator(); while(Iterator.hasNext()) { String word = Iterator.next(); EmotionSample emotionSample = emotionSampleMap.get(word); if(null != emotionSample.getDistinction()) { System.out.print(emotionSample.getDistinction()+" "); } } System.out.println(""); System.out.println("动 机:"); Iterator = emotionSampleMap.keySet().iterator(); while(Iterator.hasNext()) { String word = Iterator.next(); EmotionSample emotionSample = emotionSampleMap.get(word); if(null != emotionSample.getMotivation()) { System.out.print(emotionSample.getMotivation()+" "); } } System.out.println(""); System.out.println("倾 向:" ); Iterator = emotionSampleMap.keySet().iterator(); while(Iterator.hasNext()) { String word = Iterator.next(); EmotionSample emotionSample = emotionSampleMap.get(word); if(null != emotionSample.getTrending()) { System.out.print(emotionSample.getTrending()+" "); } } //reduce System.out.println(""); System.out.println("决 策:"); Iterator = emotionSampleMap.keySet().iterator(); while(Iterator.hasNext()) { String word = Iterator.next(); EmotionSample emotionSample = emotionSampleMap.get(word); if(null != emotionSample.getPrediction()) { System.out.print(emotionSample.getPrediction()+" "); } } } }
TypeScript
UTF-8
2,023
2.796875
3
[ "MIT" ]
permissive
import type { KeystoneConfig } from '../types'; import { idFieldType } from './id-field'; function applyIdFieldDefaults(config: KeystoneConfig): KeystoneConfig['lists'] { // some error checking for (const [listKey, list] of Object.entries(config.lists)) { if (list.fields.id) { throw new Error( `A field with the \`id\` path is defined in the fields object on the ${JSON.stringify( listKey )} list. This is not allowed, use the idField option instead.` ); } if (list.isSingleton && list.db?.idField) { throw new Error( `A singleton list cannot specify an idField, but it is configured at db.idField on the ${listKey} list` ); } } // inject ID fields const listsWithIds: KeystoneConfig['lists'] = {}; for (const [listKey, list] of Object.entries(config.lists)) { if (list.isSingleton) { // Singletons can only use an Int, idFieldType function ignores the `kind` if isSingleton is true listsWithIds[listKey] = { ...list, fields: { id: idFieldType( { kind: 'autoincrement', type: 'Int', }, true ), ...list.fields, }, }; continue; } listsWithIds[listKey] = { ...list, fields: { id: idFieldType(list.db?.idField ?? config.db.idField ?? { kind: 'cuid' }, false), ...list.fields, }, }; } return listsWithIds; } export function initConfig(config: KeystoneConfig) { if (!['postgresql', 'sqlite', 'mysql'].includes(config.db.provider)) { throw new TypeError( 'Invalid db configuration. Please specify db.provider as either "sqlite", "postgresql" or "mysql"' ); } // WARNING: Typescript should prevent this, but empty string is useful for Prisma errors config.db.url ??= 'postgres://'; // TODO: use zod or something if want to follow this path return { ...config, lists: applyIdFieldDefaults(config), }; }
JavaScript
UTF-8
245
2.640625
3
[ "MIT" ]
permissive
//+ Jonas Raoni Soares Silva //@ http://raoni.org function canConstruct(a) { // One rule that I could remember from childhood: a number is divisible by 3 if the sum of its digits is also divisible by 3 =] return a.reduce((t, c) => t += c) % 3 ? 'No' : 'Yes'; }
JavaScript
UTF-8
7,898
3.4375
3
[]
no_license
var date = [] var sku = [] var unitPrice = [] var quantity = [] var totalPrice = [] const totalData = {} getData(); async function getData() { const response = await fetch('sales-data.txt'); const data = await response.text(); const rows = data.split('\n').slice(1) const title = data.split('\n').slice(0,1)[0].split(',') for (var t of title) { t = t.split(" ")[0] totalData[t]=[] } console.log(title); rows.forEach((row) => { const rows = row.split(','); let index =0 for (var x in totalData) { let netvalue = Number(rows[index])?Number(rows[index]):rows[index] // console.log(netvalue,x, Number(rows[index]), Number(rows[index])); totalData[x].push(netvalue) index=index+1 } // date.push(rows[0]) // sku.push(rows[1]) // unitPrice.push(Number(rows[2])) // quantity.push(Number(rows[3])) // totalPrice.push(Number(rows[4])) }); date = totalData.Date sku = totalData.SKU quantity = totalData.Quantity unitPrice = totalData.Unit totalPrice = totalData.Total console.log(date); console.log(totalData); // console.log(date); // console.log(sku); // console.log(unitPrice); // console.log(quantity); // console.log(totalPrice); totalSales() monthWiseTotalSales() mostPopularItem() } // total sales function totalSales() { let total = 0; for (var i = 0; i < quantity.length -1; i++) { total += quantity[i] } document.getElementsByClassName('one')[0].innerHTML = total console.log("Total sales of the store:- " + total); } // monthly wise total sales function monthWiseTotalSales() { let jan = 0; let feb = 0; let mar = 0; for (var i = 0; i < date.length-1; i++) { if(date[i] >= "2019-01-01" && date[i] <= "2019-01-31"){ jan += quantity[i]; } if(date[i] >= "2019-02-01" && date[i] <= "2019-02-28"){ feb += quantity[i]; } if(date[i] >= "2019-03-01" && date[i] <= "2019-03-31"){ mar += quantity[i]; } } console.log("Total sales of the store in January :- " +jan); console.log("Total sales of the store in Febraury :- "+feb); console.log("Total sales of the store in March :-" +mar); document.getElementsByClassName('two')[0].innerHTML = jan document.getElementsByClassName('two')[1].innerHTML = feb document.getElementsByClassName('two')[2].innerHTML = mar } // popular item & top revenue item function mostPopularItem() { const filteredSkuArrayJan = [] const filteredSkuArrayFeb = [] const filteredSkuArrayMar = [] let jan = [] let feb = [] let mar = [] let janRevenue = [] let febRevenue = [] let marRevenue = [] let itemObjJan = {} let itemObjFeb = {} let itemObjMar = {} let revenueObjJan = {} let revenueObjFeb = {} let revenueObjMar = {} for (var i = 0; i < date.length-1; i++) { if(date[i] >= "2019-01-01" && date[i] <= "2019-01-31"){ itemObjJan[sku[i]] = itemObjJan[sku[i]]?itemObjJan[sku[i]]+quantity[i]:quantity[i] revenueObjJan[sku[i]] = revenueObjJan[sku[i]]?revenueObjJan[sku[i]]+totalPrice[i]:totalPrice[i] } if(date[i] >= "2019-02-01" && date[i] <= "2019-02-28"){ itemObjFeb[sku[i]] = itemObjFeb[sku[i]]?itemObjFeb[sku[i]]+quantity[i]:quantity[i] revenueObjFeb[sku[i]] = revenueObjFeb[sku[i]]?revenueObjFeb[sku[i]]+totalPrice[i]:totalPrice[i] } if(date[i] >= "2019-03-01" && date[i] <= "2019-03-31"){ itemObjMar[sku[i]] = itemObjMar[sku[i]]?itemObjMar[sku[i]]+quantity[i]:quantity[i] revenueObjMar[sku[i]] = revenueObjMar[sku[i]]?revenueObjMar[sku[i]]+totalPrice[i]:totalPrice[i] } } for (var x in itemObjJan) { jan.push(itemObjJan[x]) filteredSkuArrayJan.push(x) } for (var x in itemObjFeb) { feb.push(itemObjFeb[x]) filteredSkuArrayFeb.push(x) } for (var x in itemObjMar) { mar.push(itemObjMar[x]) filteredSkuArrayMar.push(x) } for (var x in revenueObjJan) { janRevenue.push(revenueObjJan[x]) } for (var x in revenueObjFeb) { febRevenue.push(revenueObjFeb[x]) } for (var x in revenueObjMar) { marRevenue.push(revenueObjMar[x]) } // find highest number in array const LargestNum = (input)=>{ let highNum =0; for (var i = 0; i < input.length; i++) { if(input[i]>highNum){ highNum = input[i] } } return highNum; } // console.log(LargestNum(jan),LargestNum(feb),LargestNum(mar),Math.min(...jan),Math.min(...feb),Math.min(...mar)); // console.log(jan.indexOf(LargestNum(jan)), feb.indexOf(LargestNum(feb)), mar.indexOf(LargestNum(mar))); const popularItemJan = filteredSkuArrayJan[jan.indexOf(LargestNum(jan))] const popularItemFeb = filteredSkuArrayFeb[feb.indexOf(LargestNum(feb))] const popularItemMar = filteredSkuArrayMar[mar.indexOf(LargestNum(mar))] const topRevenueJan = filteredSkuArrayJan[janRevenue.indexOf(LargestNum(janRevenue))] const topRevenueFeb = filteredSkuArrayFeb[febRevenue.indexOf(LargestNum(febRevenue))] const topRevenueMar = filteredSkuArrayMar[marRevenue.indexOf(LargestNum(marRevenue))] // populatItem each month console.log("Most popular item (most quantity sold) in each month:-" + popularItemJan, popularItemFeb, popularItemMar); document.getElementsByClassName('three')[0].innerHTML = popularItemJan; document.getElementsByClassName('three')[1].innerHTML = popularItemFeb; document.getElementsByClassName('three')[2].innerHTML = popularItemMar; // top reveune item each month console.log("Items generating most revenue in each month:-" + topRevenueJan, topRevenueFeb, topRevenueMar); document.getElementsByClassName('four')[0].innerHTML = topRevenueJan; document.getElementsByClassName('four')[1].innerHTML = topRevenueFeb; document.getElementsByClassName('four')[2].innerHTML = topRevenueMar; // min max & average of each month function janTotalItems() { let janCount=0 for (var j = 0; j < date.length-1; j++) { if(date[j] >= "2019-01-01" && date[j] <= "2019-01-31"){ if(filteredSkuArrayJan[jan.indexOf(LargestNum(jan))]==sku[j]){ janCount++ } } } return janCount } function febTotalItems() { let febCount=0 for (var j = 0; j < date.length-1; j++) { if(date[j] >= "2019-02-01" && date[j] <= "2019-02-28"){ if(filteredSkuArrayFeb[feb.indexOf(LargestNum(feb))]==sku[j]){ febCount++ } } } return febCount } function marTotalItems() { let marCount=0 for (var j = 0; j < date.length-1; j++) { if(date[j] >= "2019-03-01" && date[j] <= "2019-03-31"){ if(filteredSkuArrayMar[mar.indexOf(LargestNum(mar))]==sku[j]){ marCount++ } } } return marCount } const janMin = Math.min(...jan) const janMax = LargestNum(jan) const janAverage = LargestNum(jan)/janTotalItems() console.log("January Min, Max & Average Data:- " + janMin, janMax, janAverage); document.getElementsByClassName('five')[0].innerHTML = "Min :-" + janMin document.getElementsByClassName('five')[1].innerHTML = "Max :-" + janMax document.getElementsByClassName('five')[2].innerHTML = "Average :- " + janAverage const febMin = Math.min(...feb) const febMax = LargestNum(feb) const febAverage = LargestNum(feb)/febTotalItems() console.log("February Min, Max & Average Data:- " + febMin, febMax, febAverage); document.getElementsByClassName('five')[3].innerHTML ="Min :-" + febMin document.getElementsByClassName('five')[4].innerHTML ="Max :-"+ febMax document.getElementsByClassName('five')[5].innerHTML = "Average :-"+febAverage const marMin = Math.min(...mar) const marMax = LargestNum(mar) const marAverage = LargestNum(mar)/marTotalItems() console.log("March Min, Max & Average Data:- " + marMin, marMax, marAverage); document.getElementsByClassName('five')[6].innerHTML ="Min :-" + marMin document.getElementsByClassName('five')[7].innerHTML = "Max :-"+ marMax document.getElementsByClassName('five')[8].innerHTML = "Average :- "+ marAverage }
JavaScript
UTF-8
1,274
3.4375
3
[]
no_license
import React from "react"; class FilterString extends React.Component { constructor() { super(); this.solveToyProblem = this.solveToyProblem.bind(this); this.state = { unfilteredArray: [ "James", "Jessica", "Melody", "Tyler", "Blake", "Jennifer", "Mark", "Maddy" ], userInput: "", filteredArray: [] }; } solveToyProblem(input) { let names = this.state.unfilteredArray; let filteredNames = []; for (let i = 0; i < names.length; i++) { if (names[i].includes(input)) { filteredNames.push(names[i]); } } this.setState({ filteredArray: filteredNames }); } render() { return ( <div className='puzzleBox filterStringPB'> <h4>Filter Strings</h4> <span className='puzzleText'> Filtered Names: {this.state.unfilteredArray} </span> <input onChange={e => { this.setState({ userInput: e.target.value }); }} className='inputLine' /> <button onClick={() => this.solveToyProblem(this.state.userInput)} className='confirmationButton' > Enter </button> <span className='resultsBox filterStringRB'> FIltered: {JSON.stringify(this.state.filteredArray, null, 10)} </span> </div> ); } } export default FilterString;
Markdown
UTF-8
4,688
2.59375
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
# 5G 真的有宣传中的那么厉害吗?无人驾驶、智能家居、远程医疗等必须得有 5G 才能实现吗? Tags: **Science** > 5G 真的有宣传中的那么厉害吗?无人驾驶、智能家居、远程医疗等必须得有 5G 才能实现吗? 11.20看看: [中国移动吴彤:5G智能移动车载医疗应用解决行业两大痛点\_中国IDC圈](https://link.zhihu.com/?target=http%3A//app.idcquan.com/mobile.php%3Fcontentid%3D146162)尴尬不? 你们还真是聪明啊……还好意思冷嘲热讽。 比如,大群人在这攻击“在急救车上手术会晃”,还自以为很聪明“一针见血”。 **人家不知道停车下桩吗?** ![](https://pic2.zhimg.com/50/v2-47229a1969bcdca4ab90cb9e8bbaa484_hd.jpg?source=1940ef5c) ![](https://pic2.zhimg.com/50/v2-a683f6edd5eb17baec603df503380847_hd.jpg?source=1940ef5c) ![](https://pic4.zhimg.com/50/v2-7de25acdae68926499e2d34a71fb2f67_hd.jpg?source=1940ef5c)够不够稳? **谁说移动医疗是“边开车边开刀”这种形式?麻烦你们喷之前先去搞清楚自己在喷的是什么好吗?** 移动医疗的主要形式是**预约式的流动医疗服务!** 两三辆车作为一个医疗单元,提供一种检验/诊断/医疗服务,数十乃至上百组这样的小医疗单元为广大的不具备这种医疗条件的地县级地区提供高质量的诊疗服务,这才是移动医疗的基本样式。 建立起分布式、流动式的、覆盖数倍乃至数十倍区域的医疗服务,这才是移动医疗的主要价值。 说白了,你这个县养不起脑科医生,也养不起一个高级别的心胸外科……事实上可以说任何一种高级别的医疗服务你都养不起。不止你这个县,方圆几百里,得要到省城才开始有让人放心的医院和医生存在。对于中西部地区,西南地区,甚至省城都靠不住。 你以为光纤就便宜?高技术、高集成的流动医院使用高度规范的5G网络远比在千奇百怪的有线网络条件下的光纤来得敏捷。 甚至更加可靠! 5G流动医疗站可以同时连接四五个不同线路的基站信号,互为备份,无缝切换。 光纤你准备同时牵四五条不同线路的光纤专线吗?你知道三四条高保障、高优先的光纤专线月租多少钱吗? 如果你只牵一条光纤,解放路施工把光缆挖断了,你咋办? 以为“光纤一定比移动链接可靠”,其实是一种原始的幻觉,在实践中移动信号要比有线信号更能稳定保障——只要基站赋予你高优先级。 流动医疗中心只需要一个三十辆车的车队就能定期为若干地县城市提供全国乃至世界一流专家的直接服务,现场需要的却只是一群机械师、司机和护理士。每个月你都可以在你们县预约到价格便宜的一流手术机会。只需要你们县有能同时收到四个5G基站的停车场。 你以为这真的可以用“固定光纤”替代? 话说得丑一点——**把你们县医院卖了都凑不齐这十几个科目的远程光纤手术室,你们不跟隔壁十来个县——甚至跟隔壁省——共用,一般地区的医疗需求根本不可能承受得起这个成本!** **以你们的“光纤致胜论”,这方圆五百里的十来个县,就得每个县都要配十来个光纤手术室、十来组维护人员,十来组受过医疗和自动控制双重训练的医疗小组。** **看清楚——每个县都要配。** **你配得起?还是硬配起来看他们天天嗑瓜子?** 那怎么办?让全国这些老人们自费去宣武门外打地铺? 现在他们就在打地铺! 你们在这挑剔远程医疗这有问题那有问题,你们问过那些有点稍微麻烦点的病就要家里出两三个成人去省城脱产陪病人救命的家庭的意见吗? 你问过那些年年参加医疗下乡的医生们的意见吗?你有没有想过那些医生们手里拿着听诊器,心知肚明以眼前病人有机会接触的医疗资源几乎是死路一条时的心情? 对你们,是优劣问题,对人家,是**有无问题**。 对中西部的几亿县级以下城镇人口来说,这是有无问题,你们懂不懂? 有问题,那就想办法解决问题。看到了问题怕别人没考虑到于是提出来,也是在帮忙。这种优越傲慢,把支持5G远程医疗愿景的人群当蠢蛋看的心态,是什么鬼? 这是可以拿来榨取优越感的话题吗? 尤其是自以为找到的大堆所谓“死穴”,“致命问题”,自己真的有花点精力去核实一下资料和真实场景吗?
C++
UTF-8
1,275
2.953125
3
[]
no_license
#include <stdio.h> void exaple1(void); void exaple2(void); int main(void) { FILE *fp; int i; int data1 = 0; double data2 = 0.0; char ch; fp = fopen("data3.txt", "rt"); if (fp == NULL) { //printf("File Writing Error!\n"); puts("File Reading Error!"); return -1; } else{ puts("File Reading Success!"); } for (i = 0; i < 2; i++) { // ch = fgetc(fp); fscanf(fp, "%d", &data1); printf("%d \n", data1); } for (i = 0; i < 2; i++) { // ch = fgetc(fp); fscanf(fp, "%lf", &data2); printf("%lf \n", data2); } fclose(fp); return 1; } void exaple1(void) { FILE *fp; fp = fopen("data2.txt", "wt"); if (fp == NULL) { //printf("File Writing Error!\n"); puts("File Writing Error!\n"); return; } else{ puts("File Writing Success!\n"); } fputc('A', fp); //fprintf(fp, "%c", "A"); fputc('B', fp); fputc('C', fp); fputs("\nDEF\n", fp); printf("%d\n", fclose(fp)); return; } void exaple2(void) { FILE *fp; int i; char ch; fp = fopen("data2.txt", "rt"); if (fp == NULL) { //printf("File Writing Error!\n"); puts("File Reading Error!\n"); return; } else{ puts("File Reading Success!\n"); } for (i = 0; i < 7; i++) { // ch = fgetc(fp); fscanf(fp, "%c", &ch); printf("%c \n", ch); } fclose(fp); return; }
C++
UTF-8
2,010
3.8125
4
[]
no_license
//https://leetcode.com/problems/reverse-integer/description/ //Given a 32 - bit signed integer, reverse digits of an integer. // //Example 1 : // // Input : 123 // Output : 321 // Example 2 : // // Input : -123 // Output : -321 // Example 3 : // // Input : 120 // Output : 21 // Note : // Assume we are dealing with an environment which could only store integers within the 32 - bit signed integer range : [−231, 231 − 1].For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. #include <iostream> #include <math.h> #include <algorithm> #include<vector> #include<string> #include <queue> #include <stack> #include <list> #include <map> //hash table #include<unordered_map> #include <vector> using namespace std; class Solution2 { public: int reverse(int x) { int rev = 0; while (x != 0) { // if x >0, will not work on negative integer. int pop = x % 10; x /= 10; if (rev > INT_MAX / 10) { return 0; } if (rev < INT_MIN / 10) { return 0; } rev = rev * 10 + pop; } return rev; } }; class Solution { public: int reverse(int x) { long long res = 0; // must long , not int. while (x) { // pay attention on this part. res = res * 10 + x % 10; //-12 % 10 = -2 //-32*10 + (-1%10)=-320+(-1) x /= 10; //-12 / 10 = -1 // -1 / 10 = 0; } // 2*-3 = =6 //For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. return (res<INT_MIN || res>INT_MAX) ? 0 : res; /* 0 * 10 + (-123) % 10 res = 0 + (-3) = -3; */ } }; //does not work //class Solution3 { //public: // int reverse(int x) { // int ans = 0; // while (x > 0) { // x /= 10; // int temp = x % 10; // ans = ans * 10 + temp; // } // return ans; // } //}; int main() { /*Solution3 question;*/ /*question.reverse(123);*/ Solution question; question.reverse(-123); return 0; }
Markdown
UTF-8
2,832
2.96875
3
[]
no_license
--- layout: post title: "2015 South Davis Recap" date: 2015-11-22 16:44:00 author: Ethan Beseris image: /blog/2015-south-davis-recap-highlight.jpg --- It has been a hard three weeks of hard training since the Buff Invite, and it has certainly shown! On Saturday, November 14th, the Utes recorded their first win of the season against the Utah State Aggies. The competition was fierce, but Utah was able to top USU by a sizable margin of 147 points. * Combined Team Scores - Utah: 901 - USU: 754 * Women's Team Scores - Utah: 365 - USU: 310 * Men's Team Scores - Utah: 536 - USU: 444 We had a number of mentionable swims, including eight first-place finishes and six new team records. **First place finishers:** | Swimmer | Event | Time | |-----------------------|-------------------|-----------| | Al Jamora | Women's 1650 Free | 21:44.74 | | Megan Dearden | Women's 400 IM | 5:13.35 | | Al Jamora | Women's 50 Free | 26.41 | | Megan Dearden | Women's 200 Back | 2:24.67 | | Connor Morgan | Men's 200 Back | 2:09.69 | | Megan Dearden | Women's 50 Fly | 30.82 | | Melissa Hofmann | Women's 100 Free | 59.26 | | Ethan Beseris | Men's 200 IM | 2:17.10 | | Megan Dearden | Women's 200 Free | 2:11.47 | **New records:** | Swimmer | Event | Time | |-----------------------|-------------------|-----------| | Connor Morgan | Men's 50 Back | 26.91 | | Connor Morgan | Men's 200 Back | 2:09.69 | | Jeppesen Feliciano | Men's 200 Breast | 2:28.47 | | Megan Dearden | Women's 200 Free | 2:11.47 | | Megan Dearden | Women's 400 IM | 5:13.35 | Additionally, the men’s and women’s relays smashed the current team records. | Morgan, Feliciano, Beseris, Hise | Men’s 200 Medley Relay | 1:46.57 | | Dearden, Jamora, McMahon, Hofmann | Women’s 200 Free Relay | 1:50.73 | Of course, there were countless other incredible swims that the stats won’t show. The Utes are taking on a tough training regimen focused on refining stroke mechanics in the water and power lifting out of the water, not to mention the impending conclusion of the academic semester. Despite being fatigued, Utah was able to bring home a win against the Aggies, and we are looking better each day for the big meet in Atlanta. We would like to thank the South Davis Masters Team for hosting a great meet, and congratulate the Masters community on their swims this weekend. We would also like to recognize the incredibly competitive team from Utah State University, and thank them for a great meet this past weekend — we are looking forward to our season together. Stay tuned for the next Utah v. USU match-up in January! ![South Davis Team 2015]({{ site.image_url }}/blog/2015-south-davis-group.jpg)
C#
UTF-8
841
3.921875
4
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Numerics; namespace Large_sum { class Program { const string fileName = "100 50-digit numbers.txt"; static void Main(string[] args) { string[] numbers = Parse(); BigInteger sum = 0; foreach (string s in numbers) sum += BigInteger.Parse(s); string answer = sum.ToString().Substring(0, 10); Console.WriteLine(answer); Console.ReadLine(); } static string[] Parse() { StreamReader sr = new StreamReader(fileName); List<string> numbers = new List<string>(); while (!sr.EndOfStream) numbers.Add(sr.ReadLine()); return numbers.ToArray(); } } }
C#
UTF-8
2,428
2.953125
3
[]
no_license
using Sabio.Starter.Template.Web.Domain.Tests; using Sabio.Starter.Template.Web.Services.Interfaces; using System; using System.Collections.Generic; using System.Data.Entity.Core; using System.Linq; using System.Web; namespace Sabio.Starter.Template.Web.Services { public class EmployeeService : IEmployeeService { private List<TestEmployee> _data = new List<TestEmployee>(); private int _nextId = 1; public EmployeeService() { Add(new TestEmployee { FirstName = "Oscar", LastName = "De La Hoya", Dob = new DateTime(1972, 6, 15), Title = "Golden Boy", Status=1 }); Add(new TestEmployee { FirstName = "Floyd", LastName = "Mayweather", Dob = new DateTime(1976, 12, 1), Title = "Pretty Boy Floyd", Status = 1 }); Add(new TestEmployee { FirstName = "Manny", LastName = "Pacquiao", Dob = new DateTime(1979, 3, 31), Title = "Pac Man", Status=1 }); } public List<TestEmployee> GetAll() { return _data; } public TestEmployee Get(int id) { int index = id - 1; index = (index < 0) ? 0 : index; if (this._data.ElementAtOrDefault(index) != null) return this._data.ElementAt(index); throw new ObjectNotFoundException("could not locate employee with id " + id); } public TestEmployee Add(TestEmployee item) { if (item == null) { throw new ArgumentNullException("item"); } // TO DO : Code to save record into database item.Id = _nextId++; this._data.Add(item); return item; } public bool Update(TestEmployee item) { if (item == null) { throw new ArgumentNullException("item"); } // TO DO : Code to update record into database int index = this._data.FindIndex(p => p.Id == item.Id); if (index == -1) { return false; } this._data.RemoveAt(index); this._data.Add(item); return true; } public bool Delete(int id) { // TO DO : Code to remove the records from database this._data.RemoveAll(p => p.Id == id); return true; } } }
PHP
UTF-8
631
2.828125
3
[]
no_license
<?php function connectToDB(){ require 'dbconfig.php'; $hostname = DB_HOST; $username = DB_USER; $password = DB_PASSWORD; $dbname = DB_DATABASE; try{ $conn = new PDO( "mysql:host=$hostname;dbname=$dbname", $username, $password ); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } } ?>
Go
UTF-8
3,041
2.96875
3
[]
no_license
package lunar import ( "fmt" "reflect" "testing" ) func TestMove(t *testing.T) { tcs := []struct { sP Pos v Vel eP Pos }{ {sP: Pos{1, 2, 3}, v: Vel{-2, 0, 3}, eP: Pos{-1, 2, 6}}, } for _, tc := range tcs { got := move(tc.sP, tc.v) if got != tc.eP { t.Errorf("%v != %v", got, tc.eP) } } } func TestApplyGravity(t *testing.T) { tcs := []struct { Before []Moon Steps int After []Moon }{ { Before: []Moon{ Moon{P: Pos{-1, 0, 2}}, Moon{P: Pos{2, -10, -7}}, Moon{P: Pos{4, -8, 8}}, Moon{P: Pos{3, 5, -1}}, }, Steps: 1, After: []Moon{ Moon{P: Pos{2, -1, 1}, V: Vel{3, -1, -1}}, Moon{P: Pos{3, -7, -4}, V: Vel{1, 3, 3}}, Moon{P: Pos{1, -7, 5}, V: Vel{-3, 1, -3}}, Moon{P: Pos{2, 2, 0}, V: Vel{-1, -3, 1}}, }, }, { Before: []Moon{ Moon{P: Pos{-1, 0, 2}}, Moon{P: Pos{2, -10, -7}}, Moon{P: Pos{4, -8, 8}}, Moon{P: Pos{3, 5, -1}}, }, Steps: 10, After: []Moon{ Moon{P: Pos{2, 1, -3}, V: Vel{-3, -2, 1}}, Moon{P: Pos{1, -8, 0}, V: Vel{-1, 1, 3}}, Moon{P: Pos{3, -6, 1}, V: Vel{3, 2, -3}}, Moon{P: Pos{2, 0, 4}, V: Vel{1, -1, -1}}, }, }, } for _, tc := range tcs { ApplyGravity(tc.Before, tc.Steps) if reflect.DeepEqual(tc.Before, tc.After) == false { t.Errorf("\n%+v !=\n%+v", tc.Before, tc.After) } } } func TestTotalEnergy(t *testing.T) { tcs := []struct { Before []Moon Steps int Energy int }{ { Before: []Moon{ Moon{P: Pos{-1, 0, 2}}, Moon{P: Pos{2, -10, -7}}, Moon{P: Pos{4, -8, 8}}, Moon{P: Pos{3, 5, -1}}, }, Steps: 10, Energy: 179, }, { Before: []Moon{ Moon{P: Pos{-8, -10, 0}}, Moon{P: Pos{5, 5, 10}}, Moon{P: Pos{2, -7, 3}}, Moon{P: Pos{9, -8, -3}}, }, Steps: 100, Energy: 1940, }, } for _, tc := range tcs { ApplyGravity(tc.Before, tc.Steps) got := TotalEnergy(tc.Before) if got != tc.Energy { t.Errorf("%v != %v", got, tc.Energy) } } } func TestRepeatCount(t *testing.T) { tcs := []struct { Before []Moon Steps int Energy int }{ { Before: []Moon{ Moon{P: Pos{-1, 0, 2}}, Moon{P: Pos{2, -10, -7}}, Moon{P: Pos{4, -8, 8}}, Moon{P: Pos{3, 5, -1}}, }, Steps: 2772, }, { Before: []Moon{ Moon{P: Pos{-8, -10, 0}}, Moon{P: Pos{5, 5, 10}}, Moon{P: Pos{2, -7, 3}}, Moon{P: Pos{9, -8, -3}}, }, Steps: 4686774924, }, } for _, tc := range tcs { got := RepeatCount(tc.Before) if got != tc.Steps { t.Errorf("%v != %v", got, tc.Steps) } } } func TestPartOne(t *testing.T) { moons := []Moon{ Moon{P: Pos{14, 15, -2}}, Moon{P: Pos{17, -3, 4}}, Moon{P: Pos{6, 12, -13}}, Moon{P: Pos{-2, 10, -8}}, } ApplyGravity(moons, 1000) energy := TotalEnergy(moons) fmt.Println("Part One:", energy) } func TestPartTwo(t *testing.T) { moons := []Moon{ Moon{P: Pos{14, 15, -2}}, Moon{P: Pos{17, -3, 4}}, Moon{P: Pos{6, 12, -13}}, Moon{P: Pos{-2, 10, -8}}, } cycle := RepeatCount(moons) fmt.Println("Part Two:", cycle) }