language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
185
1.609375
2
[]
no_license
package boot.system.service; import boot.system.model.SysDict; import java.util.List; /** * 字典 服务类 */ public interface ISysDictService { List<SysDict> selectAll(); }
Markdown
UTF-8
5,637
2.96875
3
[ "MIT", "Apache-2.0" ]
permissive
--- layout: post title: "第29天 - 韧性、疗愈和内在自由 | 我是谁(对觉知的正念)" subtitle: "作者:杰克·康菲尔德、塔拉·布拉赫 来自:壹心理与睿心" date: 2019-01-26 00:00:00 author: "于磊" header-img: "img/mindful/29_bg.jpg" catalog: true tags: - 正念冥想 - 壹心理 - 心理学 --- 一个重要的哲学和精神问题是:我到底是谁? 我们经常会认为自己是有独立的渴望和恐惧,成功和失败的小我所组成的 当被问及我们到底是谁? 一位著名的冥想大师拿出一张白纸,他在纸上画了一个很小的 V 形,然后问他的学生他画的是什么? 大多数人回答,他画的是一只正在飞行的小鸟 他说:并不是的,我画的是一片天空,有一只小鸟在天空中飞过 **你关注自己和生活的什么,就决定了你会体验到什么** 聚焦于鸟就如同把注意力放在心里最显眼的部分,想法、感觉、情感 转而看向天空就如同对抱持所有这些体验的整个的背景开放 正念练习中,最大的背景就是指觉知的海洋 在清醒的开放中,你察觉到一切正在发生 觉知的海洋总是在当下 我想邀请你做一个小实验 在接下来的十秒钟里,试着不要保持觉知,好吗? 现在开始 你可以不在觉知中吗? 自然的,你做不到 相反,你可能已经觉察到,你正在看到,或者听到,想到或者感受到的什么 或许某些时刻里,你也觉察到你处于觉知的状态 觉知总是在这里,只是我们不能总是意识到它的存在 到现在为止,我们的正念练习主要关注于觉知的对象,例如:呼吸、身体、感受、声音、念头 现在,我们可以拓展我们的训练,探索觉知本身将正念转向无形的体验中 当我们照镜子时,我们可以看到随着岁月变化的脸和身体 这就是前景中的那只鸟,但是其实还有更多 你可能会问自己,什么东西是你每次看都始终如一的呢? 也许当你思考这个问题的时候,你可以感觉到在整个大背景中那种不变的,当下的临在一直在那里 那是不随时间而改变的意识或者觉知 当你能够正念觉知到这临在,这正透过你的眼睛看着世界的觉知,听着这些话的觉知 你便唤醒了更深远的存在感 你发现了这自然而然的开放、觉醒、温柔的当下 **认识觉知的本质就是意识到我们是谁** 当我们将注意力转换到身体、感觉和念头背后的广阔的觉知,我们正在经历禅宗大师所说的:向后一步进入觉知的永恒的避难所,这就是超越这不断变化的形式,这短暂人生之后我们真实的模样 迈入这个避难所,可以帮助我们记住我们最重要的东西,它是一个归宿,可以给我们平静、智慧和一颗开放的心去面对不可避免的变化和丧失 有时不太可能直接转向觉知,假如你心神不宁那么最好回到之前的练习方法,首先是将意念收回,在正念呼吸和感受身体中放松,当你的身心保持在一个相对自在的状态时,你可以再来探索对觉知保持正念 向后迈一步,让自己一点点接近觉知,单纯的对这里的一切保持好奇和接纳 假如你发现自己在想正在发生的事情,带着趣味和自在让它离开 单纯的再次向一直在这里的当下去开放 当你转向觉知时,你会发现觉知没有任何形状可以让你去碰触 然而这神秘的,一直在当下的觉知就在这里 假如你对这个练习有些困惑或者感到有压力,把它放下重新开始你的核心练习 之后,当你觉得需要时,你可以再来探索这项练习 现在,让我们一起来探索 请舒适的坐下 让自己保持警醒与放松 你可以先做几个深呼吸 吸气,让空气填满你的胸与肺 慢慢的呼气,释放你身体和心里的紧张 花点时间安定下来 随着吸气和呼气,放松下来 对所有的感觉保持开放,聆听各种声音,让声音洗礼你的全身 聆听并感受你身体的感觉,看看你能对这声音与感觉的河流有多少开放 **放松、开放、聆听,感受每时每刻** 你能感觉到这意识前景中一直在变化着的河流吗? 同时,还有整个背景中的警醒以及觉知内在一切的平静吗? 认识到觉知就在这里是怎样的感觉呢? 你能感觉到觉知的空间吗? 那包容正在发生的一切的广阔和开放 再一次让你的感官完全的打开和清醒 去听这些声音,近的声音、远的声音 不仅用你的耳朵听,而且是用你全部的觉知 允许声音洗礼你的全身 你能感觉到背景里正在安静聆听的觉知吗? 注意那开放的、静默的觉知 内在就有一份觉醒 每时每刻里,每一个当下它都知晓发生的一切 自然而然的识别和知道这就是声音 继续让你的感知保持开放和清醒 允许声音的交织洗礼你的全身 感觉到前景中的声音 它带来的感受和情感 这些感官、知觉所交织奏响的乐章而在背景里则是那份觉醒开放的觉知 回到放松的状态和觉知在一起 你能感觉到你在这个世界的经历继续影响着你 但是它并没有以任何方式困住或者限定觉知的那份内在、广阔或觉醒 你就是鸟儿飞翔的那片天空,自然、柔和、开放、觉醒 把这个当做你真正的家 再次的放松 在你觉知的光芒与纯净中放松 叮......
C#
UTF-8
5,652
3.734375
4
[]
no_license
using System; namespace Assets.Scripts.AStar { public class Heap<T> where T : IHeapItem<T> { private readonly T[] _items; public int Count { get; private set; } /// <summary> /// Heap Constructor /// </summary> /// <param name="capacity"></param> public Heap(int capacity) { _items = new T[capacity]; } /// <summary> /// Add item to Heap /// </summary> /// <param name="item"></param> public void Add(T item) { // Add item to top off Heap item.HeapIndex = Count; _items[Count] = item; // Sort the item to ne in correct place SortUp(item); // Increment total count Count++; } /// <summary> /// Removes the first item from Heap and then re-sorts Heap /// </summary> /// <returns></returns> public T RemoveFirst() { // Get the first item var firstItem = _items[0]; // Decrement total count Count--; // Put item at end of Heap to the first item _items[0] = _items[Count]; _items[0].HeapIndex = 0; // Sort item at begining back to its correct position SortDown(_items[0]); // Return the first node back return firstItem; } /// <summary> /// Updates 'item' in the Heap /// </summary> /// <param name="item"></param> public void UpdateItem(T item) { SortUp(item); } /// <summary> /// Checks if Heap contains 'item' /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(T item) { return Equals(_items[item.HeapIndex], item); } /// <summary> /// Sort current item value down to correct position /// </summary> /// <param name="item"></param> private void SortDown(T item) { while (true) { var childIndexLeft = FindLeftChildIndex(item.HeapIndex); var childIndexRight = FindRightChildIndex(item.HeapIndex); // Check if left child index is within Heap Count if (childIndexLeft < Count) { // Current swap index is left child var swapIndex = childIndexLeft; // Check if right child index is within Heap Count if (childIndexRight < Count) { // Check if right child value is less than left child value if (_items[childIndexLeft].CompareTo(_items[childIndexRight]) < 0) // Current swap index is right child swapIndex = childIndexRight; } // Check if swap index value is less than current value; if so swap if (item.CompareTo(_items[swapIndex]) < 0) Swap(item, _items[swapIndex]); else return; } else return; } } /// <summary> /// Sort current item value up to correct position /// </summary> /// <param name="item"></param> private void SortUp(T item) { var parentIndex = FindParentIndex(item.HeapIndex); while (true) { // If current item greater than parent item, swap values if (item.CompareTo(_items[parentIndex]) > 0) Swap(item, _items[parentIndex]); else break; // if swapped change parent index parentIndex = FindParentIndex(item.HeapIndex); } } /// <summary> /// Finds the parent item index of 'heapIndex' /// </summary> /// <param name="heapIndex"></param> /// <returns></returns> private static int FindParentIndex(int heapIndex) { return (heapIndex - 1) / 2; } /// <summary> /// Find the left child index of 'heapIndex' /// </summary> /// <param name="heapIndex"></param> /// <returns></returns> private static int FindLeftChildIndex(int heapIndex) { return heapIndex * 2 + 1; } /// <summary> /// Find the right child index of 'heapIndex' /// </summary> /// <param name="heapIndex"></param> /// <returns></returns> private static int FindRightChildIndex(int heapIndex) { return heapIndex * 2 + 2; } /// <summary> /// Swaps the indexes of the supplied items /// </summary> /// <param name="itemA"></param> /// <param name="itemB"></param> private void Swap(T itemA, T itemB) { // Set itemA index to value of itemB and vis versa _items[itemA.HeapIndex] = itemB; _items[itemB.HeapIndex] = itemA; // Store current itemA index var itemAIndex = itemA.HeapIndex; // swap item indexes itemA.HeapIndex = itemB.HeapIndex; itemB.HeapIndex = itemAIndex; } } public interface IHeapItem<T> : IComparable<T> { int HeapIndex { get; set; } } }
TypeScript
UTF-8
419
2.875
3
[]
no_license
export interface IVideo { id?: number; title?: string; description?: string; category?: string; link?: string; avgRating?: number; } export class Video implements IVideo { constructor( public id?: number, public title?: string, public description?: string, public category?: string, public link?: string, public avgRating?: number ) {} }
Python
UTF-8
1,646
2.625
3
[]
no_license
import sqlite3 conn = sqlite3.connect('nwt.sqlite') c = conn.cursor() c.execute('CREATE TABLE langs (id VARCHAR PRIMARY KEY, engname, selfname, bibleurl)') for line in filter(lambda l: len(l) > 0, file('good.txt').read().split('\n')): p = line.split(',') c.execute('INSERT INTO langs VALUES (?, ?, ?, ?)', ( p[2], p[0], p[1], p[3] )) conn.commit() c.execute('CREATE TABLE books (code VARCHAR PRIMARY KEY, no INTEGER)') c.execute('CREATE INDEX no ON books (no)') c.execute('CREATE TABLE booknames (lang, book, name)') c.execute('CREATE INDEX book__lang ON booknames (book, lang)') c.execute('CREATE TABLE chapters (book, chapter, versecount)') c.execute('CREATE INDEX book__chapter ON chapters (book, chapter)') bookNo = 1 for line in filter(lambda l: len(l) > 0, file('../books.ini').read().split('\n')): if line[0] == '[': curbook = line[1:-1] c.execute('INSERT INTO books VALUES (?, ?)', (curbook, bookNo)) bookNo += 1 elif line[0:7] == 'verses=': import itertools versecounts = line[7:].split(';') for chapNo, versecount in itertools.izip(itertools.count(1), versecounts): c.execute('INSERT INTO chapters VALUES (?, ?, ?)', ( chapNo, curbook, versecount )) conn.commit() import glob, os for chapfile in glob.glob('chaps/*'): langcode = os.path.basename(chapfile) for line in filter(lambda l: len(l)>0, file(chapfile).read().split('\n')): c.execute('INSERT INTO booknames VALUES (?, ?, ?)', ( line.split('=')[0], langcode, line.split('=')[1] )) conn.commit()
Shell
UTF-8
1,050
3.046875
3
[ "MIT" ]
permissive
#!/bin/bash echo "Installing Speedtest-mod and required dependencies" command -v pihole >/dev/null 2>&1 || { whiptail --title "Install Failed" --msgbox "No pihole install found. Aborting install" 8 78 >&2; exit;} if php -v | grep 'PHP 7' > /dev/null ; then sudo apt install php7.3-sqlite -y else sudo apt install php5-sqlite -y fi sudo apt install python3-pip -y &> /dev/null cd /tmp wget https://install.speedtest.net/app/cli/ookla-speedtest-1.0.0-armhf-linux.tgz tar -xvzf ookla-speedtest-1.0.0-armhf-linux.tgz sudo mv speedtest /usr/bin/speedtest sudo apt install sqlite3 -y &> /dev/null sudo apt install -y jq &> /dev/null cd /var/www/html sudo mv admin pihole_admin sudo git clone https://github.com/TooManyEggrolls/AdminLTE admin cd admin if [ ! -f /etc/pihole/speedtest.db ]; then #Create new DB in /etc/pihole/ sudo cp scripts/pi-hole/speedtest/speedtest.db /etc/pihole/ fi cd /opt/pihole/ sudo mv webpage.sh webpage.sh.org sudo wget https://github.com/TooManyEggrolls/pi-hole/raw/master/advanced/Scripts/webpage.sh
Python
UTF-8
258
3.640625
4
[]
no_license
import turtle turtle.fillcolor("black") turtle.begin_fill() turtle.forward(50) turtle.right(90) turtle.forward(50) turtle.right(45) turtle.forward(50) turtle.right(90) turtle.forward(50) turtle.right(45) turtle.forward(50) turtle.end_fill() turtle.mainloop()
C
UTF-8
1,241
3.421875
3
[]
no_license
/** * A simple implementation of arpa/inet functions. * * @file endian.c * @date 13 juin 2014 * @copyright PAWM International * * @author Mickael Germain * */ #include "endian.h" void* endian_copyToB16(void* dest, const void* src, const size_t n) { void* ret; uint16_t* cur; size_t i; cur = (uint16_t*) dest; ret = memcpy(dest, src, n); for (i = 0 ; i < n / sizeof(uint16_t) ; i++) { cur[i] = endian_htons(cur[i]); } return ret; } void* endian_copyToB32(void* dest, const void* src, size_t n) { void* ret; uint32_t* cur; size_t i; cur = (uint32_t*) dest; ret = memcpy(dest, src, n); for (i = 0 ; i < n / sizeof(uint32_t) ; i++) { cur[i] = endian_htonl(cur[i]); } return ret; } void* endian_copyToB(void* dest, const void* src, const size_t n, const size_t size) { void* ret; switch (size) { case sizeof(uint32_t) : ret = endian_copyToB32(dest, src, n); break; case sizeof(uint16_t) : ret = endian_copyToB16(dest, src, n); break; case sizeof(uint8_t) : default : ret = memcpy(dest, src, n); break; } return ret; }
Java
UTF-8
323
2.03125
2
[]
no_license
package missionaries_cannibal_problem; public class App { public static void main(String[] args) { State startState=new State(Constants.NUM_MISSIONARIES,Constants.NUM_CANNIBALS,Constants.FIRST_BANK); StateSpace stateSpace=new StateSpace(startState); stateSpace.generateStates(); stateSpace.writeAllPaths(); } }
Java
UTF-8
5,928
1.820313
2
[ "MIT" ]
permissive
// Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package com.microsoft.aad.adal; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.microsoft.identity.common.adal.internal.net.HttpWebResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(AndroidJUnit4.class) public class WebFingerMetadataRequestorTests extends AndroidTestHelper { private static final String RESPONSE = "{\n" + " \"subject\": \"https://fs.lindft6.com\",\n" + " \"links\": [\n" + " {\n" + " \"rel\": \"http://schemas.microsoft.com/rel/trusted-realm\",\n" + " \"href\": \"https://fs.lindft6.com\"\n" + " }\n" + " ]\n" + "}"; private static final String DOMAIN = "https://fs.lindft6.com"; private static final DRSMetadata DRS_METADATA = new DRSMetadata(); static { IdentityProviderService identityProviderService = new IdentityProviderService(); identityProviderService.setPassiveAuthEndpoint(DOMAIN + "/adfs/ls"); DRS_METADATA.setIdentityProviderService(identityProviderService); } @Test public void testRequestMetadata() throws IOException, AuthenticationException { final HttpURLConnection mockedConnection = Mockito.mock(HttpURLConnection.class); Util.prepareMockedUrlConnection(mockedConnection); Mockito.when(mockedConnection.getInputStream()).thenReturn(Util.createInputStream(RESPONSE)); Mockito.when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); WebFingerMetadataRequestor requestor = new WebFingerMetadataRequestor(); WebFingerMetadataRequestParameters parameters = new WebFingerMetadataRequestParameters( new URL(DOMAIN), DRS_METADATA ); WebFingerMetadata metadata = requestor.requestMetadata(parameters); assertEquals("https://fs.lindft6.com", metadata.getSubject()); assertNotNull(metadata.getLinks()); assertEquals(1, metadata.getLinks().size()); assertEquals( "http://schemas.microsoft.com/rel/trusted-realm", metadata.getLinks().get(0).getRel() ); assertEquals( "https://fs.lindft6.com", metadata.getLinks().get(0).getHref() ); } @Test public void testRequestMetadataThrows() throws IOException, AuthenticationException { final HttpURLConnection mockedConnection = Mockito.mock(HttpURLConnection.class); Util.prepareMockedUrlConnection(mockedConnection); Mockito.when(mockedConnection.getInputStream()).thenReturn(Util.createInputStream(RESPONSE)); Mockito.when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_REQUEST); WebFingerMetadataRequestor requestor = new WebFingerMetadataRequestor(); WebFingerMetadataRequestParameters parameters = new WebFingerMetadataRequestParameters( new URL(DOMAIN), DRS_METADATA ); try { WebFingerMetadata metadata = requestor.requestMetadata(parameters); } catch (AuthenticationException e) { // should throw return; } } @Test public void testParseMetadata() throws AuthenticationException { HttpWebResponse mockWebResponse = Mockito.mock(HttpWebResponse.class); Mockito.when(mockWebResponse.getBody()).thenReturn(RESPONSE); WebFingerMetadata metadata = new WebFingerMetadataRequestor().parseMetadata(mockWebResponse); assertEquals("https://fs.lindft6.com", metadata.getSubject()); assertNotNull(metadata.getLinks()); assertEquals(1, metadata.getLinks().size()); assertEquals( "http://schemas.microsoft.com/rel/trusted-realm", metadata.getLinks().get(0).getRel() ); assertEquals( "https://fs.lindft6.com", metadata.getLinks().get(0).getHref() ); } @Test public void testBuildWebFingerUrl() throws MalformedURLException { final URL expected = new URL("https://fs.lindft6.com/.well-known/webfinger?resource=https://fs.lindft6.com"); final URL wfURL = WebFingerMetadataRequestor.buildWebFingerUrl(new URL(DOMAIN), DRS_METADATA); assertEquals(expected, wfURL); } }
TypeScript
UTF-8
1,385
3.28125
3
[ "MIT" ]
permissive
import { User } from "./User"; export class Directory { users: User[] = []; public constructor() { // Creation of some users this.createUser(0).name = 'Administrateur'; this.createUser(123).name = 'Étudiant testeur'; this.createUser(1424134).name = 'Erwan'; } public searchById(userId: number): User { // 1. Prepare result let foundUser: User = null; // 2. Check all existing users with the given identifier for (let index = 0; index < this.users.length; index++) { const currentUser: User = this.users[index]; if (currentUser.id === userId) { foundUser = currentUser; break; // Optional command, to stop the search early } } // 3. Return reference of the found user return foundUser; } public createUser(userId: number): User { // 1. Check if user exist const existingUser = this.searchById(userId); if (existingUser !== null) { return existingUser; } // 2. Create the new user const newUser: User = new User(); newUser.id = userId; newUser.name = 'No name yet!'; // 3. Add the new user to the directory this.users.push(newUser); // 4. Return the reference of the new user return newUser; } }
Python
UTF-8
6,624
3.46875
3
[]
no_license
import numpy as np import point import triangle import csv ''' A class to build the mesh ''' class PolygonBuilder: x_max = 0 y_max = 0 z_max = 0 points = [[], [], [], []] colours = [[], [], [], []] colour_weights = [] shape_weights = [] triangles = [] def check_max(self, p: point.Point): ''' Check if the ma values have been exceeded and if they have chnage them :param p: a new point ''' if abs(float(p.get_x())) > self.x_max: self.x_max = abs(float(p.get_x())) if abs(float(p.get_y())) > self.y_max: self.y_max = abs(float(p.get_y())) if abs(float(p.get_z())) > self.z_max: self.z_max = abs(float(p.get_z())) def find_max(self): ''' A method to find the max x, y and z values ''' for each in self.triangles: self.check_max(each.get_point1()) self.check_max(each.get_point2()) self.check_max(each.get_point3()) def get_shapes(self): ''' Read in shape file and offsets ''' files = ['sh_000.csv', 'sh_001.csv', 'sh_002.csv', 'sh_003.csv'] for i in range(0, len(files)): with open(files[i], newline='') as csv_file: shape_reader = csv.reader(csv_file) for row in shape_reader: p = point.Point(row[0], row[1], row[2]) self.points[i].append(p) def get_colours(self): ''' Read in colour file and offsets ''' files = ['tx_000.csv', 'tx_001.csv', 'tx_002.csv', 'tx_003.csv'] for i in range(0, len(files)): with open(files[i], newline='') as csv_file: col_reader = csv.reader(csv_file) for row in col_reader: self.colours[i].append([float(row[0]), float(row[1]), float(row[2])]) def get_shape_weights(self): ''' Read in shape weights ''' with open("sh_ev.csv", newline='') as csv_file: sh_reader = csv.reader(csv_file) for row in sh_reader: self.shape_weights.append(float(row[0])) def get_colour_weights(self): ''' Read in colour weights ''' with open("tx_ev.csv", newline='') as csv_file: tx_reader = csv.reader(csv_file) for row in tx_reader: self.colour_weights.append(float(row[0])) def __init__(self): self.get_shapes() self.get_colours() self.get_shape_weights() self.get_colour_weights() def build_face(self, weight1, weight2, weight3): ''' Read in mesh file and iteratively build triangles according to mesh :param weight1: weight of face 001 :param weight2: weight of face 002 :param weight3: weight of face 003 ''' with open('mesh.csv', newline='') as csv_file: mesh_reader = csv.reader(csv_file) for row in mesh_reader: t = self.create_triangle(row, weight1, weight2, weight3) self.triangles.append(t) self.find_max() def create_triangle(self, row, weight1, weight2, weight3): ''' A method that takes the indices of three points and creates a triangle that averages the points across the three faces using the weights :param row: row from mesh :param weight1: weight of face 001 :param weight2: weight of face 002 :param weight3: weight of face 003 :return:the resultant triangle ''' p1 = self.create_point(int(row[0]) - 1, weight1, weight2, weight3) p2 = self.create_point(int(row[1]) - 1, weight1, weight2, weight3) p3 = self.create_point(int(row[2]) - 1, weight1, weight2, weight3) c1 = self.create_colour(int(row[0]) - 1, weight1, weight2, weight3) c2 = self.create_colour(int(row[1]) - 1, weight1, weight2, weight3) c3 = self.create_colour(int(row[2]) - 1, weight1, weight2, weight3) t = triangle.Triangle(p1, p2, p3) t.set_colors(c1, c2, c3) return t def create_point(self, index, w1, w2, w3): ''' Create a single point that is the average of the three faces and the average face :param index: index of point :param w1: weight of face 001 :param w2: weight of face 002 :param w3: weight of face 003 :return: averaged point ''' x = self.points[0][index].get_x() + (self.points[1][index].get_x() * w1 * self.shape_weights[0]) + \ (self.points[2][index].get_x() * w2 * self.shape_weights[1]) + \ (self.points[3][index].get_x() * w3 * self.shape_weights[2]) y = self.points[0][index].get_y() + (self.points[1][index].get_y() * w1 * self.shape_weights[0]) + \ (self.points[2][index].get_y() * w2 * self.shape_weights[1]) + \ (self.points[3][index].get_y() * w3 * self.shape_weights[2]) z = self.points[0][index].get_z() + (self.points[1][index].get_z() * w1 * self.shape_weights[0]) + \ (self.points[2][index].get_z() * w2 * self.shape_weights[1]) + \ (self.points[3][index].get_z() * w3 * self.shape_weights[2]) return point.Point(x, y, z) def create_colour(self, index, w1, w2, w3): ''' Create a colour for each point that is the average colour for that point across the three faces and the average fae :param index: index of point :param w1: weight of face 001 :param w2: weight of face 002 :param w3: weigh of face 003 :return: list of rgb values ''' r = self.colours[0][index][0] + self.colours[1][index][0] * w1 * self.colour_weights[0] + \ self.colours[2][index][0] * w2 * self.colour_weights[1] + \ self.colours[3][index][0] * w3 * self.colour_weights[2] g = self.colours[0][index][1] + self.colours[1][index][1] * w1 * self.colour_weights[0] + \ self.colours[2][index][1] * w2 * self.colour_weights[1] + \ self.colours[3][index][1] * w3 * self.colour_weights[2] b = self.colours[0][index][2] + self.colours[1][index][2] * w1 * self.colour_weights[0] \ + self.colours[2][index][2] * w2 * self.colour_weights[1] + \ self.colours[3][index][2] * w3 * self.colour_weights[2] return [r, g, b]
Python
UTF-8
27,754
2.765625
3
[]
no_license
from gym_game.envs.world import World #from gym_game.envs.agents import Car, RingBuilding, CircleBuilding, Painting, Pedestrian, Sensors, getEquidistantPoints, TextAgent, CheckPointAgent from gym_game.envs.agents import * from gym_game.envs.geometry import Point, Line from gym_game.envs.graphics import GraphWin import time from tkinter import * import numpy as np import threading import random from math import sqrt human_controller = False dt = 0.1 # time steps in terms of seconds. In other words, 1/dt is the FPS. world_width = 120 # in meters world_height = 120 inner_building_radius = 25 num_lanes = 3 lane_marker_width = 0.5 num_of_lane_markers = 20 lane_width = 5 car_length = 4 car_width = 2 speed_limit = 5 speed_minimum = 1 def speed_state(car): if car.speed < speed_minimum: return 0 elif car.speed > speed_limit: return 2 else: return 1 distance_far = 7 distance_close = 3 def sensor_state_obstacle(sensor): if sensor.dist_obstacle < distance_close: return 0 elif sensor.dist_obstacle > distance_far: return 2 else: return 1 def sensor_state_painting(sensor): if sensor.closest_painting < distance_close: return 0 elif sensor.closest_painting > distance_far: return 2 else: return 1 def distance_state(car, checkpoint, init_dist): dist = car.distanceTo(checkpoint) for i in range(1, 6): if dist <= (init_dist/5)*i: return i return 5 class Carlo: def __init__(self, window_created: bool, win: GraphWin): self.window_created = window_created self.win = win self.w = World(dt, width = world_width, height = world_height, win = self.win, ppm = 6) # The world is 120 meters by 120 meters. ppm is the pixels per meter. # self.intersect_world() self.random_checkpoint_world() self.reward = 0 # Sensors initialization self.range_sensors = 20 # 10 meters self.precision = 10 # sensors' resolution self.s1 = Sensors( Point(self.c1.edge_centers[0][0]*self.ppm, self.c1.edge_centers[0][1]*self.ppm), Point(self.c1.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading), (self.ppm*self.c1.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.c1.heading)), self.range_sensors, "Front_Sensor", self.c1, self.precision) self.s2 = Sensors( Point(self.c1.corners[0].x*self.ppm, self.c1.corners[0].y*self.ppm), Point(self.c1.corners[0].x*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading + np.pi/4), (self.ppm*self.c1.corners[0].y) + self.ppm * self.range_sensors * np.sin(self.c1.heading + np.pi/4)), self.range_sensors, "Diag_Left_Sensor", self.c1, self.precision) self.s3 = Sensors( Point(self.c1.corners[3].x*self.ppm, self.c1.corners[3].y*self.ppm), Point(self.c1.corners[3].x*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading - np.pi/4), (self.ppm*self.c1.corners[3].y) + self.ppm * self.range_sensors * np.sin(self.c1.heading - np.pi/4)), self.range_sensors, "Diag_Right_Sensor", self.c1, self.precision) self.s4 = Sensors( Point(self.c1.edge_centers[1][0]*self.ppm, self.c1.edge_centers[1][1]*self.ppm), Point(self.c1.edge_centers[1][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading + np.pi/2), (self.ppm*self.c1.edge_centers[1][1]) + self.ppm * self.range_sensors * np.sin(self.c1.heading + np.pi/2)), self.range_sensors, "Mid_Left_Sensor", self.c1, self.precision) self.s5 = Sensors( Point(self.c1.edge_centers[3][0]*self.ppm, self.c1.edge_centers[3][1]*self.ppm), Point(self.c1.edge_centers[3][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading - np.pi/2), (self.ppm*self.c1.edge_centers[3][1]) + self.ppm * self.range_sensors * np.sin(self.c1.heading - np.pi/2)), self.range_sensors, "Mid_Right_Sensor", self.c1, self.precision) self.s6 = Sensors( Point(self.c1.edge_centers[0][0]*self.ppm, self.c1.edge_centers[0][1]*self.ppm), Point(self.c1.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading + np.pi/12), (self.ppm*self.c1.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.c1.heading + np.pi/12)), self.range_sensors, "Front_Left_Sensor", self.c1, self.precision) self.s7 = Sensors( Point(self.c1.edge_centers[0][0]*self.ppm, self.c1.edge_centers[0][1]*self.ppm), Point(self.c1.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading + np.pi/6), (self.ppm*self.c1.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.c1.heading + np.pi/6)), self.range_sensors, "Front_Left_Sensor_2", self.c1, self.precision) self.s8 = Sensors( Point(self.c1.edge_centers[0][0]*self.ppm, self.c1.edge_centers[0][1]*self.ppm), Point(self.c1.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading - np.pi/12), (self.ppm*self.c1.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.c1.heading - np.pi/12)), self.range_sensors, "Front_Right_Sensor", self.c1, self.precision) self.s9 = Sensors( Point(self.c1.edge_centers[0][0]*self.ppm, self.c1.edge_centers[0][1]*self.ppm), Point(self.c1.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.c1.heading - np.pi/6), (self.ppm*self.c1.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.c1.heading - np.pi/6)), self.range_sensors, "Front_Right_Sensor_2", self.c1, self.precision) self.s1.collidable = False self.s2.collidable = False self.s3.collidable = False self.s4.collidable = False self.s5.collidable = False self.s6.collidable = False self.s7.collidable = False self.s8.collidable = False self.s9.collidable = False self.w.add(self.s1) self.w.add(self.s2) self.w.add(self.s3) self.w.add(self.s4) self.w.add(self.s5) self.w.add(self.s6) self.w.add(self.s7) self.w.add(self.s8) self.w.add(self.s9) self.listSensors = [self.s1, self.s2, self.s3, self.s4, self.s5, self.s6, self.s7,self.s8, self.s9] self.agent_in_range = [] self.agentBuilding = [] for agent in self.w.static_agents: if(isinstance(agent, RectangleBuilding) or isinstance(agent, CircleBuilding) or isinstance(agent, RingBuilding)): self.agentBuilding.append(agent) # Add Text self.textTest = TextAgent(Point(5*world_width, 5*world_height), "Speed " + str(round(self.c1.speed, 3)) + "\n" \ "Travelled distance " + str(round(self.c1.distance_travelled, 3)) + "\n" \ "Reward " + str(round(self.reward, 3))) self.textTest.collidable = False self.w.add(self.textTest) ''' "Distance Front Sensor " + str(self.s1.dist_obstacle) + "\n" + "Distance Diag Right Sensor " + str(self.s3.dist_obstacle) + "\n" + "Distance Diag Left Sensor " + str(self.s2.dist_obstacle) + "\n" + "Distance Mid Left Sensor " + str(self.s4.dist_obstacle) + "\n" + "Distance Mid Right Sensor " + str(self.s5.dist_obstacle)) ''' # self.w.render(window_created) # This visualizes the world we just constructed. # def observe(self): # #return state # return tuple([self.s1.dist_obstacle, self.s2.dist_obstacle, self.s3.dist_obstacle]) # def action(self, action): # Right positive # if action == 0: # self.c1.set_control(0.5, 0) # elif action == 1: # self.c1.set_control(0, 0) # elif action == 2: # self.c1.set_control(-2, 0) # anchor = Point(world_width/5, world_height/5) # self.info = Text(anchor, str(self.c1.speed)) # self.w.add(self.info) # self.w.render() # This visualizes the world we just constructed. def observe(self): #return state return tuple([sensor_state_obstacle(self.s1), sensor_state_obstacle(self.s2), \ sensor_state_obstacle(self.s3), sensor_state_obstacle(self.s4), \ sensor_state_obstacle(self.s5), sensor_state_obstacle(self.s6),\ sensor_state_obstacle(self.s7), sensor_state_obstacle(self.s8),\ sensor_state_obstacle(self.s9),\ sensor_state_painting(self.s1), sensor_state_painting(self.s2), \ sensor_state_painting(self.s3), sensor_state_painting(self.s4), \ sensor_state_painting(self.s5), sensor_state_painting(self.s6),\ sensor_state_painting(self.s7), sensor_state_painting(self.s8),\ sensor_state_painting(self.s9),\ speed_state(self.c1), \ distance_state(self.c1, self.checkpoint, self.init_dist_to_cp)]) def action(self, action): rotation = 0.3 acceleration = 3 if action == 0: self.c1.set_control(rotation, 0.5) elif action == 1: self.c1.set_control(-rotation, 0.5) elif action == 2: self.c1.set_control(0, acceleration) elif action == 3: self.c1.set_control(0, 0.5) # if action == 0: # self.c1.set_control(rotation, 0.1) # elif action == 1: # self.c1.set_control(rotation, 1) # elif action == 2: # self.c1.set_control(rotation, -1) # elif action == 3: # self.c1.set_control(-rotation, 0.1) # elif action == 4: # self.c1.set_control(-rotation, 1) # elif action == 5: # self.c1.set_control(-rotation, -1) # elif action == 6: # self.c1.set_control(0, 0.1) # elif action == 7: # self.c1.set_control(0, 1) # elif action == 8: # self.c1.set_control(0, -1) self.w.tick() # This ticks the world for one time step (dt second) # Update sensors self.s1.car = self.c1 self.s1.p1 = Point(self.s4.car.edge_centers[0][0]*self.ppm, self.s4.car.edge_centers[0][1]*self.ppm) self.s1.p2 = Point(self.s4.car.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.s4.car.heading), (self.ppm*self.s4.car.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.s4.car.heading)) self.s1.list_points = list(getEquidistantPoints(self.s1.p1, self.s1.p2, self.precision)) # Second sensor self.s2.car = self.c1 self.s2.p1 = Point(self.s2.car.corners[0].x*self.ppm, self.s2.car.corners[0].y*self.ppm) self.s2.p2 = Point(self.s2.car.corners[0].x*self.ppm + self.ppm * self.range_sensors * np.cos(self.s2.car.heading + np.pi/4), (self.ppm*self.s2.car.corners[0].y) + self.ppm * self.range_sensors * np.sin(self.s2.car.heading + np.pi/4)) self.s2.list_points = list(getEquidistantPoints(self.s2.p1, self.s2.p2, self.precision)) # Third sensor self.s3.car = self.c1 self.s3.p1 = Point(self.s3.car.corners[3].x*self.ppm, self.s3.car.corners[3].y*self.ppm) self.s3.p2 = Point(self.s3.car.corners[3].x*self.ppm + self.ppm * self.range_sensors * np.cos(self.s1.car.heading - np.pi/4), (self.ppm*self.s3.car.corners[3].y) + self.ppm * self.range_sensors * np.sin(self.s3.car.heading - np.pi/4)) self.s3.list_points = list(getEquidistantPoints(self.s3.p1, self.s3.p2, self.precision)) # Fourth sensor self.s4.car = self.c1 self.s4.p1 = Point(self.s4.car.edge_centers[1][0]*self.ppm, self.s4.car.edge_centers[1][1]*self.ppm) self.s4.p2 = Point(self.s4.car.edge_centers[1][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.s4.car.heading + np.pi/2), (self.ppm*self.s4.car.edge_centers[1][1]) + self.ppm * self.range_sensors * np.sin(self.s4.car.heading + np.pi/2)) self.s4.list_points = list(getEquidistantPoints(self.s4.p1, self.s4.p2, self.precision)) # Fifth sensor self.s5.car = self.c1 self.s5.p1 = Point(self.s5.car.edge_centers[3][0]*self.ppm, self.s5.car.edge_centers[3][1]*self.ppm) self.s5.p2 = Point(self.s5.car.edge_centers[3][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.s5.car.heading - np.pi/2), (self.ppm*self.s5.car.edge_centers[3][1]) + self.ppm * self.range_sensors * np.sin(self.s5.car.heading - np.pi/2)) self.s5.list_points = list(getEquidistantPoints(self.s5.p1, self.s5.p2, self.precision)) # Sixth sensor self.s6.car = self.c1 self.s6.p1 = Point(self.s6.car.edge_centers[0][0]*self.ppm, self.s6.car.edge_centers[0][1]*self.ppm) self.s6.p2 = Point(self.s6.car.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.s6.car.heading + np.pi/12), (self.ppm*self.s6.car.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.s6.car.heading + np.pi/12)) self.s6.list_points = list(getEquidistantPoints(self.s6.p1, self.s6.p2, self.precision)) # Seventh sensor self.s7.car = self.c1 self.s7.p1 = Point(self.s7.car.edge_centers[0][0]*self.ppm, self.s7.car.edge_centers[0][1]*self.ppm) self.s7.p2 = Point(self.s7.car.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.s7.car.heading + np.pi/6), (self.ppm*self.s7.car.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.s7.car.heading + np.pi/6)) self.s7.list_points = list(getEquidistantPoints(self.s7.p1, self.s7.p2, self.precision)) # Eighth sensor self.s8.car = self.c1 self.s8.p1 = Point(self.s8.car.edge_centers[0][0]*self.ppm, self.s8.car.edge_centers[0][1]*self.ppm) self.s8.p2 = Point(self.s8.car.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.s8.car.heading - np.pi/12), (self.ppm*self.s8.car.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.s8.car.heading - np.pi/12)) self.s8.list_points = list(getEquidistantPoints(self.s8.p1, self.s8.p2, self.precision)) # Ninth sensor self.s9.car = self.c1 self.s9.p1 = Point(self.s9.car.edge_centers[0][0]*self.ppm, self.s9.car.edge_centers[0][1]*self.ppm) self.s9.p2 = Point(self.s9.car.edge_centers[0][0]*self.ppm + self.ppm * self.range_sensors * np.cos(self.s9.car.heading - np.pi/6), (self.ppm*self.s9.car.edge_centers[0][1]) + self.ppm * self.range_sensors * np.sin(self.s9.car.heading - np.pi/6)) self.s9.list_points = list(getEquidistantPoints(self.s9.p1, self.s9.p2, self.precision)) # Update all sensors' lines for sensor in self.listSensors: sensor.obj = [] for i in range(sensor.precision): sensor.obj.append(Line(Point(sensor.list_points[i][0], sensor.list_points[i][1]),Point(sensor.list_points[i+1][0], sensor.list_points[i+1][1]))) self.s1.collidable = False self.s2.collidable = False self.s3.collidable = False self.s4.collidable = False self.s5.collidable = False self.s6.collidable = False self.s7.collidable = False self.s8.collidable = False self.s9.collidable = False # Sensors detection parallelization # threading.Thread(target = self.sensor_detection_obstacle).start() # threading.Thread(target = self.sensor_detection_painting).start() self.sensor_detection_obstacle() self.sensor_detection_painting() self.car_in_checkpoint() # Update Text self.textTest.text = "Speed " + str(round(self.c1.speed, 3)) + "\n" \ + "Travelled distance " + str(round(self.c1.distance_travelled, 3)) + "\n" \ + "Reward " + str(round(self.reward, 3)) + "\n" \ + "Distance Front " + str(self.s1.dist_obstacle) + "\n" \ + "Distance Diag Left " + str(self.s2.dist_obstacle) + "\n" \ + "Distance Diag Right " + str(self.s3.dist_obstacle) + "\n" \ + "Distance Mid Left " + str(self.s4.dist_obstacle) + "\n" \ + "Distance Mid Right " + str(self.s5.dist_obstacle) + "\n" \ + "Distance Front Left " + str(self.s6.dist_obstacle) + "\n" \ + "Distance Front Left 2 " + str(self.s7.dist_obstacle) + "\n" \ + "Distance Front Right " + str(self.s8.dist_obstacle) + "\n" \ + "Distance Front Right 2 " + str(self.s9.dist_obstacle) self.textTest.collidable = False # For evaluation self.c1.distance_travelled += self.c1.speed*dt self.w.render(self.window_created) # time.sleep(0.1) # Let's watch it 4x if self.w.collision_exists(): # We can check if there is any collision at all. pass # print('Collision exists somewhere...') if self.w.car_cross_line(): pass # print("CAR CROSSES LINE") self.agent_in_range = [] for agent in (self.w.static_agents + self.w.dynamic_agents): if not (isinstance(agent, TextAgent) or \ isinstance(agent, CheckPointAgent) or \ isinstance(agent, Sensors) or \ isinstance(agent, RingBuilding) or \ isinstance(agent, CircleBuilding) or \ isinstance(agent, RectangleBuilding) or \ # isinstance(agent, CheckPointAgent) or\ (isinstance(agent, Car) and agent.name == "agent")): if self.c1.distanceTo(agent) < self.range_sensors+1: self.agent_in_range.append(agent) # print(len(self.agent_in_range)) def sensor_detection_obstacle(self): # Sensors detection for sensor in self.listSensors: sensor.dist_obstacle = self.range_sensors for agent in (self.agent_in_range + self.agentBuilding): if not isinstance(agent, Painting): for sensor in self.listSensors: for mRange in range(sensor.precision): if (Line( sensor.obj[mRange].p1/self.ppm, sensor.obj[mRange].p2/self.ppm).intersectsWith(agent.obj)): sensor.dist_obstacle = mRange * (self.range_sensors / sensor.precision) break def sensor_detection_painting(self): for sensor in self.listSensors: sensor.closest_painting = self.range_sensors for agent in self.agent_in_range: if isinstance(agent, Painting): for sensor in self.listSensors: # if(sensor.name == "Mid_Right_Sensor"): # print("FIRST MRS: ", sensor.obj[0].p1/self.ppm, sensor.obj[0].p2/self.ppm) # print("LAST MRS: ", sensor.obj[9].p1/self.ppm, sensor.obj[9].p2/self.ppm) # if(sensor.name == "Mid_Left_Sensor"): # print("FIRST MLS: ", sensor.obj[0].p1/self.ppm, sensor.obj[0].p2/self.ppm) # print("LAST MLS: ", sensor.obj[9].p1/self.ppm, sensor.obj[9].p2/self.ppm) for mRange in range(sensor.precision): if (Line(sensor.obj[mRange].p1/self.ppm, sensor.obj[mRange].p2/self.ppm).intersectsWith(agent.obj)): sensor.closest_painting = mRange * (self.range_sensors / sensor.precision) # print(sensor.name, "detects", agent, "range", mRange) break def car_in_checkpoint(self): if (abs(self.c1.center.x - self.checkpoint.center.x)-10 <= 0) and \ (abs(self.c1.center.y - self.checkpoint.center.y)-10 <= 0): r = (50-10) * sqrt(random.uniform(0, 1)) theta = random.uniform(0, 1) * 2 * np.pi x = world_height/2 + r * np.cos(theta) y = world_width/2 + r * np.sin(theta) self.checkpoint.center.x = x self.checkpoint.center.y = y self.init_dist_to_cp = self.c1.distanceTo(self.checkpoint) def car_outside_map(self): return self.c1.center.x>120 or self.c1.center.y>120 or self.c1.center.y<0 or self.c1.center.x<0 def evaluate(self): reward = 0 if self.w.collision_exists() or self.car_outside_map(): # We can check if there is any collision at all. reward += -10000 else: reward += self.c1.distance_travelled*10 if self.c1.speed < speed_minimum or self.c1.speed > speed_limit: reward += -100 if self.c1.speed > 3: reward += 10 if self.w.car_cross_line(): # car crosses road marking reward -= 1000 reward += -100*distance_state(self.c1, self.checkpoint, self.init_dist_to_cp) self.reward = reward return reward def is_done(self): if self.w.collision_exists() or self.car_outside_map(): self.w.erase_car() # self.carlo.w.visualizer.close() # self.w.visualizer.close() return True # if self.c1.speed == 0: # return True return False def view(self, window_created: bool): self.w.tick() # This ticks the world for one time step (dt second) self.w.render(window_created) if self.w.collision_exists(): self.w.erase_car() # time.sleep(5) # Let's watch it 4x def circular_world(self): # To create a circular road, we will add a CircleBuilding and then a RingBuilding around it self.cb = CircleBuilding(Point(world_width/2, world_height/2), inner_building_radius, 'gray80') self.w.add(self.cb) self.rb = RingBuilding(Point(world_width/2, world_height/2), inner_building_radius + num_lanes * lane_width + (num_lanes - 1) * lane_marker_width, 1+np.sqrt((world_width/2)**2 + (world_height/2)**2), 'gray80') self.w.add(self.rb) # Let's also add some lane markers on the ground. This is just decorative. Because, why not. for lane_no in range(num_lanes - 1): self.lane_markers_radius = inner_building_radius + (lane_no + 1) * lane_width + (lane_no + 0.5) * lane_marker_width self.lane_marker_height = np.sqrt(2*(self.lane_markers_radius**2)*(1-np.cos((2*np.pi)/(2*num_of_lane_markers)))) # approximate the circle with a polygon and then use cosine theorem for theta in np.arange(0, 2*np.pi, 2*np.pi / num_of_lane_markers): self.dx = self.lane_markers_radius * np.cos(theta) self.dy = self.lane_markers_radius * np.sin(theta) self.w.add(Painting(Point(world_width/2 + self.dx, world_height/2 + self.dy), Point(lane_marker_width, self.lane_marker_height), 'white', heading = theta)) # A Car object is a dynamic object -- it can move. We construct it using its center location and heading angle. self.c1 = Car(Point(91.75, 60), np.pi/2) self.c1.max_speed = 30.0 # let's say the maximum is 30 m/s (108 km/h) self.c1.velocity = Point(0, 3.0) self.c1.name = "agent" self.w.add(self.c1) self.ppm = 6 def intersect_world(self): # Intersection map # Top right self.w.add(Painting(Point(81.5, 111.5), Point(97, 27), 'gray80')) # We build a sidewalk. self.w.add(RectangleBuilding(Point(82.5, 112.5), Point(95, 25))) # The RectangleBuilding is then on top of the sidewalk, with some margin. # Let's repeat this for 4 different RectangleBuildings. # Top Left self.w.add(Painting(Point(8.5, 111.5), Point(17, 27), 'gray80')) self.w.add(RectangleBuilding(Point(7.5, 112.5), Point(15, 25))) # Bottom Left self.w.add(Painting(Point(8.5, 41), Point(17, 82), 'gray80')) self.w.add(RectangleBuilding(Point(7.5, 40), Point(15, 80))) # Bottom Right self.w.add(Painting(Point(81.5, 41), Point(97, 82), 'gray80')) self.w.add(RectangleBuilding(Point(82.5, 40), Point(95, 80))) # # Let's also add some zebra crossings. # for i in range(0, 15, 2): # self.w.add(Painting(Point(18+i, 81), Point(0.5, 2), 'white')) self.checkpoint = CheckPointAgent(Point(78, 85), np.pi, color="orange") self.w.add(self.checkpoint) # Let's also add some lane markers on the ground. for i in range (0, 81, 5): self.w.add(Painting(Point(25, i), Point(0.5, 3), 'white')) # self.w.add(Painting(Point(25, 100 + i), Point(0.5, 3), 'white')) self.w.add(Painting(Point(i + 35, 90), Point(3, 0.5), 'white')) # self.w.add(Painting(Point(i - 65, 90), Point(3, 0.5), 'white')) # A Car object is a dynamic object -- it can move. We construct it using its center location and heading angle. self.c1 = Car(Point(30, 35), np.pi/2) self.c1.max_speed = 30.0 # let's say the maximum is 30 m/s (108 km/h) self.c1.velocity = Point(0, 3.0) self.c1.name = "agent" self.w.add(self.c1) self.ppm = 6 self.c2 = Car(Point(118, 94), np.pi, 'blue') self.c2.velocity = Point(3.0, 0) # We can also specify an initial velocity just like this. self.w.add(self.c2) # Pedestrian is almost the same as Car. It is a "circle" object rather than a rectangle. self.p1 = Pedestrian(Point(40, 81), np.pi) self.p1.max_speed = 10.0 # We can specify min_speed and max_speed of a Pedestrian (and of a Car). This is 10 m/s, almost Usain Bolt. self.p1.velocity = Point(-1, 0) self.w.add(self.p1) self.init_dist_to_cp = self.c1.distanceTo(self.checkpoint) # Pedestrian self.p1.velocity = Point(-1, 0) def random_checkpoint_world(self): # Map self.rb = RingBuilding(Point(world_width /2, world_height /2), 50, 1 + np.sqrt((world_width) ** 2 + (world_height) ** 2), 'gray80') # Car self.c1 = Car(Point(world_width/2, world_height/2), np.pi / 2) self.c1.max_speed = 30.0 # let's say the maximum is 30 m/s (108 km/h) self.c1.velocity = Point(0, 3.0) self.c1.name = "agent" self.ppm = 6 # Checkpoint r = 50 * sqrt(random.uniform(0, 1)) theta = random.uniform(0, 1) * 2 * np.pi x = world_height / 2 + r * np.cos(theta) y = world_width / 2 + r * np.sin(theta) self.checkpoint = CheckPointAgent(Point(x, y), 10, color="orange") # self.checkpoint = CheckPointAgent(Point(world_height/2, world_width/2+60), 10, color="orange") self.init_dist_to_cp = self.c1.distanceTo(self.checkpoint) # Add elements to map (order matters for visuals (only for non-movable objects) self.w.add(self.rb) self.w.add(self.checkpoint) self.w.add(self.c1)
Python
UTF-8
1,062
3.328125
3
[]
no_license
from random import randint class TestDataEmptyArray(object): @staticmethod def get_array(): # complete this function return [] class TestDataUniqueValues(object): a = set() for _ in range(10): a.add(randint(0, 100)) @staticmethod def get_array(): # complete this function a = TestDataUniqueValues.a return list(a) @staticmethod def get_expected_result(): # complete this function a = TestDataUniqueValues.get_array() return a.index(min(a)) class TestDataExactlyTwoDifferentMinimums(object): a = set() for _ in range(10): a.add(randint(0, 100)) a = list(a) a.append(min(a)) @staticmethod def get_array(): # complete this function a = TestDataExactlyTwoDifferentMinimums.a return a @staticmethod def get_expected_result(): # complete this function a = TestDataExactlyTwoDifferentMinimums.get_array() return a.index(min(a))
Java
UTF-8
1,967
2.296875
2
[]
no_license
package com.simplilearn.controller; import java.io.IOException; import java.sql.SQLException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.simplilearn.service.AdminService; /** * Servlet implementation class PasswordController */ @WebServlet("/admin/PasswordController") public class PasswordController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public PasswordController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); String msg = null; String password = request.getParameter("password"); System.out.println(password); AdminService ps = new AdminService(); try { msg = ps.passwordFetch(password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } String dest = "/success.jsp"; request.setAttribute("msg", msg); RequestDispatcher dispatcher = request.getRequestDispatcher(dest); dispatcher.forward(request, response); } }
Java
UTF-8
13,563
2.09375
2
[]
no_license
package com.topscorer.testcases; import org.openqa.selenium.By; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import com.topscorer.utilities.PageObjects; public class OfflineOrders extends PageObjects { String strFileName_BuyModal = "./TestData/Buy Modal.xlsx"; String strSheetName_off_line = "Off-line Orders"; @Parameters({ "browserName", "projectURL" }) @BeforeMethod public void setUp(String browserName, String projectURL) throws Exception { seleniumUtil.openBrowser(browserName); seleniumUtil.openURL(projectURL); seleniumUtil.implicitLoadTime(); } @AfterMethod public void postCondition(ITestResult result) throws Exception { if (ITestResult.FAILURE == result.getStatus()) { snapShot(System.getProperty("user.dir")+"\\Screenshots\\OfflineOrdersQA\\",result.getName()); }else { driver.close(); } } @Test public void TC01_To_verify_offline_orders_using_new_registration() throws Exception { SoftAssert softAssert = new SoftAssert(); String strBoard = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 1); String strMedium = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 2); String strGrade = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 3); By tab_bord = By.xpath("//a[@href='#" + strBoard + "']"); By tab_bord_medium = By.xpath("//a[@href='#" + strBoard + "-" + strMedium + "']"); seleniumUtil.mouseHover(tab_bord); seleniumUtil.click(tab_bord); // seleniumUtil.click(tab_bord_medium); By lnk_grade_1 = By.xpath("(//div[starts-with(@id,'cbse-')]/ul/li)[1]"); By btn_continue = By.xpath("//div[starts-with(@id,'cbse-')]//button"); seleniumUtil.click(lnk_grade_1); seleniumUtil.click(btn_continue); seleniumUtil.implicitLoadTime(); Thread.sleep(2000); seleniumUtil.clickByJavaScriptExecutor(standard.btn_buy_standardCombo); seleniumUtil.click(standard.sd_buyModal); seleniumUtil.implicitLoadTime(); seleniumUtil.click(cartPage.btn_Proceed_To_Payment); seleniumUtil.implicitLoadTime(); seleniumUtil.click(checkoutPage.btn_Register); Thread.sleep(2500); String getddlBoardValue = seleniumUtil.getDropdownSelectedValue(register.ddlBoard); String getddlGradeValue = seleniumUtil.getDropdownSelectedValue(register.ddlGrade); softAssert.assertEquals(getddlBoardValue.toLowerCase().contains(strBoard.toLowerCase()), true, "On registration, board is not selected as per MP selection."); softAssert.assertEquals(getddlGradeValue, strGrade, "On registration, grade is not selected as per MP selection."); commonMethods.userRegistration_buy_modal(); Thread.sleep(2500); commonMethods.communication(); Thread.sleep(2500); String strPromoCode = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 4); seleniumUtil.enterText(checkoutPage.txt_promoCode, strPromoCode); seleniumUtil.click(checkoutPage.btn_apply); Thread.sleep(3000); // String strGetPromoCodeMsg = // seleniumUtil.getText(checkoutPage.lbl_pramocode_msg); // String strPromoCodeMsg = excelUtil.getDataFromExcel(strFileName_BuyModal, // strSheetName_online, 1, 5); // // softAssert.assertEquals(strPromoCodeMsg, strGetPromoCodeMsg, // "'Promo code has been successfully applied' message does not matched."); boolean btnOK = seleniumUtil.isElementDisplayed(checkoutPage.btn_ok); if (btnOK == true) { seleniumUtil.click(checkoutPage.btn_ok); } Thread.sleep(3000); seleniumUtil.click(checkoutPage.btn_Proceed_to_Pay_Securely); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.rbtn_Cash_On_Delivery), "Cash on delivery payment option is not appear after clicking on payment securely."); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.rbtn_Online_Payment_through_CCAvenue), "Online Payment through CCAvenue payment option is not appear after clicking on payment securely."); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.rbtn_Cash_On_Delivery); seleniumUtil.click(checkoutPage.btn_Generate_OTP); Thread.sleep(10000); fluentWait(checkoutPage.txt_OTP); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.txt_OTP), "OTP text box is not appear after clicking on Generate OTP."); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.btn_Confirm_Order), "Confirm Orde button is not appear after clicking on Generate OTP."); softAssert.assertAll(); } @Parameters({ "projectURL" }) @Test public void TC02_To_verify_off_line_order_in_existing_user_using_coupons(String projectURL) throws Exception { SoftAssert softAssert = new SoftAssert(); String strUserEmailID = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 6); String strUserPassword = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 7); commonMethods.userLogin(strUserEmailID, strUserPassword); Thread.sleep(3500); commonMethods.emptyCart(projectURL); driver.navigate().refresh(); Thread.sleep(5000); commonMethods.userLoggedOut(); seleniumUtil.openURL(projectURL); String strBoard = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 8); String strMedium = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 9); By tab_bord = By.xpath("//a[@href='#" + strBoard + "']"); By tab_bord_medium = By.xpath("(//a[starts-with(@href,'#gseb')])[3]"); seleniumUtil.mouseHover(tab_bord); Thread.sleep(1000); seleniumUtil.click(tab_bord); seleniumUtil.click(tab_bord_medium); By lnk_grade_1 = By.xpath("(//div[starts-with(@id,'gseb-')][2]/ul/li)[2]"); By btn_continue = By.xpath("(//div[starts-with(@id,'gseb-')]//button)[2]"); seleniumUtil.click(lnk_grade_1); seleniumUtil.click(btn_continue); seleniumUtil.implicitLoadTime(); Thread.sleep(2000); seleniumUtil.clickByJavaScriptExecutor(standard.btn_buy_standardCombo); seleniumUtil.click(standard.usb_buyModal); seleniumUtil.implicitLoadTime(); Thread.sleep(2500); seleniumUtil.doubleClick(cartPage.btn_Proceed_To_Payment); seleniumUtil.implicitLoadTime(); commonMethods.userLogin_at_checkOutPage(strUserEmailID, strUserPassword); Thread.sleep(3500); String strPromoCode = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 10); seleniumUtil.enterText(checkoutPage.txt_promoCode, strPromoCode); seleniumUtil.click(checkoutPage.btn_apply); Thread.sleep(1500); // String strGetPromoCodeMsg = // seleniumUtil.getText(checkoutPage.lbl_pramocode_msg); // String strPromoCodeMsg = excelUtil.getDataFromExcel(strFileName_BuyModal, // strSheetName_online, 1, 11); // // softAssert.assertEquals(strPromoCodeMsg, strGetPromoCodeMsg, // "'Promo code has been successfully applied' message does not matched."); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.btn_Proceed_to_Pay_Securely); Thread.sleep(1500); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.rbtn_Cash_On_Delivery), "Cash on delivery payment option is not appear after clicking on payment securely."); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.rbtn_Online_Payment_through_CCAvenue), "Online Payment through CCAvenue payment option is not appear after clicking on payment securely."); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.rbtn_Online_Payment_through_CCAvenue); Thread.sleep(1500); String strBeforeGetCurrentUrl = driver.getCurrentUrl(); driver.switchTo().frame("paymentFrame"); boolean tabPaymentInfo = seleniumUtil.isElementDisplayed(checkoutPage.tab_paymentinformation); softAssert.assertEquals(tabPaymentInfo, true, "By clicking on Online Payment through CCAvenue, Paymentinformation tab is not open under payment option."); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.tab_netBanking); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.rbtn_SBI); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.btn_MakePayment_netBnk); seleniumUtil.switchToWindow(); seleniumUtil.implicitLoadTime(); Thread.sleep(2500); softAssert.assertNotEquals(strBeforeGetCurrentUrl, driver.getCurrentUrl(), "Page is not redirect from merchant login page."); seleniumUtil.switchToDefaultFrame(); driver.switchTo().defaultContent(); softAssert.assertAll(); } @Test public void TC03_To_verify_offline_order_using_the_new_registration_without_coupns() throws Exception { SoftAssert softAssert = new SoftAssert(); String strBoard = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 12); String strMedium = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 13); By tab_bord = By.xpath("//a[@href='#" + strBoard + "']"); By tab_bord_medium = By.xpath("//a[@href='#" + strBoard + "-" + strMedium + "']"); seleniumUtil.mouseHover(tab_bord); seleniumUtil.click(tab_bord); // seleniumUtil.click(tab_bord_medium); By lnk_grade_1 = By.xpath("(//div[starts-with(@id,'cbse-')]/ul/li)[1]"); By btn_continue = By.xpath("//div[starts-with(@id,'cbse-')]//button"); seleniumUtil.click(lnk_grade_1); seleniumUtil.click(btn_continue); seleniumUtil.implicitLoadTime(); Thread.sleep(2000); seleniumUtil.clickByJavaScriptExecutor(standard.btn_buy_standardCombo); seleniumUtil.click(standard.usb_buyModal); seleniumUtil.implicitLoadTime(); seleniumUtil.click(cartPage.btn_Proceed_To_Payment); seleniumUtil.implicitLoadTime(); seleniumUtil.click(checkoutPage.btn_Register); Thread.sleep(2500); commonMethods.userRegistration_buy_modal(); Thread.sleep(2500); commonMethods.communication(); Thread.sleep(2500); seleniumUtil.click(checkoutPage.btn_Proceed_to_Pay_Securely); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.rbtn_Cash_On_Delivery), "Cash on delivery payment option is not appear after clicking on payment securely."); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.rbtn_Online_Payment_through_CCAvenue), "Online Payment through CCAvenue payment option is not appear after clicking on payment securely."); Thread.sleep(1000); fluentWait(checkoutPage.rbtn_Cash_On_Delivery); seleniumUtil.click(checkoutPage.rbtn_Cash_On_Delivery); Thread.sleep(5000); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.btn_Generate_OTP); Thread.sleep(5000); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.txt_OTP), "OTP text box is not appear after clicking on Generate OTP."); softAssert.assertTrue(seleniumUtil.isElementDisplayed(checkoutPage.btn_Confirm_Order), "Confirm Orde button is not appear after clicking on Generate OTP."); softAssert.assertAll(); } @Parameters({ "projectURL" }) @Test public void TC04_To_verify_offline_orders_using_existing_registration_without_applying_any_coupons( String projectURL) throws Exception { SoftAssert softAssert = new SoftAssert(); String strUserEmailID = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 16); String strUserPassword = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 17); commonMethods.userLogin(strUserEmailID, strUserPassword); Thread.sleep(3500); commonMethods.emptyCart(projectURL); String strBoard = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 18); String strMedium = excelUtil.getDataFromExcel(strFileName_BuyModal, strSheetName_off_line, 1, 19); By tab_bord = By.xpath("//a[@href='#" + strBoard + "']"); By tab_bord_medium = By.xpath("(//a[starts-with(@href,'#gseb')])[3]"); seleniumUtil.mouseHover(tab_bord); Thread.sleep(1000); seleniumUtil.click(tab_bord); seleniumUtil.click(tab_bord_medium); By lnk_grade_1 = By.xpath("(//div[starts-with(@id,'gseb-')][2]/ul/li)[2]"); By btn_continue = By.xpath("(//div[starts-with(@id,'gseb-')]//button)[2]"); seleniumUtil.click(lnk_grade_1); seleniumUtil.click(btn_continue); seleniumUtil.implicitLoadTime(); Thread.sleep(2000); seleniumUtil.clickByJavaScriptExecutor(standard.btn_buy_standardCombo); seleniumUtil.click(standard.sd_buyModal); seleniumUtil.implicitLoadTime(); Thread.sleep(3500); seleniumUtil.click(cartPage.btn_Proceed_To_Payment); seleniumUtil.implicitLoadTime(); Thread.sleep(1500); seleniumUtil.click(checkoutPage.btn_Proceed_to_Pay_Securely); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.rbtn_Online_Payment_through_CCAvenue); Thread.sleep(1500); String strBeforeGetCurrentUrl = driver.getCurrentUrl(); driver.switchTo().frame("paymentFrame"); boolean tabPaymentInfo = seleniumUtil.isElementDisplayed(checkoutPage.tab_paymentinformation); softAssert.assertEquals(tabPaymentInfo, true, "By clicking on Online Payment through CCAvenue, Paymentinformation tab is not open under payment option."); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.tab_netBanking); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.rbtn_SBI); seleniumUtil.clickByJavaScriptExecutor(checkoutPage.btn_MakePayment_netBnk); Thread.sleep(2500); seleniumUtil.switchToWindow(); seleniumUtil.implicitLoadTime(); Thread.sleep(2500); softAssert.assertNotEquals(strBeforeGetCurrentUrl, driver.getCurrentUrl(), "Page is not redirect from merchant login page."); seleniumUtil.switchToDefaultFrame(); softAssert.assertAll(); } }
PHP
UTF-8
1,445
2.765625
3
[ "MIT" ]
permissive
<?php namespace App\Controllers; use App\Models\LogModel; use CodeIgniter\Controller; class Log extends Controller { public function index() { $model = new \App\Models\LogModel(); $model = $model->orderBy('id','desc'); $data = [ 'title' => 'Logs', 'log' => $model->paginate(10), 'pager' => $model->pager ]; $data['log'] = $this->processLogRow($data['log']); $data['log'] = $this->processResponse($data['log']); // echo '<pre>'; var_dump($data); exit; echo view('logs/index', $data); } public function processLogRow($log) { foreach ($log as $key => $value) { // if (isset(\json_decode($value["response"])->created_at)) { // $value["response"] = \json_decode($value["response"])->created_at; // // } else { // $value["response"] = NULL; // } $value["generic_data"] = \json_decode($value["generic_data"], TRUE); $log[$key] = $value; } // \var_dump($value); exit; return $log; } public function processResponse($response) { // echo '<pre>';var_dump($response); exit; foreach ($response as $key => $value) { $users = \json_decode($value['response'], TRUE); // echo '<pre>'. \var_dump($users); if(strlen($value['response'])>10) $value['response'] = processJson($value['response']); $response[$key] = $value; } return $response; } } ?>
JavaScript
UTF-8
3,785
2.65625
3
[ "MIT" ]
permissive
const RetryStrategyInterface = Jymfony.Component.HttpClient.Retry.RetryStrategyInterface; /** * Decides to retry the request when HTTP status codes belong to the given list of codes. * * @memberOf Jymfony.Component.HttpClient.Retry */ export default class GenericRetryStrategy extends implementationOf(RetryStrategyInterface) { /** * @param {Object.<number, string[]|boolean>} statusCodes List of HTTP status codes that trigger a retry * @param {int} delayMs Amount of time to delay (or the initial value when multiplier is used) * @param {float} multiplier Multiplier to apply to the delay each time a retry occurs * @param {int} maxDelayMs Maximum delay to allow (0 means no maximum) */ __construct(statusCodes = __self.DEFAULT_RETRY_STATUS_CODES, delayMs = 1000, multiplier = 2.0, maxDelayMs = 0) { /** * @type {Object<number, string[]|boolean>} * * @private */ this._statusCodes = statusCodes; /** * @type {int[]} * * @private */ this._codes = Object.keys(this._statusCodes).map(Number); if (0 > delayMs) { throw new InvalidArgumentException(__jymfony.sprintf('Delay must be greater than or equal to zero: "%s" given.', delayMs)); } /** * @type {int} * * @private */ this._delayMs = delayMs; if (1 > multiplier) { throw new InvalidArgumentException(__jymfony.sprintf('Multiplier must be greater than or equal to one: "%s" given.', multiplier)); } /** * @type {float} * * @private */ this._multiplier = multiplier; if (0 > maxDelayMs) { throw new InvalidArgumentException(__jymfony.sprintf('Max delay must be greater than or equal to zero: "%s" given.', maxDelayMs)); } /** * @type {int} * * @private */ this._maxDelayMs = maxDelayMs; } /** * @inheritdoc */ shouldRetry(responseInfo, responseContent, exception) { const statusCode = responseInfo.http_code || 0; if (this._codes.includes(statusCode) && isBoolean(this._statusCodes[statusCode])) { return this._statusCodes[statusCode]; } if (isArray(this._statusCodes[statusCode])) { return this._statusCodes[statusCode].includes(responseInfo.http_method); } if (! exception) { return false; } if (this._codes.includes(0) && isBoolean(this._statusCodes[0])) { return this._statusCodes[0]; } if (isArray(this._statusCodes[0])) { return this._statusCodes[0].includes(responseInfo.http_method); } return false; } /** * @inheritdoc */ getDelay(responseInfo) { const delay = this._delayMs * this._multiplier ** responseInfo.retry_count; if (delay > this._maxDelayMs && 0 !== this._maxDelayMs) { return this._maxDelayMs; } return ~~delay; } } Object.defineProperty(GenericRetryStrategy, 'IDEMPOTENT_METHODS', { writable: false, configurable: false, value: [ 'GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS', 'TRACE' ] }); Object.defineProperty(GenericRetryStrategy, 'DEFAULT_RETRY_STATUS_CODES', { writable: false, configurable: false, value: { 0: GenericRetryStrategy.IDEMPOTENT_METHODS, // For transport exceptions 423: true, 425: true, 429: true, 500: GenericRetryStrategy.IDEMPOTENT_METHODS, 502: true, 503: true, 504: GenericRetryStrategy.IDEMPOTENT_METHODS, 507: GenericRetryStrategy.IDEMPOTENT_METHODS, 510: GenericRetryStrategy.IDEMPOTENT_METHODS, }});
Python
UTF-8
556
2.65625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
f = FormattedString() f.fill(1, 0, 0) f.fontSize(100) f += "hello" attr = f.getNSObject() attr.addAttribute_value_range_("com.petr.pageBot.myAttribute", "this is my data", (0, 5)) f += " " f += "world" attr = f.getNSObject() attr.addAttribute_value_range_("com.petr.pageBot.myOtherAttibute", ["a", "list", "object"], (5, 5)) text(f, (96, 172)) print attr f = FormattedString() f += 'ABVCEESFJLK LDKJD LSDK DSLK' attr = f.getNSObject() l = [] attr.addAttribute_value_range_('io.pagebot.aaa', l, (0, 10)) l.append('aaaaaaa') print f.getNSObject()
Java
UTF-8
1,349
2.234375
2
[]
no_license
package com.oocl.parkingsmart.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.Objects; @Entity public class UserShopPromotions { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private Long userId; private Long shopId; private Boolean isActive=true; public UserShopPromotions() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Long getShopId() { return shopId; } public void setShopId(Long shopId) { this.shopId = shopId; } public Boolean getActive() { return isActive; } public void setActive(Boolean active) { isActive = active; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserShopPromotions)) return false; UserShopPromotions that = (UserShopPromotions) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } }
Python
UTF-8
2,994
4.125
4
[]
no_license
''' A trial implementation of Barnsley Fern (https://en.wikipedia.org/wiki/Barnsley_fern) in Python. ''' import sys import random import matplotlib.pyplot as draw # f2 as described in the Wikipage -- it maps any point inside the red triangle leaflet to # a point inside the opposite smaller blue triangle leaflet. It is chosen 84% of the time. def transformation_0(p): x = p[0] y = p[1] x1 = 0.95*x + 0.002*y - 0.002 y1 = -0.002*x + 0.93*y + 0.5 return x1, y1 # f3 as described in the Wikipage -- it maps any point inside the blue triangle leaflet to # a point inside the alternating corresponding triangle across the stem (with flipping). # It is chosen 7% of the time. def transformation_1(p): x = p[0] y = p[1] x1 = 0.035*x - 0.11*y - 0.05 y1 = 0.27*x + 0.01*y + 0.005 return x1, y1 # f4 as described in the Wikipage -- it maps any point inside the blue triangle leaflet to # a point inside the alternating corresponding triangle across the stem (without flipping). # It is chosen 7% of the time. def transformation_2(p): x = p[0] y = p[1] x1 = -0.04*x + 0.11*y + 0.047 y1 = 0.27*x + 0.01*y + 0.06 return x1, y1 # f1 as described in the Wikipage -- it maps any point to another point at the base of the # stem. It is chosen 2% of the time. def transformation_3(p): x = p[0] y = p[1] x1 = 0 y1 = 0.25*y - 0.4 return x1, y1 def get_index(probability): x = random.random() cumulated_prob = 0 sum_probability = [] # We seem to evaluate cumulated_prob and sum_probability every time we call get_index. # Can it be avoided? for p in probability: cumulated_prob += p sum_probability.append(cumulated_prob) for item, sp in enumerate(sum_probability): if x <= sp: return item return len(probability) - 1 def transform(p): transformations = [transformation_0, transformation_1, transformation_2, transformation_3] prob_transformations = [0.84, 0.07, 0.07, 0.02] # Choosing the transformation function as selected by their probabilities. tindex = get_index(prob_transformations) t = transformations[tindex] x, y = t(p) return x, y def draw_fern(n): # The Barnsley Fern starts with (0, 0) x = [0] y = [0] x1, y1 = 0, 0 # The following loop iterates n times and build up the lists of x and y, to be drawn later for i in range(n): x1, y1 = transform((x1, y1)) x.append(x1) y.append(y1) return x, y if __name__ == '__main__': # We wil take the number of points (n) as a command-line argument. At this time the # error handling of n is not implemented. n = int(sys.argv[1]) x, y = draw_fern(n) draw.plot(x, y, '.', color='green') draw.title('Barnsley fern with {0} points'.format(n)) draw.show()
Java
UTF-8
1,253
2.03125
2
[]
no_license
package com.jk.model; public class ZixunBean { private Integer id; private String title; private String content; private String releaseTime; private Integer typeId; private String typeName; private String image; public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getReleaseTime() { return releaseTime; } public void setReleaseTime(String releaseTime) { this.releaseTime = releaseTime; } public Integer getTypeId() { return typeId; } public void setTypeId(Integer typeId) { this.typeId = typeId; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } }
JavaScript
UTF-8
407
3.265625
3
[]
no_license
while (true) { var highestIndex = 0 var highestHeight = 0 for (let i = 0; i < 8; i++) { const mountainH = parseInt(readline()); // represents the height of one mountain. if (mountainH > highestHeight) { highestHeight = mountainH highestIndex = i } } console.log(highestIndex); // The index of the mountain to fire on. }
Java
UTF-8
384
2.0625
2
[]
no_license
package com.leslie.springcloud_demo.entities; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class CommonResult<T> { private Integer code; private String message; private T object; public CommonResult(Integer code,String message){ this(code,message,null); } }
Java
UTF-8
2,790
1.820313
2
[]
no_license
package group.cc.occ.dao; import group.cc.core.Mapper; import group.cc.occ.model.UserWorkArrange; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.List; public interface UserWorkArrangeMapper extends Mapper<UserWorkArrange> { @Select("SELECT * FROM USER_WORK_ARRANGE WHERE ${key} like #{value}") public List<UserWorkArrange> listByKey(@Param("key")String key, @Param("value")String value); @Delete("DELETE FROM USER_WORK_ARRANGE WHERE ID in(${ids})") public void deleteBatch(@Param("ids")String ids); @Select("SELECT USERID FROM USER_WORK_ARRANGE WHERE WORKARRANGEID = #{workId}") public List<Integer> getWorkUser(@Param("workId") Integer workId); @Select("SELECT * FROM USER_WORK_ARRANGE WHERE WORKARRANGEID like #{workId}") public List<UserWorkArrange> findByWorkId(@Param("workId") Integer workId); @Update("UPDATE USER_WORK_ARRANGE SET ISCOMPLETE = '是' WHERE USERID = #{userId} AND WORKARRANGEID = #{workId} ") public void finish(@Param("workId")Integer workId, @Param("userId")Integer userId); @Update("UPDATE USER_WORK_ARRANGE SET ISCOMPLETE = '是', COMPLETEYEAR = #{completeYear} WHERE USERID = #{userId} AND WORKARRANGEID = #{workId} ") public void finishAndContinue(@Param("workId")Integer workId, @Param("userId")Integer userId, @Param("completeYear")String year); @Select("SELECT * FROM USER_WORK_ARRANGE WHERE USERID = #{userId} AND WORKARRANGEID = #{workId} ") public UserWorkArrange findByUserIdAndWorkId(@Param("workId")Integer workId, @Param("userId")Integer userId); @Select("SELECT\n" + "\t(\n" + "\t\t(\n" + "\t\t\tSELECT\n" + "\t\t\t\tCOUNT(*)\n" + "\t\t\tFROM\n" + "\t\t\t\tuser_work_arrange\n" + "\t\t\tWHERE\n" + "\t\t\t\tworkarrangeid = #{workId}\n" + "\t\t\tAND isComplete = '是'\n" + "\t\t) - (\n" + "\t\t\tSELECT\n" + "\t\t\t\tCOUNT(*)\n" + "\t\t\tFROM\n" + "\t\t\t\tuser_work_arrange\n" + "\t\t\tWHERE\n" + "\t\t\t\tworkarrangeid = #{workId}\n" + "\t\t)\n" + "\t)") public Integer getSubNum(@Param("workId")Integer workId); @Select("SELECT ID FROM USER_WORK_ARRANGE WHERE WORKARRANGEID = #{workId}") public List<Integer> getWorkUserIdByWorkId(@Param("workId") Integer workId); @Update("UPDATE USER_WORK_ARRANGE SET ISREPEAT = #{isRepeat} WHERE ID = #{id}") public void updateState(@Param("id")Integer id, @Param("isRepeat")String isRepeat); }
Java
UTF-8
669
3.890625
4
[]
no_license
class Node{ int data; Node next; Node(int data){this.data=data;} } class Stack{ Node top; public void push(int data){ Node node=new Node(data); node.next=top; top=node; } public void pop(){ if(top!=null){ top=top.next; } } public void printStack(){ Node temp=top; System.out.print("["); while(temp!=null){ System.out.print(temp.data+", "); temp=temp.next; } System.out.println("\b\b]"); } } class Example{ public static void main(String args[]){ Stack s1=new Stack(); s1.push(10); s1.push(20); s1.push(30); s1.push(40); s1.printStack(); s1.pop(); s1.printStack(); s1.push(99); s1.printStack(); } }
Java
UTF-8
1,350
2.921875
3
[]
no_license
package test; import java.sql.Timestamp; import java.util.concurrent.CountDownLatch; class Processor extends Thread { private static Integer MINUTES = 1; private static Integer ITERATION_INTERVAL_IN_SECONDS = 5; private CountDownLatch latch; private String threadName; private transient String addressToPing; public Processor(CountDownLatch latch) { this.latch = latch; } public void run() { int iterationCount = (MINUTES * 60)/ITERATION_INTERVAL_IN_SECONDS; PingAddress pingAddress = new PingAddress(); for(int i = 0; i < iterationCount;i++) { try { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); Boolean pingResult = pingAddress.pingAddress(addressToPing); String result = threadName + " --- " + timestamp + " --- " + pingResult.toString(); System.out.println(result); Thread.sleep(ITERATION_INTERVAL_IN_SECONDS * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } latch.countDown(); } public void setThreadName(String threadName) { this.threadName = threadName; } public void setPingAddress(String siteAddress) { this.addressToPing = siteAddress; // TODO Auto-generated method stub } }
Java
GB18030
443
3.0625
3
[]
no_license
public class shangjilianxi13 { public static void main(String[] args) { int a=3; switch (a) { case 1: System.out.println("ְֵͨĺ"); break; case 2: System.out.println("ͨĺ"); break; case 3: System.out.println("ͨүүĺ"); break; case 4: System.out.println("̵ͨĺ"); break; default: System.out.println(); break; } } }
C#
UTF-8
3,568
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ControlTEst { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void buttonADD_Click(object sender, EventArgs e) { if (!double.TryParse(textBoxA.Text, out double a)) { MessageBox.Show("Введіть число в А", "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!double.TryParse(textBoxB.Text, out double b)) { MessageBox.Show("Введіть число в B", "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } textBoxRes.Text = "" + (a + b); } private void textBoxAandB_TextChanged(object sender, EventArgs e) { textBoxRes.Text = ""; } private void buttonEQ_Click(object sender, EventArgs e) { if (!double.TryParse(textBoxA.Text, out double a)) { MessageBox.Show("Введіть число в А", "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!double.TryParse(textBoxB.Text, out double b)) { MessageBox.Show("Введіть число в B", "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //if (radioButton1.Checked) // textBoxRes2.Text = "" + (a + b); //if (radioButton2.Checked) // textBoxRes2.Text = "" + (a - b); //if (radioButton3.Checked) // textBoxRes2.Text = "" + (a * b); //if (radioButton4.Checked) // textBoxRes2.Text = "" + (a / b); //if (radioButton1.Checked) // textBoxRes2.Text = "" + (a + b); //else //{ // if (radioButton2.Checked) // textBoxRes2.Text = "" + (a - b); // else // { // if (radioButton3.Checked) // textBoxRes2.Text = "" + (a * b); // else // textBoxRes2.Text = "" + (a / b); // } //} //Controls char? zn = ' '; //foreach (var item in Controls) //{ // if (item is RadioButton RB && RB.Checked) { // zn = RB.Text[0]; // break; // } //} //zn = Controls // .OfType<RadioButton>() // .Where(r => r.Checked) // .Select(r=>r.Text[0]) // .FirstOrDefault(); zn = Controls .OfType<RadioButton>() .FirstOrDefault(r => r.Checked) ?.Text.FirstOrDefault(); switch (zn) { case '+': textBoxRes2.Text = "" + (a + b); break; case '-': textBoxRes2.Text = "" + (a - b); break; case '*': textBoxRes2.Text = "" + (a * b); break; case '/': textBoxRes2.Text = "" + (a / b); break; default: textBoxRes2.Text = ""; break; } } } }
C++
UTF-8
3,778
3.1875
3
[]
no_license
#include "Subtracao.h" #include <string.h> #include <stdlib.h> #include "SubtradoraUmDigito.h" Subtracao::Subtracao(int b) { base = b; tamanhoInt = 0; tamanhoFrac = 0; } Subtracao::Subtracao() { } int Subtracao::getTamanho() { return tamanhoInt + tamanhoFrac + 1; } void Subtracao::PreparaDigitosInt(string int1, string int2) { int tam1, tam2; tam1 = int1.size(); tam2 = int2.size(); if (tam1 > tam2) tamanhoInt = tam1; else tamanhoInt = tam2; inteira1 = (SubtradoraUmDigito*)malloc(sizeof(SubtradoraUmDigito) * tamanhoInt); inteira2 = (SubtradoraUmDigito*)malloc(sizeof(SubtradoraUmDigito) * tamanhoInt); for (int i = 0; i < tamanhoInt; i++) { inteira1[i] = SubtradoraUmDigito(Digito('0', base)); inteira2[i] = SubtradoraUmDigito(Digito('0', base)); } for (int i = tamanhoInt - tam1; i <= tamanhoInt; i++) inteira1[i] = SubtradoraUmDigito(Digito(int1[i + tam1 - tamanhoInt], base)); for (int i = tamanhoInt - tam2; i <= tamanhoInt; i++) inteira2[i] = SubtradoraUmDigito(Digito(int2[i + tam2 - tamanhoInt], base)); } void Subtracao::PreparaDigitosFrac(string frac1, string frac2) { int tam1, tam2; tam1 = frac1.size(); tam2 = frac2.size(); if (tam1 > tam2) tamanhoFrac = tam1; else tamanhoFrac = tam2; fracionaria1 = (SubtradoraUmDigito*)malloc(sizeof(SubtradoraUmDigito) * tamanhoFrac); fracionaria2 = (SubtradoraUmDigito*)malloc(sizeof(SubtradoraUmDigito) * tamanhoFrac); for (int i = 0; i < tamanhoFrac; i++) { fracionaria1[i] = SubtradoraUmDigito(Digito('0', base)); fracionaria2[i] = SubtradoraUmDigito(Digito('0', base)); } for (int i = 0; i < tam1; i++) fracionaria1[i] = SubtradoraUmDigito(Digito(frac1[i], base)); for (int i = 0; i < tam2; i++) fracionaria2[i] = SubtradoraUmDigito(Digito(frac2[i], base)); } string Subtracao::SubtraiNumeros(string num1, string num2) { inte1 = getInteira(num1); inte2 = getInteira(num2); fraci1 = getFracionaria(num1); fraci2 = getFracionaria(num2); PreparaDigitosInt(inte1, inte2); PreparaDigitosFrac(fraci1, fraci2); string resultado; int exd = 0; int x = tamanhoFrac + tamanhoInt; resultado.resize((x + 1), ' '); for (int i = tamanhoFrac - 1; i >= 0; i--, x--) { exd = fracionaria1[i].SubtrairDigito(fracionaria2[i].getDigito(), exd); resultado[x] = fracionaria1[i].getDigito().getValorChar(); } resultado[x] = ','; x--; for (int i = tamanhoInt - 1; i >= 0; i--, x--) { exd = inteira1[i].SubtrairDigito(inteira2[i].getDigito(), exd); resultado[x] = inteira1[i].getDigito().getValorChar(); } return resultado; } string Subtracao::getInteira(string num) { string ret = ""; unsigned int tamanho = 0; for (int i = 0; i < num.size() && num[i] != ','; i++) tamanho++; ret.resize(tamanho); for (int i = 0; i < tamanho; i++) ret[i] = num[i]; return ret; } string Subtracao::getFracionaria(string num) { string ret = ""; bool copiar = false; int posicaoVirgula = -1; unsigned int x = 0; unsigned int tamanho = 0; int i = 0; for (i = num.size() - 1; i > 0 && num[i] != ','; i--) { if (num[i - 1] == ',') posicaoVirgula = i - 1; tamanho++; } ret.resize(tamanho); ret = num.substr(posicaoVirgula + 1, num.size() - 1); if (posicaoVirgula < 0) { ret.resize(1); ret = "0"; } return ret; }
C++
UTF-8
763
2.9375
3
[]
no_license
//SECANT METHOD #include<iostream> #include<cmath> #include<iomanip> using namespace std; inline float f(float x) { return (x*x*x-9*x*x+1); } void sec() { float eps=0.0001; float a,b,c; int count; cout<<"enter initial root interval"; cin>>a>>b; if((f(a)*f(b))<0) { count=0; do { c=(a*f(b)-b*f(a))/(f(b)-f(a)); count=count+1; if(fabs((c-b)/c)<eps && (f(c)==0)) break; else a=b; b=c; }while((count<=100) && fabs(f(c))>eps); cout<<"root="<<c<<endl; cout<<"iterations"<<count<<endl; } else cout<<"initial interval incorrect"; } main() { sec(); }
C#
UTF-8
1,967
3.28125
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Bech32LockTimeStat { class Program { static void Main(string[] args) { var lines = File.ReadAllLines("locktime-data.txt"); var myDic = new Dictionary<int, int>(); foreach (var line in lines) { var word = line.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); var currentBlock = int.Parse(word[1]); var locktime = int.Parse(word[2]); var diff = locktime - currentBlock; int relativeLocktime; if (locktime == 0) { relativeLocktime = 1; } else if (diff == 0) { relativeLocktime = 0; } else if (diff > 0) { continue; } else { relativeLocktime = diff; } // Console.WriteLine($"locktime: {relativeLocktime}"); if (myDic.ContainsKey(relativeLocktime)) { myDic[relativeLocktime]++; } else { myDic.Add(relativeLocktime, 1); } } var totalValid = myDic.Sum(x => x.Value); foreach (var pair in myDic.OrderByDescending(x => x.Key)) { var locktimeString = pair.Key == 1 ? "zero" : pair.Key == 0 ? "tip" : pair.Key.ToString(); Console.WriteLine($"locktime {locktimeString}, count: {pair.Value}, percentage: {Math.Round((((decimal)pair.Value / totalValid) * 100), 2)}%"); } Console.WriteLine("Press a key to exit..."); Console.ReadKey(); } } }
Python
UTF-8
900
3.296875
3
[]
no_license
class Solution: def run(self): testcase = [ ([0, 1, 0, 3, 12], [1, 3, 12, 0, 0]), ([0, 0, 0, 3, 12], [3, 12, 0, 0, 0]), ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]), ] for test in testcase: self.moveZeroes(test[0]) if str(test[0]) != str(test[1]): print("Check fail with input {}, expect {}, get {}".format(test[0], test[1], test[0])) else: print("Testcase with input {} success".format(test[0])) def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ writeIdx = 0 for cur in range(0, len(nums)): if nums[cur] != 0: nums[writeIdx] = nums[cur] writeIdx += 1 for cur in range(writeIdx, len(nums)): nums[cur] = 0
Python
UTF-8
958
3.421875
3
[]
no_license
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ # I II III IV V VI VII VIII VIIII X # I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1,000 # a letter placed after another of greater value adds (thus XVI or xvi is 16), whereas a letter placed before another of greater value subtracts (thus XC or xc is 90) # greater, less = greater + less # less, greater = -1*less + 5 # less, greater, less # XIV = greater, less, greater = 10 + (-1) + 5 d = dict({'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C' : 100, 'D' : 500, 'M' : 1000}) sum = 0 i = 0 for i in range(len(s)-1): if d[s[i+1]] > d[s[i]]: sum -= d[s[i]] else: sum += d[s[i]] print d[s[i]] ++i sum += d[s[len(s)-1]] return sum
C#
UTF-8
303
2.546875
3
[]
no_license
using InterfacesLib; using System; namespace RandomPlugin { class DoubleGenerator : IGenerator { Random rnd = new Random((int)DateTime.Now.Ticks); public object Generate() { return rnd.NextDouble() + rnd.Next(); } } }
Java
UTF-8
5,738
2.265625
2
[]
no_license
package com.sylconnexity.spring18.controller; import com.sylconnexity.spring18.dbschema.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.List; import java.util.Optional; /** * Base Controller */ @Controller @RequestMapping(path = "") public class BaseController { @Autowired private ClickRepository clickRepository; @Autowired private LinkRepository linkRepository; @Autowired private MerchantRepository merchantRepository; @Autowired private PublisherRepository publisherRepository; @GetMapping("/sampleUI") public ModelAndView sample_view(@RequestParam(value = "name", defaultValue = "User") String value) { ModelAndView result = new ModelAndView(); result.addObject("userName", value); result.setViewName("sampleAnalyticsUI/sample"); return result; } // /** // * Get the Links with the associated publisherID or merchantID if provided. // * // * @param publisherID The ID of an associated publisher // * @param merchantID The ID of an associated merchant // * @return A list of links, filtered by the given IDs if provided // */ // @GetMapping(path = "") // public @ResponseBody // Iterable<Link> getLinks(@RequestParam(value = "publisherID", defaultValue = "-1") Long publisherID, // @RequestParam(value = "merchantID", defaultValue = "-1") Long merchantID) { // if (publisherID >= 0 && merchantID >= 0) // return linkRepository.findByPublisherIDAndMerchantID(publisherID, merchantID); // else if (publisherID >= 0) // return linkRepository.findByPublisherID(publisherID); // else if (merchantID >= 0) // return linkRepository.findByMerchantID(merchantID); // return linkRepository.findAll(); // } // // /** // * Gets the Link with the given ID if it exists. // * // * @param id The ID of a link // * @return The link with the given ID or null if it does not exist // */ // @GetMapping(path = "/{id}") // public @ResponseBody // Link getLinkByID(@PathVariable(value = "id") Long id) { // Optional<Link> res = linkRepository.findById(id); // if (!res.isPresent()) // return null; // return res.get(); // } // // /** // * Creates a new Link with the given information. // * // * @param publisherID Identifier for an individual influencer // * @param merchantID The merchant identifier for where the SYL Link landed // * @param earnings Amount of money the influencer has earned from a SYL Link // * @param customTitle The title associated with the SYL Link that the user provided // * @param originalURL The original URL associated with the SYL Link that the user provided // * @param imageRedirectPermahashLink The unique hash code associated with a SYL Link // * @return The newly created Link // */ // @PostMapping(path = "") // public @ResponseBody // Link saveLink(@RequestParam(value = "publisherID") Long publisherID, // @RequestParam(value = "merchantID") Long merchantID, // @RequestParam(value = "earnings") Double earnings, // @RequestParam(value = "customTitle", defaultValue = "New Link") String customTitle, // @RequestParam(value = "originalURL") String originalURL, // @RequestParam(value = "imageRedirectPermahashLink") String imageRedirectPermahashLink) { // if (!publisherRepository.existsById(publisherID) || !merchantRepository.existsById(merchantID)) { // return null; // } // Link created = new Link(publisherID, merchantID, earnings, customTitle, originalURL, imageRedirectPermahashLink); // return linkRepository.save(created); // } // // /** // * Updates the Link with the given ID if it exists with the provided information. // * // * @param id The ID of a Link // * @param earnings The new earnings of the link // * @param customTitle The new title of the link // * @return The updated Link, or null if the original ID did not exist // */ // @PostMapping(path = "/{id}") // public @ResponseBody // Link saveLinkByID(@PathVariable(value = "id") Long id, // @RequestParam(value = "earnings", defaultValue = "-1.0") Double earnings, // @RequestParam(value = "customTitle", defaultValue = "") String customTitle) { // if (!linkRepository.existsById(id)) { // return null; // } // Link old = linkRepository.findById(id).get(); // if (earnings > 0) // old.setEarnings(earnings); // if (!customTitle.equals("")) // old.setCustomTitle(customTitle); // return linkRepository.save(old); // } // // /** // * Deletes the Link with the given ID and its associated clicks. // * // * @param id The ID of a Link // */ // @DeleteMapping(path = "/{id}") // public @ResponseBody // void deleteLink(@PathVariable(value = "id") Long id) { // if (linkRepository.existsById(id)) // linkRepository.deleteById(id); // List<Click> clicks = clickRepository.findByLinkID(id); // if (clicks != null) // clickRepository.deleteAll(clicks); // } }
Markdown
UTF-8
8,806
3.09375
3
[]
no_license
The goal of this exercise is to build a containerized two tier application in the OpenShift cluster. This application will help you learn about clustered containers and distributed systems. It will teach you about Kubernetes and how it operates with the principles of "defined state" and "actual state" - it constantly monitors the environment and attempts to make the actual state match the defined state. ## Terminal 2 ## Before we do anything, we need some application images for MySQL and HTTPD/PHP. To do this, we are going to build the supply chain again. Open a **second** teminal because this command will take a while to complete. While it builds, continue on using Terminal 1: ``make -C ~/labs/lab2-step4/ docker tag wordpress wordpress:csc``{{execute}} ## Terminal 1 ## In Kubernetes/OpenShift, applications are defined with either JSON or YAML files - either file format can be imported or exported, even converting between the two. In this lab, we will use YAML files. Essentially, the application definition files are a collection of software defined objects in Kubernetes. The objects in the file are imported and become defined state for the application. Important objects include: - Pods: Collections of one or more containers - ReplicationControllers: Ensure that the correct number of pods are running. - Services: Internal object which represents the port/daemon/program running. - Routes: Expose services to the external world. - PeristentVolumeClaims: Represents the request for storage and how much. Typically defined in the application by the developer or architect. - PersistentVolume: Represents the actual storage. Typically defined by sysadmins or automation. Developers and architects can group these objects/resources in a single file to make sharing and deployment of the entire application easier. These definitions can be stored in version control systems just like code. In a **new** terminal, let's inspect some of the Kubernetes resource definitions we will use for this lab. First, look at the objects/resources that define the application: ``cat ~/labs/lab4-step1/wordpress-objects.yaml``{{execute}} Notice there are two Services defined - one for MySQL and one for Wordpress. This allows these two Services to scale independently. The front end can scale with web traffic demand. The MySQL service could also be made to scale with a technology like Galera, but would require special care. You may also notice that even though there are two Services, there is only a single Route in this definition. That's because Services are internal to the Kubernetes cluster, while Routes expose the service externally. We only want to expose our Web Server externally, not our Database: The application also needs storage for the MySQL tables, and Web Root for Apache. Let's inspect the YAML file which will create the storage. We will create four persistent volumes - two that have 1GB of storage and two that will have 2GB of storage. In this lab environment, these persistent volumes will reside on the local all-in-one installation, but in a production environment they could reside on shared storage and be accessed from any node in the Kubernetes/OpenShift cluster. In a production environment, they could also be dynamically provisioned definied by rules. OpenShift supports persistent volumes which leverage Gluster, Ceph, AWS EBS Volumes, NFS, iSCSI, and others: ``cat ~/labs/lab4-step1/persistent-volumes.yaml``{{execute}} Now, let's instantiate some Persistent Volumes: ``oc create -f ~/labs/lab4-step1/persistent-volumes.yaml``{{execute}} Notice that the persistent volumes are unbound. They are available and waiting, but will not be utilized until you define an application which consumes storage. This is inline with the way Kubernetes constantly tries to drive the actual state toward the defined state. Currently, there is no definition to consume this storage: ``oc get pv``{{execute}} ## Terminal 1 ## **Wait** for the builds in Terminal 2 to complete before moving on. Once the builds in Terminal 2 complete, instantiate the two-tier application: ``oc create -f ~/labs/lab4-step1/wordpress-objects.yaml``{{execute}} Look at the status of the application. The two pods that make up this application will remain in a "pending" state - why? Kubernetes will connect the Persistent Volume Claims with the available Persistent Volumes, pull images, and schedule the pods to a node. Keep running these commands until the pods start: ``oc describe pod wordpress-``{{execute}} ``oc describe pod mysql-``{{execute}} Now, the persistent volume claims for the application will become Bound and satisfy the storage requirements. Kubernetes/OpenShift will now start to converge the defined state and the actual state: ``oc get pvc``{{execute}} Also, take a look at the Persistent Volumes again: ``oc get pv``{{execute}} You may notice the wordpress pod enter a state called CrashLoopBackOff. This is a natural state in Kubernetes/OpenShift which helps satisfy dependencies. The wordpress pod will not start until the mysql pod is up and running. This makes sense, because wordpress can't run until it has a database and a connection to it. Similar to email retries, Kubernetes will back off and attempt to restart the pod again after a short time. Kubernetes will try several times, extending the time between tries until eventually the dependency is satisfied, or it enters an Error state. Luckily, once the mysql pod comes up, wordpress will come up successfully. Here are some useful commands to watch the state: Show all pods. You may run this command several times waiting for the actual state to converge with the defined state: ``oc get pods``{{execute}} View the events for a pod. You may run these commands several times waiting for the actual state to converge with the defined state: ``oc describe pod mysql-``{{execute}} ``oc describe pod wordpress-``{{execute}} Once the pods are scheduled and running, view the terminal output for each pod: ``oc logs $(oc get pods | grep mysql- | awk '{print $1}')``{{execute}} ``oc logs $(oc get pods | grep wordpress- | awk '{print $1}')``{{execute}} Now, log into the OpenShift web interface which is a convenient place to monitor the state, and troubleshoot things when they go wrong. You can even get a debug terminal into a Pod to troubleshoot if it crashes. This can help you figure out why it crashed. This shouldn't happen in this lab, but as you build applications it surely will. Also, feel free to delete a pod and see what happens. Kubernetes will see that the defined state and actual state no longer match and will recreate it. This is useful when things are taking too long :-) * Username: `admin`{{copy}} * Password: `admin`{{copy}} * Console: [here](https://[[HOST_SUBDOMAIN]]-8443-[[KATACODA_HOST]].environments.katacoda.com/console/project/default/overview) Here are some useful locations to investigate what is happening. The "Events" section is useful early in the Pod creation process, when its being scheduled in the cluster and then when the container image is being pulled. Later in the process when a Pod is crashing because of something in the container image itself, its useful to watch the terminal output in the "Logs" section. It can also be useful to run commands live in a Terminal. Sometimes a Pod won't start, so it's useful poke around with using the "Debug in Terminal" section. Get a feel in the following areas of the interface: - Applications -> Pods -> mysql-##### -> Events - Applications -> Pods -> mysql-##### -> Logs - Applications -> Pods -> mysql-##### -> Terminal - Applications -> Pods -> mysql-##### -> Details -> Debug in Terminal - Applicaitons -> Pods -> wordpress-##### -> Events - Applicaitons -> Pods -> wordpress-##### -> Logs - Applicaitons -> Pods -> wordpress-##### -> Terminal - Applicaitons -> Pods -> wordpress-##### -> Details -> Debug in Terminal Finally, ensure that the web interface is up and running. We will need this for the next lab: ``curl http://$(oc get svc | grep wpfrontend | awk '{print $3}')/wp-admin/install.php``{{execute}} In this exercise you learned how to deploy a fully functional two tier application with a single command (oc create). As long as the cluster has persistent volumes available to satisify the application, an end user can do this on their laptop, in a development environment or in production data centers all over the world. All of the dependent code is packaged up and delivered in the container images - all of the data and configuration comes from the environment. Production instances will access production persistent volumes, development environments can be seeded with copies of production data, etc. It's easy to see why container orchestration is so powerful.
Markdown
UTF-8
9,786
3.203125
3
[]
no_license
# Sass # 3) Nesting, import, extend, 조건과 반복, Mixin, Function ## 1. Nesting : Nesting은 Sass의 유용한 확장 기능으로, 선언을 중첩 하는 것이다. CSS는 후손 셀렉터의 경우, 부모요소를 기술해야 한다. ```css #navbar { width: 80%; height: 23px; } #navbar ul { list-style-type : none; } // ul은 부모요소 #navbar를 기술한다. ``` Sass의 Nesting은 후손 셀렉터를 간단히 기술이 가능하다. 또한 HTML의 구조를 반영한 css를 기술할 수 있다. 그렇지만 너무 깊은 Nesting은 가독성을 나쁘게 하고 셀렉터를 복잡하게 한다. ```scss #navbar { width: 80%; height: 23px; ul { list-style-type: none; } li { float: left; a { font-weight: bold; } } } ``` 부모요소의 참조가 필요한 경우 `&`를 사용한다. :hover또는 ::before등의 가상 클래스 선택자를 지정하는 경우 부모요소의 참조가 필요하다. ```scss .myAnchor { color: blue; // .myAnchor: hover &:hover { text-decoration: underline; } // .myAnchor: visited &:visited { color: purple; } } ``` Nesting은 프로퍼티에도 사용할 수 있다. ```scss .funky { font: { family: fantasy; size: 30em; weight: bold; } } ``` ## 2. @-Rules and Directives : 기능에 따라 css 파일을 분리하면 재사용 및 유지보수 측면에서 유리하다. 따라서 룰을 정하여 파일을 분리하여 개발하는 것은 효과적인 방법이다. Sass는 @import directive를 사용하여 분리된 stylesheet 파일을 import 할 수 있다. 기존의 css @import 보다 편리한 기능을 제공한다. ```scss @import "foo.scss"; @import "foo" // 확장자는 생략 가능하다 @import "rounded-corners", "text-shadow"; // import multiple files $family: unquote("Droid+sans"); @import url("http://fonts.googleapis.com/css?family=#{$family}"); ``` 여러개의 파일로 분할하는 것 또는 분할된 파일 => `partial` partial된 Sass파일명의 선두에는 underscore(_)를 붙인다. _reset.scss, _module.scss, _print.scss 예를들어 "_foo.scss"라는 partial된 Sass파일이 있고, 이 파일을 import 하는 경우, 아래와 같이 기술한다. 파일명의 선두의 _와 확장자는 생략가능 ```scss @import "foo"; ``` partial된 Sass 파일명 선두에 붙인 _의 의미는 import 는 수행하되, CSS로의 컴파일은 수행하지 말라는 의미를 갖는다. partial은 import시에는 css 파일로 컴파일 되지 않기 때문에 최종적으로 css로 컴파일을 수행할 sass파일에서 import 한다. -> Sass 파일명 선두에 _를 붙이면 import 시에는 css파일로 컴파일 되지 않고, import가 완료된 이후 css로 컴파일을 수행한다. * @import는 top-level에서 사용하는 것이 일반적이지만, css rule 또는 @media rule 내에 포함시키는 것도 가능하다. * ```scss // _example.scss .example { color: red; } ``` * ```scss #main { @import "example"; } // main안에서 import 수행 => nested된다. ``` * 위 코드의 컴파일 결과 ```scss #main .example { color: red; } ``` ### 2.2 @extend : 기존 스타일을 상속하고자 하는경우 사용한다. 상속되는 rule set을 그대로 상속받아 다른 부분만 별도 선언하면 된다. ```scss .error { border: 1px #f00; background-color: blue; } .seriousError { @extend .error; border-width: 3px; border-color: darkblue; } ``` 위 코드의 컴파일 결과 (.error와 .seriousError가 공통으로 사용하는 프로퍼티를 묶어 합리적 룰셋 생성) ```css .error, .seriousError { border: 1px #f00; background-color: blue; } .seriousError { border-width: 3px; border-color: darkblue; } ``` * @extend를 사용하면 컴파일 후 자신의 셀렉터가 어디에 첨부될 것인지 예상하기 어렵고, 예상치 못한 부작용이 발생할 수 있다. -> @extend의 사용은 가급적 자제하고 Mixin을 사용하자. (@extend의 부작용) ### 2.3 Placeholder Selectors : Sass 3.2부터 제공되는 기능. 재이용 가능한 rule set을 % 키워드로 지정하는 @extend 전용 selector이다. 상속만을 위한 rule set이므로 자신은 컴파일 되지 않는다. ```scss %input-style { font-size: 14px; } .input-black { @extend %input-style; color: black; } .input-red { @extend %input-style; color: red; } ``` 컴파일 결과는 아래와 같다. ```css .input-black, .input-red { font-size: 14px } .input-black { color: black; } .input-red { color: red; } ``` ## 3. 조건과 반복 : sass는 js 같은 프로그래밍 언어와 같이 제어문 기능을 제공한다. ### 3.1 if() : built-in if()함수는 주어진 조건을 판단하여 결과를 리턴한다. Javascript의 삼항연산자와 유사하게 동작 ```scss if(condition, if_true, if_false) // condition이 true 이면, if_true를 // condition이 false 이면, if_false를 반환한다. ``` ```scss $type: ocean; p { color: if($type == ocean, blue, black); // color: blue; } ``` ### 3.2 @if : @if를 사용하면 조건 분기가 가능하다. ```scss $type: monster; p { @if $type == ocean { color: blue; } @else if $type == matador { color: red; } @else if $type == monster { color: green; } @else { color: black; } } ``` 컴파일 결과 ```css p { color: green; } ``` ### 3.3 @for : @for로 반복문을 사용할 수 있다. ```scss @for $i from 1 through 3 { .item-#{$i} { width: 2em * $i; } }// .item-1, .item-2, .item-3...생성 ``` ```css /* 컴파일 결과 */ .item-1 { width: 2em; } .item-2 { width: 4em; } .item-3 { width: 6em; } ``` ### 3.4 @each : @each는 list또는 map의 요소에 대해 반복을 실시한다. ```scss @each $animal in puma, sea-slug, egret, salamander { // List .#{$animal}-icon { background-image: url('/images/#{$animal}.png'); } } // Map // $header: h1, $size: 2em // $header: h2, $size: 1.5em // $header: h3, $size: 1.2em @each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) { #{$header} { font-size: $size; } } ``` ```css .puma-icon { background-image: url("/images/puma.png"); } .sea-slug-icon { background-image: url("/images/sea-slug.png"); } .egret-icon { background-image: url("/images/egret.png"); } .salamander-icon { background-image: url("/images/salamander.png"); } h1 { font-size: 2em; } h2 { font-size: 1.5em; } h3 { font-size: 1.2em; } ``` ### 3.5 @while : 반복문을 사용할 수 있다. ```scss $i: 6; @while $i > 0 { .item-#{$i} { width: 2em * $i; } $i: $i - 2; } ``` 컴파일 결과 ```css .item-6 { width: 12em; } .item-4 { width: 8em; } .item-2 { width: 4em; } ``` ## 4. Mixin : Mixin 은 Sass의 매우 유용한 기능으로 중복 기술을 방지하기 위해 사용 빈도가 높은 마크업을 사전에 정의하여 필요할 때에 불러 사용하는 방법이다. @exten와 유사하지만, 프로그래밍 언어의 함수와 같이 argument를 받을 수 있다. `@mixin`을 선언하고 `@include`로 불러들인다. ```scss // 지름이 50px인 원 @mixin circle { width: 50px; height: 50px; border-radius: 50%; } // 지름이 50px인 원을 위한 mixin을 include한 후, 배경을 추가 지정 .box { @include circle; background: #foo; } ``` ```css /* 컴파일 결과 */ .box { width: 50px; height: 50px; border-radius: 50%; background: #f00; } ``` * @extend와 달리 Mixin은 함수처럼 argument를 사용할 수 있다. ```scss @mixin circle($size) { width: $size; height: $size; border-radius: 50%; } .box { @include circle(100px); background: #f00; } // 컴파일 결과 // .box { // width: 100px; // height: 100px; // border-radius: 50%; // background: #f00; // } ``` ```scss // argument의 초기값을 설정할 수도 있다. @mixin circle($size: 10px) { width: $size; height: $size; border-radius: 50%; } .box { //인자가 없으면 초기값을 사용한다. @include circle(); background: #f00; } ``` ```css /* 컴파일 결과 */ .box { width: 10px; height: 10px; border-radius: 50%; background: #f00; } ``` ```scss /* Mixin을 사용한 유용한 예제 */ @mixin vendorPrefix($property, $value) { @each $prefix in -webkit-, -moz-, -ms-, -o-, '' { #{$prefix}#{$property}: $value; } } .border_radius { @include vendorPrefix(transition, 0.5s); } ``` ```css .border_radius { -webkit-transition: 0.5s; -moz-transition: 0.5s; -ms-transition: 0.5s; -o-transition: 0.5s; transition: 0.5s; } ``` ```scss @mixin position($position, $top: null, $right: null, $bottom: null, $left: null) { position: $position; top: $top; right: $right; bottom: $bottom; left: $left; } .box { @include position (absolute, $top: 10px, $left: 50%); } ``` ```css .box { position: absolute; top: 10px; left: 50%; } ``` ## 5. Function : Function은 mixin과 유사하나 리턴값에 차이가 있다. * Mixing: style markup을 리턴 * Function: @return directive를 통해 값을 리턴 ```scss $grid-width: 40px; $gutter-width: 10px; @function grid-width($n) { @return $n * $grid-width + ($n - 1) * $gutter-width; } #sidebar { width: grid-width(5); } // width: 240px; ``` ## 6. comment(주석) : ` css는 멀티라인 주석 /* */만 지원하지만, sass는 /* */와 // 모두 사용가능 하다.` 한줄 주석 //은 컴파일 후 css에서 사라지고, 멀티라인 주석은 css에 나타난다.
PHP
UTF-8
5,961
2.640625
3
[ "MIT" ]
permissive
<?php namespace TenUp\SwiftStream\v1_1_0\Pixelate; /** * Set up any required hooks in the namespace. */ function setup() { $n = function( $function ) { return __NAMESPACE__ . "\\$function"; }; // Only hook in to create intermediate images if we're _not_ on WordPress.com. if ( ! defined( 'WPCOM_IS_VIP_ENV' ) || ! WPCOM_IS_VIP_ENV ) { add_action( 'after_setup_theme', $n( 'add_placeholder_sizes' ), 999, 0 ); add_filter( 'wp_generate_attachment_metadata', $n( 'filter_images' ), 10, 1 ); } } /** * Loop through registered image sizes and add placeholders * * @global array $_wp_additional_image_sizes */ function add_placeholder_sizes() { global $_wp_additional_image_sizes; if( !isset( $_wp_additional_image_sizes ) ){ $_wp_additional_image_sizes = array(); } $new_sizes = array(); foreach( get_intermediate_image_sizes() as $name ) { if ( isset( $_wp_additional_image_sizes[ $name ]['width'] ) ) { $width = absint( $_wp_additional_image_sizes[ $name ]['width'] ); } else { $width = absint( get_option( "{$name}_size_w" ) ); } if ( isset( $_wp_additional_image_sizes[ $name ]['height'] ) ) { $height = absint( $_wp_additional_image_sizes[ $name ]['height'] ); } else { $height = absint( get_option( "{$name}_size_h" ) ); } if ( isset( $_wp_additional_image_sizes[ $name ]['crop'] ) ) { $crop = $_wp_additional_image_sizes[ $name ]['crop']; } else { $crop = get_option( "{$name}_crop" ); } $new_sizes[ $name . '-ph' ] = array( 'width' => $width, 'height' => $height, 'crop' => $crop, ); } $_wp_additional_image_sizes = array_merge( $_wp_additional_image_sizes, $new_sizes ); } /** * Automatically resample and save the downsized versions of each graphic. * * @param array $meta * * @return array */ function filter_images( $meta ) { $n = function( $function ) { return __NAMESPACE__ . "\\$function"; }; add_filter( 'image_resize_dimensions', $n( 'upscale_dimensions' ), 1, 6 ); $uploads = wp_upload_dir(); // Generate a placeholder for the full image $file = basename( $meta[ 'file' ] ); $file_base_path = trailingslashit( $uploads[ 'basedir' ] ) . str_replace( $file, '', $meta[ 'file' ] ); $new_parent = create_placeholder( $file, $file_base_path ); // Generate placeholders for each image size foreach( $meta['sizes'] as $name => $data ) { if ( false !== strpos( $name, '-ph' ) ) { $new_file = create_placeholder( $data['file'], $file_base_path ); $meta['sizes'][ $name ]['file'] = $new_file; } } $file_ext = pathinfo( $file, PATHINFO_EXTENSION ); $mime_type = 'application/octet-stream'; $mime_types = wp_get_mime_types(); foreach( $mime_types as $extension => $type ) { if ( preg_match( "/{$file_ext}/i", $extension ) ) { $mime_type = $type; break; } } $meta['sizes']['full-ph'] = array( 'file' => $new_parent, 'width' => $meta['width'], 'height' => $meta['height'], 'mime-type' => $mime_type, ); remove_filter( 'image_resize_dimensions', $n( 'upscale_dimensions' ), 1 ); return $meta; } /** * Create a placeholder image given a regular image. * * @param string $image_filename * @param string $base_file_path * @return string */ function create_placeholder( $image_filename, $base_file_path ) { $image = wp_get_image_editor( trailingslashit( $base_file_path ) . $image_filename ); if ( is_wp_error( $image ) ) { return $image_filename; } // Get proportions $size = $image->get_size(); $old_width = $size['width']; $old_height = $size['height']; $width = $old_width / 10; $height = $old_height / 10; // Placeholder filename $new_name = preg_replace( '/(\.gif|\.jpg|\.jpeg|\.png)/', '-ph$1', $image_filename ); $image->set_quality( 10 ); $image->resize( $width, $height, false ); $image->resize( $old_width, $old_height, false ); $image->save( trailingslashit( $base_file_path ) . $new_name ); return $new_name; } /** * Allow WordPress to upscale images. * * @see https://wordpress.org/support/topic/wp-351-wp-image-editor-scaling-up-images-does-not-work?replies=6 * * @param null $null * @param int $orig_w * @param int $orig_h * @param int $dest_w * @param int $dest_h * @param bool $crop * * @return array|bool */ function upscale_dimensions( $null, $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) { if ( $crop ) { // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h $aspect_ratio = $orig_w / $orig_h; $new_w = min( $dest_w, $orig_w ); $new_h = min( $dest_h, $orig_h ); if ( ! $new_w ) { $new_w = intval( $new_h * $aspect_ratio ); } if ( ! $new_h ) { $new_h = intval( $new_w / $aspect_ratio ); } $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h ); $crop_w = round( $new_w / $size_ratio ); $crop_h = round( $new_h / $size_ratio ); $s_x = floor( ( $orig_w - $crop_w ) / 2 ); $s_y = floor( ( $orig_h - $crop_h ) / 2 ); } else { // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box $crop_w = $orig_w; $crop_h = $orig_h; $s_x = 0; $s_y = 0; /* wp_constrain_dimensions() doesn't consider higher values for $dest :( */ /* So just use that function only for scaling down ... */ if ( $orig_w >= $dest_w && $orig_h >= $dest_h ) { list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h ); } else { $ratio = $dest_w / $orig_w; $w = intval( $orig_w * $ratio ); $h = intval( $orig_h * $ratio ); list( $new_w, $new_h ) = array( $w, $h ); } } // Now WE need larger images ... if ( $new_w == $orig_w && $new_h == $orig_h ) { return false; } // the return array matches the parameters to imagecopyresampled() // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h ); }
C++
UTF-8
1,064
3.578125
4
[]
no_license
#pragma once #include <Image/Image.hpp> namespace Graphics { namespace Draw { /** * @brief Mix two colors * * @param c1 first color * @param c2 second color * @param p percentage of first color * @return Pixel mixed color */ inline Pixel mixColors(const Pixel &c1, const Pixel &c2, const float p) { return {static_cast<uint8_t>(std::sqrt(p * c1.r * c1.r + (1 - p) * c2.r * c2.r)), static_cast<uint8_t>(std::sqrt(p * c1.g * c1.g + (1 - p) * c2.g * c2.g)), static_cast<uint8_t>(std::sqrt(p * c1.b * c1.b + (1 - p) * c2.b * c2.b))}; } /** * @brief Helper function to plot a pixel on an image with mixed colors * * @param image image to draw on * @param x x location * @param y y location * @param p percentage of color to plot * @param c color */ inline void plot(Image &image, const int x, const int y, const double p, const Pixel &c) { if (x < 0 || x >= image.width() || y < 0 || y >= image.height()) return; image.at({x,y}) = mixColors(c, image.at({x, y}), p); } } // namespace Draw } // namespace Graphics
C#
UTF-8
18,363
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Blokc { public partial class frmBlokc : Form { public static int stevec = 1; public frmBlokc() { InitializeComponent(); } // širina za txtLinije public int sirina() { int s = 25; int linija = txtBlokc.Lines.Length; if (linija <= 99) { s = 20 + (int)txtBlokc.Font.Size; } else if (linija <= 999) { s = 30 + (int)txtBlokc.Font.Size; } else { s = 60 + (int)txtBlokc.Font.Size; } return s; } // dodajanje št linij v txtLinije public void dodajStLin() { Point pt = new Point(0, 0); int PrviIndeks = txtBlokc.GetCharIndexFromPosition(pt); int PrvaLinija = txtBlokc.GetLineFromCharIndex(PrviIndeks); pt.X = ClientRectangle.Width; pt.Y = ClientRectangle.Height; int ZadnjiIndeks = txtBlokc.GetCharIndexFromPosition(pt); int ZadnjaLinija = txtBlokc.GetLineFromCharIndex(ZadnjiIndeks); txtLinije.SelectionAlignment = HorizontalAlignment.Center; txtLinije.Text = ""; txtLinije.Width = sirina(); for (int i = PrvaLinija; i <= ZadnjaLinija + 1; ++i) { txtLinije.Text += i + 1 + "\n"; } } // dodatna koda za txtLinije - potrebno prečekirat / popravit določene zadeve (npr. vključen word wrap ne bi smel prikazovati nove linije pri nadaljevanju texta) private void frmBlokc_Load(object sender, EventArgs e) { txtLinije.Font = txtBlokc.Font; txtBlokc.Select(); dodajStLin(); } private void txtBlokc_SelectionChanged(object sender, EventArgs e) { Point pt = txtBlokc.GetPositionFromCharIndex(txtBlokc.SelectionStart); if (pt.X == 1) { dodajStLin(); } } private void txtBlokc_VScroll(object sender, EventArgs e) { txtLinije.Text = ""; dodajStLin(); txtLinije.Invalidate(); } // prikaz podatkov v statusni vrstici + v rtb (txtLinije) private void txtBlokc_TextChanged(object sender, EventArgs e) { // statusna vrstica: int stLinij = txtBlokc.Lines.Length; txtLinije.Text = ""; for (int i = 0; i != stLinij; ++i) { txtLinije.AppendText((i + 1) + "\n"); } lblStatus.Text = "Linija: " + stLinij.ToString() + " - Znaki: " + txtBlokc.Text.Length.ToString(); // prikaz linij na levi strani (txtLinije) if (txtBlokc.Text == "") { dodajStLin(); } } // koda za pisavo v txtLinije private void txtBlokc_FontChanged(object sender, EventArgs e) { txtLinije.Font = txtBlokc.Font; txtBlokc.Select(); dodajStLin(); } private void txtLinije_MouseDown(object sender, MouseEventArgs e) { txtBlokc.Select(); txtLinije.DeselectAll(); } // klicanje metode dodajStLin() private void frmBlokc_Resize(object sender, EventArgs e) { dodajStLin(); } // nov Blok'c private void novToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.Modified == true) { // kliče sfdShrani, če je v txtBlokc zaznana sprememba (zapisan text,...) in uporabnik pritisne na "Nov" v menustrip-u shraniKotToolStripMenuItem_Click(sender, e); } } // odpri Blok'c private void odpriToolStripMenuItem_Click(object sender, EventArgs e) { // odpri datoteko ofdOdpri.Filter = "Blok'c besedila (*.txt)|*.txt|Vse datoteke (*.*)|*.*"; ofdOdpri.FilterIndex = 1; // izbran filter (*.txt), 2 = *.* ofdOdpri.RestoreDirectory = true; if (ofdOdpri.ShowDialog() == DialogResult.OK) { using (var sr = new StreamReader(ofdOdpri.FileName)) { txtBlokc.Text = sr.ReadToEnd(); } } } // shrani Blok'c private void shraniToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.Modified == true) { sfdShrani.Filter = "Blok'c besedila (*.txt)|*.txt|Vse datoteke (*.*)|*.*"; sfdShrani.FileName = "Neimenovan Blok'c"; DialogResult dg = MessageBox.Show("Ali želiš shraniti trenutni Blok'c?", "Shrani Blok'c?", MessageBoxButtons.YesNoCancel); if (dg == DialogResult.Yes) { sfdShrani.ShowDialog(); using (var sw = new StreamWriter(sfdShrani.FileName)) { sw.WriteLineAsync(txtBlokc.Text); } } else if (dg == DialogResult.Cancel) { // ... } else if (dg == DialogResult.No) { txtBlokc.Clear(); } } } private void shraniKotToolStripMenuItem_Click(object sender, EventArgs e) { sfdShrani.Filter = "Blok'c besedila (*.txt)|*.txt|Vse datoteke (*.*)|*.*"; sfdShrani.FileName = "Neimenovan Blok'c"; DialogResult dg = MessageBox.Show("Ali želiš shraniti trenutni Blok'c?", "Shrani Blok'c?", MessageBoxButtons.YesNoCancel); if (dg == DialogResult.Yes) { sfdShrani.ShowDialog(); using (var sw = new StreamWriter(sfdShrani.FileName)) { sw.WriteLineAsync(txtBlokc.Text); } } else if (dg == DialogResult.Cancel) { // ... } else if (dg == DialogResult.No) { txtBlokc.Clear(); } } // priprava za tiskanje private void pripravaStraniToolStripMenuItem_Click(object sender, EventArgs e) { printPreviewDialog.Document = printDokument; printPreviewDialog.ShowDialog(); } // natisni Blok'c private void natisniToolStripMenuItem_Click(object sender, EventArgs e) { printPreviewDialog.Document = printDokument; if (printDialog.ShowDialog() == DialogResult.OK) { printDokument.Print(); } } private void printDokument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { e.Graphics.DrawString(txtBlokc.Text, txtBlokc.Font, Brushes.Black, 12, 10); } // razveljavi, povrni, izreži, kopiraj, prilepi, izbriši, izbriši vse (dodaj kodo), izberi vse, datum / ura private void razveljaviToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.Undo(); } private void povrniToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.Redo(); } private void izrežiToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.Cut(); } private void kopirajToolStripMenuItem1_Click(object sender, EventArgs e) { txtBlokc.Copy(); } private void prilepiToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.Paste(); } private void izbrišiToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectedText = ""; } private void izbrišiVseToolStripMenuItem_Click(object sender, EventArgs e) { // ... txtBlokc.Clear(); } private void izberiVseToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectAll(); } private void datumUraToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectedText = Convert.ToString(DateTime.Now) + " "; //txtBlokc.Select(txtBlokc.Text.Length, 0); // postavi kazalko tipkovnice na konec dokumenta. } // word wrap private void wordWrapToolStripMenuItem_Click(object sender, EventArgs e) { if (wordWrapToolStripMenuItem.Checked == false) { wordWrapToolStripMenuItem.Checked = true; txtBlokc.WordWrap = true; } else { wordWrapToolStripMenuItem.Checked = false; txtBlokc.WordWrap = false; } } // pisava private void pisavaToolStripMenuItem1_Click(object sender, EventArgs e) { DialogResult pisava = fdPisava.ShowDialog(); fdPisava.ShowColor = true; // označeno besedilo se spremeni v željen font + neoznačeno besedilo "se nadaljuje" v željenem fontu... if (pisava == DialogResult.OK) { if (txtBlokc.SelectionLength > 0) { txtBlokc.SelectionFont = fdPisava.Font; txtBlokc.SelectionColor = fdPisava.Color; } else if (txtBlokc.Text.Length > 0) { txtBlokc.SelectionFont = fdPisava.Font; txtBlokc.SelectionColor = fdPisava.Color; } else { txtBlokc.Font = fdPisava.Font; txtBlokc.ForeColor = fdPisava.Color; } } } // označi / highlight private void rumenoToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectionBackColor = Color.Yellow; txtBlokc.SelectionColor = Color.Black; } private void rdečeToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectionBackColor = Color.Crimson; txtBlokc.SelectionColor = Color.Gainsboro; } private void zelenoToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectionBackColor = Color.LawnGreen; txtBlokc.SelectionColor = Color.Black; } private void modroToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectionBackColor = Color.RoyalBlue; txtBlokc.SelectionColor = Color.White; } // krepko, ležeče, podčrtano, prečrtano private void krepkoToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.SelectionFont != null) { System.Drawing.Font trenutniFont = txtBlokc.SelectionFont; System.Drawing.FontStyle noviFontStil; if (txtBlokc.SelectionFont.Bold == true) { noviFontStil = FontStyle.Regular; } else { noviFontStil = FontStyle.Bold; } txtBlokc.SelectionFont = new Font(trenutniFont.FontFamily, trenutniFont.Size, noviFontStil); } } private void poševnoToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.SelectionFont != null) { System.Drawing.Font trenutniFont = txtBlokc.SelectionFont; System.Drawing.FontStyle noviFontStil; if (txtBlokc.SelectionFont.Italic == true) { noviFontStil = FontStyle.Regular; } else { noviFontStil = FontStyle.Italic; } txtBlokc.SelectionFont = new Font(trenutniFont.FontFamily, trenutniFont.Size, noviFontStil); } } private void podčrtanoToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.SelectionFont != null) { System.Drawing.Font trenutniFont = txtBlokc.SelectionFont; System.Drawing.FontStyle noviFontStil; if (txtBlokc.SelectionFont.Underline == true) { noviFontStil = FontStyle.Regular; } else { noviFontStil = FontStyle.Underline; } txtBlokc.SelectionFont = new Font(trenutniFont.FontFamily, trenutniFont.Size, noviFontStil); } } private void prečrtanoToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.SelectionFont != null) { System.Drawing.Font trenutniFont = txtBlokc.SelectionFont; System.Drawing.FontStyle noviFontStil; if (txtBlokc.SelectionFont.Strikeout == true) { noviFontStil = FontStyle.Regular; } else { noviFontStil = FontStyle.Strikeout; } txtBlokc.SelectionFont = new Font(trenutniFont.FontFamily, trenutniFont.Size, noviFontStil); } } // male in velike črke private void maleČrkeToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectedText = txtBlokc.SelectedText.ToLower(); } private void vELIKEČRKEToolStripMenuItem_Click(object sender, EventArgs e) { txtBlokc.SelectedText = txtBlokc.SelectedText.ToUpper(); } // bullets (pike) private void dodajPikoToolStripMenuItem_Click(object sender, EventArgs e) { try { txtBlokc.BulletIndent = 10; txtBlokc.SelectionBullet = true; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Zgodila se je čudna napača. Poskusi še enkrat."); } } private void odstraniPikoToolStripMenuItem_Click(object sender, EventArgs e) { try { txtBlokc.BulletIndent = 0; txtBlokc.SelectionBullet = false; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Zgodila se je čudna napača. Poskusi še enkrat."); } } // zoom private void povečajToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.ZoomFactor < 64.5) { txtBlokc.ZoomFactor = txtBlokc.ZoomFactor + 0.25f; } } private void pomanjšajToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.ZoomFactor > 0.515625) { txtBlokc.ZoomFactor = txtBlokc.ZoomFactor - 0.125f; } } private void prvotniPogledToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.ZoomFactor > 1 || txtBlokc.ZoomFactor < 1) { txtBlokc.ZoomFactor = 1.0f; } } private void iščiToolStripMenuItem_Click(object sender, EventArgs e) { Iskalnik iskalnik = new Iskalnik(); iskalnik.Show(); } // pomoč private void pomočToolStripMenuItem1_Click(object sender, EventArgs e) { } // about private void oProgramuToolStripMenuItem_Click(object sender, EventArgs e) { } // izhod private void izhodToolStripMenuItem_Click(object sender, EventArgs e) { if (txtBlokc.Modified == true) { sfdShrani.Filter = "Blok'c besedila (*.txt)|*.txt|Vse datoteke (*.*)|*.*"; sfdShrani.FileName = "Neimenovan Blok'c"; DialogResult dg = MessageBox.Show("Ali želiš shraniti trenutni Blok'c?", "Shrani Blok'c?", MessageBoxButtons.YesNoCancel); if (dg == DialogResult.Yes) { sfdShrani.ShowDialog(); using (var sw = new StreamWriter(sfdShrani.FileName)) { sw.WriteLineAsync(txtBlokc.Text); } } else if (dg == DialogResult.Cancel) { // ... } else if (dg == DialogResult.No) { txtBlokc.Clear(); } } else { this.Close(); } } } } // stara koda /* private void statusnaVSprememba() { if (statusnaVrstica.Visible) { statusnaVrsticaToolStripMenuItem.Checked = false; statusnaVrstica.Visible = false; } else { statusnaVrsticaToolStripMenuItem.Checked = true; statusnaVrstica.Visible = true; } } private void statusnaVPosodobi() { int statusBarLine = txtBlokc.GetLineFromCharIndex(txtBlokc.GetFirstCharIndexOfCurrentLine()); int statusBarColumn = txtBlokc.SelectionStart - txtBlokc.GetFirstCharIndexOfCurrentLine(); lblStatusBar.Text = "Ln " + statusBarLine.ToString() + ", Col " + statusBarColumn.ToString(); } private void txtBlokc_Changed (object sender, EventArgs e) { this.statusnaVPosodobi(); } private void statusnaVrsticaToolStripMenuItem_Click(object sender, EventArgs e) { statusnaVSprememba(); } */
Python
UTF-8
2,097
2.984375
3
[]
no_license
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # "Project Name" : "PyPostgres" # # "File Name" : "postconn" # # "Author" : "rishabhzn200" # # "Date of Creation" : "Aug-29-2018" # # "Time of Creation" : "5:19 PM" # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import psycopg2 as postgreconn try: # connect to database con = postgreconn.connect("dbname='postgres' user='rishabhzn200' host='localhost' password=''") con.autocommit = True cur = con.cursor() cur.execute("""create database test""") cur.close() con.close() # open database test contest = postgreconn.connect("dbname='test' user='rishabhzn200' host='localhost' password=''") contest.autocommit = True cur = contest.cursor() # Create 3 tables and add values # Create Table tbl1 = """CREATE TABLE USERS(USERID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL);""" tbl2 = """CREATE TABLE MOVIES (MOVIEID INT PRIMARY KEY NOT NULL, TITLE TEXT NOT NULL, GENRE TEXT);""" tbl3 = """CREATE TABLE RATINGS(USERID INT REFERENCES USERS(USERID), NOVIEID INT REFERENCES MOVIES(MOVIEID), RATING NUMERIC NOT NULL CHECK(RATING>=0 AND RATING<=5));""" for tbl in [tbl1, tbl2, tbl3]: cur.execute(tbl) # # insert values # User table users = [(1, 'David'), (2, 'Eric'), (3, 'Kevin')] for userid, user in users: cur.execute(f"INSERT INTO users VALUES ({userid}, '{user}');") # Movies table # Insert from the file cur.execute(f"COPY MOVIES FROM '/Users/rishabhzn200/movies.dat' delimiter '_';") # Ratings Table allratings = [(1, 122, 5.0), (1, 185, 4.5), (2, 231, 4.0), (2, 294, 3.5), (3, 316, 3.0)] for uid, movieid, rating in allratings: cur.execute(f"insert into ratings VALUES ({uid}, {movieid}, {rating});") except: print("Error Occured")
Rust
UTF-8
2,793
2.921875
3
[]
no_license
extern crate common; extern crate intcode; use std::collections::HashMap; const COLOR_BLACK: i64 = 0; const COLOR_WHITE: i64 = 1; const TURN_LEFT: i64 = 0; const TURN_RIGHT: i64 = 1; const DIR_N: i64 = 0; const DIR_E: i64 = 1; const DIR_S: i64 = 2; const DIR_W: i64 = 3; const NUM_DIRS: i64 = 4; fn run_painter(mut memory: Vec<i64>, start_color: i64) -> HashMap<(i64, i64), i64> { let mut ptr = 0; let mut relative_base = 0; let mut dir = DIR_N; let mut pos: (i64, i64) = (0, 0); let mut color_pos: HashMap<(i64, i64), i64> = HashMap::new(); color_pos.entry(pos).or_insert(start_color); loop { let color = color_pos.entry(pos).or_insert(COLOR_BLACK); let (mem_new, output_numbers, ptr_new, relative_base_new, halted) = intcode::run(memory.clone(), [*color as i64].to_vec(), ptr, relative_base); assert_eq!(output_numbers.len(), 2); let color_new = output_numbers[0]; let turn = output_numbers[1]; color_pos.insert(pos, color_new); assert!(color_new == COLOR_BLACK || color_new == COLOR_WHITE); assert!(turn == TURN_LEFT || turn == TURN_RIGHT); if turn == TURN_LEFT { dir = (dir + NUM_DIRS - 1) % NUM_DIRS; } else { dir = (dir + 1) % NUM_DIRS; } if dir == DIR_N { pos = (pos.0, pos.1 - 1); } else if dir == DIR_W { pos = (pos.0 - 1, pos.1); } else if dir == DIR_E { pos = (pos.0 + 1, pos.1); } else if dir == DIR_S { pos = (pos.0, pos.1 + 1); } if halted { break; } ptr = ptr_new; memory = mem_new; relative_base = relative_base_new; } return color_pos; } fn draw_map(map: HashMap<(i64, i64), i64>) -> String { let mut min = (0, 0); let mut max = (0, 0); for (k, _v) in &map { min = (std::cmp::min(min.0, k.0), std::cmp::min(min.1, k.1)); max = (std::cmp::max(max.0, k.0), std::cmp::max(max.1, k.1)); } let w = 1 + max.0 - min.0; let h = 1 + max.1 - min.1; let mut s = String::new(); for y in 0..h { for x in 0..w { let color = map .get(&(min.0 + x, min.1 + y)) .unwrap_or(&COLOR_BLACK) .clone(); s.push(if color == COLOR_BLACK { ' ' } else { '#' }); } s.push('\n') } return s; } pub fn solve() { let input = common::read_file("2019/day11/input"); let map_first = run_painter(intcode::parse_input(input.as_str()), COLOR_BLACK); let map_second = run_painter(intcode::parse_input(input.as_str()), COLOR_WHITE); println!("Part one: {}", map_first.len()); print!("Part two:\n{}", draw_map(map_second)); }
Java
UTF-8
11,920
1.765625
2
[]
no_license
package com.example.adityadesai.cngcustomer.Activities; import android.app.Dialog; import android.content.Intent; import android.net.Uri; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.RatingBar; import android.widget.TextView; import com.example.adityadesai.cngcustomer.Adapters.CategoryAdapter; import com.example.adityadesai.cngcustomer.Adapters.CustomPagerAdapter; import com.example.adityadesai.cngcustomer.Adapters.MenuRecyclerAdapter; import com.example.adityadesai.cngcustomer.Objects.MenuItem; import com.example.adityadesai.cngcustomer.R; import java.util.ArrayList; import me.relex.circleindicator.CircleIndicator; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; public class ShopDetailsActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener { CustomPagerAdapter mCustomPagerAdapter; ViewPager mViewPager; private RecyclerView mRecyclerView; private GridLayoutManager mGridLayoutManager; private MenuRecyclerAdapter mAdapter; ArrayAdapter mArrayAdapter; private String name; public static String address; public static String phone; public static String industry; public static String id; public static ArrayList<String> url; public static String ownerid; public static ArrayList<String> offers; private ListView mListView; //public static ArrayList<ItemDetail> mItemDetails; int isFavourite=0; private ArrayList<MenuItem> mMenuItems; private FirebaseDatabase mFirebaseDatabase; private DatabaseReference mItemDatabaseReference; private ChildEventListener mChildEventListener; private FirebaseStorage mFirebaseStorage; private StorageReference mStorageReference; private ValueEventListener mValueEventListener; //This is our tablayout private TabLayout tabLayout; //This is our viewPager private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shop_details); offers = new ArrayList<String>(); Intent i = getIntent(); name = i.getStringExtra("shopName"); address = i.getStringExtra("shopAddress"); phone = i.getStringExtra("shopPhone"); industry=i.getStringExtra("industry_name"); id = i.getStringExtra("shop_id"); if(i.getStringArrayListExtra("shop_url") != null) { url.addAll(0,i.getStringArrayListExtra("shop_url")); } ownerid = i.getStringExtra("owner_id"); if(i.getStringArrayListExtra("offers") != null) { offers.addAll(0, i.getStringArrayListExtra("offers")); } //Initializing viewPager viewPager = (ViewPager) findViewById(R.id.viewpager); //Creating our pager adapter CategoryAdapter adapter = new CategoryAdapter(this,getSupportFragmentManager()); //Adding adapter to pager viewPager.setAdapter(adapter); tabLayout = (TabLayout) findViewById(R.id.tabs); //Adding onTabSelectedListener to swipe views tabLayout.setupWithViewPager(viewPager); NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nest_scrollview); scrollView.setFillViewport (true); // Set title android.support.design.widget.CollapsingToolbarLayout toolbar=(android.support.design.widget.CollapsingToolbarLayout)findViewById(R.id.collapsingToolbar); toolbar.setTitle(name); mCustomPagerAdapter = new CustomPagerAdapter(this); mViewPager = (ViewPager) findViewById(R.id.shop_image_pager); mViewPager.setAdapter(mCustomPagerAdapter); CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator); indicator.setViewPager(mViewPager); //mRecyclerView = (RecyclerView) findViewById(R.id.shop_menu_recycler); //mGridLayoutManager=new GridLayoutManager(this,2); //mRecyclerView.setLayoutManager(mGridLayoutManager); mMenuItems= new ArrayList<>(); mFirebaseDatabase = FirebaseDatabase.getInstance(); mItemDatabaseReference = mFirebaseDatabase.getReference().child(industry); /*mMenuItems.add(new MenuItem("Item A")); mMenuItems.add(new MenuItem("Item B")); mMenuItems.add(new MenuItem("Item C")); mMenuItems.add(new MenuItem("Item D")); mMenuItems.add(new MenuItem("Item E")); mMenuItems.add(new MenuItem("Item F")); mMenuItems.add(new MenuItem("Item G")); mMenuItems.add(new MenuItem("Item H")); mMenuItems.add(new MenuItem("Item I")); mMenuItems.add(new MenuItem("Item J"));*/ // fetchItemList fIL = new fetchItemList(); // fIL.execute(); /******* A sample on how to push data********/ // mItemDatabaseReference.push().setValue(new MenuItem("Rice")); //mItemDatabaseReference.push().setValue(new MenuItem("Oil")); } //END OF onCreate// // public void updateUI(){ // mAdapter = new MenuRecyclerAdapter(mMenuItems); // mRecyclerView.setAdapter(mAdapter); // } // public class fetchItemList extends AsyncTask<Void,Void,ArrayList<MenuItem>> { // @Override // protected ArrayList<MenuItem> doInBackground(Void... params) { // // mValueEventListener = new ValueEventListener() { // @Override // public void onDataChange(DataSnapshot dataSnapshot) { // mMenuItems.clear(); // for(DataSnapshot snapshot : dataSnapshot.getChildren()){ // String iName = (String) snapshot.child("itemName").getValue(); // /*Trapping the price and Description????How???*/ // //ItemDetail itemDetail = new ItemDetail(iName,iPrice,iDesc); // //mItemDetails.add(itemDetail); // if(iName != null) { // mMenuItems.add(new MenuItem(iName)); // } // // } // updateUI(); // } // // @Override // public void onCancelled(DatabaseError databaseError) { // // } // }; // // mItemDatabaseReference.addValueEventListener(mValueEventListener); // return null; // } // } public String getId(){ return id; } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } public void goToAddress(View v){ //NY for now double latitude = 40.714728; double longitude = -73.998672; String label = name; String uriBegin = "geo:" + latitude + "," + longitude; String query = latitude + "," + longitude + "(" + label + ")"; String encodedQuery = Uri.encode(query); String uriString = uriBegin + "?q=" + encodedQuery + "&z=16"; Uri uri = Uri.parse(uriString); Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri); startActivity(intent); } public void callPhone(View v){ Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:"+phone)); startActivity(intent); } public void favouriteChecked(View v){ com.github.clans.fab.FloatingActionButton favFab=(com.github.clans.fab.FloatingActionButton)findViewById(R.id.fab22); if(isFavourite==0){ favFab.setImageResource(R.drawable.ic_favorite_white_24px); isFavourite=1; } else{ favFab.setImageResource(R.drawable.ic_favorite_border_white_24px); isFavourite=0; } } public void ratingCheck(View v){ final Dialog rankDialog = new Dialog(ShopDetailsActivity.this, R.style.Theme_AppCompat_Light_Dialog); rankDialog.setContentView(R.layout.rank_dialog); rankDialog.setCancelable(true); final RatingBar ratingBar = (RatingBar)rankDialog.findViewById(R.id.dialog_ratingbar); ratingBar.setRating(0); TextView text = (TextView) rankDialog.findViewById(R.id.rank_dialog_text1); text.setText(name); ImageButton updateButton = (ImageButton) rankDialog.findViewById(R.id.rank_dialog_button); updateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mItemDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for(DataSnapshot snapshot: dataSnapshot.getChildren()){ //Log.v("tag",snapshot.child("shop_id")); if(snapshot.hasChild("shop_id") && snapshot.child("shop_id").getValue().toString().equals(id)){ String presentPoints; String presentNum; presentPoints = snapshot.child("totalRatePoints").getValue().toString(); presentNum = snapshot.child("numRates").getValue().toString(); // Log.v("tag",presentPoints); // Log.v("tag",presentNum); // Log.v("tag",Float.toString(Float.parseFloat(presentPoints)+ratingBar.getRating())); // Log.v("tag",Integer.toString(Integer.parseInt(presentNum)+1)); //FirebaseDatabase.getInstance().getReference().child(industry).child(snapshot.getKey()).child("totalRatePoints").setValue(Float.toString(Float.parseFloat(presentPoints)+ratingBar.getRating())); snapshot.getRef().child("totalRatePoints").setValue(Float.toString(Float.parseFloat(presentPoints)+ratingBar.getRating())); snapshot.getRef().child("numRates").setValue(Integer.toString(Integer.parseInt(presentNum)+1)); rankDialog.dismiss(); break; } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } }); //now that the dialog is set up, it's time to show it rankDialog.show(); } @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }
Markdown
UTF-8
1,549
2.953125
3
[]
no_license
## 准备工作 1. 文本编辑器 用来写c程序的,常见文本编辑器sublime、notepad、vim。 通过编辑器创建的为源文件,C语言的源文件通常使用'.c'为扩展名 2. C编译器 为了让源文件的代码对机器可读,需要进行编译,转为机器语言。最常见的编译器有CNU的C/C++编译器。 ### 编译器安装 #### Unix/Linux 如果使用Linux或者unix,可以先使用下面命令检查系统是否已经安装GCC ```c $ gcc -v ``` 如果有GCC会显示相应版本消息,如果没有安装,可以按照<http://gcc.gnu.org/install/>上说明进行安装 #### Mac OS 如果使用的是 Mac OS X,最快捷的获取 GCC 的方法是从苹果的网站上下载 Xcode 开发环境,并按照安装说明进行安装。一旦安装上 Xcode,您就能使用 GNU 编译器。 Xcode 目前可从 [developer.apple.com/technologies/tools/](http://developer.apple.com/technologies/tools/) 上下载。 #### Windows Windows 上安装 GCC,需要安装 MinGW。请访问 MinGW 的主页 [www.mingw.org](http://www.mingw.org/),进入下载页。 当安装 MinWG 时,您至少要安装 gcc-core、gcc-g++、binutils 和 MinGW runtime,但是一般情况下都会安装更多其他的项。 添加您安装的 MinGW 的 bin 子目录到您的 **PATH** 环境变量中,这样您就可以在命令行中通过简单的名称来指定这些工具。 当完成安装时,您可以从 Windows 命令行上运行 gcc、g++、ar、ranlib、dlltool 和其他一些 GNU 工具
C++
GB18030
6,763
3.421875
3
[]
no_license
#pragma once #include <utility> #include <memory> #include <string> #include <iostream> #include <stdexcept> #include <initializer_list> #include <algorithm> class StrVec { friend std::ostream& print(std::ostream& os, StrVec& str); // 14.16 friend bool operator==(const StrVec&, const StrVec&); friend bool operator!=(const StrVec&, const StrVec&); // 14.18 friend bool operator<(const StrVec&, const StrVec&); friend bool operator<=(const StrVec&, const StrVec&); friend bool operator>(const StrVec&, const StrVec&); friend bool operator>=(const StrVec&, const StrVec&); public: StrVec() :elements(nullptr), first_free(nullptr), cap(nullptr) {} StrVec(const std::initializer_list<std::string>&); StrVec(const StrVec&); StrVec& operator=(const StrVec&); StrVec(StrVec&&) noexcept; StrVec& operator=(StrVec&&) noexcept; ~StrVec(); StrVec& operator=(const std::initializer_list<std::string>&); // 14.26 std::string& operator[](std::size_t n) { return elements[n]; } const std::string& operator[](std::size_t n) const { return elements[n]; } size_t size() const { return first_free - elements; } size_t capacity() const { return cap - elements; } std::string* begin() const { return elements; } std::string* end() const { return first_free; } void push_back(const std::string&); void resize(std::size_t); void resize(std::size_t, const std::string&); void reserve(std::size_t); private: std::string* elements; std::string* first_free; std::string* cap; static std::allocator<std::string> alloc; void chk_n_alloc(); std::pair<std::string*, std::string*> alloc_n_copy(const std::string*, const std::string*); void free(); void reallocate(std::size_t); }; std::allocator<std::string> StrVec::alloc; void StrVec::chk_n_alloc() { auto now_size = size(); if (now_size == 0) // ĬϷĸԪڴ档 reallocate(4); else if (now_size == capacity()) reallocate(2 * now_size); } std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string* b, const std::string* e) { auto data = alloc.allocate(e - b); return { data, std::uninitialized_copy(b, e, data) }; } void StrVec::free() { /* if (elements) { for (auto p = first_free; p != elements;) alloc.destroy(--p); alloc.deallocate(elements, cap - elements); } */ // for_each lambda д if (elements) { auto dealloc = [](std::string& p) {alloc.destroy(&p); }; std::for_each(elements, first_free, dealloc); alloc.deallocate(elements, cap - elements); } } void StrVec::reallocate(std::size_t new_capacity) { // ռ auto new_data = alloc.allocate(new_capacity); //Ӿɿռƶ¿ռ /* for (std::size_t i = 0; i < size(); ++i) alloc.construct(dest++, std::move(*src++)); free(); */ auto last = std::uninitialized_copy(std::make_move_iterator(begin()), std::make_move_iterator(end()), new_data); free(); elements = new_data; first_free = last; cap = new_data + new_capacity; } StrVec::StrVec(const std::initializer_list<std::string>& ini_list_str) { auto new_data = alloc_n_copy(ini_list_str.begin(), ini_list_str.end()); elements = new_data.first; first_free = new_data.second; cap = new_data.second; } StrVec::StrVec(const StrVec& s) { auto newdata = alloc_n_copy(s.begin(), s.end()); elements = newdata.first; first_free = newdata.second; cap = newdata.second; } StrVec::StrVec(StrVec&& s) noexcept :elements(s.elements), first_free(s.first_free), cap(s.cap) { s.elements = s.first_free = s.cap = nullptr; } StrVec& StrVec::operator=(const StrVec& rhs) { auto data = alloc_n_copy(rhs.begin(), rhs.end()); free(); elements = data.first; first_free = data.second; cap = data.second; return *this; } StrVec& StrVec::operator=(StrVec&& rhs) noexcept { if (this != &rhs) { free(); elements = rhs.elements; first_free = rhs.first_free; cap = rhs.cap; rhs.elements = rhs.first_free = rhs.cap = nullptr; } return *this; } StrVec::~StrVec() { free(); } void StrVec::push_back(const std::string& str) { chk_n_alloc(); alloc.construct(first_free++, str); } void StrVec::resize(std::size_t new_size) { resize(new_size, ""); } void StrVec::resize(std::size_t new_size, const std::string& str) { // resize() new_size Ϊ 0 ȼڵ free() ͷڴ档 if (new_size == 0) { free(); return; } if (new_size < 0) { throw std::runtime_error("resize ֵǸ"); return; } // ʱ· if (new_size == size()) return; // resize IJڵǰֻǻ reserve() if (new_size > capacity()) reserve(new_size); auto now_size = size(); if (new_size > now_size) // ٶĬϹ for (std::size_t i = 0; i < new_size - now_size; ++i) alloc.construct(first_free++, str); else if (new_size < now_size) for (std::size_t i = 0; i < now_size - new_size; ++i) alloc.destroy(--first_free); } void StrVec::reserve(std::size_t new_capacity) { auto now_capacity = capacity(); // reserve IJȵǰ capacity СʲôҲ if (now_capacity < new_capacity) reallocate(new_capacity); } std::ostream& print(std::ostream& os, StrVec& str) { for (auto p = str.elements; p != str.end(); ++p) std::cout << *p << std::endl; std::cout << std::endl; return os; } StrVec& StrVec::operator=(const std::initializer_list<std::string>& ini_list_str) { auto new_data = alloc_n_copy(ini_list_str.begin(), ini_list_str.end()); free(); elements = new_data.first; first_free = new_data.second; cap = new_data.second; return *this; } bool operator==(const StrVec& lhs, const StrVec& rhs) { if (lhs.size() != rhs.size()) return false; for (auto src_lhs = lhs.begin(), src_rhs = rhs.begin(); src_lhs != lhs.end(); ++src_lhs, ++src_rhs) { if (*src_lhs != *src_rhs) return false; } return true; } bool operator!=(const StrVec& lhs, const StrVec& rhs) { return !(lhs == rhs); } bool operator<(const StrVec& lhs, const StrVec& rhs) { // ҲȽϵΪСֵ< Ϊ false if (rhs.elements == nullptr) return false; if (lhs.elements == nullptr) return true; for (auto src_lhs = lhs.begin(), src_rhs = rhs.begin(); src_lhs != lhs.end() && src_rhs != rhs.end(); ++src_lhs, ++src_rhs) { if (*src_lhs < *src_rhs) return true; if (*src_lhs > *src_rhs) return false; } // ѭʱбȽϹԪضȣôͱȽϳ if (lhs.size() < rhs.size()) return true; else return false; } bool operator>(const StrVec& lhs, const StrVec& rhs) { return rhs < lhs; } bool operator<=(const StrVec& lhs, const StrVec& rhs) { return !(rhs < lhs); } bool operator>=(const StrVec& lhs, const StrVec& rhs) { return !(lhs < rhs); }
Swift
UTF-8
1,610
2.875
3
[]
no_license
// // MasuratoareRow.swift // Statie Meteo // // Created by Narcis Zait on 12/08/2020. // Copyright © 2020 Alex Paval. All rights reserved. // import SwiftUI struct MasuratoareRow: View { var masuratoare: Masuratoare var body: some View { VStack(alignment: .leading) { Spacer() HStack { Text("Temperatura: ") .bold() .foregroundColor(.white) Spacer() Text("\(masuratoare.temperatura) °C") .foregroundColor(.white) }.padding(8) HStack { Text("Umiditate: ") .bold() .foregroundColor(.white) Spacer() Text("\(masuratoare.umiditate) %") .foregroundColor(.white) }.padding(8) HStack { Text("Vant: ") .bold() .foregroundColor(.white) Spacer() Text("\(masuratoare.vant) m/s") .foregroundColor(.white) }.padding(8) Spacer() }.background( LinearGradient(gradient: Gradient(colors: [Color(red: 0.64, green: 0.67, blue: 0.72), Color(red: 0.42, green: 0.46, blue: 0.54)]), startPoint: .leading, endPoint: .trailing)) .cornerRadius(15.0) } } //struct MasuratoareRow_Previews: PreviewProvider { // static var previews: some View { // MasuratoareRow(masuratoare: Masuratoare()) // } //}
Java
UTF-8
408
2.078125
2
[]
no_license
package be.felixdeswaef.reminder; import java.sql.Time; import java.sql.Timestamp; public class task{ public int id; public String name; public Timestamp deadline; public Timestamp creationdate; public Boolean checked; public Boolean hidden; public String description; public int completion; public task(String nname){ id = -1; name = nname; } }
C#
UTF-8
768
2.65625
3
[]
no_license
namespace Shp2JSON { using System.Diagnostics; using System.IO; using System.Linq; class Program { static void Main(string[] args) { var root = args.Any() ? args.Single() : @"C:\Users\Bon\Desktop\Corine Dissolve"; var filePaths = Directory.GetFiles(root, "*.shp", SearchOption.AllDirectories); foreach (var path in filePaths) { var outputPath = string.Format(@"{0}\JSON\{1}.geojson", root, Path.GetFileNameWithoutExtension(path)); Process.Start( @"C:\Program Files\QGIS Brighton\bin\ogr2ogr.exe", string.Format(" -f GeoJSON -t_srs crs:84 \"{0}\" \"{1}\"", outputPath, path)); } } } }
Markdown
UTF-8
366
2.53125
3
[]
no_license
#### Elasticsearch Notes This box is special in that it sets up several VMs in tandem which form an Elasticsearch cluster. You can edit the Vagrantfile to only spin up one, or maybe 3 or 5 boxes however you like. Be careful on the hardware settings. ES requires at *least* 2GB of memory to function or you risk crashing the JVM from not having enough free memory.
JavaScript
UTF-8
848
3.078125
3
[]
no_license
function addNewComment(name, email, text, date){ var newComment = $("#comments div:eq(0)").clone(); newComment.find('.comment-title').text(name); newComment.find('.comment-email').text(email); newComment.find('.comment-text').text(text); newComment.find('.comment-date').text(date); return newComment; } function loadAllComments(){ $.get('api.php?action=getNew', function(result){ var resultComments = JSON.parse(result); var comments = []; for (var i = 0; i < resultComments.length; i++) { var newComment = addNewComment(resultComments[i].name, resultComments[i].email, resultComments[i].text, resultComments[i].date); // name, email, text, date comments.push(newComment); } $('#comments').children().remove(); $('#comments').append(comments); }); } // loadAllComments(); setInterval( loadAllComments, 1000 );
TypeScript
UTF-8
293
2.609375
3
[ "MIT" ]
permissive
import {RolePermissions} from './role-permissions'; /** * Basic role class, may be extended as needed */ export class Role { /** * Identifier of the role */ id: string; /** * Permissions attached to this role */ permissions: RolePermissions; }
C
UTF-8
280
3.296875
3
[]
no_license
#include<stdio.h> int main() { int n ; printf("Enter N ?") ; scanf("%d", &n) ; int count = 1 ; // initialization while(count <= n) // condition { printf("%d\n" , count) ; count = count + 1 ; // re-initialization } return 0 ; }
C#
UTF-8
900
2.515625
3
[]
no_license
using myPT.Core.Interfaces.Model; using myPT.Core.Interfaces.View; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace myPT.Core.Implementation.Presenter.Mapper { class HomeMapper : Common.Mapper { public HomeMapper() { Setup(); } public void Setup() { AddToConfig<IDataModel, IHomeView>((s, t) => MapModelToView((IDataModel)s, (IHomeView)t)); AddToConfig<IHomeView, IDataModel>((s, t) => MapViewToModel((IHomeView)s, (IDataModel)t)); } private void MapModelToView(IDataModel list, IHomeView mainView) { mainView.Programs = list.Programs; } private void MapViewToModel(IHomeView mainView, IDataModel model) { model.Programs = mainView.Programs; } } }
C++
UTF-8
744
2.5625
3
[]
no_license
// // Created by swk on 2019-08-23. // #include "stringmatch.h" namespace happycoding { class BfMatch : public StringMatch{ public: int indexOf (const char* text, unsigned int textSize, const char* pattern, unsigned int patternSize) override{ for (unsigned int i = 0; i < textSize - patternSize + 1; ++i) { bool isMatched = true; for (unsigned int j = 0; j < patternSize; ++j) { if (text[i + j] != pattern[j]) { isMatched = false; break; } } if (isMatched) return i; } return -1; } }; }
C#
UTF-8
944
2.625
3
[]
no_license
using System.Globalization; using BlockChain.Extensions; namespace BlockChain { public class TransactionIn { public OutPoint PreviousOutput { get; } public SignatureScript Script { get; } public uint Sequence { get; } public Transaction Transaction { get; set; } public TransactionOut TxOut { get; set; } public TransactionIn(byte[] buffer, ref int index, Transaction transaction){ PreviousOutput = buffer.ToOutPoint(ref index); Script = buffer.ToSignatureScript(ref index); Sequence = buffer.ToUInt32(ref index); Transaction = transaction; } public override string ToString() { if (TxOut != null){ return $"TxIn: {TxOut.Script.Address}"; } if (Sequence == 0xFFFFFFFF) return "TxIn: (none)"; return $"TxIn: {Sequence}"; } } }
Python
UTF-8
4,465
2.953125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Jun 11 20:32:12 2017 @author: Daniel """ import numpy #loading our favorite library from matplotlib import pyplot #and the useful plotting library from matplotlib import animation import time t0 = time.time() height = 1 length = 1 ######################################################## def init(): line.set_data([], []) return line, #fig = pyplot.figure() #ax = pyplot.axes(xlim=(0, length), ylim=(0, height)) #line, = ax.plot([], [], lw=2) ######################################################### for w in range(1,2): nx = 1001 # Number of mesh points dx = length / float(nx - 1) # Distance between mesh points nt = 1000 # The number of timesteps we want to calculate dt = 0.0001 # Size of the time steps Stg = 1000.0 # Stanton Number of the gas phase Stl = 200.0 # Stanton Numer of the liquid phase Sts = 4000.0 # Stanton Numer of the solid phase Stjump = 80.0 # Stanton Numer of the jump conditional phase rho_lv = 141.0 # Ratio of the liquid phase to the vapor phase Tsat = 0.99 delta_theta = 1.0 - Tsat # Change in theta in the jump conditional phase e.g. (1-0.99) rho = 141.0 # Non-dimensionalized density ratio from liquid to vapor vel = 1.0 # Non-dim. velocity Tl = numpy.zeros(nx) # Initializing temperature of the liquid phase Ts = numpy.zeros(nx) # Initializing temperature of the solid phase f = numpy.ones(nx) # Initializing vapor quality rho = numpy.ones(nx) # Initializing density dTdt = numpy.zeros(nx) # Initializing derivative of temperature of with time v = numpy.zeros(nx) # Initializing velocity dvdx = numpy.zeros(nx) # Initializing derivative of velocity with distance v[0] = 1 Tl[0] = 1 Ts[0] = 1 #u[int(0.5 / dx):int(1.0 / dx + 1)] = 2 #setting u = 2 between 0.5 and 1 as per our I.C.s Tln = numpy.ones(nx) #our placeholder array, Tln, to advance the solution in time Tsn = numpy.ones(nx) #our placeholder array, Tsn, to advance the solution in time for n in range(nt): #iterate through time #def animate(j): Tln = Tl.copy() Tsn = Ts.copy() ##copy the existing values of T into Tn for i in range(1, nx - 1): if Tl[i]>=1.0: rho[i] = 1.0 v[i] = 1.0 # v[i] = v[i-1] Tl[i] = Tln[i] - Stg * dt * (Tln[i]-Tsn[i]) - (dt/float(dx))*(Tln[i]-Tln[i-1]) Ts[i] = Tsn[i] - Sts * dt * (Tln[i]-Tsn[i]) elif Tl[i]<Tsat+0.01 and Tl[i]>Tsat: rho[i] = 1 + (1-(Tl[i]-Tsat)/delta_theta)*rho_lv dTdt[i] = -Stjump*(Tl[i]-Ts[i])-(Tl[i]-Tl[i-1])/dx v[i] = v[i-1] + (((rho_lv/delta_theta)*(dTdt[i]+v[i-1]*(Tl[i]-Tl[i-1])/dx))/rho[i])*dx dvdx[i] = (((rho_lv/delta_theta)*(dTdt[i]+v[i]*(Tl[i]-Tl[i-1])/dx))/rho[i]) f[i] = (rho_lv/delta_theta)*(Tl[i]-Tsat)*(dTdt[i]+v[i]*((Tl[i]-Tl[i-1])/dx)) Tl[i] = Tl[i] + dt*((Stjump*(-Tl[i]+Ts[i]))/rho[i]+f[i]/rho[i]-(v[i]*(Tl[i]-Tl[i-1])/dx)-(Tl[i]-Tsat)*dvdx[i]) Ts[i] = Ts[i] + Sts * dt * (Tl[i]-Ts[i]) elif Tl[i] < Tsat: rho[i] = 141.0 v[i] = 1.0/141.0 # v[i] = v[i-1] Tl[i] = Tl[i] - Stl * dt * (Tl[i]-Ts[i]) - (dt/dx)*(Tl[i]-Tl[i-1]) Ts[i] = Ts[i] + Sts * dt * (Tl[i]-Ts[i]) v[nx-1] = v[nx-2] rho[nx-1] = rho[nx-2] # line.set_data(numpy.linspace(0, length, nx), theta) # # return line, #pyplot.figure(1) #pyplot.semilogx(numpy.linspace(0, 2, nx), theta) # pyplot.figure(2) # pyplot.semilogx(numpy.linspace(0, length, nx), Tl) # pyplot.semilogx(numpy.linspace(0.001, length, nx), P) pyplot.plot(numpy.linspace(0, 1, nx), Tl); pyplot.plot(numpy.linspace(0, 1, nx), v); # call the animator. blit=True means only re-draw the parts that have changed. #anim = animation.FuncAnimation(fig, animate, init_func=init, # frames=20000, interval=20, blit=True) t1 = time.time() total = t1-t0 print total
Java
UTF-8
1,343
1.984375
2
[ "Apache-2.0" ]
permissive
package com.shizhefei.meizhi.modle; import android.app.Application; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.shizhefei.meizhi.view.LoadViewFactory; import com.shizhefei.mvc.MVCHelper; /** * Created by LuckyJayce on 2016/7/12. */ public class AppContext extends Application { @Override public void onCreate() { super.onCreate(); MVCHelper.setLoadViewFractory(new LoadViewFactory()); // 初始化图片加载 if (!ImageLoader.getInstance().isInited()) { ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .threadPriority(Thread.NORM_PRIORITY - 2).diskCacheFileNameGenerator(new Md5FileNameGenerator()) .diskCacheSize(50 * 1024 * 1024) // 50 // Mb .tasksProcessingOrder(QueueProcessingType.LIFO).writeDebugLogs() // Remove // for // release // app .build(); ImageLoader.getInstance().init(config); } } }
Java
UTF-8
359
1.65625
2
[]
no_license
package com.microservices.SOAPWebserviceClient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SoapWebserviceClientApplication { public static void main(String[] args) { SpringApplication.run(SoapWebserviceClientApplication.class, args); } }
Python
UTF-8
15,228
2.578125
3
[]
no_license
# db를 관리하는 code import psycopg2 as pg import psycopg2.extras import json import requests from apicall import hosp_list from pprint import pprint from datetime import datetime from urllib.request import urlopen from bs4 import BeautifulSoup pg_local = { 'host': "localhost", # localhost 'user': "postgres", # dbuser 'dbname': "postgres", # dbapp 'password': "password" } db_connector = pg_local connect_string = "host={host} user={user} dbname={dbname} password={password}".format( **db_connector) # - 정적인 정보들 - # <회원 정보 Table> # 이메일, 비밀번호, 타입(환자, 병원관리자, 상점주인) # <병원 정보 Table> # 위도, 경도, 진료시간, 의원 수, 진료 과목, 이름, 주소 # <약국 정보 Table> # 위도, 경도, 처방시간(from 0 to 24), 이름, 주소, # id, 이름, 휴대폰 번호를 가지는 Table 생성 def create_customersInfo_table(): sql = f'''CREATE TABLE customers_Info ( id SERIAL NOT NULL, name varchar(20) NOT NULL, phone_number varchar(20) NOT NULL PRIMARY KEY, local varchar(20) NOT NULL, domain varchar(20) NOT NULL, password varchar(20) NOT NULL, type varchar(20) DEFAULT 'patient' ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) # customers정보 초기화 def init_customersInfo_table(): try: conn = pg.connect(connect_string) cur = conn.cursor() f = open("C:\\Users\\Public\\customers.csv", "r", encoding='UTF-8') for line in f: tmp = line.split(',') name = tmp[0] phone_number = tmp[1] local = tmp[2] domain = tmp[3] password = tmp[4] lat = tmp[len(tmp)-2] tmp = tmp[len(tmp)-1].split('\n') lng = tmp[0] print(lng) sql = f'''INSERT INTO customers_Info(name, phone_number, local, domain, password) VALUES (\'{name}\', \'{phone_number}\', \'{local}\' , \'{domain}\', \'{password}\'); ''' print(sql) cur.execute(sql) f.close() conn.commit() conn.close() # print(sql) except pg.OperationalError as e: print(e) return -1 return 1; # 전문의 의원 수(doctor_cnt), 진료 과목(diagnosis_kinds), 이름(name), 주소(addr), 위도(XPos), 경도(YPos), 거리(distance) def create_hospInfo_table(): sql = f'''CREATE TABLE hosp_Info ( id SERIAL NOT NULL, name varchar(100) NOT NULL PRIMARY KEY, addr varchar(100) NOT NULL, lat double precision NOT NULL, lng double precision NOT NULL, distance double precision NOT NULL, weekday_open integer NOT NULL, weekday_close integer NOT NULL, weekend_open integer NOT NULL, weekend_close integer NOT NULL, doctor_cnt integer NOT NULL, diagnosis_kinds varchar(100) NOT NULL ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) # 병원 정보 Table def init_hospInfo_table(): json = hosp_list() hosp = json['response']['body']['items']['item'] try: conn = pg.connect(connect_string) cur = conn.cursor() for data in hosp: # print(data) name = data['yadmNm'] addr = data['addr'] lng = data['XPos'] lat = data['YPos'] weekday_open = 8 weekday_close = 19 weekend_open = 13 weekend_close = 17 distance = data['distance'] doctor_cnt = data['sdrCnt'] diagnosis_kinds = "종합과목 진료(한방, 치과제외)" sql = f'''INSERT INTO hosp_Info(name, addr, lat, lng, distance, weekday_open, weekday_close, weekend_open, weekend_close, doctor_cnt, diagnosis_kinds) VALUES (\'{name}\', \'{addr}\', \'{lat}\', \'{lng}\', \'{distance}\' , \'{weekday_open}\', \'{weekday_close}\', \'{weekend_open}\' , \'{weekend_close}\', \'{doctor_cnt}\', \'{diagnosis_kinds}\'); ''' print(sql) cur.execute(sql) conn.commit() conn.close() # print(sql) except pg.OperationalError as e: print(e) return -1 return 1; # 약국 정보 테이블 # 이름(name), 주소(addr), 위도(XPos), 경도(YPos), 거리(distance), 오픈시간, 처방가능여부 def create_pharmInfo_table(): sql = f'''CREATE TABLE pharm_Info ( id SERIAL NOT NULL, name varchar(100) NOT NULL PRIMARY KEY, addr varchar(100) NOT NULL, lat double precision NOT NULL, lng double precision NOT NULL, distance double precision NOT NULL, weekday_open integer NOT NULL, weekday_close integer NOT NULL, weekend_open integer NOT NULL, weekend_close integer NOT NULL, prescribe_possible varchar(100) DEFAULT 'unknown' ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) # 약국 정보 Table def init_hospInfo_table(): json = hosp_list() hosp = json['response']['body']['items']['item'] try: conn = pg.connect(connect_string) cur = conn.cursor() for data in hosp: # print(data) name = data['yadmNm'] addr = data['addr'] lng = data['XPos'] lat = data['YPos'] weekday_open = 8 weekday_close = 19 weekend_open = 13 weekend_close = 17 distance = data['distance'] doctor_cnt = data['sdrCnt'] diagnosis_kinds = "종합과목 진료(한방, 치과제외)" sql = f'''INSERT INTO hosp_Info(name, addr, lat, lng, distance, weekday_open, weekday_close, weekend_open, weekend_close, doctor_cnt, diagnosis_kinds) VALUES (\'{name}\', \'{addr}\', \'{lat}\', \'{lng}\', \'{distance}\' , \'{weekday_open}\', \'{weekday_close}\', \'{weekend_open}\' , \'{weekend_close}\', \'{doctor_cnt}\', \'{diagnosis_kinds}\'); ''' print(sql) cur.execute(sql) conn.commit() conn.close() # print(sql) except pg.OperationalError as e: print(e) return -1 return 1; # 환자 방문 기록 def create_visited_record_table(): sql = f'''CREATE TABLE visited_record ( id SERIAL NOT NULL, patient_name varchar(20) NOT NULL, institution_name varchar(20) NOT NULL, date varchar(100) NOT NULL ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) # 즐겨찾는 병원 목록 def create_favorite_hospital_table(): sql = f'''CREATE TABLE favorite_hospital ( id SERIAL NOT NULL, hospital_name varchar(20) NOT NULL, local varchar(20) NOT NULL, domain varchar(20) NOT NULL ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) # 예약 내역 def create_reservation_list_table(): sql = f'''CREATE TABLE reservation_list ( id SERIAL NOT NULL, name varchar(20) NOT NULL, phone_number varchar(20) NOT NULL, date varchar(20) NOT NULL, institution_name varchar(20) NOT NULL ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) # 발급 년월일 번호 # 환자 이름 # 병원 이름 # 처방의약품의 명칭, 1회투약량, 1일 투여횟수, 총투약일수 # 조제 연월일 # 병원 이름 # 처방 변경-수정-확인 내용 def create_description_list_table(): sql = f'''CREATE TABLE prescription_list ( id SERIAL NOT NULL, patient_name varchar(20), phone_number varchar(20), hospital_name varchar(100), hospital_date varchar(30), medicine_name varchar(20), amount_per_onetime integer, count_per_oneday integer, how_long_day integer, pharmacy_date varchar(30), pharmacy_name varchar(100), pharmacy_opinion varchar(100), pharmacy_status varchar(10) DEFAULT 'unknown' ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) def create_glass_store_table(): sql = f'''CREATE TABLE glasses_store ( lat double precision, lng double precision, name varchar(50), addr varchar(100), type varchar(10) ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) def create_glasses_description_table(): sql = f'''CREATE TABLE glasses_description ( id serial NOT NULL, hospital_date varchar(20), patient_name varchar(50), hospital_name varchar(50), r_vision varchar(10), l_vision varchar(10), fixed_r_vision varchar(10), fixed_l_vision varchar(10), galsses_date varchar(20), recommend_date varchar(20) ); ''' try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) def init_glass_store_table(): # 네이버 검색 결과 res = requests.get('https://search.naver.com/search.naver?sm=tab_hty.top&where=nexearch&query=%ED%95%9C%EC%96%91%EB%8C%80+%EC%95%88%EA%B2%BD%EC%A0%90&oquery=%EC%95%88%EA%B2%BD%EC%A0%90&tqi=UQ55jsprvN8ssv165RZssssssNC-479615') soup = BeautifulSoup(res.content, 'html.parser') try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 for link in soup.find_all('a'): tmp = link.get('href') tmp = str(tmp) if 'lng' in tmp: idx = tmp.find('lat') lat = tmp[idx+4:idx+14] idx = tmp.find('lng') lng = tmp[idx+4:idx+14] type = "naver" sql = f'''INSERT INTO glasses_store(lat, lng, type) VALUES (\'{lat}\', \'{lng}\', \'{type}\') ''' cur.execute(sql) print(sql) cur.execute(sql) # sql 문을 실행 conn.commit() conn.close() except pg.OperationalError as e: print(e) def nikon(page): url = 'http://www.nikon-lenswear.co.kr/assets/store-search-daum/com_list.php' params = { 'sno': page, 'location': 'a' } res = requests.get(url, params=params) try: conn = pg.connect(connect_string) # DB연결(로그인) cur = conn.cursor() # DB 작업할 지시자 정하기 # res = requests.get('http://www.nikon-lenswear.co.kr/assets/store-search-daum/com_list.php?sno=2520&location=a&tmptitle=&title_like=&isee=') soup = BeautifulSoup(res.content, 'html.parser') for link in soup.find_all('div'): link = str(link) if '서울' in link: tmp = link.split('\n') if len(tmp) == 8: name = tmp[1] name = name[5:] idx = name.find('<') name = name[:idx] addr = tmp[2] addr = addr[5:] idx = addr.find('<') addr = addr[:idx] type = "nikon" sql = f'''INSERT INTO glasses_store (name, addr, type) VALUES (\'{name}\', \'{addr}\', \'{type}\'); ''' print(sql) cur.execute(sql) conn.commit() conn.close() except pg.OperationalError as e: print(e) if __name__ == "__main__": # create_customersInfo_table() # init_customersInfo_table() # create_hospInfo_table() # init_hospInfo_table() # create_visited_record_table() # add_visited_record() # create_favorite_hospital_table() # create_pharmInfo_table() # create_description_list_table() # create_reservation_list_table() # create_glass_store_table() # init_glass_store_table() # nikon(2510) # nikon(2520) # nikon(2430) # nikon(2540) create_glasses_description_table()
C++
UTF-8
416
3.078125
3
[]
no_license
// https://zxi.mytechroad.com/blog/math/leetcode-1266-minimum-time-visiting-all-points/ class Solution { public: int minTimeToVisitAllPoints(vector<vector<int>>& points) { int ans = 0; for (size_t i = 1; i < points.size(); ++i) { int dx = abs(points[i - 1][0] - points[i][0]); int dy = abs(points[i - 1][1] - points[i][1]); ans += min(dx, dy) + abs(dx - dy); } return ans; } };
Java
UTF-8
6,988
2
2
[]
no_license
package org.moreunit.elements; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.ui.IEditorPart; import org.moreunit.log.LogHandler; import org.moreunit.preferences.Preferences; import org.moreunit.ui.MarkerUpdateRunnable; import org.moreunit.util.BaseTools; import org.moreunit.util.SearchTools; /** * ClassTypeFacade offers easy access to a simple java file within eclipse. The * file represented by this instance is not a testcase. * * @author vera * * 23.05.2006 20:29:57 */ public class TestCaseTypeFacade extends TypeFacade { public TestCaseTypeFacade(ICompilationUnit compilationUnit) { super(compilationUnit); } public TestCaseTypeFacade(IEditorPart editorPart) { super(editorPart); } public TestCaseTypeFacade(IFile file) { super(file); } public IType getCorrespondingClassUnderTest() { final Preferences preferences = Preferences.newInstance(this.javaProjectFacade.getJavaProject()); List<String> testedClasses = BaseTools.getTestedClass( getType().getFullyQualifiedName(), preferences.getPrefixes(), preferences.getSuffixes(), preferences.getTestPackagePrefix(), preferences.getTestPackageSuffix()); if (testedClasses.isEmpty()) { return null; } try { List<String> typeNames = BaseTools.getListOfUnqualifiedTypeNames(testedClasses); Set<IType> searchResults = new HashSet<IType>(); for (String typeName : typeNames) { Set<IType> searchFor = SearchTools.searchFor(typeName, compilationUnit); if (searchFor != null && searchFor.size() > 0) { searchResults.addAll(searchFor); } } return searchResults.size() > 0 ? searchResults.iterator().next() : null; } catch (Exception exc) { LogHandler.getInstance().handleExceptionLog(exc); } return null; } public IMethod getCorrespondingTestedMethod(IMethod testMethod, IType classUnderTest) { try { String testedMethodName = BaseTools.getTestedMethod(testMethod.getElementName()); if (testedMethodName != null) { IMethod[] foundTestMethods = classUnderTest.getMethods(); for (IMethod method : foundTestMethods) { if (testedMethodName.startsWith(method.getElementName()) && method.exists()) { return method; } } } } catch (JavaModelException exc) { LogHandler.getInstance().handleExceptionLog(exc); } return null; } /** * Creates a testmethod for the method that should be tested. * * @param methodToTest * The method that should be tested. * @return <code>true</code> if the method was successfully created, * <code>false</code> if the method already existed or the method * creation threw an exception. */ /* * public boolean createTestMethodForMethod(IMethod methodToTest) { try { * String methodName = methodToTest.getElementName(); methodName = * BaseTools.firstCharToUpperCase(methodName); * * String testMethodName = MagicNumbers.TEST_METHOD_PRAEFIX + methodName; if * (doesMethodExist(testMethodName)) return false; * * compilationUnit.findPrimaryType().createMethod(getTestMethodString(testMethodName), * null, true, null); * * if (Preferences.instance().shouldUseJunit4Type()) { * compilationUnit.createImport("org.junit.Test", null, null); } return * true; } catch (JavaModelException exc) { * LogHandler.getInstance().handleExceptionLog(exc); } * * return false; } */ /** * Creates another testmethod for the given method aTestMethod * * @param aTestMethod * @return */ /* * public IMethod createAnotherTestMethod(IMethod aTestMethod) { try { * String testedMethodName = * BaseTools.getTestedMethod(aTestMethod.getElementName()); IMethod * testedMethod = * BaseTools.getFirstMethodWithSameNamePrefix(getCorrespondingClassUnderTest().getMethods(), * testedMethodName); if(testedMethod != null) { String testMethodName = * MagicNumbers.TEST_METHOD_PRAEFIX + * BaseTools.firstCharToUpperCase(testedMethod.getElementName()); if * (doesMethodExist(testMethodName)) testMethodName = * testMethodName.concat(MagicNumbers.SUFFIX_NAME); * * IMethod newTestMethod = * compilationUnit.findPrimaryType().createMethod(getTestMethodString(testMethodName), * null, true, null); * * return newTestMethod; } } catch (JavaModelException e) { * LogHandler.getInstance().handleExceptionLog(e); } * * return null; } */ /* * private String getTestMethodString(String testMethodName) { if * (Preferences.instance().shouldUseJunit4Type()) { StringBuffer result = * new StringBuffer(); result.append("@Test").append(MagicNumbers.NEWLINE); * result.append("public void ").append(testMethodName).append("() * {").append(MagicNumbers.NEWLINE).append("}"); * * return result.toString(); } else { return "public void " + testMethodName + * "() {" + MagicNumbers.NEWLINE + "}"; } } */ public void createMarkerForTestedClass() throws CoreException { IResource resource = this.compilationUnit.getUnderlyingResource(); if (resource == null) { return; } if (!Flags.isAbstract(getType().getFlags())) { IType testedClass = getCorrespondingClassUnderTest(); if (testedClass == null) { return; } new MarkerUpdateRunnable(testedClass, getType()).schedule(); } } } //$Log: not supported by cvs2svn $ //Revision 1.11 2007/08/12 17:09:32 gianasista //Refactoring: Test method creation // //Revision 1.10 2007/03/02 22:14:07 channingwalton //[ 1667386 ] Jump to test can miss some testcases // //Fixed // //Revision 1.9 2007/01/25 08:34:25 hannosti //Some comments. Removed dead code. // //Revision 1.8 2007/01/24 20:11:50 gianasista //Bugfix: flexible testcase matching // //Revision 1.7 2007/01/12 21:55:54 gianasista //Better matching for testcases [1575497] // //Revision 1.6 2006/12/22 19:03:50 gianasista //changed textselection after creation of another testmethod // //Revision 1.5 2006/11/25 14:58:56 gianasista //Create second testmethod // //Revision 1.4 2006/10/08 17:26:27 gianasista //Suffix preference // //Revision 1.3 2006/09/18 20:00:10 channingwalton //the CVS substitions broke with my last check in because I put newlines in them // //Revision 1.2 2006/09/18 19:56:07 channingwalton //Fixed bug [ 1537839 ] moreunit cannot find test class if it is in wrong package. Also found a classcast exception in UnitDecorator whicj I've guarded for.Fixed the Class wizard icon // //
Java
UTF-8
3,368
2.15625
2
[]
no_license
package ac.uiu.messmanagementsystem.fragments.profile; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import ac.uiu.messmanagementsystem.R; import ac.uiu.messmanagementsystem.adapters.FixedExpenseAdapter; import ac.uiu.messmanagementsystem.model.FixedExpense; /** * A simple {@link Fragment} subclass. */ public class ProfileFragment extends Fragment { public ProfileFragment() { // Required empty public constructor } private ArrayList<FixedExpense> fixedExpenses; private Button btn_add,btn_save; private EditText et_expName,et_title,et_email,et_username,et_members,et_rooms; private EditText et_amount; private FixedExpenseAdapter adapter; private FloatingActionButton fab_edit; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_profile, container, false); getActivity().setTitle("Mess Information"); ListView lv = view.findViewById(R.id.lv_exp); btn_add = view.findViewById(R.id.btn_pro_add); et_expName = view.findViewById(R.id.et_pro_expName); et_amount = view.findViewById(R.id.et_pro_amount); fab_edit =view.findViewById(R.id.fab_profile); et_title = view.findViewById(R.id.et_pro_title); et_email = view.findViewById(R.id.et_pro_email); et_username = view.findViewById(R.id.et_pro_username); et_members = view.findViewById(R.id.et_pro_member); et_rooms = view.findViewById(R.id.et_pro_rooms); btn_save = view.findViewById(R.id.btn_pro_save); fixedExpenses = new ArrayList<FixedExpense>(); fixedExpenses.add(new FixedExpense("Rent",20000)); adapter = new FixedExpenseAdapter(fixedExpenses,getActivity()); lv.setAdapter(adapter); return view; } @Override public void onResume() { super.onResume(); btn_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(v.getId() == R.id.btn_pro_add && !et_expName.getText().toString().isEmpty() && !et_amount.getText().toString().isEmpty()){ adapter.add(new FixedExpense(et_expName.getText().toString(),Integer.parseInt(et_amount.getText().toString()))); adapter.notifyDataSetChanged(); et_amount.setText(""); et_expName.setText(""); } } }); fab_edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { et_title.setEnabled(true); et_email.setEnabled(true); et_members.setEnabled(true); et_rooms.setEnabled(true); btn_save.setEnabled(true); } }); } }
Python
UTF-8
653
3.984375
4
[]
no_license
import random f_r = int(input("Enter the first range:")) s_r = int(input("Enter the second range:")) attempt = int(input("Enter the number of attempts:")) rand_num = random.randint(f_r,s_r+1) print(rand_num) while attempt!=0: attempt-=1 print(attempt) ans = int(input("Enter the expected number:")) if ans==rand_num: print("Good job!You win! Your number is " + str(rand_num)) break else: if ans>rand_num: print("Your number is less") continue else: print("Your number is greater") else: print("Try to win in the next game! Good luck!")
Java
UTF-8
3,815
1.960938
2
[]
no_license
package com.sundeinfo.kd.zs.apis.restful.auth.wx; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.sundeinfo.core.authentication.dao.DaoAuthenticationProvider; import com.sundeinfo.core.permission.strategy.token.AuthenticationResponse; import com.sundeinfo.foundation.mvc.controller.AbstractController; import com.sundeinfo.foundation.request.RequestState; import com.sundeinfo.foundation.request.ResponseCallback; import com.sundeinfo.foundation.request.result.Result; import com.sundeinfo.kd.zs.define.enums.WeChatMpType; import com.sundeinfo.kd.zs.dto.auth.wx.WxLoginDTO; import com.sundeinfo.kd.zs.dto.auth.wx.WxRegisterPhoneDTO; import com.sundeinfo.kd.zs.dto.auth.wx.WxSessionInfoDTO; import com.sundeinfo.kd.zs.dto.sys.UserDTO; import com.sundeinfo.kd.zs.service.auth.UserAuthService; import com.sundeinfo.kd.zs.service.auth.wx.WxAuthService; import com.sundeinfo.kd.zs.service.user.UserService; import com.sundeinfo.kd.zs.utility.StringUtils; import com.sundeinfo.kd.zs.utility.UserHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.core.AuthenticationException; import org.springframework.web.bind.annotation.*; @CrossOrigin @RestController @RequestMapping("kdzs/api/auth/wx/") public class WxAuthRestController extends AbstractController<WxAuthRestController> { @Autowired private WxAuthService wxAuthService; @Autowired private UserService userService; @Autowired private UserAuthService userAuthService; @PostMapping(value = "/login") public ResponseEntity<Result<AuthenticationResponse>> login(@RequestBody WxLoginDTO wxLoginDTO) throws AuthenticationException { return requestHandler.doPost( new ResponseCallback<AuthenticationResponse>() { String token = ""; @Override public RequestState doCheck() { return RequestState.SUCCESS; } @Override public RequestState invoke() throws Exception { WxSessionInfoDTO wxSessionInfoDto = wxAuthService.jscode2session(wxLoginDTO.getMpType(), wxLoginDTO.getWxCode()); if (wxSessionInfoDto == null) { return RequestState.WX_AUTH_ERROR; } UserDTO userDTO = null; if (wxSessionInfoDto.getSession_key() != null) { if (wxSessionInfoDto.getUnionid() != null) { userDTO = userService.findByUnionId(wxSessionInfoDto.getUnionid()); } else { if (wxSessionInfoDto.getOpenid() != null) { userDTO = userService.findByOpenId(wxSessionInfoDto.getOpenid()); } } if (userDTO != null) { token = userAuthService.login(userDTO.getUsername(), DaoAuthenticationProvider.getNoEncoderPassword(userDTO.getLoginPassword())); } else { return RequestState.WX_AUTH_NO_USER_ERROR; } } else { return RequestState.WX_AUTH_ERROR; } return RequestState.SUCCESS; } @Override public AuthenticationResponse response() throws Exception { return UserHelper.createJwtAuthenticationResponse(token); } } ); } }
Python
UTF-8
1,093
3.109375
3
[]
no_license
# # # # # # # # Author phantomhive # # 20-07-2019 # # # # # # # # from collections import Counter, deque, defaultdict from math import ceil, floor, sqrt, log, factorial from fractions import Fraction, gcd from sys import stdin, stdout from bisect import bisect, bisect_left, bisect_right from heapq import heapify, heappop, heappush, heappushpop from time import time def lcm(a,b): return (a*b) / gcd(a,b) cin, cout = stdin.readline, stdout.write # Start time START = time() def my_hash(num): hash_ = [0]*10 while num: key = num%10 hash_[key]+=1 num/=10 return tuple(hash_) LIMIT = 10**4 store = defaultdict(lambda : list()) for i in xrange(1,LIMIT): value = pow(i, 3) key = my_hash(value) store[key].append(i) five_cube = list() for key, value in store.items(): if len(value)>=5: five_cube.append(value) value = min([min(array) for array in five_cube]) print pow(value, 3) # End Time END = time() seconds = END - START print("Total time %d minutes %d seconds"%(seconds/60, seconds%60))
Python
UTF-8
2,495
2.546875
3
[]
no_license
import time from catapult.deploy.constants import TRANSPORT_PUSHOVER, TRANSPORT_SLACK, TRANSPORT_TELEGRAM from catapult.library.renders import render_string from catapult.library.transports import pushover, telegram, slack class Notifier: def __init__(self, notifications, request, logger): self.notifications = notifications self.request = request self.logger = logger def notify(self, is_success=True): if not self.notifications: return for transport, config in self.notifications.items(): if not config: continue message = self.get_message( is_success, config['messages']['success'], config['messages']['fail'] ) if transport == TRANSPORT_TELEGRAM: try: self.logger.info('try to deliver message with transport Telegram') telegram( config['token'], config['chat_id'], message ) self.logger.success('message sent') except Exception as error: self.logger.error(error) if transport == TRANSPORT_PUSHOVER: try: self.logger.info('try to deliver message with transport Pushover') for client in config['clients']: pushover( config['token'], client, message ) self.logger.success('message sent') except Exception as error: self.logger.error(error) if transport == TRANSPORT_SLACK: try: self.logger.info('try to deliver message with transport Slack') slack( config['token'], config['channel'], message ) self.logger.success('message sent') except Exception as error: self.logger.error(error) def get_message(self, is_success, success, fail): self.request['time'] = round(int(time.time()) - self.request['time_start'], 2) template = success if is_success else fail return render_string(template, self.request)
Java
UTF-8
1,477
3
3
[]
no_license
package it.polito.tdp.borders.model; import java.util.ArrayList; import java.util.List; import org.jgrapht.Graph; import org.jgrapht.Graphs; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; public class Recursive { //CLASSE CONTENENTE L'ALGORITMO RICORSIVO private Graph<Country, DefaultEdge> grafo = new SimpleGraph<>(DefaultEdge.class); /** * * @param grafo (Grafo creato a partire da un anno specificato) * @param statoPartenza (punto di partenza per la ricerca del cammino) * @return Lista di stati raggiungibili via terra dallo stato passato come parametro */ public List<Country> getListaVicini(Graph<Country, DefaultEdge> graph, Country statoPartenza){ grafo = graph; List<Country> parziale = new ArrayList<>(); parziale.add(statoPartenza); cerca(parziale, statoPartenza); return parziale; } public void cerca(List<Country> parziale, Country paeseVisitato){ /* * CASO GENERALE: dal paese in cui mi trovo prelevo i suoi vicini, * controllo se siano già stati inseriti e, nel caso * rimando la ricorsione */ List<Country> adiacenti = new ArrayList<>(Graphs.neighborListOf(grafo, paeseVisitato)); for(Country c: adiacenti) { //Controllo che il nodo adiacente non sia già nella lista parziale if(!parziale.contains(c)) { parziale.add(c); cerca(parziale, c); } } } }
JavaScript
UTF-8
224
2.703125
3
[]
no_license
var fs = require('fs'); var path = require('path'); fs.readdir(process.argv[2],function(err,data) { for (var i=0;i<data.length;i++) if (path.extname(data[i])=='.'+process.argv[3]) console.log(data[i]); });
PHP
UTF-8
4,985
3.421875
3
[]
no_license
<?php namespace zibo\library\network; use zibo\library\network\exception\ConnectionException; use zibo\library\Number; use zibo\library\String; use \Exception; /** * Connection with a server */ class Connection { /** * The hostname from the URL * @var string */ protected $host; /** * The port of the host to connect to * @var integer */ protected $port; /** * Flag to see if a secured connection should be made * @var boolean */ protected $isSecured; /** * The socket of the connection * @var resource */ protected $socket; /** * Constructs a new connection * @param string $host The hostname or ip address to connect to * @param integer $port The port to connect to * @param boolean $isSecured Set to true to create a secured connection (SSL) * @return null */ public function __construct($host, $port = 80, $isSecured = false) { $this->setHost($host); $this->setPort($port); $this->setIsSecured($isSecured); $this->socket = null; } /** * Sets the host of this connection * @param string $host * @return null * @throws zibo\library\network\exception\ConnectionException when the host is invalid */ protected function setHost($host) { if (String::isEmpty($host)) { throw new ConnectionException('Could not set the host: invalid host provided'); } $this->host = $host; } /** * Gets the host of this connection * @return string */ public function getHost() { return $this->host; } /** * Sets the port of this connection * @param integer $port The port of this connection * @return null * @throws zibo\library\network\exception\ConnectionException when the port is invalid */ protected function setPort($port) { if (Number::isNegative($port)) { throw new ConnectionException('Could not set the port: invalid port provided'); } $this->port = $port; } /** * Gets the port of this connection * @return integer */ public function getPort() { return $this->port; } /** * Sets whether this is a secured connection (SSL) * @param boolean $isSecured * @return null */ protected function setIsSecured($isSecured) { $this->isSecured = $isSecured; } /** * Gets whether this is a secured connection (SSL) * @return boolean */ public function isSecured() { return $this->isSecured; } /** * Creates a connection with the host * @param integer $timeoutSeconds The timeout for the connection in seconds * @param integer $timeoutMicroseconds The timeout for the connection in microseconds * @return null */ public function connect($timeoutSeconds = 15, $timeoutMicroseconds = 0) { if ($this->socket) { return; } // secured url? if ($this->isSecured) { $this->socket = @fsockopen('ssl://' . $this->host, $this->port, $errorNumber, $errorMessage, $timeoutSeconds); } else { $this->socket = @fsockopen($this->host, $this->port, $errorNumber, $errorMessage, $timeoutSeconds); } if (!$this->socket) { throw new ConnectionException('Could not connect to ' . $this->host); } stream_set_timeout($this->socket, $timeoutSeconds, $timeoutMicroseconds); } /** * Closes the connection with the host * @return null */ public function disconnect() { if (!$this->socket) { return; } fclose($this->socket); $this->socket = null; } /** * Checks whether this connection is connected * @return boolean */ public function isConnected() { return $this->socket ? true : false; } /** * Sends a request to the host * @param string $requestString The request string to send * @return null * @throws zibo\library\network\exception\ConnectionException when the request could not be send */ public function sendRequest($requestString) { if (!$this->socket) { $this->connect(); } $bytesRequestString = strlen($requestString); $bytesWritten = fwrite($this->socket, $requestString, $bytesRequestString); if ($bytesWritten === false) { throw ConnectionException('Could not send the request'); } } /** * Receives the response from the host * @param integer $bytes Number of bytes to read * @return string The response */ public function receiveResponse($bytes = 128) { $responseString = ''; while (!feof($this->socket)) { $responseString .= fgets($this->socket, $bytes); } return $responseString; } }
Java
UTF-8
2,352
2.1875
2
[]
no_license
package com.chengxin.adapter; import java.util.List; import com.chengxin.R; import com.chengxin.Entity.Goods; import com.chengxin.global.ImageLoader; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class GridGoodsAdapter extends BaseAdapter { private List <Goods> mList; private Context mContext; private LayoutInflater mInflater; private ImageLoader mImageLoader = new ImageLoader(); public GridGoodsAdapter(Context context, List<Goods> list) { super(); mList = list; mContext = context; mInflater = LayoutInflater.from(context); } @Override public int getCount() { return mList.size(); } @Override public Object getItem(int position) { return mList.get(position); } @Override public long getItemId(int position) { return Long.parseLong(mList.get(position).id); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null || ((ViewHolder)convertView.getTag()).mTag != position){ holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.gridview_goods_item, null); holder.mTag = position; holder.mLayoutLogo = (LinearLayout)convertView.findViewById(R.id.layout_logo); holder.mPrice = (TextView)convertView.findViewById(R.id.goods_price); holder.mText = (TextView)convertView.findViewById(R.id.goods_name); holder.mLogo = (ImageView)convertView.findViewById(R.id.goods_logo); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Goods item = mList.get(position); if (item.logo != null && !item.logo.equals("") && !item.logo.equals("null")) { mImageLoader.getBitmap(mContext, holder.mLogo, null, item.logo, 0, false, false, false); } holder.mText.setText(item.name); holder.mPrice.setText(String.format("¥%.2f", item.price)); return convertView; } static class ViewHolder { int mTag; TextView mPrice; TextView mText; ImageView mLogo; LinearLayout mLayoutLogo; @Override public int hashCode() { return mText.hashCode() + mPrice.hashCode() + mLogo.hashCode() + mLayoutLogo.hashCode(); } } }
Markdown
UTF-8
9,024
3.328125
3
[]
no_license
[[File:Desargues_theorem.svg|350px]] '''笛沙格(Desargues)定理'''說明:在[[射影空間|射影空間]]中,有六點A,B,C,a,b,c。Aa,Bb,Cc共點若且唯若AB∩ab,BC∩bc,CA∩ca共线。 在[[射影幾何|射影幾何]]的對偶性來看,笛沙格定理是自對偶的。 ==证明== 笛沙格定理可以表述如下: :如果''A''.''a'',''B''.''b'',''C''.''c''共点,则 :(''A''.''B'')∩(''a''.''b''),(''A''.''C'')∩(''a''.''c''),(''B''.''C'')∩(''b''.''c'')共线。 利用[[向量积|向量积]]、[[数量积|数量积]]和[[三重积|三重积]],笛沙格定理也可以表述为: 如果 :<math> \langle A \times a, B \times b, C \times c\rangle = 0 </math> 那么 :<math> \langle (A \times B) \times (a \times b), (A \times C) \times (a \times c), (B \times C) \times (b \times c)\rangle = 0. </math> ===第一个重述=== 向量三重积 :<math> X \times (Y \times Z) </math> 等于 :<math> Y (X \cdot Z) - Z (X \cdot Y), </math> 我们便可以推出以下的公式: :<math> (X \times Y) \times (Z \times W) = \langle X,Y,W\rangle Z - \langle X,Y,Z\rangle W. </math> 从这个公式中,我们可以进一步推出以下的恒等式: :<math> \langle U \times V, W \times X, Y \times Z\rangle = \langle W,X,Z\rangle \langle U,V,Y\rangle - \langle W,X,Y\rangle \langle U,V,Z\rangle. </math> 利用这个恒等式,笛沙格定理就可以重述为: 如果 :<math> \langle B,b,c\rangle \langle A,a,C\rangle = \langle B,b,C\rangle \langle A,a,c\rangle </math> 那么 :<math> \langle A \times C, a \times c, b \times c\rangle \langle A \times B, a \times b, B \times C\rangle = \langle A \times C, a \times c, B \times C\rangle \langle A \times B, a \times b, b \times c\rangle. </math> ===第二个重述=== 把第一个重述的[[后件|后件]]再应用上面的恒等式,把三重积交换,并把每一个三重积中的向量进行循环置换,我们便得到第二个重述: 如果 :<math> \langle A,a,c\rangle \langle b,B,C\rangle = \langle a,A,C\rangle \langle B,b,c\rangle </math> 那么 :<math> \langle C,a,c\rangle \langle b,A,B\rangle = \langle c,A,C\rangle \langle B,a,b\rangle. </math> 注意后件的左端可以从[[前件|前件]]的左端通过变量代换''A''→''C'',''B''→''A'',''C''→''B''得到。后件的右端也可以从前件的右端通过变量代换''a''→''c'',''b''→''a'',''c''→''b''得到。 ===第三个重述=== [[向量分析|向量分析]]中的一个定理说明,两个标量三重积的乘积等于以下矩阵的[[行列式|行列式]]: :<math> M_{ij} = u_i \cdot v_j, \qquad \langle u_1,u_2,u_3\rangle \langle v_1,v_2,v_3\rangle = |M|. </math> 把这个定理应用于第二个重述,便得到第三个重述: 如果 :<math> \left| \begin{matrix} A \cdot b & a \cdot b & c \cdot b \\ A \cdot B & a \cdot B & c \cdot B \\ A \cdot C & a \cdot C & c \cdot C \end{matrix} \right| = \left| \begin{matrix} a \cdot B & A \cdot B & C \cdot B \\ a \cdot b & A \cdot b & C \cdot b \\ a \cdot c & A \cdot c & C \cdot c \end{matrix} \right| </math> 那么 :<math> \left| \begin{matrix} C \cdot b & a \cdot b & c \cdot b \\ C \cdot A & a \cdot A & c \cdot A \\ C \cdot B & a \cdot B & c \cdot B \end{matrix} \right| = \left| \begin{matrix} c \cdot B & A \cdot B & C \cdot B \\ c \cdot a & A \cdot a & C \cdot a \\ c \cdot b & A \cdot b & C \cdot b \end{matrix} \right|. </math> ===第四个重述=== 把第三个重述中的行列式展开,便得到第四个重述: 如果 :<math> (A \cdot b) (a \cdot B) (c \cdot C) + (a \cdot b) (c \cdot B) (A \cdot C) + (c \cdot b) (A \cdot B) (a \cdot C) </math> :: <math> - (A \cdot b) (c \cdot B) (a \cdot C) - (a \cdot b) (A \cdot B) (c \cdot C) - (c \cdot b) (a \cdot B) (A \cdot C) </math> :<math> = (a \cdot B) (A \cdot b) (C \cdot c) + (A \cdot B) (C \cdot b) (a \cdot c) + (C \cdot B) (a \cdot b) (A \cdot c)</math> :<math> - (a \cdot B) (C \cdot b) (A \cdot c) - (A \cdot B) (a \cdot b) (C \cdot c) - (C \cdot B) (A \cdot b) (a \cdot c) </math> 那么 :<math> (C \cdot b) (a \cdot A) (c \cdot B) + (a \cdot b) (c \cdot A) (C \cdot B) + (c \cdot b) (C \cdot A) (a \cdot B) </math> :: <math> - (C \cdot b) (c \cdot A) (a \cdot B) - (a \cdot b) (C \cdot A) (c \cdot B) - (c \cdot b) (a \cdot A) (C \cdot B) </math> :<math> = (c \cdot B) (A \cdot a) (C \cdot b) + (A \cdot B) (C \cdot a) (c \cdot b) + (C \cdot B) (c \cdot a) (A \cdot b) </math> :<math> - (c \cdot B) (C \cdot a) (A \cdot b) - (A \cdot B) (c \cdot a) (C \cdot b) - (C \cdot B) (A \cdot a) (c \cdot b). </math> ===第五个重述=== 第四个重述的两个方程(前件和后件)的两端的第一项和第五项都互相抵消,便得到第五个重述: 如果 :<math> (A \cdot C) (B \cdot c) (a \cdot b) + (A \cdot B) (C \cdot a) (b \cdot c)</math> ::<math> - (A \cdot b) (B \cdot c) (C \cdot a) - (A \cdot C) (B \cdot a) (b \cdot c) </math> :<math> = (A \cdot B) (C \cdot b) (a \cdot c) + (A \cdot c) (B \cdot C) (a \cdot b) </math> ::<math> - (A \cdot c) (B \cdot a) (C \cdot b) - (A \cdot b) (B \cdot C) (a \cdot c) </math> 那么 :<math> (A \cdot c) (B \cdot C) (a \cdot b) + (A \cdot C) (B \cdot a) (b \cdot c) </math> ::<math> - (A \cdot c) (B \cdot a) (C \cdot b) - (A \cdot C) (B \cdot c) (a \cdot b)</math> :<math> = (A \cdot B) (C \cdot a) (b \cdot c) + (A \cdot b) (B \cdot C) (a \cdot c) </math> ::<math> - (A \cdot b) (B \cdot c) (C \cdot a) - (A \cdot B) (C \cdot b) (a \cdot c). </math> ===第六个重述=== 在第五个重述的两个方程之间有八个不同的项;每一个项都出现了两次。把这些项记为: :<math> t_1 = (A \cdot C) (B \cdot c) (a \cdot b), </math> :<math> t_2 = (A \cdot B) (C \cdot a) (b \cdot c), </math> :<math> t_3 = (A \cdot b) (B \cdot c) (C \cdot a), </math> :<math> t_4 = (A \cdot C) (B \cdot a) (b \cdot c), </math> :<math> t_5 = (A \cdot B) (C \cdot b) (a \cdot c), </math> :<math> t_6 = (A \cdot c) (B \cdot C) (a \cdot b), </math> :<math> t_7 = (A \cdot c) (B \cdot a) (C \cdot b), </math> :<math> t_8 = (A \cdot b) (B \cdot C) (a \cdot c). </math> 于是我们得到第六个重述: 如果 :<math> t_1 + t_2 - t_3 - t_4 = t_5 + t_6 - t_7 - t_8, </math> 那么 :<math> t_6 + t_4 - t_7 - t_1 = t_2 + t_8 - t_3 - t_5. </math> ===第七个重述=== 把前件的右端的项移到左端,再把后件的左端的项移到右端,便得到: 如果 :<math> t_1 + t_2 - t_3 - t_4 - t_5 - t_6 + t_7 + t_8 = 0, </math> 那么 :<math> 0 = t_1 + t_2 - t_3 - t_4 - t_5 - t_6 + t_7 + t_8. </math> 这里可以看出,前件与后件是相同的,因此便证明了笛沙格定理。 ===笛沙格定理的引申=== 笛沙格定理可以简单描述为笛沙格图形 <math>ABC-S-A'B'C'</math>的形式, <math>A,B,C</math>和<math>A',B',C'</math>是三对对应点,<math>S</math>是三对对应点连线的交点. 笛沙格定理还可以进行向高维空间的引申, 其引申形式对应的笛沙格图形为: <math>ABCD-S-A'B'C'D'</math>, 或者<math>ABCDE-S-A'B'C'D'E'</math>, 乃至更高维数的笛沙格图形. 三维空间里的<math>ABCD-S-A'B'C'D'</math>形式的笛沙格定理最有实用价值. 这时,<math>ABCD</math>和<math>A'B'C'D'</math>必须都是四面体, 或至少其中一个是四面体, 另一个为完全四点形; 它们对应线的(组合数<math>C_{n+1}^{2}</math>, <math>n=3</math>, 共6个)交点, 也由<math>ABC-S-A'B'C'</math>情况下的共线, 扩展为三维时的共面, 或更一般意义下的"共超平面". 基于齐次坐标表示形式对笛沙格定理进行的解析证明是向高维空间作引申时最为简明方便的证明方式. 根据引申的笛沙格定理和基于齐次坐标的表示而定义的几何变换:空间透射(<math>stereohomology</math>), 其定义涵盖了理论图形学中的中心投影,平行投影,平移,反射,位似等几何变换, 并且可以证明其变换矩阵和矩阵计算理论中的初等矩阵实际上是等价的集合. 该几何变换的意义主要在于, 图形学理论中重要的几何变换或者投影变换的定义及其系数矩阵的确定可以通过独立于坐标系选择的方式进行, 更加简明和具有一般性意义. 关于"空间透射stereohomology"的较早的利用笛沙格定理的引申所作的定义, 可以参考: 1. 透视投影研究. 华东理工大学学报(自然科学版). 2000, vol.26, No.2: pp201~205 关于空间透射和初等矩阵的对应关系的总结, 可以参考: 2. 初等矩阵的射影几何意义及其应用. 自然科学进展. 2005,vol.15,No.9:pp1113-1122 最好是参考英文版的更新: https://arxiv.org/abs/1307.0998 以及非正式发表的资料: 中文的讲义: http://www.newsmth.net/att.php?p.50.48961.589.pdf 英文的详细论证: https://arxiv.org/abs/1307.0998 ==参见== *[[布列安桑定理|布列安桑定理]] *[[帕斯卡定理|帕斯卡定理]] *[[帕普斯定理|帕普斯定理]] [[Category:射影几何|Category:射影几何]] [[Category:几何定理|Category:几何定理]]
PHP
UTF-8
3,615
2.578125
3
[ "MIT" ]
permissive
<?php namespace PHPSpec2\Mocker; use PHPSpec2\Mocker\MockerInterface; use PHPSpec2\Wrapper\ArgumentsUnwrapper; use PHPSpec2\Formatter\Presenter\PresenterInterface; use PHPSpec2\Exception\MockException; use ArrayAccess; class MockExpectation implements ArrayAccess { private $mock; private $method; private $arguments; private $mocker; private $expectation; private $unwrapper; private $presenter; public function __construct($mock, $method, MockerInterface $mocker, ArgumentsUnwrapper $unwrapper, PresenterInterface $presenter) { $this->mock = $mock; $this->method = $method; $this->mocker = $mocker; $this->unwrapper = $unwrapper; $this->presenter = $presenter; } public function shouldBeCalled() { $this->mocker->shouldBeCalled($this->getExpectation()); return $this; } public function shouldNotBeCalled() { $this->mocker->shouldNotBeCalled($this->getExpectation()); return $this; } public function willBeDefault() { $this->mocker->makeDefault($this->getExpectation()); return $this; } public function willReturn($value) { $this->mocker->willReturn( $this->getExpectation(), $this->unwrapper->unwrapOne($value) ); return $this; } public function willReturnUsing($callback) { $this->mocker->willReturnUsing($this->getExpectation(), $callback); return $this; } public function willReturnArgument() { $this->willReturnUsing(function($argument) { return $argument; }); return $this; } public function willReturnSelf() { $this->willReturn($this->mock); return $this; } public function willThrow($exception, $message = '') { if ($exception instanceof \Exception) { $message = $exception->getMessage(); $exception = get_class($exception); } $this->mocker->willThrow($this->getExpectation(), $exception, $message); return $this; } public function offsetExists($offset) { return $this->mocker->hasExpectation( $this->mock, $this->method, $this->arguments, $offset ); } public function offsetGet($offset) { if (!$this->offsetExists($offset)) { throw new MockException(sprintf( 'Expectation with %s offset not found.', $this->presenter->presentValue($offset) )); } $this->expectation = $this->mocker->getExpectation( $this->mock, $this->method, $this->arguments, $offset ); return $this; } public function offsetUnset($offset) { throw new MockException('You can not unset already defined expectation.'); } public function offsetSet($offset, $value) { throw new MockException('You can not replace already defined expectation.'); } public function __invoke() { $this->arguments = $this->unwrapper->unwrapAll(func_get_args()); if (null !== $this->expectation) { $this->mocker->withArguments($this->expectation, $this->arguments); } return $this; } private function getExpectation() { if (null !== $this->expectation) { return $this->expectation; } return $this->expectation = $this->mocker->createExpectation( $this->mock, $this->method, $this->arguments ); } }
Python
UTF-8
819
2.84375
3
[]
no_license
import csv # with open('csvexample.csv', newline='') as myFile: # reader = csv.reader(myFile) # for row in reader: # print(row) def sendmail(attribute): name = attribute[0] email = attribute[1] print("Sending email to {}".format(email)) # to = email # sender = "you.email@gmail.com" # subject = "subject" # msgPlain = "" # msgHtml = "Hi {},<br/>This is a test email".format(first_name) # print(sender, to, subject, msgHtml, msgPlain) def main(): with open("newcsvexample.csv", "r") as file: msg_reader = csv.reader(file, delimiter=',') # print(msg_reader) # msg_reader.next() for row in msg_reader: sendmail(row) return row if __name__ == '__main__': i=main() # get_credentials()
C++
UTF-8
616
2.546875
3
[]
no_license
#include "sparkParticle.h" sparkParticle::sparkParticle(Point _position, Graphics* _gfx, float _xvel, float _yvel) { gfx = _gfx; position = _position; xVel = _xvel; yVel = _yvel; } sparkParticle::~sparkParticle() {delete image;} void sparkParticle::load() { hasGravity = true; gravity = 0.5; despawnTimer = 120; image = new SpriteSheet(L"sparkSpriteSheet.png", 5, 5, 0, 1, gfx); frame = rand() % 6 + 1; width = 5; height = 5; maxvel = 4.9; } void sparkParticle::draw() { image->Draw(frame, position.x, position.y); //gfx->DrawLine(position, Point{ position.x + 7, position.y + 7 }, 1, 1, 0, 20.6); }
C++
UTF-8
1,498
3.328125
3
[ "MIT" ]
permissive
#pragma once namespace osgUtil { /** @brief Helper class for vertices with discrete position */ class Vec3ui { public: Vec3ui() : _x(0) , _y(0) , _z(0) {} Vec3ui(unsigned int v) : _x(v) , _y(v) , _z(v) {} Vec3ui(unsigned int v1, unsigned int v2, unsigned int v3) : _x(v1) , _y(v2) , _z(v3) {} bool operator==(const Vec3ui& rhs) const { return (_x == rhs._x) && (_y == rhs._y) && (_z == rhs._z); } bool operator!=(const Vec3ui& rhs) const { return !(*this == rhs); } unsigned int& x() { return _x; } unsigned int& y() { return _y; } unsigned int& z() { return _z; } unsigned int x() const { return _x; } unsigned int y() const { return _y; } unsigned int z() const { return _z; } protected: unsigned int _x; unsigned int _y; unsigned int _z; }; /** @brief quantizes vertex position with different bit precissions(used for vertex clustering) */ template<class Vector> Vec3ui quantize(int bits, float min, float max, const Vector& vertex) { float factor = (pow(2.0f, bits) - 1.0f) / (max-min); return Vec3ui( unsigned int(factor * (vertex.x() - min) + 0.5f), unsigned int(factor * (vertex.y() - min) + 0.5f), unsigned int(factor * (vertex.z() - min) + 0.5f)); } template<class Vector> Vector dequantize(int bits, float min, float max, const Vec3ui& vertex) { float invFactor = (max-min)/pow(2.0f, bits); return Vector( invFactor * vertex.x() + min, invFactor * vertex.y() + min, invFactor * vertex.z() + min); } }
Python
UTF-8
1,874
3.0625
3
[]
no_license
""" smmilutils.sysutils.fileutils utilities for manipulating files Pil Smmilut 2011-02-12 """ import os import logging import errors #============================================================================== global logger logger = logging.getLogger("fileutils") #------------------------------------------------------------------------------ def rename(fulloldname, newname, overwrite=False): """ Renames (and/or move) a file (FULL path of files !!) """ global logger destpath = os.path.split(fulloldname)[0] fullnewname = os.path.join(destpath, newname) ## Check if files exist if not os.path.isfile(fulloldname): ## The file doesn't exist! Can't rename! logger.error("File \"%s\" doesn't exist !" % fulloldname) raise errors.FileDoesntExistError(fulloldname) if os.path.isfile(fullnewname) and not overwrite: ## Filename already exists and we don't want to overwrite # We must generate a new name #raise errors.FileAlreadyExistsError(fullnewname) logger.warning("Destination file \"%s\" already exists." % newname) fbase, fext = os.path.splitext(newname) n = 0 while os.path.isfile(fullnewname): n += 1 # Format "_001" appendix = "_%03.f" % n newnew = "".join((fbase, appendix, fext)) fullnewname = os.path.join(destpath, newnew) if n >= 999: ## We're going to loop forever! raise errors.FileAlreadyExistsError(fullnewname) ## Rename the file ! os.rename(fulloldname, fullnewname) logger.info("File \"%s\" renamed to -> \"%s\"." % (fulloldname, fullnewname)) #============================================================================== if __name__ == "__main__": pass # rename("caca", "cucu")
Python
UTF-8
2,400
3.015625
3
[]
no_license
#!/usr/bin/env python3 """Archive.org PDF books downloader.""" import logging import os import re import requests from time import sleep from multiprocessing.pool import ThreadPool logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s', level=logging.INFO, datefmt='%Y/%m/%dT%H:%M:%S') def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ value = value.encode('ascii', 'ignore') value = re.sub('[^\w\s-]', '', value.decode()).strip().lower() value = re.sub('[-\s]+', '-', value) return value def get_links(): """Helper to generate links to PDF files.""" links = [] cursor = '' url = 'https://archive.org/services/search/v1/scrape?' + \ 'fields=title&q=genealogy&count=10000' while True: body = requests.get(url + cursor) logging.info(f"{body.json().get('total')} URLs left to parse") [links.append(i) for i in body.json()['items'] if i not in links] cursor_raw = body.json().get('cursor') if cursor_raw: cursor = f'&cursor={cursor_raw}' else: return links return links def fetch_url(item): if 'census' in item['title'].lower(): return path = os.path.join(directory, slugify(item['title'])[:50] + '.pdf') filelink = 'http://archive.org/download/{0}/{0}.pdf'.format( item['identifier']) if not os.path.exists(path): for i in range(10): try: r = requests.get(filelink, stream=True) break except Exception as e: logging.warning('\tConnection problem, retrying!') sleep(5) else: return if r.status_code == 200: with open(path, 'wb') as f: for chunk in r: f.write(chunk) logging.info(f"\t[{item['title']}]...OK") return path if __name__ == "__main__": while True: items = get_links() directory = '/books' os.makedirs(directory, exist_ok=True) while True: try: ThreadPool(10).map(fetch_url, items) break except Exception as e: continue
Markdown
UTF-8
3,619
2.890625
3
[]
no_license
--- published: true imdb: tt2366450 image: stories-we-tell.jpg author: christopherr stars: 4.5 excerpt: "You didn&rsquo;t live long enough to see Sarah blossom from adorable child star into important Canadian artist, but based on your own career ambitions, it&rsquo;s safe to say your little girl would have made you proud. She grew up in front of the camera, recently earned an Academy Award nomination behind the camera, and now she&rsquo;s taking the camera even further. In her documentary <em>Stories We Tell</em>, Sarah puts the Polley family under investigation. She&rsquo;s looking for answers (one in particular), and more importantly, a better understanding about her own identity. You kept the truth hidden for your entire life, and to our wonder, fascination, and delight, your youngest daughter tells the compelling tale." position: Documentary Subject addressee: Diane Polley layout: review categories: - reviews - on-video title: "Stories We Tell" comments: true tags: [Canadian, Diane Polley, documentary, Family, Letters to the Dead, NFB, ONF, personal, Sarah POlley, Stories We Tell, Uncategorized] --- You didn't live long enough to see Sarah blossom from adorable child star into important Canadian artist, but based on your own career ambitions, it's safe to say your little girl would have made you proud. She grew up in front of the camera, recently earned an Academy Award nomination behind the camera, and now she's taking the camera even further. In her documentary _Stories We Tell_, Sarah puts the Polley family under investigation. She's looking for answers (one in particular), and more importantly, a better understanding about her own identity. You kept the truth hidden for your entire life, and to our wonder, fascination, and delight, your youngest daughter tells the compelling tale. Some reviews for the film have revealed this mystery as if it's a simple component necessary to the synopsis. But I'm going to take your lead and keep quiet. Instead, I'll focus on all the other brilliant things I love about this very personal documentary. It starts with the film's "personality". That it doesn't take itself too seriously (that wonderful Canadian attribute) shows confidence in the subject matter. It seems that Sarah - and others members of the family - often questioned the interest others had in exploring such personal questions. The frankness of some of the answers would probably make you blush, but of course, the more specific everyone gets, the more real you become to us strangers--and the more universal Sarah's story becomes. This directorial approach also renders the film's construction refreshingly transparent. We get some great candid moments as your friends and family prepare to be interviewed. We see your husband Michael recording a voiceover (a heartfelt and articulate piece of introspection that he composed himself); Sarah asks him to re-record lines, no matter how confident he is with the delivery. We also get a mixture of found and new footage, but the line between truth and fiction blurs as the film wears on. That's another wonderful revelation we learn over the course of the film. At one point, Sarah herself is asked what the film is really about. Her answer is a bit laboured and intellectual, touching on ideas of representation and identity. Of course the truth is much simpler, even if these themes are what make the film resonate. But as the film itself proves, not knowing all the answers has no bearing on our love for the final product. And what your daughter has created is something I was able to love without reservation.
Java
UTF-8
13,350
2.140625
2
[]
no_license
package piotrrr.thesis.bots.rlbot; import cbr.CaseBase; import cbr.Movement; import java.util.LinkedList; import java.util.Map; import java.util.Random; import java.util.TreeMap; import piotrrr.thesis.bots.rlbot.rl.Action; import piotrrr.thesis.bots.mapbotbase.MapBotBase; import piotrrr.thesis.common.combat.*; import piotrrr.thesis.common.CommFun; import piotrrr.thesis.common.jobs.HitsReporter; import piotrrr.thesis.common.stats.BotStatistic; import piotrrr.thesis.tools.Dbg; import pl.gdan.elsy.qconf.Brain; import pl.gdan.elsy.qconf.Perception; import soc.qase.tools.vecmath.Vector3f; /** * TODO: * - tylko jeden sposób strzelania? - przewidywanie z tw. sinusów. */ /** * The aiming module * @author Piotr Gwizda�a */ public class RLCombatModule extends Perception { RLBot bot; double actionReward = 0; int actionTime = 10; int actionEndFrame = -1; int actionFireMode = Action.NO_FIRE; public TreeMap<Integer, WeaponScore> weaponRanking = new TreeMap<Integer, WeaponScore>(); public static class WeaponScore implements Comparable<WeaponScore> { private double rewardsTotal; private int rewardsCount; public WeaponScore(double rewardsTotal, int rewardsCount) { this.rewardsTotal = rewardsTotal; this.rewardsCount = rewardsCount; } double getScore() { return rewardsTotal / rewardsCount; } public int compareTo(WeaponScore o) { double t = getScore(); double a = o.getScore(); if (t > a) { return -1; } if (t < a) { return 1; } return 0; } } class Shooting { long shotTime = 0; long hitTime = 0; String enemyName = null; double reward = 0; public Shooting(long shotTime, long hitTime, String enemyName) { this.shotTime = shotTime; this.hitTime = hitTime; this.enemyName = enemyName; } } LinkedList<Shooting> shootings = new LinkedList<Shooting>(); Action[] actions = Action.getAllActionsArray(); public static final int maxShootingsCount = 100; public Brain brain; double actionDistance = 0; boolean unipolar = true; public RLCombatModule(RLBot bot) { this.bot = bot; brain = new Brain(this, actions); brain.setAlpha(0.8); //learning rate brain.setGamma(0.3); //discounting rate brain.setLambda(0.6); //trace forgetting // b.setUseBoltzmann(true); // b.setTemperature(0.001); brain.setRandActions(0.1); //exploration // brain.setAlpha(getRandParam(0.1, 0.8, 0.1)); //learning rate // brain.setGamma(getRandParam(0, 0.9, 0.2)); //discounting rate // brain.setLambda(getRandParam(0, 0.9, 0.2)); //trace forgetting //// b.setUseBoltzmann(true); //// b.setTemperature(0.001); // brain.setRandActions(getRandParam(0.01, 0.4, 0.1)); //exploration // unipolar = Rand.b(); for (int i = 7; i < 18; i++) { weaponRanking.put(i, new WeaponScore(0.5, 1)); } } double getRandParam(double from, double to, double quant) { int count = (int) ((to - from) / quant) + 1; Random r = new Random(); return from + r.nextInt(count) * quant; } @Override public String toString() { String s = "alpha=" + brain.getAlpha() + " gamma=" + brain.getGamma() + "\nlambda=" + brain.getLambda() + " rand=" + brain.getRandActions() + "\nunip=" + isUnipolar() + "\n"; TreeMap<Integer, WeaponScore> newRanking = new TreeMap<Integer, WeaponScore>(); for (Map.Entry<Integer, WeaponScore> e : weaponRanking.entrySet()) { newRanking.put(e.getKey(), e.getValue()); } weaponRanking = newRanking; for (Map.Entry<Integer, WeaponScore> e : weaponRanking.entrySet()) { s += "\n" + CommFun.getGunName(e.getKey()) + " : " + e.getValue().getScore(); } return s; } public FiringDecision getFiringDecision() { Vector3f playerPos = bot.getBotPosition(); EnemyInfo chosen = null; float chosenRisk = Float.MAX_VALUE; float maxDist = -1; float maxError = 0; LinkedList<EnemyInfo> eligible = new LinkedList<EnemyInfo>(); for (EnemyInfo ei : bot.kb.enemyInformation.values()) { if (ei.getBestVisibleEnemyPart(bot) == null) { continue; } if (ei.lastUpdateFrame + bot.cConfig.maxEnemyInfoAge4Firing < bot.getFrameNumber()) { continue; } float dist = CommFun.getDistanceBetweenPositions(playerPos, ei.getObjectPosition()); float error = ei.lastPredictionError; if (dist > maxDist) { maxDist = dist; } if (error > maxError) { maxError = error; } eligible.add(ei); } for (EnemyInfo ei : eligible) { float dist = CommFun.getDistanceBetweenPositions(playerPos, ei.getObjectPosition()); float error = ei.lastPredictionError; float risk = dist / maxDist + error / maxError; if (chosenRisk > risk) { chosenRisk = risk; chosen = ei; } } if (chosen == null) { return null; } actionDistance = CommFun.getDistanceBetweenPositions(playerPos, chosen.getObjectPosition()); return new FiringDecision(chosen, -1); } /** * Returns the firing instructions * @param fd firing decision * @param bot the bot * @return */ public FiringInstructions getFiringInstructions(FiringDecision fd) { if (fd == null || fd.enemyInfo == null) { return null; } updateRewards(); boolean reloading = bot.getWorld().getPlayer().getPlayerGun().isCoolingDown(); Vector3f noFiringLook = fd.enemyInfo.predictedPos == null ? fd.enemyInfo.getObjectPosition() : fd.enemyInfo.predictedPos; if (reloading) { return getNoFiringInstructions(noFiringLook); } shootings.add(new Shooting( bot.getFrameNumber(), bot.getFrameNumber() + (long) getTimeToHit( bot.cConfig.getBulletSpeedForGivenGun(bot.getCurrentWeaponIndex()), bot.getBotPosition(), fd.enemyInfo.getObjectPosition(), fd.enemyInfo.predictedPos), fd.enemyInfo.ent.getName())); if (shootings.size() > maxShootingsCount) { shootings.removeFirst(); } if (actionEndFrame == -1) { //first time } if (bot.getFrameNumber() >= actionEndFrame) { actionEndFrame = bot.getFrameNumber() + actionTime; //count rewards: bot.rewardsCount++; if (actionReward <= 1 && actionReward >= -1) { bot.totalReward += actionReward; } else { bot.totalReward += (actionReward > 0) ? 1 : -1; System.out.println("excessive reward! " + actionReward); } int rc = 1; double rwd = actionReward; int cwpi = bot.getCurrentWeaponIndex(); if (weaponRanking.get(cwpi) != null) { rc = weaponRanking.get(cwpi).rewardsCount + 1; rwd = weaponRanking.get(cwpi).rewardsTotal + actionReward; } weaponRanking.put(cwpi, new WeaponScore(rwd, rc)); BotStatistic.getInstance().addReward(bot.getBotName(), actionReward, bot.getFrameNumber()); // Dbg.prn(bot.getBotName()+"@"+bot.getFrameNumber()+" r="+actionReward); //choose new action and execute it perceive(); brain.count(); executeAction(actions[brain.getAction()]); actionReward = 0; } // return getFiringInstructionsAtHitpoint(fd, 1); // return getNewPredictingFiringInstructions(bot, fd, bot.cConfig.getBulletSpeedForGivenGun(bot.getCurrentWeaponIndex())); switch (actionFireMode) { case Action.FIRE: return getFastFiringInstructions(fd, bot); case Action.FIRE_PREDICTED: return getNewPredictingFiringInstructions(bot, fd, bot.cConfig.getBulletSpeedForGivenGun(bot.getCurrentWeaponIndex())); default: case Action.NO_FIRE: return getNoFiringInstructions(noFiringLook); } } FiringInstructions getNoFiringInstructions(Vector3f enemyPos) { FiringInstructions ret = new FiringInstructions(CommFun.getNormalizedDirectionVector(bot.getBotPosition(), enemyPos)); ret.doFire = false; return ret; } public static FiringInstructions getNewPredictingFiringInstructions(MapBotBase bot, FiringDecision fd, float bulletSpeed) { Vector3f playerPos = bot.getBotPosition(); Vector3f enemyPos = fd.enemyInfo.getBestVisibleEnemyPart(bot); //Calculate the time to hit double timeToHit = getTimeToHit(bulletSpeed, playerPos, enemyPos, fd.enemyInfo.predictedPos); if (timeToHit <= 1.5) { timeToHit = 1f; } //We add to enemy position the movement that the enemy is predicted to do in timeToHit. Vector3f hitPoint = CommFun.cloneVector(enemyPos); //movement is between bot position, not the visible part of the bot Vector3f movement = CommFun.getMovementBetweenVectors(fd.enemyInfo.getObjectPosition(), fd.enemyInfo.predictedPos); movement = CommFun.multiplyVectorByScalar(movement, (float) timeToHit); hitPoint.add(movement); return new FiringInstructions(CommFun.getNormalizedDirectionVector(playerPos, hitPoint)); } /** * * Point the enemy and shoot. * @param fd * @param playerPos * @return */ static public FiringInstructions getFastFiringInstructions(FiringDecision fd, MapBotBase bot) { Vector3f to = new Vector3f(fd.enemyInfo.getBestVisibleEnemyPart(bot)); Vector3f fireDir = CommFun.getNormalizedDirectionVector(bot.getBotPosition(), to); // bot.dtalk.addToLog("Fast firing."); return new FiringInstructions(fireDir); } public static double getTimeToHit(double bulletSpeed, Vector3f playerPos, Vector3f enemyPos, Vector3f enemyPredictedPos) { double d = CommFun.getDistanceBetweenPositions(playerPos, enemyPos); double v = bulletSpeed; double u = CommFun.getDistanceBetweenPositions(enemyPos, enemyPredictedPos); Vector3f vec1 = CommFun.getNormalizedDirectionVector(playerPos, enemyPos); Vector3f vec2 = CommFun.getNormalizedDirectionVector(enemyPos, enemyPredictedPos); double alpha = Math.toRadians(vec1.angle(vec2)); double delta = 4 * d * d * u * u * Math.cos(alpha) * Math.cos(alpha) + 4 * (v * v - u * u) * d * d; double t = (2 * d * u * Math.cos(alpha) + Math.sqrt(delta)) / (2 * (v * v - u * u)); double t2 = (2 * d * u * Math.cos(alpha) - Math.sqrt(delta)) / (2 * (v * v - u * u)); // System.out.println("t="+t+" v="+v+" d="+d+" u="+u+" t2="+t2); if (Double.isNaN(t)) { t = 1; } return t; } private void executeAction(Action action) { actionFireMode = action.getShootingMode(); if (Action.isProhibited(action)) { return; } int wpind = action.actionToInventoryIndex(); if (bot.getCurrentWeaponIndex() != wpind) { bot.changeWeaponToIndex(wpind); // if (bot.botHasItem(wpind)) System.out.println("chng wpn to: "+CommFun.getGunName(wpind)); } } public void updateRewards() { if (bot.scoreCounter.getBotScore() > bot.lastBotScore) { bot.lastBotScore = bot.scoreCounter.getBotScore(); //TODO: moze dac to do innego shootingu? Np. tego ktory ma hitpoint na teraz actionReward += 1; } // Dbg.prn(""); LinkedList<Shooting> toDelete = new LinkedList<Shooting>(); for (Shooting s : shootings) { int damage = HitsReporter.wasHitInGivenPeriod(s.shotTime + 1, s.hitTime + 2, s.enemyName); if (damage > 0) { actionReward += (damage / 100d) * 0.2; toDelete.add(s); // System.out.println(bot.getBotName()+" got shooting rwd - "+actionReward); } else if (s.hitTime + 4 < bot.getFrameNumber()) { toDelete.add(s); // System.out.println(bot.getBotName()+" missed! - "+actionReward); // actionReward -= 0.001; } } shootings.removeAll(toDelete); return; } @Override public boolean isUnipolar() { return unipolar; } @Override public double getReward() { return actionReward; } @Override protected void updateInputValues() { setNextValue(actionDistance); for (int i = 7; i < 18; i++) { setNextValue(bot.botHasItem(i)); } } }
Go
UTF-8
695
2.640625
3
[]
no_license
package web import ( "fmt" "net/http" "github.com/SilverCory/PerkboxTest/config" "github.com/SilverCory/PerkboxTest/data" ) type Web struct { data *data.Handler conf config.Web } func NewWeb(conf config.Web, data *data.Handler) *Web { ret := &Web{ data: data, conf: conf, } // TODO basic userauth middleware http.HandleFunc("/api/coupon/create", ret.CouponCreate) http.HandleFunc("/api/coupon/", ret.CouponHandler) return ret } func (web *Web) Start() error { return http.ListenAndServe(web.conf.ListenAddress, nil) } func (web *Web) WriteError(w http.ResponseWriter, status int, err error) { w.WriteHeader(status) w.Write([]byte(fmt.Sprintf(`{"error": %q}`, err))) }
TypeScript
UTF-8
1,945
2.75
3
[ "Apache-2.0" ]
permissive
import { ObjectID } from 'bson' import { assert } from 'chai' import { Institution } from '../../../src/application/domain/model/institution' describe('Models: Institution', () => { const institutionJSON: any = { id: new ObjectID() } const emptyInstitutionJSON: any = {} describe('fromJSON(json: any)', () => { context('when the json is correct', () => { it('should return an Institution model', () => { const result = new Institution().fromJSON(institutionJSON) assert.propertyVal(result, 'id', institutionJSON.id) }) }) context('when the json is empty', () => { it('should return an empty Institution model', () => { const result = new Institution().fromJSON(emptyInstitutionJSON) assert.propertyVal(result, 'id', emptyInstitutionJSON.id) }) }) context('when the json is undefined', () => { it('should return an Institution model with id with undefined value', () => { const result = new Institution().fromJSON(undefined) assert.isUndefined(result.id) }) }) context('when the json is a string', () => { it('should transform the string in json and return Institution model', () => { const result = new Institution().fromJSON(JSON.stringify(institutionJSON)) assert.propertyVal(result, 'id', institutionJSON.id.toHexString()) }) }) }) describe('toJSON()', () => { context('when the Institution model is correct', () => { it('should return a JSON from Institution model', () => { let result = new Institution().fromJSON(institutionJSON) result = result.toJSON() assert.propertyVal(result, 'id', institutionJSON.id) }) }) }) })
Shell
UTF-8
1,600
3.296875
3
[]
no_license
#June 19, 2019 #TianR. makeDonorDir(){ pdir=$1 sampleDonorTable=$2 for dir in `less $sampleDonorTable | grep SRR |cut -f2 | sort | uniq |tr "\n" " "` do echo $dir mkdir -p $pdir/$dir done } moveByDonor(){ wdir=`pwd` sampleDonorTable=$1 dir=$2 less $sampleDonorTable | grep SRR | awk '{print "[ -d "$2" ] && mv "$1"* "$2}' >$dir/mvByDonor.sh chmod +x $dir/mvByDonor.sh cd $dir ./mvByDonor.sh cd $wdir } goMove(){ makeDonorDir $exprsDir $1 moveByDonor $1 $exprsDir makeDonorDir $hlaDir $1 moveByDonor $1 $hlaDir } runByDonor(){ donor=$1 exprsDir=$2 hlaDir=$3 wdir=`pwd` rpkmDir=$exprsDir/$donor seqHLAdir=$hlaDir/$donor cd $rpkmDir ~/pipelines/aggregate.all.gene.sh $seqHLAdir cp all.tab.pdf $wdir/$donor".HLA.pdf" cd $wdir } #dataset 719 #run719(){ # local stemDir="/home/tianr/dataset/singleCellRNAseq/multiple_myeloma_SRP132719_3.12" # local exprsDir=$stemDir"/RPKM" # local hlaDir=$stemDir"/results_SRP132719_multiple_myeloma/results_seq2hla.2019.3.12" # goMove $stemDir"/readme/SRP132719_SraRunTable.txt.c2p" #} #run719 #dataset 590 stemDir="/home/tianr/dataset/singleCellRNAseq/SRP158590_CD138positive_15patients_MM" exprsDir=$stemDir"/RPKM" hlaDir=$stemDir"/results_SRP158590_CD138positive_15patients_MM/results_sra2hla" path="./" $path"getCell2Donor2.sh" $stemDir"/readme/SRP158590_SraRunTable.txt" sampleDonorTable=$stemDir"/readme/SRP158590_SraRunTable.txt.c2p" goMove $sampleDonorTable for dir in `less $sampleDonorTable | grep SRR |cut -f2 | sort | uniq |tr "\n" " "` do #echo $dir runByDonor $dir $exprsDir $hlaDir done
Markdown
UTF-8
2,178
3.15625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- layout: page title: 童年 --- 夏天是什麼做的?\\ 銼冰、芋仔冰、枝仔冰\\ 巴布、巴布,賣--豆--花--喔 滾燙燙的柏油路\\ 熱烘烘的日頭 家裏沒冰箱\\ 樓上二房東家有\\ 房東家女兒用砂糖加開水\\ 注入布丁型鋁容器\\ 放入冷凍庫\\ 結成一個個小小布丁型冰棒\\ 一面舔著吃,一面不自覺炫耀著\\ 妺妺看到了,很想吃\\ 姐姐有零用錢\\ 就向房東家女兒買小小的布丁型冰棒 姐姐勤奮又聰明\\ 暑假到成衣廠踩縫紉機\\ 學期間帶橘子零食到學校賣\\ 賺的錢拿給媽媽\\ 媽媽很高興\\ 給姐姐一點零用錢\\ 姐姐用自己的零用錢\\ 買冰棒給妹妹吃 家裏沒冰箱\\ 哥哥買了個大西瓜\\ 放在水桶裏裝了水\\ 妹妹跑到巷尾的柑仔店\\ 向外省婆仔買冰塊\\ 四四方方的冰塊\\ 一塊塊\\ 放在冰庫裏\\ 外省婆仔拉開冰庫門\\ 一陣冷氣襲面而來\\ 好涼喔 妹妹提著麻繩綁起來的冰塊\\ 一路跑回家\\ 哥哥將冰塊放入水桶\\ 三重大拜拜\\ 等客人吃飽喝夠\\ 可以來片冰冰涼涼的西瓜\\ 妹妹嚥了口口水\\ 如果客人沒吃完\\ 妹妹也可以嚐一片\\ 冰冰涼涼的紅西瓜 家裏沒冰箱\\ 妹妹想吃枝仔冰\\ 爸爸也想吃枝仔冰\\ 從口袋裏掏出一張五元鈔票\\ 讓妹妹去買枝仔冰\\ 一枝枝仔冰五角錢\\ 五塊錢可以買十枝枝仔冰\\ 十枝枝仔冰,十枝枝仔冰\\ 妹妹一路走、一路想 日頭熱烘烘\\ 柏油路滾燙燙 妹妹一心想著十枝枝仔冰\\ 快快走,快快走\\ 一個轉彎再一個轉彎\\ 一個巷弄再一個巷弄\\ 妹妹把錢遞給賣枝仔冰的婦人\\ 挑了十枝枝仔冰\\ 紅豆、綠豆、花生、牛奶、鳳梨、芋仔、…\\ 妹妹最喜歡芋仔枝仔冰\\ 快快走,快快走\\ 十枝枝仔冰\\ 或許可以吃兩枝\\ 兩枝芋仔枝仔冰\\ 妹妹嚥下一口又一口口水 滾燙燙的柏油路\\ 熱烘烘的日頭 夏天是什麼做的?\\ 一枝枝仔冰\\ 兩粒芋仔冰\\ 一盤銼冰\\ 一碗豆花\\ 就叫人雀躍不已的童年 ![lilimist](/images/food/Food2010-04-15_P6924-800x.jpg "蓮霧")
Python
UTF-8
443
3.296875
3
[]
no_license
# Create a method that decrypts texts/encoded_zen_lines.txt def decrypt(file_name): my_file = open(file_name, "r") chars = [] s='' message = "" for line in my_file: for c in line: chars.append(c) for i in range(0, len(chars)): if chars[i] != ' ' and chars[i] != '\n': chars[i] = chr(ord(chars[i]) - 1) message = s.join(chars) print(message) decrypt("encoded-lines.txt")
Markdown
UTF-8
1,062
2.5625
3
[ "MIT" ]
permissive
USE sdz9w1lbrjjeliul; INSERT INTO Definitions (topic, definition, example, language) VALUES ('HTML', 'Hyper-Text Markup Language is the standard markup language for creating web pages.', '', 'HTML'); INSERT INTO Definitions (topic, definition, example, language) VALUES ('Tags','HTML tags label pieces of content such as "heading", "paragraph", "table", and so on.','<h1>Hello World!(/h1>','HTML'); INSERT INTO Definitions (topic, definition, example, language) VALUES ('Elements','An HTML element is defined by a start tag, some content, and an end tag.','<tagname>Content goes here...</tagname>','HTML'); INSERT INTO Definitions (topic, definition, example, language) VALUES ('Attributes','An attribute provides additional information about an HTML element and usually come in name/value pairs like: name="value".','HTML'); INSERT INTO Definitions (topic, definition, example, language) VALUES ('Links', 'HTML links are known as Hyperlinks and direct the user to other web addresses or pages within the same URL.', '<a href="url">link text</a>','HTML');
Shell
UTF-8
4,214
3.421875
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # # DART software - Copyright UCAR. This open source software is provided # by UCAR, "as is", without charge, subject to all terms of use at # http://www.image.ucar.edu/DAReS/DART/DART_download # # DART $Id$ # # split the monthly file into "daily" files which start at 12:01Z # the previous day and end at 12:00Z on the day that matches the # day in the filename. # #BSUB -J splitobs #BSUB -W 4:00 #BSUB -o %J.out #BSUB -e %J.err #BSUB -q share #BSUB -P 93300315 #BSUB -n 1 # set the first and last days to be split. can roll over # month and year boundaries now! note that for the first day # you need the previous day data available. let start_year=1998 let start_month=1 let start_day=2 let end_year=1999 let end_month=12 let end_day=31 EXEDIR='../work' DATDIR='../data' # end of things you should have to set in this script # convert the start and stop times to gregorian days, so we can # compute total number of days including rolling over month and # year boundaries. make sure all values have leading 0s if they # are < 10. do the end time first so we can use the same values # to set the initial day while we are doing the total day calc. # these outputs from advance time (with the -g flag) are # 2 integers: gregorian_day_number seconds # and since we don't set hours, minutes, or seconds, the second # number is always 0 and uninteresting for us. mon2=`printf %02d $end_month` day2=`printf %02d $end_day` end_d=(`echo ${end_year}${mon2}${day2}00 0 -g | ${EXEDIR}/advance_time`) #echo $end_d mon2=`printf %02d $start_month` day2=`printf %02d $start_day` start_d=(`echo ${start_year}${mon2}${day2}00 0 -g | ${EXEDIR}/advance_time`) #echo $start_d # these are a string in the format YYYYMMDDHH # do them here to prime the loop below which first takes them apart. currday=(`echo ${start_year}${mon2}${day2}00 0 | ${EXEDIR}/advance_time`) nextday=(`echo ${start_year}${mon2}${day2}00 +1d | ${EXEDIR}/advance_time`) prevday=(`echo ${start_year}${mon2}${day2}00 -1d | ${EXEDIR}/advance_time`) # how many total days are going to be merged (for the loop counter) # (pull out the first of the 2 numbers which are output from advance_time) let totaldays=${end_d}-${start_d}+1 #echo $totaldays # loop over each day let d=1 while (( d <= totaldays)) ; do #echo top of loop #echo $currday $nextday # parse out the parts from a string which is YYYYMMDDHH # both for the current day and tomorrow cyear=${currday:0:4} cmonth=${currday:4:2} cday=${currday:6:2} nyear=${nextday:0:4} nmonth=${nextday:4:2} nday=${nextday:6:2} pyear=${prevday:0:4} pmonth=${prevday:4:2} pday=${prevday:6:2} #echo curr $cyear $cmonth $cday #echo next $nyear $nmonth $nday #echo prev $pyear $pmonth $pday # compute the equivalent gregorian days here. g=(`echo ${cyear}${cmonth}${cday}00 -1d -g | ${EXEDIR}/advance_time`) greg0=${g[0]} g=(`echo ${cyear}${cmonth}${cday}00 0 -g | ${EXEDIR}/advance_time`) greg1=${g[0]} g=(`echo ${cyear}${cmonth}${cday}00 +1d -g | ${EXEDIR}/advance_time`) greg2=${g[0]} #echo $greg0 $greg1 $greg2 echo starting WOD obs for ${cyear}${cmonth}${cday} gregorian= $greg1 # last 12 hrs yesterdays data plus the first 12 hrs of todays if [[ ${cmonth} == '01' && ${cday} == '01' ]] ; then echo "${DATDIR}/obs_seq${pyear}.wod" > olist echo "${DATDIR}/obs_seq${cyear}.wod" >> olist else echo "${DATDIR}/obs_seq${cyear}.wod" > olist fi sed -e "s/YYYY/${cyear}/g" \ -e "s/MM/${cmonth}/g" \ -e "s/PP/${pmonth}/g" \ -e "s/DD/${cday}/g" \ -e "s/GREG0/${greg0}/g" \ -e "s/GREG1/${greg1}/g" \ -e "s/GREG2/${greg2}/g" < ./input.nml.template > input.nml # make sure output dir exists if [[ ! -d ../${cyear}${cmonth} ]] ; then mkdir ../${cyear}${cmonth} fi # do the extract here ${EXEDIR}/obs_sequence_tool # advance the day; the output is YYYYMMDD00 prevday=$currday currday=$nextday nextday=(`echo ${nyear}${nmonth}${nday}00 +1d | ${EXEDIR}/advance_time`) #echo $currday $nextday $prevday # advance the loop counter let d=d+1 #echo d=$d done exit 0 # <next few lines under version control, do not edit> # $URL$ # $Revision$ # $Date$
Java
UTF-8
1,292
2.484375
2
[]
no_license
package de.chusek.sessionkeeper.logic; import android.content.ContentValues; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; import java.util.List; import de.chusek.sessionkeeper.gui.PlayerActivity; import de.chusek.sessionkeeper.model.Player; /** * Created by carsten on 14.02.2017. */ public class PlayerListOnItemClickListener implements AdapterView.OnItemClickListener { private AppCompatActivity linkedActivity; private List<Player> players; public PlayerListOnItemClickListener(AppCompatActivity linkedActivity, List<Player> plist) { this.linkedActivity = linkedActivity; players = plist; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(linkedActivity, String.valueOf(position)+";"+String.valueOf(id), Toast.LENGTH_SHORT).show(); // the same procedure as everywhere Intent nextActivity = new Intent(linkedActivity, PlayerActivity.class); //add extra to intent! with PUT , sigh // and u cant pass anything so again ContentValues seems our friend nextActivity.putExtra("player", players.get(position).toCVal()); linkedActivity.startActivity(nextActivity); } }
Java
UTF-8
7,052
3.234375
3
[]
no_license
/* * Copyright 2019 mon-mode - 0mon.mode@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.japo.java.main; import java.util.Locale; import java.util.Scanner; /** * * @author nv3ob61 */ public class Main { public static final Scanner SCN = new Scanner(System.in, "Windows-1252") .useLocale(Locale.ENGLISH).useDelimiter("\\s+"); public static void main(String[] args) { //Variables int year; int month; int day = 0; int max_month = 0; //int para sumar 1 al módulo para sacar el día. NO ES BOOLEAN! int isBisiesto; /** * ********************************************************************** * FALTA CONTROLAR PARÁMETROS DE ENTRADA.... * /********************************************************************* */ //Validamos año System.out.println("Introduzca año: "); year = SCN.nextInt(); //Validamos mes do { System.out.println("Introduzca mes (1 a 12)"); month = SCN.nextInt(); } while (month > 12 || month < 1); //Switch para delimitar el nº de días switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: //Todos estos casos son meses con 31 días System.out.println("Meses con 31 días máx."); max_month = 31; break; //Caso para febrero, comprueba si el año es bisiesto llamando // a isLeap(year); Si es bisiesto max_month = 29, else ... = 28; case 2: System.out.println("Febrero, es bisiesto o no?"); System.out.println(isLeap(year)); if (isLeap(year)) { max_month = 29; } else { max_month = 28; } break; case 4: case 6: case 9: case 11: //Todos estos casos son meses con 30 días System.out.println("Meses con 30 días test"); max_month = 30; break; default: break; } //Validamos el día do { System.out.println("Introduce el día: "); day = SCN.nextInt(); } while (day > max_month || day < 1); //módulo para sacar el día.. Empieza cogiendo un valor si el año es Leap // o no. if (isLeap(year) == true) { isBisiesto = 1; } else { isBisiesto = 0; } //cálculos para el módulo del día de la semana. modulo_mes(month, isBisiesto); //Definimos a lo guarro las variables aquí. MODIFICAR. int a = (year - 1) % 7; int d = day % 7; int dm = (((year - 1) / 4) - (3 * ((year - 1) / 100 + 1) / 4)) % 7; int resultado = (a + d + modulo_mes(month, isBisiesto) + dm) % 7; //SALIDA: pasamos el resultado a un string y sout. String busca_dia = busca_dia(resultado); System.out.println(busca_dia); } //Método para esBiesto... public static boolean isLeap(int year) { boolean leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); return leap; } //Método que devuelve un string con el nombre del día que validamos public static String busca_dia(int day) { String stringDia = " "; switch (day) { case 1: stringDia = "Lunes"; break; case 2: stringDia = "Martes"; break; case 3: stringDia = "Miércoles"; break; case 4: stringDia = "Jueves"; break; case 5: stringDia = "Viernes"; break; case 6: stringDia = "Sábado"; break; case 0: stringDia = "Domingo"; break; } return stringDia; } //Método que pasando el nº de mes y si es bisiesto calcula el módulo para // determinar el día de la semana de la fecha a validar. public static int modulo_mes(int mes, int bisiesto) { int modulo = 0; switch (mes) { case 1: modulo = 0; break; case 2: modulo = 3; break; case 3: if (bisiesto == 1) { modulo = 4; } else { modulo = 3; } break; case 4: if (bisiesto == 1) { modulo = 0; } else { modulo = 6; } break; case 5: if (bisiesto == 1) { modulo = 2; } else { modulo = 1; } break; case 6: if (bisiesto == 1) { modulo = 5; } else { modulo = 4; } break; case 7: if (bisiesto == 1) { modulo = 0; } else { modulo = 6; } break; case 8: if (bisiesto == 1) { modulo = 3; } else { modulo = 2; } break; case 9: if (bisiesto == 1) { modulo = 6; } else { modulo = 5; } break; case 10: if (bisiesto == 1) { modulo = 0; } else { modulo = 1; } break; case 11: if (bisiesto == 1) { modulo = 4; } else { modulo = 3; } break; case 12: if (bisiesto == 1) { modulo = 6; } else { modulo = 5; } break; } return modulo; } }
C++
UTF-8
15,022
2.875
3
[]
no_license
/** * * @author Carmel & Efrat & Odelia * @since 2019-03 */ #include <iostream> #include <sstream> using std::cout, std::endl, std::istringstream; #include "PhysicalNumber.h" using ariel::PhysicalNumber, ariel::Unit; #include "badkan.hpp" int main() { badkan::TestCase testcase; int grade=0; int signal = setjmp(badkan::longjmp_buffer); if (signal == 0) { // BASIC TESTS - DO NOT CHANGE PhysicalNumber a(2, Unit::KM); PhysicalNumber b(300, Unit::M); PhysicalNumber c(2, Unit::HOUR); PhysicalNumber d(30, Unit::MIN); PhysicalNumber e(3.2,Unit::KM); PhysicalNumber f(80,Unit::M); PhysicalNumber g(20, Unit::CM); PhysicalNumber h(90, Unit::SEC); PhysicalNumber i(40, Unit::MIN); PhysicalNumber j(1, Unit::HOUR); PhysicalNumber k(100, Unit::G); PhysicalNumber l(5.3, Unit::KG); PhysicalNumber m(7, Unit::TON); testcase .setname("Basic output") .CHECK_OUTPUT(a, "2[km]") .CHECK_OUTPUT(b, "300[m]") .setname("Compatible dimensions") .CHECK_OUTPUT(b+a, "2300[m]") .CHECK_OUTPUT((a+=b), "2.3[km]") .CHECK_OUTPUT(a, "2.3[km]") .CHECK_OUTPUT(a+a, "4.6[km]") .CHECK_OUTPUT(b-b, "0[m]") .CHECK_OUTPUT(c, "2[hour]") .CHECK_OUTPUT(d, "30[min]") .CHECK_OUTPUT(d+c, "150[min]") .setname("Incompatible dimensions") .CHECK_THROWS(a+c) .CHECK_THROWS(a+d) .CHECK_THROWS(b+c) .CHECK_THROWS(b+d) .setname("Basic input") .CHECK_OK(istringstream("700[kg]") >> a) .CHECK_OUTPUT((a += PhysicalNumber(1, Unit::TON)), "1700[kg]") // YOUR TESTS - INSERT AS MANY AS YOU WANT .setname("Basic output- km,m,cm") .CHECK_OUTPUT(e, "3.2[km]") .CHECK_OUTPUT(f, "80[m]") .CHECK_OUTPUT(g, "20[cm]") .setname("Compatible dimensions- km,m,cm") .CHECK_OUTPUT(-e,"-3.2[km]") .CHECK_OUTPUT(-f, "-80[m]") .CHECK_OUTPUT(-g, "-20[cm]") .CHECK_OUTPUT(+e,"3.2[km]") .CHECK_OUTPUT(+f, "80[m]") .CHECK_OUTPUT(+g, "20[cm]") .CHECK_OUTPUT(++e,"4.2[km]") .CHECK_OUTPUT(++f, "81[m]") .CHECK_OUTPUT(++g, "21[cm]") .CHECK_OUTPUT(--e,"3.2[km]") .CHECK_OUTPUT(--f, "80[m]") .CHECK_OUTPUT(--g, "20[cm]") .CHECK_OK(e++) .CHECK_OUTPUT(e,"4.2[km]") .CHECK_OK(f++) .CHECK_OUTPUT(f, "81[m]") .CHECK_OK(g++) .CHECK_OUTPUT(g, "21[cm]") .CHECK_OK(e--) .CHECK_OUTPUT(e,"3.2[km]") .CHECK_OK(f--) .CHECK_OUTPUT(f, "80[m]") .CHECK_OK(g--) .CHECK_OUTPUT(g, "20[cm]") .CHECK_OUTPUT(f+g,"80.2[m]") .CHECK_OUTPUT(g+f,"8020[cm]") .CHECK_OUTPUT(e+f,"3.28[km]") .CHECK_OUTPUT(f+e,"3280[m]") .CHECK_OUTPUT(g+e,"320020[cm]") .CHECK_OUTPUT(e+g,"3.2002[km]") .CHECK_OUTPUT(f-g,"79.8[m]") .CHECK_OUTPUT(e-f,"3.12[km]") .CHECK_OUTPUT(g-f,"-7980[cm]") .CHECK_OUTPUT(f-e,"-3120[m]") .CHECK_OUTPUT(g-e,"-319980[cm]") .CHECK_OUTPUT(e-g,"3.1998[km]") .CHECK_OUTPUT((e+=f),"3.28[km]") //--> e=3.28 km .CHECK_OUTPUT(e,"3.28[km]") .CHECK_OUTPUT(e+e,"6.56[km]") .CHECK_OUTPUT((f-=g),"79.8[m]") //--> f=79.8 m .CHECK_OUTPUT(f,"79.8[m]") .CHECK_OUTPUT(f-f,"0[m]") .CHECK_EQUAL(f<e,true) .CHECK_OUTPUT((g+=f),"8000[cm]") //--> g = 8000 cm .CHECK_OUTPUT(g,"8000[cm]") .CHECK_EQUAL(f<=g,true) .CHECK_OUTPUT((g-=g),"0[cm]") .CHECK_OUTPUT(g,"0[cm]") //--> g = 0 cm .CHECK_OUTPUT(--g, "-1[cm]") //--> g = -1 cm .CHECK_OUTPUT(+g,"-1[cm]") //--> g = -1 cm .CHECK_EQUAL(f>g,true) .CHECK_EQUAL(e>=g,true) .CHECK_EQUAL(g==PhysicalNumber(-1, Unit::CM),true) .setname("Incompatible dimensions- km,m,cm -- (+,-,+=,-=,<,>,<=,>=)") .CHECK_THROWS(e+h) .CHECK_THROWS(e+i) .CHECK_THROWS(e+j) .CHECK_THROWS(e+k) .CHECK_THROWS(e+l) .CHECK_THROWS(e+m) .CHECK_THROWS(f+h) .CHECK_THROWS(f+i) .CHECK_THROWS(f+j) .CHECK_THROWS(f+k) .CHECK_THROWS(f+l) .CHECK_THROWS(f+m) .CHECK_THROWS(g+h) .CHECK_THROWS(g+i) .CHECK_THROWS(g+j) .CHECK_THROWS(g+k) .CHECK_THROWS(g+l) .CHECK_THROWS(g+m) .CHECK_THROWS(e+=h) .CHECK_THROWS(e+=i) .CHECK_THROWS(e+=j) .CHECK_THROWS(e+=k) .CHECK_THROWS(e+=l) .CHECK_THROWS(e+=m) .CHECK_THROWS(f+=h) .CHECK_THROWS(f+=i) .CHECK_THROWS(f+=j) .CHECK_THROWS(f+=k) .CHECK_THROWS(f+=l) .CHECK_THROWS(f+=m) .CHECK_THROWS(g+=h) .CHECK_THROWS(g+=i) .CHECK_THROWS(g+=j) .CHECK_THROWS(g+=k) .CHECK_THROWS(g+=l) .CHECK_THROWS(g+=m) .CHECK_THROWS(e-h) .CHECK_THROWS(e-i) .CHECK_THROWS(e-j) .CHECK_THROWS(e-k) .CHECK_THROWS(e-l) .CHECK_THROWS(e-m) .CHECK_THROWS(f-h) .CHECK_THROWS(f-i) .CHECK_THROWS(f-j) .CHECK_THROWS(f-k) .CHECK_THROWS(f-l) .CHECK_THROWS(f-m) .CHECK_THROWS(g-h) .CHECK_THROWS(g-i) .CHECK_THROWS(g-j) .CHECK_THROWS(g-k) .CHECK_THROWS(g-l) .CHECK_THROWS(g-m) .CHECK_THROWS(e-=h) .CHECK_THROWS(e-=i) .CHECK_THROWS(e-=j) .CHECK_THROWS(e-=k) .CHECK_THROWS(e-=l) .CHECK_THROWS(e-=m) .CHECK_THROWS(f-=h) .CHECK_THROWS(f-=i) .CHECK_THROWS(f-=j) .CHECK_THROWS(f-=k) .CHECK_THROWS(f-=l) .CHECK_THROWS(f-=m) .CHECK_THROWS(g-=h) .CHECK_THROWS(g-=i) .CHECK_THROWS(g-=j) .CHECK_THROWS(g-=k) .CHECK_THROWS(g-=l) .CHECK_THROWS(g-=m) .CHECK_THROWS(e<h) .CHECK_THROWS(e<i) .CHECK_THROWS(e<j) .CHECK_THROWS(e<k) .CHECK_THROWS(e<l) .CHECK_THROWS(e<m) .CHECK_THROWS(f<h) .CHECK_THROWS(f<i) .CHECK_THROWS(f<j) .CHECK_THROWS(f<k) .CHECK_THROWS(f<l) .CHECK_THROWS(f<m) .CHECK_THROWS(g<h) .CHECK_THROWS(g<i) .CHECK_THROWS(g<j) .CHECK_THROWS(g<k) .CHECK_THROWS(g<l) .CHECK_THROWS(g<m) .CHECK_THROWS(e<=h) .CHECK_THROWS(e<=i) .CHECK_THROWS(e<=j) .CHECK_THROWS(e<=k) .CHECK_THROWS(e<=l) .CHECK_THROWS(e<=m) .CHECK_THROWS(f<=h) .CHECK_THROWS(f<=i) .CHECK_THROWS(f<=j) .CHECK_THROWS(f<=k) .CHECK_THROWS(f<=l) .CHECK_THROWS(f<=m) .CHECK_THROWS(g<=h) .CHECK_THROWS(g<=i) .CHECK_THROWS(g<=j) .CHECK_THROWS(g<=k) .CHECK_THROWS(g<=l) .CHECK_THROWS(g<=m) .CHECK_THROWS(e>=h) .CHECK_THROWS(e>=i) .CHECK_THROWS(e>=j) .CHECK_THROWS(e>=k) .CHECK_THROWS(e>=l) .CHECK_THROWS(e>=m) .CHECK_THROWS(f>=h) .CHECK_THROWS(f>=i) .CHECK_THROWS(f>=j) .CHECK_THROWS(f>=k) .CHECK_THROWS(f>=l) .CHECK_THROWS(f>=m) .CHECK_THROWS(g>=h) .CHECK_THROWS(g>=i) .CHECK_THROWS(g>=j) .CHECK_THROWS(g>=k) .CHECK_THROWS(g>=l) .CHECK_THROWS(g>=m) .CHECK_THROWS(e>h) .CHECK_THROWS(e>i) .CHECK_THROWS(e>j) .CHECK_THROWS(e>k) .CHECK_THROWS(e>l) .CHECK_THROWS(e>m) .CHECK_THROWS(f>h) .CHECK_THROWS(f>i) .CHECK_THROWS(f>j) .CHECK_THROWS(f>k) .CHECK_THROWS(f>l) .CHECK_THROWS(f>m) .CHECK_THROWS(g>h) .CHECK_THROWS(g>i) .CHECK_THROWS(g>j) .CHECK_THROWS(g>k) .CHECK_THROWS(g>l) .CHECK_THROWS(g>m) .CHECK_THROWS(e==h) .CHECK_THROWS(e==i) .CHECK_THROWS(e==j) .CHECK_THROWS(e==k) .CHECK_THROWS(e==l) .CHECK_THROWS(e==m) .CHECK_THROWS(f==h) .CHECK_THROWS(f==i) .CHECK_THROWS(f==j) .CHECK_THROWS(f==k) .CHECK_THROWS(f==l) .CHECK_THROWS(f==m) .CHECK_THROWS(g==h) .CHECK_THROWS(g==i) .CHECK_THROWS(g==j) .CHECK_THROWS(g==k) .CHECK_THROWS(g==l) .CHECK_THROWS(g==m) .CHECK_THROWS(e!=h) .CHECK_THROWS(e!=i) .CHECK_THROWS(e!=j) .CHECK_THROWS(e!=k) .CHECK_THROWS(e!=l) .CHECK_THROWS(e!=m) .CHECK_THROWS(f!=h) .CHECK_THROWS(f!=i) .CHECK_THROWS(f!=j) .CHECK_THROWS(f!=k) .CHECK_THROWS(f!=l) .CHECK_THROWS(f!=m) .CHECK_THROWS(g!=h) .CHECK_THROWS(g!=i) .CHECK_THROWS(g!=j) .CHECK_THROWS(g!=k) .CHECK_THROWS(g!=l) .CHECK_THROWS(g!=m) .setname("Basic output- hour,min,sec") .CHECK_OUTPUT(h, "90[sec]") .CHECK_OUTPUT(i, "40[min]") .CHECK_OUTPUT(j, "1[hour]") .setname("Compatible dimensions- hour,min,sec") .CHECK_OUTPUT(-h, "-90[sec]") .CHECK_OUTPUT(-i, "-40[min]") .CHECK_OUTPUT(-j, "-1[hour]") .CHECK_OUTPUT(+h, "90[sec]") .CHECK_OUTPUT(+i, "40[min]") .CHECK_OUTPUT(+j, "1[hour]") .CHECK_OUTPUT(++h, "91[sec]") .CHECK_OUTPUT(++i, "41[min]") .CHECK_OUTPUT(++j, "2[hour]") .CHECK_OUTPUT(--h, "90[sec]") .CHECK_OUTPUT(--i, "40[min]") .CHECK_OUTPUT(--j, "1[hour]") .CHECK_OK(h++) .CHECK_OUTPUT(h, "91[sec]") .CHECK_OK(i++) .CHECK_OUTPUT(i, "41[min]") .CHECK_OK(j++) .CHECK_OUTPUT(j, "2[hour]") .CHECK_OK(h--) .CHECK_OUTPUT(h, "90[sec]") .CHECK_OK(i--) .CHECK_OUTPUT(i, "40[min]") .CHECK_OK(j--) .CHECK_OUTPUT(j, "1[hour]") .CHECK_OUTPUT(h+i,"2490[sec]") .CHECK_OUTPUT(i+h,"41.5[min]") .CHECK_OUTPUT(h+j,"3690[sec]") //.CHECK_OUTPUT(j+h,"1.02500[hour]") .CHECK_OUTPUT(i+j,"100[min]") // .CHECK_OUTPUT(j+i,"1.66666667[hour]") .CHECK_OUTPUT(i-h,"38.5[min]") .CHECK_OUTPUT(j-h,"0.975[hour]") .CHECK_OUTPUT(h-i,"-2310[sec]") .CHECK_OUTPUT(h-j,"-3510[sec]") .CHECK_OUTPUT(i-j,"-20[min]") //.CHECK_OUTPUT(j-i,"0.333333333[hour]") .CHECK_OUTPUT((i+=j),"100[min]") // --> i=100 min .CHECK_OUTPUT(i,"100[min]") .CHECK_OUTPUT(i+i,"200[min]") .CHECK_OUTPUT((j-=h),"0.975[hour]") //--> j=0.975 hour .CHECK_OUTPUT(j,"0.975[hour]") .CHECK_EQUAL(j<i,true) .CHECK_OUTPUT(j-j,"0[hour]") .CHECK_OUTPUT(i-j,"41.5[min]") .CHECK_OUTPUT((h+=j),"3600[sec]") //-->h=3600 sec .CHECK_OUTPUT(h,"3600[sec]") .CHECK_EQUAL(h>j,true) .CHECK_EQUAL(i==PhysicalNumber(100, Unit::MIN),true) .CHECK_EQUAL(h<=i,true) .CHECK_EQUAL(i>=j,true) .setname("Incompatible dimensions- hour,min,sec -- (+,-,+=,-=,<,>,<=,>=)") .CHECK_THROWS(h+k) .CHECK_THROWS(h+l) .CHECK_THROWS(h+m) .CHECK_THROWS(i+k) .CHECK_THROWS(i+l) .CHECK_THROWS(i+m) .CHECK_THROWS(j+k) .CHECK_THROWS(j+l) .CHECK_THROWS(j+m) .CHECK_THROWS(h+=k) .CHECK_THROWS(h+=l) .CHECK_THROWS(h+=m) .CHECK_THROWS(i+=k) .CHECK_THROWS(i+=l) .CHECK_THROWS(i+=m) .CHECK_THROWS(j+=k) .CHECK_THROWS(j+=l) .CHECK_THROWS(j+=m) .CHECK_THROWS(h-k) .CHECK_THROWS(h-l) .CHECK_THROWS(h-m) .CHECK_THROWS(i-k) .CHECK_THROWS(i-l) .CHECK_THROWS(i-m) .CHECK_THROWS(j-k) .CHECK_THROWS(j-l) .CHECK_THROWS(j-m) .CHECK_THROWS(h-=k) .CHECK_THROWS(h-=l) .CHECK_THROWS(h-=m) .CHECK_THROWS(i-=k) .CHECK_THROWS(i-=l) .CHECK_THROWS(i-=m) .CHECK_THROWS(j-=k) .CHECK_THROWS(j-=l) .CHECK_THROWS(j-=m) .CHECK_THROWS(h<k) .CHECK_THROWS(h<l) .CHECK_THROWS(h<m) .CHECK_THROWS(i<k) .CHECK_THROWS(i<l) .CHECK_THROWS(i<m) .CHECK_THROWS(j<k) .CHECK_THROWS(j<l) .CHECK_THROWS(j<m) .CHECK_THROWS(h<=k) .CHECK_THROWS(h<=l) .CHECK_THROWS(h<=m) .CHECK_THROWS(i<=k) .CHECK_THROWS(i<=l) .CHECK_THROWS(i<=m) .CHECK_THROWS(j<=k) .CHECK_THROWS(j<=l) .CHECK_THROWS(j<=m) .CHECK_THROWS(h>k) .CHECK_THROWS(h>l) .CHECK_THROWS(h>m) .CHECK_THROWS(i>k) .CHECK_THROWS(i>l) .CHECK_THROWS(i>m) .CHECK_THROWS(j>k) .CHECK_THROWS(j>l) .CHECK_THROWS(j>m) .CHECK_THROWS(h>=k) .CHECK_THROWS(h>=l) .CHECK_THROWS(h>=m) .CHECK_THROWS(i>=k) .CHECK_THROWS(i>=l) .CHECK_THROWS(i>=m) .CHECK_THROWS(j>=k) .CHECK_THROWS(j>=l) .CHECK_THROWS(j>=m) .CHECK_THROWS(h==k) .CHECK_THROWS(h==l) .CHECK_THROWS(h==m) .CHECK_THROWS(i==k) .CHECK_THROWS(i==l) .CHECK_THROWS(i==m) .CHECK_THROWS(j==k) .CHECK_THROWS(j==l) .CHECK_THROWS(j==m) .CHECK_THROWS(h!=k) .CHECK_THROWS(h!=l) .CHECK_THROWS(h!=m) .CHECK_THROWS(i!=k) .CHECK_THROWS(i!=l) .CHECK_THROWS(i!=m) .CHECK_THROWS(j!=k) .CHECK_THROWS(j!=l) .CHECK_THROWS(j!=m) .setname("Basic output-ton,kg,g") .CHECK_OUTPUT(k, "100[g]") .CHECK_OUTPUT(l, "5.3[kg]") .CHECK_OUTPUT(m, "7[ton]") .setname("Compatible dimensions-ton,kg,g") .CHECK_OUTPUT(-k, "-100[g]") .CHECK_OUTPUT(-l, "-5.3[kg]") .CHECK_OUTPUT(-m, "-7[ton]") .CHECK_OUTPUT(+k, "100[g]") .CHECK_OUTPUT(+l, "5.3[kg]") .CHECK_OUTPUT(+m, "7[ton]") .CHECK_OUTPUT(++k, "101[g]") .CHECK_OUTPUT(++l, "6.3[kg]") .CHECK_OUTPUT(++m, "8[ton]") .CHECK_OUTPUT(--k, "100[g]") .CHECK_OUTPUT(--l, "5.3[kg]") .CHECK_OUTPUT(--m, "7[ton]") .CHECK_OK(k++) .CHECK_OUTPUT(k, "101[g]") .CHECK_OK(l++) .CHECK_OUTPUT(l, "6.3[kg]") .CHECK_OK(m++) .CHECK_OUTPUT(m, "8[ton]") .CHECK_OK(k--) .CHECK_OUTPUT(k, "100[g]") .CHECK_OK(l--) .CHECK_OUTPUT(l, "5.3[kg]") .CHECK_OK(m--) .CHECK_OUTPUT(m, "7[ton]") .CHECK_OUTPUT(k+l,"5400[g]") .CHECK_OUTPUT(l+k,"5.4[kg]") //.CHECK_OUTPUT(k+m,"7000100[g]") .CHECK_OUTPUT(m+k,"7.0001[ton]") .CHECK_OUTPUT(l+m,"7005.3[kg]") .CHECK_OUTPUT(m+l,"7.0053[ton]") .CHECK_OUTPUT(l-k,"5.2[kg]") .CHECK_OUTPUT(m-k,"6.9999[ton]") .CHECK_OUTPUT(k-l,"-5200[g]") //.CHECK_OUTPUT(k-m,"-6999900[g]") .CHECK_OUTPUT(l-m,"-6994.7[kg]") .CHECK_OUTPUT(m-l,"6.9947[ton]") .CHECK_OUTPUT((l+=k),"5.4[kg]") // --> l=5.4 kg .CHECK_OUTPUT(l,"5.4[kg]") .CHECK_OUTPUT(l+l,"10.8[kg]") // .CHECK_EQUAL(l==PhysicalNumber(5.4,Unit::KG),true) .CHECK_OUTPUT((m-=k),"6.9999[ton]") //--> m=6.9999 ton .CHECK_OUTPUT(m,"6.9999[ton]") .CHECK_OUTPUT(m-m,"0[ton]") .CHECK_EQUAL(m>=l,true) // .CHECK_OUTPUT((k+=m),"7000100[g]") //--> k=7000100 g // .CHECK_OUTPUT(k,"7000100[g]") .CHECK_OUTPUT(k-k,"0[g]") // .CHECK_EQUAL(k>l,true) // .CHECK_EQUAL(m<=k,true) .CHECK_EQUAL(l<m,true) .setname("check input") .CHECK_OK(istringstream("2[min]") >> e) .CHECK_OUTPUT((e += PhysicalNumber(30, Unit::SEC)), "2.5[min]") .CHECK_OK(istringstream("30[kg]") >> l) .CHECK_OUTPUT((l += PhysicalNumber(50, Unit::G)), "30.05[kg]") .CHECK_OK(istringstream("5[m]") >> k) .CHECK_OUTPUT((k += PhysicalNumber(20, Unit::CM)), "5.2[m]") .setname("check conversions") .CHECK_EQUAL((PhysicalNumber(1, Unit::HOUR))==(PhysicalNumber(60, Unit::MIN)),true) .CHECK_EQUAL((PhysicalNumber(3600, Unit::SEC))==(PhysicalNumber(60, Unit::MIN)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::HOUR))==(PhysicalNumber(3600, Unit::SEC)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::MIN))==(PhysicalNumber(60, Unit::SEC)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::M))==(PhysicalNumber(100, Unit::CM)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::KM))==(PhysicalNumber(1000, Unit::M)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::KM))==(PhysicalNumber(100000, Unit::CM)),true) .CHECK_EQUAL((PhysicalNumber(1000, Unit::M))==(PhysicalNumber(100000, Unit::CM)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::KG))==(PhysicalNumber(1000, Unit::G)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::TON))==(PhysicalNumber(1000, Unit::KG)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::TON))==(PhysicalNumber(1000000, Unit::G)),true) .CHECK_EQUAL((PhysicalNumber(1000, Unit::KG))==(PhysicalNumber(1000000, Unit::G)),true) .CHECK_EQUAL((PhysicalNumber(1000, Unit::KG))!=(PhysicalNumber(100, Unit::G)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::HOUR))!=(PhysicalNumber(1, Unit::MIN)),true) .CHECK_EQUAL((PhysicalNumber(23, Unit::M))!=(PhysicalNumber(100000, Unit::CM)),true) .CHECK_EQUAL((PhysicalNumber(1, Unit::TON))!=(PhysicalNumber(60, Unit::G)),true) .print(cout, /*show_grade=*/false); grade = testcase.grade(); } else { testcase.print_signal(signal); grade = 0; } cout << "*** Grade: " << grade << " ***" << endl; return grade; }
JavaScript
UTF-8
820
2.59375
3
[]
no_license
import axios from 'axios'; class BlogService { constructor() { let service = axios.create({ baseURL: 'https://foodfighters-web.herokuapp.com', withCredentials: true }); this.service = service; } renderBlog = () => { return this.service.get('/foodie') .then(response => response.data) }; renderFormation = () =>{ return this.service.get('/formation') .then(response => response.data) } renderExperiencie = () =>{ return this.service.get('/experiencie') .then(response => response.data) } renderPost = (id) => { console.log(id) return this.service.post('/post', {id}) .then(response => response.data) } } export default BlogService;
Java
UTF-8
493
1.8125
2
[ "Apache-2.0" ]
permissive
package io.nsu.hire.apiusers.service; import io.nsu.hire.apiusers.model.UserApplication; import org.springframework.data.domain.Page; import java.util.List; import java.util.Optional; public interface UserApplicationService { Page<UserApplication> readUserApplications(Integer size, Integer page); List<UserApplication> readUserApplications(); Optional<UserApplication> readUserApplicationByUuid(String uuid); UserApplication createUserApplication(UserApplication userApplication); }
C++
UTF-8
1,785
3.390625
3
[]
no_license
#include <iostream> using namespace std; class mystring { public: mystring( char ch ); mystring ( const char *cstring = "" ); mystring( const mystring & str ); ~mystring( ) { delete [ ] buffer; } const mystring & operator=( const mystring & rhs); const mystring & operator+=( const mystring & rhs ); const int size( ) { return sizeof( *this ) / sizeof ( char ); } const char *c_str( ) const { return buffer; } int length( ) const { return strLength; } bool empty( ) { return *this == ""; } void clear( ) { *this = ""; } char at(int i) { return *this[i]; } char operator[]( int k ) const; char & operator[]( int k ); mystring operator() ( int begin, int end); private: int strLength; int bufferLength; char *buffer; }; ostream & mystring::operator<<( ostream & out, const mystring & str ); istream & mystring::operator>>( istream & in, mystring & str ); istream & mystring::getline( istream & in, mystring & str, char delim = '\n' ); mystring mystring::operator() ( int begin, int end ) { mystring s =""; for(int i = begin; i < end; i++) s += *this[i]; return s; } bool mystring::operator==(const mystring & lhs, const mystring & rhs); bool mystring::operator!=(const mystring & lhs, const mystring & rhs); bool mystring::operator< (const mystring & lhs, const mystring & rhs); bool mystring::operator<=(const mystring & lhs, const mystring & rhs); bool mystring::operator> (const mystring & lhs, const mystring & rhs); bool mystring::operator>=(const mystring & lhs, const mystring & rhs); mystring::mystring(const char * cstring) { if (cstring == NULL) cstring = ""; strLength = strlen( cstring ); bufferLength = strLength + 1; buffer = new char[ bufferLength ]; strcpy( buffer, cstring ); }
Java
UTF-8
289
2.140625
2
[]
no_license
package com.magicalrice.adolph.kmovie.data.entities; public class BaseTvEpisodeRatingObject extends BaseRatingObject { private int show_id; public int getShow_id() { return show_id; } public void setShow_id(int show_id) { this.show_id = show_id; } }
C#
UTF-8
3,079
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace _07wcfservice { // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service1”。 public class LoginService : ILoginService { public static Dictionary<string, ICallback> channelDic = new Dictionary<string, ICallback>(); //public void Login(string msg) //public void Login(string username) //{ // ////这些是输出到server端的额,可以做些监控或者日志 // //var ip = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString(); // //var info = string.Format("当前 request有 server={0} 返回message={1}", ip, username); // //Console.WriteLine(info); // //获取当前client的对象或者channel或者通道 // var callback = OperationContext.Current.GetCallbackChannel<ICallback>(); // channelDic[username] = callback; // Console.WriteLine("当前username={0}",username); //} public void Login(Student student) { ////这些是输出到server端的额,可以做些监控或者日志 //var ip = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString(); //var info = string.Format("当前 request有 server={0} 返回message={1}", ip, username); //Console.WriteLine(info); //获取当前client的对象或者channel或者通道 var callback = OperationContext.Current.GetCallbackChannel<ICallback>(); channelDic[student.StudentName] = callback; Console.WriteLine("当前username={0}", student.StudentName); } public static void Modify() { while (true) { var input = Console.ReadLine();//从控制台读东西 if (!string.IsNullOrEmpty(input))//起到过滤回调操作的东西,因为猜想中,是执行完,就调用回调函数,一对一的,是一来一回的,其实不是的,只是,你可以调用我,我可以调用你,也就是说我调用了你,你不一定必须要紧接着调用我, { foreach (var item in channelDic) { item.Value.Notify(input); } } } } } public class Student { public int StudentId { get; set; } public string StudentName { get; set; } public List<string> AddressList { get; set; } public SortedDictionary<int,int> MySortedDictionary { get; set; } public SexEnum MySexEnum { get; set; } } public enum SexEnum { Male, Female } }
SQL
UTF-8
148
3.40625
3
[]
no_license
select t.name, avg(c.level) from Trainer t, CatchedPokemon c, Gym g where t.id=g.leader_id and c.owner_id=t.id group by g.leader_id order by t.name;
C++
UTF-8
516
3.0625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { priority_queue<int> p; p.push(400); p.push(200);/// in priority queue we can use push(),pop(),top() - (front) fuction p.push(100); p.push(45);/// In int it will be sorted in descending order but in string p.push(250);/// the strings will be sorted in reverse order of laxico-graphical order while(!p.empty()) { int x; x=p.top(); cout<<x <<"\t"; p.pop(); } return 0; }
Markdown
UTF-8
4,491
2.8125
3
[ "BSD-3-Clause" ]
permissive
--- description: How to setup Http Clients --- # Setup [[TOC]] ## Register Service Provider Register `HttpClientServiceProvider` inside your `config/app.php`. ```php return [ // ... previous not shown ... // /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- */ 'providers' => [ \Aedart\Http\Clients\Providers\HttpClientServiceProvider::class // ... remaining services not shown ... // ], ]; ``` ## Publish Assets Run `vendor:publish` to publish this package's assets. ```shell php artisan vendor:publish ``` After the command has completed, you should see the following configuration file in your `/configs` directory: - `http-clients.php` ### Publish Assets for Athenaeum Core Application If you are using the [Athenaeum Core Application](../../core), then run the following command to publish assets: ```shell php {your-cli-app} vendor:publish-all ``` ## Configuration In your `/config/http-clients.php` configuration, you should see a list of "profiles". Feel free to add as many profiles as your application requires. Each profile consists of two keys: * `driver`: Class patch to the Http Client "driver" to be used. * `options`: Http Client options. You can use [Guzzle's Request Options](http://docs.guzzlephp.org/en/stable/request-options.html), for each client profile. ```php return [ // ... previous not shown /* |-------------------------------------------------------------------------- | Http Client Profiles |-------------------------------------------------------------------------- */ 'profiles' => [ 'default' => [ 'driver' => \Aedart\Http\Clients\Drivers\DefaultHttpClient::class, 'options' => [ 'data_format' => \GuzzleHttp\RequestOptions::FORM_PARAMS, 'grammar-profile' => env('HTTP_QUERY_GRAMMAR', 'default'), ] ], 'json' => [ 'driver' => \Aedart\Http\Clients\Drivers\JsonHttpClient::class, 'options' => [ 'grammar-profile' => 'json_api', ] ], // Add your own profiles... e.g. a preconfigured json http client 'flights-api-client' => [ 'driver' => \Aedart\Http\Clients\Drivers\JsonHttpClient::class, 'options' => [ 'base_uri' => 'https://acme.com/api/v2/flights', 'grammar-profile' => 'odata', ] ], ] // ... remaining not shown ... ]; ``` ### Http Query Grammars Each Http Client profile can specify it's desired Http Query Grammars profile to use. The following grammars are offered by default: - `DefaultGrammar`: Does not follow any specific syntax or convention. - `JsonApiGrammar`: Adheres to [Json API's](https://jsonapi.org/format/1.1/#fetching) syntax for Http Queries. - `ODataGrammar`: Adheres to [OData's](https://www.odata.org/getting-started/basic-tutorial/#queryData) syntax for Http Queries. You can find a matching profile, inside your `config/http-clients.php`, where you may change any of the available options. ```php <?php return [ // ... previous not shown ... 'profiles' => [ 'json' => [ 'driver' => \Aedart\Http\Clients\Drivers\JsonHttpClient::class, 'options' => [ // Http Query grammar profile to use 'grammar-profile' => 'json_api', ] ] ], /* |-------------------------------------------------------------------------- | Http Query Grammars |-------------------------------------------------------------------------- */ 'grammars' => [ 'profiles' => [ 'json_api' => [ 'driver' => \Aedart\Http\Clients\Requests\Query\Grammars\JsonApiGrammar::class, 'options' => [ 'datetime_format' => \DateTimeInterface::ISO8601, 'date_format' => 'Y-m-d', 'year_format' => 'Y', 'month_format' => 'm', 'day_format' => 'd', 'time_format' => 'H:i:s', // ... remaining not shown ... ] ], // ... remaining not shown ... ] ] ]; ```
Markdown
UTF-8
761
2.65625
3
[ "MIT" ]
permissive
# Module Management The module manager provides a list of all of the modules that are currently installed in your version of the Oqtane framework. Modules are a key feature of Oqtane and allow for a variety of features to be placed on your pages. At the top of the module manager page there is a install button to install a module from the list provided or by using the upload tab, you can use a NuGet package of a module, so that it will be included as one of the possible modules to use on the site. Inside the list of modules there is also the options to edit modules which will show an overview of the module with a description and an option to delete any module that is not a default Oqtane module. ![module-management](./assets/module-management.png)
Python
UTF-8
133
3.09375
3
[]
no_license
celsius = 45.5 fahrenheit = (celsius * 1.8) + 32 print('%.1f degree Celsius is equal to %.1f degree Fahrenheit'%(celsius,fahrenheit))