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
Markdown
UTF-8
366
2.546875
3
[ "MIT" ]
permissive
# Python-tutorials Hey enthusiasts,Welcome to Python Tutorials. In this repo you can find: Tutorials related to Python Interesting projects to improve your skills In short, this repo will help to land on the best resouces in a single click. ## Accessing the resources Head towards the resources.md section under the code. 🥳*Keep Learning*🥳
C#
UTF-8
380
3.15625
3
[ "Apache-2.0" ]
permissive
using System; namespace TypeCasting { class Program { static void Main(string[] args) { double myDouble = 74.87; int myInt = (int) myDouble; bool myBool = true; Console.WriteLine(myDouble); Console.WriteLine(myInt); Console.WriteLine(Convert.ToString(myBool)); } } }
SQL
UTF-8
1,750
3.53125
4
[ "MIT" ]
permissive
/** * @version v1.9.4 * @signature b26f29a6bb5dbb3510b057632182d138 * @title Add properties field and drop 'resolved' state * * This patch drops resolved state and any associated statuses * */ -- Move tickets in resolved state to the default closed status SET @statusId = ( SELECT id FROM `%TABLE_PREFIX%ticket_status` WHERE `state` = 'closed' ORDER BY id ASC LIMIT 1); UPDATE `%TABLE_PREFIX%ticket` t1 JOIN `%TABLE_PREFIX%ticket_status` t2 ON (t2.id = t1.status_id) SET t1.status_id = @statusId WHERE t2.state='resolved'; -- add properties field IF it doesn't exist SET @s = (SELECT IF( (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '%TABLE_PREFIX%ticket_status' AND table_schema = DATABASE() AND column_name = 'properties' ) > 0, "SELECT 1", "ALTER TABLE `%TABLE_PREFIX%ticket_status` ADD `properties` text NOT NULL AFTER `sort`" )); PREPARE stmt FROM @s; EXECUTE stmt; UPDATE `%TABLE_PREFIX%ticket_status` s INNER JOIN `%TABLE_PREFIX%config` c ON(c.namespace = CONCAT('TS.', s.id) AND c.key='properties') SET s.properties = c.value; -- add default reopen settings to existing closed state statuses UPDATE `%TABLE_PREFIX%ticket_status` SET `properties`= INSERT(`properties`, 2, 0, '"allowreopen":true,"reopenstatus":0,') WHERE `state` = 'closed'; -- change thread body text to 16Mb. ALTER TABLE `%TABLE_PREFIX%ticket_thread` CHANGE `body` `body` mediumtext NOT NULL; -- index ext id ALTER TABLE `%TABLE_PREFIX%note` ADD INDEX (`ext_id`); -- Set new schema signature UPDATE `%TABLE_PREFIX%config` SET `value` = 'b26f29a6bb5dbb3510b057632182d138' WHERE `key` = 'schema_signature' AND `namespace` = 'core';
Java
UTF-8
981
2.3125
2
[]
no_license
package com.zx.hotnews.adapter; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; import java.util.List; import static android.os.Build.VERSION_CODES.M; /** * Created by zhangxin on 2017/3/10 0010. * <p> * Description : * 试图来封装一个BaseAdapter,但是感觉自己封装的不是很好,暂时不用... */ public abstract class BaseAdapter<T> extends RecyclerView.Adapter<BaseViewHolder> { protected OnItemClickListener<T> listener; public List<T> data = new ArrayList<>(); public void addAll(List<T> data) { this.data.addAll(data); } public void clear() { data.clear(); } @Override public int getItemCount() { return data.size(); } public void setOnItemClickListener(OnItemClickListener<T> listener) { this.listener = listener; } @Override public void onBindViewHolder(BaseViewHolder holder, int position) { } }
Markdown
UTF-8
3,401
3
3
[]
no_license
# HDFS客户端操作 IO流操作 ## HDFS文件上传 ```java @Test public void putFileToHDFS() throws IOException, InterruptedException, URISyntaxException { // 1 获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "zhutiansama"); // 2 创建输入流 FileInputStream fis = new FileInputStream(new File("e:/data.txt")); // 3 获取输出流 FSDataOutputStream fos = fs.create(new Path("/data.txt")); // 4 流对拷,关键 IOUtils.copyBytes(fis, fos, configuration); // 5 关闭资源 IOUtils.closeStream(fos); IOUtils.closeStream(fis); fs.close(); } ``` ## HDFS文件下载 ```java // 文件下载 @Test public void getFileFromHDFS() throws IOException, InterruptedException, URISyntaxException{ // 1 获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://master:9000"), configuration, "hadoop"); // 2 获取输入流 FSDataInputStream fis = fs.open(new Path("/data.txt")); // 3 获取输出流,注意Input是从哪里输入,Output是输出到哪里 FileOutputStream fos = new FileOutputStream(new File("e:/data.txt")); // 4 流的对拷 IOUtils.copyBytes(fis, fos, configuration); // 5 关闭资源 IOUtils.closeStream(fos); IOUtils.closeStream(fis); fs.close(); } ``` ## 定位文件获取 ### 1. 下载第一块文件数据(文件如果过大就会分块存储,所以需要分块读取) ```java @Test public void readFileSeek1() throws IOException, InterruptedException, URISyntaxException{ // 1 获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://master:9000"), configuration, "hadoop"); // 2 获取输入流 FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz")); // 3 创建输出流 FileOutputStream fos = new FileOutputStream(new File("e:/hadoop- 2.7.2.tar.gz.part1")); // 4 流的拷贝 byte[] buf = new byte[1024]; for(int i =0 ; i < 1024 * 128; i++){ fis.read(buf); fos.write(buf); } // 5关闭资源 IOUtils.closeStream(fis); IOUtils.closeStream(fos); } ``` ### 2. 下载第二块文件数据 ```java @Test public void readFileSeek2() throws IOException, InterruptedException, URISyntaxException{ // 1 获取文件系统 Configuration configuration = new Configuration(); FileSystem fs = FileSystem.get(new URI("hdfs://master:9000"), configuration, "hadoop"); // 2 打开输入流 FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz")); // 3 定位输入数据位置 fis.seek(1024*1024*128); // 4 创建输出流 FileOutputStream fos = new FileOutputStream(new File("e:/hadoop- 2.7.2.tar.gz.part2")); // 5 流的对拷 IOUtils.copyBytes(fis, fos, configuration); // 6 关闭资源 IOUtils.closeStream(fis); IOUtils.closeStream(fos); } ``` ### 3. 合并两块文件 > 按住shift打开cmd,对数据进行合并 > > type hadoop-2.7.2.tar.gz.part2 >> hadoop-2.7.2.tar.gz.part1 > > 合并完成后,将hadoop-2.7.2.tar.gz.part1重新命名为hadoop-2.7.2.tar.gz即可
PHP
UTF-8
3,729
2.609375
3
[]
no_license
<?php $link = mysqli_connect("localhost", "admin", "lightson100%", "emailcheck_db"); if (!$link) { echo "Ошибка: Невозможно установить соединение с MySQL." . PHP_EOL; echo "Код ошибки errno: " . mysqli_connect_errno() . PHP_EOL; echo "Текст ошибки error: " . mysqli_connect_error() . PHP_EOL; exit; } //echo "Соединение с MySQL установлено!" . PHP_EOL; //echo "Информация о сервере: " . mysqli_get_host_info($link) . PHP_EOL; if(isset($_POST['submit'])) { $email = $_POST['email']; $checkbox1 = isset($_POST['checkbox1']) ? 1 : 0; $checkbox2 = isset($_POST['checkbox2']) ? 1 : 0; $checkbox3 = isset($_POST['checkbox3']) ? 1 : 0; $checkbox4 = isset($_POST['checkbox4']) ? 1 : 0; $checkbox5 = isset($_POST['checkbox5']) ? 1 : 0; $checkbox6 = isset($_POST['checkbox6']) ? 1 : 0; $checkbox7 = isset($_POST['checkbox7']) ? 1 : 0; /* $checkbox8 = isset($_POST['checkbox8']) ? 1 : 0; $checkbox9 = isset($_POST['checkbox9']) ? 1 : 0; $checkbox10 = isset($_POST['checkbox10']) ? 1 : 0; $checkbox11 = isset($_POST['checkbox11']) ? 1 : 0; $checkbox12 = isset($_POST['checkbox12']) ? 1 : 0; $checkbox13 = isset($_POST['checkbox13']) ? 1 : 0; $checkbox14 = isset($_POST['checkbox14']) ? 1 : 0; $checkbox15 = isset($_POST['checkbox15']) ? 1 : 0; $checkbox16 = isset($_POST['checkbox16']) ? 1 : 0; $checkbox17 = isset($_POST['checkbox17']) ? 1 : 0; $checkbox18 = isset($_POST['checkbox18']) ? 1 : 0; $checkbox19 = isset($_POST['checkbox19']) ? 1 : 0; $checkbox20 = isset($_POST['checkbox20']) ? 1 : 0; */ $query = "SELECT id FROM emails WHERE email='$email'"; $result = mysqli_query($link, $query); $row = mysqli_fetch_array($result); if(!empty($row['id'])) { $query = "UPDATE emails SET checkbox1='$checkbox1', checkbox2='$checkbox2', checkbox3='$checkbox3', checkbox4='$checkbox4', checkbox5='$checkbox5', checkbox6='$checkbox6', checkbox7='$checkbox7' WHERE email='$email'"; $result = mysqli_query($link, $query); } else { $query = "INSERT INTO emails (id, email, checkbox1, checkbox2, checkbox3, checkbox4, checkbox5, checkbox6, checkbox7) VALUES (0, '$email', '$checkbox1', '$checkbox2', '$checkbox3', '$checkbox4', '$checkbox5', '$checkbox6', '$checkbox7')"; $result = mysqli_query($link, $query); } /* if(!empty($row['id'])) { $query = "UPDATE emails SET checkbox1='$checkbox1', checkbox2='$checkbox2', checkbox3='$checkbox3', checkbox4='$checkbox4', checkbox5='$checkbox5', checkbox6='$checkbox6', checkbox7='$checkbox7', checkbox8='$checkbox8', checkbox9='$checkbox9', checkbox10='$checkbox10', checkbox11='$checkbox11', checkbox12='$checkbox12', checkbox13='$checkbox13', checkbox14='$checkbox14', checkbox15='$checkbox15', checkbox16='$checkbox16', checkbox17='$checkbox17', checkbox18='$checkbox18', checkbox19='$checkbox19', checkbox20='$checkbox20' WHERE email='$email'"; $result = mysqli_query($link, $query); } else { $query = "INSERT INTO emails (id, email, checkbox1, checkbox2, checkbox3, checkbox4, checkbox5, checkbox6, checkbox7, checkbox8, checkbox9, checkbox10, checkbox11, checkbox12, checkbox13, checkbox14, checkbox15, checkbox16, checkbox17, checkbox18, checkbox19, checkbox20) VALUES (0, '$email', '$checkbox1', '$checkbox2', '$checkbox3', '$checkbox4', '$checkbox5', '$checkbox6', '$checkbox7', '$checkbox8', '$checkbox9', '$checkbox10', '$checkbox11', '$checkbox12', '$checkbox13', '$checkbox14', '$checkbox15', '$checkbox16', '$checkbox17', '$checkbox18', '$checkbox19', '$checkbox20')"; $result = mysqli_query($link, $query); } */ } mysqli_close($link); ?>
PHP
UTF-8
716
2.6875
3
[]
no_license
<?php include_once "model/AuthModel.php"; class RegisterController { public $model; public function __construct() { $this->model = new AuthModel(); if (isset($_SESSION['email'])) { header("location:index.php"); } else { if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = $_POST["email"]; $user = $this->model->getRecord($email); if (isset($user->email)) { header("location:admin.php?controller=register&type=auth&action=fail"); } else { $this->model->register(); } } } include "view/register.php"; } }
C
UTF-8
1,728
3.484375
3
[]
no_license
#include "cenario.h" #include <stdio.h> #include <stdlib.h> //declaracao funcoes do modulo void swap(Letra * a, Letra * b); void remover_letra(Letra * vet, int * tam, int ind); //implementacao funcoes do modulo Cenario *cenario_create(int max, float largura, float altura){ Cenario * cenario = malloc(sizeof(Cenario)); cenario->qtd = 0; cenario->max = max; cenario->vet = malloc(sizeof(Letra) * max); cenario->largura = largura; cenario->altura = altura; return cenario; } void cenario_desenhar(Cenario * cenario, sfRenderWindow * janela, sfText * text){ int i; for(i = 0; i < cenario->qtd; i++) letra_desenhar(janela, text, cenario->vet[i]); } void cenario_add_letra(Cenario *c, float vx, float vy, int tam){ if(c->qtd < c->max){ c->vet[c->qtd] = letra_criar(c->largura, vx, vy, tam); c->qtd++; } } void cenario_update(Cenario *c){ int i = 0; for(i = 0; i < c->qtd; i++) letra_update(&c->vet[i]); } boolean cenario_jogo_continua(Cenario *c){ int i = 0; for(i = 0; i < c->qtd; i++) if(c->vet[i].y + 30 > c->altura ) return FALSE; return TRUE; } boolean cenario_del_letra(Cenario *c, char letra){ int i = 0; for(i = 0; i < c->qtd; i++){ if(c->vet[i].c == letra){ remover_letra(c->vet, &c->qtd, i); return TRUE; } } return FALSE; } void cenario_destruir(Cenario *cenario){ free(cenario->vet); free(cenario); } //FUNCOES AUXILIARES void swap(Letra *a, Letra *b){ Letra aux = *a; *a = *b; *b = aux; } void remover_letra(Letra *vet, int *tam, int ind){ swap(&vet[*tam - 1], &vet[ind]); (*tam)--; }
C#
UTF-8
1,020
3
3
[ "Apache-2.0" ]
permissive
using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace calling.Controllers { [Route("")] public class DefaultController : ControllerBase { private readonly IHttpClientFactory _clientFactory; public DefaultController(IHttpClientFactory clientFactory) { _clientFactory = clientFactory; } [HttpGet] public async Task<IActionResult> GetAsync() { var httpClient = _clientFactory.CreateClient(); var url = Environment.GetEnvironmentVariable("URL"); if (url == null) { return BadRequest("No URL defined"); } var request = new HttpRequestMessage(HttpMethod.Get, url); var response = await httpClient.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); return Ok("Second service says: " + content); } } }
C++
UTF-8
3,193
2.515625
3
[]
no_license
#include "CradleMesh.h" #include "CradleFileManager.h" CradleMesh::CradleMesh(std::wstring _name, CradleFileManager* fm, CradleVertexDeclarations::VertexPosTex* verts, int numVerts /* */) : CradleResource(_name, fm) { m_vertices = verts; m_numVertices = numVerts; m_indices = 0; wprintf_s(L"Creating Mesh with %d verts\n", numVerts); D3D11_BUFFER_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(bufferDesc)); bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.ByteWidth = sizeof(CradleVertexDeclarations::VertexPosTex) * m_numVertices; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA subData; ZeroMemory(&subData, sizeof(subData)); subData.pSysMem = m_vertices; HRESULT hr = m_fileManager->GetCD3D()->m_d3dDevice->CreateBuffer(&bufferDesc, &subData, &m_vertexBuffer); HRPRINT(hr, L"Failed to create vertex buffer\n", L"Vertex buffer created\n"); fm->AddMesh(this); } CradleMesh::CradleMesh(std::wstring _name, CradleFileManager* fm, CradleVertexDeclarations::VertexPosTex* uniqueVerts, int numVerts, DWORD* indices, int numIndices) : CradleResource(_name, fm) { m_vertices = uniqueVerts; m_numVertices = numVerts; m_indices = indices; m_numIndices = numIndices; wprintf_s(L"Creating Mesh with %d verts\n", numVerts); D3D11_BUFFER_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(bufferDesc)); bufferDesc.Usage = D3D11_USAGE_DEFAULT; bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.ByteWidth = sizeof(CradleVertexDeclarations::VertexPosTex) * m_numVertices; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA subData; ZeroMemory(&subData, sizeof(subData)); subData.pSysMem = m_vertices; HRESULT hr = m_fileManager->GetCD3D()->m_d3dDevice->CreateBuffer(&bufferDesc, &subData, &m_vertexBuffer); HRPRINT(hr, L"Failed to create vertex buffer\n", L"Vertex buffer created\n"); D3D11_BUFFER_DESC indexDesc; ZeroMemory(&indexDesc, sizeof(indexDesc)); indexDesc.Usage = D3D11_USAGE_DEFAULT; indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexDesc.ByteWidth = sizeof(DWORD) * m_numIndices; indexDesc.CPUAccessFlags = 0; indexDesc.MiscFlags = 0; D3D11_SUBRESOURCE_DATA indexData; indexData.pSysMem = m_indices; hr = m_fileManager->GetCD3D()->m_d3dDevice->CreateBuffer(&indexDesc, &indexData, &m_indexBuffer); HRPRINT(hr, L"Failed to create index buffer\n", L"Index buffer created\n"); fm->AddMesh(this); } CradleMesh::~CradleMesh() { if (m_vertices) delete[] m_vertices; m_vertices = nullptr; m_numVertices = 0; if (m_indices) delete[] m_indices; m_indices = nullptr; if (m_vertexBuffer) m_vertexBuffer->Release(); m_vertexBuffer = nullptr; if (m_indexBuffer) m_indexBuffer->Release(); m_indexBuffer = nullptr; } ID3D11Buffer* CradleMesh::GetVertexBuffer() { return m_vertexBuffer; } int CradleMesh::GetNumVertices() { return m_numVertices; } void CradleMesh::Draw(DirectX::XMFLOAT4X4* matrix) { m_fileManager->DrawMesh(m_name, matrix); // m_fileManager->DrawMesh(matrix); }
PHP
UTF-8
1,105
2.796875
3
[ "CC-BY-4.0", "CC-BY-3.0" ]
permissive
<?php $servername = "localhost"; $username = "root"; $password = "mysql"; $database ="TrumpUniversity"; session_start(); if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){ $studentUser = $_SESSION["username"]; } else{ header("location: login.php"); exit; } // Create connection $conn = new mysqli($servername, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $query = "SELECT * FROM users WHERE username='".$studentUser."'"; if ($userResult = $conn->query($query)) { while ($row = $userResult->fetch_assoc()) { $studentUserId = $row["id"]; } } $deletedStudentCourses = $_POST['deletedStudentCourses']; foreach($deletedStudentCourses as $deletedStudentCourse) { echo $deletedStudentCourse; $query = "DELETE FROM StudentCourse WHERE StudentID=".$studentUserId." AND CourseID=".$deletedStudentCourse; $conn->query($query); } /*https://stackoverflow.com/questions/2112373/php-page-redirect*/ header("Location: course_registration.php"); exit(); ?>
Java
UTF-8
2,257
2.5625
3
[]
no_license
/* * A set of classes to parse, represent and display Chemical compounds in * .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html) */ package magicbeans.sunw.demo.molecule; class Atom { private static java.awt.Component panel; private static byte[] data; private final static int R = 40; private final static int hx = 15; private final static int hy = 15; private final static int bgGrey = 192; private final static int nBalls = 16; private static int maxr; private int Rl; private int Gl; private int Bl; private Image balls[]; static { data = new byte[R * 2 * R * 2]; int mr = 0; for (int Y = 2 * R; --Y >= 0;) { int x0 = (int) (Math.sqrt(R * R - (Y - R) * (Y - R)) + 0.5); int p = Y * (R * 2) + R - x0; for (int X = -x0; X < x0; X++) { int x = X + hx; int y = Y - R + hy; int r = (int) (Math.sqrt(x * x + y * y) + 0.5); if (r > mr) mr = r; data[p++] = r <= 0 ? 1 : (byte) r; } } maxr = mr; } static void setComponent(java.awt.Component app) { panel = app; } Atom(int Rl, int Gl, int Bl) { this.Rl = Rl; this.Gl = Gl; this.Bl = Bl; } private final int blend(int fg, int bg, float fgfactor) { return (int) (bg + (fg - bg) * fgfactor); } private synchronized void Setup() { balls = new Image[nBalls]; byte red[] = new byte[256]; red[0] = (byte) bgGrey; byte green[] = new byte[256]; green[0] = (byte) bgGrey; byte blue[] = new byte[256]; blue[0] = (byte) bgGrey; for (int r = 0; r < nBalls; r++) { float b = (float) (r+1) / nBalls; for (int i = maxr; i >= 1; --i) { float d = (float) i / maxr; red[i] = (byte) blend(blend(Rl, 255, d), bgGrey, b); green[i] = (byte) blend(blend(Gl, 255, d), bgGrey, b); blue[i] = (byte) blend(blend(Bl, 255, d), bgGrey, b); } IndexColorModel model = new IndexColorModel(8, maxr + 1, red, green, blue, 0); balls[r] = panel.createImage( new MemoryImageSource(R*2, R*2, model, data, 0, R*2)); } } synchronized void paint(Graphics gc, int x, int y, int radius) { if (balls == null) { Setup(); } Image i = balls[radius]; int size = 10 + radius; gc.drawImage(i, x - (size/2), y - (size/2), size, size, panel); } }
Java
UTF-8
549
2.203125
2
[]
no_license
package acquire.protocol.description; import java.util.ArrayList; import java.util.List; import acquire.basic.Action.ActionType; import acquire.basic.HotelChainI.HotelName; import acquire.state.player.PlayerStateI; public class PurchaseDescription extends ActionDescription { private final List<HotelName> _names; public PurchaseDescription(PlayerStateI player, List<HotelName> names) { super(ActionType.PURCHASE, player); _names = names; } public List<HotelName> getNames() { return new ArrayList<HotelName>(_names); } }
Python
UTF-8
11,972
2.640625
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
from loginhashblock import * class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' DEBUG = False def unittest_print(message): print(bcolors.WARNING + message + bcolors.ENDC) def unittest_title_print(message): print(bcolors.OKGREEN + message + bcolors.ENDC) def unittest_update_loginhashblocklist(): # case 01 prev_LHB = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' LHBlistStr = '' updatedLHBlistStr, LHBstr = update_loginhashblocklist(LHBlistStr, prev_LHB, DEBUG=DEBUG) source = prev_LHB.split('$') target = updatedLHBlistStr.split('$') unittest_title_print("LHB is one, LHBlist is null") if source[0] == target[0] and source[1] != target[1]: unittest_print("TestCase-01: Success") else: unittest_print("TestCase-01: Fail") # case 02 LHBlistStr = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2,aCIXQRZ2$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a3' LHBlist = LHBlistStr.split(',') updatedLHBlistStr, LHBstr = update_loginhashblocklist(LHBlistStr, prev_LHB, DEBUG=DEBUG) targetList = updatedLHBlistStr.split(',') target = targetList[0].split('$') unittest_title_print("LHB is one, LHBlist is two") if source[0] == target[0] and source[1] != target[1] and LHBlist[1] == targetList[1]: unittest_print("TestCase-01: Success") else: unittest_print("TestCase-01: Fail") if LHBlistStr != updatedLHBlistStr: unittest_print("TestCase-02: Success") else: unittest_print("TestCase-02: Fail") # case 03 LHBlistStr = 'aCIXQRZ3$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2' LHBlist = LHBlistStr.split(',') updatedLHBlistStr, LHBstr = update_loginhashblocklist(LHBlistStr, prev_LHB, DEBUG=DEBUG) targetList = updatedLHBlistStr.split(',') target = targetList[1].split('$') unittest_title_print("LHB is one, LHBlist is one, but devid is different so LHBlist will be updated LHB") if source[0] == target[0] and source[1] != target[1]: unittest_print("TestCase-01: Success") else: unittest_print("TestCase-01: Fail") if LHBlistStr != updatedLHBlistStr: unittest_print("TestCase-02: Success") else: unittest_print("TestCase-02: Fail") if len(targetList) == 2: unittest_print("TestCase-03: Success") else: unittest_print("TestCase-03: Fail") # case 04 prev_LHB = '' LHBlistStr = 'aCIXQRZ3$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2' LHBlist = LHBlistStr.split(',') updatedLHBlistStr, LHBstr = update_loginhashblocklist(LHBlistStr, prev_LHB, DEBUG=DEBUG) targetList = updatedLHBlistStr.split(',') unittest_title_print("LHB is null, LHBlist is one, su LHBlist will be maintained") if LHBlistStr == updatedLHBlistStr: unittest_print("TestCase-01: Success") else: unittest_print("TestCase-01: Fail") if len(targetList) == 1: unittest_print("TestCase-02: Success") else: unittest_print("TestCase-02: Fail") def unittest_create_loginhashblocklist(): LHBlistStr = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' updatedLHBlistStr, LHBstr = create_loginhashblocklist(LHBlistStr, DEBUG=DEBUG) LHBlist = updatedLHBlistStr.split(',') ("Create LHB and updated LHBlistStr") if len(LHBlist) == 2: unittest_print("TestCase-01: Success") else: unittest_print("TestCase-01: Fail") if LHBlist[0] == LHBlistStr: unittest_print("TestCase-02: Success") else: unittest_print("TestCase-02: Fail") def unittest_request_login_token(): unittest_title_print("unittest request login with token") LHBlistStr = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' prev_LHB = '' token='123456' verify_totp = False updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 1: unittest_print("TestCase-01: Success") else: unittest_print("TestCase-01: Fail") verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) LHBlist = updatedLHBlistStr.split(',') if LHBlist[0] == LHBlistStr: unittest_print("TestCase-02: Success") else: unittest_print("TestCase-02: Fail") if len(LHBlist) == 2: unittest_print("TestCase-03: Success") else: unittest_print("TestCase-03: Fail") prev_LHB = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 2: unittest_print("TestCase-04: Success") else: unittest_print("TestCase-04: Fail") prev_LHB = 'aCIXQRZ11$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 2: unittest_print("TestCase-05: Success") else: unittest_print("TestCase-05: Fail") prev_LHB = 'aCIXQRZ11$$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 2: unittest_print("TestCase-05: Success") else: unittest_print("TestCase-05: Fail") prev_LHB = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) updatedLHBlist = updatedLHBlistStr.split(',') if LHBlistStr != updatedLHBlist[0]: unittest_print("TestCase-06: Success") else: unittest_print("TestCase-06: Fail") prev_LHB = 'aCIXQRZ2$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) updatedLHBlist = updatedLHBlistStr.split(',') if len(updatedLHBlist) == 2: unittest_print("TestCase-07: Success") else: unittest_print("TestCase-07: Fail") prev_LHB = 'aCIXQRZ2$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) updatedLHBlist = updatedLHBlistStr.split(',') if len(updatedLHBlist) == 2: unittest_print("TestCase-07: Success") else: unittest_print("TestCase-07: Fail") devid = get_deviceId(updatedLHBlist[1], DEBUG=False) devid_ = get_deviceId(prev_LHB, DEBUG=False) if devid == devid_: unittest_print("TestCase-08: Success") else: unittest_print("TestCase-08: Fail") LHBlistStr = '' prev_LHB = '' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) updatedLHBlist = updatedLHBlistStr.split(',') if len(updatedLHBlist) == 1: unittest_print("TestCase-09: Success") else: unittest_print("TestCase-09: Fail") def unittest_request_login_notoken(): unittest_title_print("unittest request login with no token") LHBlistStr = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' prev_LHB = '' token='' verify_totp = False updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 5: unittest_print("TestCase-01: Success") else: unittest_print("TestCase-01: Fail") prev_LHB = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 4: unittest_print("TestCase-02: Success") else: unittest_print("TestCase-02: Fail") prev_LHB = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 3: unittest_print("TestCase-03: Success") else: unittest_print("TestCase-03: Fail") prev_LHB = 'aCIXQRZ11$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 3: unittest_print("TestCase-04: Success") else: unittest_print("TestCase-04: Fail") prev_LHB = 'aCIXQRZ11$$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) if ret == 3: unittest_print("TestCase-05: Success") else: unittest_print("TestCase-05: Fail") prev_LHB = 'aCIXQRZ2$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) updatedLHBlist = updatedLHBlistStr.split(',') if ret == 4: unittest_print("TestCase-06: Success") else: unittest_print("TestCase-06: Fail") prev_LHB = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' verify_totp = True updatedLHBlistStr, LHBstr, ret = mok_request_post(token, prev_LHB, verify_totp, LHBlistStr) updatedLHBlist = updatedLHBlistStr.split(',') if len(updatedLHBlist) == 1: unittest_print("TestCase-07: Success") else: unittest_print("TestCase-07: Fail") devid = get_deviceId(updatedLHBlist[0], DEBUG=False) devid_ = get_deviceId(prev_LHB, DEBUG=False) if devid == devid_: unittest_print("TestCase-08: Success") else: unittest_print("TestCase-08: Fail") def mok_request_post(token, prev_LHB, verify_totp, LHBlistStr): status = 0 new_LHB = '' if token: if not verify_totp: return LHBlistStr, new_LHB, 1 if prev_LHB: if not valid_loginhashblock(prev_LHB): return LHBlistStr, new_LHB, 2 LHBlistStr, new_LHB = update_loginhashblocklist(LHBlistStr, prev_LHB, DEBUG=DEBUG) else: LHBlistStr, new_LHB = create_loginhashblocklist(LHBlistStr, DEBUG=DEBUG) else: if prev_LHB: if not valid_loginhashblock(prev_LHB): return LHBlistStr, new_LHB, 3 if not verify_loginhashblock(LHBlistStr, prev_LHB): return LHBlistStr, new_LHB, 4 LHBlistStr, new_LHB = update_loginhashblocklist(LHBlistStr, prev_LHB, DEBUG=DEBUG) else: return LHBlistStr, new_LHB, 5 LHBlistStr = LHBlistStr return LHBlistStr, new_LHB, status DEBUG = False def unittest_subfunction_update_loginhashblock(): unittest_title_print("unittest sub function update_loginhashblock") LHBlistStr = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a1' prevLHBstr = 'aCIXQRZ1$2b76784270f608bedf2757113041a6f6e81ab55faf787afde4e57e4376d302a2' LHBlistStr, LHBstr = update_loginhashblocklist(LHBlistStr, prevLHBstr, DEBUG=False) ''' print("LHBlistStr: {}".format(LHBlistStr)) print("LHBstr: {}".format(LHBstr)) ''' unittest_update_loginhashblocklist() unittest_create_loginhashblocklist() unittest_request_login_token() unittest_request_login_notoken() unittest_subfunction_update_loginhashblock()
Shell
UTF-8
423
3.09375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#! /usr/bin/env bash # Encoded artist name. ARTIST="$1" # Encoded song title. TITLE="$2" #Encoded album name. ALBUM="$3" unquote () { decoded_url=$(python3 -c 'import sys, urllib.parse; print(urllib.parse.unquote(sys.argv[1]))' "$1") echo $decoded_url } UNQ_ARTIST=$(unquote "$ARTIST") UNQ_TITLE=$(unquote "$TITLE") prismriver-cli.py -t "$UNQ_TITLE" -a "$UNQ_ARTIST" --output $'%LYRICS%\n\nSource: %PLUGIN_NAME%'
Java
UTF-8
75
1.578125
2
[]
no_license
package jpabook.jpashop.domain; public enum OrderStatus { ORDER, CANCEL }
C++
UTF-8
629
2.796875
3
[]
no_license
/* Author: Austin Henry Date: 8/14/2018 Assignment: Final Project This is the header file for the Trainer Class */ #include "Space.hpp" #include "Monster.hpp" #include <vector> #include <string> using std::vector; using std::string; #ifndef TRAINER_HPP #define TRAINER_HPP class Trainer { private: Space * currentSpace; Monster* currentPokemon; vector <int> items; public: Trainer(Space*, Monster*); void initializePointer(Space*); Space* getSpace(); void moveNorth(); void moveSouth(); void checkPokemon(); void healPokemon(); bool checkBadge(); void giveBadge(); void giveRareCandy(); void useCandy(); }; #endif
Python
UTF-8
935
3.234375
3
[]
no_license
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: if not matrix or not matrix[0]: return 0 row = len(matrix) col = len(matrix[0]) heights = [0] * col res = 0 for i in range(row): for j in range(col): if matrix[i][j] == '1': heights[j] += 1 else: heights[j] = 0 area = self. LargestRectangleArea(heights) res = max(res, area) return res def LargestRectangleArea(self, heights): stack = [-1] heights += [0] res = 0 for i, h in enumerate(heights): while h < heights[stack[-1]]: hig = heights[stack.pop()] res = max(res, (i - stack[-1] - 1) * hig) stack.append(i) return res
C
UTF-8
2,069
3.3125
3
[]
no_license
/* BY SUBMITTING THIS FILE AS PART OF MY LAB ASSIGNMENT, I CERTIFY THAT ** ALL OF THE CODE FOUND WITHIN THIS FILE WAS CREATED BY ME WITH NO ** ASSISTANCE FROM ANY PERSON OTHER THAN THE INSTRUCTOR OF THIS COURSE ** OR ONE OF OUR UNDERGRADUATE GRADERS. ** getFloatFromUser.c created by Kohl Kuntze */ #include <stdio.h> #include <stdlib.h> #include "lab4.h" float getFloatFromUser(char *prompt) { float returnFloat; int counter, numAfterDecimal; char charStr[40]; char currentChar; int currentValue; int nonDigitFound, decimalFound, isNegative, checkValue; nonDigitFound = 0; numAfterDecimal = 0; isNegative = 0; decimalFound = 0; getStringFromUser(prompt, charStr); returnFloat = 0.0f; // read string for float related characters for(counter = 0; counter < 40; counter++) { currentChar = *(charStr + counter); checkValue = 0; if((currentChar >= '0' && currentChar <= '9') || currentChar == '.' || currentChar == '-') { checkValue = 1; } if(nonDigitFound == 0) { if(checkValue == 1) { if(currentChar >= '0' && currentChar <= '9') { returnFloat = returnFloat * 10.0f; currentValue = currentChar - '0'; returnFloat += currentValue; if (decimalFound == 1) { numAfterDecimal++; } } if(currentChar == '.'){ decimalFound = 1; } else if(currentChar == '-') { isNegative = 1; } } else { nonDigitFound = 1; } } } // correct number of decimal places for(counter = 0; counter < numAfterDecimal; counter++) { returnFloat = returnFloat / 10.0f; } // if negative multiply by negative one if(isNegative == 1) { returnFloat = returnFloat * -1.0f; } return returnFloat; }
C
UTF-8
3,326
3.484375
3
[]
no_license
/* * Menu.h * * Created on: 17 abr. 2021 * Author: Maty */ #ifndef MENU_H_ #define MENU_H_ /** \brief Muestra las opciones del menu y retorna la respuesta del mismo * * \return int retorna la opcion elegida * */ int menu(void); /** \brief toma los datos de tipo float y lo devuelve * * \return float retorna el numero ingresado * */ float tomaDeDatos(void); /** \brief valida la opcion de salida del programa * * \return char devuelve unicamente 'S' para salir o 'N' para continuar con el programa * */ char pedidoDeSalida(void); /** \brief Realiza las operaciones y devuelve 1 si se realizaron o 0 si no se realizo la division * * \param x primer numero a operar * \param y segundo numero a operar * \param resultadoSuma float* recibe el puntero del resultado de la suma para realizarla y devolver el mismo * \param resultadoSuma float* recibe el puntero del resultado de la resta para realizarla y devolver el mismo * \param resultadoSuma float* recibe el puntero del resultado de la division para realizarla y devolver el mismo * \param resultadoSuma float* recibe el puntero del resultado de la multiplicacion para realizarla y devolver el mismo * \param banderaDecimalX int* recibe el puntero a la bandera de si es decimal para el numero A * \param banderaDecimalY int* recibe el puntero a la bandera de si es decimal para el numero B * \param resultadoFactorialX unsigned long long int* recibe el puntero del resultado del factorial para realizarlo y devolver el mismo * \param resultadoFactorialY unsigned long long int* recibe el puntero del resultado del factorial para realizarlo y devolver el mismo * \return int retorna 1 si se realizaron todas las operacion, 0 si no se realizo la division * */ int realizacionDeOperaciones(float x, float y, float* resultadoSuma, float* resultadoResta, float* resultadoDivision, float* resultadoMultiplicacion, int* banderaDecimalX, int* banderaDecimalY, unsigned long long int* resultadoFactorialX, unsigned long long int* resultadoFactorialY); /** \brief Pide los datos para mostrarlos a traves de printf * * \param x primer numero a operar * \param y segundo numero a operar * \param resultadoSuma float* recibe el resultado de la suma para mostrarlo * \param resultadoResta float* recibe el resultado de la resta para mostrarlo * \param resultadoDivision float* recibe el resultado de la division para mostrarlo * \param resultadoMultiplicacion float* recibe el resultado de la multiplicacion para mostrarlo * \param banderaDecimalX int* recibe el puntero a la bandera de si es decimal para el numero A * \param banderaDecimalY int* recibe el puntero a la bandera de si es decimal para el numero B * \param resultadoFactorialX unsigned long long int* recibe el resultado del factorial para mostrarlo * \param banderaDivision int muestra si se pudo realizar la division o no * \param resultadoFactorialY unsigned long long int* recibe el resultado del factorial para mostrarlo * \return void * */ void muestraDeResultados(float x, float y, float resultadoSuma, float resultadoResta, float resultadoDivision, float resultadoMultiplicacion, int banderaDecimalX, int banderaDecimalY, unsigned long long int resultadoFactorialX, unsigned long long int resultadoFactorialY, int banderaDivision); #endif /* MENU_H_ */
Java
UTF-8
1,212
2.234375
2
[ "Apache-2.0" ]
permissive
package pi2schema.schema.providers.protobuf.personaldata; import com.google.protobuf.Message; import pi2schema.crypto.Decryptor; import pi2schema.crypto.Encryptor; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; public class PersonalMetadata { private final List<OneOfPersonalDataFieldDefinition> personalDataFields; public PersonalMetadata(List<OneOfPersonalDataFieldDefinition> personalDataFields) { this.personalDataFields = personalDataFields; } public boolean requiresEncryption() { return !personalDataFields.isEmpty(); } public Stream<CompletableFuture<Void>> encryptPersonalData( Encryptor encryptor, Message.Builder encryptingBuilder) { return personalDataFields .parallelStream() .map(field -> field.swapToEncrypted(encryptor, encryptingBuilder)); } public Stream<CompletableFuture<Void>> decryptPersonalData( Decryptor decryptor, Message.Builder decryptingBuilder) { return personalDataFields .parallelStream() .map(field -> field.swapToDecrypted(decryptor, decryptingBuilder)); } }
TypeScript
UTF-8
829
2.875
3
[]
no_license
import { Pipe, PipeTransform } from '@angular/core'; // Angular Pipe developed by Sahana P @Pipe({ name: 'orderBy' }) export class OrderByPipe implements PipeTransform { noManipulationTypes = ['number', 'boolean']; transform(array: any, field?: any, type?: any): any[] { array.sort((a: any, b: any) => { let isAsc = type == '' || type == undefined ? true : false; let aVal = this.noManipulationTypes.includes(typeof a[field]) ? a[field] : (a[field] || '').toLowerCase(); let bVal = this.noManipulationTypes.includes(typeof b[field]) ? b[field] : (b[field] || '').toLowerCase(); if (isAsc ? (aVal < bVal) : (aVal > bVal)) { return -1; } else if (isAsc ? (aVal > bVal) : (aVal < bVal)) { return 1; } else { return 0; } }); return array; } }
Python
UTF-8
525
3
3
[]
no_license
import random def pali(): x=raw_input("write n: ") while x!="n" : x=raw_input("try again: ") z=raw_input("probabilliy for heads: ") z=int(z) while int(z) >= 101: z=raw_input("don't insert more than 100,try again: ") ht=random.randint(0,100) if ht >= (100-z): print "H" else: print "T" def etz(): z=raw_input("probabilliy for heads: ") z=int(z) while int(z) >= 101: z=raw_input("don't insert more than 100,try again: ") x=raw_input("write n: ") while x!="n" : x=raw_input("try again: ") pali()
C++
UTF-8
494
2.546875
3
[]
no_license
/* * File: Complex.h * Author: Tauan * * Created on September 3, 2013, 12:10 AM */ #ifndef COMPLEX_H #define COMPLEX_H class Complex { private: double real; double imag; public: Complex(); ~Complex(); void imprime(); void set(double,double); Complex operator+(Complex); Complex operator-(Complex); bool operator==(Complex); Complex operator*(Complex); Complex operator/(Complex); }; #endif /* COMPLEX_H */
C++
UTF-8
7,817
3.515625
4
[]
no_license
#pragma once #include <forward_list> #include <vector> #include <algorithm> #include <stdexcept> #include <list> #include <utility> template<class KeyType, class ValueType, class Hash = std::hash<KeyType>> class HashMap { public: using KeyValuePair = std::pair<const KeyType, ValueType>; using const_iterator = typename std::list<KeyValuePair>::const_iterator; using iterator = typename std::list<KeyValuePair>::iterator; HashMap(Hash hash_obj = Hash()); void insert(const KeyValuePair& element); template<typename ForwardIterator> HashMap(ForwardIterator start, ForwardIterator end, Hash hash_obj = Hash()); HashMap(std::initializer_list<KeyValuePair> init_list, Hash hash_obj = Hash()); void erase(const KeyType& key); const_iterator find(const KeyType& key) const; iterator find(const KeyType& key); size_t size() const; bool empty() const; Hash hash_function() const; ValueType &operator[] (const KeyType& key); const ValueType& at(const KeyType& key) const; HashMap &operator= (const HashMap &other); const_iterator begin() const; const_iterator end() const; iterator begin(); iterator end(); void clear(); ~HashMap(); private: std::vector<std::list<iterator>> table_; std::list<KeyValuePair> data_; size_t current_size_; size_t current_capacity_; Hash hash_maker_; void InsertInternal(const KeyValuePair& element, size_t hashed_key); void Initialization(size_t capacity_ = 32); size_t MakeHash(const KeyType& object) const; void RehashIfNeeded(); }; template<class KeyType, class ValueType, class Hash> HashMap<KeyType, ValueType, Hash>::HashMap(Hash hash_obj) : hash_maker_(hash_obj) { Initialization(); } template<class KeyType, class ValueType, class Hash> template<typename ForwardIterator> HashMap<KeyType, ValueType, Hash>::HashMap( ForwardIterator start, ForwardIterator end, Hash hash_obj) : hash_maker_(hash_obj) { Initialization(); for (; start != end; ++start) { insert(*start); } } template<class KeyType, class ValueType, class Hash> HashMap<KeyType, ValueType, Hash>::HashMap( std::initializer_list<KeyValuePair> init_list, Hash hash_obj) : hash_maker_(hash_obj) { Initialization(); for (auto&& element : init_list) { insert(element); } } template<class KeyType, class ValueType, class Hash> size_t HashMap<KeyType, ValueType, Hash>::size() const { return current_size_; } template<class KeyType, class ValueType, class Hash> bool HashMap<KeyType, ValueType, Hash>::empty() const { return current_size_ == 0; } template<class KeyType, class ValueType, class Hash> Hash HashMap<KeyType, ValueType, Hash>::hash_function() const { return hash_maker_; } template<class KeyType, class ValueType, class Hash> auto HashMap<KeyType, ValueType, Hash>::begin() const -> const_iterator { return const_iterator(data_.begin()); } template<class KeyType, class ValueType, class Hash> auto HashMap<KeyType, ValueType, Hash>::end() const -> const_iterator { return const_iterator(data_.end()); } template<class KeyType, class ValueType, class Hash> auto HashMap<KeyType, ValueType, Hash>::begin() -> iterator { return iterator(data_.begin()); } template<class KeyType, class ValueType, class Hash> auto HashMap<KeyType, ValueType, Hash>::end() -> iterator { return iterator(data_.end()); } template<class KeyType, class ValueType, class Hash> void HashMap<KeyType, ValueType, Hash>::insert(const KeyValuePair& element) { size_t hash_table_cell_id = MakeHash(element.first); if (!table_[hash_table_cell_id].empty()) { auto it = table_[hash_table_cell_id].begin(); while (it != table_[hash_table_cell_id].end()) { if ((*it)->first == element.first) { return; } ++it; } } InsertInternal(element, hash_table_cell_id); RehashIfNeeded(); } template<class KeyType, class ValueType, class Hash> void HashMap<KeyType, ValueType, Hash>::erase(const KeyType& key) { size_t hash_table_cell_id = MakeHash(key); auto it = table_[hash_table_cell_id].begin(); for (; it != table_[hash_table_cell_id].end(); ++it) { if ((*it)->first == key) { data_.erase(*it); table_[hash_table_cell_id].erase(it); --current_size_; return; } } } template<class KeyType, class ValueType, class Hash> auto HashMap<KeyType, ValueType, Hash>::find( const KeyType& key) const -> const_iterator { size_t hash_table_cell_id = MakeHash(key); for (auto&& element : table_[hash_table_cell_id]) { if (element->first == key) { return const_iterator(element); } } return end(); } template<class KeyType, class ValueType, class Hash> auto HashMap<KeyType, ValueType, Hash>::find(const KeyType& key) -> iterator { size_t hash_table_cell_id = MakeHash(key); for (auto&& element : table_[hash_table_cell_id]) { if (element->first == key) { return iterator(element); } } return end(); } template<class KeyType, class ValueType, class Hash> ValueType& HashMap<KeyType, ValueType, Hash>::operator[] (const KeyType& key) { auto it = find(key); if (it == end()) { insert({key, ValueType()}); return data_.back().second; } return it->second; } template<class KeyType, class ValueType, class Hash> const ValueType& HashMap<KeyType, ValueType, Hash>::at( const KeyType& key) const { auto it = find(key); if (it != end()) { return it->second; } throw std::out_of_range("OutOfRangeError"); } template<class KeyType, class ValueType, class Hash> HashMap<KeyType, ValueType, Hash>&HashMap<KeyType, ValueType, Hash>::operator= ( const HashMap &other) { if (this == &other) { return *this; } clear(); hash_maker_ = other.hash_function(); Initialization(other.current_capacity_); for (auto&& element : other) { insert(element); } return *this; } template<class KeyType, class ValueType, class Hash> void HashMap<KeyType, ValueType, Hash>::clear() { for (auto&& element : data_) { size_t hash_table_cell_id = MakeHash(element.first); table_[hash_table_cell_id].clear(); } data_.clear(); current_size_ = 0; } template<class KeyType, class ValueType, class Hash> HashMap<KeyType, ValueType, Hash>::~HashMap() { clear(); } template<class KeyType, class ValueType, class Hash> void HashMap<KeyType, ValueType, Hash>::InsertInternal( const KeyValuePair& element, size_t hashed_key) { data_.emplace_back(element); auto current_iterator = data_.end(); table_[hashed_key].emplace_back(--current_iterator); ++current_size_; } template<class KeyType, class ValueType, class Hash> void HashMap<KeyType, ValueType, Hash>::Initialization(size_t capacity_) { table_ = std::vector<std::list<iterator>> (capacity_); current_capacity_ = capacity_; current_size_ = 0; } template<class KeyType, class ValueType, class Hash> size_t HashMap<KeyType, ValueType, Hash>::MakeHash( const KeyType& object) const { return hash_maker_(object) % current_capacity_; } template<class KeyType, class ValueType, class Hash> void HashMap<KeyType, ValueType, Hash>::RehashIfNeeded() { if (current_capacity_ > 2 * current_size_) { return; } table_.clear(); current_capacity_ *= 2; table_.resize(current_capacity_); for (auto it = data_.begin(); it != data_.end(); ++it) { size_t hash_table_cell_id = MakeHash(it->first); table_[hash_table_cell_id].push_back(it); } }
JavaScript
UTF-8
1,078
2.734375
3
[ "Apache-2.0" ]
permissive
/** * Author: Davide Alocci * Version: 0.0.1 */ import {Enum} from 'enumify'; export default class DonorPosition extends Enum { getDonorPosition(value) { switch (value){ case 1: return DonorPosition.ONE; case 2: return DonorPosition.TWO; case 3: return DonorPosition.THREE; case 4: return DonorPosition.FOUR; case 5: return DonorPosition.FIVE; case 6: return DonorPosition.SIX; case 7: return DonorPosition.SEVEN; case 8: return DonorPosition.EIGHT; case 9: return DonorPosition.NINE; default: return DonorPosition.UNDEFINED; } } } DonorPosition.initEnum({ ONE: { value: 1 }, TWO: { value: 2 }, THREE: { value: 3 }, FOUR:{ value: 4 }, FIVE: { value: 5 }, SIX: { value: 6 }, SEVEN: { value: 7 }, EIGHT: { value: 8 }, NINE: { value: 9 }, UNDEFINED: { value: 'undefined' } });
C++
UTF-8
6,683
2.796875
3
[]
no_license
// // Created by sooda on 16/6/6. // #include "common/util.h" #include <vector> #include <string> #include <functional> #include <iostream> #include <fstream> #include "cppjieba/Unicode.hpp" #include "limonp/StringUtil.hpp" #include "limonp/Logging.hpp" namespace cppmary { std::vector<std::string> split(const std::string &text, char sep) { std::vector<std::string> tokens; std::size_t start = 0, end = 0; while ((end = text.find(sep, start)) != std::string::npos) { tokens.push_back(text.substr(start, end - start)); start = end + 1; } tokens.push_back(text.substr(start)); return tokens; } std::vector<std::string> splitAndTrim(const std::string& text, char sep) { std::vector<std::string> tokens = split(text, sep); std::vector<std::string> trimTokens; for (int i = 0; i < tokens.size(); i++) { std::string tokenStr = tokens[i]; tokenStr = trim(tokenStr); if (tokenStr.empty()) { continue; } trimTokens.push_back(tokenStr); } return trimTokens; } // trim from start std::string &ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } // trim from end std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } // trim from both ends std::string &trim(std::string &s) { return ltrim(rtrim(s)); } void dumpStringMap(std::map<std::string, std::string> stringMap) { std::map<std::string, std::string>::iterator iter; for (iter = stringMap.begin(); iter != stringMap.end(); iter++) { std::cout << iter->first << " " << iter->second << std::endl; } } std::vector<std::string> getSyllablesStringVec(std::string& word) { cppjieba::RuneStrArray syllables; DecodeRunesInString(word, syllables); cppjieba::RuneStrArray::const_iterator iter; std::vector<std::string> sylsVec; for (iter = syllables.begin(); iter != syllables.end(); iter++) { std::string subStr = cppjieba::GetStringFromRunes(word, iter, iter); subStr = trim(subStr); if (subStr.empty()) { continue; } sylsVec.push_back(subStr); } return sylsVec; } std::string getFileString(const std::string& filepath) { std::ifstream is(filepath); std::string filebuffer=""; if (is) { // get length of file: is.seekg (0, is.end); long long length = is.tellg(); is.seekg (0, is.beg); char * buffer = new char [length]; std::cout << "Reading " << filepath << " " << length << " characters... "; // read data as a block: is.read (buffer,length); if (is) std::cout << "all characters read successfully." << std::endl; else std::cout << "error: only " << is.gcount() << " could be read"; is.close(); // ...buffer contains the entire file... filebuffer = std::string(buffer,length); delete[] buffer; } return filebuffer; } void loadDict(std::map<std::string, std::string>& dict, const std::string& filePath, const std::string& pattern, bool bufferFlag) { std::string line; std::vector<std::string> buf; if (bufferFlag) { std::vector<std::string> bufferVec = limonp::Split(filePath,"\n"); for (int i = 0; i < bufferVec.size(); i++) { std::string line = bufferVec[i]; line = trim(line); limonp::Split(line, buf, pattern); assert(buf.size() >= 2); dict[trim(buf[0])] = trim(buf[1]); } } else { std::ifstream ifs(filePath.c_str()); //ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); XCHECK(ifs.is_open()) << "open " << filePath << " failed."; for (size_t lineno = 0; getline(ifs, line); lineno++) { limonp::Split(line, buf, pattern); assert(buf.size() >= 2); dict[trim(buf[0])] = trim(buf[1]); } ifs.close(); } //dumpStringMap(dict); } void loadDict(std::vector<std::string>& keys, std::vector<std::string>& values, const std::string& filePath, const std::string& pattern, bool bufferFlag) { std::string line; std::vector<std::string> buf; if (bufferFlag) { std::vector<std::string> bufferVec = limonp::Split(filePath,"\n"); for (int i = 0; i < bufferVec.size(); i++) { std::string line = bufferVec[i]; limonp::Split(line, buf, pattern); assert(buf.size() >= 2); keys.push_back(buf[0]); values.push_back(buf[1]); } } else { std::ifstream ifs(filePath.c_str()); //ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); XCHECK(ifs.is_open()) << "open " << filePath << " failed."; for (size_t lineno = 0; getline(ifs, line); lineno++) { limonp::Split(line, buf, pattern); assert(buf.size() >= 2); keys.push_back(buf[0]); values.push_back(buf[1]); } ifs.close(); } } std::string replaceAll(const std::string& orig, const std::string& replaceThis, const std::string& replaceWith) { std::string result = orig; while(result.find(replaceThis) != std::string::npos) { result.replace(result.find(replaceThis),replaceThis.size(),replaceWith); } return result; } std::string replaceWith(const std::string& orig, const std::string& replaceThis, const std::string& replaceWith) { std::string result = orig; if (result.find(replaceThis) != std::string::npos) { result = replaceWith; } return result; } std::string getParentPath(std::string location) { std::size_t found = location.rfind("/"); if(found == std::string::npos) { std::cerr << "invalid path " << location << std::endl; exit(0); } std::string parent = location.substr(0, found+1); return parent; } }
Java
UTF-8
1,487
2.90625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fr.philippefichet; /** * * @author glopinous */ public class ProgressBar { private long value; private long max; private String progressBar; private int size; private char progressSymbole = '|'; public ProgressBar(long value, long max, int size) { this.value = value; this.max = max; this.size = size; } public char getProgressSymbole() { return progressSymbole; } public void setProgressSymbole(char progressSymbole) { this.progressSymbole = progressSymbole; } public long getValue() { return value; } public long getMax() { return max; } public String getProgressBar() { int sizeValue = (int) (((float)value / (float)max)*(size)); if (progressBar == null) { StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < size - 2; i++) { if (i <= (sizeValue - 2)) { sb.append(progressSymbole); } else { sb.append(" "); } } sb.append("]"); progressBar = sb.toString(); } return progressBar; } public int getSize() { return size; } }
PHP
UTF-8
524
2.53125
3
[]
no_license
<?php namespace SBL\Action; use SBL\Library\AbstractAction; use Slim\Psr7\Request; use Slim\Psr7\Response; class LogoutAction extends AbstractAction { /** * @param Request $request * @param Response $response * @param array $args * * @return Response */ public function __invoke(Request $request, Response $response, array $args): Response { $this->session->delete('sbl.user.current'); return $response->withStatus(302)->withHeader('Location', '/'); } }
Python
UTF-8
174
3.34375
3
[]
no_license
import itertools def possible_permutations(arg): for per in itertools.permutations(arg): yield list(per) [print(n) for n in possible_permutations([1, 2, 3])]
PHP
UTF-8
894
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; //四脚猫隐式控制器 class UsersController extends Controller { /** * 响应/users的GET请求 */ public function getIndex(Request $req) { return 'getindex';exit; $input = $req->all(); $title = $req->input('title'); return print_r($input, true); } /** * 响应/users/show-name/1的GET请求 */ public function getShowName($id) { return "show user id $id"; } /** * 响应/users/admin-profile的GET请求 */ public function getAdminProfile() { return 'getAdminProfile'; } /** * 响应/users/hello的GET请求 */ public function getHello() { $name = 'Jim'; return view('hello', compact('name')); } }
JavaScript
UTF-8
3,029
3.109375
3
[]
no_license
import { ROWS, COLS, NUM } from './config.js'; import random from './random.js'; export const memory = new Uint8Array(ROWS * COLS); export const pages = [Uint8Array.from(memory)]; export const loadMemory = test => { reset(); const lines = test.split('\n'); let ctr = memory.length - 1; for (let i = lines.length - 1; i >= 0; i--) { for (let k = lines[i].length - 1; k >= 0; k--) { const chr = lines[i][k]; if (chr !== '0') { memory[ctr] = chr.charCodeAt(0); } else { memory[ctr] = 0; } ctr--; } } pages.push(Uint8Array.from(memory)); // console.log(toString()); }; export const set = (index, value) => (memory[index] = value); export const get = index => memory[index]; export const copyToPage = () => pages.push(Uint8Array.from(memory)); export const initialise = () => { for (let i = 0; i < ROWS * COLS; i++) { memory[i] = ((random() * NUM) | 0) + 1; } copyToPage(); }; export const reset = () => { pages.length = 0; memory.fill(0); }; export const forEach = cb => memory.forEach(cb); export const getIndexForXY = (x, y, width = COLS) => { if (x < 0) { throw new Error(`out of bounds: x(${x}) < 0`); } if (x >= COLS) { throw new Error(`out of bounds: x(${x}) > COLS(${COLS})`); } if (y < 0) { throw new Error(`out of bounds: y(${y}) < 0`); } if (y >= ROWS) { throw new Error(`out of bounds: y(${y}) > ROWS(${ROWS})`); } return width * y + x; }; export const getXYForIndex = i => { const x = i % COLS; const y = (i / COLS) | 0; return { x, y }; }; export const toString = (source = memory) => source .reduce((acc, curr, i) => { const { y } = getXYForIndex(i); if (!acc[y]) acc[y] = ''; acc[y] += curr; return acc; }, []) .join('\n'); export const write = tet => { const { x, y, w, h, shape, type: { char } } = tet; // ordering is important so we can jump straight to the shape value let ctr = 0; for (let k = y; k < y + h; k++) { for (let j = x; j < x + w; j++) { if (shape[ctr]) { let i = getIndexForXY(j, k); memory[i] = char.charCodeAt(0); // (ignored for now) } ctr++; } } pages.push(Uint8Array.from(memory)); // document.querySelector('#memdump').innerHTML = toString().replace(/0/g, '🔲').replace(/1/g, '🔳') }; export const test = tet => { const { x, y, w, h, shape } = tet; const res = new Uint8Array(shape.length); let hit = false; // ordering is important so we can jump straight to the shape value let ctr = 0; for (let k = y; k < y + h; k++) { for (let j = x; j < x + w; j++) { if (shape[ctr]) { let i = getIndexForXY(j, k); res[ctr] = memory[i]; if (shape[ctr] && memory[i]) { hit = true; } } ctr++; } } return { hit, res }; }; export const isFree = tet => { try { return !test(tet).hit; } catch (E) { // console.log(E); return false; } };
Python
UTF-8
151
2.984375
3
[]
no_license
def main(): pair = (1, 2) print pair if 3 in pair: print True else: print False if __name__ == '__main__': main()
C++
UTF-8
2,281
2.5625
3
[]
no_license
#include "GameManager.hpp" #include "Services/DataManager.hpp" namespace simpleGL { Window* GameManager::s_pWindowService; INodeMgrPtr GameManager::s_pNodeService; ISceneMgrPtr GameManager::s_pSceneService; IDataMgrPtr GameManager::s_pDataService; // Should be called before anything else void GameManager::Init(unsigned int _windowWidth, unsigned int _windowHeight, std::string _windowName) { // Window as an internal service s_pWindowService = new Window(_windowWidth, _windowHeight, _windowName); s_pWindowService->Init(); // DataMgr as an internal service s_pDataService = IDataMgrPtr(new DataManager()); s_pDataService->Init(); // Null pattern s_pNodeService = INodeMgrPtr(new NullNodeManager()); s_pSceneService = ISceneMgrPtr(new NullSceneManager()); // Init random once srand((uint32_t)glfwGetTime()); } void GameManager::DetachNodeMgr() { s_pNodeService.reset(new NullNodeManager()); } void GameManager::DetachSceneMgr() { s_pSceneService.reset(new NullSceneManager()); } void GameManager::AttachNodeMgr(INodeManager* _service) { if (_service == nullptr) { s_pNodeService.reset(new NullNodeManager()); } else { s_pNodeService.reset(_service); } } void GameManager::AttachSceneMgr(ISceneManager* _service) { if (_service == nullptr) { s_pSceneService.reset(new NullSceneManager()); } else { s_pSceneService.reset(_service); } } // Reset services if needed void GameManager::Update() { GetDataMgr().Update(); GetSceneMgr().Update(); GetNodeMgr().Update(); } void GameManager::Start() { s_pSceneService->Init(); s_pNodeService->Init(); s_pWindowService->Update(); s_pWindowService->Quit(); } void GameManager::Quit() { GetSceneMgr().Quit(); GetDataMgr().Quit(); } void GameManager::Render() { GetDataMgr().Render(); GetSceneMgr().Render(); GetNodeMgr().Render(); } }
Java
UTF-8
1,272
2.40625
2
[]
no_license
package com.zhoujixing.logic; import com.zhoujixing.entity.DateStatisticsModel; import com.zhoujixing.service.CustomerService; import com.zhoujixing.service.DateStatisticsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; /** * 按日期统计业务逻辑层 */ @Component public class DateStatisticsLogic { @Autowired private DateStatisticsService dateStatisticsService; @Autowired private CustomerService customerService; /** * 查询并保存统计 */ public void statistics(){ //获取前一天 Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, -1); //得到前一天 Date date = calendar.getTime(); System.out.println(date.toString()); //获取统计数据 List<DateStatisticsModel> dateStatisticsModelList = customerService.getDayCOUNT(date); for (Iterator<DateStatisticsModel> iterator = dateStatisticsModelList.iterator(); iterator.hasNext(); ) { DateStatisticsModel next = iterator.next(); dateStatisticsService.add(next); } } }
Markdown
UTF-8
1,841
2.84375
3
[ "MIT" ]
permissive
# World of Warcraft Auction The goal of this project is to analyse auction house trends. ## Parts The project is made of two major parts. ### Crawler It contains the crawler which is a node application. The goal here is to crawl auction dump from the [Blizzard's API](https://dev.battle.net/). In the futur, it will also calculate statistics about the acquired dumps. ### Web It presents the data crawled. In the futur, I'll try to have graphics and statistics about each realm. ## Run ### Crawler To run the crawler ```npm start``` and ```npm run test``` to launch the tests. ### Web ```npm run web``` ## TODO There's many things left to do. Those lists are not exhaustives ### Crawler - [ ] Rework the classes separation - [x] Controllers - [ ] CLI - [x] Validate API responses - [x] Have fun with node 4 - [ ] ES6 imports (to considere) - [ ] Significant statistics - [ ] Gather data - [ ] Work with server with multiple names (not even sure what it means) - [ ] Better way to store auction dumps - [ ] Continue Abathur - [x] Improve error management with node-rest-client - [x] Why is the logger not global...? - [x] Logger : Use subject rather than level - [ ] Cleaner : model-test.cleanDb() ### Web - [ ] Choose which stack to use for frontend. Node rest + ng2? - [ ] Admin account to manager everything - [ ] Cool graphics - [ ] Meaningful statistics to present - [ ] Design ## Api key I didn't put my Api keys in the project. If you want to add yours you simply need to create ```src/crawler/key.js``` containing ```javascript module.exports = function() { return 'your key'; }; ``` ## Participate Don't hesitate to PR and add new issues. If you want to help me structure the project and create something more meaningful, don't hesitate to contact me. ## License MIT. If you do something cool with it. Please let me know :)
TypeScript
UTF-8
1,597
3.125
3
[ "MIT" ]
permissive
import { globalAgent } from "http"; class FriendList { friend = []; addFriend(name) { this.friend.push(name); this.announceFriendShip(name) } announceFriendShip(name) { global.console.log(`${name}is now a friend`); } removeFriend(name) { const idx = this.friend.indexOf(name); if (idx === -1) { throw new Error('Friend not found'); } this.friend.splice(idx, 1); } } describe('FriendList', () => { let friendList; beforeEach(() => { friendList = new FriendList(); }) it('intialize friend list', () => { expect(friendList.friend.length).toEqual(0) }); it('adds a friend to the list', () => { friendList.addFriend('Aka') expect(friendList.friend.length).toEqual(1) }) it('announces friendship', () => { // mock function friendList.announceFriendShip = jest.fn(); expect(friendList.announceFriendShip).toHaveBeenCalledTimes(0) friendList.addFriend('Arianl'); expect(friendList.announceFriendShip).toHaveBeenCalledTimes(1) }); describe('removeFriend', () => { it('remove friend', () => { friendList.addFriend('Momo') expect(friendList.friend[0]).toEqual('Momo') friendList.removeFriend('Momo'); expect(friendList.friend[0]).toBeUndefined(); }) it('throws an error as friend does not exits',()=>{ expect (()=>friendList.removeFriend('Momo')).toThrow(new Error('Friend not found')); }) }) });
Markdown
UTF-8
3,351
2.765625
3
[ "MIT" ]
permissive
[<img src='media/logo.png' width='300px' />][github-repo] ========================================================= [![Build Status][shield-travis]][travis] [![Coverage Status][shield-coveralls]][coveralls] [![Downloads][shield-downloads]][npm] [![Version][shield-version]][npm] > Javascript implementation of simple Ciphers <br/> ![CipherJS CLI Demo][cli-demo] ## Installation Install the package using `yarn`: ```bash $ yarn add cipherjs ``` or `npm`: ```bash $ npm install --save cipherjs ``` <br/> ## Usage Start by `require`-ing the module: ```js const CipherJS = require('cipherjs'); ``` It returns an `Object` of available ciphers, each with their own `encrypt` and `decrypt` methods: ```js CipherJS.Vigenere.encrypt('MY SECRET MESSAGE', 'MY SECRET KEY') // YW KIEIIM WIQEYYI ``` <br/> ## Command-line App `cipherjs` comes with a CLI app that lets you encrypt or decrypt data interactively. To use it, install the package globally: ```bash $ npm install -g cipherjs ``` and just execute `cipherjs` in your terminal: ```bash $ cipherjs ``` <br/> ## Ciphers All Ciphers have one `encrypt` and `decrypt` method, with the first argument as the ciphertext / plaintext. ### Affine Cipher Takes two numeric keys, the first of which should be a `coprime` with `26` and the second should be between `0-25`: ```js CipherJS.Affine.encrypt('AFFINE CIPHER', 5, 23) // 'XWWLKR HLUGRE' CipherJS.Affine.decrypt('XWWLKR HLUGRE', 5, 23) // 'AFFINE CIPHER' ``` ### Caesar Cipher Takes one numeric key along with the plaintext / ciphertext: ```js CipherJS.Caesar.encrypt('CAESAR CIPHER', 13) // 'PNRFNE PVCURE' CipherJS.Caesar.decrypt('PNRFNE PVCURE', 13) // 'CAESAR CIPHER' ``` ### Simple Substitution Cipher Takes only a string key for encoding and decoding: ```js CipherJS.Substitution.encrypt('SIMPLE SUBSTITUTION CIPHER', 'SECRET KEY') // 'OBHLGT OQEOPBPQPBJI CBLATN' CipherJS.Substitution.decrypt('OBHLGT OQEOPBPQPBJI CBLATN', 'SECRET KEY') // 'SIMPLE SUBSTITUTION CIPHER' ``` ### Vigenere Cipher Takes only a string key for encoding and decoding: ```js CipherJS.Vigenere.encrypt('VIGENERE CIPHER', 'ANOTHER SECRET KEY') // 'VVUXUIIW GKGLXB' CipherJS.Vigenere.decrypt('VVUXUIIW GKGLXB', 'ANOTHER SECRET KEY') // 'VIGENERE CIPHER' ``` <br/> ## Contributing - [Fork][github-fork], Enhance, Send PR - Lock issues with any bugs or feature requests - Implement something from Roadmap - Spread the word <br/> ## License This package is available as open source under the terms of the [MIT License][github-license]. <br/> [logo]: media/logo.png [cli-demo]: media/cli.gif [npm]: https://www.npmjs.com/package/cipherjs [travis]: https://travis-ci.org/sheharyarn/cipherjs [coveralls]: https://coveralls.io/github/sheharyarn/cipherjs [github-repo]: https://github.com/sheharyarn/cipherjs [github-fork]: https://github.com/sheharyarn/cipherjs/fork [github-license]: https://github.com/sheharyarn/cipherjs/blob/master/LICENSE [shield-travis]: https://img.shields.io/travis/sheharyarn/cipherjs.svg [shield-coveralls]: https://img.shields.io/coveralls/sheharyarn/cipherjs.svg [shield-downloads]: https://img.shields.io/npm/dt/cipherjs.svg [shield-version]: https://img.shields.io/npm/v/cipherjs.svg
TypeScript
UTF-8
560
3.6875
4
[]
no_license
class User { public name: string; public email: string; public age: number; constructor(name: string, email: string, age: number){ this.name = name; this.email = email; this.age= age; console.log("User Is Created with Name = "+ this.name+ " Email = "+ this.email + ' and Age = '+ this.age ) } register() { console.log(this.name, ' Is now registered') } } let usman = new User("Usman Bakhsh", "ehmusman@gmail.com", 25) console.log(usman.name) console.log(usman.email) console.log(usman.age) usman.register()
PHP
UTF-8
1,414
2.53125
3
[]
no_license
<?php namespace App\DataFixtures; use App\Entity\Coaches; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; class CoachesFixture extends Fixture { private Coaches $coachFixture; public const COACH_FIXTURE = 'coach-fixture'; public function load(ObjectManager $manager): Coaches { $this->coachFixture = new Coaches(); $this->coachFixture->setUsername('test'); $this->coachFixture->setRoles(['role' => 'ROLE_USER']); $manager->persist($this->coachFixture); $manager->flush(); $this->addReference(self::COACH_FIXTURE, $this->coachFixture); return $this->coachFixture; } /** * @param ObjectManager $manager * @param int $nombre * @return mixed */ public function loadMultiCoach(ObjectManager $manager, $nombre) { $coachFixtures = null; for ($compteur = 0; $compteur < $nombre; $compteur++) { $coach = new Coaches(); $coach->setUsername('test_' . $compteur); $coach->setRoles(['role' => 'ROLE_USER']); $coachFixtures[] = $coach; $manager->persist($coach); $manager->flush(); } return $coachFixtures; } public function deleteFixture(ObjectManager $manager) : void { $manager->remove($this->coachFixture); $manager->flush(); } }
JavaScript
UTF-8
6,259
2.71875
3
[]
no_license
const Discord = require("discord.js"); const genUtils = require("../../command_utilities/general_utilities"); module.exports.run = async (bot, message, args) => { if (args.length == 0) { message.channel.send(`You have to provide a password, ${genUtils.getRandomNameInsult(message)}`); return; } else if (args.length > 1) { message.channel.send(`Too many parameters, ${genUtils.getRandomNameInsult(message)}`); return; } let password = args[0]; if (!password.match(/^\d+$/g)) { message.channel.send(`The supplied password must be an integer, ${genUtils.getRandomNameInsult(message)}`); return; } switch (password) { case "25": { let newEmbed = new Discord.RichEmbed(); newEmbed.setImage(`https://cdn.discordapp.com/attachments/527666605396721684/610339595963334667/e4aa7c6e21b32fd6b97afd495fe4e338.png`); message.channel.send(newEmbed); break; } case "69": { message.channel.send(`🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆🍆`); break; } case "83": { let newEmbed = new Discord.RichEmbed(); newEmbed.setImage(`https://cdn.discordapp.com/attachments/494016258078015491/610300158999265296/20190810_152708.jpg`); message.channel.send(newEmbed); break; } case "243": { message.channel.send(`excuse me?`); } case "420": { let newEmbed = new Discord.RichEmbed(); newEmbed.setImage(`https://cdn.discordapp.com/attachments/527341248214990850/610330928807411715/testImage.png`); message.channel.send(newEmbed); break; } case "621": { let newEmbed = new Discord.RichEmbed(); newEmbed.setImage(`https://cdn.discordapp.com/attachments/527341248214990850/610341313224769550/gotcha.png`); message.channel.send(newEmbed); break; } case "666": { let newEmbed = new Discord.RichEmbed(); newEmbed.setImage(`https://cdn.discordapp.com/attachments/527341248214990850/584252304992108577/AaAAAaaaAAaAaaaaAaAAAAAaAaAa.jpg`); message.channel.send(newEmbed); break; } case "911": { message.channel.send(`https://youtu.be/AJW2LlphuSs?t=155`); break; } case "980": { message.channel.send(`honk honk`); break; } case "1273": { message.channel.send(`https://www.youtube.com/watch?v=jPrmR3RIoFE`); break; } case "1337": { message.channel.send(`😔`); break; } case "8008": case "80085": case "8008135": { bot.commands.get("fumika").run(bot, message, args); break; } case "12345": { message.channel.send("haha, nice one"); break; } case "25565": { let newEmbed = new Discord.RichEmbed(); newEmbed.setImage(`https://www.meme-arsenal.com/memes/4eef95644849536a6ab8e3f0c60eb18f.jpg`); message.channel.send(newEmbed); break; } case "27015": { let newEmbed = new Discord.RichEmbed(); newEmbed.setImage(`https://cdn.discordapp.com/attachments/527341248214990850/610316597952774153/Steam_2019-08-11_20-39-57.png`); message.channel.send(newEmbed); break; } case "980089": { bot.commands.get("pride").run(bot, message, args); break; } case "2204355": { let newEmbed = new Discord.RichEmbed(); newEmbed.setImage(`https://thumbs.gfycat.com/ConcernedFrayedAuklet-size_restricted.gif`); message.channel.send(newEmbed); break; } case "8675309": { message.channel.send("Jenny?"); break; } case "01251999": { message.channel.send("https://itsyourbirthday.today/#bianca"); break; } case "08011998": { message.channel.send("https://itsyourbirthday.today/#vincent"); break; } case "10151996": { message.channel.send("https://itsyourbirthday.today/#kordell"); break; } case "10261994": { message.channel.send("https://itsyourbirthday.today/#michael"); break; } case "8005882300": { bot.commands.get("rimage").run(bot, message, ["empire today"]); break; } case "18775277454": { message.channel.send(`https://www.youtube.com/watch?v=ybJ6fS7ruuo`); break; } default: { message.channel.send(`Incorrect password. However, here's some info I found about that number:\n...`); bot.commands.get("urban").run(bot, message, args); break; } } } module.exports.help = { name: "password", description: "Takes a password, and produces an output if the password is correct", usage: "!password (number)", example: "!password 83", funFacts: [ `This command spawned when I realized how many numbers associated with inside jokes there are, with some being more obscure than others. One obscure \ one is listed in the example above.`, `If the password isn't currently in the system, Big Bill will try to look up an urban article of the number. A surprising amount of the time, there is \ an article for the number.` ] }
Python
UTF-8
1,930
3.65625
4
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "SMLNJ" ]
permissive
import gc import timeit import time class TimeMe: """Small class to time portions of the code. It has two main usages: 1. In a with block, of the type: t = TimeMe() with t: doMyThings() print("Took {} seconds".format(t.interval) 2. With multiple ticks and tocs: t = TimeMe() t.tic() # stores the marker 'start' ... t.tic("halfway") # stores the marker 'halfway' ... secondsElapsed = t.toc() # get the seconds from start secondsElapsedFromHalfway= t.toc() # get the seconds from halfway """ def __init__(self, timer=None, disable_gc=False, verbose=False): if timer is None: timer = timeit.default_timer self.timer = timer self.disable_gc = disable_gc self.verbose = verbose self.start = self.end = self.interval = None self.markers = dict() def __enter__(self): if self.disable_gc: self.gc_state = gc.isenabled() gc.disable() self.start = self.timer() return self def __exit__(self, *args): self.end = self.timer() if self.disable_gc and self.gc_state: gc.enable() self.interval = self.end - self.start if self.verbose: print('time taken: %f seconds' % self.interval) def print(self, end='\n'): """ Print the time elapsed in the with block """ print("%.4fs" % self.interval, end=end, flush=True) def tocStr(self, markerName: str = "start", restart: bool = False): """ Get a string representation of the time elapsed from the specified marker """ return "%.4fs" % self.toc(markerName) def tick(self, markerName: str = "start"): self.markers[markerName] = self.timer() def toc(self, markerName: str = "start", restart: bool = False): return self.timer() - self.markers[markerName]
Python
UTF-8
5,223
2.796875
3
[]
no_license
""" Loads the raw data files and dumps the intermediate ones. If no golden files exist, copies them into place. If golden files exist, compares the data and reports on differences. You should run this once to populate new golden files before making any changes to the raw data parsers. """ import argparse import difflib import json import os import pathlib import shutil from pad.common.pad_util import json_string_dump from pad.common.shared_types import Server from pad.raw_processor import merged_database from pad.raw_processor.crossed_data import CrossServerDatabase def parse_args(): parser = argparse.ArgumentParser(description="Runs the integration test.", add_help=False) inputGroup = parser.add_argument_group("Input") inputGroup.add_argument("--input_dir", required=True, help="Path to a folder where the input data is") outputGroup = parser.add_argument_group("Output") outputGroup.add_argument("--output_dir", required=True, help="Path to a folder where output should be saved") helpGroup = parser.add_argument_group("Help") helpGroup.add_argument("-h", "--help", action="help", help="Displays this help message and exits.") return parser.parse_args() def run_test(args): input_dir = args.input_dir output_dir = args.output_dir new_output_dir = os.path.join(output_dir, 'new') pathlib.Path(new_output_dir).mkdir(parents=True, exist_ok=True) golden_output_dir = os.path.join(output_dir, 'golden') pathlib.Path(golden_output_dir).mkdir(parents=True, exist_ok=True) jp_db = merged_database.Database(Server.jp, input_dir) na_db = merged_database.Database(Server.na, input_dir) kr_db = merged_database.Database(Server.kr, input_dir) print('loading JP') jp_db.load_database(skip_extra=True) print('loading NA') na_db.load_database(skip_extra=True) print('loading KR') kr_db.load_database(skip_extra=True) print('merging data') cross_db = CrossServerDatabase(jp_db, na_db, kr_db) print('saving merged data') cross_db.save_all(new_output_dir, True) # Add sort by something, bonuses seem to be non-deterministicly ordered. files = { 'all_cards.json': cross_db.all_cards, 'dungeons.json': cross_db.dungeons, 'active_skills.json': cross_db.active_skills, 'leader_skills.json': cross_db.leader_skills, 'enemy_skills.json': cross_db.enemy_skills, # 'jp_bonuses.json': cross_db.jp_bonuses, # 'na_bonuses.json': cross_db.na_bonuses, # 'kr_bonuses.json': cross_db.kr_bonuses, } failed_comparisons = 0 bad_records = 0 print('starting diff') for file, data in files.items(): new_file = os.path.join(new_output_dir, file) golden_file = os.path.join(golden_output_dir, file) if not os.path.exists(golden_file): print('golden file does not exist, creating', golden_file) shutil.copy(new_file, golden_file) continue print('diffing', golden_file, 'against', new_file) with open(golden_file, encoding="utf-8") as f: golden_data = json.load(f) if len(golden_data) != len(data): print('ERROR') print('ERROR: file lengths differed ({} vs {}), indicates old golden data for {}'.format( len(golden_data), len(data), file)) print('ERROR') failed_comparisons += 1 continue failures = [] for i in range(len(golden_data)): gold_row = golden_data[i] new_row = data[i] gold_str = json_string_dump(gold_row, pretty=True) new_str = json_string_dump(new_row, pretty=True) if gold_str != new_str: failures.append([gold_str, new_str]) if not failures: continue fail_count = len(failures) disp_count = min(fail_count, 6) print('encountered', fail_count, 'errors, displaying the first', disp_count) failed_comparisons += 1 bad_records += fail_count failure_ids = [] for failure in failures: gold_str = failure[0] failure_ids.append(find_ids(gold_str)) print('All failing ids:\n' + '\n'.join(failure_ids)) for i in range(disp_count): gold_str = failures[i][0] new_str = failures[i][1] print('row identifiers:\n{}\n'.format(find_ids(gold_str))) diff_lines = difflib.context_diff( gold_str.split('\n'), new_str.split('\n'), fromfile='golden', tofile='new', n=1) print('\n'.join(diff_lines)) if failed_comparisons: print('Bad files:', failed_comparisons) print('Bad records:', bad_records) exit(1) def find_ids(gold_str): def is_id_line(line): return any(x in line for x in ['monster_no', 'dungeon_id', 'leader_skill_id', 'active_skill_id']) id_hits = filter(is_id_line, gold_str.split('\n')) id_info = set(map(str.strip, id_hits)) return '\n'.join(id_info) if __name__ == '__main__': args = parse_args() run_test(args)
JavaScript
UTF-8
1,325
2.703125
3
[]
no_license
// document.getElementById("bio").innerHTML = "Selam gençler" // var intro1 = document.getElementById("intro1"); // var mesaj = document.getElementById("mesaj"); // mesaj.innerHTML = intro1.innerHTML; // var tumListeler = document.getElementsByTagName("ul"); // var sehirler = tumListeler[0]; // var sehirElemanlari = sehirler.getElementsByTagName("li"); // for (i = 0; i < sehirElemanlari.length; i++) { // alert(sehirElemanlari[i].innerHTML); // } // var classElemanlari = document.getElementsByClassName("intro1"); // alert(classElemanlari[0].innerHTML); // var queryElemanlari = document.querySelectorAll("p.intro1"); // alert(queryElemanlari.length); // var isimElemanlari = document.getElementsByName("musteriAdi") // alert(isimElemanlari[0].value) // var h1Eleman = document.getElementById("berkay"); // h1Eleman.addEventListener("mouseover", rengiDegistir); // function rengiDegistir() { // document.getElementById("div1").style.backgroundColor = "red"; // } // var node = document.getElementById("agac"); // alert(node.childNodes[0].nodeValue); var baslik = document.createElement("h2"); var node = document.createTextNode("Hey JS"); baslik.appendChild(node); var div1 = document.getElementById("div1"); var p2 = document.getElementById("p2"); // div1.insertBefore(baslik, p2); div1.replaceChild(baslik, p2);
Java
UTF-8
1,373
1.8125
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.tremorvideo.sdk.android.richmedia; import com.tremorvideo.sdk.android.videoad.aw; public class l { public com.tremorvideo.sdk.android.videoad.s.a a; private String b; private String c; private int d; private int e; private aw f[]; private boolean g; public l(String s, String s1, int i, int j, aw aaw[], boolean flag, com.tremorvideo.sdk.android.videoad.s.a a1) { d = i; e = j; b = s; c = s1; f = aaw; g = flag; a = a1; } public int a() { return d; } public void a(String s) { c = s; } public int b() { return e; } public String c() { return b; } public int d() { if (b != null && b.startsWith("video-")) { return Integer.parseInt(b.substring(b.length() - 1)) - 1; } else { return -1; } } public String e() { return c; } public boolean f() { return g; } public aw[] g() { return f; } public com.tremorvideo.sdk.android.videoad.s.a h() { return a; } }
Java
UTF-8
387
1.867188
2
[]
no_license
package com.welove520.qzoneemojiparser.emoji; import android.support.annotation.NonNull; import com.welove520.qzoneemojiparser.emoji.category.QzoneCategory; public final class IosEmojiProvider implements EmojiProvider { @Override @NonNull public EmojiCategory[] getCategories() { return new EmojiCategory[]{ new QzoneCategory() }; } }
PHP
UTF-8
904
2.53125
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateNewsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::defaultStringLength(191); Schema::create('news', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('title',3000); $table->string('body',5000); $table->integer('user_id'); $table->string('image_1',555)->default('noImage.jpg'); $table->string('image_2',555); $table->string('image_3',555); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('news'); } }
Java
UTF-8
1,718
2.265625
2
[]
no_license
package ru.job4j.passport.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import ru.job4j.passport.model.Passport; import ru.job4j.passport.service.PassportRestService; import java.util.List; @RestController @RequestMapping("/passportRest") public class PassportController { private final PassportRestService service; public PassportController(PassportRestService service) { this.service = service; } @PostMapping public Passport save(@RequestBody Passport passport) { return service.add(passport); } @PutMapping public ResponseEntity<Void> update(@RequestParam int id, @RequestBody Passport passport) { boolean status = service.replace(id, passport); return ResponseEntity .status(status ? HttpStatus.OK : HttpStatus.NOT_FOUND) .build(); } @DeleteMapping public ResponseEntity<Void> delete(@RequestParam int id) { boolean status = service.delete(id); return ResponseEntity .status(status ? HttpStatus.OK : HttpStatus.NOT_FOUND) .build(); } @GetMapping("/getBySerial") public Passport getBySerial(@RequestParam int serial) { return service.findBySerial(serial); } @GetMapping("/getAll") public List<Passport> getAll() { return service.findAll(); } @GetMapping("/unavailable") public List<Passport> unavailable() { return service.findUnavaliabe(); } @GetMapping("/findReplaceable") public List<Passport> findReplaceable() { return service.findReplaceable(); } }
Shell
UTF-8
473
3.765625
4
[]
no_license
#!/bin/bash ####### # script used to verify that the user has correctly execute the exercise # # Produce a file with the count of the 'WARN' occurences in all the 'log' files # `find target/ -name "*.log" -print | xargs grep WARN | wc -l > count-warn` # ####### result=1 checkCount(){ if [ -e /root/count-warn ] then if [ `cat /root/count-warn` -eq 133 ] then result=0 fi fi } checkCount [ $result -eq 0 ] && echo "done"
JavaScript
UTF-8
3,055
2.875
3
[]
no_license
//Imported the request Module var request = require('request'); var async = require('async') function wrapperObject(affId,affToken) { this.affId = affId; this.affToken = affToken; } function categoryProcessor(item,callback) { var categoryObj = { name:item['apiName'], get:item['availableVariants']['v1.1.0']['get'], deltaGet:item['availableVariants']['v1.1.0']['deltaGet'] }; callback(null,categoryObj); } exports.mainClass = wrapperObject; //Use this Function to get a list of all categories //It returns a list of object having name,feed url and delta field url //Delta field url is used to generate a list of small number of frequently changing items wrapperObject.prototype.getAllCategories = function(opts,callback) { reqOpts= { url : "https://affiliate-api.flipkart.net/affiliate/api/"+this.affId+".json", method : "GET" } request(reqOpts,function(err,response,body){ if(err)callback(err,null); else { async.map(JSON.parse(body)['apiGroups']['affiliate']['apiListings'],categoryProcessor, function(err,result){ if(err)console.log(err); else console.log(result); }); } }); } wrapperObject.prototype.getThisCategoryLink = function(opts,callback) { if(opts['category']==undefined) { callback(new Error("Category not provided"),null); return; } else var category = opts['category']; reqOpts= { url : "https://affiliate-api.flipkart.net/affiliate/api/"+this.affId+".json", method : "GET" } request(reqOpts,function(err,response,body){ if(err)callback(err,null); else { async.detect(JSON.parse(body)['apiGroups']['affiliate']['apiListings'] ,function(item,cb){ if(item['apiName']==category)cb(null,true); else cb(null,false); },function(err,result){ if(err)console.log(err); if(result==undefined) { callback(new Error("Category not matching"),null); return; } else { callback(null,{ name:result['apiName'], get:result['availableVariants']['v1.1.0']['get'], deltaGet:result['availableVariants']['v1.1.0']['deltaGet'] }); } }); } }); } wrapperObject.prototype.searchProduct = function(opts,callback) { if(opts['searchKey'] == undefined || opts['resultCount']<0) { callback(new Error("Error in search product options"),null); return; } reqOpts= { url : "https://affiliate-api.flipkart.net/affiliate/1.0/search.json", headers:{ "Fk-Affiliate-Id":this.affId, "Fk-Affiliate-Token":this.affToken }, qs:{ query:opts['searchKey'], resultCount:2 }, method : "GET", qs:{ query:opts['searchKey'], resultCount:parseInt(opts['resultCount'],10) } } request(reqOpts,function(err,response,body){ if(err)callback(err,null); else callback(null,body); }); } wrapperObject.prototype.getDeltaFeed = function(opts,callback) { if(opts['link']==undefined) { callback(new Error("No link provided"),null) return; } } module.exports = function(affId,affToken) { var obj = new wrapperObject(affId,affToken); return obj; }
Markdown
UTF-8
4,112
2.515625
3
[]
no_license
# Cut to the chase Everyone (alone) write a haiku about your story. 5-7-5. What's the most important thing? The essence? # Backing up Gists <http://amandabee.github.io/CUNY-data-skills/hands-on/advanced_gist.html> # Surveys Make a google survey; Look at the results in a spreadsheet; Think about how much you actually need to know. We're doing this light. Some things we should be clear on: a real survey is a random sample. But, asking what people think is a great way to engage an audience and build a better and more diverse network of sources. So ... let's look at [some examples](http://freegreentea.info/talks/numeracy/#/12). (A [newer poll](http://blogs.wsj.com/metropolis/2014/12/03/poll-should-horse-drawn-carriages-be-banned/) brought in tens of thousands of votes). [The Public Insight Network](https://www.publicinsightnetwork.org/about/) is more complex than it looks on its face, but they tell a great story about networks, that starts in Jan 2009, when [US Airways Flight 1549](http://en.wikipedia.org/wiki/US_Airways_Flight_1549) [made an emergency landing](http://en.wikipedia.org/wiki/US_Airways_Flight_1549#/media/File:Plane_crash_into_Hudson_River_%28crop%29.jpg) in the Hudson River. WNYC, and a few other news outlets reporting on the crash landing had a box in their sidebar inviting folks to join the Public Insight Network and/or asking for folks who work in aviation to explain how something like this happens. Ultimately, PIN wasn't integral to unravelling that mystery, but it meant that the network was now stocked with a lot of folks who work in aviation. Fast forward almost a year: two hours after leaving San Diego, NW Airlines Flight 188 [lost contact](http://en.wikipedia.org/wiki/Northwest_Airlines_Flight_188) with air traffic control. 20 minutes after the flight was supposed to have landed, Air Traffic Controllers finally got ahold of the pilots who were 100 miles past Minneapolis. A lot of newsrooms were trying to figure out *what happened*, especially since the FAA was not being particularly forthcoming. Finally, someone (I think it was MPR, but I can't swear to that) sent a query out to the Public Insight Network: "What should we be asking?" and got the same response from lots and lots of folks who work in aviation: The pilots were probably distracted, checking Facebook or email. Et voila: on direct questioning in a press conference we learned that the pilots were checking email ([schedules, they said](http://www.cnn.com/2009/US/10/26/airliner.flyby/index.html)). Without that specialized network, we might not have gotten the story out of the FAA. ## More [Listenign Post NOLA](http://listeningpostnola.com/) does a great job of getting folks talking about local issues, from taxes to wetlands conservation. ProPublica regularly seeks input from readers, on [Patient Privacy](http://www.propublica.org/getinvolved/item/has-your-medical-privacy-been-compromised), [Debt Collection](http://www.propublica.org/getinvolved/item/have-you-ever-been-sued-over-a-debt-help-propublica-investigate-collection-), and [Workers Comp](http://www.propublica.org/getinvolved/item/help-propublica-investigate-workers-comp). * Some of this may be apocryphal. But it's still a good story. # Spreadsheet Funtimes U.S. Department of Health & Human Services Administration for Children & Families publishes state by state data on child welfare outcomes, including time to adopt. For those children who are adopted out of foster care, how long do they spend *in* care first? I pulled out some 2013 [data](http://amandabee.github.io/CUNY-data-skills/assets/adoption_timeframe.csv) for us to play with. What's the national average? + Break out a small chunk. Get a raw number and give that as a percent of the whole. Are you comfortable with what the figures are doing? What's the halfway point? How long does it take for at least half of the kids in care to be adopted? # Inkscape http://stackoverflow.com/questions/27741030/embedding-svg-image-into-a-webpage-different-behaviour-in-ff http://wiki.inkscape.org/wiki/index.php/Tricks_and_tisp
C
UTF-8
10,464
3.328125
3
[]
no_license
#include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <inttypes.h> #include "seq-tree.h" SEQNode *SEQ_NewNode(uint32_t val) { SEQNode *root = malloc(sizeof(struct SEQ_Node)); root->parents = T; root->left = T; root->right = T; root->value = val; root->color = RB_RED; root->size = 1; } SEQTree *SEQ_NewTree(uint32_t val) { SEQNode *root = SEQ_NewNode(val); SEQTree *tree = (SEQTree *)malloc(sizeof(struct SEQ_Tree)); root->color = RB_BLACK; root->size = 1; tree->root = root; return tree; } static void Left_Rotate(SEQTree *tree, SEQNode *pivot) { SEQNode *right = pivot->right; right->size = pivot->size; pivot->right = right->left; if (right->left != T) right->left->parents = pivot; right->left = pivot; right->parents = pivot->parents; pivot->parents = right; if (tree->root == pivot) tree->root = right; else if (pivot == right->parents->left) right->parents->left = right; else if (pivot == right->parents->right) right->parents->right = right; pivot->size = pivot->left->size + pivot->right->size + 1; } static void Right_Rotate(SEQTree *tree, SEQNode *pivot) { SEQNode *left = pivot->left; left->size = pivot->size; pivot->left = left->right; if (left->right != T) left->right->parents = pivot; left->right = pivot; left->parents = pivot->parents; pivot->parents = left; if (tree->root == pivot) tree->root = left; else if (pivot == left->parents->left) left->parents->left = left; else if (pivot == left->parents->right) left->parents->right = left; pivot->size = pivot->left->size + pivot->right->size + 1; } static void SEQ_InsertFix(SEQTree *tree, SEQNode *new) { SEQNode *current = new; SEQNode *uncle; while(current->parents->color == RB_RED) { if (current->parents == current->parents->parents->left) { uncle = current->parents->parents->right; if (uncle->color == RB_RED) { uncle->color = RB_BLACK; current->parents->color = RB_BLACK; current = current->parents->parents; current->color = RB_RED; continue; } if (current == current->parents->right) { current = current->parents; Left_Rotate(tree, current); continue; } if (current == current->parents->left) { current->parents->parents->color = RB_RED; current->parents->color = RB_BLACK; Right_Rotate(tree, current->parents->parents); break; } } if (current->parents == current->parents->parents->right) { uncle = current->parents->parents->left; if (uncle->color == RB_RED) { uncle->color = RB_BLACK; current->parents->color = RB_BLACK; current = current->parents->parents; current->color = RB_RED; continue; } if (current == current->parents->left) { current = current->parents; Right_Rotate(tree, current); continue; } if (current == current->parents->right) { current->parents->parents->color = RB_RED; current->parents->color = RB_BLACK; Left_Rotate(tree, current->parents->parents); break; } } } tree->root->color = RB_BLACK; } void SEQ_InsertNode(SEQTree *tree, SEQNode *node) { SEQNode *search = tree->root; SEQNode *current = T; while(search != T) { current = search; current->size++; //seq insert a new node if (node->value < search->value) search = search->left; else search = search->right; } if (current == T) { tree->root = node; } if (node->value < current->value) current->left = node; else current->right = node; node->parents = current; node->left = T; node->right = T; node->size = 1; node->color = RB_RED; SEQ_InsertFix(tree, node); } static void SEQ_Transplat(SEQTree *tree, SEQNode *old, SEQNode *new) { if (tree->root == old) tree->root = new; else if (old == old->parents->left) old->parents->left = new; else old->parents->right = new; new->parents = old->parents; } static SEQNode *MinNode(SEQTree *tree, SEQNode *node) { while (node->left != T) node = node->left; return node; } static void SEQ_DeleteFix(SEQTree *tree, SEQNode *node) { SEQNode *brother; SEQNode *current = node; while(current != tree->root && current->color == RB_BLACK) { if (current == current->parents->left) { brother = current->parents->right; if (brother->color == RB_RED) { brother->color = RB_BLACK; current->parents->color = RB_RED; Left_Rotate(tree, current->parents); continue; } if (brother->left->color == RB_BLACK && brother->right->color == RB_BLACK) { brother->color = RB_RED; current = current->parents; continue; } if (brother->right->color == RB_BLACK) { brother->left->color = RB_BLACK; brother->color = RB_RED; Right_Rotate(tree, brother); } else { brother->color = current->parents->color; current->parents->color = RB_BLACK; brother->right->color = RB_BLACK; Left_Rotate(tree, current->parents); current = tree->root; } } else { brother = current->parents->left; if (brother->color == RB_RED) { brother->color = RB_BLACK; current->parents->color = RB_RED; Right_Rotate(tree, current->parents); continue; } if (brother->left->color == RB_BLACK && brother->right->color == RB_BLACK) { brother->color = RB_RED; current = current->parents; continue; } if (brother->left->color == RB_BLACK) { brother->color = RB_RED; brother->right->color = RB_BLACK; Left_Rotate(tree, brother); } else { brother->color = current->parents->color; current->parents->color = RB_BLACK; brother->left->color = RB_BLACK; Right_Rotate(tree, current->parents); current = tree->root; } } } current->color = RB_BLACK; } void SEQ_DeleteNode(SEQTree *tree, SEQNode *node) { SEQNode *current; SEQNode *search; uint32_t color = node->color; if (node->left == T) { current = node->right; SEQ_Transplat(tree, node, current); search = current->parents; while(search != T) { search->size--; search = search->parents; } } else if (node->right == T) { current = node->left; SEQ_Transplat(tree, node, current); search = current->parents; while(search != T) { search->size--; search = search->parents; } } else { SEQNode *min = MinNode(tree, node->right); color = min->color; current = min->right; min->color = node->color; if(min->parents == node) { current->parents = min; min->left = node->left; node->left->parents = min; SEQ_Transplat(tree, node ,min); min->size = min->left->size + min->right->size + 1; search = min->parents; while(search != T) { search->size--; search = search->parents; } }else { SEQ_Transplat(tree, min, min->right); min->left = node->left; node->left->parents = min; min->right = node->right; node->right->parents = min; min->size = min->left->size + min->right->size + 1; SEQ_Transplat(tree, node, min); search = current->parents; while(search != T) { search->size--; search = search->parents; } } } if (color == RB_BLACK) SEQ_DeleteFix(tree, current); T->parents = NULL; } uint32_t SEQ_SelfTest(SEQNode *root) { uint32_t ret = 0; uint32_t lret; uint32_t rret; if (root != T) { lret = SEQ_SelfTest(root->left); ret = lret; if (root->color == RB_BLACK) ret += 1; else if (root->left->color != RB_BLACK || root->right->color != RB_BLACK) { printf("color error val=%u\n", root->value); exit(1); } if (root->size != (root->left->size + root->right->size + 1)) { printf("size is error %u\n", root->value); exit(2); } rret = SEQ_SelfTest(root->right); if (lret != rret) { printf("error count of black node is not match %u\n", root->value); exit(1); } } return ret; } void SEQ_walkTreeRec(SEQNode *root) { if ( root != T ) { SEQ_walkTreeRec(root->left); printf("%u\n", root->value); SEQ_walkTreeRec(root->right); } } SEQNode * SEQ_Walk(SEQNode *root, uint32_t i) { uint32_t current; current = root->left->size + 1; if ( i == current) return root; else if (i < current) SEQ_Walk(root->left, i); else if (i > current) SEQ_Walk(root->right, i-current); } int main(int argc, char *argv[]) { SEQTree *tree = SEQ_NewTree(500); int i = 0; SEQNode *arr[10000]; uint32_t val; SEQNode *node; for (; i < 1000; i++) { val = random(); arr[i] = SEQ_NewNode(val%1000); SEQ_InsertNode(tree, arr[i]); } i = 0; for (; i < 900; i++) { SEQ_DeleteNode(tree, arr[i]); } SEQ_SelfTest(tree->root); SEQ_walkTreeRec(tree->root); node = SEQ_Walk(tree->root, 99); printf("get node %u\n", node->value); }
C#
UTF-8
505
2.84375
3
[]
no_license
using Microsoft.VisualBasic.FileIO; ... var path = @"C:\YourFile.csv"; using (var parser = new TextFieldParser(path)) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters(","); string[] line; while (!parser.EndOfData) { try { line = parser.ReadFields(); } catch (MalformedLineException ex) { // log ex.Message } }
Markdown
UTF-8
8,324
3.296875
3
[]
no_license
--- layout: page title: 'Denoising: wavelet thresholding' date: 2011-01-23 14:25:48.000000000 -05:00 category: course-material topic: imaging comments: true --- We have seen a naïve way to perform denoising on images by a simple <a href="http://blancosilva.github.io/course-material/2011/01/18/convolution-with-gaussian-kernels.html">convolution with Gaussian kernels</a>. In this post I would like to compare that simple method with a more elaborate one: *wavelet thresholding*. The basic philosophy is based upon the local knowledge that wavelet coefficients offer us: Intuitively, small wavelet coefficients are dominated by noise, while wavelet coefficients with a large absolute value carry more signal information than noise. Being that the case, it is reasonable to obtain a fast denoising of a given image if we perform two basic operations: * Eliminate in the wavelet representation those elements with small coefficients, and * Decrease the impact of elements with large coefficients. In mathematical terms, all we are doing is *thresholding* the absolute value of wavelet coefficients by an appropriate function. For example, if we chose to eliminate all coefficients with absolute value less than a given threshold <span>\\( \theta \\)</span>, and keep the rest of the coefficients untouched, we end up with the thresholding function <span>\\( \tau_\theta \colon \mathbb{R}^+ \to \mathbb{R} \\)</span> given by: <p style="text-align:center;"><img src="https://i0.wp.com/farm6.static.flickr.com/5124/5381177149_15bb17a09e_m_d.jpg" style="width:25%"></p> <div> \begin{equation} \tau_\theta (x) = \begin{cases} 0 &\text{if } 0 \leq x\leq \theta \\ x &\text{if } x > \theta\end{cases} \end{equation} </div> We refer to this function as a *hard thresholding*. But we might want to decrease the impact of the elements with large coefficients in absolute value—this is what we refer as *soft thresholding*. A common way to perform this thresholding is by simple imposition of continuity of the function; e.g.: <p style="text-align:center;"><img src="https://i0.wp.com/farm6.static.flickr.com/5047/5381815942_112bef03cf_m_d.jpg" style="width:25%"></p> <div> \begin{equation} \tau_\theta (x) = \begin{cases} 0 &\text{if } 0\leq x\leq \theta \\ x-\theta &\text{if }x > \theta \end{cases} \end{equation} </div> Other thresholding functions are of course possible, and the reader is encouraged to come up with different examples, and experiment with them. The wavelet module `PyWavelet` is <a href="http://blancosilva.github.io/course-material/2011/01/23/wavelets-in-sage.html">easily embedded in `sage`</a>, and allows us to perform very fast and elegant denoising codes. The following session shows an example: We load the image of Lena as an array of size <span>\\( 512 \times 512 \\)</span> containing values between `0` and `255`. We contaminate the image with white noise <span>\\( (\sigma=16.0) \\)</span> and perform denoising with this technique. Since <span>\\( 512 = 2^9, \\)</span> we require all nine levels of the Haar wavelet coefficients of the image. {% highlight python linenos %} from numpy import * import scipy import pywt image = scipy.misc.lena().astype(float32) noiseSigma = 16.0 image += random.normal(0, noiseSigma, size=image.shape) wavelet = pywt.Wavelet('haar') levels = Integer( floor( log2(image.shape[0]) ) ) WaveletCoeffs = pywt.wavedec2( image, wavelet, level=levels) {% endhighlight %} The object `WaveletCoeffs` is a tuple with ten entries: the first one is the approximation at the highest level: 9; the second entry is a 3-tuple containing the three different details (horizontal, vertical and diagonal) at the same level. Each consecutive entry is a 3-tuple containing the three different details at lower levels <span>\\( (n=8,7,6,5,4,3,2,1) \\)</span> The module `pywt` has several threshold functions implemented. Let us use the soft thresholding indicated above, with a made-up threshold <span>\\( \theta = \sigma \sqrt{2 \log_2(\texttt{image.size})}. \\)</span> In order to apply this threshold to each single wavelet coefficient, we will make use of the powerful tools of functional programming from `sage`. We need: * A thresholding function. We use the ones provided by the `pywt` package: `pywt.thresholding.soft`, and in particular its lambda expression: {% highlight python %} lambda x: pywt.thresholding.soft(x, threshold) {% endhighlight %} * `Python`'s built-in function `map(func, seq1, seq2, ...)` * The tuple of objects over which we need to apply the thresholding: In this case, the set of wavelet coefficients `WaveletCoeffs` computed above. Once computed the new coefficients, we use `pywt.waverec2` to obtain the corresponding reconstruction: {% highlight python linenos %} threshold = noiseSigma*sqrt(2*log2(image.size)) NewWaveletCoeffs = map (lambda x: pywt.thresholding.soft(x,threshold), WaveletCoeffs) NewImage = pywt.waverec2( NewWaveletCoeffs, wavelet) {% endhighlight %} <table style="width:75%;border-width:0;margin-left:auto;margin-right:auto;"> <tbody> <tr> <td style="width:50%;border-width:0;"><img src="https://i0.wp.com/farm6.static.flickr.com/5164/5367475002_4275491e81_o_d.png" alt="" width="100%" /></td> <td style="width:50%;border-width:0;"><img src="https://i0.wp.com/farm6.static.flickr.com/5045/5382329870_e3ee536df5_o_d.png" alt="" width="100%" /></td> </tr> <tr> <td style="text-align:center;border-width:0;">original + noise</td> <td style="text-align:center;border-width:0;">denoised (`haar`)</td> </tr> </tbody> </table> Denoising is good, but the overall visual quality of the resulting image is very poor: there are many artifacts, due mainly to the blocky nature of the Haar wavelet. Also, the choice of threshold is artificial: it has a priori no relationship with the structure of the image. Let's put a temporary solution to this problem by using a smoother wavelet, while keeping the same threshold. To avoid excessive typing, we will wrap the code above into a neat function with variables being the image to be treated, the standard deviation of the noise added, and the name of the wavelet employed: {% highlight python linenos %} def denoise(data,wavelet,noiseSigma): levels = Integer(floor(log2(data.shape[0]))) WC = pywt.wavedec2(data,wavelet,level=levels) threshold=noiseSigma*sqrt(2*log2(data.size)) NWC = map(lambda x: pywt.thresholding.soft(x,threshold), WC) return pywt.waverec2( NWC, wavelet) {% endhighlight %} We can now perform the same operation with different wavelets.  The following script creates a `python` dictionary that assigns, to each wavelet, the corresponding denoised version of the corrupted Lena image. {% highlight python linenos %} Denoised={} for wlt in pywt.wavelist(): Denoised[wlt] = denoise( data=image, wavelet=wlt, noiseSigma=16.0) {% endhighlight %} The  four images below are the respective denoising by soft thresholding of wavelet coefficients on the same image with the same level of noise <span>\\( (\sigma = 16.0), \\)</span> for the symlet `sym15`, the Daubechies wavelet `db6`, the biorthogonal wavelet `bior2.8`, and the coiflet `coif2`. Note that, except in the case of the denoising by biorthogonal wavelet, all of the others present clear artifacts: <table style="width:75%;border-width:0;margin-left:auto;margin-right:auto;"> <tbody> <tr> <td style="width:50%;border-width:0;"><img src="https://i0.wp.com/farm6.static.flickr.com/5170/5381872501_e9296eb13c_o_d.png" alt="" width="100%" /></td> <td style="width:50%;border-width:0;"><img src="https://i0.wp.com/farm6.static.flickr.com/5047/5382434292_891d198cdd_o_d.png" alt="" width="100%" /></td> </tr> <tr> <td style="text-align:center;border-width:0;">denoised (`sym15`)</td> <td style="text-align:center;border-width:0;">denoised (`db6`)</td> </tr> <tr> <td style="width:50%;border-width:0;"><img src="https://i0.wp.com/farm6.static.flickr.com/5047/5382484863_5a054f4f3f_o_d.png" alt="" width="100%" /></td> <td style="width:50%;border-width:0;"><img src="https://i0.wp.com/farm6.static.flickr.com/5284/5382485013_0683a07128_o_d.png" alt="" width="100%" /></td> </tr> <tr> <td style="text-align:center;border-width:0;">denoised (`bior2.8`)</td> <td style="text-align:center;border-width:0;">denoised (`coif2`)</td> </tr> </tbody> </table>
PHP
UTF-8
5,381
3.3125
3
[ "MIT" ]
permissive
<?php $input = file('input.txt', FILE_IGNORE_NEW_LINES); foreach ($input as $i => $row) { $input[$i] = str_split($row); } // Part 1 $changes = null; while ($changes !== 0) { $changes = 0; $seatsOccupied = 0; $resultingInput = $input; foreach ($input as $y => $row) { foreach ($row as $x => $space) { if ($space === '.') { continue; } $occupiedSeatsAdjacent = substr_count(implode('', [ $input[$y-1][$x-1] ?? '', $input[$y-1][$x] ?? '', $input[$y-1][$x+1] ?? '', $input[$y][$x-1] ?? '', $input[$y][$x+1] ?? '', $input[$y+1][$x-1] ?? '', $input[$y+1][$x] ?? '', $input[$y+1][$x+1] ?? '', ]), '#'); if ($space === 'L' && $occupiedSeatsAdjacent === 0) { // If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied. $resultingInput[$y][$x] = '#'; $changes++; } elseif ($space === '#' && $occupiedSeatsAdjacent >= 4) { // If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty. $resultingInput[$y][$x] = 'L'; $changes++; } if ($resultingInput[$y][$x] === '#') { $seatsOccupied++; } } } $input = $resultingInput; } echo "Part 1: $seatsOccupied\n"; // Part 2 $input = file('input.txt', FILE_IGNORE_NEW_LINES); foreach ($input as $i => $row) { $input[$i] = str_split($row); } $iterations = 0; $changes = null; while ($changes !== 0 && $iterations < 5000) { $iterations++; $changes = 0; $seatsOccupied = 0; $resultingInput = $input; foreach ($input as $y => $row) { foreach ($row as $x => $space) { if ($space === '.') { continue; } $occupiedSeatsAdjacent = occupiedAdjacentSeats($input, $x, $y); if ($space === 'L' && $occupiedSeatsAdjacent === 0) { // If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied. $resultingInput[$y][$x] = '#'; $changes++; } elseif ($space === '#' && $occupiedSeatsAdjacent >= 5) { // If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty. // Part 2 changes this: it now takes five or more visible occupied seats for an occupied seat to become empty (rather than four or more from the previous rules) $resultingInput[$y][$x] = 'L'; $changes++; } if ($resultingInput[$y][$x] === '#') { $seatsOccupied++; } } } $input = $resultingInput; } echo "Part 2: $seatsOccupied\n"; function occupiedAdjacentSeats(array $input, int $startX, int $startY): int { $xLength = count(end($input)) - 1; $yLength = count($input) - 1; $count = 0; // Up, Left $x = $startX; $y = $startY; while ($x >= 0 && $y >= 0) { $y--; $x--; if (($input[$y][$x] ?? '') === 'L') { break; } elseif (($input[$y][$x] ?? '') === '#') { $count++; break; } } // Up $x = $startX; $y = $startY; while ($y >= 0) { $y--; if (($input[$y][$x] ?? '') === 'L') { break; } elseif (($input[$y][$x] ?? '') === '#') { $count++; break; } } // Up, Right $x = $startX; $y = $startY; while ($x <= $xLength && $y >= 0) { $y--; $x++; if (($input[$y][$x] ?? '') === 'L') { break; } elseif (($input[$y][$x] ?? '') === '#') { $count++; break; } } // Left $x = $startX; $y = $startY; while ($x >= 0) { $x--; if (($input[$y][$x] ?? '') === 'L') { break; } elseif (($input[$y][$x] ?? '') === '#') { $count++; break; } } // Right $x = $startX; $y = $startY; while ($x <= $xLength) { $x++; if (($input[$y][$x] ?? '') === 'L') { break; } elseif (($input[$y][$x] ?? '') === '#') { $count++; break; } } // Down, Left $x = $startX; $y = $startY; while ($x >= 0 && $y <= $yLength) { $y++; $x--; if (($input[$y][$x] ?? '') === 'L') { break; } elseif (($input[$y][$x] ?? '') === '#') { $count++; break; } } // Down $x = $startX; $y = $startY; while ($y <= $yLength) { $y++; if (($input[$y][$x] ?? '') === 'L') { break; } elseif (($input[$y][$x] ?? '') === '#') { $count++; break; } } // Down, Right $x = $startX; $y = $startY; while ($x <= $xLength && $y <= $yLength) { $y++; $x++; if (($input[$y][$x] ?? '') === 'L') { break; } elseif (($input[$y][$x] ?? '') === '#') { $count++; break; } } return $count; }
Python
UTF-8
7,440
2.765625
3
[]
no_license
import os import json import pdb import sys import pandas as pd from gensim.models import TfidfModel import numpy as np from corextopic import corextopic as ct from corextopic import vis_topic as vt import matplotlib.pyplot as plt import itertools import shutil import os from shutil import copyfile print("-" * 80 + "\n") print("The topic modelling (standard, anchored and hiearchical) of the Anglo-Saxon Chronicle began") print("\n") # Add current path to python path sys.path.append(os.getcwd()) from Utils import gensim_utils import constants def chunks(l, n): """Returns every n elements of a list.""" l = [element for element in l if len(element) > 0] # For item i in a range that is a length of l, for i in range(0, len(l), n): # Create an index range for l of n items: yield l[i:i + n] # Set up the data directory data_directory = os.getcwd() + '/' + constants.OUTPUT_FOLDER + \ 'Anglo_Saxon_Chronicles/' # Read the document collection with open(data_directory + 'lemmatized_content_words_only_multi_words_document_collection.json') as json_file: document_collection = json.load(json_file) # Get every three sentences chunked_bows = [] for document in document_collection: for element in chunks(document, 3): chunked_bows.append(list(itertools.chain.from_iterable(element))) preselected_features = pd.read_csv(data_directory + 'Precomputed_data/historically_specific_vocab.csv')['0'].to_list() # Initialize a gensim dictionary gensim_dic = gensim_utils.initialize_gensim_dictionary([preselected_features]) # Create a TF-IDF based bag of word representation of each entry # Build a gensim corpus gensim_corpus = [gensim_dic.doc2bow(text) for text in chunked_bows] # Train a tf-idf model and reuse the gensim dic model = TfidfModel(gensim_corpus) # Build a tf-idf corpus corpus_tfidf = model[gensim_corpus] # Get the matrix representation (matrix_documents) of the TF-IDF corpus n_items = len(gensim_dic) ds = [] for doc in corpus_tfidf: d = [0] * n_items for index, value in doc: d[index] = value ds.append(d) matrix_documents = np.array(ds) # Remove entries that have many null values or too many values entries_for_remove = [] for element in enumerate(matrix_documents): if ((np.nonzero(element[1])[0].shape[0] < 5) or (np.nonzero(element[1])[0].shape[0] > 100)): entries_for_remove.append(element[0]) matrix_documents = np.delete(matrix_documents, entries_for_remove, 0) # Remove those entries that were removed from document term matrix for i in sorted(entries_for_remove, reverse=True): del chunked_bows[i] # Create a list from the features (features_list) so that they can be reused features_list = [element[1] for element in gensim_dic.iteritems()] # Transform the document term matrix into a binary matrix doc_word = np.where(matrix_documents > 0, 1, 0) print("\n") print ("The following topics were extracted from the Anglo-Saxon Chronicle") print("\n") # Run Corex topic modelling topic_model = ct.Corex(n_hidden=20, max_iter=200, verbose=False, seed=8) topic_model.fit(np.matrix(doc_word), words=features_list) # Print document topic matrix: topic_model.log_p_y_given_x # Print the key topics topics = topic_model.get_topics() topics_to_print = [] for n,topic in enumerate(topics): topic_words,_ = zip(*topic) topics_words_values = [] for element in topic: topics_words_values.append(element[0] + ' (' + str(np.round(element[1], decimals=3)) + ')') topics_to_print.append(','.join(topics_words_values)) print('{}: '.format(n) + ','.join(topic_words)) # Print top ten documents of each topic ''' top_docs = topic_model.get_top_docs(n_docs=10, sort_by='log_prob') selected_chunked_bows = [] for topic_n, topic_docs in enumerate(top_docs): docs, probs = zip(*topic_docs) docs = [str(element) for element in docs] topic_str = str(topic_n + 1) + ': ' + ','.join(docs) doc_bows = [] for doc in docs: doc_bows.append(' '.join(chunked_bows[int(doc)])) print(topic_str) ''' # Create a report on the topic modelling (folder named topic-model-report created automatically) vt.vis_rep(topic_model, column_label=features_list, prefix='topic-model-report') # Run a hiearchical topic modelling # Train a second layer to the topic model tm_layer2 = ct.Corex(n_hidden=3) tm_layer2.fit(topic_model.labels) # Train a third layer to the topic model tm_layer3 = ct.Corex(n_hidden=1) tm_layer3.fit(tm_layer2.labels) vt.vis_hierarchy([topic_model, tm_layer2, tm_layer3], column_label=features_list, max_edges=200, prefix='topic-model-hierarchical-report') # Train an anchored topic modelling print ("\n") print ("The following topics anchored to 'kill' were extracted from the Anglo-Saxon Chronicle") print ("\n") topic_model = ct.Corex(n_hidden=20, max_iter=200, verbose=False, seed=8) topic_model.fit(np.matrix(doc_word), words=features_list, anchors=['kill'], anchor_strength=5) # Render the results # Print the key topics topics = topic_model.get_topics() topics_to_print = [] for n,topic in enumerate(topics): topic_words,_ = zip(*topic) topics_words_values = [] for element in topic: topics_words_values.append(element[0] + ' (' + str(np.round(element[1], decimals=3)) + ')') topics_to_print.append(','.join(topics_words_values)) print('{}: '.format(n) + ','.join(topic_words)) # Print top ten documents of each topic ''' top_docs = topic_model.get_top_docs(n_docs=10, sort_by='log_prob') selected_chunked_bows = [] for topic_n, topic_docs in enumerate(top_docs): docs, probs = zip(*topic_docs) docs = [str(element) for element in docs] topic_str = str(topic_n + 1) + ': ' + ','.join(docs) doc_bows = [] for doc in docs: doc_bows.append(' '.join(chunked_bows[int(doc)])) print(topic_str) ''' vt.vis_rep(topic_model, column_label=features_list, prefix='topic-model-anchored-report') # Render a diagram about the topic model plt.figure(figsize=(10, 5)) plt.bar(range(topic_model.tcs.shape[0]), topic_model.tcs, color='#4e79a7', width=0.5) plt.xlabel('Topic', fontsize=16) plt.ylabel('Total Correlation (nats)', fontsize=16) plt.savefig(data_directory+'topics.png', bbox_inches='tight') # copy output to output data folder cwd = os.getcwd() # check if folder already exists if not os.path.isdir(data_directory+'topic-model-anchored-report'): shutil.move(cwd+'/topic-model-anchored-report', data_directory) shutil.move(cwd+'/topic-model-hierarchical-report', data_directory) shutil.move(cwd+'/topic-model-report', data_directory) else: shutil.rmtree(data_directory+'/topic-model-anchored-report') shutil.rmtree(data_directory+'/topic-model-report') shutil.rmtree(data_directory+'/topic-model-hierarchical-report') shutil.move(cwd+'/topic-model-anchored-report', data_directory) shutil.move(cwd+'/topic-model-hierarchical-report', data_directory) shutil.move(cwd+'/topic-model-report', data_directory) print ("Topic modelling finished, reports were copied to the following folders:") print ("\n") print (data_directory+'topic-model-anchored-report') print (data_directory+'topic-model-report') print (data_directory+'topic-model-hierarchical-report')
Java
UTF-8
2,198
2.921875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tarea_.modulo_7; public class procesos_calculadora { private double Valor_1; private double Valor_2; private String Operacion; private double Resultado; public double getValor_1() { return Valor_1; } public void setValor_1(double Valor_1) { this.Valor_1 = Valor_1; } public double getValor_2() { return Valor_2; } public void setValor_2(double Valor_2) { this.Valor_2 = Valor_2; } public String getOperacion() { return Operacion; } public void setOperacion(String Operacion) { this.Operacion = Operacion; } public double getResultado() { return Resultado; } public void setResultado(double Resultado) { this.Resultado = Resultado; } public String Resultado_operacion(){ String resultado = null; String operacion=getOperacion(); double Calculo; double valor_1= getValor_1(); double valor_2= getValor_2(); switch (operacion){ case "suma": Calculo=valor_1+valor_2; resultado=" "+valor_1+" + " +valor_2+" = "+Calculo; break; case "resta": Calculo=valor_1-valor_2; resultado=" "+valor_1+" - " +valor_2+" = "+Calculo; break; case "multiplicacion": Calculo=valor_1*valor_2; resultado=" "+valor_1+" * " +valor_2+" = "+Calculo; break; case "divicion": Calculo=valor_1/valor_2; resultado=" "+valor_1+" / " +valor_2+" = "+Calculo; break; default: resultado = "Ingrese la operacion"; } return resultado; } }
Markdown
UTF-8
3,732
3.046875
3
[]
no_license
# 利用`#undef`实现特定模块的调试输出 ## Preface 在平时的编程中肯定会用到打印功能来调试自己的程序,调试的时候将打印函数取消注释,在调试完成后将打印函数注释掉。不知大家是如何处理的,我以前可一直是这么干的。这样处理第一太繁琐,第二影响程序的美观性。后面想了一个用`#if ... #endif`语法来封装`printf`函数的做法: ```c #if DEBUG_MOUDEL print("debug moudel\n"); #endif ``` 需要调试特定模块的时候只需在该模块文件的开头添加`#define DEBUG_MOUDEL`即可。但这样给写程序添加了很大的负担。 对于`#undef`,在这里我们知道他的书面意思就够了,与`#define`相对,解除对后面宏的定义。 ## Instance ### `debug_out.h` 这是我们用于调试输出的核心文件,在需要调试的模块文件中要包含该文件,并在之前添加上`# define DEBUG_OUT`的宏定义便可开启该模块的调试。调试完成后只需将`#define DEBUG_OUT`的宏注释掉即可。 ```c #include <stdio.h> //用于调试的串行别名。 //用法:在给定的.cpp文件中定义DEBUG_OUT(或不定义)后,包括此标头 //用于特定模块(文件)的调试 #define NOOP //(void(0)) #undef DEBUG_PRINT #if DEBUG_OUT #define DEBUG_PRINT printf #else #define DEBUG_PRINT(...) NOOP #endif #undef DEBUG_OUT ``` ### `moudel1` `moudel1.h` ```c #ifndef __MOUDEL1_H #define __MOUDEL1_H #define DEBUG_OUT //调试MOUDEL1 #include "debug_out.h" void moudel1(void); #endif ``` `moudel1.c` ```c #include "moudel1.h" void moudel1(void) { DEBUG_PRINT("moudel1 debug...\n"); } ``` ### `moude21` `moudel2.h` ```c #ifndef __MOUDEL2_H #define __MOUDEL2_H //#define DEBUG_OUT //不调试MOUDEL2 #include "debug_out.h" void moudel1(void); #endif ``` `moudel2.c` ```c #include "moudel2.h" void moudel2(void) { DEBUG_PRINT("moudel2 debug...\n"); } ``` ### `main.c` ```c #include <stdio.h> #include "moudel1.h" #include "moudel2.h" int main(void) { printf("test debug out:\n"); moudel1(); moudel2(); return 0; } ``` ## 结果 ```bash C:\Users\username\Desktop\C_CPP\debug_test>gcc main.c moudel1.c moudel2.c -o main C:\Users\username\Desktop\C_CPP\debug_test>.\main.exe test debug out: moudel1 debug... ``` ----- **`Note:`** `#define DEBUT_OUT`只能定义在要调试的模块文件中才行,如果想在统一的文件中定义是否调试某个模块可以转一层定义,下面是一种思路: ```c #define DEBUG_OUT defined(DEBUG_MOUDEL1) ``` 在配置文件中定义`#define DEBUG_MOUDEL1`,只需在上面代码之前包含配置文件即可。 --- ## 分析 针对于`moudel1.c`文件将所有的预处理展开后如下: ```c /* moudel1.h start */ #ifndef __MOUDEL1_H #define __MOUDEL1_H #define DEBUG_OUT //调试MOUDEL1 /* debug_out.h start */ #include <stdio.h> //用于调试的串行别名。 //用法:在给定的.cpp文件中定义DEBUG_OUT(或不定义)后,包括此标头 //用于特定模块(文件)的调试 #define NOOP //(void(0)) #undef DEBUG_PRINT #if DEBUG_OUT #define DEBUG_PRINT printf #else #define DEBUG_PRINT(...) NOOP #endif #undef DEBUG_OUT /* debug_out end */ void moudel1(void); #endif /* moudel1.h end */ void moudel1(void) { DEBUG_PRINT("moudel1 debug...\n"); } ``` 首先定义了`DEBUG_OUT`自然条件编译在选择时是`#define DEBUG_PRINT printf`故该模块中的`DEBUG_PRINT`当做`printf`对待。后面又有一句`#udef DEBUG_OUT`解除对DEBUG_OUT的定义故对其他未定义`DEBUG_OUT`的模块,预处理中条件编译的选择是`#define DEBUG_PRINT(...) NOOP`,即`DEBUG_PRINT`是一个空函数。
Swift
UTF-8
2,969
2.90625
3
[]
no_license
// // AppDomain.swift // PhotoSlider // // Created by Ivan Quintana on 15/03/21. // import Foundation import ComposableArchitecture enum UIState: Hashable { case auth case home } struct AppState: Equatable { var uiState: UIState = .auth var authState: AuthState = .init() var sliderState: SliderState = .init() } enum AppAction: Equatable { case loginUser case registerUser case userAuthenticated case validateSession case authAction(AuthAction) case sliderAction(SliderAction) } struct AppEnvironment { var firebaseManager: FirebaseManager var mainQueue: AnySchedulerOf<DispatchQueue> } extension AppEnvironment { static let `default` = Self.init( firebaseManager: FirebaseManager(), mainQueue: DispatchQueue.main.eraseToAnyScheduler() ) } typealias AppReducer = Reducer<AppState, AppAction, AppEnvironment> let appReducer = AppReducer.combine( authReducer.pullback( state: \.authState, action: /AppAction.authAction, environment: { env -> AuthEnvironment in .init( firebaseManager: env.firebaseManager, mainQueue: env.mainQueue ) } ), sliderReducer.pullback( state: \.sliderState, action: /AppAction.sliderAction, environment: { env -> SliderEnvironmnet in .init( firebaseManager: env.firebaseManager, mainQueue: env.mainQueue ) } ), .init { state, action, environment in switch action { case .loginUser: return .none case .registerUser: return .none case .userAuthenticated: state.uiState = .home return .none case .validateSession: if environment.firebaseManager.isUserLoggedIn { state.authState.loginUser.email = environment.firebaseManager.getCurrentUser()?.email ?? "" return Effect(value: .userAuthenticated) } return .none case let .authAction(action): switch action { case let .authResponse(.success(.loginSuccess(data))): state.sliderState.currentUser = data.user state.uiState = .home case let .authResponse(.success(.userCreated(data))): state.sliderState.currentUser = data.user state.uiState = .home case let .authResponse(.failure(error)): print("TODO: handle error: ", error) default: break } return .none case let .sliderAction(action): switch action { case .logOutResult(.success(_)): state.uiState = .auth default: break } return .none } } )
PHP
UTF-8
2,680
2.5625
3
[]
no_license
<html> <body> <center><h1> Agregar pasos para contratacion</h1></center> <form enctype="multipart/form-data" id = "formaAgregar" method="POST" > <button onclick="agregarPaso(); return false">Agregar Paso</button><br> <button type="button" onclick="sendData()">Agregar</button><br> <!--<input hidden name = "num" type = "number" id = "num"> --> <label>Descripcion del paso <input type="text" name="desc1"></label> <?php include '../../config.php'; $con=mysqli_connect($host,$user,$pass,$name); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query = "SELECT * FROM permisos ORDER BY nombre"; $result = mysqli_query($con,$query); echo "Nivel autorizacion: <select id = \"permiso\" name=\"idPermiso1\">\n"; while($row = mysqli_fetch_array($result)){ echo "<option value=".$row["id"].">".$row["nombre"]."</option>\n"; } echo "</select><br>\n"; ?> </form> </body> </html> <script> var numDePasos = 1; function agregarPaso() { numDePasos++; var lbl1 = document.createElement("LABEL"); var caption = document.createTextNode("Descripcion del paso "); lbl1.appendChild(caption); var inpt = document.createElement("INPUT"); inpt.setAttribute("name", "desc" + numDePasos) console.log(inpt); var lbl2 = document.createElement("LABEL"); var caption = document.createTextNode(" Nivel Autorizacion: "); lbl2.appendChild(caption); var permisoCopia = document.getElementById("permiso").cloneNode(true); permisoCopia.setAttribute("name", "idPermiso" + numDePasos); //document.getElementById("num").value = numDePasos; var enter = document.createElement("BR"); var forma = document.getElementById("formaAgregar"); forma.appendChild(lbl1); forma.appendChild(inpt); forma.appendChild(lbl2); forma.appendChild(permisoCopia); forma.appendChild(enter); } function sendData(data) { console.log("Enviando formulario") var formElement = document.getElementById("formaAgregar"); formData = new FormData(formElement); formData.append("num", numDePasos); var request = new XMLHttpRequest(); request.open("POST", "pasos_contratacionDB.php"); request.send(formData); } </script>
Python
UTF-8
315
2.921875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sun Aug 8 22:18:46 2021 @author: 009671631 """ import psutil def format_memory(info): return round(info/(1024*1024*1024), 2) disco = psutil.disk_usage('.') total = format_memory(disco.free) print(f"Disco(armazenamento disponível): {total} GB")
Java
UTF-8
299
2.875
3
[]
no_license
package Beverge; /** * 具体的浓缩咖啡 * Created by jimersylee on 17-8-19. */ public class Espresso extends Beverage { public Espresso() { description="Espresso";//description变量继承自Beverage } @Override public double cost() { return 1.99; } }
Python
UTF-8
2,518
2.609375
3
[]
permissive
from contextlib import contextmanager from threading import local from django import urls from django.http import HttpRequest # Get a pointer to Django's reverse and resolve because we're going to hijack # them after we define our own. # As we're using a url prefixer to automatically add the locale and the app to # URLs, we're not compatible with Django's default reverse and resolve, and # thus need to monkeypatch them. django_reverse = urls.reverse django_resolve = urls.resolve # Thread-local storage for URL prefixes. Access with {get,set}_url_prefix. _local = local() def set_url_prefix(prefix): """Set ``prefix`` for the current thread.""" _local.prefix = prefix def get_url_prefix(): """Get the prefix for the current thread, or None.""" return getattr(_local, 'prefix', None) def clean_url_prefixes(): """Purge prefix cache.""" if hasattr(_local, 'prefix'): delattr(_local, 'prefix') def reverse( viewname, urlconf=None, args=None, kwargs=None, current_app=None, add_prefix=True ): """Wraps django's reverse to prepend the correct locale and app.""" prefixer = get_url_prefix() url = django_reverse(viewname, urlconf, args, kwargs, current_app) if prefixer and add_prefix: return prefixer.fix(url) else: return url # Replace Django's reverse with our own. urls.reverse = reverse def resolve(path, urlconf=None): """Wraps django's resolve to remove the locale and app from the path.""" from olympia.amo.urlresolvers import Prefixer _lang, application, path_fragment = Prefixer.split_path(path) return django_resolve(f'/{path_fragment}', urlconf) # Replace Django's resolve with our own. urls.resolve = resolve def resolve_with_trailing_slash(path): """Try resolving a path by appending a trailing slash if necessary.""" try: return resolve(path) except urls.Resolver404: if not path.endswith('/'): return resolve(f'{path}/') raise @contextmanager def override_url_prefix(*, app_name=None, locale=None): from olympia.amo.urlresolvers import Prefixer old_prefixer = get_url_prefix() request = HttpRequest() request.META['SCRIPT_NAME'] = '' new_prefixer = Prefixer(request) new_prefixer.app = app_name or (old_prefixer or new_prefixer).app new_prefixer.locale = locale or (old_prefixer or new_prefixer).locale try: set_url_prefix(new_prefixer) yield finally: set_url_prefix(old_prefixer)
C++
UTF-8
2,599
2.515625
3
[ "MIT" ]
permissive
// Copyright 2021, James S. Wang, All rights reserved. #pragma once #include "Blueprint/UserWidget.h" #include "CoreMinimal.h" #include "MainMenuInterface.h" #include "LSWidget.generated.h" class IMainMenuInterface; /** * @brief The base widget class for all UI widgets. * It contains lifecycle methods like Create and Destroy that's common among * all widgets. It also holds onto a IMainMenuInterface for its children to use * if they need functionality specific to the game. */ UCLASS() class TD_API ULSWidget : public UUserWidget { GENERATED_BODY() public: /** * @brief Does all of the setup required for this widget to be used. * By default, this will add the widget to the viewport and make it * focusable. Then it will set the input mode to UIOnly and show the mouse * cursor. */ UFUNCTION(BlueprintCallable, Category = "Initialization") virtual void Create(); /** * @brief Destroys the widget and cleans it up. * By default, this will remove the widget from the viewport and make it no * longer focusable. Then it will set the input mode to GameOnly and hide * the mouse cursor. */ UFUNCTION(BlueprintCallable, Category = "Lifecycle") virtual void Destroy(); /** * @brief Usually called when loading a new level (and so the old one is * getting destroyed). By default, this will Destroy() this widget before * calling the parent implementation. * @param InLevel The level that the game is currently in * @param InWorld The world the game is currently in */ virtual void OnLevelRemovedFromWorld( ULevel* InLevel, UWorld* InWorld) override; /** * @brief Sets the MainMenuInterface so that we can call those functions * when necessary. * @param Interface The implementer of the IMainMenuInterface */ void SetMainMenuInterface(TScriptInterface<IMainMenuInterface> Interface) { MainMenuInterface = Interface; }; private: /** * @brief The implementer of IMainMenuInterface that we can call methods * from. Using TScriptInterface allows us to use this in blueprints. */ UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "IMainMenuInterface", meta = (AllowPrivateAccess = "true")) TScriptInterface<IMainMenuInterface> MainMenuInterface = nullptr; /** * @brief Gets the local player's PlayerController for setting things like * mouse cursor visibility. * @return The local player's PlayerController */ APlayerController* GetPlayerController() const; };
Markdown
UTF-8
1,080
2.734375
3
[]
no_license
# D3-Biodiversity-Dashboard An interactive dashboard to explore the Belly Button Biodiversity dataset, which catalogs the microbes that colonize human navels. The dataset reveals that a small handful of microbial species (also called operational taxonomic units, or OTUs, in the study) were present in more than 70% of people, while the rest were relatively rare. --- [Visit my site HERE!](https://gitgranthub.github.io/D3-Biodiversity-Dashboard/) * D3.js * Plot.ly * Javascript * HTML ---- * I've included a brief description of the **study** below the jumbotron heading. The background image in the jumbotron is ©CDC and for public use. I've used custom css throughout the page. ![top_page.png](docs/static/images/top_page.png) ---- ---- * Data for each subject is easily selected using the dropdown menu. I modified the gauge to be what I thought was very readable. ![middle_page.png](docs/static/images/middle_page.png) ---- ---- * The Plot.ly bubble chart also update based on the subject selected. ![bottom_page.png](docs/static/images/bottom_page.png) ---- ----
Python
UTF-8
754
3.921875
4
[]
no_license
# Python Data Structure Dictionaries # Unlike sequences (Lists, Strings etc.), which are indexed by a range of numbers, # dictionaries are indexed by keys, which can be any immutable type; # strings and numbers can always be keys. tel = {'jack': 4098, 'sape': 4139} tel['guido'] = 4127 tel # Displays {'jack': 4098, 'sape': 4139, 'guido': 4127} tel['jack'] # Displays 4098 del tel['sape'] tel['irv'] = 4127 tel # Displays {'jack': 4098, 'guido': 4127, 'irv': 4127} list(tel) # Displays ['jack', 'guido', 'irv'] sorted(tel) # Displays ['guido', 'irv', 'jack'] 'guido' in tel # Displays True 'jack' not in tel # Displays False
Java
UTF-8
1,538
2.359375
2
[ "Apache-2.0" ]
permissive
/** * File generated by the ThingML IDE * /!\Do not edit this file/!\ * In case of a bug in the generated code, * please submit an issue on our GitHub **/ package org.thingml.generated.messages; import no.sintef.jasm.*; import no.sintef.jasm.ext.*; import java.util.*; import java.nio.*; public class DrawRectvar3yheightMessageType extends EventType { public DrawRectvar3yheightMessageType(short code) {super("drawRectvar3yheight", code); } public DrawRectvar3yheightMessageType() { super("drawRectvar3yheight", (short) 45); } public Event instantiate(final byte var57, final int y, final int height, final byte var3) { return new DrawRectvar3yheightMessage(this, var57, y, height, var3); } public Event instantiate(Map<String, Object> params) {return instantiate((Byte) params.get("var57"), (Integer) params.get("y"), (Integer) params.get("height"), (Byte) params.get("var3")); } public class DrawRectvar3yheightMessage extends Event implements java.io.Serializable { public final byte var57; public final int y; public final int height; public final byte var3; public String toString(){ return "drawRectvar3yheight (" + "var57: " + var57 + ", " + "y: " + y + ", " + "height: " + height + ", " + "var3: " + var3 + ")"; } protected DrawRectvar3yheightMessage(EventType type, final byte var57, final int y, final int height, final byte var3) { super(type); this.var57 = var57; this.y = y; this.height = height; this.var3 = var3; } public Event clone() { return instantiate(this.var57, this.y, this.height, this.var3); }} }
Python
UTF-8
1,192
3.0625
3
[]
no_license
import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import tensorflow as tf import tensorflow.keras.backend as K x = np.array([1,2,3,4,5,6,7,8]).astype('float32') y = np.array([1,2,3,4,5,6,7,8]).astype('float32') def custom_mse(y_true,y_pred): return tf.math.reduce_mean(tf.square(y_true-y_pred)) def quantile_loss(y_true,y_pred): qs = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] q = tf.constant(np.array([qs]),dtype=tf.float32) e = y_true-y_pred v = tf.maximum(q*e,(q-1)*e) return K.mean(v) def quantile_loss_dacon(q, y_true, y_pred): err = (y_true - y_pred) return K.mean(K.maximum(q*err, (q-1)*err), axis=-1) quantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] for q in quantiles: model = Sequential() model.add(Dense(10,input_shape=(1,))) model.add(Dense(10)) model.add(Dense(1)) model.compile(loss = lambda y_true, y_pred: quantile_loss_dacon(q, y_true, y_pred), optimizer='adam', metrics=[lambda y, pred: quantile_loss(q, y, pred)]) model.fit(x,y,batch_size=1,epochs=50) loss = model.evaluate(x,y) print(loss) ''' 0.011618913151323795 0.008749164640903473 '''
C++
UTF-8
648
2.8125
3
[]
no_license
#include <list> #include <string> #include <pthread.h> #include <stdio.h> #include <unistd.h> #include <assert.h> std::list<std::string> g_list; void* push_thread(void*) { int count = 100000; while (count--) { g_list.push_back("husdhaisdhu"); ::usleep(20); } } int main() { pthread_t tid; pthread_create(&tid, 0, &push_thread, 0); int count = 100000; while (count--) { g_list.push_back("shduygdfhguysgyq"); ::usleep(18); } pthread_join(tid, 0); printf("%lu\n", g_list.size()); //for (std::list<std::string>::iterator it = g_list.begin(); it != g_list.end(); it++) //{ // //printf("%s\n", (*it).c_str()); //} return 0; }
JavaScript
UTF-8
1,181
2.796875
3
[]
no_license
var search = location.search.slice(8); var xhr = $.get("https://api.giphy.com/v1/gifs/search?q=" + search +"&api_key=53WYlS1SZqJ1NOEAgZeQlD6sddrUA013&limit=25", function(data){ var images = document.querySelectorAll("img"); for(var i = 0; i < images.length; i++){ images[i].src=data["data"][i]["images"]["fixed_height"]["url"]; } $(".myButton").css("opacity", "1"); $(".myButton").css("display", "inline-block"); }); var needMore = true; $(".myButton").click(function(){ if(needMore){ $(".more").slideDown(1000, function(){ $(".more").css("opacity", "1"); needMore = false; document.querySelector(".myButton").textContent = "Load Less"; }); } else { $(".more").slideUp(1000, function(){ $(".more").css("opacity", "0"); needMore = true; document.querySelector(".myButton").textContent = "Load More"; }); } }); $("form").click(function(){ var search = $("input[type='text']").val(); var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=53WYlS1SZqJ1NOEAgZeQlD6sddrUA013&limit=25", function(data){ var images = document.querySelectorAll("img"); for(var i = 0; i < images.length; i++){ images[i].src=data["data"][i]["images"]["fixed_height"]["url"]; } }); });
C#
UTF-8
991
2.78125
3
[ "CC-BY-4.0", "MIT" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace VbPowerPacksDrawLine2CS { public partial class DrawLine2 : Form { public DrawLine2() { InitializeComponent(); } private void DrawLine2_Load(object sender, EventArgs e) { // <Snippet1> Microsoft.VisualBasic.PowerPacks.ShapeContainer canvas = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); Microsoft.VisualBasic.PowerPacks.LineShape line1 = new Microsoft.VisualBasic.PowerPacks.LineShape(0, 0, 1000, 1000); // Set the form as the parent of the ShapeContainer. canvas.Parent = this; // Set the ShapeContainer as the parent of the LineShape. line1.Parent = canvas; // </Snippet1> } } }
Python
UTF-8
559
3.859375
4
[]
no_license
import sys def insertion_sort(array): for index in range(1, len(array)): while 0 < index and array[index] < array[index -1]: array[index], array[index-1] = array[index-1], array[index] index -= 1 return array if __name__ == "__main__": if sys.version_info.major < 3: input_function = raw_input else: input_function = input user_input = input_function("Enter numbers seperated by comma : ") unsortedlist = [int(i) for i in user_input.split(',')] print insertion_sort(unsortedlist)
C
UTF-8
12,395
2.53125
3
[ "MIT" ]
permissive
#ifdef __cplusplus extern "C" { #endif //TODO: finish the ports for BSD and windows based platforms #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include "permTables.h" #include "desEncrypt.h" #if defined(_WIN32) || defined(_WIN64) #elif defined (__linux__) #include <byteswap.h> #elif defined (__MACH__) || defined (__unix__) #endif void dumphex(char *data, int size) { int i; int row = 8; for(i = 0; i < size; i++) { printf("%02x", (uint8_t) data[i]); if (i % row == 0 && i != 0) printf("\n"); } printf("\n"); } CryptAPI initialize(DESCtx *ctx) { size_t numBlocks, padding = 0,i = 0; memset(ctx->subkeys, 0, sizeof(uint64_t) * NUM_SUB_KEYS); if (ctx->inSize == 0) { printf("Specify a message size within the context.\n"); return CRYPT_INPUT_ERROR; } numBlocks = (ctx->inSize / 8); numBlocks += 1; padding = (8 - (ctx->inSize % 8)); ctx->blocks = numBlocks; ctx->outSize = 8 * numBlocks; ctx->out = (char *) calloc(1, ctx->outSize); if (ctx->pad == PKCS5Pad) { for (i = 0; i < padding; i++) { ctx->out[ctx->inSize + i] = padding; } } CRYPT_MEMCPY(ctx->out, ctx->in, ctx->inSize); generateKeySchedule(*((uint64_t *) ctx->key), ctx->subkeys); return CRYPT_SUCCESS; } CryptAPI finalize(DESCtx *ctx, CtxType type) { bool cryptType = false; CryptAPI ret; if (ctx->op == UNK_Mode) { printf("Specify a mode of operation.\n"); return CRYPT_INPUT_ERROR; } if (type == DecryptT) cryptType = true; if (ctx->op == ECB_Mode) ret = encryptBlocksECB(ctx, cryptType); if (ctx->op == CBC_Mode) ret = encryptBlocksCBC(ctx, cryptType); if (ctx->op == CFB_Mode) ret = encryptBlocksCFB(ctx, cryptType); if (ctx->op == OFB_Mode) ret = encryptBlocksOFB(ctx, cryptType); return ret; } CryptAPI encryptBlocksECB(DESCtx *ctx, bool cryptType) { int i = 0; uint64_t *dataPtr = NULL; dataPtr = (uint64_t *) (ctx->out); for (i = 0; i < ctx->blocks; i++) { #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \ defined(__LITTLE_ENDIAN__) || \ defined(__ARMEL__) || \ defined(__THUMBEL__) || \ defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) #if defined(_WIN32) || defined(_WIN64) *dataPtr = _byteswap_uint64(*dataPtr); #elif defined (__linux__) *dataPtr = bswap_64(*dataPtr); #elif defined (__MACH__) || defined (__unix__) *dataPtr = __builtin_bswap64(*dataPtr); #endif #endif CryptDES(dataPtr, ctx->subkeys, cryptType); #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \ defined(__LITTLE_ENDIAN__) || \ defined(__ARMEL__) || \ defined(__THUMBEL__) || \ defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) #if defined(_WIN32) || defined(_WIN64) *dataPtr = _byteswap_uint64(*dataPtr); #elif defined (__linux__) *dataPtr = bswap_64(*dataPtr); #elif defined (__MACH__) || defined (__unix__) *dataPtr = __builtin_bswap64(*dataPtr); #endif #endif dataPtr++; } return CRYPT_SUCCESS; } CryptAPI encryptBlocksCBC(DESCtx *ctx, bool cryptType) { int i = 0; uint64_t *dataPtr = NULL; uint64_t *chainData = NULL; *(uint64_t *) ctx->iv = 0; dataPtr = (uint64_t *) (ctx->out); for (i = 0; i < ctx->blocks; i++) { #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \ defined(__LITTLE_ENDIAN__) || \ defined(__ARMEL__) || \ defined(__THUMBEL__) || \ defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) #if defined(_WIN32) || defined(_WIN64) *dataPtr = _byteswap_uint64(*dataPtr); #elif defined (__linux__) *dataPtr = bswap_64(*dataPtr); #elif defined (__MACH__) || defined (__unix__) *dataPtr = __builtin_bswap64(*dataPtr); #endif #endif if (i == 0) chainData = (uint64_t *) ctx->iv; *dataPtr ^= *chainData; CryptDES(dataPtr, ctx->subkeys, cryptType); *chainData = *dataPtr; #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \ defined(__LITTLE_ENDIAN__) || \ defined(__ARMEL__) || \ defined(__THUMBEL__) || \ defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) #if defined(_WIN32) || defined(_WIN64) *dataPtr = _byteswap_uint64(*dataPtr); #elif defined (__linux__) *dataPtr = bswap_64(*dataPtr); #elif defined (__MACH__) || defined (__unix__) *dataPtr = __builtin_bswap64(*dataPtr); #endif #endif dataPtr++; } return CRYPT_SUCCESS; } CryptAPI encryptBlocksCFB(DESCtx *ctx, bool cryptType) { int i = 0; uint64_t *dataPtr = NULL; uint64_t *chainData = NULL; *(uint64_t *) ctx->iv = 0; dataPtr = (uint64_t *) (ctx->out); for (i = 0; i < ctx->blocks; i++) { #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \ defined(__LITTLE_ENDIAN__) || \ defined(__ARMEL__) || \ defined(__THUMBEL__) || \ defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) #if defined(_WIN32) || defined(_WIN64) *dataPtr = _byteswap_uint64(*dataPtr); #elif defined (__linux__) *dataPtr = bswap_64(*dataPtr); #elif defined (__MACH__) || defined (__unix__) *dataPtr = __builtin_bswap64(*dataPtr); #endif #endif if (i == 0) chainData = (uint64_t *) ctx->iv; CryptDES(chainData, ctx->subkeys, cryptType); *dataPtr ^= *chainData; *chainData = *dataPtr; #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \ defined(__LITTLE_ENDIAN__) || \ defined(__ARMEL__) || \ defined(__THUMBEL__) || \ defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) #if defined(_WIN32) || defined(_WIN64) *dataPtr = _byteswap_uint64(*dataPtr); #elif defined (__linux__) *dataPtr = bswap_64(*dataPtr); #elif defined (__MACH__) || defined (__unix__) *dataPtr = __builtin_bswap64(*dataPtr); #endif #endif dataPtr++; } return CRYPT_SUCCESS; } CryptAPI encryptBlocksOFB(DESCtx *ctx, bool cryptType) { int i = 0; uint64_t *dataPtr = NULL; uint64_t *chainData = NULL; *(uint64_t *) ctx->iv = 0; dataPtr = (uint64_t *) (ctx->out); for (i = 0; i < ctx->blocks; i++) { #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \ defined(__LITTLE_ENDIAN__) || \ defined(__ARMEL__) || \ defined(__THUMBEL__) || \ defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) #if defined(_WIN32) || defined(_WIN64) *dataPtr = _byteswap_uint64(*dataPtr); #elif defined (__linux__) *dataPtr = bswap_64(*dataPtr); #elif defined (__MACH__) || defined (__unix__) *dataPtr = __builtin_bswap64(*dataPtr); #endif #endif if (i == 0) chainData = (uint64_t *) ctx->iv; CryptDES(chainData, ctx->subkeys, cryptType); *dataPtr ^= *chainData; #if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \ defined(__LITTLE_ENDIAN__) || \ defined(__ARMEL__) || \ defined(__THUMBEL__) || \ defined(__AARCH64EL__) || \ defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__) #if defined(_WIN32) || defined(_WIN64) *dataPtr = _byteswap_uint64(*dataPtr); #elif defined (__linux__) *dataPtr = bswap_64(*dataPtr); #elif defined (__MACH__) || defined (__unix__) *dataPtr = __builtin_bswap64(*dataPtr); #endif #endif dataPtr++; } return CRYPT_SUCCESS; } void sanitize(DESCtx *ctx) { if (ctx->out != NULL) { memset(ctx->out, 0, ctx->outSize); free(ctx->out); } if (ctx == NULL) return; memset(ctx, 0, sizeof(DESCtx)); free(ctx); } void CryptDES(uint64_t *message,uint64_t *subkeys, bool decrypt) { int i,j,k; uint64_t _ip = 0; uint64_t finalPermutation = 0; uint64_t concatBlocks = 0; uint32_t r[NUM_BLOCKS + 1] = {0}; uint32_t l[NUM_BLOCKS + 1] = {0}; // encode with intial permutation for (i = 0; i < INT_SIZE64; i++) { _ip |= (uint64_t) (((*message >> (uint64_t) (MAX_SIZE - IP[i]) ) & 0x1) << (MAX_SIZE - 1 - i)); } // split permutated message into // right and left blocks r[0] |= _ip; l[0] = _ip >> ((INT_SIZE64) / 2); // rounds if (!decrypt) { for (i = 1; i <= NUM_BLOCKS; i++) { l[i] = r[i-1]; r[i] = l[i-1] ^ sBoxPermutation(r[i-1],subkeys[i-1]); } } else { for (i = 1; i <= NUM_BLOCKS; i++) { l[i] = r[i-1]; r[i] = l[i-1] ^ sBoxPermutation(r[i-1],subkeys[NUM_SUB_KEYS - i]); } } concatBlocks |= r[16]; concatBlocks = concatBlocks << ((INT_SIZE64) / 2); concatBlocks |= l[16]; // final inverse permutation for (j = 0; j < INT_SIZE64; j++) finalPermutation |= ((concatBlocks >> ((uint64_t) INT_SIZE64 - FP[j])) & 0x1) << (uint64_t)(INT_SIZE64 - 1 - j); *message = finalPermutation; } void generateKeySchedule(const uint64_t key, uint64_t *subKeys) { int i,j; uint64_t key_plus = 0; uint32_t _c[NUM_SUB_KEYS+1] = {0}; uint32_t _d[NUM_SUB_KEYS+1] = {0}; uint64_t _cd[NUM_SUB_KEYS] = {0}; uint32_t temp = 0; int shiftSchedule[NUM_SUB_KEYS] = {1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1}; //load key in big endian and perform PC-1 for (i = 0; i < INT_SIZE56; i++) { key_plus |= (uint64_t) (((key >> (uint64_t) (MAX_SIZE - PC1[i]) ) & 0x1) << (MAX_SIZE - 1 - i)); } // seperate permutation into c and d blocks _c[0] = (key_plus>>36); _d[0] = (key_plus>>8); for (i = 1; i < NUM_SUB_KEYS + 1; i++) { temp = _d[i-1]; for (j = 1; j <= shiftSchedule[i-1]; j++) { _d[i] = (temp << 1) | (1 & (temp >> 27)); temp = _d[i]; } temp = _c[i-1]; for (j = 1; j <= shiftSchedule[i-1]; j++) { _c[i] = (temp << 1) | (1 & (temp >> 27)); temp = _c[i]; } // clear high bits _c[i] = (_c[i] << 4) >> 4; _d[i] = (_d[i] << 4) >> 4; } // concatenate blocks for (i = 0; i < NUM_SUB_KEYS; i++) { _cd[i] |= _c[i+1]; _cd[i] = (_cd[i] << 28); _cd[i] |= _d[i+1]; } // generate key schedule for (i = 0; i < NUM_SUB_KEYS; i++) { for (j = 0; j < (INT_SIZE48); j++) subKeys[i] |= (_cd[i] >> ((INT_SIZE56) - PC2[j]) & 0x1) << ((INT_SIZE48) - j - 1); } } uint32_t sBoxPermutation (const uint32_t block, uint64_t key) { uint64_t _e = 0; uint32_t pOut = 0; uint32_t sLookup; int j, index, count = 0, sBoxCount = 0; uint8_t sCmpn, row = 0, column = 0; // expand right block (E) for (j = 0; j < INT_SIZE48; j++) _e |= (((uint64_t) (block >> ((INT_SIZE32) - E[j])) & 0x1) << ((INT_SIZE48) - j - 1)); // sBox Lookup table count = INT_SIZE48; sBoxCount = 1; sLookup = 0; while (count != 0) { count -= 6; // extract 6 bits at a time from output of e ^ K sCmpn = (((_e ^ key) >> (count)) << 2) >> 2; row = (((sCmpn >> 5) & 1) << 1) | (sCmpn & 1); column = (sCmpn >> 1) & 0xf; index = (NUM_BLOCKS*row + column); sLookup |= SBOXMAP[sBoxCount - 1][index]; if (sBoxCount != 8) sLookup <<= 4; sBoxCount++; } // sBox Permutation for (j = 0; j < INT_SIZE32; j++) pOut |= ((sLookup >> (uint32_t) ((INT_SIZE32) - P[j])) & 0x1) << (uint32_t)((INT_SIZE32) - 1 -j); return pOut; } #ifdef __cplusplus } #endif
Python
UTF-8
2,879
2.59375
3
[ "LicenseRef-scancode-warranty-disclaimer", "Unlicense" ]
permissive
#!/usr/bin/env python #-*- coding: utf-8 -*- # from __future__ import unicode_literals, division, absolute_import, print_function import sys from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, QLabel, QApplication, QHBoxLayout, QVBoxLayout, QCheckBox) from PyQt5.QtCore import Qt class askSetting(QWidget): def __init__(self, items, app = None, parent = None ): super(askSetting, self).__init__(parent) self.app = app self.items = items layout = QVBoxLayout() self.buttons = {} self.lineedits = {} for key in items.keys(): if isinstance(items[key], bool): self.buttons[key] = QCheckBox(key) self.buttons[key].setChecked(items[key]) self.buttons[key].setFocusPolicy(Qt.StrongFocus) layout.addWidget(self.buttons[key]) else: # I Default it is string layoutX = QHBoxLayout() layoutX.addWidget(QLabel(key)) self.lineedits[key] = QLineEdit() self.lineedits[key].setText(items[key]) #enable ime input self.lineedits[key].inputMethodQuery(Qt.ImEnabled) layoutX.addWidget(self.lineedits[key]) layout.addLayout(layoutX) self.btn = QPushButton('OK', self) self.btn.clicked.connect(lambda:(self.bye(items))) self.btn.setFocusPolicy(Qt.StrongFocus) layout.addWidget(self.btn) self.setLayout(layout) self.setWindowTitle(' Setting ') def bye(self, items): for key in self.lineedits.keys(): self.items[key] = self.lineedits[key].text() for key in self.buttons.keys(): self.items[key] = self.buttons[key].isChecked() self.close() self.app.exit(1) # def btnstate(self,key): # self.items[key] = self.buttons[key].isChecked() def run(bk): if sys.platform == "darwin": print("Don't use bundle python or it may not work") items = {"TextBox1": "", "CheckBox1": True, "CheckBox2": False, "TextBox2": "2"} app = QApplication(sys.argv) ask = askSetting(items=items, app=app) ask.show() rtnCode = app.exec_() #If press OK button rtnCode should be 1 if rtnCode != 1 : print('User abort by closing Setting dialog') return -1 print(items) #selected file in file list abc = bk.selected_iter() if abc is None: print("None") else: print("Found Selected %s" % (abc) ) return 0 def main(): print("I reached main when I should not have\n") return -1 if __name__ == "__main__": sys.exit(main())
Markdown
UTF-8
3,818
3.421875
3
[]
no_license
# Coherent Subtyping with Typing This works extends Linus' work "Subtyping with Typing" with disjointness. The syntax for abstractions and products are extended with a disjoint constraint. The environments now associates a variable to its respective type and constraint. ## Typed Subtyping Typed subtyping contains typing, well-formedness and subtyping unified in one judgement. Here follows a few informal explanations of some rules (the ones different from original): **App** An application (e1 A) is a subtype of application (e2 A) when e1 <: e2 under some pi-type. Notice the well-formed checks for type A and the disjointness constraint in the pi-type. **Pi** The rule is similar to the original typed subtyping. It is covariant on the bodies and contravariant on the constraints. **Merge** This rule now ensures the merge operator is only applied at the "term-level". ## Typed Disjointness The rules for disjointness are separated into two different judgements, although they could easily be merged together. Typed disjointness deals with two expressions composed by the same construct, whereas non-structural disjointness deals with different constructs. In comparison to previous work, the disjointness relation now includes the type/universe of both expressions. Next follows a few informal explanations of some rules. Firstly, the structural rules. **Lam1** Straightforward definition that respects the typed subtyping judgement. **Pi** Two abstractions are disjoint if their bodies are disjoint under a new environment. Note how we are assuming that the type/universe of the variable does not play a role in typing/disjointness... **App** The tricky rule. We could allow AppAlternative as the first naive version, but that rule will not cover all cases which are disjoint. For example, there might be two applications that do not have the same arguments, but live in the same type/universe. Consider, for example, the (incomplete) disjointness derivation for the following types: --------------------------------- TDBaseType x * T : STAR |- Char * Int : STAR ----------------------------------------------------------------------- TDLam1 (\x * T : STAR . Char) * (\x * T : STAR . Int) : pi x * T : STAR . STAR ... ------------------------------------------------------------------------------------ TDApp (\x * T : STAR . Char) Char : STAR * (\x * T : STAR . Int) Int : STAR This derivation is possible with the App rule, but not with AppAlternative. The syntactic restriction (C[x -> A] = C[x -> B]) is used to ensure the types/universes of the terms are consistent (and perhaps could be weakened too?). Also, note on how might need to type e1 and e2 to figure out their type/universe, which should be input to this algorithmic system. The rest of the rules in this judgement are quite straightforward and similar to Fi. Next, the non-structural rules. Again, these rules have to ensure the expressions live in the same type/universe. The "tricky" part is again the application, which might live in any type. **StarApp** Applications living in STAR are disjoint with STAR itself. **AppLam** Applications and abstractions living in the same pi-type are always disjoint. **AppPi** Applications living in STAR and pi types are always disjoint. **AppMerge** Applications living in intersection types are always disjoint with merges. The other rules follow the same structure as defined in Fi. Observation: rules And1, And2, Top, TopSym are also non-structural. # Building the document To build the pdf, please type `make subanddis.pdf`. Make sure you have ott and LaTeX installed :) # Disclaimer This work was heavily based on Linus' work "Subtyping with Typing". Infrastructure taken from his "subtype" repository, forked here for convenience. Thanks Linus!
JavaScript
UTF-8
5,276
2.609375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require(['jquery', 'jira/lib/class'], function($, Class) { var NotificationEditor = Class.extend({ init: function (options) { var instance = this; instance.$editor = options.editor; instance.$toolbar = options.toolbar; instance.$toolbar.find("div.aui-button") .tooltip() .click(function(e) { e.preventDefault(); $(this).tooltip("hide"); var macro = $(this).data("macro"); if (macro) { instance.insertMacro("$" + macro); instance.$editor.trigger("contentModified"); instance.$editor.focus(); } }); }, /** * Insert the macro text at the current cursor position in the editor. * * Utility methods borrowed from Mention.js in the Jira source. */ insertMacro: function(macro) { var raw = this._rawInputValue(), caretPos = this._getCaretPosition(), before = raw.substr(0, caretPos).replace(/\r\n/g, "\n"), after = raw.substr(caretPos); if (macro === '$example') { macro = "Hey, this event was generated by a post function!\n" + "Project: $project.name ($project.key)\n" + "Action: $action\n" + "Creator: $creator.name\n" + "Actor: $user.name\n\n" + "##\n" + "## these are basic velocity comments\n" + "##\n\n" + "#if ($issue.resolution)\n" + "Resolution: $issue.resolution.name\n" + "#end\n\n" + "#if ($assignee) \n" + "Assignee: $assignee.name\n" + "#end\n\n" + "## Custom fields\n" + "$customFields.fieldName.name -> $!customFields.fieldName.value\n" + "Or just: $customFields.fieldName ($customFields.customfield_XXXXX)"; } if (before.length !== 0) { macro = " " + macro; } this._rawInputValue([before, macro, after].join("")); this._setCursorPosition(before.length + macro.length); }, /** * Sets the cursor position to the specified index. * * @param index The index to move the cursor to. */ _setCursorPosition: function(index) { var input = this.$editor.get(0); if (input.setSelectionRange) { input.focus(); input.setSelectionRange(index, index); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', index); range.moveStart('character', index); range.select(); } }, /** * Returns the position of the cursor in the editor field. */ _getCaretPosition:function (){ var element = this.$editor.get(0); var rawElementValue = this._rawInputValue(); var caretPosition, range, offset, normalizedElementValue, elementRange; if (typeof element.selectionStart === "number") { return element.selectionStart; } if (document.selection && element.createTextRange){ range = document.selection.createRange(); if (range) { elementRange = element.createTextRange(); elementRange.moveToBookmark(range.getBookmark()); if (elementRange.compareEndPoints("StartToEnd", element.createTextRange()) >= 0) { return rawElementValue.length; } else { normalizedElementValue = rawElementValue.replace(/\r\n/g, "\n"); offset = elementRange.moveStart("character", -rawElementValue.length); caretPosition = normalizedElementValue.slice(0, -offset).split("\n").length - 1; return caretPosition - offset; } } else { return rawElementValue.length; } } return 0; }, /** * Gets or sets the text value of our input via the browser, not jQuery. * @return The precise value of the input element as provided by the browser (and OS). * @private */ _rawInputValue: function() { var el = this.$editor.get(0); if (typeof arguments[0] === "string") { el.value = arguments[0]; } return el.value; } }); AJS.toInit(function() { var $editor = $(".slack-notification-editor"); if ($editor.length) { new NotificationEditor({ editor: $editor, toolbar: $(".slack-notification-editor-toolbar") }); } }); });
C++
UTF-8
739
3.484375
3
[]
no_license
#include <iostream> #include <string> using namespace std; string checkMonth(float n); int main() { cout << "Podaj liczbe, dla ktorej chcesz poznac odpowiednik miesiaca" << endl; float n; cin >> n; cout << "Twoja liczba: " << n << " to odpowiednik miesiaca: " << checkMonth(n) << endl; system("pause"); return 0; } string checkMonth(float n) { string miesiace[12] = { "styczen", "luty", "marzec", "kwiecien", "maj", "czerwiec", "lipiec", "sierpien", "wrzesien", "pazdziernik", "listopad", "grudzien" }; int odpowiednik_float = static_cast<int>(n); if (n > 12.1) { cout << "Nie znaleziono odpowiednika miesiaca dla " << n << endl; return 0; } return miesiace[odpowiednik_float - 1]; }
Java
UTF-8
4,558
2.4375
2
[]
no_license
package com.sj.at.customview; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.sj.at.customFour.CustomFour; import com.sj.at.customOne.CustomOne; import com.sj.at.customThree.CustomThree; import com.sj.at.customTwo.CustomTwo; import com.sj.at.myAuto.AutoActivity; import com.sj.at.myDrag.VDHActivity; import com.sj.at.drawFour.DrawFourActivity; import com.sj.at.drawOne.DrawOneActivity; import com.sj.at.drawThree.DrawThreeActivity; import com.sj.at.drawTwo.DrawTwoActivity; /** * 作者: Shaojia on 2015/8/14. * 邮箱: 309814872@qq.com * * 部分自定义控件 * 第一排 paint(画笔) canvas(画布) 基础;文字;区域;变换操作 * 第二排 自定义View起步 * 第三排 自定义的控件 * */ public class MainActivity extends Activity implements View.OnClickListener{ private Button btn_graphics_one_step,btn_graphics_two_step,btn_graphics_three_step,btn_graphics_four_step = null; private Button btn_one_step,btn_two_step,btn_three_step,btn_four_step = null; private Button btn_one_view,btn_two_view = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initLayout(); } public void initLayout(){ //Draw方法 btn_graphics_one_step = (Button) this.findViewById(R.id.btn_graphics_one_step); btn_graphics_two_step = (Button) this.findViewById(R.id.btn_graphics_two_step); btn_graphics_three_step = (Button) this.findViewById(R.id.btn_graphics_three_step); btn_graphics_four_step = (Button) this.findViewById(R.id.btn_graphics_four_step); //自定义布局初学之路 btn_one_step = (Button) this.findViewById(R.id.btn_one_step); btn_two_step = (Button) this.findViewById(R.id.btn_two_step); btn_three_step = (Button) this.findViewById(R.id.btn_three_step); btn_four_step = (Button) this.findViewById(R.id.btn_four_step); //自定义布局实战 btn_one_view = (Button) this.findViewById(R.id.btn_one_view); btn_two_view = (Button) this.findViewById(R.id.btn_two_view); btn_graphics_one_step.setOnClickListener(this); btn_graphics_two_step.setOnClickListener(this); btn_graphics_three_step.setOnClickListener(this); btn_graphics_four_step.setOnClickListener(this); btn_one_step.setOnClickListener(this); btn_two_step.setOnClickListener(this); btn_three_step.setOnClickListener(this); btn_four_step.setOnClickListener(this); btn_one_view.setOnClickListener(this); btn_two_view.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_graphics_one_step: startActivity(new Intent(this,DrawOneActivity.class)); break; case R.id.btn_graphics_two_step: startActivity(new Intent(this,DrawTwoActivity.class)); break; case R.id.btn_graphics_three_step: startActivity(new Intent(this,DrawThreeActivity.class)); break; case R.id.btn_graphics_four_step: startActivity(new Intent(this,DrawFourActivity.class)); break; /*自定义布局初学之路 * 1、自定义View的属性 * 2、在View的构造方法中获得我们自定义的属性 * [ 3、重写onMesure ] * 4、重写onDraw */ case R.id.btn_one_step: startActivity(new Intent(this,CustomOne.class)); break; case R.id.btn_two_step: startActivity(new Intent(this,CustomTwo.class)); break; case R.id.btn_three_step: startActivity(new Intent(this,CustomThree.class)); break; case R.id.btn_four_step: startActivity(new Intent(this,CustomFour.class)); break; case R.id.btn_one_view: // 自动换行布局 startActivity(new Intent(this,AutoActivity.class)); break; case R.id.btn_two_view: // 拖动 startActivity(new Intent(this,VDHActivity.class)); break; default: } } }
Python
UTF-8
8,096
2.625
3
[]
no_license
#! /usr/bin/env python """This module imports XML and converts it to a plist-compatible format. The primary method here is xml_to_dict. It iterates over the XML tree and looks for these terms as tags, attributes, and as children elements of the parent. It compares these terms to the correct dictionary for the element and replaces the FML word with the accepted .itpl word. This script will 'flatten' the above into the correct .plist format, and will apply the attributes of the children to the parent, just like the .itpl file. it will turn "edit='1'" into "<key>dynamic_list</key><integer>1</integer>" and add it to the parent element. Currently, it is not as recursive as it maybe could be, so only one layer of nesting children is supported. also, it doesn't really care whether the values are attributes or child elements. This is by design, especially since at present the syntax and styling are all very young. Many values have defaults and do not need to be explicitly entered, but can be easily overridden if they are present in the FML file. Order_num is determined when the file is translated from FML to a dict for plistlib, so just by building the FML correctly will the order of elements and sections be determined.""" import xml.etree.ElementTree as ET import plistlib as PLIB import os as OS import baseparts as BP import formeditor as FE import reorderform as ROF ##eventually move this out from boxdict import _boxtypes from fmltodict import _xmltranslate, _elemdict, _xmltextlocation from pprint import pprint as pp ##these, along with the defaults in pyfml.py, should be in a separate file in a dict FMLFOLDER = 'fml' FMLFILE = 'test.fml' IMGFOLDER = 'images' ##return this on element creation fail _BADELEMENT = _elemdict['label'](field_label="**An error occurred here. REMOVE this element and correct.**") ##escape characters. ## for list items, [] to replace <> in blocks. are there more? _fmlcharsonly = {"##":"\r","[":"<","]":">"} def read_xml(xmlpath): """Loads XML from stated path.""" tree = ET.parse(xmlpath) return tree.getroot() def read_xml_from_str(xmlstring): """Returns ET object from a string.""" return ET.fromstring(xmlstring) def new_shell_from_xml(xmlobj): """Returns a form populated with translated FML values.""" newShell = BP.make_new_form_shell() maybeid = xmlobj.find('id') if maybeid is not None: xmlobj.attrib['mp_uuid'] = maybeid.attrib.get('mp_uuid', None) for k, v in xmlobj.attrib.iteritems(): newShell[k] = v maybetitle = tidy_up(xmlobj.text) if maybetitle: newShell['template_name'] = maybetitle return newShell def new_section_from_xml(xmlsection): """Returns a section populated with translated FML values.""" newSectionOuter = BP.make_new_section_outer() boxType = _boxtypes.get(xmlsection.tag, False) if boxType is 'id': return 'id' elif boxType is not False: newSectionOuter['mp_box_type'] = boxType del newSectionOuter['iform_section'] else: newSectionInner = BP.make_new_section_inner() maybeid = xmlsection.find('id') if maybeid is not None: xmlsection.attrib['mp_uuid'] = maybeid.attrib.get('mp_uuid', None) for k, v in xmlsection.attrib.iteritems(): if k is not 'order_num': newSectionInner[k] = v maybetitle = tidy_up(xmlsection.text) if maybetitle: newSectionInner['section_name'] = maybetitle newSectionOuter['iform_section'] = newSectionInner return newSectionOuter def new_elem_from_xml(xmlelement): """Returns an element populated with translated FML values.""" elemType = xmlelement.tag translator = _xmltranslate.get(elemType, None) elem_method = _elemdict.get(elemType, None) if translator is 'id' or elem_method is 'id': #print "found an id, returning id and moving on?" return 'id' elif translator is None or elem_method is None: print "Can't work with %s" % xmlelement.tag #print "trans: %s\t method: %s" % (translator, elem_method) #print """There's no <%s> element in FML. Available elements are: \n%s #""" % (elemType,''.join(['\n\t%s' % x for x in _elemdict.keys()])) return _BADELEMENT else: newElem = elem_method() elemTextKey = _xmltextlocation.get(elemType, 'field_label') ##next line gets value of 'open text', or sets to '' if None. ##this allows for void elements such as <label /> or simply ##elements with no field_label. also, python ternary <3 <3 ##read as -> elemTextVal = xmlelem.text == None ? '' : xmlelem.text elemTextVal = xmlelement.text if xmlelement.text is not None else '' elemAttrib = xmlelement.attrib.items() ##attributes as list of tuples elemData = [(elemTextKey, elemTextVal)] for k, v in elemAttrib: elemData += [(k, v)] nestedData = [] for item in xmlelement: ##add nested xml to 'parent' element ## <3 nestedData += [(item.tag, item.text if item.text is not None else '')] nestedAttrib = item.attrib.items() for k, v in nestedAttrib: nestedData += [(k, v)] for k, v in elemData + nestedData: k = translator.get(k, k) v = tidy_up(v) ##cleans up strings if k is 'field_label' and v is not None: v = str(v) ##field_label MUST be string if v: ##only add if v exists newElem[k] = v #if 'id' in newElem: # del newElem['id'] ###OH MAN THIS SUCKS. :( WHAT A LOUSY HACK if 'imageObjData' in newElem: ##encodes images if present ##apparently this works for future builds but not current?? O_o ## ## maybeimage = img_path_to_base64(newElem['imageObjData']) if maybeimage is not None: newElem['imageObjData'] = maybeimage else: del newElem['imageObjData'] print "Unfortunately you'll need to load some drawing image data yourself." return newElem def img_path_to_base64(imageobjdatapath): """Turns a relative path into a base64 encoded image. Should be called after the FML element is translated into a dict.""" try: pathinfolder = OS.path.join(IMGFOLDER, imageobjdatapath) with open(pathinfolder, "rb") as f: dataToTranslate = f.read() except IOError: if not len(pathinfolder) < 50: pathinfolder = str(pathinfolder)[:50] + "...(truncated)" print "Bad path: %s" % pathinfolder return None except AttributeError: if isinstance(imageobjdatapath, PLIB.Data): print "Already has binary data -- no need to load!" return imageobjdatapath else: return PLIB.Data(dataToTranslate) def xml_to_dict(xmlform): """Pass this an FML file; returns a dict for plistlib to convert to .itpl. The order_num of elements is determined on translation, so it need not be present in the FML file.""" newForm = new_shell_from_xml(xmlform) for section in xmlform: newSection = new_section_from_xml(section) if newSection is not 'id': for element in section: newElem = new_elem_from_xml(element) if newElem is not 'id': FE.add_elem_to_section(newElem, newSection) FE.add_section_to_form(newSection, newForm) return newForm def tidy_up(somexml): """Ensures strings are unicode, removes newlines and tabs from strings, and replaces the ## delimiter as newlines from lists/sublists. If passed something besides basestring or int, returns it as-is.""" if not isinstance (somexml, (basestring, int)): return somexml try: tidied = int(somexml) except: tidied = somexml.strip() for badchar in _fmlcharsonly.keys(): tidied = tidied.replace(badchar, _fmlcharsonly.get(badchar)) return tidied ###help methods for quick testing, not probably much use for anything else def test(filepath=FMLFILE): """Quickly tests fmltest.xml to see that it loads as both valid XML and turns into a plist-friendly dict. Both the XML and the dict are returned as (XML, dict) tuple. If need be, an optional filepath can be passed.""" newpath = OS.path.join(FMLFOLDER, filepath) xmlF = read_xml(newpath) newF = xml_to_dict(xmlF) return newF def bigtest(): """In case one needs to work with a 'finished' form in the Python interpreter.""" newF = test() ROF.set_order_num(newF) ROF.set_field_ids(newF) ROF.set_narrative(newF) return newF def quicktest(): """Even shorter test! Just pretty-prints the dict version of the FML file. Returns nothing.""" pp(test())
JavaScript
UTF-8
778
2.71875
3
[]
no_license
function checkHidden(cols, rows){ var arr = []; var sum = 0; var se = document.getElementById("weight"); var p = document.createElement("P"); for(var i = 0; i < cols.length; i++){ var weight = []; if(cols[i].style.display != "none" && cols[i].className){ arr.push(cols[i].children); } for(var j = 0; j < arr.length; j++){ if(arr[j][2].innerText != "") weight.push(arr[j][2].innerText); } } for(var i = 0; i < weight.length; i++){ var num = Number(weight[i]); sum += num; } var result = sum.toString(); p.append(result); $(se).html(p); }
Java
UTF-8
6,343
2.546875
3
[]
no_license
package com.atguigu.springboot04.controller; import com.atguigu.springboot04.bean.Goods; import com.atguigu.springboot04.bean.Kinds; import com.atguigu.springboot04.bean.Users; import com.atguigu.springboot04.bean.Words; import com.atguigu.springboot04.dto.Page; import com.atguigu.springboot04.service.GoodsService; import com.atguigu.springboot04.service.WordsService; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; //这个类的所有方法返回的数据直接写给浏览器,(如果是对象转为json数据) /*@ResponseBody//只能返回String,返回url只能写controller @Controller*/ @Controller public class IndexController { @Autowired private GoodsService goodsService; @Autowired private WordsService wordsServicec; @RequestMapping(value = "/index",method = RequestMethod.GET) public String index(HttpServletRequest request, Model model, @RequestParam(name="page",defaultValue = "1") Integer page,//但前要访问的页面 @RequestParam(name="set",defaultValue = "1") Integer set,//标记来自不同页面的请求 @RequestParam(name="number",defaultValue = "-1") Integer number,//各自页面中当前操作的商品number @RequestParam(name="size",defaultValue = "8") Integer size,//每页所包含的数据数目 @RequestParam(name="kind",defaultValue = "-1") String kind ){ Page t=common(page,size,set,kind); List<Kinds> l=goodsService.getKinds(); model.addAttribute("indexpage",t); model.addAttribute("indexkind",l); if(kind.equals("-1")) { model.addAttribute("kind","-1"); } else { model.addAttribute("kind",kind); } System.out.println(l+" 1213"); return "index"; } public Page common(Integer page,Integer size,Integer set,String kind){ if(kind.equals("-1")) { int s=goodsService.getCountAll(set); Page t=new Page(); t.setPageInation(s,page,size); List<Goods> list=null; if(t.getPage()>=1) { list=goodsService.getGoodsById(((t.getPage()-1)*size),size,set); } t.setGoods(list); return t; } else { //点击二级分类查询商品 int s=goodsService.getCountByKind(kind); Page t=new Page(); t.setPageInation(s,page,size); List<Goods> list=null; if(t.getPage()>=1) { list=goodsService.getGoodsByKinds(kind,((t.getPage()-1)*size),size); } t.setGoods(list); return t; } } // RESTAPI的方式 //首页进入商品详情页面 @RequestMapping(value = "/goodpage",method = RequestMethod.GET) public String goodPage(Model model, @RequestParam(name="number") Integer number, @RequestParam(name="set",defaultValue = "0") Integer set,//set=1表示从上架商品页面点击商品编号进入商品详情页面 @RequestParam(name="page",defaultValue = "-1") Integer page ){ Goods g=goodsService.getGoodsByNumber(number); if(set==1&&(g.getUdstatus()!=1||g.getDeletstatus()==1)) { //表示从上架商品页面点击商品编号进入商品详情页面时该商品已出售或已下架 model.addAttribute("erro","该商品已下架或已出售!"); return "redirect:/upgood?page="+page; } //长期处于商品详情页面,但该商品已下架时,点击任何事件 if(g.getUdstatus()!=1||g.getDeletstatus()==1) { return "redirect:/index"; } model.addAttribute("goodpage",g); model.addAttribute("all",0); //留言区 List<Words> words=wordsServicec.getWords(number); for(Words c: words) { System.out.println(c.getId()+" "+c.getDate()); } model.addAttribute("comment",words); //推荐区,推荐商品 List<Goods> recommends=goodsService.getRecommends(g); model.addAttribute("recommends",recommends); return "goodpage"; } @RequestMapping(value = "/ups",method = RequestMethod.GET) public String ups(Model model ){ model.addAttribute("sure","index"); return "up"; } /* @RequestMapping(value = "/kind",method = RequestMethod.GET) public String kind(Model model ){ model.addAttribute("sure","index"); return "up"; }*/ //搜索按钮查询 @RequestMapping(value = "/check",method = RequestMethod.GET) public String index(HttpServletRequest request, Model model, @RequestParam(name="page",defaultValue = "1") Integer page,//当前要访问的页面 @RequestParam(name="size",defaultValue = "10") Integer size,//每页所包含的数据数目 @RequestParam(name="check") String check ){ /*if(check.trim().equals("")) { model.addAttribute("erro","关键字不能为空!"); }*/ Page t=common(page,size,check); model.addAttribute("indexpage",t); model.addAttribute("ckeck",check); return "checkpage"; } public Page common(Integer page,Integer size,String check) { int s = goodsService.getCountByCheck(check); Page t = new Page(); t.setPageInation(s, page, size); List<Goods> list = null; if (t.getPage() >= 1) { list = goodsService.getGoodsByCheck( check,((t.getPage() - 1) * size), size); } t.setGoods(list); return t; } }
Java
UTF-8
397
1.664063
2
[]
no_license
package com.officego.commonlib.common.model; import com.google.gson.annotations.SerializedName; /** * Created by shijie * Date 2021/3/24 **/ public class AlipayBean { @SerializedName("orderInfo") private String orderInfo; public String getOrderInfo() { return orderInfo; } public void setOrderInfo(String orderInfo) { this.orderInfo = orderInfo; } }
Java
UTF-8
169
2.203125
2
[]
no_license
class N { public static void main(String agrs[]) { int a,b; a=Integer.parseInt(agrs[0]); b=Integer.parseInt(agrs[1]); int c=a+b; System.out.println(c); } }
C
UTF-8
4,191
3.578125
4
[]
no_license
/* * Created by Ben Gustafson on 10/9/2017 */ #include "input.h" void SolveMaze(struct ReadMaze maze) { struct Solver crawler; int endRow = maze.end[1]; int endCol = maze.end[0]; char nullChar = 'X'; /* Represents possible empty space on maze edge */ char up, dn, rt, lf; crawler.row = maze.start[1]; crawler.col = maze.start[0]; /* Default value. Updates on loop start */ crawler.currentDir = SOUTH; maze.MazeData[crawler.row][crawler.col] = '.'; while (!(crawler.row == endRow && crawler.col == endCol)) { /* * Assign values from the Maze's data to placeholders; null if at an edge * (That way, the code to assign them per direction isn't too verbose) */ if (crawler.row > 0) up = maze.MazeData[crawler.row - 1][crawler.col]; else up = nullChar; if (crawler.col > 0) lf = maze.MazeData[crawler.row][crawler.col - 1]; else lf = nullChar; if (crawler.row < maze.rows) dn = maze.MazeData[crawler.row + 1][crawler.col]; else dn = nullChar; if (crawler.col < maze.Columns) rt = maze.MazeData[crawler.row][crawler.col + 1]; else rt = nullChar; /* * Assign placeholders to the Solver's respective values * (Based on direction) */ switch (crawler.currentDir) { case NORTH: crawler.fwd = up; /* up */ crawler.left = lf; /* lf ^ rt */ crawler.right = rt; /* dn */ crawler.rear = dn; break; case EAST: crawler.fwd = rt; /* up */ crawler.left = up; /* lf > rt */ crawler.right = dn; /* dn */ crawler.rear = lf; break; case SOUTH: crawler.fwd = dn; /* up */ crawler.left = rt; /* lf v rt */ crawler.right = lf; /* dn */ crawler.rear = up; break; case WEST: crawler.fwd = lf; /* up */ crawler.left = dn; /* lf < rt */ crawler.right = up; /* dn */ crawler.rear = rt; break; default: break; } /* * Get the solver to rotate and advance * (Based on these previously set environment values) * * Follows the right-hand-wall rule to solve * * Go until Solver's co-ords line up with maze's end */ switch (CheckEnvironment(crawler.fwd, crawler.left, crawler.right, crawler.rear)) { /* If right is open */ case 'R': /* Sets the enum to the next value (clockwise) */ crawler.currentDir = (crawler.currentDir + 1) % 4; /* Move the solver based on its direction */ if (crawler.currentDir == NORTH) --crawler.row; else if (crawler.currentDir == EAST) ++crawler.col; else if (crawler.currentDir == SOUTH) ++crawler.row; else if (crawler.currentDir == WEST) --crawler.col; break; /* If right is a wall and fwd is open */ case 'F': /* Move the solver based on its direction */ if (crawler.currentDir == NORTH) --crawler.row; else if (crawler.currentDir == EAST) ++crawler.col; else if (crawler.currentDir == SOUTH) ++crawler.row; else if (crawler.currentDir == WEST) --crawler.col; break; /* If right and fwd are walls and left is open */ case 'L': /* Sets the enum to the previous value (counter-clockwise) */ crawler.currentDir = (crawler.currentDir - 1) % 4; break; /* If all three but rear are walls */ case 'B': /* Rotate the crawler 180 degrees */ crawler.currentDir = (crawler.currentDir + 2) % 4; break; default: break; } /* Change the character under the solver to represent the path taken */ maze.MazeData[crawler.row][crawler.col] = '.'; } /* Display the solved maze */ printf("Maze Solved!\n"); Display(maze.MazeData, maze.Columns, maze.rows); } char CheckEnvironment(char fwd, char left, char right, char rear) { /* Check if right is open */ if (right != 'X') return 'R'; /* Check if right is a wall and fwd is open */ else if (right == 'X' && fwd != 'X') return 'F'; /* Check if right and fwd are walls and left is open */ else if (right == 'X' && fwd == 'X' && left != 'X') return 'L'; /* Check if all three but rear are walls */ else if (right == 'X' && fwd == 'X' && left == 'X' && rear != 'X') return 'B'; /* Default return value, should never realistically be used */ else return 'x'; }
Java
UTF-8
2,999
1.875
2
[]
no_license
package com.wyu.iwork.view.fragment; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.wyu.iwork.R; import com.wyu.iwork.adapter.CommuChatAdapter; import com.wyu.iwork.interfaces.DataIView; import com.wyu.iwork.presenter.CommuChatPresenter; import com.wyu.iwork.util.Logger; import com.wyu.iwork.view.activity.NotificationActivity; import com.wyu.iwork.view.activity.OrganzManageActivity; import java.util.List; import io.rong.imlib.model.Conversation; /** * Created by jhj_Plus on 2016/10/25. */ public class CommuChatFragment extends BaseFragment implements DataIView<List<Conversation>> { private static final String TAG = "MyFragments"; private RecyclerView mRv; private CommuChatAdapter mAdapter; private CommuChatPresenter mPresenter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPresenter = new CommuChatPresenter(getActivity()); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ViewGroup content = (ViewGroup) inflater .inflate(R.layout.fragment_commu_chat, container, false); mPresenter.attachView(this); mPresenter.readData(); return super.onCreateView(inflater, content, savedInstanceState); } @Override public void onInitView(View rootView) { mRv= (RecyclerView) rootView.findViewById(R.id.recyclerView); mAdapter = new CommuChatAdapter(getActivity()); mRv.setAdapter(mAdapter); rootView.findViewById(R.id.notification).setOnClickListener(this); rootView.findViewById(R.id.organz).setOnClickListener(this); rootView.findViewById(R.id.userManage).setOnClickListener(this); rootView.findViewById(R.id.invite).setOnClickListener(this); } @Override public void onClick(View v) { super.onClick(v); switch (v.getId()) { case R.id.notification: startActivity(new Intent(getActivity(), NotificationActivity.class)); break; case R.id.organz: startActivity(new Intent(getActivity(), OrganzManageActivity.class)); break; } } @Override public void onReadFinished(boolean success, List<Conversation> data) { if (success && data != null && !data.isEmpty()) { Logger.e(TAG, "conversation data===>" + data.toString()); //mAdapter.insertItems(data); } } @Override public void onWriteFinished(boolean success) { } @Override public void onDestroyView() { super.onDestroyView(); mPresenter.detachView(); } }
Python
UTF-8
2,234
3.015625
3
[]
no_license
#encoding:UTF-8 from __future__ import division #ensure that float number when divide import random import cal_chrofitness def sumfitness(fitlist): #种群中全部个体的fitness之和 total=0 for i in range(len(fitlist)): total=total+fitlist[i] return total def cumcomfit(fitlist): #将种群中每个fitness标准化,得到累积fitness列表,为 轮盘赌 做准备 norfitlist=[] for i in range(len(fitlist)): norfitlist.append(fitlist[i]/sumfitness(fitlist)) cumfitlist = [] for i in range(len( norfitlist)): t = 0 j = 0 while (j <= i): t += norfitlist[j] j = j + 1 cumfitlist.append(t) return cumfitlist def fitprocess_before_RS(pop, flag): #将 种群的 fitness计算和累积fitness合并到一个函数,在 轮盘赌 中调用 fit_list = cal_chrofitness.pop_fitlist_cov(pop,flag) # 以 coverage #print fit_list #for test cumfit_list=cumcomfit(fit_list) return cumfit_list def RouletteSelection(pop, flag): #以适应度来选择个体,轮盘赌 selectedchrolist=[] templist=fitprocess_before_RS(pop,flag) #print templist #for test for i in range(len(pop)): #若种群大小为M,则用随机数选择M次,将这些父母按被选择的顺序存入selectedchro列表中,父母会重复被选择 randnum = random.uniform(0, 1) #print randnum #for test for j in range(len(pop)): if randnum<=templist[j]: selectedchrolist.append(pop[j]) break #print '选择后的种群:',selectedchrolist return selectedchrolist if __name__ == '__main__': pop = [['T1', 'T4', 'T5', 'T8', 'T20', 'T22', 'T10', 'T23'], ['T1', 'T2', 'T4', 'T5', 'T8', 'T10', 'T8', 'T19', 'T22', 'T10', 'T7', 'T9', 'T23'], ['T1', 'T2', 'T4', 'T6', 'T8', 'T17', 'T21', 'T10', 'T23'], ['T1', 'T2', 'T2', 'T4', 'T6', 'T8', 'T19', 'T21', 'T20', 'T22', 'T18', 'T22', 'T10', 'T7', 'T9', 'T23'], ['T1', 'T2', 'T2', 'T4', 'T5', 'T23']] #print fitprocess_before_RS(pop) print pop RouletteSelection(pop) print pop
Shell
UTF-8
484
2.859375
3
[]
no_license
if [ "$#" -ne 3 ]; then echo "usage: ./whatever experiment_name num_threads name_suffix"; exit 1; fi assets=20 set -ex make singlenode_validator -j 8 make generate_zeroblock -j 8 make xdrpy_module -j 8 EXPERIMENT_DATA_FILE=experiment_data/$1 DEFAULT_AMOUNT=10000000000 #./clean_persisted_data.sh ${assets} keep #./generate_zeroblock ${EXPERIMENT_DATA_FILE} ${DEFAULT_AMOUNT} ./singlenode_validator ${EXPERIMENT_DATA_FILE} experiment_results/${output_name}_validation $2
Python
UTF-8
1,057
2.875
3
[ "MIT" ]
permissive
from bot.models import Earning, CategoryEarning, CategoryConsumption def make_text_earning(session, earning): category = session.query(CategoryEarning).get(earning.category_id) return f'Доход {earning.amount_money} руб. {category.category} {earning.get_str_time_creation()} - ' \ f'/del_e{earning.id}\n' def make_text_consumption(session, consumption): category = session.query(CategoryConsumption).get(consumption.category_id) return f'Расход {consumption.amount_money} руб. {category.category} {consumption.get_str_time_creation()} - ' \ f'/del_c{consumption.id}\n' def make_text_list_transactions(session, list_transactions: list): if not list_transactions: return 'Нет транзакций.' text = '' for transaction in list_transactions: if isinstance(transaction, Earning): text += make_text_earning(session=session, earning=transaction) else: text += make_text_consumption(session=session, consumption=transaction) return text
Java
UTF-8
3,644
2.328125
2
[ "Apache-2.0" ]
permissive
package edu.pdx.cs410J.huanhua; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.navigation.fragment.NavHostFragment; import com.google.android.material.snackbar.Snackbar; import java.io.File; import edu.pdx.cs410J.ParserException; /** * A fragmnent for print a whole phone bill */ public class FragmentPrintBill extends Fragment { private View thisView = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment thisView = inflater.inflate(R.layout.fragment_print_bill, container, false); return thisView; } /** * after view is created * * @param view * @param savedInstanceState */ @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // when click go back view.findViewById(R.id.button_go_back_print_bill_fragment).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleGoBack(); } }); // when click search bill view.findViewById(R.id.button_phone_bill_search).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { handleSearch(); } }); } /** * handle event when click go back */ private void handleGoBack() { NavHostFragment.findNavController(this) .navigate(R.id.action_FragmentPrintBill_to_FragmentMain); } /** * handle event when click search bill */ private void handleSearch() { TextView customerView = thisView.findViewById(R.id.input_print_bill_customer); String customer = customerView.getText().toString(); PhoneBill bill = null; if (customer.isEmpty()) { Snackbar.make(thisView, "Please enter a customer name.", 5000) .setAction("Action", null).show(); return; } // search phone bill // String path = thisView.getContext().getApplicationInfo().dataDir; // String path = thisView.getContext().getFilesDir().getPath(); File path = thisView.getContext().getFilesDir(); File file = new File(path, customer); try { bill = TextParser.parseFile(file); } catch (ParserException e) { Snackbar.make(thisView, e.getMessage(), 5000) .setAction("Action", null).show(); return; } if (bill == null) { String msg = "No phone bill found for customer \"" + customer + "\""; Snackbar.make(thisView, msg, 5000) .setAction("Action", null).show(); } else { // prepare data to send to another fragment Bundle bundle = new Bundle(); // bundle.putString("customer", customer); bundle.putSerializable("bill", bill); bundle.putInt("back", R.id.action_FragmentPrintBillResult_to_FragmentPrintBill); // go to result fragment NavHostFragment.findNavController(FragmentPrintBill.this) .navigate(R.id.action_FragmentPrintBill_to_FragmentPrintBillResult, bundle); } } }
Java
UTF-8
682
2.109375
2
[]
no_license
package com.troopar.trooparapp.adapter.viewholder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.troopar.trooparapp.R; /** * Created by barry on 16/07/2016. */ public class InvitePeopleViewHolder extends RecyclerView.ViewHolder{ private ImageView invitePeopleBtn; public InvitePeopleViewHolder(View itemView) { super(itemView); invitePeopleBtn= (ImageView) itemView.findViewById(R.id.invitePeopleBtn); } public void setImageSize(LinearLayout.LayoutParams layoutParams){ invitePeopleBtn.setLayoutParams(layoutParams); } }
Markdown
UTF-8
1,766
2.609375
3
[]
no_license
<a href="https://truyentiki.com/chung-ta-yeu-nhau-di-sai-ga-the-hon-tong-tai.30798/" title="Chúng Ta Yêu Nhau Đi: Sai Gả Thế Hôn Tổng Tài"><h1>Chúng Ta Yêu Nhau Đi: Sai Gả Thế Hôn Tổng Tài</h1></a><div style="display:table"><img align="right" style="float: left; padding: 10px;" src="https://truyentiki.com/a/img/str/src/30798.jpg" alt="Chúng Ta Yêu Nhau Đi: Sai Gả Thế Hôn Tổng Tài">Để trả tiền chữa trị cho anh trai, Shen Qi phải kết hôn với em gái mình trong gia đình giàu có. Cô luôn nghĩ mình cưới anh và con trai anh, nhưng không biết rằng người chồng hư danh của cô là con trai thứ hai của anh, He Yining. He Yining, người thừa kế thực sự của gia đình He, hoàng đế kinh doanh lúng túng, bạo chúa sự nghiệp tàn nhẫn và em gái cô mơ ước được kết hôn. Khi hoàng đế kinh doanh ép mình lên xuống, cô sững sờ: "Này, anh sẽ làm gì? Tôi là chị dâu của anh!" "Chị dâu?"</div><p><br><b>Truyện Hay Khác :</b></p><a href="https://truyentiki.com/canh-tu-nong-nu-nhat-cai-tuong-quan-hao-lam-ruong.30797/" alt="Cảnh Tú Nông Nữ: Nhặt Cái Tướng Quân Hảo Làm Ruộng">Cảnh Tú Nông Nữ: Nhặt Cái Tướng Quân Hảo Làm Ruộng</a><br/><a href="https://github.com/nownovels/truyenhay/tree/master/truyenhay/30396/README.md" alt="Ở Bên Nhau">Ở Bên Nhau</a><br/><a href="https://github.com/nownovels/truyenhay/tree/master/truyenhay/30690/README.md" alt="Bằng Hư Công Tử">Bằng Hư Công Tử</a><br/><a href="https://truyencv2020.blogspot.com/2020/06/tong-tai-co-cai-trong-long-bao.html" alt="Tổng Tài Có Cái Trong Lòng Bảo">Tổng Tài Có Cái Trong Lòng Bảo</a><br/>
Java
UTF-8
421
2.640625
3
[]
no_license
package entities; public class Error { private Boolean hasError; private String message; public Error() { setHasError(false); setMessage(""); } public Boolean getHasError() { return hasError; } public void setHasError(Boolean hasError) { this.hasError = hasError; } public String getMessage() { return message; } public void setMessage(String errorMessage) { this.message = errorMessage; } }
Markdown
UTF-8
1,030
3.71875
4
[]
no_license
# Article Word Count - Inside the file ["input/article.txt"](input/article.txt) is an article that we would like to know the number of times each word has been shown. ## Your Tasks ### Write codes to: - Read the file *(I'm not asking you to read the file literally)* - Perform a count on the number of occurences for each word inside the article - Output the result on console ## Notes - This isn't a grammar test. You may ignore abbreviations, hyphenations and most other punctuations. For example, "stove-lids" should be count as two (2) different words "stove" and "lids"; "Samuel L. Jackson" should be treated as three (3) different words "Samuel", "L" and "Jackson"; "S.O.S." should be counted as three (3) words - two "S" and one "O" - The only punctuation that you do need to be concerned about is the single quote ('). For example, "can't" should stay as the word "can't" and not "can" and "t" - The test should be case insensitive. "JObs", "jobs" and "joBS" - total count should be three (3) words as it is the same word.
JavaScript
UTF-8
1,045
2.5625
3
[ "MIT" ]
permissive
var assert = require('chai').assert; var format = require('../formatter.js').format; describe('format', function () { it('should handle empty input', function () { assert.equal("\n", format("", true, false, false)); }); it('should handle simple headers', function () { assert.equal("Key: Value\n\n", format("Key: Value", true, false, false)); }); it('should put list header values on separate lines', function () { assert.equal("Require-Bundle:\n foo\n bar\n baz\n\n", format("Require-Bundle: foo,bar,baz\n", true, false, false)); }); it('should trim list header values', function () { assert.equal("Require-Bundle:\n foo\n bar\n\n", format("Require-Bundle: foo , bar\n", true, false, false)); }); it('should sort list header values', function () { assert.equal("Require-Bundle:\n bar\n foo\n\n", format("Require-Bundle: foo,bar\n", true, true, false)); }); it('should sort headers', function () { assert.equal("Bar: Bar\nFoo: Foo\n\n", format("Foo: Foo\nBar: Bar\n", true, true, true)); }); });
C++
UTF-8
3,024
2.515625
3
[ "MIT" ]
permissive
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file correlative_scan_matcher.h * \author Collin Johnson * * Declaration of CorrelativeScanMatcher. */ #ifndef LASER_CORRELATIVE_SCAN_MATCHER_H #define LASER_CORRELATIVE_SCAN_MATCHER_H #include <laser/scan_matcher_params.h> #include <laser/scan_likelihood_grid.h> #include <core/laser_scan.h> #include <core/multivariate_gaussian.h> namespace vulcan { namespace laser { /** * CorrelativeScanMatcher implements the scan matching algorithm described in: * * http://april.eecs.umich.edu/pdfs/olson2009icra.pdf * * The basic idea behind the algorithm is the following: * * 0) Create a log-likelihood grid from a scan or other reference frame, like a map. * 1) Create a search volume [x, y, theta] * 2) Find the maximum likelihood transformation [delta_x, delta_y, delta_theta] * 3) Calculate covariance estimate of the measurement * * At the current time, the scan matcher interface consists of two methods: * * void setReferenceScan(const cartesian_laser_scan_t& reference); * -Set the scan to use as a reference for transform calculations performed by * findMostLikelyTransform() * * math::MultiVariateGaussian findMostLikelyTransform(const cartesian_laser_scan_t& scan) const; * -Finds the mostly likely transformation between reference and scan. The ensuing transform is a Gaussian * with the mean as the transform. * */ class CorrelativeScanMatcher { public: /** * Constructor for CorrelativeScanMatcher. */ CorrelativeScanMatcher(const scan_matcher_params_t& params); /** * setReferenceScan sets the reference scan to be used for future calls to * findMostLikelyTransform(). * * \param reference Points to be used for the reference scan * \param referenceTime Time at which the points in the scan were captured */ void setReferenceScan(const std::vector<Point<float>>& reference, int64_t referenceTime); /** * findMostLikelyTransform searches for the most likely transformation between the previously * set reference scan and the current scan. * * \param scan Points to compare with the reference * \param scanTime Time at which the scan was taken */ MultivariateGaussian findMostLikelyTransform(const std::vector<Point<float>>& scan, int64_t scanTime) const; private: mutable ScanLikelihoodGrid fineResolutionGrid; mutable ScanLikelihoodGrid coarseResolutionGrid; float coarseResolutionMetersPerCell; scan_matcher_params_t params; int64_t referenceScanTimestamp; // full scan isn't needed, as necessary contents are in the likelihood grid }; } } #endif // LASER_CORRELATIVE_SCAN_MATCHER_H
SQL
UTF-8
15,946
3.453125
3
[ "Apache-2.0" ]
permissive
DROP DATABASE IF EXISTS scholar_tool; CREATE DATABASE scholar_tool DEFAULT CHARSET utf8 COLLATE utf8_general_ci; USE scholar_tool; GRANT SELECT, INSERT, UPDATE, DELETE ON scholar_tool.* TO 'www-data'@'localhost' IDENTIFIED BY 'www->R&daD6xZM6283n3-data'; GRANT SELECT, SHOW VIEW, LOCK TABLES, TRIGGER on scholar_tool.* TO 'dumper'@'localhost' IDENTIFIED BY 'dumper->a7&alnMn-bb'; CREATE TABLE user ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `username` VARCHAR(64) NOT NULL, `email` VARCHAR(64) NOT NULL, `password` VARCHAR(64) NOT NULL, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '用户'; CREATE TABLE invitation_code ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `code` VARCHAR(36) NOT NULL, `inviter_uuid` VARCHAR(36) NOT NULL, `invitee_uuid` VARCHAR(36) DEFAULT NULL, `invited_at` DATETIME DEFAULT NULL DEFAULT CURRENT_TIMESTAMP, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废,3 - 已使用', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '邀请码'; CREATE TABLE event ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `author_uuid` VARCHAR(36) NOT NULL, `title` VARCHAR(128) NOT NULL, `summary` VARCHAR(512) NOT NULL, `content` MEDIUMTEXT NOT NULL, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '公告'; CREATE TABLE service ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `user_uuid` VARCHAR(36) NOT NULL COMMENT '所属用户UUID', `template_uuid` VARCHAR(36) NOT NULL COMMENT '学术服务模板UUID', `type` TINYINT(4) NOT NULL COMMENT '0 - 包月套餐,1 - 流量套餐', `usage` BIGINT(16) NOT NULL COMMENT '已用流量', `package` BIGINT(16) NOT NULL COMMENT '总流量', `auto_renew` TINYINT(4) COMMENT '自动续费状态:0 - 不自动,1 - 自动续费,包月套餐专用字段', `billing_date` DATE NOT NULL COMMENT '账单日,下次付款的时间', # `reset_at` DATETIME COMMENT '下次将已用流量重置为0的时间点,包月套餐专用字段', # `last_reset_at` DATETIME COMMENT '上次将已用流量重置为0的时间点,暨上次续费的时间', # `expired_at` DATETIME COMMENT '套餐过期时间,流量套餐专用字段', `total_usage` BIGINT(16) NOT NULL COMMENT '已使用流量合计', `port` INT(11) NOT NULL COMMENT '服务绑定的端口号', `password` VARCHAR(64) NOT NULL COMMENT '服务密码', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废,3 - 暂停,待续费,4 - 失效', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '学术服务'; CREATE TABLE service_template ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `type` INT(4) NOT NULL COMMENT '套餐类型:0 - 包月套餐,1 - 流量套餐', `title` VARCHAR(64) NOT NULL COMMENT '套餐名', `subtitle` VARCHAR(64) NOT NULL COMMENT '副标题', `description` TEXT NOT NULL COMMENT '套餐描述', `package` BIGINT(20) NOT NULL COMMENT '流量', `price` DECIMAL(12, 2) NOT NULL COMMENT '价格', `initialization_fee` DECIMAL(12, 2) NOT NULL COMMENT '初装费', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废,3 - 下架', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '学术服务模板'; CREATE TABLE scholar_payment_account ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `user_uuid` VARCHAR(36) NOT NULL COMMENT '账户持有人UUID', `balance` DECIMAL(12, 2) NOT NULL DEFAULT 0 COMMENT '账户余额', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '学术积分账户'; CREATE TABLE scholar_payment_account_log ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `account_uuid` VARCHAR(36) NOT NULL COMMENT '学术积分账户UUID', `pay_order_uuid` VARCHAR(36) NOT NULL COMMENT '流水对应的支付订单UUID', `former_balance` DECIMAL(12, 2) NOT NULL COMMENT '操作前账户余额', `amount` DECIMAL(12, 2) NOT NULL COMMENT '金额', `balance` DECIMAL(12, 2) NOT NULL COMMENT '操作后账户余额', `type` TINYINT NOT NULL COMMENT '0 - 减少,1 - 增加', `purpose_type` TINYINT NOT NULL COMMENT '0 - 消费(-),1 - 充值(+),2 - 转出(-),3 - 转入(+),4 - 补缴(-),5 - 补偿(+)', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '学术积分账户流水'; CREATE TABLE service_trade_order ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `service_uuid` VARCHAR(36) NOT NULL COMMENT '学术服务UUID', `trade_order_uuid` VARCHAR(36) NOT NULL COMMENT '交易订单UUID', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '学术服务交易订单关系表'; CREATE TABLE trade_order ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `user_uuid` VARCHAR(36) NOT NULL COMMENT '交易方UUID', `type` TINYINT NOT NULL COMMENT '0 - 退款,1 - 充值,2 - 消费,3 - 转账,4 - 提现', `amount` DECIMAL(12, 2) NOT NULL COMMENT '金额', `description` TEXT COMMENT '交易描述', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 支付完成,2 - 作废,3 - 支付中,4 - 部分支付,5 - 退款中,6 - 部分退款,7 - 全部退款,8 - 取消', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '交易订单'; CREATE TABLE subscribe_service_snapshot ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `trade_order_uuid` VARCHAR(36) NOT NULL COMMENT '交易订单UUID', `user_uuid` VARCHAR(36) NOT NULL COMMENT '订购人UUID', `service_password` VARCHAR(64) NOT NULL COMMENT '服务密码', `auto_renew` TINYINT NOT NULL DEFAULT 0 COMMENT '是否自动续费:0 - 否,1 - 是', `service_template_uuid` VARCHAR(36) NOT NULL COMMENT '服务模板UUID', `type` INT(4) NOT NULL COMMENT '套餐类型:0 - 包月套餐,1 - 流量套餐', `title` VARCHAR(64) NOT NULL COMMENT '套餐名', `subtitle` VARCHAR(64) NOT NULL COMMENT '副标题', `description` TEXT NOT NULL COMMENT '套餐描述', `package` BIGINT(20) NOT NULL COMMENT '流量', `price` DECIMAL(12, 2) NOT NULL COMMENT '价格', `initialization_fee` DECIMAL(12, 2) NOT NULL COMMENT '初装费', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '订购学术服务交易快照'; CREATE TABLE payment_method ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `name` VARCHAR(32) NOT NULL COMMENT '渠道名', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '支付渠道'; CREATE TABLE pay_order ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `type` TINYINT NOT NULL COMMENT '1 - 充值,2 - 消费,3 - 转账,4 - 提现', `amount` DECIMAL(12, 2) NOT NULL COMMENT '付款金额', `trade_order_uuid` VARCHAR(36) NOT NULL COMMENT '交易订单UUID', `payment_method_uuid` VARCHAR(36) NOT NULL COMMENT '交易渠道UUID', `payment_method_token` VARCHAR(64) NOT NULL COMMENT '交易渠道唯一标识符', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 支付完成,2 - 作废,3 - 支付中', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '付款订单'; CREATE TABLE refund_order ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `type` TINYINT NOT NULL COMMENT '0 - 非原路退款,1 - 原路退款', `amount` DECIMAL(12, 2) NOT NULL COMMENT '退款金额', `trade_order_uuid` VARCHAR(36) NOT NULL COMMENT '交易订单UUID', `payment_method_uuid` VARCHAR(36) NOT NULL COMMENT '交易渠道UUID', `payment_method_token` VARCHAR(64) NOT NULL COMMENT '交易渠道唯一标识符', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 退款完成,2 - 作废,3 - 退款中', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '退款订单'; CREATE TABLE user_role ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `user_uuid` VARCHAR(36) NOT NULL COMMENT '用户UUID', `role_uuid` VARCHAR(36) NOT NULL COMMENT '角色UUID', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废,3 - 无效', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '用户角色'; CREATE TABLE role ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `name` VARCHAR(36) NOT NULL COMMENT '角色名', `description` TEXT COMMENT '角色描述', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废,3 - 无效', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '角色'; CREATE TABLE role_permission ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `role_uuid` VARCHAR(36) NOT NULL COMMENT '角色UUID', `permission_uuid` VARCHAR(36) NOT NULL COMMENT '权限UUID', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废,3 - 无效', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '角色权限'; CREATE TABLE permission ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `name` VARCHAR(36) NOT NULL COMMENT '权限名', `label` VARCHAR(36) NOT NULL COMMENT '权限标签', `description` TEXT COMMENT '权限描述', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废,3 - 无效', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '权限'; CREATE TABLE user_login_log ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `user_uuid` VARCHAR(36) NOT NULL, `ip` VARCHAR(39) DEFAULT NULL COMMENT '登录IP', `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = '用户登录日志'; /* CREATE TABLE table_name ( `id` INT(11) NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `status` TINYINT(4) NOT NULL DEFAULT 1 COMMENT '状态:0 - 初始化,1 - 有效,2 - 作废', PRIMARY KEY (`id`) ) ENGINE = innodb DEFAULT CHARSET = utf8 COMMENT = ''; */
Markdown
UTF-8
3,760
2.6875
3
[]
no_license
# 如何在CentOS 7上安装Nginx ### 关于Nginx Nginx是一款高性能的Web服务器软件。它比Apache HTTP Server更灵活轻便。 本教程将教您如何在CentOS 7服务器上安装并启动Nginx。 ## 先决条件 本教程中的步骤要求用户拥有root权限。您可以通过[使用CentOS 7](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-centos-7)教程的[初始服务器设置](https://www.digitalocean.com/community/tutorials/initial-server-setup-with-centos-7)中的步骤3和4来了解如何设置。 ## 第一步 - 添加Nginx存储库 要添加CentOS 7 EPEL存储库,请打开终端并使用以下命令: ``` sudo yum install epel-release ``` ## 第二步 - 安装Nginx 现在Nginx存储库已安装在您的服务器上,请使用以下`yum`命令安装Nginx : ``` sudo yum install nginx ``` 在对提示回答yes后,Nginx将在您的虚拟专用服务器(VPS)上完成安装。 ## 第三步 - 启动Nginx Nginx不会自行启动。要让Nginx运行,请输入: ``` sudo systemctl start nginx ``` 如果您正在运行防火墙,请运行以下命令以允许HTTP和HTTPS流量: ``` sudo firewall-cmd --permanent --zone=public --add-service=http sudo firewall-cmd --permanent --zone=public --add-service=https sudo firewall-cmd --reload ``` 您可以立即进行现场检查,通过在Web浏览器中访问服务器的公共IP地址来验证所有事情是否按计划进行(请参阅下一标题下的注释,以了解如果您没有此信息时您的公共IP地址是什么已经): ``` http://server_domain_name_or_IP/ ``` 您将看到默认的CentOS 7 Nginx网页,该网页用于提供信息和测试目的。它应该看起来像这样: ![CentOS 7 Nginx默认](https://assets.digitalocean.com/articles/lemp_1404/nginx_default.png) 如果您看到此页面,则您的Web服务器现在已正确安装。 在继续之前,您可能需要在系统引导时启用Nginx。为此,请输入以下命令: ``` sudo systemctl enable nginx ``` 恭喜!Nginx现在已经安装并正在运行! ### 如何查找您的服务器的公共IP地址 要找到您的服务器的公共IP地址,请键入以下命令找到您计算机上的网络接口: ``` ip addr ``` ``` 1. lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN . . . 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000 . . . ``` 您可能会在此看到许多接口,具体取决于服务器上可用的硬件。该`lo`接口是本地环回接口,这不是我们想要的。在我们上面的例子中,`eth0`接口就是我们想要的。 获得接口名称后,可以运行以下命令来显示服务器的公共IP地址。替换您在上面找到的接口名称: ``` ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//' ``` ## 服务器根目录和配置 如果你想通过Nginx开始提供自己的页面或应用程序,你需要知道Nginx配置文件和默认服务器根目录的位置。 ### 默认服务器根 默认的服务器根目录是`/usr/share/nginx/html`。放置在那里的文件将在您的Web服务器上提供。该位置在位于的Nginx附带的默认服务器块配置文件中指定`/etc/nginx/conf.d/default.conf`。 ### 服务器块配置 任何额外的服务器模块,在Apache中称为虚拟主机,都可以通过在其中创建新的配置文件来添加`/etc/nginx/conf.d`。`.conf`当Nginx启动时,将以该目录结尾的文件加载。 ### Nginx全局配置 主要的Nginx配置文件位于`/etc/nginx/nginx.conf`。这是您可以更改设置的位置,例如运行Nginx守护进程的用户,以及Nginx运行时产生的工作进程数量等。
PHP
UTF-8
709
2.796875
3
[ "MIT" ]
permissive
<?php namespace Core\Ajax\Commands\Dom; /** * CssCommand.php * * @author Michael "Tekkla" Zorn <tekkla@tekkla.de> * @copyright 2016 * @license MIT */ class CssCommand extends AbstractDomCommand { /** * Constructor * * jQuery($selector).css($property, $value) * * @param string $selector * The selector * @param string $property * The property * @param mixed $value * The value */ public function __construct($selector, $property, $value) { $this->setFunction(self::FUNC_CSS); $this->setSelector($selector); $this->setArgs([ $property, $value ]); } }
Java
UTF-8
2,623
2.421875
2
[]
no_license
/* Software Testing Club Android application Stefan Klaener sklaener@gmail.com */ package com.echo.stc; import java.util.ArrayList; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; class ArticleAdapter extends ArrayAdapter<Article> { private ArrayList<Article> items; private Context c; public ArticleAdapter(Context context, int textViewResourceId, ArrayList<Article> items) { super(context, textViewResourceId, items); this.items = items; this.c = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.row, null); } try { Article story = items.get(position); if (story != null) { TextView title = (TextView) v.findViewById(R.id.rowText1); if (title != null) { title.setText(story.getTitle()); } ImageView image = (ImageView) v.findViewById(R.id.rowImage); TextView centreText = (TextView) v.findViewById(R.id.centreText); centreText.setText(story.getCentreText()); if (title.getText()!= ""){ if (story.getImageURL().equals("") || story.getImageURL() == null){ //story.getImageBitmap() == null || image.setImageDrawable(c.getResources().getDrawable(R.drawable.icon)); } else { image.setImageBitmap(story.getImageBitmap()); } } else { image.setImageDrawable(c.getResources().getDrawable(R.drawable.blank)); } FrameLayout back = (FrameLayout) v.findViewById(R.id.storyBackground); back.setBackgroundResource(story.getColor()); } } catch (ArrayIndexOutOfBoundsException e){ Log.e("STC", e.toString()); return null; } return v; } public int getItemCount(){ return items.size(); } }
Java
UTF-8
1,903
2.046875
2
[]
no_license
package vn.fpt.fsoft.group3.repository; import vn.fpt.fsoft.group3.entity.Customers; import vn.fpt.fsoft.group3.entity.Orders; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestParam; public interface OrderRepository extends JpaRepository<Orders, Long>{ /* @Query(" select c " + " from Customers c " + " where cast(lower(c.name) as binary) like cast(lower(:name) as binary)") public List<Orders> findCustomerByName(@Param("name") String name); @Query(" select o " + " from Orders o " + " where cast(o.ordercode as binary) = cast(:symbol as binary) as binary) " + " and c.mode = 1 " + " and c.version = (select max(cc.version) from Customers cc where cc.symbol = c.symbol and cc.serial = c.serial and cc.mode = 1) " + " order by c.lastupdate desc" ) public List<Orders> getListOrders(@Param("customercode") String customercode,@Param("ordercode") String ordercode); */ /*@Modifying @Transactional @Query("delete from Contact c where c.id = :id") public void deleteContact(@Param("id") Long id);*/ /*@Query(" select o " + " from Orders o " + " where o.ordercode like ?1 " + " and o.customer.customercode like ?2 " )*/ public List<Orders> findByOrdercodeLikeAndCustomerCustomercodeLikeAndModeAndCustomerMode(String ordercode, String customercode, Integer mode, Integer customermode); @Query(" select max(o.serial) " + " from Orders o " + " where MONTH(o.startdate) = ?1 " + " and YEAR(o.startdate) = ?2 " ) public Integer findMaxSerialInMonthAndYear(Integer month, Integer year); }