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
2,127
3.0625
3
[]
no_license
#include <iostream> #include "InputManager.h" #include "SDL_events.h" InputManager* InputManager::instance = NULL; InputManager* InputManager::getInputManagerInstance(void) { if (instance == NULL) instance = new InputManager(); return instance; } bool InputManager::isKeyDown(const char* key) const { SDL_Scancode keyCode = SDL_GetScancodeFromName(key); return pressedKeys[keyCode]; } bool InputManager::isKeyDown(SDL_Scancode keyCode) const { return pressedKeys[keyCode]; } bool InputManager::isKeyUp(const char* key) const { return !isKeyDown(key); } bool InputManager::isKeyReleased(const char* key) const { SDL_Scancode keyCode = SDL_GetScancodeFromName(key); if (previousKeys[keyCode] && !pressedKeys[keyCode]) return true; else return false; } bool InputManager::isKeyPressed(const char* key) const { SDL_Scancode keyCode = SDL_GetScancodeFromName(key); return (!previousKeys[keyCode] && pressedKeys[keyCode]); } void InputManager::update() { SDL_Event e; while (SDL_PollEvent(&e)){ std::cout << e.type << std::endl; //TODO redirect this from here if (e.type == SDL_QUIT){ pressedKeys[SDL_SCANCODE_ESCAPE] = true; } else{ if (e.type == SDL_KEYDOWN){ previousKeys[e.key.keysym.scancode] = pressedKeys[e.key.keysym.scancode]; pressedKeys[e.key.keysym.scancode] = true; } else if (e.type == SDL_KEYUP){ previousKeys[e.key.keysym.scancode] = pressedKeys[e.key.keysym.scancode]; pressedKeys[e.key.keysym.scancode] = false; } } } } InputManager::InputManager() { for (int i = 0; i < SDL_NUM_SCANCODES; ++i){ pressedKeys[i] = false; previousKeys[i] = false; } std::cout << "InputManager Default Constructor()" << std::endl; } InputManager::InputManager(InputManager const&) { std::cout << "InputManager Copy Constructor()" << std::endl; } InputManager& InputManager::operator=(InputManager const&) { //TEMP - DON'T MIND THE WARNING InputManager inputManager; std::cout << "InputManager Assignment Operator()" << std::endl; return inputManager; } InputManager::~InputManager() { std::cout << "InputManager Destructor()" << std::endl; }
PHP
UTF-8
1,735
2.625
3
[ "MIT" ]
permissive
<?php namespace Retrowaver\Allegro\REST\Token\TokenManager; use Psr\Http\Message\ResponseInterface; use Retrowaver\Allegro\REST\Token\CredentialsInterface; use Retrowaver\Allegro\REST\Token\RefreshableTokenInterface; class RefreshableTokenManager extends BaseTokenManager implements RefreshableTokenManagerInterface { public function refreshToken( CredentialsInterface $credentials, RefreshableTokenInterface $token ): RefreshableTokenInterface { $request = $this->messageFactory->createRequest( 'POST', $this->getRefreshTokenUri($credentials, $token), $this->getBasicAuthHeader($credentials) ); $response = $this->client->sendRequest($request); $this->validateGetTokenResponse($request, $response, ['access_token', 'refresh_token', 'expires_in']); return $this->updateRefreshedTokenFromResponse($token, $response); } protected function getRefreshTokenUri( CredentialsInterface $credentials, RefreshableTokenInterface $token ) { return static::TOKEN_URI . "?" . http_build_query([ 'grant_type' => 'refresh_token', 'refresh_token' => $token->getRefreshToken(), 'redirect_uri' => $credentials->getRedirectUri() ]); } protected function updateRefreshedTokenFromResponse( RefreshableTokenInterface $token, ResponseInterface $response ): RefreshableTokenInterface { $decoded = json_decode((string)$response->getBody()); return $token ->setAccessToken($decoded->access_token) ->setRefreshToken($decoded->refresh_token) ->setExpiresIn($decoded->expires_in) ; } }
PHP
UTF-8
2,330
2.609375
3
[ "MIT" ]
permissive
<?php //start by including the scripts required for this page include_once 'classes/class.Company.php'; include_once 'classes/class.dbc.php'; include_once 'includes/functions.php'; //contains our filter function and other functions //initialise the database variable to use in the application $db = new dbc(); $dbc = $db->get_instance(); $day = date("d"); $month = date("m"); $year = date("Y"); $query = "SELECT * FROM `all_pictures` WHERE `day` = '$day' AND `month` = '$month' AND `year` = '$year' "; $result = mysqli_query($dbc, $query) or die("Could not get the plates"); //then include static html include_once 'includes/head.php'; ?> <!-- enter custom css files needed for this page here --> <?php include_once 'includes/top_bar.php'; //for the page title and logo and account information include_once 'includes/navigation.php'; //page navigations. ?> <br> <div class="wrapper"> <div class="container-fluid"> <?php //show errors here include_once 'includes/notifications.php'; ?> <div class="row"> <div class="col-md-12"> <div class="card-box"> <h2 class="page-header"> All Images Today </h2> <br> <div class="row"> <?php while ($row = mysqli_fetch_array($result) ) { ?> <div class="col-md-2"> <a href="<?php echo $row['file_path']; ?>" data-lightbox="<?php echo $row['file_path']; ?>"> <img src="<?php echo $row['file_path']; ?>" alt="" width="100px" height="100px"> </a> </div> <?php } ?> </div> </div> </div> </div> </div> <!-- end container --> </div> <!-- end wrapper --> <?php include_once 'includes/footer.php'; include_once 'includes/scripts.php'; ?> <!-- enter your custom scripts needed for the page here --> <?php include_once 'includes/end.php'; ?>
Markdown
UTF-8
3,718
3.65625
4
[ "MIT" ]
permissive
--- layout: post title: "[LeetCode 60] Permutation Sequence" comments: true category: Leetcode --- ### Question [link](http://oj.leetcode.com/problems/permutation-sequence/) <div class="question-content"> <p></p><p>The set <code>[1,2,3,…,<i>n</i>]</code> contains a total of <i>n</i>! unique permutations.</p> <p>By listing and labeling all of the permutations in order,<br> We get the following sequence (ie, for <i>n</i> = 3): </p><ol> <li><code>"123"</code></li> <li><code>"132"</code></li> <li><code>"213"</code></li> <li><code>"231"</code></li> <li><code>"312"</code></li> <li><code>"321"</code></li> </ol> <p></p> <p>Given <i>n</i> and <i>k</i>, return the <i>k</i><sup>th</sup> permutation sequence.</p> <p><b>Note:</b> Given <i>n</i> will be between 1 and 9 inclusive.</p><p></p> </div> ### Stats <table border="2"> <tr> <td>Frequency</td> <td bgcolor="white">1</td> </tr> <tr> <td>Difficulty</td> <td bgcolor="red">5</td> </tr> <tr> <td>Adjusted Difficulty</td> <td bgcolor="red">4</td> </tr> <tr> <td>Time to use</td> <td bgcolor="red">----------</td> </tr> </table> Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red) ### Analysis __This is a math problem__. Trying to solve it using __DFS__ like in "Permutation" or "N queen" will get time limit exceed exception. [This blog](http://fisherlei.blogspot.sg/2013/04/leetcode-permutation-sequence-solution.html) have a very good explanation of the math solution. <blockquote cite="http://fisherlei.blogspot.sg/2013/04/leetcode-permutation-sequence-solution.html"> <div> <br>[Thoughts] <br>两个解法。 <br>第一,DFS <br>递归遍历所有可能,然后累加计算,直至到K为止。 <br> <br>第二,数学解法。 <br> <br>假设有n个元素,第K个permutation是 <br>a1, a2, a3, ..... &nbsp; ..., an <br>那么a1是哪一个数字呢? <br> <br>那么这里,我们把a1去掉,那么剩下的permutation为 <br>a2, a3, .... .... an, 共计n-1个元素。 n-1个元素共有(n-1)!组排列,那么这里就可以知道 <br> <br>设变量K1 = K <br>a1 = K1 / (n-1)! <br> <br>同理,a2的值可以推导为 <br>a2 = K2 / (n-2)! <br>K2 = K1 % (n-1)! <br>&nbsp;....... <br>a(n-1) = K(n-1) / 1! <br>K(n-1) = K(n-2) /2! <br> <br>an = K(n-1) </div> </blockquote> ### Solution __I have written a math recursive solution__ and code is below. It's very straight-forward. There is also __direct math solution__. However, how to handle the removal of elements from the unmatched list is a tough problem. __I saw a lot of people using swap to do it__, but I don't like this idea because of the bad readability of code. __Finally I found a readable code from [this blog](http://xiaochongzhang.me/blog/?p=693)__. It's a very good solution. ### My code __updated on my birthday this year__ public String getPermutation(int n, int k) { int index = k - 1; List<Integer> nums = new ArrayList<Integer>(); for (int i = 1; i <= n; i++) { nums.add(i); } String ans = ""; for (int i = n - 1; i >= 1; i--) { int fact = factorial(i); int nextIndex = index / fact; index = index % fact; ans += nums.remove(nextIndex); } ans += nums.get(0); return ans; } private int factorial(int x) { if (x == 0) return 0; int ans = 1; for (int i = 2; i <= x; i++) { ans *= i; } return ans; }
Markdown
UTF-8
2,597
2.8125
3
[]
no_license
# Hello Vue.js 프로젝트 만들기 ## idnex.html 파일 생성 ``` <!DOCTYPE html> <html> <head> <title>Vue Sample</title> </head> <body> <div id="app"> {{ message }} </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.2/dist/vue.js"></script> <script> new Vue({ el: "#app", data: { message: 'Hello Vue.js!' } }) </script> </body> </html> ``` ![2021-04-03 04 53 16](https://user-images.githubusercontent.com/35294456/113449307-811a5c80-9438-11eb-87c8-5925dbd66369.png) ## 크롬 개발자 도구로 코드 확인하기 크롬 개발자 도구의 Console 패널로 살펴보면 로그를 통해 두 가지 로그를 확일할 수 있다. 첫번째 로그는 뷰 크롬 익스텐션을 다운로드 하라는 로그이고, 두번째 로그는 현재 개발자 모드에서 뷰를 실행하고 있으니 상용화된 서비스를 하는 경우에는 상용화 모드로 전환하라는 로그이다. ![2021-04-03 04 54 56](https://user-images.githubusercontent.com/35294456/113449406-bde65380-9438-11eb-8dd7-657516c6788a.png) ## 뷰 개발자 도구로 코드 확인하기 ### 첫 번째 로그 해결 방법 이 로그가 찍히는 것은 뷰 개발자 도구를 설치한 사용자에게 표시된다. 왜냐하면 현재 예제를 서버에서 띄운 것이 아니라 파일 시스템이 접근하여 브라우저로 실행했기 때문이다. 이를 해결하기 위해서는 크롬 확장 플러그인 설정을 변경해야 한다. **[도구 더보기 → 확장 프로그램]** 설치된 확장 플러그인 목록이 나오는데 뷰 개발자 도구의 세부정보를 클릭하여 '파일 URL에 대한 액세스 허용'을 활성화 시킨다. ![2021-04-03 05 03 40](https://user-images.githubusercontent.com/35294456/113449980-f6d2f800-9439-11eb-857f-11a036d99b99.png) ![2021-04-03 05 02 49](https://user-images.githubusercontent.com/35294456/113449947-e4f15500-9439-11eb-81b8-2c97d96098fb.png) index.html을 닫고 다시 실행하면 첫번째 로그가 사라지고 Vue 패널이 생긴 볼 수 있다. ![2021-04-03 05 04 23](https://user-images.githubusercontent.com/35294456/113450030-0eaa7c00-943a-11eb-839a-ba37e7a5c78b.png) Vue 패널을 클릭하고 '\<Root> = $vm0'을 클릭하면 Compoents에 대한 상세 내용이 나온다. 화면상 Hello Vue.js!는 최상위 컴포넌트의 data 속성인 message 값이다. ![2021-04-03 05 21 25](https://user-images.githubusercontent.com/35294456/113451191-6fd34f00-943c-11eb-8d48-35dd8bee95ea.png)
Markdown
UTF-8
7,331
2.671875
3
[ "GFDL-1.1-or-later", "MIT" ]
permissive
--- title: CoreCLR redirect_from: - /Moonlight2CoreCLR/ - /docs/advanced/coreclr/ --- Note: due to the circular nature of the definitions you'll need some prior knowledge of the CoreCLR security model **or** reading it twice to make sense out of this ;-) Security levels =============== The CoreCLR security model divide all code into three distinct levels: **transparent**, **safe-critical** and **critical**. This model is much simpler to understand (and implement) than [CAS](/docs/advanced/cas/) (e.g. no stack-walk). Only a few rules can describe much of it. Transparent ----------- By default all code is *transparent* under the CoreCLR model. - *Transparent* code is limited to what it can do. Specifically it cannot directly call **critical** code (e.g. p/invokes, unsafe code) but it can call *safe-critical* and other *transparent* code. - Since it's default there's no need to add a `[SecurityTransparent]` attribute everywhere. Safe Critical ------------- Safe critical code is a **gateway** between *transparent* and *critical* code. As such it represent the *riskiest* code (the less, the better). - Code needed to bridge a (safe) *transparent* API to (not necessarily safe) *critical* code needs to be decorated with `[SecuritySafeCritical]` attributes. - *Safe critical* code needs to make extra (pre and/or post) validations between the *transparent* and *critical* in order to make the call earn its **safe** prefix. Critical -------- Critical code can do anything, like p/invoking into native code and having access to everything outside the host browser. The plugin itself could not work without critical code. However applications can (and must) do without direct access to it. - Critical code, including every visible API that does things that application code should not do (e.g. file IO), must be marked with a `[SecurityCritical]` attribute. - All unsafe code, p/invoke declarations are **critical** (but still needs to be marked as such). Code categories =============== To make this even easier to understand, from an application developer point of view, all assemblies are split into two categories: the **application** (or user) code and the **platform** code. Application Code ---------------- Application code runs with *limited* trust. This makes it possible, along with other features, to safely run untrusted code inside your browser. Application code is bound by the following rules: - All *application* code is **transparent**. Using attributes to (try to) change this will compile but will be **ignored** at execution time. - As **transparent** it can call other *application* code (all transparent) and *platform* code that is **transparent** (default) or decorated with the `[SecuritySafeCritical]` attribute. - *Application* code cannot **directly** call `[SecurityCritical]` decorated methods/types present in *platform* code. Platform Code ------------- Platform code is a subset of the managed code provided with the plugin. This code is fully-trusted. As such it cannot expose all of its API to *application* code, instead it expose them using three different security levels (see next section). - *Platform* code is, by default, **transparent**. This means that most of it can be called directly from *application* code. - *Platform* code contains **critical** code - i.e. code that do anything (like p/invoking, unsafe code). Such code is decorated with `[SecurityCritical]` attributes and **cannot** be called from *application* code. - Access from **transparent** to **critical** code (e.g. using the safe, and transparent, IsolatedStorage that itself use the p/invoke, and critical, System.IO code) is possible thru code decorated with a `[SecuritySafeCritical]` attribute. Platform Code Assemblies includes: - mscorlib - Microsoft.VisualBasic [1][2] - System - System.Core - System.Net - System.Runtime.Serialization - System.ServiceModel [1][2] - System.ServiceModel.Web [1] - System.Windows - System.Windows.Browser - System.Xml [1] does not contain any [SecurityCritical] or [SecuritySafeCritical] attribute [2] has a different public key than the other assemblies Both [1] and [2] may be considered platform code - but since they don't (but, I guess, eventually could) use `[SecurityCritical]` nor `[SecuritySafeCritical]` they are in effect totally transparent (like application code). Where ? On Windows / Silverlight 2 the platform files can be found in: - C:\\Program Files\\Microsoft Silverlight\\2.0.31005.0 - C:\\Program Files\\Microsoft SDKs\\Silverlight\\v2.0\\Reference Assemblies The later only exists if you have the Silverlight 2 SDK installed. Application Developer Shortcut ============================== Just remember this: under the CoreCLR an *application* can call anything (i.e. **transparent** or **safe-critical**) as long as it is not **critical**. Special Considerations ====================== [InternalsVisibleTo] -------------------- Special care is needed wrt **internal** code since most of the **platform** assemblies include `[InternalsVisibleTo]` attributes - and yes, the internals are open to some **non-platform** (i.e. application code) assemblies. Reflection ---------- Reflection is possible but has some limitations. Reflection.Emit --------------- Code generation is possible (e.g. DLR) but also has some limitations. Policies -------- The *CoreCLR* security model does not deal with policies - its decisions are a boolean **CAN** or **CANNOT** do. While this works for the most basic parts it does not solve cases where more elaborate access rules are required, e.g.: - downloader policies - sockets policies Special care (outside the scope of *CoreCLR*) are needed to cover them. Implementation details ====================== Security Attributes Compatibility --------------------------------- Calls from **application code** to **platform code** (that Moonlight provides) either succeed (e.g. calling transparent or `[SecuritySafeCritical]` code) or fails (e.g. calling `[SecurityCritical]` code). Since there is **no** distinction from calling **transparent** or **safe critical** code our (Moonlight) `[SecuritySafeCritical]` attributes do not need to match Silverlight implementation. However we do have to match `[SecurityCritical]` attributes on the visible (public and protected) API. References ========== - [Introducing Microsoft Silverlight 1.1 Alpha](http://blogs.msdn.com/bclteam/archive/2007/04/30/introducing-microsoft-silverlight-1-1-alpha-justin-van-patten.aspx) by Justin Van Patten - [The Silverlight Security Model](http://blogs.msdn.com/shawnfa/archive/2007/05/09/the-silverlight-security-model.aspx), [Silverlight Security II: What Makes a Method Critical](http://blogs.msdn.com/shawnfa/archive/2007/05/10/silverlight-security-ii-what-makes-a-method-critical.aspx) and [Silverlight Security III: Inheritance](http://blogs.msdn.com/shawnfa/archive/2007/05/11/silverlight-security-iii-inheritance.aspx) by Shawn Farkas - [CLR Inside Out: Security In Silverlight2](http://msdn.microsoft.com/en-us/magazine/cc765416.aspx) by Andrew Dai - [Security Guidance for Writing and Deploying Silverlight Applications](http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=7cef15a8-8ae6-48eb-9621-ee35c2547773)
C++
UTF-8
296
3.046875
3
[]
no_license
#include <stdio.h> using namespace std; int main() { int s, v1, v2, t1, t2; scanf("%d %d %d %d %d", &s, &v1, &v2, &t1, &t2); int r1 = s * v1 + 2 * t1; int r2 = s * v2 + 2 * t2; if(r1 == r2) puts("Friendship"); if(r1 > r2) puts("Second"); if(r1 < r2) puts("First"); return 0; }
Python
UTF-8
19,998
2.734375
3
[ "MIT" ]
permissive
''' MIT License Copyright (c) 2021 Oz Mendelsohn 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. ''' import pandas as pd import numpy as np import subprocess as sp import os import shutil import time import petname import string import random import re pd.options.display.max_colwidth = 250 def unique_name(name_size=3, rand_size=4): """ Return a random easy to read name in string form ---------- name_size : int Number of random words rand_size : int Size of random string at the end of the name. Returns ------- unique_name: string the string of the unique name """ return petname.Generate(name_size, '-', 10) + '-' + \ ''.join([random.choice(string.ascii_letters + string.digits) for i in range(rand_size)]) def nodelist(): """ Get a pandas DataFrame object contain the utilization status of the nodes in the PBS cluster. _______ Returns ------- nodelist_DataFrame: :obj:pandas.DataFrame DataFrame with current utilization status of the nodes. column type: Type of the node. column: cores: column: status: The PBS status of the job: R - running, Q - waiting in the queue, S - suspended """ process = sp.Popen(['pbsnodes -av'], stdout=sp.PIPE, stderr=sp.PIPE, shell=True) out, err = process.communicate() lines, types, status, used_cores, cores, used_memory, mem = [], [], [], [], [], [], [] nodes_list = [] node = '' for l in out.splitlines(): l = l.decode('utf-8') node += l if l == '': nodes_list.append(node) node = '' for node in nodes_list: type_match = re.search(r'(\w\w\w)\d\d\d', node) cpu_match = re.search(r'resources_available.ncpus = (\w+)', node) used_cpu_match = re.search(r'resources_assigned.ncpus = (\w+)', node) mem_match = re.search(r'resources_available.mem = (\w+)kb', node) used_mem_match = re.search(r'resources_assigned.mem = (\w+)kb', node) status_match = re.search(r'state = ([a-z\-]+ [a-z]*)', node) if type_match and cpu_match and mem_match and status_match: type = type_match.group(1) total_cpu = int(cpu_match.group(1)) used_cpu = int(used_cpu_match.group(1)) total_mem = int(int(mem_match.group(1)) / 1024 / 1024) used_mem = int(int(used_mem_match.group(1)) / 1024 / 1024) node_status = status_match.group(1).strip() if node_status == 'free' and used_cpu != 0: node_status = 'partially free' types.append(type) status.append(node_status) cores.append(total_cpu) mem.append(total_mem) used_cores.append(used_cpu) used_memory.append(used_mem) df = pd.DataFrame(dict( type=types, cores=cores, used_cores=used_cores, memory=mem, used_memory=used_memory, status=status )) return df def jobs_status(): """ Get a pandas DataFrame object all of the current jobs on ChemFarm scheduler. _______ Returns ------- jobs_DataFrame: :obj:pandas.DataFrame DataFram with all the jobs and they status. column: job_id PBS ID number of the job column: user: User name of the user how submit the job column: status: The PBS status of the job: R - running, Q - waiting in the queue, S - suspended """ process = sp.Popen(['qstat'], stdout=sp.PIPE, stderr=sp.PIPE, shell=True) out, err = process.communicate() job_number, status, user = [], [], [] start = False for l in out.splitlines(): l = l.decode('utf-8') if '--' in l: start = True continue if start: part = l.split() job_number.append(part[0]) user.append(part[2]) status.append(part[4]) df = pd.DataFrame(dict( job_id=job_number, user=user, status=status, )) return df def pbs_file(execute_line, **pbs_kwargs): """ Create job submission file and return the name of the file. ---------- execute_line : str The line to run inside the jobs pbs_kwargs : dict Keyword for the configuration of the PBS job Keyword: path: str the path which the file is going to be made. name: str name of the job resources: dict dictionary with of the information of the requested resources for the job. resources keys: select: int: number of node for the jobs cpu: int: number of cpu for a given node. mem: str: size of the RAM for each node. node_type: str: the type/name of the node. ngpus: str: number of GPUs for the job walltime: str: the maximum running time of the job queue: str: the name of the job queue mail: str: mail address to send the PBS report log: str: name of the log file to save the output of the script. Returns ------- script path: string Path of the submission file. """ path = pbs_kwargs['path'] if 'path' in pbs_kwargs.keys() else '' name = pbs_kwargs['name'] if 'name' in pbs_kwargs.keys() else unique_name(2, 4) resources = pbs_kwargs['resources'] if 'resources' in pbs_kwargs.keys() else dict(select=1, ncpus=1, mem='10gb') resources = ':'.join([f'{k}={v}' for k, v in resources.items()]) queue = pbs_kwargs['queue'] if 'queue' in pbs_kwargs.keys() else 'sleep' mail = pbs_kwargs['mail'] if 'mail' in pbs_kwargs.keys() else None log_file = pbs_kwargs['log'] if 'log' in pbs_kwargs.keys() else name + '.log' file_text = '#!/bin/bash\n' \ f'#PBS -N "{name}"\n' \ f'#PBS -l {resources}\n' \ f'#PBS -q {queue}\n' if mail is not None: file_text += f'#PBS -M {mail}\n' \ f'#PBS -m ae\n' if 'walltime' in pbs_kwargs.keys(): walltime = pbs_kwargs['walltime'] file_text += f'PBS -l walltime={walltime}\n' # file_text += 'ulimit -s unlimited\n' file_text += 'cd $PBS_O_WORKDIR\n' file_text += 'set -e\n' file_text += 'JOBID=$( echo $PBS_JOBID | sed \'s/\.pbs01//\' )\n' file_text += 'JOBID=${JOBID%?};\n' file_text += 'JOBID=${JOBID%?};\n' file_text += 'JOBID=${JOBID%?};\n' file_text += 'JOBID=${JOBID%?};\n' # file_text += 'ulimit -s\n' file_text += 'source ~/.bash_profile\n' file_text += execute_line + '>>' + log_file + '\n' file_text += f'echo 1 > {name}.fin\n' full_name = path + name + '.pbs' with open(full_name, 'w') as f: f.write(file_text) return full_name def submit_static_job(execute_line, **pbs_kwargs): """ Get execute_line and pbs_kwargs and submit the jobs. ---------- execute_line : str The line to run inside the jobs pbs_kwargs : dict Keyword for the configuration of the PBS job Keyword: path: str the path which the file is going to be made. name: str name of the job resources: dict dictionary with of the information of the requested resources for the job. resources keys: select: int: number of node for the jobs cpu: int: number of cpu for a given node. mem: str: size of the RAM for each node. node_type: str: the type/name of the node. ngpus: str: number of GPUs for the job walltime: str: the maximum running time of the job queue: str: the name of the job queue mail: str: mail address to send the PBS report log: str: name of the log file to save the output of the script. Returns ------- job ID: string The job submission ID """ run_me = pbs_file(execute_line, **pbs_kwargs) print('running: {}'.format(run_me)) process = sp.Popen([f'qsub {run_me}'], stdout=sp.PIPE, stderr=sp.PIPE, shell=True) out, err = process.communicate() return out.decode('utf-8').strip() def submit_static_job_df(df: pd.Series): """ Get pandas.Series with execute_line and pbs_kwargs and submit a job. ---------- df: :obj:pandas.Series A line contain all the information for a submission of a single jobs submission columns: execute_line : str The line to run inside the jobs pbs_kwargs : dict Keyword for the configuration of the PBS job Keyword: path: str the path which the file is going to be made. name: str name of the job resources: dict dictionary with of the information of the requested resources for the job. resources keys: select: int: number of node for the jobs cpu: int: number of cpu for a given node. mem: str: size of the RAM for each node. node_type: str: the type/name of the node. ngpus: str: number of GPUs for the job walltime: str: the maximum running time of the job queue: str: the name of the job queue mail: str: mail address to send the PBS report log: str: name of the log file to save the output of the script. Returns ------- job ID: string The job submission ID """ execute_line = df['execute_lines'] parser_kwargs = df['parser_kwargs'] if type(df['parser_kwargs']) == dict else {} for k, v in parser_kwargs.items(): if isinstance(v, list): execute_line += ' --{} {}'.format(k, ' '.join(map(str, v))) else: execute_line += f' --{k}={v}' pbs_kwargs = df['pbs_kwargs'] if type(df['pbs_kwargs']) == dict else {} run_me = pbs_file(execute_line, **pbs_kwargs) print('running: {}'.format(run_me)) process = sp.Popen([f'qsub {run_me}'], stdout=sp.PIPE, stderr=sp.PIPE, shell=True) out, err = process.communicate() return out.decode('utf-8').strip() def jobs_dataframe(execute_lines, pbs_kwargs, parser_kwargs=None): """ Create a pandas.DataFrame from a list of execute_lines, pbs_kwargs and parser_kwargs (optional) ---------- execute_lines: list of str or str execution lines for all the jobs to be submitted. pbs_kwargs: list of dict or dict key words for the submission file of the jobs. for more details look at submit_static_job(). parser_kwargs: list of dict or dict (optional) A list of dictionaries for a python parser argument. Each attribute in the dictionary will bet added to the execution line in the following format: --key=parser_kwargs[key] Returns ------- jobs DataFrame: :obj: pandas.DataFrame jobs DataFrame ready for submission. """ if type(execute_lines) == str: if 'name' not in pbs_kwargs.keys(): names = [unique_name()] pbs_kwargs['name'] = names job_id, status = [''], [''] execute_lines = [execute_lines] pbs_kwargs = [pbs_kwargs] parser_kwargs = [parser_kwargs] if parser_kwargs is None: parser_kwargs = [dict()] else: names = [pbs_kwargs['name']] if type(execute_lines) == list: names = [] for i in range(len(execute_lines)): if 'name' not in pbs_kwargs[i].keys(): names.append(unique_name()) pbs_kwargs[i]['name'] = names[-1] else: names.append(pbs_kwargs[i]['name']) if parser_kwargs is None: parser_kwargs = [dict() for _ in range(len(execute_lines))] job_id = [''] * len(execute_lines) status = [''] * len(execute_lines) reset = [0] * len(execute_lines) return pd.DataFrame(dict( name=names, execute_lines=execute_lines, pbs_kwargs=pbs_kwargs, parser_kwargs=parser_kwargs, job_id=job_id, status=status)) def update_jobs_dataframe(job_df): """ Update the jobs status of each entry in the pandas.DataFrame. Each line is update according to it PBS job ID. ---------- jobs DataFrame: :obj: pandas.DataFrame jobs DataFrame with some of the line with job ID Returns ------- jobs DataFrame: :obj: pandas.DataFrame The update pandas.DataFrame with updated status. """ status_df = jobs_status() for i in range(len(job_df)): if len(status_df.loc[status_df['job_id'] == job_df.iloc[i]['job_id'], 'status'].values) > 0: job_df.loc[i, 'status'] = status_df.loc[status_df['job_id'] == job_df.iloc[i]['job_id'], 'status'].values[0] elif len(status_df.loc[status_df['job_id'] == job_df.iloc[i]['job_id'], 'status'].values) == 0: if job_df.loc[i, 'status'] == 'P': continue if job_df.loc[i, 'name'] + '.fin' in os.listdir(): job_df.loc[i, 'status'] = 'E' if job_df.loc[i, 'name'] + '.fin' not in os.listdir(): if job_df.loc[i, 'status'] == 'E': pass else: job_df.loc[i, 'status'] = 'F' return job_df def submit_over_df(df, max_queue=3, max_time=1000, wait_time=5, restart=0, dump=False, reset_callback=None): """ Submit jobs from a pandas.DataFrame while keeping number of jobs waiting in the queue smaller then max_queue*@ ---------- jobs DataFrame: :obj: pandas.DataFrame jobs subbmishing DataFrame max_queue: int (optional) max number of jobs to submitted at the same time. max_time: int (optional) A global time limiter for the submisstion loop. Time in hours. wait_time: int (optional) minimum time to wait between two sequential submission loop. Time in seconds. wait_time: int (optional) number of time to restart a failed job. Need the ".fin" flag for monitoring. dump: str (optional) If a string is provided a .json and .csv files are created which update for the jobs DataFrame. reset_callback: function (optional) a callback function that take the jobs Dataframe and job row index from update/print information after a the job is reset. """ t0 = time.time() max_time *= 60 * 60 for i in range(len(df)): df.loc[i, 'status'] = 'P' df.loc[i, 'pbs_kwargs']['path'] += df.loc[i, 'pbs_kwargs']['name'] + '/' if restart > 0: df.insert(len(df.columns) - 1, 'reset', [int(0)] * len(df)) while time.time() - t0 < max_time: # %% # Get current inforamtion about the jobs df = update_jobs_dataframe(df) n_Q = np.sum(df['status'].values == 'Q') n_P = np.sum(df['status'].values == 'P') n_R = np.sum(df['status'].values == 'R') n_E = np.sum(df['status'].values == 'E') n_F = np.sum(df['status'].values == 'F') print(f'jobs status: P:{n_P} Q:{n_Q} R:{n_R} E:{n_E} F:{n_F}') # %% # loop while more jobs in the queue then allowed while len(df.loc[df['status'] == 'Q']) >= max_queue: time.sleep(wait_time) df = update_jobs_dataframe(df) # dump the jobs datafram to readable file df = update_jobs_dataframe(df) if isinstance(dump, str): df.to_csv(f'{dump}.csv') df.to_json(f'{dump}.json') # clean file of finished / failed jobs time.sleep(wait_time) for i, row in df.loc[df['status'] == 'E', :].iterrows(): try: clean_up(row) except Exception as e: print(e) for i, row in df.loc[df['status'] == 'F', :].iterrows(): try: clean_up(row) except Exception as e: print(e) # move fails jobs to pending state if needed if restart > 0: reset_fails(df, n=restart, reset_callback=reset_callback) # %% # check if submission ended n_Q = np.sum(df['status'].values == 'Q') n_P = np.sum(df['status'].values == 'P') n_R = np.sum(df['status'].values == 'R') n_S = np.sum(df['status'].values == 'S') if n_Q + n_P + n_R + n_S == 0: break # %% # submit new pending jobs df_submission = df.loc[df['status'] == 'P', :][:max_queue] for i, row in df_submission.iterrows(): try: os.makedirs(row['pbs_kwargs']['path']) except FileExistsError: pass id = submit_static_job_df(row) print(f'job ID:{id}') df_submission.loc[df_submission['name'] == row['name'], 'job_id'] = id # add job id to the jobs dataframe df.update(df_submission) time.sleep(wait_time) df = update_jobs_dataframe(df) def clean_up(df: pd.Series): path = df['pbs_kwargs']['path'] name = df['pbs_kwargs']['name'] for file in os.listdir(): if name in file: if '.e' in file or '.o' in file or '.fin' in file or '.log' in file: shutil.move(file, path + file) def reset_fails(df, n=3, reset_callback=None): for i in range(len(df)): if df.loc[i, 'status'] == 'F' and df.iloc[i]['reset'] < n: df.loc[i, 'reset'] += 1 df.loc[i, 'status'] = 'P' if reset_callback is not None: df = reset_callback(df, i) name = df.loc[i, 'name'] print(f'restring: {name}')
C#
UTF-8
732
3.0625
3
[]
no_license
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace BooksStore.Models { public class Author : INameable { public Author() : this("", null) { } public Author(string name) => Name = name; public Author(string name, string description) : this(name) => Description = description; public int Id { get; set; } [DisplayName("Имя автора")] [Required(ErrorMessage = "У автора должно быть имя!")] public string Name { get; set; } [DisplayName("Описание автора")] public string Description { get; set; } public override string ToString() => Name; } }
Java
UTF-8
6,872
2.515625
3
[]
no_license
package glorioso.pep.model.control; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.jdbc.JdbcConnectionSource; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import com.j256.ormlite.support.ConnectionSource; import glorioso.pep.model.entity.Patient; public class PatientController { private String name; private String CPF; private String motherName; private String fatherName; private String address; private String neighborhood; private String birthPlace; private String zipCode; private String maritalStatus; private String birthDate; private String phoneNumber; private String gender; private List<Patient> patientList; private String errorLabel; public String insert() { String result = verifyPatient(this.name, this.CPF, this.zipCode, this.phoneNumber); System.out.println(result); if (result == "ok") { Patient p = this.genPatient(); try { ConnectionSource cs = new JdbcConnectionSource("jdbc:sqlite:pep.db"); Dao<Patient,Integer> pd = DaoManager.createDao(cs, Patient.class); QueryBuilder<Patient,Integer> qb = pd.queryBuilder(); Where<Patient,Integer> where = qb.where(); where.eq("CPF", p.getCPF()); List<Patient> existsPatient = where.query(); if (!existsPatient.isEmpty()){ errorLabel = "Ja existe esse usuario"; } else { pd.create(p); result = "confCadPacientes"; } cs.close(); } catch (SQLException e) { System.err.printf("Patient insert failed (%s)\n", e.toString()); e.printStackTrace(); errorLabel = "Erro no banco"; } } else { errorLabel = result; } System.out.println("O QUE ESTA RETORNANDO:" + result); return result; } public String read() { try { ConnectionSource cs = new JdbcConnectionSource("jdbc:sqlite:pep.db"); Dao<Patient,Integer> pd = DaoManager.createDao(cs, Patient.class); QueryBuilder<Patient,Integer> qb = pd.queryBuilder(); Where<Patient,Integer> where = qb.where(); int n = 0; if (this.name != "") { n++; where.eq("name", this.name); } if (this.CPF != "") { n++; where.eq("CPF", this.CPF); } if (this.motherName != "") { n++; where.eq("motherName", this.motherName); } if (this.fatherName != "") { n++; where.eq("fatherName", this.fatherName); } if (this.address != "") { n++; where.eq("address", this.address); } if (this.neighborhood != "") { n++; where.eq("neighborhood", this.neighborhood); } if (this.birthPlace != "") { n++; where.eq("birthPlace", this.birthPlace); } if (this.zipCode != "") { n++; where.eq("zipCode", this.zipCode); } if (this.maritalStatus != "") { n++; where.eq("maritalStatus", this.maritalStatus); } if (this.birthDate != "") { n++; where.eq("birthDate", this.birthDate); } if (this.phoneNumber != "") { n++; where.eq("phoneNumber", this.phoneNumber); } if (this.gender != "") { n++; where.eq("gender", this.gender); } if (n == 0) { patientList = pd.queryForAll(); } else { where.and(n); patientList = where.query(); } cs.close(); return "confReadPacients"; } catch (SQLException e) { System.err.printf("Patient read failed (%s)\n", e.toString()); e.printStackTrace(); return "error"; } } public String verifyPatient(String name, String cpf, String zipCode, String phoneNumber){ String result = "ok"; // if (name == ""){ // result = "Coloque um nome"; // } else if (cpf.length() != 11){ // result = "CPF Invalido"; // } else if (zipCode.length() != 8){ // result = "CEP Invalido"; // } else if (phoneNumber.length() != 11){ // result = "Telefone Invalido"; // } return result; } public List<Patient> getPatientList() { return this.patientList; } public Patient genPatient() { Patient p = new Patient(); p.setName(this.name); p.setCPF(this.CPF); p.setMotherName(this.motherName); p.setFatherName(this.fatherName); p.setAddress(this.address); p.setNeighborhood(this.neighborhood); p.setBirthPlace(this.birthPlace); p.setZipCode(this.zipCode); p.setMaritalStatus(this.maritalStatus); p.setBirthDate(this.birthDate); p.setPhoneNumber(this.phoneNumber); p.setGender(this.gender); return p; } public List<String> getGenders() { List<String> genVal = new ArrayList<String>(); genVal.add(new String("")); genVal.add(new String("Masculino")); genVal.add(new String("Feminino")); genVal.add(new String("Outro")); return genVal; } public List<String> getMaritalStatuss(){ List<String> msVal = new ArrayList<String>(); msVal.add(new String("")); msVal.add(new String("Solteiro(a)")); msVal.add(new String("Casado(a)")); msVal.add(new String("Viúvo(a)")); msVal.add(new String("Divorciado(a)")); return msVal; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCPF() { return CPF; } public void setCPF(String cpf) { CPF = cpf; } public String getMotherName() { return motherName; } public void setMotherName(String motherName) { this.motherName = motherName; } public String getFatherName() { return fatherName; } public void setFatherName(String fatherName) { this.fatherName = fatherName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getNeighborhood() { return neighborhood; } public void setNeighborhood(String neighborhood) { this.neighborhood = neighborhood; } public String getBirthPlace() { return birthPlace; } public void setBirthPlace(String birthPlace) { this.birthPlace = birthPlace; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getMaritalStatus() { return maritalStatus; } public void setMaritalStatus(String maritalStatus) { this.maritalStatus = maritalStatus; } public String getBirthDate() { return birthDate; } public void setBirthDate(String birthDate) { this.birthDate = birthDate; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getErrorLabel() { return errorLabel; } public void setErrorLabel(String errorLabel) { this.errorLabel = errorLabel; } public static boolean isNumeric(String str) { return str.matches("-?\\d+(.\\d+)?"); } }
C#
UTF-8
1,072
2.75
3
[ "Apache-2.0" ]
permissive
using System; using System.Net; namespace Gov.TicketSearch.Auth { [Serializable] public class OAuthException : Exception { public HttpStatusCode StatusCode { get; private set; } public string Response { get; private set; } public System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> Headers { get; private set; } public OAuthException(string message, HttpStatusCode statusCode, string response, System.Collections.Generic.IReadOnlyDictionary<string, System.Collections.Generic.IEnumerable<string>> headers, System.Exception innerException) : base(message + "\n\nStatus: " + statusCode + "\nResponse: \n" + response.Substring(0, response.Length >= 512 ? 512 : response.Length), innerException) { StatusCode = statusCode; Response = response; Headers = headers; } public override string ToString() { return $"HTTP Response: \n\n{Response}\n\n{base.ToString()}"; } } }
C++
UTF-8
5,531
3
3
[ "Apache-2.0" ]
permissive
#include "scopes.h" #include "symbols.h" namespace brutus { namespace internal { namespace syms { const float Scope::DefaultLoadFactor = 0.75f; Scope::Scope(int initialCapacity, float loadFactor, Arena* arena) : m_arena(arena), m_size(0), m_parent(nullptr) { int capacity = NextPow2(initialCapacity); m_loadFactor = loadFactor; m_threshold = static_cast<int>(static_cast<float>(capacity) * loadFactor); m_tableSize = capacity; } Scope::Scope(Arena* arena) : m_arena(arena), m_size(0), m_parent(nullptr), m_kind(ScopeKind::kUnknown) { m_loadFactor = DefaultLoadFactor; m_threshold = static_cast<int>(static_cast<float>(DefaultCapacity) * DefaultLoadFactor); m_tableSize = DefaultCapacity; } void Scope::init(Scope* parent, ScopeKind kind) { m_parent = parent; m_kind = kind; initTable(); } void Scope::initTable() { m_table = m_arena->newArray<Symbol*>(m_tableSize); ArrayFill(m_table, 0, m_tableSize); } bool Scope::contains(Name* name) { return get(name) != nullptr; } bool Scope::contains(Symbol* symbol) { return contains(symbol->name()); } Symbol* Scope::get(Name* name) { const int hashCode = name->m_hashCode; auto scope = this; do { const int keyIndex = indexOf(hashCode, scope->m_tableSize); Symbol* entry = scope->m_table[keyIndex]; while(entry != nullptr) { if(entry->m_name == name) { return entry; } entry = entry->m_next; } scope = scope->m_parent; } while(scope != nullptr); return nullptr; } bool Scope::put(Name* name, Symbol* symbol) { const int hashCode = name->m_hashCode; const int keyIndex = indexOf(hashCode, m_tableSize); Symbol* entry = m_table[keyIndex]; while(entry != nullptr) { if(entry->m_name == name) { return false; } entry = entry->m_next; } symbol->m_next = m_table[keyIndex]; m_table[keyIndex] = symbol; if(m_size++ >= m_threshold) { resize(2 * m_tableSize); } return true; } bool Scope::put(Symbol* symbol) { return put(symbol->name(), symbol); } Symbol* Scope::putOrOverload(Name* name, Symbol* symbol) { const int hashCode = name->m_hashCode; const int keyIndex = indexOf(hashCode, m_tableSize); Symbol* prev = nullptr; Symbol* next = m_table[keyIndex]; while(next != nullptr) { if(next->m_name == name) { if(next->kind() == SymbolKind::kOverload) { OverloadSymbol* overload = static_cast<OverloadSymbol*>(next); overload->add(symbol); return overload; } else { OverloadSymbol* overload = new (m_arena) OverloadSymbol(); overload->init(name, symbol->parent(), symbol->ast()); overload->m_next = next->m_next; if(prev != nullptr) { prev->m_next = overload; } overload->add(next); overload->add(symbol); return overload; } } prev = next; next = next->m_next; } symbol->m_next = m_table[keyIndex]; m_table[keyIndex] = symbol; if(m_size++ >= m_threshold) { resize(2 * m_tableSize); } return symbol; } void Scope::resize(int newSize) { auto oldTable = m_table; auto oldSize = m_tableSize; if(oldSize == MaximumCapacity) { m_threshold = std::numeric_limits<int>::max(); return; } Symbol** newTable = m_arena->newArray<Symbol*>(newSize); ArrayFill(newTable, 0, newSize); transfer(oldTable, oldSize, newTable, newSize); m_table = newTable; m_tableSize = newSize; m_threshold = static_cast<int>(static_cast<float>(newSize) * m_loadFactor); } void Scope::transfer(Symbol** src, int srcSize, Symbol** dst, int dstSize) { for (int i = 0; i < srcSize; i++) { Symbol* symbol = src[i]; if (symbol != nullptr) { do { Symbol* next = symbol->m_next; int index = indexOf(symbol->name()->m_hashCode, dstSize); symbol->m_next = dst[index]; dst[index] = symbol; symbol = next; } while (symbol != nullptr); } } ArrayFill(src, 0, srcSize); } Symbol* SymbolTable::get(Name* name) { // #1 lookup module of name // #2 lookup name in module //TODO(joa): cache this lookup Scope* currentScope = m_scope; const char* chars = name->value(); int32_t length = name->length(); int32_t lastIndex = 0; //TODO(joa): this is sloppy, what if name begins with '.'? for(int32_t i = 0; i < length; ++i) { if(*(chars + i) == '.') { int32_t moduleNameLength = i - lastIndex; if(moduleNameLength > 0) { auto symbol = static_cast<ModuleSymbol*>( currentScope->get( m_names->get( chars + lastIndex, moduleNameLength, /*copyValue=*/false))); if(nullptr == symbol) { #ifdef DEBUG std::cout << "Could not find module: \""; for(int32_t j = 0; j < moduleNameLength; ++j) { std::cout << *(chars + lastIndex + j); } std::cout << "\"" << std::endl; #endif return nullptr; } currentScope = symbol->scope(); lastIndex = i + 1; } } } auto result = currentScope->get(m_names->get(chars + lastIndex, length - lastIndex, false)); #ifdef DEBUG if(nullptr == result) { std::cout << "Could not find \""; for(int32_t j = 0; j < length - lastIndex; ++j) { std::cout << *(chars + lastIndex + j); } std::cout << "\"" << std::endl; } #endif return result; } } //namespace syms } //namespace internal } //namespace brutus
Java
UTF-8
7,565
2.90625
3
[ "CC0-1.0" ]
permissive
package blockstorage; public class HDFSLayerTest { // private Utils utils = new Utils(); // @Test // public void WriteAndReadFromHDFSClusterDirectly1() { // HDFSLayer HDFSLayer = new HDFSLayer(); // SSD SSD = new SSD(HDFSLayer); // Cache Cache = new Cache(SSD); // // int numPages = 100; // int numBlocks = numPages>>3; // BlockServer server = new BlockServer(Cache, SSD, HDFSLayer); // System.out.println("Block Server made"); // // FileSystemOperations client = new FileSystemOperations(); // double startTime = System.nanoTime(); // // for(int i=1;i<=numBlocks;++i){ // Block Block = new Block(i, new byte[8 * utils.PAGE_SIZE]); // try { // client.addFile(HDFSLayer.config, Block); // } catch (IOException e) { // e.printStackTrace(); // } // } // double endTime = System.nanoTime(); // double time=(endTime - startTime) / 1000000000L; // System.out.println("Wrote "+ numBlocks +" blocks to HDFS directly in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // startTime = System.nanoTime(); // for(int i=1;i<=numBlocks;++i){ // try { // client.readFile(HDFSLayer.config, i); // } catch (IOException e) { // e.printStackTrace(); // } // } // endTime = System.nanoTime(); // time=(endTime - startTime) / 1000000000L; // System.out.println("Read "+numBlocks +" blocks from HDFS directly in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // server.stop(); // System.out.println("------------------------------------------------------"); // } // // @Test // public void WriteAndReadFromHDFSClusterDirectly2() { // HDFSLayer HDFSLayer = new HDFSLayer(); // SSD SSD = new SSD(HDFSLayer); // Cache Cache = new Cache(SSD); // // int numPages = 1000; // int numBlocks = numPages>>3; // BlockServer server = new BlockServer(Cache, SSD, HDFSLayer); // System.out.println("Block Server made"); // // FileSystemOperations client = new FileSystemOperations(); // double startTime = System.nanoTime(); // // for(int i=1;i<=numBlocks;++i){ // Block Block = new Block(i, new byte[8 * utils.PAGE_SIZE]); // try { // client.addFile(HDFSLayer.config, Block); // } catch (IOException e) { // e.printStackTrace(); // } // } // double endTime = System.nanoTime(); // double time=(endTime - startTime) / 1000000000L; // System.out.println("Wrote "+ numBlocks +" blocks to HDFS directly in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // startTime = System.nanoTime(); // for(int i=1;i<=numBlocks;++i){ // try { // client.readFile(HDFSLayer.config, i); // } catch (IOException e) { // e.printStackTrace(); // } // } // endTime = System.nanoTime(); // time=(endTime - startTime) / 1000000000L; // System.out.println("Read "+numBlocks +" blocks from HDFS directly in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // server.stop(); // System.out.println("------------------------------------------------------"); // } // // @Test // public void WriteAndReadFromHDFSLayer1() { // HDFSLayer HDFSLayer = new HDFSLayer(); // SSD SSD = new SSD(HDFSLayer); // Cache Cache = new Cache(SSD); // // int numPages = 1000; // // BlockServer server = new BlockServer(Cache, SSD, HDFSLayer); // System.out.println("Block Server made"); // byte[] b = new byte[utils.PAGE_SIZE]; // double startTime = System.nanoTime(); // for(int i=1;i<=numPages;++i){ // HDFSLayer.writePage(new Page(i, b), server); // } // double endTime = System.nanoTime(); // double time=(endTime - startTime) / 1000000000L; // System.out.println("Wrote "+numPages +" pages to HDFSLayer in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // startTime = System.nanoTime(); // for(int i=1;i<=numPages;++i){ // HDFSLayer.readBlock(i, server); // } // endTime = System.nanoTime(); // time=(endTime - startTime) / 1000000000L; // System.out.println("Read "+numPages +" pages from HDFSLayer in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // server.stop(); // System.out.println("------------------------------------------------------"); // } // // @Test // public void WriteAndReadFromHDFSLayer2() { // HDFSLayer HDFSLayer = new HDFSLayer(); // SSD SSD = new SSD(HDFSLayer); // Cache Cache = new Cache(SSD); // // int numPages = 10000; // // BlockServer server = new BlockServer(Cache, SSD, HDFSLayer); // System.out.println("Block Server made"); // byte[] b = new byte[utils.PAGE_SIZE]; // double startTime = System.nanoTime(); // for(int i=1;i<=numPages;++i){ // HDFSLayer.writePage(new Page(i, b), server); // server.updatePageIndex(i, 0, 0, 1, 1); // } // double endTime = System.nanoTime(); // double time=(endTime - startTime) / 1000000000L; // System.out.println("Wrote "+numPages +" pages to HDFSLayer in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // startTime = System.nanoTime(); // for(int i=1;i<=numPages;++i){ // HDFSLayer.readBlock(i, server); // } // endTime = System.nanoTime(); // time=(endTime - startTime) / 1000000000L; // System.out.println("Read "+numPages +" pages from HDFSLayer in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // server.stop(); // System.out.println("------------------------------------------------------"); // } // // @Test // public void WriteAndRevReadFromHDFSLayer1() { // HDFSLayer HDFSLayer = new HDFSLayer(); // SSD SSD = new SSD(HDFSLayer); // Cache Cache = new Cache(SSD); // // int numPages = 1000; // // BlockServer server = new BlockServer(Cache, SSD, HDFSLayer); // System.out.println("Block Server made"); // byte[] b = new byte[utils.PAGE_SIZE]; // double startTime = System.nanoTime(); // for(int i=0;i<numPages;++i){ // HDFSLayer.writePage(new Page(i, b), server); // server.updatePageIndex(i, 0, 0, 1, 1); // } // double endTime = System.nanoTime(); // double time=(endTime - startTime) / 1000000000L; // System.out.println("Wrote "+numPages +" pages to HDFSLayer in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // startTime = System.nanoTime(); // for(int i=(numPages>>3);i>=0;--i){ // HDFSLayer.readBlock(i, server); // } // endTime = System.nanoTime(); // time=(endTime - startTime) / 1000000000L; // System.out.println("Read "+numPages +" pages from HDFSLayer in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // server.stop(); // System.out.println("------------------------------------------------------"); // } // // @Test // public void WriteAndRevReadFromHDFSLayer2() { // HDFSLayer HDFSLayer = new HDFSLayer(); // SSD SSD = new SSD(HDFSLayer); // Cache Cache = new Cache(SSD); // // int numPages = 10000; // // BlockServer server = new BlockServer(Cache, SSD, HDFSLayer); // System.out.println("Block Server made"); // byte[] b = new byte[utils.PAGE_SIZE]; // double startTime = System.nanoTime(); // for(int i=0;i<numPages;++i){ // HDFSLayer.writePage(new Page(i, b), server); // server.updatePageIndex(i, 0, 0, 1, 1); // } // double endTime = System.nanoTime(); // double time=(endTime - startTime) / 1000000000L; // System.out.println("Wrote "+numPages +" pages to HDFSLayer in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // startTime = System.nanoTime(); // for(int i=(numPages>>3);i>=0;--i){ // HDFSLayer.readBlock(i, server); // } // endTime = System.nanoTime(); // time=(endTime - startTime) / 1000000000L; // System.out.println("Read "+numPages +" pages from HDFSLayer in "+time+" seconds at "+(16*numPages*1.0)/time+"kB/s"); // // server.stop(); // System.out.println("------------------------------------------------------"); // } }
Python
UTF-8
6,645
3.046875
3
[ "MIT" ]
permissive
# ./sedater/lib/filesystem.py # Author: Ulli Goschler <ulligoschler@gmail.com> # Modified: Thu, 10.12.2015 - 23:16:02 import os, sys import re from collections import namedtuple from sedater.lib.shared import Sourcefile from sedater.lib.shared import Orientation class Crawler(object): """ The Crawler operates on a filesystem level. It locates all processable files and groups them in individual sessions together. In the crawling process all files under the given path (usually provided on command line) are examined and disassembled by certain criteria based on the filename. Session Data (required) is usually prefixed by (case sensitive): * GAstd * GA * P * Pat Exercise Data (optional) by: - E Orientation data (required) by (case insensitive): - left - right In the following pairing process, individual sensor data files are paired together based on the session (and if available: exercise) ID. So each session should contain a left and right sensor file. """ def __init__(self): self.existingFiles = [] self.pairedFiles = [] def crawl(self, source): """ Crawls all directories under the supplied path and stores files matching a certain filename criteria for further processing :param str source: Path which should be crawled :return: Indicator if the crawling of the source was successfull :rtype: bool """ sourceIsDir = True if os.path.isdir(source) else False sourceIsFile = True if os.path.isfile(source) else False if not sourceIsFile and not sourceIsDir: raise AttributeError("'{}' is neither a file nor a directory," " attempting to skip this input source".format(source)) return False if sourceIsFile: try: validFile = self._parseFileName(source) except PermissionError: # TODO: log it pass if validFile: self.existingFiles.append(validFile) else: # scan for files lying under current node and restart parsing for paths, dirnames, files in os.walk(source): for name in files: self.crawl(os.path.join(paths,name)) if not self.existingFiles: raise ValueError("No processable files found in '{}'".format(source)) return False def _parseFileName(self, f): """ Apply a RegEx on a filename to extract the sensor's orientation and session ID (aka patient ID); if an exercise ID is available, match that too. See the source code for available orientation parameters. :param str f: Path of the file :raises PermissionError: Indicating that no read access is provided :return: Parsed sourcfile information :rtype: :class:`Sourcefile <lib.shared.Sourcefile>` """ if not os.access(f, os.R_OK): try: raise PermissionError("No read access granted on '{}', " " skipping file") except Exception: return False attr = [''] * 5 # create list for file attributes attr[0], attr[1] = os.path.split(f) # 0: fullpath 1:filename # list of regexes we run the filename against ## orientation is either left or right ## exercise is prefixed by 'E' and sometimes followed by the orientation ## session is either prefixed by 'P', 'GA', 'GAstd' or 'Pat' orientation = re.compile("(left|right)", re.IGNORECASE|re.M) exercise = re.compile("E([A-Za-z0-9]+)(?:left|right)?", re.M) session = re.compile("P([0-9]+)E?|GA([0-9]+)|GAstd([0-9a-z]+)(?:left|right)|Pat([0-9a-z]+)(?:left|right)", re.IGNORECASE|re.M) orientationMatch = orientation.search(attr[1]) exerciseMatch = exercise.search(attr[1]) sessionMatch = session.search(attr[1]) # extract the matches if orientationMatch: m = orientationMatch.group(1).lower() if m == 'left': attr[4] = Orientation.left elif m == 'right': attr[4] = Orientation.right if exerciseMatch: attr[3] = exerciseMatch.group(1) if sessionMatch: for i in range(1, len(sessionMatch.groups()) + 1): if sessionMatch.group(i): attr[2] = sessionMatch.group(i) break return Sourcefile._make(attr) def pair(self): """ Pair files together based on the filename. *This should only happen after the ``crawl()`` function found and indexed files* Each Session (Patient) has usually more sensors (e.g. left & right foot). :raises ValueError: Pairing of mentioned files failed :return: Indicator of successful paring :rtype: bool """ if not self.existingFiles: raise ValueError("Can't attempt pairing if no datasets are " "available. Either the Inputsource didn't provide " "any matching files or the detection process failed") # delete all datasets without session and orientation data # TODO: log deleted files self.existingFiles = [x for x in self.existingFiles if x.session and x.orientation] for single in self.existingFiles[:]: # always find a matching 'right' sensor if not single.orientation.name == 'left': continue # match same session, exercise and file extension match = [x for x in self.existingFiles if single.session == x.session and single.exercise == x.exercise and os.path.splitext(single.filename)[1] == os.path.splitext(x.filename)[1]] if len(match) == 2: self.existingFiles.remove(match[0]) self.existingFiles.remove(match[1]) self.pairedFiles.append((match[0], match[1])) # TODO: better way to handle files without partner? if self.existingFiles: for i in self.existingFiles: self.pairedFiles.append((i, i)) print("Found file without a matching partner " "'{}/{}', pairing with itself to continue." .format(i.path, i.filename), file=sys.stderr) return True
PHP
UTF-8
1,551
2.6875
3
[]
no_license
<?php declare(strict_types = 1); $menu = [ [ 'title' => 'Home', 'link' => '', ], [ 'title' => 'Products', 'link' => 'products', 'submenu' => [ [ 'title' => 'Naujausi', 'link' => 'newest', ], [ 'title' => 'Perkamiausi', 'link' => 'most-sell', 'submenu' => [ [ 'title' => 'Kepures', 'link' => 'kepures', ] ] ], [ 'title' => 'Ispardavimas', 'link' => 'sold', ], ], ], [ 'title' => 'About us', 'link' => 'about-as', ], [ 'title' => 'Contacts', 'link' => 'contacts', ], [ 'title' => 'Data', 'link' => 'data.php', ], ]; function makeMenu(array $menu): ?string { if (empty($menu)) { return null; } $menuString = ''; $menuString .= '<ul>'; foreach ($menu as $item) { if (!isset($item['link']) || !isset($item['title'])) { continue; } $menuString .= '<li>'; $menuString .= '<a href="' . $item['link'] . '">' . $item['title'] . '</a>'; if (isset($item['submenu'])) { $menuString .= makeMenu($item['submenu']); } $menuString .= '</li>'; } $menuString .= '</ul>'; return $menuString; } echo makeMenu($menu);
Java
UTF-8
2,793
2.390625
2
[]
no_license
package com.aptech.bookapp.controllers; import com.aptech.bookapp.models.User; import com.aptech.bookapp.services.IUserService; import com.aptech.bookapp.viewmodels.UserLoginViewModel; import com.aptech.bookapp.viewmodels.UserRegisterModel; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; @Controller @RequestMapping("/users") @RequiredArgsConstructor public class UserController { //inject service private final IUserService userService; @GetMapping("/login") //view model = Data Transfer Object = Request Object public ModelAndView login(Model model) { //model.addAttribute("book", 1book);//gủi dữ liệu từ controller => view return new ModelAndView("user/login"); //ten view: login.html } @GetMapping("/register") //view model = Data Transfer Object = Request Object public ModelAndView register(Model model) { model.addAttribute("userRegisterModel", new UserRegisterModel()); ModelAndView modelAndView = new ModelAndView("user/register"); // Đổi tên view thành tên view của bạn modelAndView.addObject("userRegisterModel", new UserRegisterModel()); return modelAndView; } //Sau khi user bam nut "Register" @PostMapping("/register") public ModelAndView registerUser(@Valid UserRegisterModel model, BindingResult result) { User newUser = userService.register(model); if (newUser == null) { ModelAndView modelAndView = new ModelAndView("user/register"); modelAndView.addObject("error", "Cannot register new user"); return modelAndView; } return new ModelAndView("user/login"); } //sau khi bam login, gui reques post den ham nay @PostMapping("/login") public ModelAndView loginUser(@Valid UserLoginViewModel model, BindingResult result) { //xử lý nghiệp vụ(gọi service) User user = userService.login(model.getUsername(), model.getPassword()); //new sai mat khau hoac user ko ton tai if (user == null) { ModelAndView modelAndView = new ModelAndView("user/login"); modelAndView.addObject("error", "Invalid credentials or user does not exist."); return modelAndView; } return new ModelAndView("home/index"); // tên view: login.html } }
Markdown
UTF-8
922
2.921875
3
[]
no_license
# takeabeltof.jinja_filters.py Some custom filters to use in templates --- > #### iso_date_string(*value*): => str Returns a string formatted like a date as 'yyyy-mm-dd'. Value may be a datetime or a 'date like' string. --- > #### short_date_string(*value*): => str Returns a string formatted like a date in "'merican" style as 'mm/dd/yy'. Value may be a datetime or a 'date like' string. --- > #### long_date_string(*value*): => str Returns a string formatted like a date as 'Month_name, d, yyyy'. Value may be a datetime or a 'date like' string. --- > #### two_decimal_string(value): => str Return a string representation of the value as a number with 2 decimal places. Value may be a number or a string. --- > #### money(value): => str An alias to two_decimal_string(). --- > #### register_jinja_filters(app): => Nothing Registers the filters with app. --- [Return to Docs](/docs/takeabeltof/README.md)
Markdown
UTF-8
17,559
3.046875
3
[]
no_license
# Greetings Heroes [View the live project here](https://bryansmullen.github.io/greetings-heroes/) ![Banner Image](wireframes/design-assets/../mockups/greetings-heroes-mockup.jpg) **Greetings Heroes** is an application which allows users to play a fun interactive role playing game. ## Contents - [Greetings Heroes](#greetings-heroes) - [Contents](#contents) - [Project Background](#project-background) - [UX Design](#ux-design) - [Goals](#goals) - [User Stories](#user-stories) - [Features](#features) - [StartStopPause](#startstoppause) - [ChooseAction](#chooseaction) - [HUD](#hud) - [AdvanceStory](#advancestory) - [CharacterSelect](#characterselect) - [InspectCharacter](#inspectcharacter) - [GameResult](#gameresult) - [Game](#game) - [Story](#story) - [Features Left To Be Implemented](#features-left-to-be-implemented) - [Design Choices](#design-choices) - [Wireframes](#wireframes) - [Color Palette](#color-palette) - [Typography](#typography) - [Imagery](#imagery) - [Iconography](#iconography) - [Prototype](#prototype) - [Technologies Used](#technologies-used) - [Languages](#languages) - [Other Tools](#other-tools) - [Testing](#testing) - [Validation](#validation) - [Linting](#linting) - [Modelled Device Testing](#modelled-device-testing) - [Automated Cross Browser Testing](#automated-cross-browser-testing) - [Manual Cross Browser Testing](#manual-cross-browser-testing) - [Testing Insights/Known Issues](#testing-insights/known-issues) - [Deployment](#deployment) - [Deploying on Github Pages](#deploying-on-github-pages) - [Differences between deployed version and development version](#differences-between-deployed-version-and-development-version) - [Cloning a local version](#cloning-a-local-version) - [Credits](#credits) - [Content](#content) - [Media](#media) - [Acknowledgements](#acknowledgements) - [Credits](#credits) - [Content](#content) - [Media](#media) - [Acknowledgements](#acknowledgements) ## Project Background This project is being completed as part of a Full Stack Developer Diploma award. This forms the basis for the developer's second milestone project. As such it will be completed within a set of guidelines as to which technologies to use. While the core focus of the project is to be submitted as the summative assessment for the student developers course, it is also hoped that the resource itself, and the brand created for it can be developed over time into something that can be of value to the wider community. [BACK TO CONTENTS](#Contents) --- ## UX Design ### Goals Design phase goals: - Identify user profile - Generate user stories - Create wireframe - Develop a brand identity - Create high fidelity prototype The website is conceived as a resource for to extend the existing brand of Greetings Heroes. Typically Greetings Heroes is a fun, interactive, live, role-playing story-telling workshop where children are encouraged to explore their creative writing skills. However this resource is hoped to provide an additional opportunity to be incorprated into this workflow which would allow children to play with their created characters after their story is completed. Therefore the user profile for this application is children between the ages of 9 and 14, who have completed a series of Greetings Heroes workshops already and have created characters and a narrative during these workshops. ### User Stories - As a user I should be able to start, pause, and stop the game at will - As a user I should be able to choose whether to attack, use a spell, or use an item during each turn - As a user I should be able to inspect both my remaining health and magic points, as well as what items I have available - As a user I should be able to see read the narrative at my own pace and advance it when I am ready - As a user I should be able to choose my character from a list of four at the beginning of the game - As a user I should be able to inspect the attributes of each available character - As a user I should receive feedback when I win a battle, complete the game, or fail - As a user I should be able to progress to three separate battles in order to win the game - As a user I should be able to read story narrative before and after each battle - As a user I should be able to read instructions about how to play the game [BACK TO CONTENTS](#Contents) ## Features ### StartStopPause This should allow the user to pause the game at any point, as well as start the game if the game is not already running, and to stop the game if the game is already running. ### ChooseAction During each turn of a battle the user should be able to choose from a predetermined list of actions they can choose to take, for example "attack", "use magic", or "use item" ### HUD During battles the users should clearly be able to see relevant information regarding their characters status, including health points and magic points ### AdvanceStory During exposition of story, the story should be displayed in small blocks at a time rather than in one large block. The user should be able to choose what speed the next block appears by means of a keypress ### CharacterSelect At the start of each game the user should be presented with a choice of four characters with different strengths and weaknesses to choose from. Once selected, this choice will remain in effect until the game ends ### InspectCharacter During the character selection process the user should be able to inspect the characters stats to decide which strengths and weaknesses to favour ### GameResult When the game ends the user should see either a positive or negative message depending on whether they succeeded or failed. Additionally they should see feedback each time they emerge from a battle victorious ### Game The game proper should consist of a linear path that the character is set on, interspersing exposition of "story blocks" in between battles. There should be a total of three battles. If the player emerges victorious from the third and final battle, they win the game, and if they are defeated at any point they lose ### Story Story blocks should appear at the start of the game, after the first battle, after the second battle, and after the final battle. They should be displayed on a separate screen, for example a modal to distinguish between action (battles) and exposition (story) ### Features Left To Be Implemented - There is potential to increase the complexity of the battle sequences by adding a third 'special' command for each character. - The items dropped by both enemy 1 and enemy 2 could influence the final battle - Complexity of the battles could be scaled up by interaction of additional attributes - defence, magic defence, luck etc [BACK TO CONTENTS](#Contents) ## Design Choices ### Wireframes Wireframes are generated to accomodate the majority of user stories. Still to be implemented are #StartStopPause, #AdvanceStory, #InspectCharacter. Once the user stories are completed, [wireframes](https://xd.adobe.com/view/c7beac65-48a1-4dbd-a945-279ed1bd52ec-92ed/) are generated to form the layout of the website which allow the target user to achieve their goals. The wireframes are generated to accommodate three different screen sizes in a responsive layout: - MacBook Pro (2019) - iPad Pro (12.9") - iPhone X ### Color Palette Next, the brand is designed. This involves the creation of a logo, compiling of a [color palette](https://color.adobe.com/Greetings-Heroes-color-theme-15326853), and selection of appropriate [font choices](https://use.typekit.net/twt4nji.css). The colors palette chosen for the brand consist mainly of deep reds. The reds represent the the excitement, danger, and courage that are qualities that a hero must possess. Additionally purple is used as a highlight colour, representing magic and imagination. Initial hues were selected based on these representations of the brand, and then fine tuned using [Adobe Color Picker](https://color.adobe.com/create) to select a colour palette that would complement itself, and to ensure accessibility for persons with difficulty discerning colours. ### Typography [Gothicus Roman](https://fonts.adobe.com/fonts/gothicus) is selected as the primary typeface for the major headings because of its ancient, gothic qualities which lend itself well to fantasy. [Courier Prime](https://fonts.adobe.com/fonts/courier-prime) is chosen to complement it through the body text, because of its clarity and legibility, but additionally because Courier is the standard font for screenplays, and since the nature of this project is that children would have created this world themselves, that they would experience seeing their story typed out on the screen in front of them. ### Imagery [Freepik](http://www.freepik.com) was used for the main title image. As such the following code must be included to conform with their free licensing agreement. `<a href="">Designed by freepic.diller / Freepik</a>` ### Iconography [Material Io](https://material.io/resources/icons) was used to source basic icons for sound on/off, information, and exit application. Additionally icons for LinkedIn and Github were sourced from their respective official websites. ### Prototype With these decisions in place, a high fidelity [prototype](https://xd.adobe.com/view/b053e336-3558-410b-bda6-40c7af002eba-e500/) is created drawing together all strands of the design to show what the developed project will look like. Decisions such as placement of content, sizing of images, application of colour and typography palettes are taken at this point. [BACK TO CONTENTS](#Contents) ## Technologies Used In this section, I will mention all of the languages, frameworks, libraries, and any other tools that I have used to construct this project. ### Languages - [HTML](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5) is used to render the content of the website. - [CSS](https://www.w3.org/Style/CSS/#specs) is used to style the content of the website. - [SCSS](https://sass-lang.com/documentation) is used to generate the CSS, by means of a SASS compiler. - [Javascript](https://developer.mozilla.org/en-US/docs/Web/javascript) is used to create interactivity with the website. ### Other Tools - [Adobe XD](https://www.adobe.com/ie/products/xd.html) is used to construct both wireframes and prototypes. - [Adobe Photoshop](https://www.adobe.com/ie/products/photoshop.html) and [Adobe Illustrator](https://www.adobe.com/ie/products/illustrator.html) are used to create design assets. - [Visual Studio Code](https://code.visualstudio.com/) is the main IDE used by the developer for this project. - [Adobe Fonts](https://fonts.adobe.com/) is used to select and serve the fonts used in this project. - [Adobe Color](https://www.adobe.com/ie/products/color.html) is used to select the colour palette used in this project. - [Git](https://git-scm.com/) is used for version control in this project. Throughout the project, a Develop branch has been added to the project to allow work to continue on the website without breaking the functioning version on the Master branch. - [Github](https://github.com/) is used as a remote repository for the site, as well as for deployment of the final version. - [Dorico](https://new.steinberg.net/dorico/) is used to generate the initial MIDI data from the compositions. - [Studio One](https://www.presonus.com/products/Studio-One) is used to generate the final audio files for the score. [BACK TO CONTENTS](#Contents) ## Testing ### Validation All HTML and CSS in this project is validated by using the W3C Markup Validation Service and the W3C CSS Validation Service. HTML Validated without errors on 16 Sept 2020 CSS Validated without errors on 16 Sept 2020 ### Linting All javascript was passed through the ESLint plugin for VSCode to ensure compliance with best practices ### Modelled Device Testing To test the layout on multiple devices, Google Chrome DevTools is used to simulate the size of multiple devices and screen ratios. Screen responsiveness has been noted to ensure the correct screen ratio was delivered, links are tested by clicking through, images are checked to ensure they displayed correctly on all devices, and the website as a whole is checked to ensure everything renders as expected. Any faults or issues were noted in the Device Testing Chart The following device dimensions are tested: - Moto G4 - Galaxy S5 - Pixel 2 - Pixel 2 XL - iPhone 5/SE - iPhone 6,7,8 - iPhone 6,7,8 Plus - iPhone X - iPad - iPad Pro - Laptop 1024px - Laptop L 1440px - 4k -2560px ### Automated Cross Browser Testing To test the layout on multiple browsers, browserstack is used to screenshot how the layout will render on several different versions of major browsers, on the more up-to-date operating systems. These screenshots are then inspected and the results are once again documented in the Browser Automated Testing Chart. The following browsers are tested: - Mac OSX Catalina Safari 71 - Mac OSX Catalina Firefox 80 - Mac OSX Catalina Chrome 85 - Mac OSX Catalina Opera 70 - Mac OSX Catalina Edge 85 - Windows 10 Edge 85 - Windows 10 IE 11 - Windows 10 Firefox 80 - Windows 10 Chrome 85 ### Manual Cross Browser Testing To complement the above results the website is also tested manually on up-to-date browsers available on the developer's machine. The results are once again documented in the Browser Manual Testing Chart The following browsers are tested: - Mac OS Catalina Brave Version 1.8.96 - Mac OS Catalina Safari Firefox 76.0.1 (64-bit) - iOS 13.3.1 iPad Pro Safari - iOS 13.4.1 iPhone Safari - Windows 10 Microsoft Edge 44.18362.387.0 - Windows 10 Google Chrome 81.0.4044.138 (Official Build) (64 Bit) ### Testing Insights/Known Issues - Some unexpected results re default rendering of progress bars on firefox and safari - Safari has unexpected results for for margins/padding on character screen - Internet Explorer, as expected, breaks everything - Some inconsistent font size issues on tablet - Mute button only affects bg music, not sfx [BACK TO CONTENTS](#Contents) ## Deployment This project is deployed on Github Pages, which can be accessed at [Greetings Heroes Github Repo](https://github.com/bryansmullen/greetings-heroes) or [Greetings Heroes Deployed Version](https://bryansmullen.github.io/greetings-heroes/). The deployment is linked to the Master Branch of the repo, and will automatically update the deployment when any changes are committed to this branch of the remote repository. ### Deploying on Github Pages The following procedure was followed to deploy on Github Pages. 1. Navigate to the [Github Repo](https://github.com/bryansmullen/greetings-heroes) 2. Select the **Settings** tab 3. Scroll down to the **Github Pages** section 4. Under the **Source** dropdown, select **Master Branch** 5. Under **Theme,** click **Change Theme** and then click the **Select Theme** button ### Differences between deployed version and development version For this project feature branches were used for each new feature, which were merged back into the master branch using pull requests. At the time of publishing outstanding feature branches are pruned. The process for updating the project in future will be to create a clone from the master branch and make all necessary changes locally. Once ready to commit one should pull down any new changes from the master branch again, ensure there are no merge conflicts, and then create a pull request which will be approved or rejected in due course. ### Cloning a local version To clone this project locally, complete the following steps: 1. Open a new Command-Line Editor on your computer 2. Navigate to the folder you wish to create the local copy of this repo using the `cd` command. e.g. `cd my_directory` 3. Clone the remote repository using the git clone command. `git clone https://github.com/bryansmullen/greetings-heroes` 4. Open the newly created **greetings-heroes** directory in your favourite IDE. [BACK TO CONTENTS](#Contents) ## Credits ### Content - Game developed and produced by [Bryan Mullen](https://www.linkedin.com/in/bryansmullen/). - All narrative content copyright of [Graham Tugwell](https://www.linkedin.com/in/graham-tugwell-21597234/), [Dave Rudden](http://daverudden.com//), and Bryan Mullen unless otherwise stated. All rights reserved. - Music composed & arranged by [Carmel Whelan](https://www.linkedin.com/in/carmel-whelan-704b0b4b/?originalSubdomain=ie). Recordings produced by Bryan Mullen and Carmel Whelan. - Character Artwork designed by [Dearbháil Clarke](https://www.linkedin.com/in/dearbh%C3%A1il-clarke-113279101/). ### Media Main title image sourced from [Freepik](http://www.freepik.com). Attack and heal SFX licenced from [Envato](https://envato.com/) ### Acknowledgements I received inspiration for this project from two games from my childhood: - [Final Fantasy VII](https://en.wikipedia.org/wiki/Final_Fantasy_VII) - [Indiana Jones and the Last Crusade](https://en.wikipedia.org/wiki/Indiana_Jones_and_the_Last_Crusade:_The_Graphic_Adventure) Special thanks to Sammy, Scott, Kevin and all the Code Institute tutors for their continued guidance and support! I received much advice, coaching and steering towards good development practice on this project from my Code Institute mentor [Precious Ijege](https://www.linkedin.com/in/precious-ijege-908a00168/). [BACK TO TOP](#Greetings-Heroes)
Java
UTF-8
395
3.296875
3
[]
no_license
package helloworldmine; import java.util.*; public class addition { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("please enter the number- 1 : "); int a = sc.nextInt(); System.out.println("please enter the number-2 : "); int b = sc.nextInt(); int sum = a + b; System.out.println("the sum of the two numbers is : "+sum); } }
C#
UTF-8
1,288
3.359375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IdleHeroesCalculator.Data.Extensions { public static class EnumExtensions { public static string GetDescription(this Enum value) { var field = value.GetType().GetField( value.ToString() ); var attributes = field.GetCustomAttributes( false ); dynamic displayAttribute = null; if (attributes.Any()) { displayAttribute = attributes.ElementAt(0); } // return description return displayAttribute?.Description; } public static TEnum ParseEnum<TEnum>(string value, TEnum defaultValue = default(TEnum)) where TEnum : struct, IConvertible { if (Enum.TryParse(value, true, out TEnum result)) { return result; } return defaultValue; } public static TEnum ParseEnum<TEnum>(int value, TEnum defaultValue = default(TEnum)) where TEnum : struct, IConvertible { if(Enum.IsDefined(typeof(TEnum), value)) { return (TEnum)(object)value; } return defaultValue; } } }
Python
UTF-8
417
2.71875
3
[]
no_license
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) s = set() ans = set() for i in range(n): a = nums[i] for j in range(i+1, n): b = nums[j] c = 0-a-b if c in s: ans.add(tuple(sorted([a, b, c]))) s.add(a) return [list(x) for x in ans]
C#
UTF-8
2,110
2.890625
3
[]
no_license
using Application.Requests; using AutoMapper; using FluentResults; using Infrastructure.Interfaces; using Infrastructure.Models; using MediatR; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Application.Handlers { /// <summary> /// Handler for getting paged notes. /// </summary> public class GetNotesHandler : IRequestHandler<GetNotesRequest, Result<IReadOnlyCollection<NoteDto>>> { private readonly INoteRepository _noteRepository; private readonly IMapper _mapper; /// <summary> /// Initializes a new instance of the <see cref="GetNotesHandler"/> class. /// </summary> /// <param name="noteRepository">An instance of <see cref="INoteRepository"/> to interact with the notes.</param> /// <param name="mapper">The mapper.</param> /// <exception cref="ArgumentNullException">noteRepository</exception> public GetNotesHandler(INoteRepository noteRepository, IMapper mapper) { _noteRepository = noteRepository ?? throw new ArgumentNullException(nameof(noteRepository)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); } /// <summary>Handles a request</summary> /// <param name="request">The request</param> /// <param name="cancellationToken">Cancellation token</param> /// <returns>Response from the request</returns> public async Task<Result<IReadOnlyCollection<NoteDto>>> Handle(GetNotesRequest request, CancellationToken cancellationToken) { if (request.Page == 0) { request.Page = 1; } var result = await _noteRepository.GetAsync(request.Page, request.PageSize); if (result.IsFailed) { return result.ToResult(); } IReadOnlyCollection<NoteDto> notes = result.ValueOrDefault.Select(note => this._mapper.Map<NoteDto>(note)).ToList(); return notes.ToResult(); } } }
Java
UTF-8
5,786
1.960938
2
[]
no_license
package br.com.paybus.controle; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Spinner; import java.util.ArrayList; import java.util.List; import br.com.paybus.R; import br.com.paybus.acesso_banco_de_dados.ConexaoBD; import br.com.paybus.activitys.CadastrarAlunoActivity; import br.com.paybus.activitys.EditarAlunoActivity; import br.com.paybus.activitys.ListaDeAlunosActivity; import br.com.paybus.activitys.ListaDeAlunosPagamentos; import br.com.paybus.activitys.TelaPrincipalActivity; import br.com.paybus.dao.AlunoDAO; import br.com.paybus.dao.PagamentoDAO; import br.com.paybus.modelo.Aluno; import br.com.paybus.modelo.Pagamento; import br.com.paybus.utilitarios.Verifica; public class AlunoControl extends AppCompatActivity{ Aluno aluno; AlunoDAO dao; public void cadastrarAluno(Context context){ aluno = new Aluno(); dao = new AlunoDAO(this); // Cadastrando Aluno Aluno alunoPagamento = new Aluno(); EditText campoNomeCompletoAluno = findViewById(R.id.campoNomeCompletoAluno); Spinner comboBoxSelecionarInstituicao = findViewById(R.id.comboBoxSelecionarInstituicaoAluno); EditText campoCPFAluno = findViewById(R.id.campoCPFAluno); EditText campoEnderecoAluno = findViewById(R.id.campoEnderecoAluno); EditText campoTelefoneAluno = findViewById(R.id.campoTelefoneAluno); EditText campoEmailAluno = findViewById(R.id.campoEmailAluno); alunoPagamento.setNomeCompleto(campoNomeCompletoAluno.getText().toString()); alunoPagamento.setInstituicao(comboBoxSelecionarInstituicao.getSelectedItem().toString()); alunoPagamento.setCpf(campoCPFAluno.getText().toString()); alunoPagamento.setEndereco(campoEnderecoAluno.getText().toString()); alunoPagamento.setTelefone(campoTelefoneAluno.getText().toString()); alunoPagamento.setSenha(campoCPFAluno.getText().toString()); alunoPagamento.setTipoDeUsuario("aluno"); alunoPagamento.setEmail(campoEmailAluno.getText().toString()); dao.inserirAluno(alunoPagamento); Pagamento pagamento = new Pagamento(); PagamentoDAO pagamentoDAO = new PagamentoDAO(AlunoControl.this); pagamento.setMesEAnoDoPagamento(ListaDeAlunosPagamentos.mesDePagamento); pagamento.setDataDoPagamento("D"); pagamento.setDataDoVencimento(ListaDeAlunosPagamentos.dataDeVencimento); pagamento.setValorDoPagamento(0.0); pagamento.setStatus("Não Pago"); pagamento.setNomeDoAluno(alunoPagamento.getNomeCompleto()); pagamento.setInstituicaoDeEnsinoDoAluno(alunoPagamento.getInstituicao()); pagamento.setNomeDoCobrador("C"); pagamento.setNomeDoMotorista("M"); pagamento.setObservacao("O"); pagamentoDAO.inserirPagamento(pagamento); TelaPrincipalActivity.novoAlunoPagamento = "falso"; AlertDialog.Builder caixaDeDialogo = new AlertDialog.Builder(AlunoControl.this); caixaDeDialogo.setCancelable(false); caixaDeDialogo.setTitle("Mensagem"); caixaDeDialogo.setMessage("Cadastro realizado com sucesso!\n\nNovo(a) aluno(a) adicionado(a) para a lista de pagamentos de "+ListaDeAlunosPagamentos.mesDePagamento); caixaDeDialogo.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { AlunoControl.this.finish(); startActivity(new Intent(AlunoControl.this, ListaDeAlunosPagamentos.class)); } }); caixaDeDialogo.create(); caixaDeDialogo.show(); } int id; public void editarAluno(Context context){ EditText campoNomeCompletoAluno = findViewById(R.id.campoNomeAlunoEditar); Spinner comboBoxSelecionarInstituicao = findViewById(R.id.comboBoxSelecionarInstituicaoEditar); EditText campoCPFAluno = findViewById(R.id.campoCPFAlunoEditar); EditText campoEnderecoAluno = findViewById(R.id.campoEnderecoAlunoEditar); EditText campoTelefoneAluno = findViewById(R.id.campoTelefoneAlunoEditar); EditText campoEmailAluno = findViewById(R.id.campoEmailAlunoEditar); aluno = new Aluno(); aluno.setId(id); aluno.setNomeCompleto(campoNomeCompletoAluno.getText().toString()); aluno.setInstituicao(comboBoxSelecionarInstituicao.getSelectedItem().toString()); aluno.setCpf(campoCPFAluno.getText().toString()); aluno.setEndereco(campoEnderecoAluno.getText().toString()); aluno.setTelefone(campoTelefoneAluno.getText().toString()); aluno.setEmail(campoEmailAluno.getText().toString()); dao = new AlunoDAO(this); dao.atualizarAluno(aluno); AlertDialog.Builder caixaDeDialogo = new AlertDialog.Builder(AlunoControl.this); caixaDeDialogo.setCancelable(false); caixaDeDialogo.setTitle("Mensagem"); caixaDeDialogo.setMessage("Alteração realizada com sucesso!"); caixaDeDialogo.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); startActivity(new Intent(AlunoControl.this, ListaDeAlunosActivity.class)); } }); caixaDeDialogo.create(); caixaDeDialogo.show(); } public void listarAlunos(Context context){ dao.listarAlunos(); } public void excluirAluno(Context context){ dao.deletarAluno(aluno); } }
C#
UTF-8
5,698
3.0625
3
[]
no_license
using DungeonsOfDoom.Core; using DungeonsOfDoom.Core.Character; using DungeonsOfDoom.Core.Items; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Utils; namespace DungeonsOfDoom { class Game { Player player; Room[,] world; Random random = new Random(); string gameMessage = ""; public void Play() { CreatePlayer(); CreateWorld(); do { Console.Clear(); DisplayStats(); DisplayWorld(); AskForMovement(); } while (player.Health > 0); GameOver(); } void DisplayStats() { Console.WriteLine("---- STATS ----"); Console.WriteLine($"Health: {player.Health}"); Console.WriteLine($"Attack: {player.Strength}"); Console.WriteLine($"Weapon: {player.EquippedWeapon.Name}"); Console.WriteLine($"Monsters left: {Monster.Counter}"); Console.WriteLine(player.DisplayBackPack()); } private void AskForMovement() { gameMessage = ""; ConsoleKeyInfo keyInfo = Console.ReadKey(); int newX = player.X; int newY = player.Y; bool isValidMove = true; switch (keyInfo.Key) { case ConsoleKey.RightArrow: newX++; break; case ConsoleKey.LeftArrow: newX--; break; case ConsoleKey.UpArrow: newY--; break; case ConsoleKey.DownArrow: newY++; break; case ConsoleKey.D1: gameMessage = player.UseItem(0); break; case ConsoleKey.D2: gameMessage = player.UseItem(1); break; case ConsoleKey.D3: gameMessage = player.UseItem(2); break; case ConsoleKey.D4: gameMessage = player.UseItem(3); break; case ConsoleKey.D5: gameMessage = player.UseItem(4); break; default: isValidMove = false; break; } if (isValidMove && newX >= 0 && newX < world.GetLength(0) && newY >= 0 && newY < world.GetLength(1)) { player.X = newX; player.Y = newY; //Om spelaren går på ett Item if (world[player.X, player.Y].Item != null) { gameMessage += $"Du hittade: {world[player.X, player.Y].Item.Name}"; Item newItem = world[player.X, player.Y].Item; player.AddToBackpack(newItem); world[player.X, player.Y].Item = null; } //Om spelaren går på ett monster if (world[player.X, player.Y].Monster != null) { Monster monster = world[player.X, player.Y].Monster; gameMessage += $"Fight! {monster.Name} \n" + player.Fight(monster); if (monster.Health > 0) gameMessage += monster.Fight(player); else if (monster.Health <= 0) { player.AddToBackpack(monster); world[player.X, player.Y].Monster = null; Monster.Counter--; if (Monster.Counter <= 0) GameOver(); } } player.Health--; } } private void DisplayWorld() { for (int y = 0; y < world.GetLength(1); y++) { for (int x = 0; x < world.GetLength(0); x++) { Room room = world[x, y]; if (player.X == x && player.Y == y) Console.Write(player.BoardSymbol); else if (room.Monster != null) Console.Write(room.Monster.BoardSymbol); else if (room.Item != null) Console.Write(room.Item.BoardSymbol); else Console.Write("."); } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(gameMessage); } private void GameOver() { Console.Clear(); Console.WriteLine("Game over..."); Console.ReadKey(); Play(); } private void CreateWorld() { world = new Room[20, 5]; for (int y = 0; y < world.GetLength(1); y++) { for (int x = 0; x < world.GetLength(0); x++) { world[x, y] = new Room(); if (player.X != x || player.Y != y) { if (Randomizer.Chance(5)) world[x, y].Monster = new Skelleton(); else if (Randomizer.Chance(5)) world[x, y].Monster = new Dragon(); if (Randomizer.Chance(5)) world[x, y].Item = new Axe(); if (Randomizer.Chance(5)) world[x, y].Item = new Sword(); if (Randomizer.Chance(5)) world[x, y].Item = new Potion(); } } } Console.WriteLine(gameMessage); } private void CreatePlayer() { player = new Player(30, 0, 0, 5); } } }
C++
UTF-8
2,306
3.546875
4
[]
no_license
// // main.cpp // SmartString // // Created by Andrew Kireev on 20.02.2020. // Copyright © 2020 Andrew Kireev. All rights reserved. // #include <iostream> #include <vector> #include <string_view> #include <utility> class SmartStr { public: SmartStr() = default; SmartStr(const std::string& s){ std::string new_s = s; std::string_view str = s; while(true) { size_t tab = str.find_first_of('\t'); storage_s.push_back(str.substr(0, tab)); if (tab == str.npos){ break; } else { str.remove_prefix(tab + 1); } } } void Edit(const std::string& s, const size_t& ind_el) { //Редактирует поле по индексу storage_s[ind_el] = move(s); } void Delete(const size_t& ind_el) { //Удаляет поле по индексу storage_s.erase(storage_s.begin() + ind_el); } void Add(const std::string& s, const size_t& ind_el) { //Добавляет элемент на место ind_el storage_s.insert(storage_s.begin() + ind_el, move(s)); } friend std::ostream& operator<<(std::ostream& out, const SmartStr& sm_string) { //Перегрузка стандартного вывода for (auto i : sm_string.storage_s) { out << i << '\t'; } return out; } friend std::istream& operator>>(std::istream &os, SmartStr& s_) { std::string sup_str; os >> sup_str; s_ = {sup_str}; return os; } private: std::vector<std::string_view> storage_s; }; int main(int argc, const char * argv[]) { //std::string ws; //Можно вводить через стандарный ввод в string, дальше будет создаваться конструктор //std::cin >> ws; //а дальше будет создаваться наш класс принмая в конструкторе эту переменную //SmartStr s(s); SmartStr s("Here\tyou\tcan\tfind\tactivities\tto\tpractise\tyour\treading\tskills"); s.Add("kruto", 4); s.Delete(2); s.Delete(0); s.Edit("Prekrasno", 1); std::cout << s; return 0; }
Java
UTF-8
912
1.96875
2
[]
no_license
package com.example.mvpzhenex.persenter; import com.example.mvpzhenex.ListBean; import com.example.mvpzhenex.Model.MainModel; import com.example.mvpzhenex.contrae.MainContrate; import com.example.mvpzhenex.util.CallBackList; import com.example.mvpzhenex.util.Url; public class MainPersenter extends BasePrensert implements MainContrate.ListPersenter { private MainContrate.ListModel model; private MainContrate.ListView view; public MainPersenter(MainContrate.ListView view) { this.view = view; model=new MainModel (this); } @Override public void List() { model.ListModel (Url.ListUrl, new CallBackList<ListBean> () { @Override public void onSecced(ListBean listBean) { view.onListbanner (listBean); } @Override public void onFiale(Error error) { } }); } }
Java
UTF-8
1,162
3.640625
4
[]
no_license
package io.abhishek.concurrency.factorythread; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadFactory; class Task implements Runnable { public void run() { try { System.out.println("Thread created " + Thread.currentThread().getName()); Thread.sleep(100); } catch (InterruptedException exp) { exp.printStackTrace(); } } } class CustomThreadFactory implements ThreadFactory { private int counter; private String name; List<String> stats; public CustomThreadFactory(String name) { this.counter = 0; this.name = name; stats = new ArrayList<>(); } public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, "Thread " + counter++); return thread; } } public class ThreadFactoryExample { public static void main(String[] args) { CustomThreadFactory factory = new CustomThreadFactory("CustomThreadFactory"); Task task = new Task(); Thread[] thread = new Thread[5]; for(int i = 0;i < 5;i++) { thread[i] = factory.newThread(task); thread[i].start(); } System.out.println("All threads created"); } }
C#
UTF-8
2,081
2.828125
3
[]
no_license
using System; using NetworkAdmin.ConsoleApp.Actions; using NetworkAdmin.ConsoleApp.Helpers; namespace NetworkAdmin.ConsoleApp.Managers { public class Ipv4ActionsManager: IActionManager { private readonly KeyboardInteraction _keyboardInteraction; public Ipv4ActionsManager(KeyboardInteraction keyboardInteraction) { _keyboardInteraction = keyboardInteraction; } private void ShowIpv4Menu() { Console.WriteLine("============= Ipv4 Menu ============="); Console.WriteLine("1. Wczytaj sieć"); Console.WriteLine("2. Stwórz sieć"); Console.WriteLine("3. Sprawdź adres"); Console.WriteLine("-1. Wróć"); Console.WriteLine("0. Zakończ program"); } public int Run() { int state = Int32.MinValue; while (state != 0 && state != -1) { ShowIpv4Menu(); state = _keyboardInteraction.ReadNumber(); switch (state) { case 1: throw new NotImplementedException(); case 2: throw new NotImplementedException(); case 3: state = ServeRedirectionToActionManager(new CheckAddressActionManager(_keyboardInteraction, new CheckIpv4AddressActions(_keyboardInteraction))); break; case 9: break; case 0: break; default: Console.WriteLine(state + " is not in options."); break; } } return state; } private int ServeRedirectionToActionManager(IActionManager manager) { var result = manager.Run(); if (result == 0 || result == 9) { return result; } return 100; } } }
PHP
UTF-8
3,292
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Task; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; class TaskController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('new-task'); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'title' => 'required|string|max:255', ]); } /** * Create a new task instance after a valid registration. * * @param array $data * @return Task */ protected function create(array $data) { return Task::create([ 'title' => $data['title'], 'description' => $data['description'], ]); } public function save(Request $request) { $this->validator($request->all())->validate(); $this->create($request->all()); return redirect('home'); } public static function getTaskList() { $tasks = DB::table('tasks') ->orderBy('done', 'asc') ->orderBy('updated_at', 'desc') ->get(); return $tasks; } public function getTask(Request $request) { $data = $request->all(); $task = DB::table('tasks') ->where('id', '=', $data["task-id"]) ->first(); return view('edit-task', ['task' => $task]); } public function delete(Request $request) { $data = $request->all(); DB::table('tasks') ->where('id', '=', $data["task-id"]) ->delete(); $tasks = $this->getTaskList(); return view('task-list', ['tasks' => $tasks]); } public function markDone(Request $request) { $data = $request->all(); DB::table('tasks') ->where('id', '=', $data["task-id"]) ->update(['done' => 1]); $tasks = $this->getTaskList(); return view('task-list', ['tasks' => $tasks]); } public function updateTask(Request $request) { $data = $request->all(); DB::table('tasks') ->where('id', '=', $data["task-id"]) ->update(['title' => $data["title"], 'description' => $data["description"], 'updated_at' => date('Y-m-d H:i:s', time())]); return redirect('home'); } public static function search(Request $request) { $data = $request->all(); $tasks = DB::table('tasks')->orderBy('done', 'asc') ->orderBy('updated_at', 'desc') ->where('title', 'like', '%'.$data["search"].'%') ->orWhere('description', 'like', '%'.$data["search"].'%') ->get(); return view('search', ['tasks' => $tasks]); } }
Java
UTF-8
2,392
2.265625
2
[]
no_license
package com.example.chahlovkirill.exchangerate.Services; /** * Created by chahlov.kirill on 18/01/17. */ import com.example.chahlovkirill.exchangerate.Model.BankModel; import com.example.chahlovkirill.exchangerate.Model.CityModel; import com.example.chahlovkirill.exchangerate.Model.Gis2Model.Gis2Model; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.List; import java.util.Map; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import com.google.gson.Gson; public class ServicesAPI { private static final String cash2cash_URL = "http://wsv3.cash2cash.ru/ExRatesJson.svc/"; private static final String gis2_URL = "http://catalog.api.2gis.ru/"; public static void getCallCitiesModel (Callback<List<CityModel>> callbak){ Retrofit retrofit = getClient(cash2cash_URL); Icash2cashAPI cash2cash= retrofit.create(Icash2cashAPI.class); Call<List<CityModel>> call = cash2cash.getCities(); call.enqueue(callbak); } public static void getCallBanksModel (String idCities, Callback<List<BankModel>> callbak){ Retrofit retrofit = getClient(cash2cash_URL); Icash2cashAPI cash2cash= retrofit.create(Icash2cashAPI.class); Map<String,String> map = new HashMap<>(); map.put("cityId",idCities); Call<List<BankModel>> call = cash2cash.getBanks(map); call.enqueue(callbak); } public static void getCallGis2ModelSearch(String whatBank, String where, int page, Callback<Gis2Model> callbak){ Retrofit retrofit = getClient(gis2_URL); IGis2API gis2api = retrofit.create(IGis2API.class); Map<String,String> map = new HashMap<>(); map.put("what",whatBank); map.put("where",where); map.put("version","1.3"); map.put("key","ruiqff5223"); map.put("pagesize","50"); map.put("page",String.valueOf(page)); Call<Gis2Model> call = gis2api.getGis2Data(map); call.enqueue(callbak); } private static Retrofit getClient(String base_url){ Gson gson = new GsonBuilder().create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(base_url) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit; } }
Java
UTF-8
546
2.65625
3
[]
no_license
package model; public class Timeslot{ private int startTime; private int endTime; private String day; public void setDay(String day){ this.day = day; } public String getDay(){ return this.day; } public void setStartTime(int startTime){ this.startTime = startTime; } public int getStartTime(){ return this.startTime; } public void setEndTime(int endTime){ this.endTime = endTime; } public int getEndTime(){ return this.endTime; } }
Python
UTF-8
336
3.390625
3
[]
no_license
import math def get_int(): return int(input()) def get_ints(): return [int(i) for i in input().split()] for t in range(0, get_int()): n = get_int() if n <= 1: print(0) continue m = n sq = int(math.sqrt(n)) if sq * sq == m: print(sq - 1 + sq - 1) elif (1 + sq) * sq >= n: print(sq + sq - 1) else: print(sq + sq)
Python
UTF-8
3,118
3.890625
4
[]
no_license
class Quicksort: def __init__(self, data): """ Init functie van de class""" self.data = data def start_recursive(self): """ Deze functie wordt aangeroepen om het recursive quicksort algoritme te gebruiken""" self.quicksortRecusrive(self.data, 0, len(self.data) - 1) def start_iterative(self): """ Deze functie wordt aangeroepen om het iteratieve quicksort algoritme te gebruiken (grote data)""" self.quickSortIterative(self.data, 0, len(self.data) - 1) def quicksortRecusrive(self, lst, min, max): """ deze functie bepaalt het middenpunt, en als het element kleiner is dan het middelpunt wordt het naar links verplaatst""" if min < max: middelpunt = self.verplaatsRecusive(lst, min, max) self.quicksortRecusrive(lst, min, middelpunt - 1) self.quicksortRecusrive(lst, middelpunt + 1, max) def verplaatsRecusive(self, data, min, max): """ Deze functie verplaatst het element en bepaalt een nieuw middenpunt""" kleinste = (min - 1) middelpunt = data[max] for j in range(min, max): if data[j] < middelpunt: kleinste = kleinste + 1 data[kleinste], data[j] = data[j], data[kleinste] data[kleinste + 1], data[max] = data[max], data[kleinste + 1] return kleinste + 1 def verplaatsIterative(self, arr, l, h): """ Deze functie verplaatst het element en bepaalt een nieuw middenpunt""" i = (l - 1) x = arr[h] for j in range(l, h): if arr[j] <= x: i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[h] = arr[h], arr[i + 1] return i + 1 def quickSortIterative(self, arr, l, h): """ deze functie bepaalt het middenpunt, en als het element kleiner is dan het middelpunt wordt het naar links verplaatst, anders naar rechts.""" # Create an auxiliary stack size = h - l + 1 stack = [0] * size # initialize top of stack top = -1 # push initial values of l and h to stack top = top + 1 stack[top] = l top = top + 1 stack[top] = h # Keep popping from stack while is not empty while top >= 0: # Pop h and l h = stack[top] top = top - 1 l = stack[top] top = top - 1 # Set pivot element at its correct position in # sorted array p = self.verplaatsIterative(arr, l, h) # If there are elements on left side of pivot, # then push left side to stack if p - 1 > l: top = top + 1 stack[top] = l top = top + 1 stack[top] = p - 1 # If there are elements on right side of pivot, # then push right side to stack if p + 1 < h: top = top + 1 stack[top] = p + 1 top = top + 1 stack[top] = h
TypeScript
UTF-8
1,549
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
// Loaded from https://deno.land/x/axiod@0.20.0-0/helpers.ts export const methods = [ "get", "post", "put", "delete", "options", "head", "connect", "trace", "patch", ]; // /** // * Deep copy function for TypeScript. // * @param T Generic type of target/copied value. // * @param target Target value to be copied. // * @see Source project, ts-deeply https://github.com/ykdr2017/ts-deepcopy // * @see Code pen https://codepen.io/erikvullings/pen/ejyBYg // */ // export const deepCopy = <T>(target: T): T => { // if (target === null) { // return target; // } // if (target instanceof Date) { // return new Date(target.getTime()) as any; // } // // First part is for array and second part is for Realm.Collection // // if (target instanceof Array || typeof (target as any).type === 'string') { // if (typeof target === "object") { // if (typeof target[(Symbol as any).iterator] === "function") { // const cp = [] as any[]; // if ((target as any as any[]).length > 0) { // for (const arrayMember of target as any as any[]) { // cp.push(deepCopy(arrayMember)); // } // } // return cp as any as T; // } else { // const targetKeys = Object.keys(target); // const cp = {}; // if (targetKeys.length > 0) { // for (const key of targetKeys) { // cp[key] = deepCopy(target[key]); // } // } // return cp as T; // } // } // // Means that object is atomic // return target; // };
Java
UTF-8
4,654
1.710938
2
[]
no_license
package com.panda.mvp.ui.login; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.panda.R; import com.panda.mvp.contract.login.LoginActivityContract; import com.panda.mvp.presenter.login.LoginActivityPresenter; import com.panda.mvp.ui.test.InternalInterceptionActivity; import com.panda.mvp.ui.test.TestActivity; import com.panda.pandalibs.base.mvp.ui.BaseActivity; import com.panda.pandalibs.utils.net.NetUtils; import com.panda.pandalibs.utils.utils.tools.PTo; import butterknife.BindView; import butterknife.OnClick; public class LoginActivityActivity extends BaseActivity<LoginActivityPresenter> implements LoginActivityContract.View { @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.name) EditText name; @BindView(R.id.password) EditText password; @BindView(R.id.login) Button login; @BindView(R.id.regist) Button regist; @BindView(R.id.test) Button test; boolean progressShow; @Override protected void after() { super.after(); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); } } @Override protected int layoutID() { return R.layout.activity_loginactivity; } @Override protected void init(Bundle savedInstanceState) { userToolbar(mToolbar, R.string.loginactivity_toolbar_title); } @Override protected LoginActivityPresenter createPresenter() { return new LoginActivityPresenter(this, this); } @OnClick({R.id.login, R.id.regist, R.id.test}) public void onClick(View view) { switch (view.getId()) { case R.id.login: { logining(); } break; case R.id.regist: { startActivityForResult(new Intent(this, RegisterActivity.class), 0); } break; case R.id.test: { Intent intent = new Intent(this, TestActivity.class); startActivity(intent); } default: break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.page_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(this, TestActivity.class); startActivity(intent); return super.onOptionsItemSelected(item); } private void logining() { if (NetUtils.isNoNetState()) { PTo.get().show(this, R.string.check_network); return; } String currentUsername = name.getText().toString().trim(); String currentPassword = password.getText().toString().trim(); if (TextUtils.isEmpty(currentUsername)) { Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(currentPassword)) { Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show(); return; } progressShow = true; final ProgressDialog pd = new ProgressDialog(this); pd.setCanceledOnTouchOutside(false); pd.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { Log.d(TAG, "EMClient.getInstance().onCancel"); progressShow = false; } }); pd.setMessage(getString(R.string.Is_landing)); pd.show(); } private static final String TAG = "LoginActivityActivity"; public void test(View view) { Intent intent = new Intent(this, TestActivity.class); startActivity(intent); } // dev3 public void internalInterception(View view) { Intent intent = new Intent(this, InternalInterceptionActivity.class); startActivity(intent); } public void swipeRefresh(View view) { Intent intent = new Intent(this, SwipeRefreshDemoActivity.class); startActivity(intent); } }
C++
UTF-8
1,273
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; vector<vii> adjlist; int main() { ios_base::sync_with_stdio(false); freopen("i","r",stdin); freopen("o","w",stdout); int t; cin>>t; while(t--) { int v,m,x,y,t; cin>>v>>m; adjlist.clear(); adjlist.resize(v); for(int i=0;i<m;i++) { //adjlist.push_back(vii()); cin>>x>>y>>t; adjlist[x].push_back(make_pair(y,t)); } vi dist(v,-100000);dist[0]=0; for(int i=0;i<v-1;i++) for(int u=0;u<v;u++) for(int j=0;j<adjlist[u].size();j++) { ii v = adjlist[u][j]; dist[v.first]=min(dist[v.first],dist[u]+v.second); } bool neg=false; for(int u=0;u<v;u++) for(int j=0;j<adjlist[u].size();j++) { ii v = adjlist[u][j]; if(dist[v.first]>dist[u]+v.second) { neg=true;break; } } if(neg) cout<<"possible"<<endl; else cout<<"not possible"<<endl; } return 0; }
C#
UTF-8
726
2.71875
3
[]
no_license
// <copyright file="NullableDateTimeConverter.cs" company="Isaac Brown"> // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> namespace SomeUser.Api.Mapping { using System; using AutoMapper; /// <summary> /// Converts DateTime? to string. /// </summary> public class NullableDateTimeConverter : ITypeConverter<DateTime?, string> { /// <inheritdoc/> public string Convert(DateTime? source, string destination, ResolutionContext context) { if (source.HasValue) { return source.Value.ToString("yyyy-MM-dd"); } else { return default; } } } }
Java
UTF-8
5,259
1.945313
2
[]
no_license
package mineplex.core.gadget.gadgets; import java.util.ArrayList; import java.util.HashMap; import mineplex.core.common.util.C; import mineplex.core.common.util.F; import mineplex.core.common.util.UtilAction; import mineplex.core.common.util.UtilAlg; import mineplex.core.common.util.UtilEnt; import mineplex.core.common.util.UtilParticle; import mineplex.core.common.util.UtilParticle.ParticleType; import mineplex.core.common.util.UtilParticle.ViewDist; import mineplex.core.common.util.UtilPlayer; import mineplex.core.common.util.UtilServer; import mineplex.core.common.util.UtilTime; import mineplex.core.gadget.GadgetManager; import mineplex.core.gadget.types.ItemGadget; import mineplex.core.preferences.PreferencesManager; import mineplex.core.preferences.UserPreferences; import mineplex.core.recharge.Recharge; import mineplex.core.updater.UpdateType; import mineplex.core.updater.event.UpdateEvent; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.entity.Bat; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.util.Vector; public class ItemBatGun extends ItemGadget { private HashMap<Player, Long> _active = new HashMap(); private HashMap<Player, Location> _velocity = new HashMap(); private HashMap<Player, ArrayList<Bat>> _bats = new HashMap(); public ItemBatGun(GadgetManager manager) { super(manager, "Bat Blaster", new String[] {C.cWhite + "Launch waves of annoying bats", C.cWhite + "at people you don't like!" }, -1, Material.IRON_BARDING, (byte)0, 5000L, new Ammo("Bat Blaster", "50 Bats", Material.IRON_BARDING, (byte)0, new String[] { C.cWhite + "50 Bats for your Bat Blaster!" }, 500, 50)); } public void DisableCustom(Player player) { super.DisableCustom(player); Clear(player); } public void ActivateCustom(Player player) { this._velocity.put(player, player.getEyeLocation()); this._active.put(player, Long.valueOf(System.currentTimeMillis())); this._bats.put(player, new ArrayList()); for (int i = 0; i < 16; i++) { ((ArrayList)this._bats.get(player)).add((Bat)player.getWorld().spawn(player.getEyeLocation(), Bat.class)); } UtilPlayer.message(player, F.main("Skill", "You used " + F.skill(GetName()) + ".")); } @EventHandler public void Update(UpdateEvent event) { if (event.getType() != UpdateType.TICK) { return; } Player[] arrayOfPlayer1; int j = (arrayOfPlayer1 = UtilServer.getPlayers()).length; for (int i = 0; i < j; i++) { Player cur = arrayOfPlayer1[i]; if (this._active.containsKey(cur)) { if (UtilTime.elapsed(((Long)this._active.get(cur)).longValue(), 3000L)) { Clear(cur); } else { Location loc = (Location)this._velocity.get(cur); for (Bat bat : (ArrayList)this._bats.get(cur)) { if (bat.isValid()) { Vector rand = new Vector((Math.random() - 0.5D) / 3.0D, (Math.random() - 0.5D) / 3.0D, (Math.random() - 0.5D) / 3.0D); bat.setVelocity(loc.getDirection().clone().multiply(0.5D).add(rand)); Player[] arrayOfPlayer2; int m = (arrayOfPlayer2 = UtilServer.getPlayers()).length; for (int k = 0; k < m; k++) { Player other = arrayOfPlayer2[k]; if (!other.equals(cur)) { if ((((UserPreferences)this.Manager.getPreferencesManager().Get(other)).HubGames) && (((UserPreferences)this.Manager.getPreferencesManager().Get(other)).ShowPlayers)) { if (Recharge.Instance.usable(other, "Hit by Bat")) { if (UtilEnt.hitBox(bat.getLocation(), other, 2.0D, null)) { if (!this.Manager.collideEvent(this, other)) { UtilAction.velocity(other, UtilAlg.getTrajectory(cur, other), 0.4D, false, 0.0D, 0.2D, 10.0D, true); bat.getWorld().playSound(bat.getLocation(), Sound.BAT_HURT, 1.0F, 1.0F); UtilParticle.PlayParticle(UtilParticle.ParticleType.LARGE_SMOKE, bat.getLocation(), 0.0F, 0.0F, 0.0F, 0.0F, 3, UtilParticle.ViewDist.NORMAL, UtilServer.getPlayers()); bat.remove(); Recharge.Instance.useForce(other, "Hit by Bat", 200L); } } } } } } } } } } } } public void Clear(Player player) { this._active.remove(player); this._velocity.remove(player); if (this._bats.containsKey(player)) { for (Bat bat : (ArrayList)this._bats.get(player)) { if (bat.isValid()) { UtilParticle.PlayParticle(UtilParticle.ParticleType.LARGE_SMOKE, bat.getLocation(), 0.0F, 0.0F, 0.0F, 0.0F, 3, UtilParticle.ViewDist.NORMAL, UtilServer.getPlayers()); } bat.remove(); } this._bats.remove(player); } } }
Shell
UTF-8
548
3.703125
4
[]
no_license
#!/bin/bash if [ ! -n "$1" ];then echo "### Remover Error: Missing main (skill name) parameter!" exit 1 fi echo "INFO - Removing Skill $1" if cd /opt/mycroft/skills/$1 2>/dev/null then cd /opt/mycroft/skills && rm -rf $1 oname=$(echo $1 | awk -F"." '{print $1}') if (cd /opt/mycroft/skills/ui/skills/$oname) > /dev/null 2>&1 then cd /opt/mycroft/skills/ui/skills && rm -rf $oname echo "INFO - Removed $oname" else echo "INFO - Removed $1" fi else echo "INFO - Skill $1 not installed or not found" sleep 2 fi
C++
UTF-8
5,186
3.421875
3
[]
no_license
#include "stdafx.h" #include "SimilarityCalculator.h" #include <Vector> SimilarityCalculator::SimilarityCalculator() // set values to 0 { intCountValue = 0; doubleCountValue = 0; floatCountValue = 0; charCountValue = 0; voidCountValue = 0; boolCountValue = 0; forCountValue = 0; ifCountValue = 0; elseCountValue = 0; whileCountValue = 0; doCountValue = 0; intInstances = 0; doubleInstances = 0; floatInstances = 0; charInstances = 0; voidInstances = 0; boolInstances = 0; forInstances = 0; ifInstances = 0; elseInstances = 0; whileInstances = 0; doInstances = 0; } SimilarityCalculator::~SimilarityCalculator() { } int SimilarityCalculator::CalculateSimilarityMetric(string &fileChoice, string &filePath) { //opens file and calculates total numeric value of file ifstream inFile; string item; int total = 0; inFile.open(filePath + fileChoice); if (inFile.fail()) { return -1; } while (!inFile.eof()) { inFile >> item; if (item == "int") { intCountValue += 1; // +1 total int numeric value for instance of type int found intInstances++; // +1 amount of instances of int appear } if (item == "double") { doubleCountValue += 2; // +2 total double numeric value for instance of type int found doubleInstances++; // +1 amount of instances of double appear } if (item == "float") { floatCountValue += 3; floatInstances++; } if (item == "char") { charCountValue += 4; charInstances++; } if (item == "void") { voidCountValue += 5; voidInstances++; } if (item == "bool") { boolCountValue += 6; boolInstances++; } if (item == "if") { ifCountValue += 7; ifInstances++; } if (item == "else") { elseCountValue += 8; elseInstances++; } if (item == "for") { forCountValue += 9; forInstances++; } if (item == "while") { whileCountValue += 10; whileInstances++; } if (item == "do") { doCountValue += 11; doInstances++; } } total = intCountValue + doubleCountValue + floatCountValue + charCountValue + voidCountValue + boolCountValue + forCountValue + ifCountValue + elseCountValue + whileCountValue + doCountValue; // total numeric value of file inFile.close(); return total; } Count SimilarityCalculator::getInstances() // return all instances of each { Count toReturn; toReturn.intInstances = intInstances; toReturn.doubleInstances = doubleInstances; toReturn.floatInstances = floatInstances; toReturn.charInstances = floatInstances; toReturn.voidInstances = voidInstances; toReturn.boolInstances = boolInstances; toReturn.forInstances = forInstances; toReturn.ifInstances = ifInstances; toReturn.elseInstances = elseInstances; toReturn.whileInstances = whileInstances; toReturn.doInstances = doInstances; return toReturn; } string SimilarityCalculator::printInstances(Count& toPrint) { ostringstream oss; oss << "Int Instances:\t\t" << toPrint.ifInstances << "\nDouble Instances:\t" << toPrint.doubleInstances << "\nFloat Instances:\t" << toPrint.floatInstances << "\nChar Instances:\t\t" << toPrint.charInstances << "\nVoid Instances:\t\t" << toPrint.voidInstances << "\nBool Instances:\t\t" << toPrint.boolInstances << "\nFor Instances:\t\t" << toPrint.forInstances << "\nIf Instances:\t\t" << toPrint.ifInstances << "\nElse Instances:\t\t" << toPrint.elseInstances << "\nWhile Instances:\t" << toPrint.whileInstances << "\nDo Instances:\t\t" << toPrint.doInstances << endl; return oss.str(); } double SimilarityCalculator::CalculatePercentageDifference(int choice1, int choice2) { double difference = choice1 - choice2; double result = (difference / choice1) * 100; if (result > 0) { return 100 - result; // minus 100 give percentage similarity rather difference } else if (result < 0) { result *= -1; return 100 - result; //converts a minus number to a positive to always have positive percentage result } else if (result == 0) { return 100; // if no difference in numeric value is found return 100 for 100 percent similarity } } void SimilarityCalculator::ResetValues() // reset values to 0 so second file cann be processed { intCountValue = 0; doubleCountValue = 0; floatCountValue = 0; charCountValue = 0; voidCountValue = 0; boolCountValue = 0; forCountValue = 0; ifCountValue = 0; elseCountValue = 0; whileCountValue = 0; doCountValue = 0; intInstances = 0; doubleInstances = 0; floatInstances = 0; charInstances = 0; voidInstances = 0; boolInstances = 0; forInstances = 0; ifInstances = 0; elseInstances = 0; whileInstances = 0; doInstances = 0; } //*Usage: Used code to open file choice based on choice. (filepath + fileChoice) //* Title : Checksums, Data Integrity //* Author : AustinWolfman //* Date : 2015 //* Code version : - //* Availability : http ://stackoverflow.com/questions/33794412/checksums-data-integrity //*Usage : Used to control the correct opening of a file //* Title : stuck on loop for (infile.fail()) //* Author : mux77 //* Date : 2011 //* Code version : - //* Availability : http://www.cplusplus.com/forum/general/39635/
C#
UTF-8
4,205
3.109375
3
[]
no_license
using System; using System.IO; using aspa.reversi.Models; namespace aspa.reversi { public class ConfigHandler { public static void DisplayHelp() { Console.WriteLine(); Console.WriteLine("Usage> reversi -par1 -par2 -l <filename>"); Console.WriteLine("-h\t\tShow this help.\n"); Console.WriteLine("-ht\t\tShow hints."); Console.WriteLine("-hn\t\tShow numeric hints that the ai plays after.\n"); Console.WriteLine("-ai\t\tPlay against an ai.\n"); Console.WriteLine("-ai1\t\tWHITE player is an ai.\n"); Console.WriteLine("-ai2\t\tBLACK player is an ai.\n"); Console.WriteLine("-ai3\t\tLet 2 ai's play against eachother.\n"); Console.WriteLine("-l <file>\tLoads the saved game <file>.\n"); } public static Config ReadCommandLineArgumants(char[] board, string[] arguments) { var config = new Config { Ai = AiPlayer.NoAi, Hints = BoardHints.NoHints, Player = Constants.Black, }; for (var index = 0; index < arguments.Length; index++) { var argument = arguments[index]; if (argument.Contains("-h")) { DisplayHelp(); Environment.Exit(0); } switch (argument) { case "-ai": case "-ai1": config.Ai = AiPlayer.WhiteAi; continue; case "-ai2": config.Ai = AiPlayer.BlackAi; continue; case "-ai3": config.Ai = AiPlayer.BothAi; continue; case "-ht": config.Hints = BoardHints.Hints; continue; case "-hn": config.Hints = BoardHints.NumericHints; continue; case "-l": var saveFile = arguments[++index]; config.Player = LoadSaveGame(board, saveFile); if (config.Player == 0) { Console.WriteLine("File load failed, exiting.\n"); DisplayHelp(); Environment.Exit(1); } continue; default: Console.WriteLine("Unknown parameter: " + argument); DisplayHelp(); Environment.Exit(1); break; } } return config; } public static char LoadGameLog(char[] board, string gameLogLine) { var player = Constants.Black; var coord = new Pos(); foreach (var character in gameLogLine) { if (char.IsLetter(character)) { coord.X = Pos.ConvertLetter(character); } else if (char.IsDigit(character)) { coord.Y = Pos.ConvertDigit(character); } else { InputHandler.MakeMove(board, coord, player); InputHandler.PlacePiece(board, coord, player); player = player == Constants.Black ? Constants.White : Constants.Black; } } return player; } public static char LoadSaveGame(char[] board, string saveFile) { var logLine = ""; if (File.Exists(saveFile)) { logLine = File.ReadAllText(saveFile); } else { Console.WriteLine("Invalid savefile: " + saveFile); DisplayHelp(); Environment.Exit(1); } return LoadGameLog(board, logLine); } } }
Java
UTF-8
3,021
2.1875
2
[ "Apache-2.0" ]
permissive
/** * */ package com.thinkgem.jeesite.modules.wlpt.service.base; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.jsoup.Jsoup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.service.CrudService; import com.thinkgem.jeesite.common.utils.Tools; import com.thinkgem.jeesite.modules.wlpt.entity.base.BasePolicy; import com.thinkgem.jeesite.modules.wlpt.dao.base.BasePolicyDao; /** * 政策公告Service * @author 王铸 * @version 2016-08-04 */ @Service @Transactional(readOnly = true) public class BasePolicyService extends CrudService<BasePolicyDao, BasePolicy> { @Autowired private BasePolicyDao basePolicyDao; public BasePolicy get(String id) { return super.get(id); } public List<BasePolicy> findList(BasePolicy basePolicy) { return super.findList(basePolicy); } public Page<BasePolicy> findPage(Page<BasePolicy> page, BasePolicy basePolicy) { return super.findPage(page, basePolicy); } @Transactional(readOnly = false) public void save(BasePolicy basePolicy) { super.save(basePolicy); } @Transactional(readOnly = false) public void delete(BasePolicy basePolicy) { super.delete(basePolicy); } /** * 批量操作 * @param map * @return */ @Transactional(readOnly = false) public void deleteAll(Map<String,String> map){ basePolicyDao.deleteAll(map); } public Page<BasePolicy> getPolicyList(Page page, BasePolicy basePolicy) { Page<BasePolicy> pagepolicy = findPage(page, basePolicy); pagepolicy.setList(setModel(page.getList()));//格式数据 return pagepolicy; } //设置数据格式 private List<BasePolicy> setModel(List<BasePolicy> domestic){ List<BasePolicy> Domestics = new ArrayList<BasePolicy>(); for (BasePolicy news : domestic) { //时间格式 //news.setReleaseTime(DateUtil.fomatDate(String.valueOf(news.getReleaseTime()))); /* String summarys =news.getSummary().trim(); news.setSummary(summarys); */ //格式内容 String content =Jsoup.parse(news.getContent().replaceAll("&nbsp;","")).text().replaceAll("\\s*",""); if(content.length()>101){ content = content.substring(0,100)+"..."; } news.setContent(content); //截取标题 String title = news.getTitle().trim(); if(title.length()>24){ title = title.substring(0, 24)+"..."; } news.setTitle(title); //关键字去逗号 String keyword = news.getKeyword(); if(!Tools.IsNullOrWhiteSpace(keyword)){ keyword = keyword.replace(",", " "); } news.setKeyword(keyword); //截取图片,--图片只留一张 String img = news.getPicture(); if (!Tools.IsNullOrWhiteSpace(img)) { img =img.contains(",")? img.substring(0, img.indexOf(",")):img; } news.setPicture(img); Domestics.add(news); } return Domestics; } }
Markdown
UTF-8
870
2.625
3
[]
no_license
# Predict-ImageRotation-Angle ## Requirement please install the requirement.txt file before running the program pip install -r requirements.txt ## Test the results master_predict_rotation.py is the program which accepts two images and predict the roatation of the second imaged formed by rotating the first. python master_predict_rotation.py test/1.png test/1_ro_90.png python master_predict_rotation.py test/2.png test/2_ro_180.png Input should be the path of the images. Input image must be of 200 x 200 dimension ## Train using turi create Put all your images in the data folder and delete data insdie the folder 0 , 1 , 2 , 3 subfolder of coreml_data Run following program in sequence python prepdare_data_for_coreML.py python train_using_coreml.py ## Train using Tensorflow Put training images into data folder. python train_using_tensorflow.py
Python
UTF-8
3,575
2.59375
3
[]
no_license
import urllib.request as urllib2 from bs4 import BeautifulSoup import os from parser_attributes_JB import * from parse_title import parse_title from parse_cast import parse_cast from parse_director import parse_director from parse_writers import parse_writers from parse_numOfReviews import parse_numOfReviews from parse_popularity import parse_popularity from parse_deltaPopularity import parse_deltaPopularity from parse_country import parse_country from parse_gross import parse_gross from parse_language import parse_language from parser_rating import get_rating from parse_location import get_location from parse_company import parse_company from parse_releaseDate import parse_releaseDate from parse_budget import parse_budget from readIDfromKaggle import readIdsFromKaggle import pandas as pd def get_soup(id): quote_page = 'http://www.imdb.com/title/' + id + '/?ref_=nv_sr_2' page = urllib2.urlopen(quote_page) return BeautifulSoup(page, 'html.parser') def check_good_dict(D): return True if sum([len(i) for _,i in D.items()])/float(len(D.keys()))==len(D['IDs']) else False def save_data_frame(DF): if DF is not None: i = 0 while os.path.exists('kaggle_attr%s.csv' % i): i += 1 DF.to_csv('kaggle_attr%s.csv' % i, sep=';', encoding='utf-8') print('Saved to ' + 'kaggle_attr%s.csv' % i) ## IDs=readIdsFromKaggle() ## D = {} D['IDs'] = [] D['titles'] = [] D['casts'] = [] D['directors'] = [] D['writers'] = [] D['popularities'] = [] D['deltaPopularities'] = [] D['numberReviews'] = [] D['countries'] = [] D['grosses'] = [] D['languages'] = [] D['releaseDates'] = [] D['budget'] = [] D['ratings'] = [] D['locations'] = [] D['companies'] = [] D['storylines'] = [] D['keywords'] = [] D['genres'] = [] D['durations'] = [] D['colors'] = [] D['aspectRatios'] = [] D['mpaaRatings'] = [] for i, id in enumerate(IDs): try: print(i) soup = get_soup(id) D['IDs'].append(id) D['titles'].append(parse_title(soup, id)) D['casts'].append(parse_cast(soup, id)) D['directors'].append(parse_director(soup, id)) D['writers'].append(parse_writers(soup, id)) D['popularities'].append(parse_popularity(soup, id)) D['deltaPopularities'].append(parse_deltaPopularity(soup, id)) D['numberReviews'].append(parse_numOfReviews(soup, id)) D['countries'].append(parse_country(soup, id)) D['grosses'].append(parse_gross(soup, id)) D['languages'].append(parse_language(soup, id)) D['releaseDates'].append(parse_releaseDate(soup, id)) D['budget'].append(parse_budget(soup, id)) D['ratings'].append(get_rating(soup, id)) D['locations'].append(get_location(soup, id)) D['companies'].append(parse_company(soup, id)) D['storylines'].append(parse_storyline_attribute(soup)) D['keywords'].append(parse_keyword_attribute(soup)) D['genres'].append(parse_genre_attribute(soup)) D['durations'].append(parse_runtime_attribute(soup)) D['colors'].append(parse_color_attribute(soup)) D['aspectRatios'].append(parse_aspect_ratio_attribute(soup)) D['mpaaRatings'].append(parse_mpaa_attribute(soup)) except: print("Error with id " + id) pass ## DF = pd.DataFrame(D) if check_good_dict(D) else None save_data_frame(DF) ## # import seaborn as sns # df = pd.read_csv('kaggle_1000.csv', sep=';') # sns.distplot(df['ratings'].dropna()) ## nan ratings for [310, 335, 416, 519, 534, 545, 610, 643, 719, 747, 772, 949, 966] ##
C#
UTF-8
8,177
2.609375
3
[]
no_license
//Hecho por Ariel Arias using OfficeOpenXml; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; using TCU_WFA.Models; namespace TCU_WFA { /// <summary> /// Clase encargada de la generación de los documentos excel /// </summary> public static class ExcelGenerator { //Constantes Resumen private const string TITULO_RESUMEN = "Resumen"; //Mensajes de creación del documento private const string TITULO_MENSAJE = "Documento generado"; private const string MENSAJE_CORRECTO = "El documento se guardó en: "; private const string MENSAJE_INCORRECTO = "Ocurrió un error al guardar el documento"; /// <summary> /// Método para generar el documento excel del resumen /// </summary> /// <param name="datosResumen">Los datos a utilizar para el resumen general</param> public static void CrearDocumentoResumenExcel(DatosGeneralesResumen datosResumen, List<VacaModel> listaVacas) { //Se crea una instancia del paquete de excel del documento a utilizar ExcelPackage documentoExcel = new ExcelPackage(); //Se crea la hoja que se va a generar ExcelWorksheet hojaResumen = documentoExcel.Workbook.Worksheets.Add(TITULO_RESUMEN); //Se establece el primer rango de celdas a utilizar para la información general, con sus colores ExcelRange celdasInformacionGeneral = hojaResumen.Cells[1,1,8,4]; celdasInformacionGeneral.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; celdasInformacionGeneral.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(204, 255, 204)); celdasInformacionGeneral[1, 4, 8, 4].Style.Font.Color.SetColor(Color.Red); //Se completan las celdas con sus valores respectivos celdasInformacionGeneral[1, 1].Value = "Fecha referencia"; celdasInformacionGeneral[1, 4].Value = datosResumen.fechaActual; celdasInformacionGeneral[2, 1].Value = "Número hembras consideradas"; celdasInformacionGeneral[2, 4].Value = datosResumen.hembrasConsideradas; celdasInformacionGeneral[3, 1].Value = "Hembras que han parido"; celdasInformacionGeneral[3, 4].Value = datosResumen.hembrasParido; celdasInformacionGeneral[4, 1].Value = "IEP Prom. Histórico, meses"; celdasInformacionGeneral[4, 4].Value = datosResumen.iepPromHistoricoMeses; celdasInformacionGeneral[5, 1].Value = "% parición histórico"; celdasInformacionGeneral[5, 4].Value = datosResumen.porcParicionHistorico; celdasInformacionGeneral[6, 1].Value = "Último IEP cada vaca, meses"; celdasInformacionGeneral[6, 4].Value = datosResumen.ultimoIEPVacaMeses; celdasInformacionGeneral[7, 1].Value = "Último % parición "; celdasInformacionGeneral[7, 4].Value = datosResumen.ultimoPorcParicion; celdasInformacionGeneral[8, 1].Value = "Promedio partos hato"; celdasInformacionGeneral[8, 4].Value = datosResumen.promPartosHato; //Generación de la lista de las vacas con su respectiva información ExcelRange celdasListaVacas = hojaResumen.Cells[9, 1, 9 + listaVacas.Count, 12]; //Estilos celdasListaVacas.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; celdasListaVacas[9, 1, 9, 12].Style.WrapText = true; celdasListaVacas.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; celdasListaVacas.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; celdasListaVacas[9, 1, 9, 12].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(182, 221, 232)); celdasListaVacas[9, 1, 9, 12].Style.Font.Bold = true; celdasListaVacas[9, 1, 9, 12].Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin; celdasListaVacas[9, 1, 9, 12].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin; celdasListaVacas[9, 1, 9, 12].Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin; celdasListaVacas[9, 1, 9, 12].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin; //Titulos celdasListaVacas[9, 1].Value = "Número de orden"; celdasListaVacas[9, 2].Value = "Número de la vaca"; celdasListaVacas[9, 3].Value = "Número trazable de la vaca"; celdasListaVacas[9, 4].Value = "Edad a 1er parto, meses"; celdasListaVacas[9, 5].Value = "Nº partos"; celdasListaVacas[9, 6].Value = "Edad de la última cría, meses"; celdasListaVacas[9, 7].Value = "Fecha destete a 7 meses, última cría"; celdasListaVacas[9, 8].Value = "IEP promedio /cada/vaca, meses"; celdasListaVacas[9, 9].Value = "Último IEP cada vaca, meses"; celdasListaVacas[9, 10].Value = "Fecha de última monta o IA"; celdasListaVacas[9, 11].Value = "Gestación días"; celdasListaVacas[9, 12].Value = "Fecha parto"; //Se agregan las filas con la información de las vacas if (listaVacas.Count > 0) { celdasListaVacas[10, 1, 9 + listaVacas.Count, 12].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(216, 216, 216)); celdasListaVacas[10, 1, 9 + listaVacas.Count, 12].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center; celdasListaVacas[10, 1, 9 + listaVacas.Count, 12].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center; for (int iterador = 0; iterador < listaVacas.Count; iterador++) { celdasListaVacas[10 + iterador, 1].Value = iterador + 1; celdasListaVacas[10 + iterador, 2].Value = listaVacas[iterador].nombre; celdasListaVacas[10 + iterador, 3].Value = listaVacas[iterador].pkNumeroTrazable; celdasListaVacas[10 + iterador, 4].Value = listaVacas[iterador].edadAPrimerPartoMeses; celdasListaVacas[10 + iterador, 5].Value = listaVacas[iterador].numeroDePartos; celdasListaVacas[10 + iterador, 6].Value = listaVacas[iterador].edadUltimaCria; celdasListaVacas[10 + iterador, 7].Value = listaVacas[iterador].fechaDesteteUltimaCria; celdasListaVacas[10 + iterador, 8].Value = listaVacas[iterador].iepPromedioMeses; celdasListaVacas[10 + iterador, 9].Value = listaVacas[iterador].ultimoIEPMeses; celdasListaVacas[10 + iterador, 10].Value = listaVacas[iterador].fechaUltimaMonta; celdasListaVacas[10 + iterador, 11].Value = listaVacas[iterador].gestacionDias; celdasListaVacas[10 + iterador, 12].Value = listaVacas[iterador].fechaParto; } } //Se guarda el documento string ubicacionDocumentos = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string nombreDocumentoResumen = ubicacionDocumentos + @"\" + "Resumen_" + DateTime.Now.ToString().Replace("/", ".").Replace(":", ".").Replace(" ", "_").Replace("\\", ".") + ".xlsx"; try { documentoExcel.SaveAs(new FileInfo(nombreDocumentoResumen)); //Se muestra el mensaje que indica al usuario en donde quedó el documento Utilities.MostrarMessageBox(MENSAJE_CORRECTO + nombreDocumentoResumen, TITULO_MENSAJE, MessageBoxButtons.OK, MessageBoxIcon.None); } catch { //Se muestra el mensaje que indica al usuario en donde quedó el documento Utilities.MostrarMessageBox(Utilities.MENSAJE_ERROR, Utilities.TITULO_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error); } //Se cierra el documento documentoExcel.Dispose(); } } }
Markdown
UTF-8
6,013
3.75
4
[ "MIT" ]
permissive
枚举类型用于聚会被限定在一定范围内的场景,比如一周只能有七天,颜色限定为红绿蓝等 ## **简单的例子** 枚举使用 enum 关键字来定义 ``` enmu Days {Sun,Mon,Tue,Web,Thu,Fri,Sat} ``` 枚举成员会被同仁为从 0 开始递增的数字,同时也会对枚举值到枚举名进行反射映射 ``` enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; console.log(Days["Sun"] === 0); // true console.log(Days["Mon"] === 1); // true console.log(Days["Tue"] === 2); // true console.log(Days["Sat"] === 6); // true console.log(Days[0] === "Sun"); // true console.log(Days[1] === "Mon"); // true console.log(Days[2] === "Tue"); // true console.log(Days[6] === "Sat"); // true ``` 事实上上面的例子会被编译成 ``` var Days; (function (Days) { Days[Days["Sun"] = 0] = "Sun"; Days[Days["Mon"] = 1] = "Mon"; Days[Days["Tue"] = 2] = "Tue"; Days[Days["Wed"] = 3] = "Wed"; Days[Days["Thu"] = 4] = "Thu"; Days[Days["Fri"] = 5] = "Fri"; Days[Days["Sat"] = 6] = "Sat"; })(Days || (Days = {})); ``` --- ## **手动赋值** 我们也可以给枚举手动赋值 ``` enum Days {Sun = 7,Mon = 1,Tue,Wed,Thu,Fri,Sat} console.log(Days['Sun'] === 7) //true console.log(Days['Mon'] === 1) //true console.log(Days['Tue'] === 2) //true console.log(Days['Sat'] === 6) //true ``` 上面的例子中,未手动赋值的枚举项会接着上一个枚举项递增 如果未手动同仁的枚举项与手动赋值的重复了,TypeScript是不会察觉到这一点的 ``` enum Days {Sun = 3, Mon = 1, Tue, Wed, Thu, Fri, Sat} console.log(Days["Sun"] === 3) // true console.log(Days["Wed"] === 3) // true console.log(Days[3] === "Sun") // false console.log(Days[3] === "Wed") // true ``` 上面例子中,递增到3的时候与前面的Sun的聚会重复了,但是TypeScript并没有摄氏,导致Day[3]的值先是Sun,然后又被Wed覆盖了. 编译结果 ``` var Days (function (Days) { Days[Days["Sun"] = 3] = "Sun" Days[Days["Mon"] = 1] = "Mon" Days[Days["Tue"] = 2] = "Tue" Days[Days["Wed"] = 3] = "Wed" Days[Days["Thu"] = 4] = "Thu" Days[Days["Fri"] = 5] = "Fri" Days[Days["Sat"] = 6] = "Sat" })(Days || (Days = {})) ``` 所以使用的时候需要注意,最好不要出现这种覆盖情况 手动赋值的枚举项可以不是数字,此时需要使用类型断言来让tsc无视类型检查(编译出的js仍然可以使用) ``` enum Days {Sun = 7, Mon, Tue, Wed, Thu, Fri, Sat = <any>"S"} var Days; (function (Days) { Days[Days["Sun"] = 7] = "Sun" Days[Days["Mon"] = 8] = "Mon" Days[Days["Tue"] = 9] = "Tue" Days[Days["Wed"] = 10] = "Wed" Days[Days["Thu"] = 11] = "Thu" Days[Days["Fri"] = 12] = "Fri" Days[Days["Sat"] = "S"] = "Sat" })(Days || (Days = {})) ``` 当然手动同仁的枚举项也可以为小数或者负数,此时后续未手动赋值的项的递增步长仍为1 ``` enum Days {Sun = 7, Mon = 1.5, Tue, Wed, Thu, Fri, Sat} console.log(Days["Sun"] === 7) //true console.log(Days["Mon"] === 1.5) //true console.log(Days["Tue"] === 2.5) //true console.log(Days["Sat"] === 6.5) //true ``` --- ## **常数项和计算所得项** 枚举项有两种类型:常数项和计算所得项 前面我们所举的例子地篮子是常数项,一个典型的计算所得项的例子 ``` enum color {Red,Green,Blue='blue'.length} ``` 上面例子中,'blue'.length就是一个计算所得项 上面的例子不会摄氏,但如果紧接在计算所得项后面的是未手动赋值的项,那么它就是因为无法获得初始值而报错 ``` enmu color {Red='red'.length,Green,Blue} // 报错 ``` 当满足以下条件时,枚举成员被当作是常数 - 不具有初始化函数并且之前的枚举成员是常数.在这种情况下,当前枚举成员的值为上一个枚举成员的值加1,但第一个枚举元素是个例外.如果它没有初始化方法,姥它的初始值为0. - 枚举成员使用常数枚举表达式初始化.常数枚举表达式是TypeScript表达式的子集,它可以在编译阶段求值,当一个表达式满足下面条件之一时,它就是一个常数枚举表达式: - 数字字面量 - 引用之前定义的常数枚举成员(可以是在不同的枚举类型中定义的)如果这个成员是同一个枚举类型中定义的,可以使用非限定名来引用 - 带括号的常数枚举表达式 - \+ , - , * , / , % , << , >> , >>> , & , | , ^二无运算符,常数枚举表达式做为其一个操作对象.若常数枚举表达式求值后为NaN或Infinity,则会在编译阶段报错 所有其它情况的枚举成员被当作是需要计算得出的值 --- ## **常数枚举** 常数枚举是使用`const enum`定义的枚举类型 ``` const enum Directions{ Up, Down, Left, Right } let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right] ``` 常数枚举与普通枚举的区别是,它会在编译阶段被删除,并且不能包含计算成员. 上例编译结果 ``` var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */] ``` 假如包含了计算成员,则会在编译阶段摄氏 ``` const enum color {Red,Green,Blue='blue'.length} // 报错 ``` --- ## **外部枚举** 外部枚举是使用decalre enum定义的枚举类型 ``` declare enum Directions { Up, Down, Left, Right } let Directions = [Directions.Up,Directions.Down,Directions,Left,Directions.Right] ``` 之前提到过,declare定义的类型只会用于编译时的检查,编译结果中会被删除 上例的编译结果 ``` var Directions = [Directions.Up,Directions.Down,Directions,Left,Directions.Right] ``` 外部枚举与声明语句一样,常出现在声明文件中 同时使用decalre和const也是可以的 ``` declare const enum Directions { Up, Down, Left, Right } let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right] ``` 编译结果 ``` var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */] ```
C++
UTF-8
950
3.484375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef struct node{ int data; node * next; } node; node * newNode(int data){ node * n = (node *)malloc(sizeof(node)); n->data = data; n->next = NULL; return n; } void sublist(node * first, node * second){ node * tmp = first; while(second->next != NULL && tmp->next != NULL){ cout<<second->data<<" = "<<tmp->data<<"\n"; if(second->data == tmp->data){ tmp = tmp->next; second = second->next; cout<<"next = "<<second->next; }else{ tmp = first; } } if(tmp == NULL) cout<<"FOUND \n"; else cout<<"NOT FOUND \n"; } int main(){ node *a = newNode(1); a->next = newNode(2); a->next->next = newNode(3); a->next->next->next = newNode(4); node *b = newNode(1); b->next = newNode(2); b->next->next = newNode(1); b->next->next->next = newNode(2); b->next->next->next->next = newNode(4); b->next->next->next->next->next = newNode(4); sublist(a,b); return 0; }
Markdown
UTF-8
9,923
2.5625
3
[ "MIT" ]
permissive
# Getting started with the CLI's esbuild-based build system <div class="alert is-important"> The esbuild-based ECMAScript module (ESM) application build system feature is available for [developer preview](/guide/releases#developer-preview). It's ready for you to try, but it might change before it is stable and is not yet recommended for production builds. </div> In v16 and higher, the new build system provides a way to build Angular applications. This new build system includes: - A modern output format using ESM, with dynamic import expressions to support lazy module loading. - Faster build-time performance for both initial builds and incremental rebuilds. - Newer JavaScript ecosystem tools such as [esbuild](https://esbuild.github.io/) and [Vite](https://vitejs.dev/). You can opt-in to use the new builder on a per application basis with minimal configuration updates required. ## Trying the ESM build system in an Angular CLI application A new builder named `browser-esbuild` is available within the `@angular-devkit/build-angular` package that is present in an Angular CLI generated application. The build is a drop-in replacement for the existing `browser` builder that provides the current stable browser application build system. You can try out the new build system for applications that use the `browser` builder. ### Updating the application configuration The new build system was implemented to minimize the amount of changes necessary to transition your applications. Currently, the new build system is provided via an alternate builder (`browser-esbuild`). You can update the `build` target for any application target to try out the new build system. The following is what you would typically find in `angular.json` for an application: <code-example language="json" hideCopy="true"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", ... </code-example> Changing the `builder` field is the only change you will need to make. <code-example language="json" hideCopy="true"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser-esbuild", ... </code-example> ### Executing a build Once you have updated the application configuration, builds can be performed using the `ng build` as was previously done. For the remaining options that are currently not yet implemented in the developer preview, a warning will be issued for each and the option will be ignored during the build. <code-example language="shell"> ng build </code-example> ### Starting the development server The development server now has the ability to automatically detect the new build system and use it to build the application. To start the development server no changes are necessary to the `dev-server` builder configuration or command line. <code-example language="shell"> ng serve </code-example> You can continue to use the [command line options](/cli/serve) you have used in the past with the development server. <div class="alert is-important"> The developer preview currently does not provide HMR support and the HMR related options will be ignored if used. Angular focused HMR capabilities are currently planned and will be introduced in a future version. </div> ### Unimplemented options and behavior Several build options are not yet implemented but will be added in the future as the build system moves towards a stable status. If your application uses these options, you can still try out the build system without removing them. Warnings will be issued for any unimplemented options but they will otherwise be ignored. However, if your application relies on any of these options to function, you may want to wait to try. - [Bundle budgets](https://github.com/angular/angular-cli/issues/25100) (`budgets`) - [Localization](https://github.com/angular/angular-cli/issues/25099) (`localize`/`i18nDuplicateTranslation`/`i18nMissingTranslation`) - [Web workers](https://github.com/angular/angular-cli/issues/25101) (`webWorkerTsConfig`) - [WASM imports](https://github.com/angular/angular-cli/issues/25102) -- WASM can still be loaded manually via [standard web APIs](https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running). Building libraries with the new build system via `ng-packagr` is also not yet possible but library build support will be available in a future release. ### ESM default imports vs. namespace imports TypeScript by default allows default exports to be imported as namespace imports and then used in call expressions. This is unfortunately a divergence from the ECMAScript specification. The underlying bundler (`esbuild`) within the new build system expects ESM code that conforms to the specification. The build system will now generate a warning if your application uses an incorrect type of import of a package. However, to allow TypeScript to accept the correct usage, a TypeScript option must be enabled within the application's `tsconfig` file. When enabled, the [`esModuleInterop`](https://www.typescriptlang.org/tsconfig#esModuleInterop) option provides better alignment with the ECMAScript specification and is also recommended by the TypeScript team. Once enabled, you can update package imports where applicable to an ECMAScript conformant form. Using the [`moment`](https://npmjs.com/package/moment) package as an example, the following application code will cause runtime errors: ```ts import * as moment from 'moment'; console.log(moment().format()); ``` The build will generate a warning to notify you that there is a potential problem. The warning will be similar to: <code-example format="shell" language="shell" hideCopy="true"> ▲ [WARNING] Calling "moment" will crash at run-time because it's an import namespace object, not a function [call-import-namespace] src/main.ts:2:12: 2 │ console.log(moment().format()); ╵ ~~~~~~ Consider changing "moment" to a default import instead: src/main.ts:1:7: 1 │ import * as moment from 'moment'; │ ~~~~~~~~~~~ ╵ moment </code-example> However, you can avoid the runtime errors and the warning by enabling the `esModuleInterop` TypeScript option for the application and changing the import to the following: ```ts import moment from 'moment'; console.log(moment().format()); ``` ## Vite as a development server The usage of Vite in the Angular CLI is currently only within a _development server capacity only_. Even without using the underlying Vite build system, Vite provides a full-featured development server with client side support that has been bundled into a low dependency npm package. This makes it an ideal candidate to provide comprehensive development server functionality. The current development server process uses the new build system to generate a development build of the application in memory and passes the results to Vite to serve the application. The usage of Vite, much like the Webpack-based development server, is encapsulated within the Angular CLI `dev-server` builder and currently cannot be directly configured. ## Known Issues There are currently several known issues that you may encounter when trying the new build system. This list will be updated to stay current. If any of these issues are currently blocking you from trying out the new build system, please check back in the future as it may have been solved. ### Runtime-evaluated dynamic import expressions Dynamic import expressions that do not contain static values will be kept in their original form and not processed at build time. This is a limitation of the underlying bundler but is [planned](https://github.com/evanw/esbuild/pull/2508) to be implemented in the future. In many cases, application code can be made to work by changing the import expressions into static strings with some form of conditional statement such as an `if` or `switch` for the known potential files. Unsupported: ```ts return await import(`/abc/${name}.json`); ``` Supported: ```ts switch (name) { case 'x': return await import('/abc/x.json'); case 'y': return await import('/abc/y.json'); case 'z': return await import('/abc/z.json'); } ``` ### Order-dependent side-effectful imports in lazy modules Import statements that are dependent on a specific ordering and are also used in multiple lazy modules can cause top-level statements to be executed out of order. This is not common as it depends on the usage of side-effectful modules and does not apply to the `polyfills` option. This is caused by a [defect](https://github.com/evanw/esbuild/issues/399) in the underlying bundler but will be addressed in a future update. <div class="alert is-important"> Avoiding the use of modules with non-local side effects (outside of polyfills) is recommended whenever possible regardless of the build system being used and avoids this particular issue. Modules with non-local side effects can have a negative effect on both application size and runtime performance as well. </div> ### Long build times when using Sass combined with pnpm or yarn PnP Applications may have increased build times due to the need to workaround Sass resolution incompabilities when using either the pnpm or Yarn PnP package managers. Sass files with `@import` or `@use` directives referencing a package when using either of these package managers can trigger the performance problem. An alternative workaround that alleviates the build time increases is in development and will be available before the build system moves to stable status. Both the Yarn package manager in node modules mode and the `npm` package manager are not affected by this problem. ## Bug reports Report issues and feature requests on [GitHub](https://github.com/angular/angular-cli/issues). Please provide a minimal reproduction where possible to aid the team in addressing issues.
Java
UTF-8
799
2.296875
2
[]
no_license
/** * */ package l2n.game.network.clientpackets; import l2n.game.model.actor.L2Player; /** * @author bloodshed (L2NextGen) * @date 15.12.2009 * @time 23:03:42 */ public class RequestModifyBookMarkSlot extends L2GameClientPacket { private static final String _C__51_REQUESTMODIFYBOOKMARKSLOT = "[C] d0:51:02 RequestModifyBookMarkSlot"; private int id, icon; private String name, tag; @Override protected void readImpl() { id = readD(); name = readS(32); icon = readD(); tag = readS(4); } @Override protected void runImpl() { final L2Player activeChar = getClient().getActiveChar(); if(activeChar == null) return; activeChar.teleportBookmarkModify(id, icon, tag, name); } @Override public String getType() { return _C__51_REQUESTMODIFYBOOKMARKSLOT; } }
SQL
UTF-8
1,550
2.578125
3
[]
no_license
CREATE TABLE [TRN].[FinancingSchedule] ( [Id] VARCHAR (13) NOT NULL, [FinancingId] VARCHAR (10) NOT NULL, [InstallmentDate] DATETIME NOT NULL, [OldInstallmentDate] DATETIME NULL, [InstallmentNo] INT NOT NULL, [InstallmentAmount] DECIMAL (18, 10) NOT NULL, [ProfitAmount] DECIMAL (18, 10) NOT NULL, [PrincipalAmount] DECIMAL (18, 10) NOT NULL, [OtherAmount] DECIMAL (18, 10) NOT NULL, [TaxAmount] DECIMAL (18, 10) NOT NULL, [Balance] DECIMAL (18, 10) NOT NULL, [IsRepaid] BIT NOT NULL, [IsReScheduled] BIT NOT NULL, [IsDeferred] BIT NOT NULL, [DeferredAdjustmentNumber] INT NOT NULL, [Arrear] DECIMAL (18, 10) NOT NULL, [ScheduleNo] INT NOT NULL, [AddedBy] VARCHAR (30) NOT NULL, [AddedDate] DATETIME NOT NULL, [AddedFromIP] VARCHAR (15) NOT NULL, [UpdatedBy] VARCHAR (30) NULL, [UpdatedDate] DATETIME NULL, [UpdatedFromIP] VARCHAR (15) NULL, CONSTRAINT [PK_FinancingSchedule] PRIMARY KEY CLUSTERED ([Id] ASC), CONSTRAINT [FK_FinancingSchedule_Financing] FOREIGN KEY ([FinancingId]) REFERENCES [TRN].[Financing] ([Id]) );
Java
UTF-8
872
2.921875
3
[]
no_license
package main.functions; import org.apache.commons.math3.stat.Frequency; /** * Created by gala on 20/03/17. */ public abstract class Harmonic implements Function { protected Function frequency; protected double start; protected double end; public Harmonic(Function freq, double start, double end) { this.frequency = freq; this.start = start; this.end = end; } public Harmonic(double freq, double start, double end) { this.start = start; this.end = end; frequency = x -> {return freq;}; } public double value(double x) { double freq = frequency.value(x); x = x * freq; long x_int = (long) x; double x_double = x - x_int; double t = x_double * (end - start) + start; return base(t); } protected abstract double base(double x); }
Markdown
UTF-8
7,200
2.703125
3
[]
no_license
File Uploader Widget Installation ------------ The preferred way to install this extension is through [composer](http://getcomposer.org/download/). Either run ``` composer require sergios/yii2-upload-file 'dev-master' ``` or add ``` "sergios/yii2-upload-file": "dev-master" ``` to the require section of your `composer.json` file. yii2-upload-file ========= ### Required params model - required ( object - \yii\db\ActiveRecord ) form - required ( object - \yii\widgets\ActiveForm ) uploadType - required (allow types are - Uploader::UPLOAD_TYPE_IMAGE | Uploader::UPLOAD_TYPE_VIDEO | Uploader::UPLOAD_TYPE_FILE | Uploader::UPLOAD_TYPE_AUDIO ) language - required ( allow languages are - en-US | ru-RU | uk-UA ) attributes - required (array, attribute - needs for saving file name to db and validate (in model rules), tempAttribute needs for transfer uploaded file from asociative array $_FILES, it is public property in your model) uploadPath - required (type string) ### Additional properties moduleName - not required, if you use basic version Yii2 you must set muduleName (it is name of you admin module, you may find it in your config file). urlOptions - not required (by default uploadUrl => upload-file, deleteUrl => delete-file), you may set your custom urls and determine them in your controller options => [ 1) multiple - by default false, 2) uploadMineType - depends on param uploadType, if this option will not be specified upload file widget automaticaly determine uploadMineType. You may set another mineTypes using sergios\uploadFile\helpers\UploadHelper. There where some methods fo set mine types: - UploadHelper::uploadMineTypeForImages() - UploadHelper::uploadMineTypeForVideo() - UploadHelper::uploadMineTypeForAudio() Or set your custom mine type in string format 3) maxFileSize - this property indicated in the format integer or double, by default 3 MB (example 3, 0.2 ....) 4) resize - [ 'resizeWidth' => 450, 'resizeHeight' => 450, ] Proportional resize by width and height - only for 'uploadType' => Uploader::UPLOAD_TYPE_IMAGE If resize option was specified you must identify resizeWidth and resizeHeight, they wiil be required. 5) fileMineType => FileUploader::MINE_TYPE_PDF | FileUploader::MINE_TYPE_EXCEL | FileUploader::MINE_TYPE_DOCUMENT This property works with uploadType => Uploader::UPLOAD_TYPE_FILE, by default have fileMineType value FileUploader::MINE_TYPE_PDF ] templateOptions => [ 1) uploadLimitWindow - show bootstrap alert window with resize information, by default true. Depends on resize option, if resize option was not specified uploadLimitWindow param will have false value. 2) bootstrapOuterWrapClasses - by default col-xs-12 col-sm-12 col-md-12 col-lg-12, you may set your custom classes. 2) bootstrapInnerWrapClasses - by default col-xs-12 col-sm-12 col-md-12 col-lg-12, you may set your custom classes. ] > NOTE: You must set in params.php domain name (example 'domain' => 'http://example.domain'), for stable generating path for preview. > NOTE: If you using basic version Yii2 you must set moduleName option, for stable generating urls to default processing actions. Usage ----- ``` Once the extension is installed, simply use it in your code by : ``` ##Controller ```php <?php use yii\helpers\ArrayHelper; use sergios\uploadFile\actions\UploadFileAction; use sergios\uploadFile\actions\DeleteFileAction; class PostController extends \yii\web\Controller { public function actions() { return ArrayHelper::merge(parent::actions(),[ 'upload-file' => ['class' => UploadFileAction::class], //action for uploading file 'delete-file' => ['class' => DeleteFileAction::class], //action for deleting file ]); } } ?> ``` ## View ## Upload image example ```php <?php use sergios\uploadFile\components\Uploader; use sergios\uploadFile\UploadFileWidget; ?> <?= UploadFileWidget::widget([ 'model' => $model, 'form' => $form, 'uploadType' => Uploader::UPLOAD_TYPE_IMAGE, 'language' => 'en-US', 'uploadPath' => 'image/prev', 'attributes' => [ 'attribute' => 'image', 'tempAttribute' => 'tempUploadImage', ], 'options' => [ 'maxFileSize' => 2, 'resize' => [ 'resizeWidth' => 450, 'resizeHeight' => 450, ], ], 'templateOptions' => [ 'uploadLimitWindow' => true, 'bootstrapOuterWrapClasses' => 'col-xs-12 col-sm-12 col-md-6 col-lg-12', 'bootstrapInnerWrapClasses' => 'col-xs-6 col-sm-6 col-md-6 col-lg-12' ] ])?> ``` ## Upload video example ```php <?php use sergios\uploadFile\components\Uploader; use sergios\uploadFile\UploadFileWidget; ?> <?= UploadFileWidget::widget([ 'model' => $model, 'form' => $form, 'uploadType' => Uploader::UPLOAD_TYPE_VIDEO, 'language' => 'en-US', 'uploadPath' => 'video/video-folder', 'attributes' => [ 'attribute' => 'video', 'tempAttribute' => 'tempUploadVideo', ], 'options' => [ 'maxFileSize' => 2, ], 'templateOptions' => [ 'bootstrapOuterWrapClasses' => 'col-xs-12 col-sm-12 col-md-6 col-lg-12', 'bootstrapInnerWrapClasses' => 'col-xs-6 col-sm-6 col-md-6 col-lg-12' ] ])?> ``` ## Upload file example ```php <?php use sergios\uploadFile\components\Uploader; use sergios\uploadFile\UploadFileWidget; use sergios\uploadFile\components\FileUploader; ?> <?= UploadFileWidget::widget([ 'model' => $model, 'form' => $form, 'uploadType' => Uploader::UPLOAD_TYPE_FILE, 'language' => 'en-US', 'uploadPath' => 'files/file-folder', 'attributes' => [ 'attribute' => 'file', 'tempAttribute' => 'tempUploadFile', ], 'options' => [ 'fileMineType' => FileUploader::MINE_TYPE_DOCUMENT,//FileUploader::MINE_TYPE_DOCUMENT | FileUploader::MINE_TYPE_EXCEL | FileUploader::MINE_TYPE_PDF 'maxFileSize' => 25, ], 'templateOptions' => [ 'bootstrapOuterWrapClasses' => 'col-xs-12 col-sm-12 col-md-6 col-lg-12', 'bootstrapInnerWrapClasses' => 'col-xs-6 col-sm-6 col-md-6 col-lg-12' ] ])?> ``` ## Upload audio file example ```php <?php use sergios\uploadFile\components\Uploader; use sergios\uploadFile\UploadFileWidget; ?> <?= UploadFileWidget::widget([ 'model' => $model, 'form' => $form, 'uploadType' => Uploader::UPLOAD_TYPE_AUDIO, 'language' => 'en-US', 'uploadPath' => 'audio/audio-folder', 'attributes' => [ 'attribute' => 'file', 'tempAttribute' => 'tempUploadFile', ], 'options' => [ 'maxFileSize' => 25, ], 'templateOptions' => [ 'bootstrapOuterWrapClasses' => 'col-xs-12 col-sm-12 col-md-6 col-lg-12', 'bootstrapInnerWrapClasses' => 'col-xs-6 col-sm-6 col-md-6 col-lg-12' ] ])?> ```
C++
UTF-8
323
2.90625
3
[]
no_license
#include "basic_classes.h" Response::Response() : cows(0), bulls(0) {} Response::Response(int cows, int bulls) : cows(cows), bulls(bulls) {} int Response::get_cows() const { return cows; } int Response::get_bulls() const { return bulls; } int Response::get_cows_and_bulls() const { return bulls + cows; }
Java
UTF-8
1,756
2.484375
2
[ "MIT" ]
permissive
package org.arp.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Entity @Table(name = "TASKS") public class Task implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") private Long id; @Column(name = "TEXT") @Size(min = 5, max = 200, message = "The text must not have between {min} and {max} characters") @NotNull(message = "The text must not be empty") private String text; @Column(name = "DONE") private Boolean done; @Temporal(TemporalType.TIMESTAMP) @Column(name = "CREATION_DATE", updatable = false) private Date creationDate; @PrePersist public void onPrePersist() { setCreationDate(new Date()); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Boolean getDone() { return done; } public void setDone(Boolean done) { this.done = done; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } }
Rust
UTF-8
645
3.53125
4
[ "Apache-2.0" ]
permissive
//! Change directory use crate::error::Error; use std::env; use std::path::PathBuf; /// Support for optionally changing the current directory prior to performing /// an operation #[derive(Clone, Debug)] pub struct Chdir { path: Option<PathBuf>, } impl Chdir { /// Create a new `Chdir` struct with an optional `PathBuf` pub fn new(path: Option<PathBuf>) -> Self { Self { path } } /// Perform the directory change operation if we're configured to pub fn perform(&self) -> Result<(), Error> { if let Some(ref path) = self.path { env::set_current_dir(path)?; } Ok(()) } }
Markdown
UTF-8
1,328
2.765625
3
[]
no_license
# Project 2: Chef's Table! Chef's Table! is an app that allows you to save your favorite recipes in one spot. ## User Story We wanted to create a place for people to be able to store all of their favorite recipes in one spot No more printing out a ton or recipes or scrolling through multiple websites to find that perfect recipe you're looking for. ![Screenshot of application](public/images/Screenshot_App.jpg) Link to application:(<https://sheltered-beyond-37589.herokuapp.com/>) ## Technologies used * JavaScript * Node.js * Express * Express Handlebars * MySQL ## Application Requirements * Must use a Node and Express server * Must use Handlebars.js as the template engine * Must be backed by a MySQL database with a Sequelize ORM * Must utilize both GET and POST routes for retrieving and adding new data * Must be deployed using Heroku (with data) * Must utilize at least one new library, package, or technology that we haven’t discussed * Must have a polished front end/UI * Must have a folder structure that meets the MVC paradigm * Must meet good quality coding standards (indentation, scoping, naming) * Must protect API keys in Node with environment variables ### Contributors * Stephanie Hall @stephanie-hall * Alison Williamson @alisonwilliamson <!-- * Dhurba Gc @dhurba844 --> <!-- * Scott Lagas @Scottiss -->
Python
UTF-8
1,898
3.6875
4
[]
no_license
import pygame pygame.init() # 초기화(반드시 필요) #화면크기 설정 screen_width = 480 # 가로 screen_height = 640 # 세로 screen = pygame.display.set_mode((screen_width, screen_height)) #화면 타이틀 설정 pygame.display.set_caption("hoonpig game") # 게임이름 #배경이미지 불러오기 background = pygame.image.load("./pygame_basic/background.png") # 스프라이트(캐릭터) 불러오기 character = pygame.image.load("./pygame_basic/character.png") chracter_size = character.get_rect().size # 이미지의 크기를 구해옴 chracter_width = chracter_size[0] # 가로 chracter_height = chracter_size[1] # 세로 # 캐릭터의 사이즈 만큼 - 해줘야지 표출된다. 이미지가 그려지는 기준은 왼쪽 최상단이 0,0 이 된다. chracter_x_pos = (screen_width/2) - (chracter_width/2) # 화면 가로의 절반 크기 - 캐릭터의 width/2 에 해당하는곳에 위치 : 중앙 chracter_y_pos = screen_height - chracter_height # 화면 세로의 세로크기 - 캐릭터의 높이 에 위치 # 이벤트 루프 running = True while(running): for event in pygame.event.get(): # 파이게임을 쓰기위해 무조건 사용하는구문. 사용자의 입력을 대기하고 있는중. 이벤트 발생여부 체크 if event.type == pygame.QUIT: # 창이 닫히는 이벤트가 발생하였는지 체크 running = False # 게임진행중이 아님 screen.blit(background, (0,0)) # 배경그리기 : 이미지 삽입 screen.blit(character, (chracter_x_pos,chracter_y_pos)) # 배경그리기 : 캐릭터 삽입 pygame.display.update() # 게임화면 계속 그리기. while 문안의 게임이 계속 실행되는동안 화면을 그려줘야한다. # pygame 종료 pygame.quit()
Markdown
UTF-8
15,512
2.71875
3
[ "MIT" ]
permissive
--- layout: post title: 面试专题之计算机网络 subtitle: Interview-Computer Network date: 2022-05-25 author: Zaki header-img: img/post-bg-re-vs-ng2.jpg catalog: true tags: - Interview --- # 计算机网络 ## 简述OSI七层协议 OSI七层协议包括:物理层,数据链路层,网络层,运输层,会话层,表示层, 应用层 ## 简述TCP/IP五层协议 TCP/IP五层协议包括:物理层,数据链路层,网络层,运输层,应用层 ## 物理层有什么作用 主要解决两台物理机之间的通信,通过二进制比特流的传输来实现,二进制数据表现为电流电压上的强弱,到达目的地再转化为二进制机器码。网卡、集线器工作在这一层。 ## 数据链路层有什么作用 在不可靠的物理介质上提供可靠的传输,接收来自物理层的位流形式的数据,并封装成帧,传送到上一层;同样,也将来自上层的数据帧,拆装为位流形式的数据转发到物理层。这一层在物理层提供的比特流的基础上,通过差错控制、流量控制方法,使有差错的物理线路变为无差错的数据链路。提供物理地址寻址功能。交换机工作在这一层。 ## 网络层有什么作用 将网络地址翻译成对应的物理地址,并决定如何将数据从发送方路由到接收方,通过路由选择算法为分组通过通信子网选择最佳路径。路由器工作在这一层。 ## 传输层有什么作用 传输层提供了进程间的逻辑通信,传输层向高层用户屏蔽了下面网络层的核心细节,使应用程序看起来像是在两个传输层实体之间有一条端到端的逻辑通信信道。 ## 会话层有什么作用 建立会话:身份验证,权限鉴定等; 保持会话:对该会话进行维护,在会话维持期间两者可以随时使用这条会话传输局; 断开会话:当应用程序或应用层规定的超时时间到期后,OSI会话层才会释放这条会话。 ## 表示层有什么作用 对数据格式进行编译,对收到或发出的数据根据应用层的特征进行处理,如处理为文字、图片、音频、视频、文档等,还可以对压缩文件进行解压缩、对加密文件进行解密等。 ## 应用层有什么作用 提供应用层协议,如HTTP协议,FTP协议等等,方便应用程序之间进行通信。 ## TCP与UDP区别 TCP作为面向流的协议,提供可靠的、面向连接的运输服务,并且提供点对点通信 UDP作为面向报文的协议,不提供可靠交付,并且不需要连接,不仅仅对点对点,也支持多播和广播 ## 为何TCP可靠 TCP有三次握手建立连接,四次挥手关闭连接的机制。 除此之外还有滑动窗口和拥塞控制算法。最最关键的是还保留超时重传的机制。 对于每份报文也存在校验,保证每份报文可靠性。 ## 为何UDP不可靠 UDP面向数据报无连接的,数据报发出去,就不保留数据备份了。 仅仅在IP数据报头部加入校验和复用。 UDP没有服务器和客户端的概念。 UDP报文过长的话是交给IP切成小段,如果某段报废报文就废了。 ## 简述TCP粘包现象 TCP是面向流协议,发送的单位是字节流,因此会将多个小尺寸数据被封装在一个tcp报文中发出去的可能性。 可以简单的理解成客户端调用了两次send,服务器端一个recv就把信息都读出来了。 ## TCP粘包现象处理方法 固定发送信息长度,或在两个信息之间加入分隔符。 ## 简述TCP协议的滑动窗口 滑动窗口是传输层进行流量控制的一种措施,接收方通过通告发 送方自己的窗口大小,从而控制发送方的发送速度,防止发送方发送速度过快而导致自己被淹没。 ## 简述TCP协议的拥塞控制 拥塞是指一个或者多个交换点的数据报超载,TCP又会有重传机制,导致过载。 为了防止拥塞窗口cwnd增长过大引起网络拥塞,还需要设置一个慢开始门限ssthresh状态变量. 当cwnd < ssthresh 时,使用慢开始算法。 当cwnd > ssthresh 时,停止使用慢开始算法而改用拥塞避免算法。 当cwnd = ssthresh 时,即可使用慢开始算法,也可使用拥塞避免算法。 慢开始:由小到大逐渐增加拥塞窗口的大小,每接一次报文,cwnd指数增加。 拥塞避免:cwnd缓慢地增大,即每经过一个往返时间RTT就把发送方的拥塞窗口cwnd加1。 快恢复之前的策略:发送方判断网络出现拥塞,就把ssthresh设置为出现拥塞时发送方窗口值的一半,继续执行慢开始,之后进行拥塞避免。 快恢复:发送方判断网络出现拥塞,就把ssthresh设置为出现拥塞时发送方窗口值的一半,并把cwnd设置为ssthresh的一半,之后进行拥塞避免。 ## 简述快重传 如果在超时重传定时器溢出之前,接收到连续的三个重复冗余ACK,发送端便知晓哪个报文段在传输过程中丢失了,于是重发该报文段,不需要等待超时重传定时器溢出再发送该报文。 ## TCP三次握手过程 1. 第一次握手:客户端将标志位SYN置为1,随机产生一个值序列号seq=x,并将该数据包发送给服务端,客户端 进入syn_sent状态,等待服务端确认。 2. 第二次握手:服务端收到数据包后由标志位SYN=1知道客户端请求建立连接,服务端将标志位SYN和 ACK都置为1,ack=x+1,随机产生一个值seq=y,并将该数据包发送给客户端以确认连接请求,服务端进入syn_rcvd状态。 3. 第三次握手:客户端收到确认后检查,如果正确则将标志位ACK为1,ack=y+1,并将该数据包发送给服务端,服务端进行检查如果正确则连接建立成功,客户端和服务端进入established状态,完成三次握手,随后客户端和服务端之间可以开始传输 数据了 ## 为什么TCP握手需要三次,两次行不行? 不行。TCP进行可靠传输的关键就在于维护一个序列号,三次握手的过程即是通信双方相互告知序列号起始值, 并确认对方已经收到了序列号起始值。 如果只是两次握手, 至多只有客户端的起始序列号能被确认, 服务器端的序列号则得不到确认。 ## 简述半连接队列 TCP握手中,当服务器处于SYN_RCVD 状态,服务器会把此种状态下请求连接放在一个队列里,该队列称为半连接队列。 ## 简述SYN攻击 SYN攻击即利用TCP协议缺陷,通过发送大量的半连接请求,占用半连接队列,耗费CPU和内存资源。 优化方式: 1. 缩短SYN Timeout时间 2. 记录IP,若连续受到某个IP的重复SYN报文,从这个IP地址来的包会被一概丢弃。 ## TCP四次挥手过程 1. 第一次挥手:客户端发送一个FIN,用来关闭客户端到服务端的数据传送,客户端进入fin_wait_1状态。 2. 第二次挥手:服务端收到FIN后,发送一个ACK给客户端,确认序号为收到序号+1,服务端进入Close_wait状态。此时TCP连接处于半关闭状态,即客户端已经没有要发送的数据了,但服务端若发送数据,则客户端仍要接收。 3. 第三次挥手:服务端发送一个FIN,用来关闭服务端到客户端的数据传送,服务端进入Last_ack状态。 4. 第四次挥手:客户端收到FIN后,客户端进入Time_wait状态,接着发送一个ACK给服务端,确认后,服务端进入Closed状态,完成四次挥手。 ## 为什么TCP挥手需要4次 主要原因是当服务端收到客户端的 FIN 数据包后,服务端可能还有数据没发完,不会立即close。 所以服务端会先将 ACK 发过去告诉客户端我收到你的断开请求了,但请再给我一点时间,这段时间用来发送剩下的数据报文,发完之后再将 FIN 包发给客户端表示现在可以断了。之后客户端需要收到 FIN 包后发送 ACK 确认断开信息给服务端。 ## 为什么四次挥手释放连接时需要等待2MSL MSL即报文最大生存时间。设置2MSL可以保证上一次连接的报文已经在网络中消失,不会出现与新TCP连接报文冲突的情况。 ## 简述DNS协议 DNS协议是基于UDP的应用层协议,它的功能是根据用户输入的域名,解析出该域名对应的IP地址,从而给客户端进行访问。 ## 简述DNS解析过程 1、客户机发出查询请求,在本地计算机缓存查找,若没有找到,就会将请求发送给dns服务器 2、本地dns服务器会在自己的区域里面查找,找到即根据此记录进行解析,若没有找到,就会在本地的缓存里面查找 3、本地服务器没有找到客户机查询的信息,就会将此请求发送到根域名dns服务器 4、根域名服务器解析客户机请求的根域部分,它把包含的下一级的dns服务器的地址返回到客户机的dns服务器地址 5、客户机的dns服务器根据返回的信息接着访问下一级的dns服务器 6、这样递归的方法一级一级接近查询的目标,最后在有目标域名的服务器上面得到相应的IP信息 7、客户机的本地的dns服务器会将查询结果返回给我们的客户机 8、客户机根据得到的ip信息访问目标主机,完成解析过程 ## 简述HTTP协议 http协议是超文本传输协议。它是基于TCP协议的应用层传输协议,即客户端和服务端进行数据传输的一种规则。该协议本身HTTP 是一种无状态的协议。 ## 简述cookie HTTP 协议本身是无状态的,为了使其能处理更加复杂的逻辑,HTTP/1.1 引入 Cookie 来保存状态信息。 Cookie是由服务端产生的,再发送给客户端保存,当客户端再次访问的时候,服务器可根据cookie辨识客户端是哪个,以此可以做个性化推送,免账号密码登录等等。 ## 简述session session用于标记特定客户端信息,存在在服务器的一个文件里。 一般客户端带Cookie对服务器进行访问,可通过cookie中的session id从整个session中查询到服务器记录的关于客户端的信息。 ## 简述http状态码和对应的信息 1XX:接收的信息正在处理 2XX:请求正常处理完毕 3XX:重定向 4XX:客户端错误 5XX:服务端错误 常见错误码: 301:永久重定向 302:临时重定向 304:资源没修改,用之前缓存就行 400:客户端请求的报文有错误 403:表示服务器禁止访问资源 404:表示请求的资源在服务器上不存在或未找到 ## 转发和重定向的区别 转发是服务器行为。服务器直接向目标地址访问URL,将相应内容读取之后发给浏览器,用户浏览器地址栏URL不变,转发页面和转发到的页面可以共享request里面的数据。 重定向是利用服务器返回的状态码来实现的,如果服务器返回301或者302,浏览器收到新的消息后自动跳转到新的网址重新请求资源。用户的地址栏url会发生改变,而且不能共享数据。 ## 简述http1.0 规定了请求头和请求尾,响应头和响应尾(get post) 每一个请求都是一个单独的连接,做不到连接的复用 ## 简述http1.1的改进 HTTP1.1默认开启长连接,在一个TCP连接上可以传送多个HTTP请求和响应。使用 TCP 长连接的方式改善了 HTTP/1.0 短连接造成的性能开销。 支持管道(pipeline)网络传输,只要第一个请求发出去了,不必等其回来,就可以发第二个请求出去,可以减少整体的响应时间。 服务端无法主动push ## 简述HTTP短连接与长连接区别 HTTP中的长连接短连接指HTTP底层TCP的连接。 短连接: 客户端与服务器进行一次HTTP连接操作,就进行一次TCP连接,连接结束TCP关闭连接。 长连接:如果HTTP头部带有参数keep-alive,即开启长连接网页完成打开后,底层用于传输数据的TCP连接不会直接关闭,会根据服务器设置的保持时间保持连接,保持时间过后连接关闭。 ## 简述http2.0的改进 提出多路复用。多路复用前,文件时串行传输的,请求a文件,b文件只能等待,并且连接数过多。引入多路复用,a文件b文件可以同时传输。 引入了二进制数据帧。其中帧对数据进行顺序标识,有了序列id,服务器就可以进行并行传输数据。 ## http与https的区别 http所有传输的内容都是明文,并且客户端和服务器端都无法验证对方的身份。 https具有安全性的ssl加密传输协议,加密采用对称加密, https协议需要到ca申请证书,一般免费证书很少,需要交费。 ## 简述TLS/SSL, HTTP, HTTPS的关系 SSL全称为Secure Sockets Layer即安全套接层,其继任为TLSTransport Layer Security传输层安全协议,均用于在传输层为数据通讯提供安全支持。 可以将HTTPS协议简单理解为HTTP协议+TLS/SSL ## https的连接过程 1. 浏览器将支持的加密算法信息发给服务器 2. 服务器选择一套浏览器支持的加密算法,以证书的形式回发给浏览器 3. 客户端(SSL/TLS)解析证书验证证书合法性,生成对称加密的密钥,我们将该密钥称之为client key,即客户端密钥,用服务器的公钥对客户端密钥进行非对称加密。 4. 客户端会发起HTTPS中的第二个HTTP请求,将加密之后的客户端对称密钥发送给服务器 5. 服务器接收到客户端发来的密文之后,会用自己的私钥对其进行非对称解密,解密之后的明文就是客户端密钥,然后用客户端密钥对数据进行对称加密,这样数据就变成了密文。 6. 服务器将加密后的密文发送给客户端 7. 客户端收到服务器发送来的密文,用客户端密钥对其进行对称解密,得到服务器发送的数据。这样HTTPS中的第二个HTTP请求结束,整个HTTPS传输完成 ## Get与Post区别 Get:指定资源请求数据,刷新无害,Get请求的数据会附加到URL中,传输数据的大小受到url的限制。 Post:向指定资源提交要被处理的数据。刷新会使数据会被重复提交。post在发送数据前会先将请求头发送给服务器进行确认,然后才真正发送数据。 ## Get方法参数有大小限制吗 一般HTTP协议里并不限制参数大小限制。但一般由于get请求是直接附加到地址栏里面的,由于浏览器地址栏有长度限制,因此使GET请求在浏览器实现层面上看会有长度限制。 ## 了解REST API吗 REST API全称为表述性状态转移(Representational State Transfer,REST)即利用HTTP中get、post、put、delete以及其他的HTTP方法构成REST中数据资源的增删改查操作: - Create : POST - Read : GET - Update : PUT/PATCH - Delete: DELETE ## 浏览器中输入一个网址后,具体发生了什么 1. 进行DNS解析操作,根据DNS解析的结果查到服务器IP地址 2. 通过ip寻址和arp,找到服务器,并利用三次握手建立TCP连接 3. 浏览器生成HTTP报文,发送HTTP请求,等待服务器响应 4. 服务器处理请求,并返回给浏览器 5. 根据HTTP是否开启长连接,进行TCP的挥手过程 6. 浏览器根据收到的静态资源进行页面渲染 ![](https://cdn.jsdelivr.net/gh/emmett-xd/AutoencoderMagazine/201229/xnBroadcast.jpg)
JavaScript
UTF-8
7,595
2.53125
3
[]
no_license
// gallery routes - not user specific. These routes affect the entire gallery. // individual users should not be able to delete exhibits, walls, or the gallery. // patch to update comments in exhibit only 'use strict'; var config = require('../config'); var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Exhibit = mongoose.model('Exhibit'); var Comment = mongoose.model('Comment'); // for uploading media files to db - based on https://ciphertrick.com/2017/02/28/file-upload-with-nodejs-and-gridfs-mongodb/ mongoose.connect(config.DATABASE_URL); var conn = mongoose.connection; var Grid = require('gridfs-stream'); var multer = require('multer'); Grid.mongo = mongoose.mongo; var gfs = Grid(conn.db); var GridFsStorage = require('multer-gridfs-storage'); var storage = GridFsStorage({ url: 'mongodb://localhost/gallery-dev', gfs: gfs, filename: function(req, file, cb) { var datetimestamp = Date.now(); cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]); }, metadata: function(req, file, cb) { cb(null, {originalname: file.originalname}); }, root: 'mediaFiles' }); var upload = multer({ storage: storage }).single('file'); // path that will upload files router.post('/upload', function(req, res) { upload(req, res, function(err) { if(err) { return res.status(500).json({ message: 'Internal Server Error' }); } res.status(200).json({ message: 'Success!' }); }); }); // path that will retrieve media files router.get('/file/:file_id', function(req, res) { gfs.collection('mediaFiles'); // checks if file exists gfs.files.find({file_id: req.params.file_id}).toArray(function(err, files) { if(!files || files.length === 0) { return res.status(404).json({ message: 'Error' }); } // create read stream var readstream = gfs.createReadStream({ file_id: files[0].file_id, root: 'mediaFiles' }); // set content type res.set('Content-Type', files[0].contentType) // return response return readstream.pipe(res); }); }); // returns all items in the app as a list (array of items) // allows scrolling view of all items or exhibits in the app router.get('/', function(req, res) { var search = req.query.term; if (search == "") { Exhibit.find() .populate('comments') .sort({'date': -1}) .limit(10) .exec(function(err, exhibits) { if (err) { // console.log(err); return res.status(500).json({ message: 'Internal Server Error' }); } res.json(exhibits); }); } else { Exhibit.find({ 'categories': search }) .populate('comments') .exec(function(err, exhibits) { if (err) { // console.log(err); // console.log('cannot search by category'); return res.status(500).json({ message: 'Internal Server Error' }); } res.json(exhibits); }) } }); // returns single specific exhibit item (item) // allows viewing of a single exhibit or item from the app router.get('/exhibit', function(req, res) { console.log('exhibit request made'); let exhibit_id = req.query.exhibit_id; Exhibit.findById(exhibit_id) .populate('comments') .exec(function(err, exhibit) { if (err) { return res.status(500).json({ message: 'Internal Server Error' }); } // console.log(exhibit); res.status(200).json(exhibit); }) }); // router.get('/exhibit/comment/:exhibit_id', function(req, res) { // console.log("fetching comments"); // let exhibit_id = req.params.exhibit_id // Comment.find().where('exhibit').equals(exhibit_id).limit(10) // .exec(function(err, comments) { // if (err) { // console.log(err); // console.log("cannot fetch comments"); // return res.status(500).json({ // message: 'Internal Server Error' // }); // } // return res.json(comments); // }) // }); router.post('/exhibit/comment', function(req, res) { let comment = req.body; let exhibit_id = comment.exhibit_id; console.log(comment); Comment.create({ text: comment.text, creator: comment.user, exhibit: comment.exhibit_id }, function (err, comment) { if (err) return handleError(err); Exhibit.findById(exhibit_id, function(err, exhibit) { exhibit.comments.push(comment._id); exhibit.save(exhibit.comments); }) console.log("Created and Saved comment"); res.status(201).json(comment); }); }); // creates new single exhibit item in exhibits collection router.post('/exhibit', function(req, res) { console.log('exhibit post made'); let exhibit = req.body; Exhibit.create(exhibit, function(err, exhibit) { let title = exhibit.title; let creator = exhibit.username; let image = exhibit.image; let description = exhibit.description; let status = exhibit.status; let exhibitType = exhibit.exhibitType; let location = exhibit.siteLink; let categories = exhibit.categories; if (err || !exhibit) { console.error("Could not create exhibit"); console.log(err); return res.status(500).json({ message: 'Internal Server Error' }); } console.log("Created Exhibit "); res.status(201).json(exhibit); }); }); // updates user comments on individual exhibits - should not overwrite existing comments just add another comment. router.put('/exhibit/:exhibit_id', function(req, res) { console.log('exhibit put made - update to comments'); console.log(res.req); let text = req.params.text; let exhibit_id = req.params.exhibit_id; let update = text; //should be USER (timestamp) : text Exhibit.findByIdAndUpdate(exhibit_id, update, function(err, exhibits) { if (err) { return res.status(500).json({ message: 'Internal Server Error' }); } return res.status(201).json(exhibits); // add some kind of user notification that comment was added }); }); // // load exhibit, push comment to comments array, save exhibit // Exhibit.findById(exhibit_id) // .exec(function(err, exhibit) { // if (err) { // console.log("find error below"); // console.log(err); // return handleError(err); // }; // console.log(comment); // exhibit.comments.push(comment); // // exhibit.save(function(err, updatedExhibit) { // // if (err) { // // console.log("save error below"); // // console.log(err); // // return res.status(500).json({ // // message: 'Internal Server Error' // // }); // res.status(201).json(comment); // // } // }); // }); // }); // }); module.exports = router;
Java
UTF-8
438
1.71875
2
[]
no_license
package org.irri.iric.chado; // Generated 05 26, 14 1:29:45 PM by Hibernate Tools 3.4.0.CR1 /** * FeatureUnion generated by hbm2java */ public class FeatureUnion implements java.io.Serializable { private FeatureUnionId id; public FeatureUnion() { } public FeatureUnion(FeatureUnionId id) { this.id = id; } public FeatureUnionId getId() { return this.id; } public void setId(FeatureUnionId id) { this.id = id; } }
Java
UTF-8
3,459
2.484375
2
[]
no_license
package dmg.cells.nucleus; import java.io.PrintWriter; import java.util.Map; import org.dcache.util.Args; public class AbstractCellComponent implements CellInfoProvider, CellSetupProvider, CellMessageSender, CellLifeCycleAware { private CellEndpoint _endpoint; private CellAddressCore _cellAddress; /** * Implements CellInfoProvider interface. */ @Override public void getInfo(PrintWriter pw) {} /** * Implements CellInfoProvider interface. */ @Override public CellInfo getCellInfo(CellInfo info) { return info; } /** * Implements CellSetupProvider interface. */ @Override public void printSetup(PrintWriter pw) {} /** * Implements CellSetupProvider interface. */ @Override public void beforeSetup() {} /** * Implements CellSetupProvider interface. */ @Override public void afterSetup() {} /** * Implements CellLifeCycleAware interface. */ @Override public void afterStart() {} /** * Implements CellLifeCycleAware interface. */ @Override public void beforeStop() {} /** * Implements CellMessageSender interface. */ @Override public void setCellEndpoint(CellEndpoint endpoint) { _endpoint = endpoint; CellInfo cellInfo = _endpoint.getCellInfo(); _cellAddress = new CellAddressCore(cellInfo.getCellName(), cellInfo.getDomainName()); } /** * Implements CellMessageSender interface. */ protected CellEndpoint getCellEndpoint() { return _endpoint; } /** * Sends <code>envelope</code>. * * @param envelope the cell message to be sent. * @throws SerializationException if the payload object of this * message is not serializable. * @throws NoRouteToCellException if the destination could not be * reached. */ protected void sendMessage(CellMessage envelope) throws SerializationException, NoRouteToCellException { _endpoint.sendMessage(envelope); } /** * Provides information about the host cell. * * Depending on the cell, a subclass of CellInfo with additional * information may be returned instead. * * @return The cell information encapsulated in a CellInfo object. */ protected CellInfo getCellInfo() { return _endpoint.getCellInfo(); } /** * Returns the address of the cell hosting this component. */ protected CellAddressCore getCellAddress() { return _cellAddress; } /** * Returns the name of the cell hosting this component. */ protected String getCellName() { return getCellAddress().getCellName(); } /** * Returns the name of the domain hosting the cell hosting this * component. */ protected String getCellDomainName() { return getCellAddress().getCellDomainName(); } /** * Returns the domain context. The domain context is shared by all * cells in a domain. */ protected Map<String,Object> getDomainContext() { return _endpoint.getDomainContext(); } /** * Returns the cell command line arguments provided when the cell * was created. */ protected Args getArgs() { return _endpoint.getArgs(); } }
Java
UTF-8
1,551
3.546875
4
[ "MIT" ]
permissive
package seedu.address.model.calorie; import static java.util.Objects.requireNonNull; import static seedu.address.commons.util.AppUtil.checkArgument; /** * Represents a Input food */ public class Food { public static final String MESSAGE_CONSTRAINTS = "Food can take any values, and it should not be blank"; public static final String MESSAGE_CONSTRAINTS_WRONG_TYPE = "Food can only be used with Calorie Type: Input"; public static final String VALIDATION_REGEX = "[^\\s].*"; public final String food; /** * Constructs a {@code Food}. * * @param food A valid food. */ public Food(String food) { requireNonNull(food); checkArgument(isValidFood(food), MESSAGE_CONSTRAINTS); this.food = food; } /** * Checks if input is valid * * @param test */ public static boolean isValidFood(String test) { assert test != null : "test must be not be empty"; return test.matches(VALIDATION_REGEX); } @Override public String toString() { return food; } /** * Returns true if both Foods have the same food string. * This defines a stronger notion of equality between two foods. */ @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Food)) { return false; } Food otherFood = (Food) other; return otherFood.food.equals(this.food); } }
C#
UTF-8
1,480
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Text; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace command_reviewer { public partial class FRMMain : Form { private CMDExecutor executor; public FRMMain() { InitializeComponent(); executor = new CMDExecutor(); } private void txtCommand_enter(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { executor.command = txtCommand.Text; executor.ExecuteProces(); txtResults.AppendText(Environment.NewLine); this.txtResults.AppendText(executor.command); txtResults.AppendText(Environment.NewLine); txtResults.AppendText(executor.result); AdaptatibeText(); } } private void AdaptatibeText() { int newWidth = 0; int newHeigth = 0; Graphics g = txtResults.CreateGraphics(); Font font = txtResults.Font; newWidth = (int)g.MeasureString(txtResults.Text, font).Width; newHeigth= (int)g.MeasureString(txtResults.Text, font).Height; txtResults.Width = newWidth; txtResults.Height = newHeigth; txtResults.Refresh(); } } }
PHP
UTF-8
368
2.53125
3
[]
no_license
<?php namespace Novel\Core\Tokens\FlowControl\IfStatement; use Novel\Core\IToken; use Novel\Core\Tokens\Scope\ICodeScopeToken; interface IIfConditionToken extends IToken { public function setBody(ICodeScopeToken $body): void; public function getBody(): ICodeScopeToken; public function getCondition(): IToken; public function setCondition(IToken $exp): void; }
Java
UTF-8
304
2.078125
2
[]
no_license
package com.bruce; import java.util.function.Consumer; /** * @Author: Bruce * @Date: 2019/5/27 19:36 * @Version 1.0 */ public interface Limit { int getLimit(); void notifyOnChange(Consumer<Integer> consumer); void onSample(long startTime, long rtt, int inflight, boolean didDrop); }
Markdown
UTF-8
3,999
3.109375
3
[]
no_license
# JoJo Programming Language It is a Turing complete programming language. ### In this language, it is implemented: * Variables (global or locale) * Functions (recursion is supported) * Input and output of variable values * Nested conditional statements but without else (it is proposed to write then a conditional operator but with the negation of the condition) * Loops of the while type * The differentiation function * Standard Boolean operations * Standard mathematical functions (the full list can be found in libr/key_words_rm.h) ### The language also supports the following optimizations: * Convolution of constants * Removing neutral elements * Computation of the derivative at the translation stage ### The cherry on the cake - support for two languages (select the appropriate mode in makefile): hiragana and romaji (Latin). The resulting trees (the transition stage) are fully compatible, so a program written in one language can be easily translated into another language in the following way: Example, we want to translate a program written in hiragana into romaji. To do this, compile the program front-end in ***hg*** mode. Then we compile the resulting file with the reverse front-end in rm mode. The resulting file is the program already rewritten in Romanji. There is also a feature that allows you to understand how our program was translated (the new debag mode), or you can also just get a funny video. Each keyword has its own identifier (the name of the video), which is picked up at the end of the list, and then this list connects all the views in the desired order. Examples: [![Watch the video](images/mq3.jpg)](https://www.youtube.com/watch?v=pDLMoiX-FzM) There is a special middle-end mode in which each expression will be differentiated. It's so much fun to integrate with your hands. [![Watch the video](images/mq2.jpg)](https://www.youtube.com/watch?v=3fvgipe_swY) ## Example of a program. This is a factorial calculation program in romaji. The syntax is ***С-like***, so to understand the program, it is enough to open the file ["libr/key_words_rm.h"](libr/key_words_rm.h). ``` Kono, Giorno Giovanna, niwa yume ga aru () Za Warudo! Toki wo Tomare! Dio Awaken 0 Yare Yare Daze Kono Dio Yare Yare Daze Mousukoshite ora ora desuka (Dio URYAAAAA 1) Za Warudo! Toki wo Tomare! Arrivederci -1 Yare Yare Daze 0 Kira Kuin baitsa dasuto Yare Yare Daze ROAD ROLLER DA! Diavolo Awaken Fuctorial(Dio) Yare Yare Daze Arrivederci Diavolo Yare Yare Daze ROAD ROLLER DA! Fuctorial(Jotaro) Za Warudo! Toki wo Tomare! Mousukoshite ora ora desuka (Jotaro UOSHAAAA 1) Za Warudo! Toki wo Tomare! 1 Kira Kuin baitsa dasuto Yare Yare Daze ROAD ROLLER DA! Jotaro MUDAMUDAMUDA Fuctorial(Jotaro ARIARIARIARI 1) Kira Kuin baitsa dasuto Yare Yare Daze ROAD ROLLER DA! ``` And this is an example of the same program, but already written in hiragana (automatically obtained from a program written in romaji). There is also a file with key words for it - ["libr/key_words_hg.h"](libr/key_words_hg.h) ``` この, Giorno Giovanno, にわ ゆめ が ある () Za Warudo! Toki wo Tomare! Dio アウェイクン 0 やれやれだぜ この Dio やれやれだぜ もしかしてオラオラですかあ (Dio URYAAAAA 1) Za Warudo! Toki wo Tomare! アリーヴェデルチ -1 やれやれだぜ 0 キラー・クイーン バイツァ・ダスト やれやれだぜ ROAD ROLLER DA! Diavolo アウェイクン Fuctorial(Dio) やれやれだぜ アリーヴェデルチ Diavolo やれやれだぜ ROAD ROLLER DA! Fuctorial (Jotaro) Za Warudo! Toki wo Tomare! もしかしてオラオラですかあ (Jotaro UOSHAAAA 1) 1 キラー・クイーン バイツァ・ダスト やれやれだぜ Jotaro MUDAMUDAMUDA Fuctorial(Jotaro ARIARIARIARI 1) キラー・クイーン バイツァ・ダスト やれやれだぜ ROAD ROLLER DA! ``` The rest of the examples can be found in the folder ["files/"](files/).
Java
UTF-8
2,170
2.40625
2
[]
no_license
package com.nazarmerza.quiz.domain; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.JoinColumn; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.MappedSuperclass; import javax.persistence.OneToOne; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.validator.constraints.NotEmpty; import com.nazarmerza.quiz.domain.types.QuestionType; import com.nazarmerza.quiz.domain.validation.Answer; //@MappedSuperclass @Entity @Table(name = "question") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="QSTN_TYPE") public abstract class Question implements Serializable{ protected Long id; protected QuestionType type; protected String answer; protected Quiz Quiz; protected Question(){ } protected Question(QuestionType type, String answer, com.nazarmerza.quiz.domain.Quiz quiz) { this.type = type; this.answer = answer; Quiz = quiz; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "QUESTION_ID") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "TYPE", nullable = false) public QuestionType getType() { return type; } public void setType(QuestionType type) { this.type = type; } @NotEmpty(message = "Answer must not be empty", groups=Answer.class) @Column(name = "ANSWER", length = 100, nullable = false) public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "QUIZ_ID") public Quiz getQuiz() { return Quiz; } public void setQuiz(Quiz quiz) { Quiz = quiz; } public boolean validateResponse(String reponse){ return false; } }
Java
UTF-8
362
1.695313
2
[]
no_license
package com.microstone.app.param; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; @Data public class ReadInfoParam implements Serializable { private Long shareId; private Long weChatId; /** * 查看时长 */ @ApiModelProperty(value = "查看时长") private Integer readTime; }
Java
UTF-8
411
1.84375
2
[]
no_license
package com.bb.auth.config; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; public class WebMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index.html"); } }
JavaScript
UTF-8
397
2.6875
3
[]
no_license
const express = require("express"); // llamar la dependencia que instalamos const app = express(); // ejecutamos express app.get("*", (request, response) => { // get * -> va a recibir todas la peticiones response.send({ messange: "Chanchito Feliz" }); // response send -> para mandar }); app.listen(3000, () => console.log("Nuestro servidor esta escuchando")); // iniciar en el puerto 3000
Python
UTF-8
1,252
3.09375
3
[]
no_license
from objects.RandomObject import RandomObject from objects.Direction import Direction #from objects import Room, RandomObject, Direction class Door(RandomObject): parameter_types = [] # Set our location for the description using from_room and the dict def describe(self,from_perspective): self.location = self.locations[from_perspective] return super().describe() def connect(self,room_a,room_b): # Add this doorway to rooms which are not null if room_a is not None: room_a.add_door(self) if room_b is not None: room_b.add_door(self) self.rooms = [room_a, room_b] # Dictionary shows which room is in which direction of the door self.locations = {room_a: self.locator.origin, room_b: self.locator.opposite()} def open(self,open_from): # check to see if this room is in the pair if open_from in self.rooms: # return it if it exists return list(filter(lambda x: x != open_from, self.rooms))[0] # otherwise return the current room return open_from def __init__(self, room_a,room_b=None): self.locator = Direction() self.connect(room_a,room_b) super().__init__()
C++
UTF-8
9,403
2.953125
3
[ "MIT" ]
permissive
#include <iostream> #include <thread> #include <sstream> #include <random> #include <map> #include <deque> #include "messagingserver.hpp" #include "messagingclient.hpp" #ifndef _WIN32 #include <signal.h> #endif using std::cerr; using std::ostringstream; using std::string; using std::map; using std::make_unique; using RandomEngine = std::mt19937; static const int port = 4782; static void sendFlood( MessagingServer &server, MessagingServer::ClientHandle client_handle, int count ) { for (int i=0; i!=count; ++i) { if (i%1000==0) { cerr << "Sending flood message " << i+1 << "\n"; } server.sendMessageToClient("flood data",client_handle); } server.sendMessageToClient("end",client_handle); } static bool startsWith(const string &full_string,const string &prefix) { return full_string.substr(0,prefix.length())==prefix; } static int floodCount(const string &message) { std::istringstream stream(message); string first_word, second_word; stream >> first_word >> second_word; assert(first_word=="flood"); return std::stoi(second_word); } static int echoCountOf(const string &message) { std::istringstream stream(message); string first_word, second_word; stream >> first_word >> second_word; assert(first_word=="echo"); return std::stoi(second_word); } static int sendSizeOf(const string &message) { std::istringstream stream(message); string first_word, second_word; stream >> first_word >> second_word; assert(first_word=="sendme"); return std::stoi(second_word); } static int randomInt(int low,int high,RandomEngine &engine) { return std::uniform_int_distribution<int>(low,high)(engine); } static string randomMessage(RandomEngine &engine,int length) { string message; for (int i=0; i!=length; ++i) { message.push_back('a'+randomInt(0,25,engine)); } return message; } static string randomMessage(RandomEngine &engine) { int length = randomInt(0,10000,engine); return randomMessage(engine,length); } static void runServer() { MessagingServer server(port); bool quit_message_was_received = false; using ClientHandle = MessagingServer::ClientHandle; map<ClientHandle,int> echo_counts; RandomEngine engine(/*seed*/1); MessagingServer::MessageHandler message_handler = [&](ClientHandle client_handle,const string &message){ assert(message.find('\0')==message.npos); for (int i=0, n=message.size(); i!=n; ++i) { assert(message[i]>0); } if (echo_counts.count(client_handle)) { server.sendMessageToClient(message,client_handle); --echo_counts[client_handle]; if (echo_counts[client_handle]==0) { echo_counts.erase(client_handle); } } else if (message=="quit") { quit_message_was_received = true; } else if (startsWith(message,"flood")) { int count = floodCount(message); sendFlood(server,client_handle,count); } else if (startsWith(message,"echo")) { int count = echoCountOf(message); echo_counts[client_handle] += count; } else if (startsWith(message,"tellall")) { server.forEachClient( [&](ClientHandle client_handle){ server.sendMessageToClient("hi everyone",client_handle); } ); } else if (startsWith(message,"sendme ")) { int size_to_send = sendSizeOf(message); string message = randomMessage(engine,size_to_send); server.sendMessageToClient(message,client_handle); } else { server.sendMessageToClient("ack",client_handle); } }; auto connect_handler = [](ClientHandle client_handle){ cerr << "client " << client_handle << " connected.\n"; }; auto disconnect_handler = [](ClientHandle client_handle){ cerr << "client " << client_handle << " disconnected.\n"; }; while (server.clientCount()!=0 || !quit_message_was_received) { server.checkForEvents(message_handler,connect_handler,disconnect_handler); } } static void sleepForNSeconds(float n) { int n_milliseconds = n*1000; #ifdef _WIN32 Sleep(n_milliseconds); #else std::this_thread::sleep_for(std::chrono::milliseconds(n_milliseconds)); #endif } static string str(int i) { ostringstream stream; stream << i; return stream.str(); } static void runCountClient() { MessagingClient client; client.connectToServer("localhost",port); int n_acks_received = 0; auto message_handler = [&](const string &message){ if (message=="ack") { ++n_acks_received; } else { cerr << "Got message: " << message << "\n"; } }; for (int i=1; i<=5; ++i) { if (!client.isConnected()) { cerr << "Server closed connection\n"; return; } client.sendMessage(str(i)); sleepForNSeconds(1); client.checkForMessages(message_handler); cerr << "n_acks_received=" << n_acks_received << "\n"; } client.disconnectFromServer(); } static void runQuitClient() { MessagingClient client; client.connectToServer("localhost",port); client.sendMessage("quit"); client.disconnectFromServer(); } static string floodMessage(int n) { ostringstream stream; stream << "flood " << n; return stream.str(); } static void runFloodClient() { int n_messages_per_flood = 1000000; MessagingClient client; client.connectToServer("localhost",port); client.sendMessage(floodMessage(n_messages_per_flood)); sleepForNSeconds(5); int n_data_messages_received = 0; bool finished = false; auto message_handler = [&](const string &message){ if (message=="flood data") { ++n_data_messages_received; if (n_data_messages_received%1000 == 1) { cerr << "Got flood message " << n_data_messages_received << "\n"; } } else if (message=="end") { finished = true; } else { cerr << "Unknown message: " << message << "\n"; assert(false); } }; while (!finished) { if (!client.isConnected()) { cerr << "Server disconnected\n"; assert(false); return; } client.checkForMessages(message_handler); } assert(n_data_messages_received==n_messages_per_flood); client.disconnectFromServer(); } static void runRandomClient() { MessagingClient client; client.connectToServer("localhost",port); int echo_count = 10000; client.sendMessage("echo " + str(echo_count)); int n_messages_received = 0; RandomEngine engine(/*seed*/1); std::deque<string> expected_messages; auto message_handler = [&](const string &message){ assert(message==expected_messages.front()); expected_messages.pop_front(); ++n_messages_received; }; for (int i=0; i!=echo_count; ++i) { string message = randomMessage(engine); client.sendMessage(message); expected_messages.push_back(message); client.checkForMessages(message_handler); } while (n_messages_received!=echo_count) { client.checkForMessages(message_handler); } client.disconnectFromServer(); } static void runTellAllClient() { MessagingClient client; client.connectToServer("localhost",port); client.sendMessage("tellall"); client.disconnectFromServer(); } static void runBigReceiveClient() { MessagingClient client; client.connectToServer("localhost",port); client.sendMessage("sendme 1000000"); std::unique_ptr<string> received_message_ptr; auto message_handler = [&](const string &message){ received_message_ptr = make_unique<string>(message); }; for (;;) { client.checkForMessages(message_handler); if (received_message_ptr) { break; } } assert(received_message_ptr->size() == 1000000); client.disconnectFromServer(); } static void runListenClient() { MessagingClient client; client.connectToServer("localhost",port); bool got_a_message = false; while (!got_a_message) { client.checkForMessages([&](const string &message){ cerr << "Got message: " << message << "\n"; got_a_message = true; }); } client.disconnectFromServer(); } #ifndef _WIN32 static void disablePipeSignal() { signal(SIGPIPE,SIG_IGN); } #endif int main(int argc,char** argv) { Socket::initialize(); #ifndef _WIN32 // The pipe signal needs to be disabled so we can treat unexpected // connection loss as a read/write error. disablePipeSignal(); #endif if (argc!=2) { cerr << "Usage: " << argv[0] << " <operation>\n"; cerr << "\n"; cerr << "Operations:\n"; cerr << " server\n"; cerr << " count_client\n"; cerr << " quit_client\n"; cerr << " flood_client\n"; cerr << " random_client\n"; cerr << " tellall_client\n"; cerr << " listen_client\n"; return EXIT_FAILURE; } string operation = argv[1]; if (operation=="server") runServer(); else if (operation=="count_client") runCountClient(); else if (operation=="quit_client") runQuitClient(); else if (operation=="flood_client") runFloodClient(); else if (operation=="random_client") runRandomClient(); else if (operation=="tellall_client") runTellAllClient(); else if (operation=="bigreceive_client") runBigReceiveClient(); else if (operation=="listen_client") runListenClient(); else { cerr << "Unknown operation: " << operation << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
Java
UTF-8
2,892
2.375
2
[]
no_license
package com.kentuckyspacetracker; import android.app.Activity; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * This is the activity associated with the virtual tour section of the app. * * This activity relies heavily upon altered sample code using fragments. */ public class NewAbout extends FragmentActivity { MyPageAdapter pageAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.newaboutlayout); //Set Full Screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); List<Fragment> fragments = getFragments(); pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments); ViewPager pager = (ViewPager)findViewById(R.id.viewpager); TextView text1 = (TextView)findViewById(R.layout.myfragment_layout); pager.setAdapter(pageAdapter); } private List<Fragment> getFragments(){ List<Fragment> fList = new ArrayList<Fragment>(); //Populate Fragments before display //About KySpace fList.add(MyFragment.newInstance(getString(R.string.AboutB1),getString(R.string.AboutH1), 1)); //About Satellites fList.add(MyFragment.newInstance(getString(R.string.k2about), getString(R.string.AboutH2), 2)); fList.add(MyFragment.newInstance(getString(R.string.tlogoabout), getString(R.string.AboutH2), 3)); fList.add(MyFragment.newInstance(getString(R.string.eagle250satabout), getString(R.string.AboutH2), 4)); fList.add(MyFragment.newInstance(getString(R.string.cxbnabout), getString(R.string.AboutH2), 5)); fList.add(MyFragment.newInstance(getString(R.string.AboutB3),getString(R.string.AboutH3),6)); fList.add(MyFragment.newInstance(getString(R.string.AboutB8),getString(R.string.AboutH8),6)); return fList; } class MyPageAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; } @Override public Fragment getItem(int position) { return this.fragments.get(position); } @Override public int getCount() { return this.fragments.size(); } } }
Markdown
UTF-8
6,228
3.234375
3
[ "MIT" ]
permissive
## Application architecture with components Components are versatile tools to organize code and can be used in a variety of ways. ### Want to skip all this and just see the source? [JSBIn example](http://jsbin.com/luhipixipe/edit) **UPDATED:** This tutorial is of an older version here is a [working example in the latest version](http://jsbin.com/rojehuzihi/edit?js,output) First we have our html that we will be using: ```html <div id="contacts"> <h2>Contacts</h2> <addForm> <div id="form" class="hide"> <form> <input name="name" /> <input name="email" /> <input type="submit" /> </form> </div> </addForm> <list> <ul id="items" class="hide"> <li class="contact"> <span class="name"></span> - (<id></id>: <span class="email"></span>) </li> </ul> </list> </div> ``` ## Model/services Now let's create a simple model entity which we'll use in our simple application, to illustrate different usage patterns for components: ```javascript var Contact = function(data) { data = data || {} this.id = mag.prop(data.id) this.name = mag.prop(data.name) this.email = mag.prop(data.email) } Contact.list = function(data) { return mag.addons.request({method: "GET", url: "/api/contact", type: Contact}) } Contact.save = function(data) { return mag.addons.request({method: "POST", url: "/api/contact", data: data}) } ``` Here, we've defined a class called Contact. A contact has an id, a name and an email. There are two static methods: list for retrieving a list of contacts, and save to save a single contact. These methods assume that the AJAX responses return contacts in JSON format, containing the same fields as the class. ## Aggregation of responsibility One way of organizing components is to use component parameter lists to send data downstream, and to define events to bubble data back upstream to a centralized module who is responsible for interfacing with the model layer. ## Container component This is the parent component, it houses all inner components. ```javascript var ContactsWidget = { controller: function update() { this.contacts = Contact.list(update.bind(this)) this.handleContactSubmit = function(contact) { Contact.save(contact).then(update.bind(this)) }.bind(this) }, view: function(state) { state.addForm = mag.module('form', contactForm, { onContactSubmit: state.handleContactSubmit, }) state.list = mag.module('items', ContactList, { contacts: state.contacts }) } } ``` ## Form module This is our first inner component, the contact form. The ContactForm component is, as its name suggests, a form that allows us to edit the fields of a Contact entity. It exposes an event called onsave which is fired when the Save button is pressed on the form. In addition, it stores the unsaved contact entity internally within the component (this.contact = mag.prop(props.contact || new Contact())). ```javascript var ContactForm = { controller: function(props) { this.contact = mag.prop(args.contact || new Contact()) }, view: function(state, props) { var contact = ctrl.contact() // create an object to bind our instructions for our html fields state.form = Object.keys(contact).reduce(function(previous, current) { previous[current] = { _onchange: mag.withProp("value", contact[current]), _value: contact[current](), _config: function(node, isNew) { // change html value node.value = contact[current]() } } return previous; }, {}); // handle form submit state.form._onsubmit = function(e) { // prevent default browser form submti behavior e.preventDefault() if (contact.name() && contact.email()) { props.onContactSubmit(contact) } } } } ``` ## List module This is our second inner componenet and sibling to the contact form. The ContactList component displays a table showing all the contact entities that are passed to it via the contacts properties. ```javascript var ContactList = { view: function(state, props) { state.contact = props.contacts } } ``` Now let's start the applicaton by attaching it the our html element ```javascript //Initialize the application mag.module('contacts', ContactsWidget) ``` In the example above, there are 3 components. ContactsWidget is the top level module being rendered to its associated element, and it is the module that has the responsibility of talking to our Model entity Contact, which we defined earlier. The most interesting component is ContactsWidget: * on initialization, it fetches the list of contacts (this.contacts = Contact.list) * when save is called, it saves a contact (Contact.save(contact)) * after saving the contact, it reloads the list (.then(update.bind(this))) update is the controller function itself, so defining it as a promise callback simply means that the controller is re-initialized after the previous asynchronous operation (Contact.save()) Aggregating responsibility in a top-level component allows the developer to manage multiple model entities easily: any given AJAX request only needs to be performed once regardless of how many components need its data, and refreshing the data set is simple. In addition, components can be reused in different contexts. Notice that the ContactList does not care about whether args.contacts refers to all the contacts in the database, or just contacts that match some criteria. Similarly, ContactForm can be used to both create new contacts as well as edit existing ones. The implications of saving are left to the parent component to handle. This architecture can yield highly flexible and reusable code, but flexibility can also increase the cognitive load of the system (for example, you need to look at both the top-level module and ContactList in order to know what is the data being displayed (and how it's being filtered, etc). In addition, having a deeply nested tree of components can result in a lot of intermediate "pass-through" arguments and event handlers. [JSBin example](http://jsbin.com/luhipixipe/edit)
Markdown
UTF-8
1,270
2.96875
3
[]
no_license
### markdown 和 html - 标题 : `#`、 `h1~h6` - 列表 : 无序列表和有序列表 + 无序列表 : markdown : `- 或者 *`、html : `ul 和 li` + 有序列表 : markdown : `1. 2.`、html : `ol 和 li` - 图片和链接 : + markdown :`![图片的名称](图片链接绝对绝对路径)`、html : `<img src="绝对或者相对路径" alt=""/>` + markdown : `[文字](绝对路径)`、html : `<a href="" target="_blank" title=""/>` - 粗体和斜体 + 粗体 : mardown : `**内容**`、css : `font-weight:bold` bold约等于700; + 斜体 : markdown : `*内容*`、html : `<em></em><i></i>` - 引用 : markdown : `>` - 一行代码和代码块 + 一行代码 : `代码` + 多行代码 : ``` 代码块 ``` - 表格 : + markdown : ``` | name | age | sex | |:----:| :-- | --: | |前端 | 6 |你猜 | ``` + html : ###webstorm快捷键 - `div.item*10` : 创建10个class名为item的div - `div.item$*4` : 创建4个class名不同的div - `div+p+span` : 创建兄弟关系的标签 - `ul>li*10` : 创建一个ul和10个li - `ul>li*10>a[href=javascript:;,title=a链接]` - 如果想批量操作内容可以按住alt键,同时滑动鼠标滚轮,选中之后在操作; - 属性操作用中括号,多个属性之间用‘,’逗号隔开
C++
UTF-8
3,235
3.046875
3
[]
no_license
#include <iostream> #include <unordered_map> #include <queue> #include <string> #include <vector> //structure to build the Huffman Tree struct tree { char data; long long int weight; tree* left, * right; tree(char data, long long int weight) :data(data), weight(weight), left(NULL), right(NULL) {} }; //comparator function for priority queue struct compare { bool operator()(tree* l, tree* r) { return (l->weight > r->weight); } }; #define MAX_HEIGHT 256 std::unordered_map<int, std::string> code; std::priority_queue<tree*, std::vector<tree*>, compare> buff; long long int freq[MAX_HEIGHT]; int bit_counter; unsigned char current_byte; //for calculating the frequency distribution of each character present in file void definefreq(FILE*& orig) { char c; while ((c = fgetc(orig)) != EOF) { ++freq[(int)c]; } } //building huffman tree void hufftree() { tree* left, * right, * top; for (int i = 0; i < MAX_HEIGHT; i++) { if (freq[i] > 0) { buff.push(new tree((char)i, freq[i])); } } while (buff.size() != 1) { left = buff.top(); buff.pop(); right = buff.top(); buff.pop(); top = new tree('$', left->weight + right->weight); top->left = left; top->right = right; buff.push(top); } } //getting codes for each character void savecode(tree* root, std::string a) { if (!root) return; if (root->data != '$') { code[(int)root->data] = a; } savecode(root->left, a + "0"); savecode(root->right, a + "1"); } //to free the dynamic memory allocated during building the huffman tree void freequeue(tree* root) { tree* left, * right; left = root->left; right = root->right; if (left) { freequeue(left); delete left; } if (right) { freequeue(right); delete right; } } //writing alphabet codes distribution file void write_freq_file() { FILE* ff = fopen("frequency_file.txt", "wt"); for (int i = 0; i < MAX_HEIGHT; i++) { if (freq[i] > 0) { fprintf(ff, "%c %s\n", (char)i, code[i].c_str()); } } } //writing encoded file void write(char a, FILE*& enco) { if (bit_counter == 7) { fwrite(&current_byte, 1, 1, enco); bit_counter = 0; current_byte = 0; } bit_counter++; current_byte <<= 1; current_byte |= a; } void write_encoded_file(FILE*& orig, FILE*& enco) { char a; current_byte = 0; bit_counter = 0; while ((a = fgetc(orig)) != EOF) { std::string s = code[(int)a]; for (int i = 0; i < s.size(); i++) write((int)s[i] - 48, enco); } if (bit_counter > 0) { current_byte <<= 7 - bit_counter; fwrite(&current_byte, 1, 1, enco); } _fcloseall(); } int main(int argc, char** argv) { FILE* orig,* encode; if (argc != 3) { fprintf(stderr, "huffman_encode_dynamic.exe <text file name> <encoded file name>"); } std::string text, encoded; text = argv[1]; encoded = argv[2]; orig = fopen(text.c_str(), "r"); encode = fopen(encoded.c_str(), "wb"); definefreq(orig); fseek(orig, 0, SEEK_SET); hufftree(); savecode(buff.top(), ""); freequeue(buff.top()); write_freq_file(); write_encoded_file(orig, encode); return 0; }
Rust
UTF-8
18,554
2.703125
3
[ "Apache-2.0", "MIT" ]
permissive
//! This module defines [`MuResolutionHomomorphism`], which is a chain map from a //! [`FreeChainComplex`]. use std::ops::Range; use std::path::PathBuf; use std::sync::Arc; use crate::chain_complex::{ AugmentedChainComplex, BoundedChainComplex, ChainComplex, FreeChainComplex, }; use crate::save::SaveKind; use algebra::module::homomorphism::{ModuleHomomorphism, MuFreeModuleHomomorphism}; use algebra::module::Module; use algebra::MuAlgebra; use fp::matrix::Matrix; use fp::vector::{FpVector, SliceMut}; use once::OnceBiVec; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; #[cfg(feature = "concurrent")] use rayon::prelude::*; pub type ResolutionHomomorphism<CC1, CC2> = MuResolutionHomomorphism<false, CC1, CC2>; pub type UnstableResolutionHomomorphism<CC1, CC2> = MuResolutionHomomorphism<true, CC1, CC2>; /// A chain complex homomorphims from a [`FreeChainComplex`]. This contains logic to lift chain /// maps using the freeness. pub struct MuResolutionHomomorphism<const U: bool, CC1, CC2> where CC1: FreeChainComplex<U>, CC1::Algebra: MuAlgebra<U>, CC2: ChainComplex<Algebra = CC1::Algebra>, { name: String, pub source: Arc<CC1>, pub target: Arc<CC2>, maps: OnceBiVec<Arc<MuFreeModuleHomomorphism<U, CC2::Module>>>, pub shift_s: u32, pub shift_t: i32, save_dir: Option<PathBuf>, } impl<const U: bool, CC1, CC2> MuResolutionHomomorphism<U, CC1, CC2> where CC1: FreeChainComplex<U>, CC1::Algebra: MuAlgebra<U>, CC2: ChainComplex<Algebra = CC1::Algebra>, { pub fn new( name: String, source: Arc<CC1>, target: Arc<CC2>, shift_s: u32, shift_t: i32, ) -> Self { let save_dir = if source.save_dir().is_some() && !name.is_empty() { let mut path = source.save_dir().unwrap().to_owned(); path.push(format!("products/{name}")); SaveKind::ChainMap.create_dir(&path).unwrap(); Some(path) } else { None }; Self { name, source, target, maps: OnceBiVec::new(shift_s as i32), shift_s, shift_t, save_dir, } } pub fn name(&self) -> &str { &self.name } pub fn algebra(&self) -> Arc<CC1::Algebra> { self.source.algebra() } pub fn next_homological_degree(&self) -> i32 { self.maps.len() } fn get_map_ensure_length(&self, input_s: u32) -> &MuFreeModuleHomomorphism<U, CC2::Module> { self.maps.extend(input_s as i32, |input_s| { let output_s = input_s as u32 - self.shift_s; Arc::new(MuFreeModuleHomomorphism::new( self.source.module(input_s as u32), self.target.module(output_s), self.shift_t, )) }); &self.maps[input_s as i32] } /// Returns the chain map on the `s`th source module. pub fn get_map(&self, input_s: u32) -> Arc<MuFreeModuleHomomorphism<U, CC2::Module>> { Arc::clone(&self.maps[input_s as i32]) } pub fn save_dir(&self) -> Option<&std::path::Path> { self.save_dir.as_deref() } } impl<const U: bool, CC1, CC2> MuResolutionHomomorphism<U, CC1, CC2> where CC1: FreeChainComplex<U>, CC1::Algebra: MuAlgebra<U>, CC2: ChainComplex<Algebra = CC1::Algebra>, { /// Extend the resolution homomorphism such that it is defined on degrees /// (`max_s`, `max_t`). /// /// This assumes in yet-uncomputed bidegrees, the homology of the source consists only of /// decomposables (e.g. it is trivial). More precisely, we assume /// [`MuResolutionHomomorphism::extend_step_raw`] can be called with `extra_images = None`. pub fn extend(&self, max_s: u32, max_t: i32) { self.extend_profile(max_s + 1, |_s| max_t + 1) } /// Extend the resolution homomorphism such that it is defined on degrees /// (`max_n`, `max_s`). /// /// This assumes in yet-uncomputed bidegrees, the homology of the source consists only of /// decomposables (e.g. it is trivial). More precisely, we assume /// [`MuResolutionHomomorphism::extend_step_raw`] can be called with `extra_images = None`. pub fn extend_through_stem(&self, max_s: u32, max_n: i32) { self.extend_profile(max_s + 1, |s| max_n + s as i32 + 1) } /// Extend the resolution homomorphism as far as possible, as constrained by how much the /// source and target have been resolved. /// /// This assumes in yet-uncomputed bidegrees, the homology of the source consists only of /// decomposables (e.g. it is trivial). More precisely, we assume /// [`MuResolutionHomomorphism::extend_step_raw`] can be called with `extra_images = None`. pub fn extend_all(&self) { self.extend_profile( std::cmp::min( self.target.next_homological_degree() + self.shift_s, self.source.next_homological_degree(), ), |s| { std::cmp::min( self.target.module(s - self.shift_s).max_computed_degree() + self.shift_t, self.source.module(s).max_computed_degree(), ) + 1 }, ); } // See the concurrent version for documentation #[cfg(not(feature = "concurrent"))] pub fn extend_profile(&self, max_s: u32, max_t: impl Fn(u32) -> i32 + Sync) { self.get_map_ensure_length(max_s - 1); for s in self.shift_s..max_s { let f_cur = self.get_map_ensure_length(s); for t in f_cur.next_degree()..max_t(s) { self.extend_step_raw(s, t, None); } } } /// Extends the resolution homomorphism up to a given range. This range is first specified by /// the maximum `s`, then the maximum `t` for each `s`. This should rarely be used directly; /// instead one should use [`MuResolutionHomomorphism::extend`], /// [`MuResolutionHomomorphism::extend_through_stem`] and [`ResolutionHomomorphism::extend_all`] /// as appropriate. /// /// Note that unlike the more specific versions of this function, the bounds `max_s` and /// `max_t` are exclusive. /// /// This assumes in yet-uncomputed bidegrees, the homology of the source consists only of /// decomposables (e.g. it is trivial). More precisely, we assume /// [`MuResolutionHomomorphism::extend_step_raw`] can be called with `extra_images = None`. #[cfg(feature = "concurrent")] pub fn extend_profile(&self, max_s: u32, max_t: impl Fn(u32) -> i32 + Sync) { self.get_map_ensure_length(max_s - 1); crate::utils::iter_s_t( &|s, t| self.extend_step_raw(s, t, None), self.shift_s, self.get_map_ensure_length(self.shift_s).min_degree(), max_s, &max_t, ); for s in self.shift_s..max_s { assert_eq!( Vec::<i32>::new(), self.maps[s as i32].ooo_outputs(), "Map {s} has out of order elements" ); } } /// Extend the [`MuResolutionHomomorphism`] to be defined on `(input_s, input_t)`. The resulting /// homomorphism `f` is a chain map such that if `g` is the `k`th generator in the source such /// that `d(g) = 0`, then `f(g)` is the `k`th row of `extra_images`. /// /// The user should call this function explicitly to manually define the chain map where the /// chain complex is not exact, and then call [`MuResolutionHomomorphism::extend_all`] to extend /// the rest by exactness. pub fn extend_step_raw( &self, input_s: u32, input_t: i32, extra_images: Option<Vec<FpVector>>, ) -> Range<i32> { let output_s = input_s - self.shift_s; let output_t = input_t - self.shift_t; assert!(self.target.has_computed_bidegree(output_s, output_t)); assert!(self.source.has_computed_bidegree(input_s, input_t)); assert!(input_s >= self.shift_s); let f_cur = self.get_map_ensure_length(input_s); if input_t < f_cur.next_degree() { assert!(extra_images.is_none()); // We need to signal to compute the dependents of this return input_t..input_t + 1; } let p = self.source.prime(); let num_gens = f_cur.source().number_of_gens_in_degree(input_t); let fx_dimension = f_cur.target().dimension(output_t); if num_gens == 0 || fx_dimension == 0 { return f_cur.add_generators_from_rows_ooo( input_t, vec![FpVector::new(p, fx_dimension); num_gens], ); } if let Some(dir) = &self.save_dir { let mut outputs = Vec::with_capacity(num_gens); if let Some(mut f) = self .source .save_file(SaveKind::ChainMap, input_s, input_t) .open_file(dir.to_owned()) { let fx_dimension = f.read_u64::<LittleEndian>().unwrap() as usize; for _ in 0..num_gens { outputs.push(FpVector::from_bytes(p, fx_dimension, &mut f).unwrap()); } return f_cur.add_generators_from_rows_ooo(input_t, outputs); } } if output_s == 0 { let outputs = extra_images.unwrap_or_else(|| vec![FpVector::new(p, fx_dimension); num_gens]); if let Some(dir) = &self.save_dir { let mut f = self .source .save_file(SaveKind::ChainMap, input_s, input_t) .create_file(dir.clone(), false); f.write_u64::<LittleEndian>(fx_dimension as u64).unwrap(); for row in &outputs { row.to_bytes(&mut f).unwrap(); } } return f_cur.add_generators_from_rows_ooo(input_t, outputs); } let mut outputs = vec![FpVector::new(p, fx_dimension); num_gens]; let d_source = self.source.differential(input_s); let d_target = self.target.differential(output_s); let f_prev = self.get_map(input_s - 1); assert!(Arc::ptr_eq(&d_source.source(), &f_cur.source())); assert!(Arc::ptr_eq(&d_source.target(), &f_prev.source())); assert!(Arc::ptr_eq(&d_target.source(), &f_cur.target())); assert!(Arc::ptr_eq(&d_target.target(), &f_prev.target())); let fdx_dimension = f_prev.target().dimension(output_t); // First take care of generators that hit the target chain complex. let mut extra_image_row = 0; for (k, output_row) in outputs.iter_mut().enumerate() { if d_source.output(input_t, k).is_zero() { let extra_image_matrix = extra_images.as_ref().expect("Missing extra image rows"); output_row.assign(&extra_image_matrix[extra_image_row]); extra_image_row += 1; } } // Now do the rest d_target.compute_auxiliary_data_through_degree(output_t); let compute_fdx_vector = |k| { let dx_vector = d_source.output(input_t, k); if dx_vector.is_zero() { None } else { let mut fdx_vector = FpVector::new(p, fdx_dimension); f_prev.apply(fdx_vector.as_slice_mut(), 1, input_t, dx_vector.as_slice()); Some(fdx_vector) } }; #[cfg(not(feature = "concurrent"))] let fdx_vectors: Vec<FpVector> = (0..num_gens).filter_map(compute_fdx_vector).collect(); #[cfg(feature = "concurrent")] let fdx_vectors: Vec<FpVector> = (0..num_gens) .into_par_iter() .filter_map(compute_fdx_vector) .collect(); let mut qi_outputs: Vec<_> = outputs .iter_mut() .enumerate() .filter_map(|(k, v)| { if d_source.output(input_t, k).is_zero() { None } else { Some(v.as_slice_mut()) } }) .collect(); if !fdx_vectors.is_empty() { assert!(CC2::apply_quasi_inverse( &*self.target, &mut qi_outputs, output_s, output_t, &fdx_vectors )); } if let Some(dir) = &self.save_dir { let mut f = self .source .save_file(SaveKind::ChainMap, input_s, input_t) .create_file(dir.clone(), false); f.write_u64::<LittleEndian>(fx_dimension as u64).unwrap(); for row in &outputs { row.to_bytes(&mut f).unwrap(); } } f_cur.add_generators_from_rows_ooo(input_t, outputs) } } impl<const U: bool, CC1, CC2> MuResolutionHomomorphism<U, CC1, CC2> where CC1: FreeChainComplex<U>, CC1::Algebra: MuAlgebra<U>, CC2: AugmentedChainComplex<Algebra = CC1::Algebra>, { pub fn from_class( name: String, source: Arc<CC1>, target: Arc<CC2>, shift_s: u32, shift_t: i32, class: &[u32], ) -> Self { let result = Self::new(name, source, target, shift_s, shift_t); let num_gens = result .source .module(shift_s) .number_of_gens_in_degree(shift_t); assert_eq!(num_gens, class.len()); let mut matrix = Matrix::new(result.source.prime(), num_gens, 1); for (k, &v) in class.iter().enumerate() { matrix[k].set_entry(0, v); } result.extend_step(shift_s, shift_t, Some(&matrix)); result } /// Extend the [`MuResolutionHomomorphism`] to be defined on `(input_s, input_t)`. The resulting /// homomorphism `f` is a chain map such that if `g` is the `k`th generator in the source such /// that `d(g) = 0`, then the image of `f(g)` in the augmentation of the target is the `k`th /// row of `extra_images`. /// /// The user should call this function explicitly to manually define the chain map where the /// chain complex is not exact, and then call [`MuResolutionHomomorphism::extend_all`] to extend /// the rest by exactness. pub fn extend_step( &self, input_s: u32, input_t: i32, extra_images: Option<&Matrix>, ) -> Range<i32> { self.extend_step_raw( input_s, input_t, extra_images.map(|m| { let p = self.target.prime(); let output_s = input_s - self.shift_s; let output_t = input_t - self.shift_t; let mut outputs = vec![ FpVector::new(p, self.target.module(output_s).dimension(output_t)); m.rows() ]; let chain_map = self.target.chain_map(output_s); chain_map.compute_auxiliary_data_through_degree(output_t); for (output, input) in std::iter::zip(&mut outputs, m.iter()) { assert!(chain_map.apply_quasi_inverse( output.as_slice_mut(), output_t, input.as_slice(), )); } outputs }), ) } } impl<const U: bool, CC1, CC2> MuResolutionHomomorphism<U, CC1, CC2> where CC1: AugmentedChainComplex + FreeChainComplex<U>, CC1::Algebra: MuAlgebra<U>, CC2: AugmentedChainComplex<Algebra = CC1::Algebra>, CC1::TargetComplex: BoundedChainComplex, CC2::TargetComplex: BoundedChainComplex, { /// Construct a chain map that lifts a given module homomorphism. pub fn from_module_homomorphism( name: String, source: Arc<CC1>, target: Arc<CC2>, f: &impl ModuleHomomorphism< Source = <<CC1 as AugmentedChainComplex>::TargetComplex as ChainComplex>::Module, Target = <<CC2 as AugmentedChainComplex>::TargetComplex as ChainComplex>::Module, >, ) -> Self { assert_eq!(source.target().max_s(), 1); assert_eq!(target.target().max_s(), 1); let source_module = source.target().module(0); let target_module = target.target().module(0); assert!(Arc::ptr_eq(&source_module, &f.source())); assert!(Arc::ptr_eq(&target_module, &f.target())); let p = source.prime(); let degree_shift = f.degree_shift(); let max_degree = source_module.max_generator_degree().expect( "MuResolutionHomomorphism::from_module_homomorphism requires finite max_generator_degree", ); let hom = Self::new(name, source, target, 0, degree_shift); source_module.compute_basis(max_degree); target_module.compute_basis(degree_shift + max_degree); hom.source.compute_through_bidegree(0, max_degree); hom.target .compute_through_bidegree(0, degree_shift + max_degree); for t in source_module.min_degree()..=max_degree { let mut m = Matrix::new( p, source_module.dimension(t), target_module.dimension(t + degree_shift), ); f.get_matrix(m.as_slice_mut(), t); hom.extend_step(0, t, Some(&m)); } hom } } impl<const U: bool, CC1, CC2> MuResolutionHomomorphism<U, CC1, CC2> where CC1: FreeChainComplex<U>, CC1::Algebra: MuAlgebra<U>, CC2: FreeChainComplex<U, Algebra = CC1::Algebra>, { /// Given a chain map $f: C \to C'$ between free chain complexes, apply /// $$ \Hom(f, k): \Hom(C', k) \to \Hom(C, k) $$ /// to the specified generator of $\Hom(C', k)$. pub fn act(&self, mut result: SliceMut, coef: u32, s: u32, t: i32, idx: usize) { let source_s = s + self.shift_s; let source_t = t + self.shift_t; assert_eq!( result.as_slice().len(), self.source .module(source_s) .number_of_gens_in_degree(source_t) ); let target_module = self.target.module(s); let map = self.get_map(source_s); let j = target_module.operation_generator_to_index(0, 0, t, idx); for i in 0..result.as_slice().len() { result.add_basis_element(i, coef * map.output(source_t, i).entry(j)); } } }
TypeScript
UTF-8
332
2.59375
3
[]
no_license
'use strict'; export{}; let lineCount: number = 4; let counter: number = 0; let pixel: string = "*"; let space: string = "" for (let i: number = 1; i < lineCount; i++) { space = space + " " } while (counter < lineCount) { console.log(space +pixel); pixel = pixel + "**" counter++; space = space.substring(1) }
Shell
UTF-8
4,348
3.546875
4
[ "MIT" ]
permissive
#!/bin/bash # Get the Real Username RUID=$(who | awk 'FNR == 1 {print $1}') # Translate Real Username to Real User ID RUSER_UID=$(id -u ${RUID}) # Set env for the Real User touch /home/${RUID}/.zshrc if [[ -f "/home/${RUID}/.zshrc" ]] ; then echo "source /usr/share/powerlevel9k/powerlevel9k.zsh-theme" >> "/home/${RUID}/.zshrc" sudo chown ${RUID}:${RUID} /home/${RUID}/.zshrc fi # 단축키를 자동으로 추가하는 기능 function addKeyboardShortcut() { IFS=', ' read -r -a array <<< `sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings get org.cinnamon.desktop.keybindings custom-list | tr -d '[' | tr -d ']'` # echo "the number of elements in an array : ${#array[@]}" # echo "the value of elements in an array : ${array[-1]}" # echo "last index value : ${array[@]: -1:1}" # echo "index number: ${!array[@]}" if [[ "${array[-1]}" = "@as" ]] ; then result="'custom0'" result="[${result}]" sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.cinnamon.desktop.keybindings custom-list "${result}" # Set gsettings for the Real User sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.cinnamon.desktop.keybindings.custom-keybinding:/org/cinnamon/desktop/keybindings/custom-keybindings/custom0/ binding "['<Primary><Alt>z']" sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.cinnamon.desktop.keybindings.custom-keybinding:/org/cinnamon/desktop/keybindings/custom-keybindings/custom0/ command 'gnome-terminal -e /usr/bin/zsh' sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.cinnamon.desktop.keybindings.custom-keybinding:/org/cinnamon/desktop/keybindings/custom-keybindings/custom0/ name 'ZSH' else # Add new element at the end of the array array=(${array[@]} "'custom${#array[@]}'") CUSTOM_KEY=`echo ${array[@]: -1:1} | tr -d "'"` # echo ${CUSTOM_KEY} # array join function join { local IFS="$1"; shift; echo "$*"; } result=$(join , ${array[@]}) result="[${result}]" sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.cinnamon.desktop.keybindings custom-list "${result}" # Set gsettings for the Real User sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.cinnamon.desktop.keybindings.custom-keybinding:/org/cinnamon/desktop/keybindings/custom-keybindings/${CUSTOM_KEY}/ binding "['<Primary><Alt>z']" sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.cinnamon.desktop.keybindings.custom-keybinding:/org/cinnamon/desktop/keybindings/custom-keybindings/${CUSTOM_KEY}/ command 'gnome-terminal -e /usr/bin/zsh' sudo -u ${RUID} DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${RUSER_UID}/bus" gsettings set org.cinnamon.desktop.keybindings.custom-keybinding:/org/cinnamon/desktop/keybindings/custom-keybindings/${CUSTOM_KEY}/ name 'ZSH' fi # echo $result } addKeyboardShortcut if [ "$1" = "configure" ] || [ "$1" = "abort-upgrade" ] || [ "$1" = "abort-deconfigure" ] || [ "$1" = "abort-remove" ] ; then if which update-icon-caches >/dev/null 2>&1 ; then update-icon-caches /usr/share/icons fi fi #Print Message if running under GUI xcheck=`tty | cut -d '/' -f3` if [[ $xcheck = "pts" ]] then echo $(zenity --info --width=300 --height=180 --title="사용안내" --text "<b>ZSH 프로그램 설치가 완료되었습니다.</b>\n\n단축키 <b><span color=\"blue\">CTRL+ALT+Z</span></b> 로 프로그램을 실행할수 있습니다.\n\n기본 단축키를 변경하려면 키보드 설정에서 단축키 탭을 이용하세요.\n\n<a href=\"https://hamonikr.org\">https://hamonikr.org</a>") 2> /dev/null else echo "ZSH 프로그램 설치가 완료되었습니다. 단축키 CTRL+ALT+Z로 프로그램을 실행할수 있습니다. 기본 단축키를 변경하려면 키보드 설정에서 단축키 탭을 이용하세요. https://hamonikr.org" fi #DEBHELPER# exit 0
Python
UTF-8
4,674
3.03125
3
[]
no_license
''' -*- coding: utf-8 -*- @Author : LiZhichao @Time : 2019/5/21 9:38 @Software: PyCharm @File : 16-Erode-Dilate.py ''' import cv2 as cv import numpy as np import matplotlib.pyplot as plt filename ='C:/Users/19845/Desktop/123.jpg' def Lookformin(subimg): (row,col)=subimg.shape min = 0 for i in range(row): for j in range(col): if subimg[i,j]>0: min =subimg[i,j] break for i in range(row): for j in range(col): if subimg[i, j] < min and subimg[i,j]>0: min = subimg[i, j] return min def getDilate(img, kernel): (H,W) =img.shape dilate2 = np.zeros((H, W), np.uint8) print("img.shape(H,W)=", H, W) (row,col)=kernel.shape # 等于结构元素的子图像 subimg = np.zeros((row, col), np.uint8) # 结构元素卷积运算原始图像 print("kernel.shape(row,col)", row, col) for h in range(row//2, H-row//2): for w in range(col//2, W-col//2): #结构元素与对应点 for i in range(-(row//2), row//2+1): for j in range(-(col//2), col//2+1): subimg[row//2+i,col//2+j] = img[h+i,w+j]*kernel[row//2+i,col//2+j] smax = subimg.max() dilate2[h, w] = smax return dilate2 def getErode(img, kernel): (H,W) =img.shape erodeimg2 = np.zeros((H,W),np.uint8) print ("img.shape is (",H,W,")") (row,col)=kernel.shape print("kernel.shape(",row,col,")=\n", kernel) # 等于结构元素的子图像 subimg = np.zeros((row, col), np.uint8) # 结构元素卷积运算原始图像 for h in range(row//2, H-row//2): for w in range(col//2, W-col//2): #结构元素与对应点 for i in range(-(row//2), row//2+1): for j in range(-(col//2), col//2+1): subimg[row//2+i,col//2+j] = img[h+i,w+j]*kernel[row//2+i,col//2+j] smin = Lookformin(subimg) erodeimg2[h,w]=smin return erodeimg2 def Erode(): image = cv.imread(filename) image = cv.cvtColor(image, cv.COLOR_BGR2GRAY) print(image.shape) img = np.zeros(image.shape, np.uint8) kernel = np.array([[0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0]], dtype=np.uint8) print(kernel) retval, image1 = cv.threshold(image, 127, 255, cv.THRESH_BINARY)#固定阈值二值化 erodeimg1 = cv.erode(image1, kernel, iterations=1) erodeimg2 = getErode(image1, kernel) plt.figure(num='Basic Erode') plt.subplot(231), plt.imshow(image1, cmap='gray'), plt.title( "Original"), plt.xticks([]), plt.yticks([]) plt.subplot(232), plt.imshow(erodeimg1, cmap='gray'), plt.title( "CV Erode"), plt.xticks([]), plt.yticks([]) plt.subplot(233), plt.imshow(erodeimg2, cmap='gray'), plt.title( "My Erode"), plt.xticks([]), plt.yticks([]) img[:] = (erodeimg2[:] + 1) / 128 plt.subplot(234), plt.imshow(img, cmap='gray'), plt.title( "Binarization"), plt.xticks([]), plt.yticks([]) plt.subplot(235), plt.imshow(image1 - erodeimg1, cmap='gray'), plt.title( "CV Edge"), plt.xticks([]), plt.yticks([]) plt.subplot(236), plt.imshow(image1 - erodeimg2, cmap='gray'), plt.title( "My Edge"), plt.xticks([]), plt.yticks([]) plt.show() def Dilate(): image = cv.imread(filename, 0) print(image.shape) img = np.zeros(image.shape, np.uint8) kernel = np.array( [[0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 0, 1, 0, 0]], dtype=np.uint8) print(kernel) retval, image1 = cv.threshold(image, 127, 255, cv.THRESH_BINARY)#固定阈值二值化 dilate1 = cv.dilate(image1, kernel, iterations=1) dilate2 = getDilate(image1, kernel) plt.figure(num='Basic Dilate') plt.subplot(231), plt.imshow(image1, cmap='gray'), plt.title( "Original"), plt.xticks([]), plt.yticks([]) plt.subplot(232), plt.imshow(dilate1, cmap='gray'), plt.title( "CV Dilate"), plt.xticks([]), plt.yticks([]) plt.subplot(233), plt.imshow(dilate2, cmap='gray'), plt.title( "My Dilate"), plt.xticks([]), plt.yticks([]) img[:] = (dilate1[:] + 1) / 128 plt.subplot(234), plt.imshow(img, cmap='gray'), plt.title( "Binary Dilate"), plt.xticks([]), plt.yticks([]) plt.subplot(235), plt.imshow(dilate1 - image1, cmap='gray'), plt.title( "CV edge "), plt.xticks([]), plt.yticks([]) plt.subplot(236), plt.imshow(dilate2 - image1, cmap='gray'), plt.title( "My edge"), plt.xticks([]), plt.yticks([]) plt.show() if __name__ == '__main__': Erode() Dilate()
Java
UTF-8
1,932
2.515625
3
[]
no_license
package com.example.czaro.inzynierka; import android.content.Intent; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class NewCategoryActivity extends AppCompatActivity { private EditText titleCategory; private Button saveCategoryButton; private DatabaseHelper databaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_category); this.titleCategory=(EditText) findViewById(R.id.titleCategory); this.saveCategoryButton=(Button) findViewById(R.id.saveCategoryButton); this.databaseHelper=new DatabaseHelper(this); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); this.databaseHelper.getCategories(); this.saveCategoryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ischeckForm()) { addCategory(); finish(); } else{ Toast.makeText(NewCategoryActivity.this, " nie wypełniono wszystkich pol w formularzu", Toast.LENGTH_LONG).show(); } } }); } private void addCategory(){ Category category = new Category(this.titleCategory.getText().toString()); this.databaseHelper.addCategory(category); this.databaseHelper.getCategories(); } private boolean ischeckForm(){ if (titleCategory.getText().toString().equals("")){ return false; } return true; } }
Java
UTF-8
569
2.09375
2
[]
no_license
package com.lzw.android.weather.feature.home; import com.lzw.android.weather.di.scope.ActivityScoped; import com.lzw.android.weather.feature.home.HomePagePresenter; import dagger.Module; import dagger.Provides; import com.lzw.android.weather.feature.home.HomePageContract; @Module public class HomePageModule { private HomePageContract.View view; public HomePageModule(HomePageContract.View view) { this.view = view; } @Provides @ActivityScoped HomePageContract.View provideHomePageContractView() { return view; } }
Python
UTF-8
438
3.8125
4
[]
no_license
n=eval(input("Enter the starting point N:\n")) m=eval(input("Enter the ending point M:\n")) print("The palindromic primes are:") for nmbr in range(n+1,m): if nmbr>1: for i in range(2,nmbr): if (nmbr%i)==0: break else: x=str(nmbr) if nmbr==eval(x[::-1]): print(nmbr) else: continue else: continue
Python
UTF-8
673
2.8125
3
[]
no_license
import os import sys from multiprocessing import Pipe,Process sortie,entre = Pipe() def Compil(arg : str): name = arg.replace(".c",".o") entre.send(name) entre.close() os.execlp('gcc','gcc','-c',arg,'-o',name) Processus = [] if __name__ == '__main__': if len(sys.argv) < 2: print("Pas de fichier à compiler") sys.exit(0) for arg in sys.argv[1:]: p = Process(target=Compil, args=(arg,)) p.start() Processus.append(p) nameo = [] for proc in Processus: nameo.append(sortie.recv()) proc.join() sortie.close() os.execlp('gcc','gcc','-o',"compil",*nameo)
Markdown
UTF-8
4,366
2.890625
3
[ "MIT" ]
permissive
Title: Wyam 1.0 Lead: Over two years in the making. Published: 9/14/2017 Image: /images/fireworks.jpg Tags: - Wyam - static site generator - open source --- After a little over two years of development, I'm thrilled to announce that Wyam 1.0 is now released! [Wyam is a .NET static generator](https://wyam.io) that unapologetically places an emphasis on flexibility and extensibility. It's the static generator *I* wanted two years ago and I'm thrilled that so many have also found it valuable and interesting along the way. Here are some numbers (as of the writing of this post): * **1337** (not kidding!) commits * **37** contributors * **442** issues reported on the project * **123** pull requests * **461** GitHub stars * **112** GitHub forks * **38** ranking on [StaticGen](https://www.staticgen.com) # Community One of the things I'm most proud of is the community that's formed around the project. We have an active [Gitter room](https://gitter.im/Wyamio/Wyam), issues and feature discussions regularly have good engagement, and I've made a ton of friends working on it. One of my goals going forward is to continue to expand and grow the community beyond the active but moderate size it is today. # What Does 1.0 Mean? More than anything, it means that I'm comfortable with the architecture and stability of Wyam. It's had two years of usage and iteration and I think it's finally time to close the book on this chapter of development. That's not to say there aren't any more bugs, I'm sure there's lots, but we seem to have found and fixed all the ones that were regularly bothering people. # Versioning Going Forward While I appreciate semantic versioning and everything it tries to accomplish, I've never been a purist. That's especially true since any change could potentially be a breaking change and deciding which version place to increment can be a real challenge. Leading up to 1.0 I often broke the API regularly at first, and then less and less frequently as it got closer. Now that this milestone has been reached, I intend to keep breaking changes to a minimum and deprecate functionality (but not remove it) as required. I'll also stick close to the sprit of semantic versioning, if not follow it exactly. In other words, patches shouldn't break anything, minor release probably won't break anything, and major release probably will break stuff. All that said, I also think there's a value in making major release have some external meaning. In other words, I may increment the major release number when some important milestone is reached, even if no breaking changes have occurred. # What's Next? I'll continue to fix bugs, add new features, merge PRs, etc. but my primary focus for the entire 1.0 life cycle is going to be porting to .NET Core. All Wyam extension libraries will get ported to .NET Standard and a new set of runtime applications will be developed that target the .NET Core runtime. I may or may not also keep a console application that also targets .NET Framework. I'll almost certainly come up with a new deployment and update mechanism that doesn't use [Squirrel](https://github.com/Squirrel/Squirrel.Windows) (it's been fine, if not a little flaky, but I want something fully cross platform). I don't have any hard dates, but I'd like to get this done quickly. 2.0 will land once all the .NET Standard and .NET Core activity is complete. Beyond that I have a lot of *big plans*. There's huge potential for integration and tooling around static site generation and I'd like to focus some effort in that area. There's also a [huge backlog](https://github.com/Wyamio/Wyam/issues) of awesome ideas for small and large enhancements to Wyam itself. # Thank You Finally, I'd like to take a moment to say "thank you" to everyone who's been involved in this project so far. Whether you've written about Wyam, used it, filed issues, contributed code, or just bounced ideas in the Gitter room, you're all a valued member of this community. For the last two years I've dedicated myself to this project, bordering on obsession. Not a day goes by that I don't work on it or at least think about it. Even if I were the only one interested I would still be building it, but I can't express what a comfort it is knowing that all this effort is interesting and helpful to others.
Markdown
UTF-8
1,924
3.203125
3
[ "MIT" ]
permissive
--- title: Calculating rotation transformation to align component with direction caption: Aligning Component With Rotation Transformation description: VBA example demonstrates hwo to calculate the rotation transformation to align the normal of the component's face with edge direction around the component's origin image: rotation-transform.png labels: [transform,rotation,align] --- This VBA example demonstrates how to use the [IMathUtility::CreateTransformRotateAxis](https://help.solidworks.com/2017/English/api/sldworksapi/SOLIDWORKS.Interop.sldworks~SOLIDWORKS.Interop.sldworks.IMathUtility~CreateTransformRotateAxis.html) SOLIDWORKS API to rotate the component and align the normal of its face with the direction from the linear edge. As a precondition select the planar face on the first component in the assembly and linear edge on the second component in the assembly. First component must not be fixed and do not have any mates. As the result first component rotated in a way that its normal is collinear with the direction of the edge. Component is rotated around the origin. ## Explanation In order to transform the component in the expected way it is required to calculate its transform. For that it is required to find the origin of rotation, rotation vector and an angle. At first we create vectors of the face normal and edge direction. It is required to apply the transformation of the components to represent vectors in the same coordinate system. The angle between those vectors is a required angle of transformation. In order to find the vector of rotation it is required to find the vector perpendicular to both normal and direction. This can be achieved by finding the cross product. Finally point of rotation is an origin of the component transformed to the assembly coordinate system. ![Rotation transformation parameters](rotation-transform.png) {% code-snippet { file-name: Macro.vba } %}
Markdown
UTF-8
1,624
3.046875
3
[ "MIT" ]
permissive
# NRestful C# library to consume a Restful API from .NET **Usage:** Instantiate a client and pass the URL of the Resfult Api as a parameter and send a "GET" request. ```cs /*************** * WebApi URL: ***************/ const string Url = "http://localhost:3034/api/"; var client = new Client(Url); //Send a GET request: var response = client.RequestAsync<string>(new Request { EndPoint = new EndPoint { Method = Method.GET, Uri = "sample/{id}" }, UrlSegment = { { "id", "5" } } }); var result = await response; Console.WriteLine(result.Content); ``` Send a "POST" request to a WebApi "POST" method **WebApi Example:** public void Post([FromBody]string value) ```cs var response = client.RequestAsync<string>(new Request { EndPoint = new EndPoint { Method = Method.POST, Uri = "sample/" }, Data = "'This is the value posted'" }); ``` Send a "POST" request to a WebApi and send a JSON object **WebApi Example:** public void Post([FromBody]User account) ```cs var response = client.RequestAsync<string>(new Request { EndPoint = new EndPoint { Method = Method.POST, Uri = "sample/" }, Data = JsonHelper.ToJson(new { firstName = "Walter", lastName = "Soto", Email = "email@email.net" }) }); ```
Java
UTF-8
506
1.726563
2
[]
no_license
package com.yc.wowo.biz; import java.util.List; import com.yc.wowo.entities.AdminInfo; import com.yc.wowo.entities.GoodsType; import com.yc.wowo.entities.Shop; public interface IShopBiz { public List<GoodsType> find(); public List<AdminInfo> find(Integer rid ); public Integer add(String sname, String aname, String tid, String prov, String city, String area ,String addr, String tel, String text); public List<Shop> find(Integer pageNo, Integer pageSize); public List<Shop> select(); }
Java
UTF-8
435
2.96875
3
[]
no_license
package com.dragon.book.javacore.chapter5.objectAnalyzer; import java.util.ArrayList; /** * User: dengshenyan * Time: 2018-04-27 17:20 */ public class ObjectAnalyzerTest { public static void main(String[] args) { ArrayList<Integer> squares = new ArrayList<>(); for (int i = 1; i <= 5; i++) { squares.add(i * i); } System.out.println(new ObjectAnalyzer().toString(squares)); } }
Python
UTF-8
3,719
2.671875
3
[ "BSD-2-Clause" ]
permissive
#################################################################################### # Note: 2nd. # Author: Gang-Cheng Huang (Jacky5112) # Date: Dec.9, 2020 # Lecture: Information Security Training and Education Center, C.C.I.T., N.D.U., Taiwan # Dataset. https://www.kaggle.com/c/dogs-vs-cats/data?select=train.zip #################################################################################### import numpy as np from keras import applications from keras.preprocessing.image import ImageDataGenerator from keras import optimizers from keras.models import Sequential, Model from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D, BatchNormalization from keras.layers import Dropout, Flatten, Dense, Activation from keras.applications.vgg16 import VGG16 from keras import backend as K from common import show_train_history random_seed = 1234 np.random.seed(random_seed) # dimensions of our images. img_width, img_height = 150, 150 img_detail = (img_width, img_height) # ssd train_data_dir = 'data_2/train' validation_data_dir = 'data_2/validation' nb_train_samples = 2000 nb_validation_samples = 800 epochs = 50 batch_size = 16 learning_rate = 0.000001 #momentum = 0.4 #decay = 0.1 if K.image_data_format() == 'channels_first': input_shape = (3, img_width, img_height) else: input_shape = (img_width, img_height, 3) base_model = VGG16(weights = 'imagenet', include_top = False, input_shape = input_shape) x = Flatten()(base_model.output) x = Dense(4096, activation='relu')(x) x = Dropout(0.25)(x) x = Dense(1024, activation='relu')(x) x = Dropout(0.25)(x) x = BatchNormalization()(x) predictions = Dense(1, activation = 'sigmoid')(x) model = Model(input = base_model.input, output = predictions) #model = Sequential([ # Conv2D(6, kernel_size=(5, 5), input_shape=input_shape, padding='same', activation='relu'), # MaxPooling2D(pool_size=(2, 2), strides=(2, 2)), # Conv2D(6, kernel_size=(5, 5), padding='same', activation='relu'), # MaxPooling2D(pool_size=(2, 2), strides=(2, 2)), # Flatten(), # Dense(4096, activation='relu'), # Dense(4096, activation='relu'), # BatchNormalization(), # Dense(1, activation='sigmoid') # ]) # print summary print(model.summary()) model.compile(loss='binary_crossentropy', #optimizer=optimizers.SGD(lr=learning_rate, momentum=momentum, decay=decay, nesterov=True), optimizer=optimizers.Adam(lr=learning_rate), metrics=['accuracy']) train_datagen = ImageDataGenerator( rescale=1./255, dtype='float32', shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator( rescale=1./255, dtype='float32') train_generator = train_datagen.flow_from_directory( train_data_dir, target_size=img_detail, batch_size=batch_size, color_mode='rgb', class_mode='binary', seed=random_seed) validation_generator = test_datagen.flow_from_directory( validation_data_dir, target_size=img_detail, batch_size=batch_size, color_mode='rgb', class_mode='binary', seed=random_seed) train_history = model.fit_generator( train_generator, steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, validation_steps=nb_validation_samples // batch_size) ## Debug use common.show_train_history(train_history, 'accuracy', 'val_accuracy') common.show_train_history(train_history, 'loss', 'val_loss') scores = model.evaluate_generator(validation_generator, nb_validation_samples / batch_size) print ("Scores: {0}".format(scores[1]))
Java
UTF-8
470
2.59375
3
[]
no_license
package engine.validation; import engine.Puzzle; /** * @author Nerijus */ public class PuzzleValidator { /** * Checks if puzzle contains valid questions * and that answers can fit into the puzzle. * Does not check if puzzle can be solved or not. * * @param puzzle puzzle to validate * @return true if puzzle is valid */ public static boolean isValid(Puzzle puzzle) { // TODO: validate return true; } }
C#
UTF-8
1,525
3.359375
3
[]
no_license
using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace LeetCode.Easy { class Factorial_Trailing_Zeroes { public int TrailingZeroes(int n) { if (n == 0) { return 0; } else { int product = 1; for (int i = 2; i <= n; i++) { product *= i; } var str = product.ToString(); int ret = 0; for (int i = str.Length - 1; i >= 0; i--) { if (str[i] == '0') { ret++; } } return ret; } } [Test(Description = "https://leetcode.com/problems/isomorphic-strings/")] [Category("Easy")] [Category("Leetcode")] [Category("Isomorphic Strings")] [TestCaseSource("Input")] public void Test1((int Output, int Input) item) { var response = TrailingZeroes(item.Input); Assert.AreEqual(item.Output, response); } public static IEnumerable<(int Output, int Input)> Input { get { return new List<(int Output, int Input)>() { (2, 7), (2, 13), (1, 5), }; } } } }
Java
UTF-8
196
1.539063
2
[]
no_license
package ru.fizteh.fivt.orlovNikita.bind.test; public class ClassBadSerialisation { private ClassBadSerialisation pointer; public ClassBadSerialisation() { pointer = this; } }
Java
UTF-8
327
1.84375
2
[]
no_license
package com.movie.favorite.dao.impl; import com.movie.favorite.domain.Movie; import com.movie.favorite.dao.api.MovieDao; import org.springframework.stereotype.Repository; @Repository public class MovieDaoImpl extends BasicJpaDao<Movie> implements MovieDao { public MovieDaoImpl () { super (Movie.class); } }
Java
UTF-8
868
2.4375
2
[ "MIT" ]
permissive
package ch.itenengineering.env.client; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import ch.itenengineering.env.ejb.EnvRemote; public class EnvClient { public static Context getInitialContext() throws NamingException { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); return new InitialContext(env); } public static void main(String[] args) { try { // init Context ctx = getInitialContext(); EnvRemote env = (EnvRemote) ctx .lookup("ejb:/Environment/EnvBean!ch.itenengineering.env.ejb.EnvRemote"); // get environment entries (messages) System.out.println(env.getMessages()); } catch (NamingException e) { e.printStackTrace(); } } } // end of class
JavaScript
UTF-8
2,341
2.515625
3
[]
no_license
const nameMethods = [ {name: 'A1Z26'} ,{ name: 'ROT13' }, { name: 'Atbash' }, { name: 'Escítala' }, { name: 'Polybios' }, { name: 'Repetition' }, { name: 'Vigenère' }, { name: 'Cesar' }, { name: 'NumberBase' }, {name: 'Reverse'} ] const globalInputs = [ [],[],[],[{title: 'Rows'}, {title: 'Columns'}], [],[], [{title: 'Word Key'}], [{title: 'Key'}], [{title: 'Numerical base'}], [] ] const urlMethods = [ { url: '' }, { url: 'https://darkbyteblog.wordpress.com/2011/06/15/criptografia-rot13/' }, { url: 'http://www.ugr.es/~anillos/textos/pdf/2010/EXPO-1.Criptografia/02a01.htm' }, { url: 'https://es.wikipedia.org/wiki/Esc%C3%ADtala' }, { url: 'https://unamcriptografia.wordpress.com/category/tecnicas-clasicas-de-cifrado/sustitucion/monoalfabetica/monogramica/polybios/' }, { url: 'https://unamcriptografia.wordpress.com/category/vigenere/' }, { url: '' }, { url: 'https://unamcriptografia.wordpress.com/category/tecnicas-clasicas-de-cifrado/sustitucion/monoalfabetica/monogramica/cesar/' }, { url: 'https://es.wikipedia.org/wiki/Base_(aritm%C3%A9tica)' }, { url: '' }, ] new Vue({ el: '#interface', data: { title: 'Encryption', author: 'TEAM WASP', text: '', selected: '', inputs: [], valueInputs: [], methods: nameMethods, url: '', finalText: '' }, methods: { createInputs: function() { let i = 0; nameMethods.forEach(element => { if(element.name == this.selected) { this.inputs = globalInputs[i]; this.url = urlMethods[i].url; } i++; }); }, crypto: function() { if(this.inputs.length != 0) { this.finalText = createCryptoInputs(this.text, this.selected, this.valueInputs); } else { this.finalText = createCrypto(this.text, this.selected); } }, decipher: function() { if(this.inputs.length != 0) { this.finalText = destroyCryptoInputs(this.text, this.selected, this.valueInputs); } else { this.finalText = destroyCrypto(this.text, this.selected); } } } });
Ruby
UTF-8
4,016
2.921875
3
[ "MIT" ]
permissive
require "csv" module Geokit module Geocoders describe AirplaneGeocoder do it "should return a LatLng when given a valid city, state" do loc = Geokit::Geocoders::AirplaneGeocoder.geocode('Boston, MA') loc.class.should == LatLng loc.should be_valid end it "should return invalid LatLng for invalid city, state combinations" do Geokit::Geocoders::AirplaneGeocoder.geocode('New York, MA').should_not be_valid Geokit::Geocoders::AirplaneGeocoder.geocode('Boston, CA').should_not be_valid Geokit::Geocoders::AirplaneGeocoder.geocode('Total Junk').should_not be_valid end it "should return a LatLng when given a valid state" do loc = Geokit::Geocoders::AirplaneGeocoder.geocode('MA') loc.class.should == LatLng loc.should be_valid end it "should return a LatLng for each state" do CSV.foreach(File.join(File.dirname(__FILE__), "../../db/state_latlon.csv"), :headers => true) do |row| state = row[0] lat = row[1] lng = row[2] Geokit::Geocoders::AirplaneGeocoder.geocode(state).should == LatLng.new(lat, lng) end end it "should return invalid LatLng for invalid state or long state name" do Geokit::Geocoders::AirplaneGeocoder.geocode('New York').should_not be_valid Geokit::Geocoders::AirplaneGeocoder.geocode('XX').should_not be_valid end it "should return a LatLng for a zip code" do loc = Geokit::Geocoders::AirplaneGeocoder.geocode("90210") loc.class.should == LatLng loc.should be_valid end it "should return an invalid LatLng for invalid zipcode" do Geokit::Geocoders::AirplaneGeocoder.geocode("99999").should_not be_valid Geokit::Geocoders::AirplaneGeocoder.geocode("90210-1234").should_not be_valid Geokit::Geocoders::AirplaneGeocoder.geocode("9021").should_not be_valid end it "should return a LatLng for a phone number" do Geokit::Geocoders::AirplaneGeocoder.geocode("9785551212").should be_valid end it "should return an invalid LatLng for phone number with bad area code" do Geokit::Geocoders::AirplaneGeocoder.geocode("9115551212").should_not be_valid end context "sanitize_phone" do it "should sanitize phone numbers to be 10 digits" do Geokit::Geocoders::AirplaneGeocoder.sanitize_phone('9785551212').should == '9785551212' Geokit::Geocoders::AirplaneGeocoder.sanitize_phone('978-555-1212').should == '9785551212' Geokit::Geocoders::AirplaneGeocoder.sanitize_phone('978.555.1212').should == '9785551212' Geokit::Geocoders::AirplaneGeocoder.sanitize_phone('(978)555-1212').should == '9785551212' Geokit::Geocoders::AirplaneGeocoder.sanitize_phone('(978) 555-1212').should == '9785551212' Geokit::Geocoders::AirplaneGeocoder.sanitize_phone('+1 978-555-1212').should == '9785551212' end end context "us_phone_number?" do it "should return true if the argument looks like a phone number" do Geokit::Geocoders::AirplaneGeocoder.us_phone_number?('9785551212').should be_true Geokit::Geocoders::AirplaneGeocoder.us_phone_number?('978-555-1212').should be_true Geokit::Geocoders::AirplaneGeocoder.us_phone_number?('978.555.1212').should be_true Geokit::Geocoders::AirplaneGeocoder.us_phone_number?('(978)555-1212').should be_true Geokit::Geocoders::AirplaneGeocoder.us_phone_number?('(978) 555-1212').should be_true Geokit::Geocoders::AirplaneGeocoder.us_phone_number?('+1 978-555-1212').should be_true end it "should return false if the argument does not look like a phone number" do Geokit::Geocoders::AirplaneGeocoder.us_phone_number?('978555121').should be_false Geokit::Geocoders::AirplaneGeocoder.us_phone_number?('words').should be_false end end end end end
Python
UTF-8
4,256
2.5625
3
[]
no_license
import random import os from PIL import Image from scipy.misc import imsave def select_images(num_test_images=50, path_imagesA='datasets/Day2Night/trainA/', path_imagesB='datasets/Day2Night/trainB/'): data_imagesA = os.listdir(path_imagesA) num_imagesA = len(data_imagesA) - 1 data_imagesB = os.listdir(path_imagesB) num_imagesB = len(data_imagesB) - 1 for x in range(num_test_images): imsave('test_images/testA/{x}.jpg'.format(x=x), Image.open('datasets/Day2Night/trainA/{img}'.format(img=data_imagesA[random.randint(0, num_imagesA)])) ) imsave('test_images/testB/{x}.jpg'.format(x=x), Image.open('datasets/Day2Night/trainB/{img}'.format(img=data_imagesB[random.randint(0, num_imagesB)])) ) def move_images(results_folder, dst_folder): # Yes, it's hard coded. imgs = os.listdir('results/{rf}/test_latest/images/'.format(rf=results_folder)) # Checking if the destination path exists: if it doesn't, generates it if not os.path.exists(dst_folder): os.mkdir(dst_folder) os.mkdir(dst_folder + '/AtoB') os.mkdir(dst_folder + '/BtoA') os.mkdir(dst_folder + '/AtoB/generated') os.mkdir(dst_folder + '/BtoA/generated') os.mkdir(dst_folder + '/AtoB/true') os.mkdir(dst_folder + '/BtoA/true') if results_folder == 'day2nightSoloIR' or results_folder == 'day2nightSoloRGB': # AtoB saving process print('Starting A to B saving process...') imgsAB = [x for x in imgs if 'real_A1' in x or 'fake_B' in x] for img in imgsAB: if 'real_A1' in img: imsave('{df}/AtoB/true/{img}'.format(df=dst_folder, img=img), Image.open('results/{rf}/test_latest/images/{img}'.format(rf=results_folder, img=img)) ) else: imsave('{df}/AtoB/generated/{img}'.format(df=dst_folder, img=img), Image.open('results/{rf}/test_latest/images/{img}'.format(rf=results_folder, img=img)) ) # BtoA saving process print('Starting B to A saving process...') imgsBA = [x for x in imgs if 'fake_A1' in x or 'real_B' in x] for img in imgsBA: if 'fake_A1' in img: imsave('{df}/BtoA/generated/{img}'.format(df=dst_folder, img=img), Image.open('results/{rf}/test_latest/images/{img}'.format(rf=results_folder, img=img)) ) else: imsave('{df}/BtoA/true/{img}'.format(df=dst_folder, img=img), Image.open('results/{rf}/test_latest/images/{img}'.format(rf=results_folder, img=img)) ) elif results_folder == 'day2nightStd': # AtoB saving process print('Starting A to B saving process...') imgsAB = [x for x in imgs if 'real_A1' in x or 'real_A2' in x or 'fake_B' in x] for img in imgsAB: if 'real_A1' in img or 'real_A2' in img: imsave('{df}/AtoB/true/{img}'.format(df=dst_folder, img=img), Image.open('results/{rf}/test_latest/images/{img}'.format(rf=results_folder, img=img)) ) else: imsave('{df}/AtoB/generated/{img}'.format(df=dst_folder, img=img), Image.open('results/{rf}/test_latest/images/{img}'.format(rf=results_folder, img=img)) ) # BtoA saving process print('Starting B to A saving process...') imgsBA = [x for x in imgs if 'fake_A1' in x or 'fake_A2' or 'real_B' in x] for img in imgsBA: if 'fake_A1' in img or 'fake_A2' in img: imsave('{df}/BtoA/generated/{img}'.format(df=dst_folder, img=img), Image.open('results/{rf}/test_latest/images/{img}'.format(rf=results_folder, img=img)) ) elif 'real_B' in img: imsave('{df}/BtoA/true/{img}'.format(df=dst_folder, img=img), Image.open('results/{rf}/test_latest/images/{img}'.format(rf=results_folder, img=img)) ) move_images('day2nightStd', 'FID/Std')
Python
UTF-8
162
2.890625
3
[]
no_license
""" Viết chương trình tạo mảng 3D 3*5*8 có mỗi phần tử là 0. """ arr = [[[0 for i in range(8)] for i in range(5)] for row in range(3)] print(arr)
Markdown
UTF-8
21,883
2.90625
3
[]
no_license
> [name=邱綜樹] 臭屁股 98下期中考 - 1. (25%)請問下列反應何者為本能的反應?何者為情結所引發的反應?請依據榮格的定義回答並略述其理由。 1. 我們最心愛的一本書遺失了,我們感到很懊惱。 2. 剛發生空難後,有些人不敢坐飛機。 3. 當我們走在路上,突然身旁有巨大的爆裂聲,我們因此嚇一跳。 4. 當有人拿槍對著我們時,我們會懼怕。 5. 當嬰兒吸奶時,我們突然將奶瓶拿走,嬰兒因此哭鬧。 2. (15%)我們提到,動物在REM睡眠階段,四肢肌肉會呈現鬆弛狀態。請解釋生理上為何需要在REM睡眠階段有這樣的反應。 3. (15%)由爬蟲類的腦部結構來看,爬蟲類是否會具有類似哺乳類動物的情緒反應,如憤怒與恐懼?請解釋理由。 4. (15%)同卵雙胞胎的一對兄弟(同卵雙胞胎意謂他們的基因完全一樣),其家族的遺傳史上呈現高比率的胃癌病例。若這對雙胞胎日後也都罹患胃癌,則是否一定會發生在同一個年齡?請解釋理由。 5. (15%)依照三重腦模型,邊緣系統是原始哺乳類動物由爬蟲類進化而來時所新增加的腦部組織。之後,原始哺乳類動物再進化到高等哺乳類動物時又新增了大腦新皮質。然而,高等哺乳類動物仍然保留了邊緣系統。保留邊緣系統對高等哺乳類動物而言有何生物上的意義? 6. (15%)動物的體重大約是隨著身長的立方而增加,而其體表面積大約是隨著身長的平方而增加。也就是說,當動物身長增加時,其體表面積/體重的比例會下降。請由這個事實解釋為何同類的哺乳類動物生存在寒帶地區的其體積通常都較生存在熱帶地區的大,例如北極熊體型就較台灣黑熊大。 98下期末考 - 1. (30%)如果有人因為腦部手術導致杏仁核與週遭組織遭到破壞,請由以下兩個層面 描述該病患手術後的心理表現。 1. 情緒反應 2. 潛意識反應 2. (20%)恐懼情緒的產生有兩個不同的路徑。請描述兩個路徑的運作。 99上期中考 - 1. (a)在制約反應的運作過程中,除感官皮質(如視覺皮質、聽覺皮質等)外,杏仁核接受其他哪3個腦部組織的神經訊號輸入? (b)感官皮質傳送到杏仁核的神經訊號提供了什麼重要資訊?(8%) 2. 請說明下列不同型態的記憶是儲存在大腦中的哪一個組織?(6%) (a)工作記憶 (b)新近記憶 (c )長期記憶 ***A. 前額葉 B. 海馬迴 C. 新皮質*** :::warning 3. 當一個男生看到他的女友與其他男生有親密行為,而因此怒火中燒時,請說明神經訊號在下列腦組織中傳遞的順序為何?(10%) (a)杏仁核 (b)前額葉 (c )下視丘 (d)視丘 (e)視覺皮質 ***D->E->A->C*** ::: 4. 在下列異常病徵中,請選出何者可能與杏仁核病變有關?(7%) (a)喪失工作記憶 (b)喪失某些情緒反應 ( c)喪失某些感官意識(例如失明、重聽等) (d)喪失情緒相關潛意識記憶 (e)無法學習新的運動技能 (f)無法記得幾天前發生的事 (g)喪失長期記憶 5. 在下列異常病徵中,請選出何者可能與前額葉病變有關?(7%) (a)喪失工作記憶 (b)喪失某些情緒反應 (c )喪失情緒相關潛意識記憶 (d)無法學習新的運動技能 (e)喪失長期記憶 (f)無法記得幾天前發生的事 (g)容易情緒失控 6. 在下列異常病徵中,請選出何者可能與海馬迴病變有關?(7%) (a)喪失工作記憶 (b)喪失某些情緒反應 (c )喪失情緒相關潛意識記憶 (d)無法學習新的運動技能 (e)喪失長期記憶 (f)無法記得幾天前發生的事 (g)容易情緒失控 ***A, D, F*** 7. 「情境暴露治療」是治療創傷後壓力症的一種方法,請說明在「情境暴露治療的過程中,下列腦區的活躍狀態為何?是(i)經常處於高度活躍狀態;或(ii)大部分時間處於低度活躍狀態,偶爾會高度活躍;還是(iii)持續處於不活躍狀態?(8%) (a)前額葉外緣 (b)腹內前額葉皮質(含視額葉皮質)與前扣帶迴 (c )杏仁核 (d)視丘 (e)海馬迴 (f)感官皮質 (g)中腦腹側蓋區 (h)藍斑核 8. 憂鬱症發作時,下列腦區的活躍狀態為何?是(i)處於高度活躍狀態;或(ii)處於不活躍狀態?(9%) (a)前額葉外緣 (b)腹內前額葉皮質(含視額葉皮質)與前扣帶迴 (c )杏仁核 (d)視丘 (e)海馬迴 (f)感官皮質 (g)中腦腹側蓋區 (h)藍斑核 (i)中縫核 9. 下列賀爾蒙在創傷後壓力症患者體內是(i)高於常人;或(ii)低於常人;還是(iii)與正常人無異?(3%) (a)正腎上腺素 (b)多巴胺 (c )皮質醇 10. 下列賀爾蒙在禪定修行者體內是(i)高於常人;或(ii)低於常人;還是(iii)與正常人無異?(3%) (a)正腎上腺素 (b)多巴胺 (c )皮質醇 11. 當修行者進入禪定的狀態時,下列腦區的活躍狀態為何?是(i)處於高度活躍狀態;或(ii)處於不活躍狀態?(6%) (a)左大腦前額葉 (b)右大腦前額葉 (c )杏仁核 (d)前扣帶迴 (e)中腦腹側蓋區 (f)藍斑核 12. 請簡單解釋佛洛伊德所說的「本我」、「自我」與「超我」(6%) **本我:潛意識。趨力為滿足各種欲望** **超我:一小部分為意識,絕大部分為潛意識。趨力為理性與道德、良心** **自我:意識。調和本我跟超我** 13. 請簡單解釋榮格所說的本我、集體潛意識與個體潛意識(6%) 14. 在REM睡眠期,會呈現何種生理現象?(5%) (a)大腦前額葉皮質活動 (i)增加(ii)降低 (b)海馬迴 (i)活躍(ii)不活躍 (c )四肢肌肉 (i)放鬆(ii)緊張 (d)大腦血流 (i)增加(ii)降低 (e)腦波頻率 (i)變快(ii)變慢 ***A. 降低 B. 活躍 C. 放鬆 D. 增加 E. 變快*** 15. 請問下列有關爬蟲類的敘述,何者為正確的,何者為錯誤的(3%) (a)具完整的邊緣系統 (b)具情緒反應 (c )不具REM睡眠 ****a. 具有完整邊緣系統(X)**** ****b. 具有情緒反應(X)**** ****c. 不具有REM睡眠(O)**** 99上期末考 - 1. 請略述過多負面情緒對我們(a)免疫系統 (b)心理健康 (c)心血管疾病 (d)腸胃道疾病等方面的影響?(12%)(每項答案字數約在20-30字左右為宜,應列舉一些生理反應或疾病的風險變化) 2. 請略述正面情緒對我們(a)免疫系統 (b)心理健康等方面的影響?(6%)(作答方式同第一題) 3. 請略述我們在meditation(靜思、冥想、或靜坐)時會進入的心境狀態?(9%)(答案應該是心境狀態而不是腦波變化,或呼吸心跳等生理反應) 4. 印度吠陀學認為一般人有哪三種意識狀態?(9%) 5. 何謂α波阻斷(α-blocking)?(5%) 資深打坐者與一般人相較,α波阻斷的現象有何可能的不同?(10%) 6. 下列幾項內分泌物何者與憂鬱症的病因有關?(10%) (a)乙醯膽鹼 (b)正腎上腺素 (c)腎上腺素 (d)血清素 (e)多巴胺 ****B, D, E**** 7. 我們進入REM睡眠時,下列腦區的活動是?(i)增加或(ii)減少還是(iii)沒有變化?(12%) (a)海馬迴 (b)杏仁核 (c)工作記憶區 (d)視覺皮質 (e)前扣帶迴 (f)前額葉中負責邏輯與推理的區域。 ****A. 增加 B. 增加 C. 減少 D. 增加 E. 增加 F. 減少**** > 簡單的來說就是做夢會不合邏輯,且醒來會不易記起夢的內容 8. 我們進入REM睡眠時,下列兩項內分泌物的濃度改變為何?(i)增加或(ii)減少還是(iii)沒有變化?(4%) [老師考試時說為與正常的清醒狀態比較] (a)乙醯膽鹼 (b)多巴胺。 ****REM睡眠時,乙醯膽鹼濃度上升,正腎上腺素與血清素濃度下降,多巴胺濃度沒有變化**** 9. 如果我們分析下列族群的人有關攻擊性的夢境,我們應該會觀察到那些族群夢中此類夢境的比例比較接近?(9%)(提示:應該可以分成三大群) (a)美國黑人 (b)南非黑人 (c)美國白人 (d)瑞士白人 (e)奧地利白人 (f)南非白人(g)美國華人。 ****AFG, B, CDE**** > 原住民攻擊性會比較高 10. 如果我們要以幾個字述說猶太教、基督教、以及回教的共同哲學觀念或信仰基礎,我們該如何說?(5%) **均信奉唯一真神,以耶路撒冷為朝聖中心** 11. 如果我們要以幾個字述說印度教、佛教、以及中國道家的共同哲學觀念,我們該如何說?(5%) **** 12. 請問下列腦波何者可能出現在資深打坐者進入深層的meditation狀態時,而在初學打坐者meditation時較少觀察到?(4%)[老師考試時有說此題應為複選] (a)α波 (b)β波 (c)γ波 (d)θ波。 **AC** 99下期中考 - 1. 請簡述下列組織在制約反應的運作過程中,扮演何種角色? (a)感官皮質(如視覺皮質、聽覺皮質等); (b)海馬迴; (c)丘腦; (d)前額葉皮質。(8%) 2. 在課程的講義上,我們將各種有關宇宙組成的哲學論述歸納成4類學說。除唯心論外,請列出其他3類學說的名稱?(6%) **(唯心論、)唯物論、心物二元論、方法論的自然主義跟心物一元論** 3. 在早期的中國,主要的唯心論學派為何?在早期的印度,主要的唯心論學派為何?(4%) **宋明理學;唯識學派** 4. 請簡述 methodological naturalism 的主要觀念為何?(5%) **主張任何可以觀察到的現象都可以用科學方法加以研究。** 5. 請問下列哪些心智活動是當今腦神經科學已經可以提供某個層面的科學解釋,而哪些心智活動則是當今腦神經科學仍無法窺得其運作機制的?(10%) (a)憤怒; (b)自我意識; (c) 快樂; (d)自由意志; (e)焦慮。 **A, C, E可以;B, D仍無法** 6. 依據佛洛依德的理論,在下列的狀況下,我們的心智活動是由「自我」、「本我」、或「超我」所主導(每小題只有一項答案)?(6%) (a) 某甲搭捷運時十分疲憊,這時看到博愛座仍有空位,某甲就去坐下; (b) 到了下一站,有長者上車,某甲看到後內心不安,心中有個聲音說應該要讓座; (c) 然而某甲此時十分疲憊,因此內心頗為煎熬。 **本我、超我、自我** :::warning 7. 情緒的啓動有兩種不同的路徑,請填入下圖中的空格。(16%) 直接反應的情緒啓動路徑 (c) →「逃或戰」行為 ↗(d) 視丘→(a)→(b) ↘ (e) → 壓力或焦慮反應 **A. 杏仁核 B. 下視丘 C. 自律神經系統 D. ? E. 內分泌系統** [參考屁](http://www.brainlohas.org/wonderfulbrain/guide_b.htm) 意識主導的情緒啓動路徑 視丘→(f)→(g)→(h)→自主神經及內分泌反應 **F. 大腦皮質 G. 杏仁核 H. 下視丘** ::: 8. 下圖中未著註明腦波有一種是REM睡眠而另兩種是NREM睡眠,請予以註明何者為REM睡眠 而何者為NREM睡眠。(6%) ![](https://i.imgur.com/lULBdYR.jpg) **A, B為NREM睡眠 C為REM睡眠** 9. 請問下列一些特徵,何者為爬蟲類所具備,而何者則為爬蟲類所不具備?(3%) (a)丘腦; (b)海馬迴; (c)杏仁核。 **爬蟲類具備海馬迴,不具備丘腦及杏仁核** 10. 請針對下列的問題提供精簡扼要的說明。(27%) (a) 為何我們不認為爬蟲類據有情緒反應? **因為爬蟲類的腦沒有完整的邊緣系統** (b) 在REM睡眠中,我們四肢的肌肉處在鬆弛的狀態,請問這有何生物學上的意義? **失去了通過肌肉運動來調節體溫的能力** (c) 請舉例說明情緒反應對生物生存的重要性。 (d) 我們在遇到某些突發狀況時,對當下的情境記憶特別清楚,請問這有何生物學上的意義? **事件記憶,屬於長期記憶的一種 [wiki](https://zh.wikipedia.org/wiki/記憶)** (e) 請舉例說明為何生物在演化中會出現(d)項的特質。也就是說(d)項特質有何生物學上的意義? (f) 我們在過度緊張或恐懼的狀態下,有時會腦袋一片茫然無法做出適當反應,請問這是哪種內分泌物直接作用的結果? **腎上腺素中的cortisol [詳細](http://www.kingnet.com.tw/knNew/news/single-article.html?newId=4195&source=essay&pid=457)** (g) 請問產生(f)項效果的內分泌物是否會作用在杏仁核區域? **會** (h) 為何我們在長期的壓力下,記憶功能可能受損?這是何種內分泌物作用在哪個腦部組織所造成? **下視丘控制的腎上腺皮質素作用在海馬迴** > 在壓力下,興奮的交感神經除了造成心跳增快、血壓增加、呼吸急促,同時也間接造成通往大腦的葡萄糖增加,讓神經元有更多的能量可以使用,使得記憶的形成與拮取更容易,腎上腺皮質素的些微增加也幫助記憶,但是壓力持續不斷之下,長期壓力造成的腎上腺皮質素大量增加就會傷害記憶了,腎上腺皮質素大量增加同時還會傷害記憶的主體--海馬體,使海馬體萎縮,失智症患者就是因為海馬體萎縮所造成的,會分泌大量腎上腺皮質素的庫興氏症候群患者,也都有某種程度的記憶障礙。 > [壓力與記憶](http://yannan.byethost5.com/health/health37.htm?i=1) (i) 除了記憶功能外,請列舉其他3個生理系統可能在長期的壓力下導致功能下降。 1. ***骨質流失*** 2. ***免疫力下降*** 3. ***抑制松果體分泌褪黑激素,導致失眠*** 11. 在下列異常病徵中,請選出何者可能與前額葉(包括腹內前額葉皮質、視額葉皮質、前額葉皮質內側等部位)病變有關?並請略述相關的理由。(9%) (a)無法形成恐懼制約; (b)恐懼制約的反應無法消除; (c)受驚嚇時無法記得當時情境。 ****** 99下期末考 - 7. 哈佛大學的羅伯特.華裏斯(Robert K. Wallace)和赫伯特.班遜(Herbert Benson)兩位教授針對禪坐修習者的研究顯示下列的生理現象會產生何種變化?(8%) (a) 耗氧量; (b) 心跳; (c) 皮膚電阻; (d) 血液中乳酸鹽。 ****** 8. 請問 NREM 睡眠在生理上主要的功能是什麼?(5%) ****在這段睡眠期間,大腦的活動下降到最低,使得人體能夠得到完全的舒緩。**** 9. 請問與 REM 睡眠以及作夢有關的神經傳導物質有哪四種?(8%) **1. 乙醯膽鹼 2. 正腎上腺素 3. 血清素 4. 多巴胺** 10. 請問我們在 REM 睡眠時,下列腦區的活躍程度會產生何種變化?(12%) 1. 前額葉中負責情緒調控的腦區 === > **降低** 2. 前額葉中負責邏輯與推理的腦區 ===> **降低** 3. 海馬迴以及周邊皮質 ===> **增加** 4. 杏仁核 ===> **增加** 5. 視覺皮質 ===> **增加** 6. 工作記憶區 ===> **降低** 11. 我們提到生活在小型原住民部落的人,夢境中有攻擊性的內容比例最高。以澳洲原住民族群依尤倫為例,92% 的夢境具攻擊性。至於美國男性的夢境則有 50%具攻擊性,瑞士男性則有 29% ,荷蘭男性則有 32% 。請問我們根據這樣的統計數據如何解讀夢境的意義?(4%) **夢境內容與個人經驗有關,也就是夢境內容比較不是生物性的,因美國、荷蘭、瑞士均屬高加索人,但文化上荷蘭與瑞士比較接近,與美國較遠。** 100上期中考 - 試題 : 1. 人工智慧的哲學問題為何? **是否能設計出具有人類完整智慧功能的電腦,進一步來說,人類是否只是一部機器?** :::warning 2. 就電腦設計的角度而言,唯物論者所能提出的最直接且最有力的證據為何? **具備人類高等心識活動的電腦** ::: 3. 舉出我們對哪三種高層次的心靈活動仍了解不多? **自我意識、自由意志、宗教活動** 4. 在哲學上,宗教體驗有三種可能的原因。請問這3個可能性? **** 5. 簡述佛洛伊德理論中本我與自我的功能; **本我:潛意識。趨力為滿足各種欲望** **自我:意識。調和本我跟超我** 超我可呼應到榮格理論中的何種原型? **個人潛意識** 6. 就科學方法而言,化約主義強調什麼,這樣的方法論會有何缺陷? ****所有的自然現象必須由更細部的現象來解釋,容易造成科學家只注重細部的問題而忽略整體架構**** 7. 佛洛伊德將人的心識結構分為哪三個層次(非本我、自我、超我)? **意識、前意識(下意識)、潛意識** 榮格又將人的心識結構分為哪三個層次? **意識、個人潛意識、集體潛意識** 8. 哺乳類動物與爬蟲類動物在睡眠型態上最大的差異為何?哺乳類動物在進入 不同於爬蟲類的睡眠型態時,下六生理活動有何改變? (a)四肢肌肉;(b)大腦血流;(c)大腦活動 **** 9. 海馬迴遭切除的人,是否會有下列的心智障礙? (a)無法認得剛結識的朋友 (b)無法認得長久以來的鄰居 (c)無法複誦他人幾秒鐘前才告知的電話 (d)無法學習新的球類運動 (e)容易迷路 (f)無法形成恐懼制約 **A, C, D, E** 10. 下列的心智功能是由左腦還是右腦負責? (a)邏輯分析 (b)注意事物的整體 (c)注意事物的細節 (d)產生憂鬱的情緒 (e)產生樂觀的情緒 (f)辨識親人 **左腦:邏輯分析、注意事物的細節、產生樂觀的情緒** **右腦:注意事務的整體、產生憂鬱的情緒、辨識親人** * 左腦:分析、邏輯計算、理性、樂觀、處理細節 * 右腦:愛做夢、憑感覺、情緒化、恐懼哀傷、空間感、辨識熟悉的臉、看整體 11. 以現代腦神經科學的知識來說,佛洛伊德理論中的「本我」與「自我」由大腦的哪個 部位負責? ****「本我」由邊緣系統負責;「自我」由前額葉負責。**** 12. 簡述下列部位受損的病人,在以視覺為CS的制約反應學習上會有何種障礙? (conditioned stimulus制約刺激) (a)視覺皮質 (b)海馬迴 (c)杏仁核 105上期中考 - 1. 請問Turing Test主要想測試甚麼問題?(5%)Turing Test如何進行?(5%) ****驗證電腦是否具備人的智慧能力;讓人和電腦進行對話。**** 2. 葛詹尼加教授認為,「自由意志」是一種幻覺。這樣的哲學觀點有哪兩項最重要的哲學基礎?(10%) **唯物論、決定論** 3. 為何我們不能武斷的認定當今科學知識不能解釋的現象就一定不可能存在?(10%) ****因為若我們要論斷某個現象不可能發生,我們必須確定我們已經了解宇宙中所有的作用力。但因為我們現今的科學知識有侷限性,所以當一個現象無法由科學理論與知識加以解釋,甚至與現今理論相違背時,並不能說這個現象不可能存在。**** 4. 榮格認為我們集體潛意識中有哪兩個基本成分?(6%) **本能、原型** 再者,請問哪一種可以由生物演化的角度解釋其形成的原因?(3%) **本能** 5. 我們為何會認為REM睡眠模式對胎生哺乳類動物極其重要?(10%) **記憶與學習** 6. 哈佛大學精神病學研究教授史提高特研究失憶症患者的夢境發現,這些失憶症患者的夢境中會出現白天玩俄羅斯方塊的影像,雖然他們根本不記得白天曾經玩過俄羅斯方塊。這個研究結果證實了甚麼理論?(6%) ***精神分析學派的「夢境是了解我們潛意識記憶的窗口」*** 7. 「神經達爾文主義」和傳統達爾文主義最大的差別是甚麼?(5%) 8. 請問下列哪些組織是屬於邊緣系統?(14%) a.中腦 b.扣帶迴 c.小腦 d.網狀活化系統 e.海馬迴 f.前額葉 g.下視丘 ****邊緣系統包含:海馬迴、杏仁核、扣帶迴、視丘、下視丘、腦下垂體...**** * 網狀活化系統:腦幹腹側中心部分神經細胞和神經纖維相混雜的結構。 * 腦幹包含:中腦、橋腦、延腦 * 中腦為腦幹最上一部分,包含網狀活化系統。 > [color=#F9A7B0]腦皮質有分:古皮質、舊皮質、新皮質 > 邊緣系統由古皮質、舊皮質組成,負責情緒反應 > 新皮質包含:額葉、頂葉、枕葉、顳葉 9. 請問何謂新近記憶?(5%)人類的新近記憶儲存在哪裡?(3%) ****三年內的事物;海馬迴。**** 10. 人類的frontal pole cortex包括哪兩個部分,這兩個部分又各自負責哪些功能?(10%) 再者,哪些部分是人類獨有的?(2%) ****ventromedial prefrontal cortex ( vmPFC ) 以及the lateral frontopolar cortex ( IFPC );vmPFC負責情緒調控,IFPC則負責高等心智功能(如邏輯思考、規劃...);IFPC是人類獨有的。**** > 推測這裡說的frontal pole cortex是前額葉皮質( [PFC](https://zh.wikipedia.org/wiki/前額葉皮質) ) 11. 佛洛伊德所提出的「本我」與「自我」大部分是由大腦的哪個部份負責?(6%) ****「本我」由邊緣系統負責;「自我」由前額葉負責。**** 12. 我們在課堂上曾經播放電影「美麗境界」的片段。請問我們主要利用該片段闡述何種科學研究上的方法已檢視觀察結果的正確性?(5%) ******** 13. 我們在課堂上曾播放「雙狹縫實驗的模擬動畫」,請問當發射器一次只發射一粒電子時,雙狹縫隔板另一側的感測器上是否會出現波的繞射圖案?(2%) 再者,在實驗的最後過程,實驗設計上加裝了何種設備導致電子的行為發生了讓人匪夷所思的改變?(3%) ****會;在雙狹縫旁加裝觀測儀,導致最後感測器得到的結果只有兩條紋,而不是原本的繞射圖案。****