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
| 3,730 | 3.65625 | 4 |
[] |
no_license
|
# TOP84.Largest Rectangle In Histogram
### 题目描述

### 解题思路
- 两重循环+剪枝(自己想的方法,不过最后有个case过不去
```cpp
// TL 95/96
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int ans=0;
for(int i=0;i<heights.size();i++){
int _min=heights[i];
if(i&&heights[i]<=heights[i-1])continue;
for(int j=i;j<heights.size();j++){
_min=min(_min,heights[j]);
if(ans>(heights.size()-i)*_min)break;
ans=max(ans,(j-i+1)*_min);
}
}
return ans;
}
};
```
- 分治法
分治法比较风骚,找一个最矮的矩形,计算包括它能构成的最大面积和不包括它能构成的最大面积然后取最大值返回结果
如果包含 s=(end-start)*height_of_minHeight_rectangle
如果不包含 s=max(最矮矩形左边区域构成的最大面积,最矮矩形右边区域构成的最大面积)
```cpp
class solution {
public:
int largestrectanglearea(vector<int>& heights) {
return largest(heights,0,heights.size());
}
int largest(vector<int>&heights,int start,int end){
if(start==end)return 0;
if(start+1==end)return heights[start];
int min_index=0;
for(int i=start;i<end;i++){
if(heights[i]<heights[min_index])min_index=i;
}
return max(heights[min_index]*(end-start),largest(heights,start,min_index),largest(heights,min_index+1,end));
}
};
```
- 线段树+分治
分治过程中每次查找最小高度矩形是依次遍历
用线段树可以优化这个查询过程
```cpp
class SegTreeNode {
public:
int start;
int end;
int min;
SegTreeNode *left;
SegTreeNode *right;
SegTreeNode(int start, int end) {
this->start = start;
this->end = end;
left = right = NULL;
}
};
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if (heights.size() == 0) return 0;
SegTreeNode *root = buildSegmentTree(heights, 0, heights.size() - 1);
return calculateMax(heights, root, 0, heights.size() - 1);
}
int calculateMax(vector<int>& heights, SegTreeNode* root, int start, int end) {
if (start > end) {
return -1;
}
if (start == end) {
return heights[start];
}
int minIndex = query(root, heights, start, end);
int leftMax = calculateMax(heights, root, start, minIndex - 1);
int rightMax = calculateMax(heights, root, minIndex + 1, end);
int minMax = heights[minIndex] * (end - start + 1);
return max( max(leftMax, rightMax), minMax );
}
SegTreeNode *buildSegmentTree(vector<int>& heights, int start, int end) {
if(start>end)return NULL;
SegTreeNode* root = new SegTreeNode(start,end);
if(start==end)root->min=start;
else{
int mid=start+(end-start)/2;
root->left=buildSegmentTree(heights,start,mid);
root->right=buildSegmentTree(heights,mid+1,end);
root->min=heights[root->left->min]>heights[root->right->min]?root->right->min:root->left->min;
}
return root;
}
int query(SegTreeNode *root, vector<int>& heights, int start, int end) {
if(end<root->start||start>root->end)return -1;
if(start<=root->start&&end>=root->end)return root->min;
int left_min_index=query(root->left,heights,start,end);
int right_min_index=query(root->right,heights,start,end);
if(left_min_index==-1)return right_min_index;
if(right_min_index==-1)return left_min_index;
return heights[left_min_index]>heights[right_min_index]?right_min_index:left_min_index;
}
};
```
|
C++
|
UTF-8
| 2,492 | 2.734375 | 3 |
[] |
no_license
|
#include "Engine.h"
namespace Batman
{
Input::Input(HWND hwnd)
{
//save window handle
window = hwnd;
//create DirectInput object
DirectInput8Create(
GetModuleHandle(NULL), //get this app handle
DIRECTINPUT_VERSION,
IID_IDirectInput8, //unique id
(void**)&di, //pointer to di object
NULL
);
//initialise keyboard
di->CreateDevice(
GUID_SysKeyboard, //unique id
&keyboard, //keyboard object
NULL
);
//keyboard data format (standard DI)
keyboard->SetDataFormat(&c_dfDIKeyboard);
//for this window foreground means
//use when in FOREGROUND and give up access
//thereafter; NONEXCLUSIVE
//means it doesn't stop other apps using it
keyboard->SetCooperativeLevel(
window,
DISCL_FOREGROUND | DISCL_NONEXCLUSIVE
);
//Get keyboard control
keyboard->Acquire();
//clear key array
memset(keyState, 0, 256);
//initialise mouse
di->CreateDevice(
GUID_SysMouse, //unique id
&mouse, //mouse object
NULL //NULL
);
//mouse data format (standard DI)
mouse->SetDataFormat(&c_dfDIMouse);
//for this window foreground means
//use when in FOREGROUND and give up access
//thereafter; NONEXCLUSIVE
//means it doesn't stop other apps using it
mouse->SetCooperativeLevel(
window,
DISCL_FOREGROUND | DISCL_NONEXCLUSIVE
);
//get mouse control
mouse->Acquire();
}
Input::~Input()
{
mouse->Release(); //release mouse object
keyboard->Release(); //release keyboard object
di->Release(); //release direct input object
}
void Input::Update()
{
//poll state of the keyboard
keyboard->Poll();
//get state of keys - buffer and pointer to storage
if(!SUCCEEDED(
keyboard->GetDeviceState(256,(LPVOID)&keyState))
)
{
//keyboard device lost, try to re-acquire
keyboard->Acquire();
}
//poll state of the mouse
mouse->Poll();
//get state of mouse - buffer and pointer to storage
if(!SUCCEEDED(
mouse->GetDeviceState(sizeof(DIMOUSESTATE),&mouseState))
)
{
//mouse device lost, try to re-acquire
mouse->Acquire();
}
//get mouse position on screen (not DirectInput)
GetCursorPos(&position);
//get position relative to window origin
ScreenToClient(window, &position);
}
int Input::GetMouseButton(char button)
{
//get whether button is pressed
return (mouseState.rgbButtons[button] & 0x80);
}
};
|
Java
|
UTF-8
| 1,728 | 3.28125 | 3 |
[] |
no_license
|
package leetcode.dp;
import java.util.ArrayList;
import java.util.List;
public class Triangle {
public static void main(String[] args) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> list1 = new ArrayList<Integer>();
list1.add(-1);
List<Integer> list2 = new ArrayList<Integer>();
list2.add(3);
list2.add(2);
List<Integer> list3 = new ArrayList<Integer>();
list3.add(-3);
list3.add(1);
list3.add(-1);
List<Integer> list4 = new ArrayList<Integer>();
list4.add(4);
list4.add(1);
list4.add(8);
list4.add(3);
list.add(list1);
list.add(list2);
list.add(list3);
// list.add(list4);
System.out.println(minimumTotal(list));
}
public static int minimumTotal(List<List<Integer>> triangle) {
int rowNums = triangle.size();
if (rowNums == 0) {
return 0;
}
if(rowNums == 1){
return triangle.get(0).get(0);
}
int[][] dp = new int[rowNums][rowNums];
int minPath = Integer.MAX_VALUE;
dp[0][0] = triangle.get(0).get(0);
for (int i = 1; i < rowNums; i++) {
dp[i][0] += triangle.get(i).get(0) + dp[i-1][0];
dp[i][i] += triangle.get(i).get(i) + dp[i-1][i-1];
}
for (int i = 1; i < rowNums; i++) {
for (int j = 1; j < i; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i - 1][j - 1]) + triangle.get(i).get(j);
}
}
for (int k = 0; k < rowNums; k++) {
minPath = Math.min(dp[rowNums-1][k], minPath);
}
return minPath;
}
}
|
SQL
|
UTF-8
| 22,334 | 2.703125 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.0.10.14
-- http://www.phpmyadmin.net
--
-- Host: localhost:3306
-- Generation Time: Jun 09, 2017 at 02:16 PM
-- Server version: 5.6.31-77.0-log
-- PHP Version: 5.4.31
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `codinttm_Socialweb`
--
-- --------------------------------------------------------
--
-- Table structure for table `friends`
--
CREATE TABLE IF NOT EXISTS `friends` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user1_id` int(11) NOT NULL,
`user2_id` int(11) NOT NULL,
`datemade` datetime NOT NULL,
`accepted` enum('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `user1_id` (`user1_id`),
KEY `user2_id` (`user2_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=39 ;
--
-- Dumping data for table `friends`
--
INSERT INTO `friends` (`id`, `user1_id`, `user2_id`, `datemade`, `accepted`) VALUES
(1, 15, 16, '2017-05-13 00:59:46', '1'),
(2, 15, 17, '2017-05-13 00:59:59', '1'),
(3, 15, 18, '2017-05-13 04:40:21', '1'),
(4, 15, 19, '2017-05-13 04:47:13', '1'),
(5, 15, 21, '2017-05-13 05:09:14', '1'),
(6, 15, 23, '2017-05-13 06:17:19', '1'),
(7, 15, 28, '2017-05-13 13:22:20', '1'),
(8, 29, 15, '2017-05-13 13:53:41', '1'),
(9, 33, 15, '2017-05-14 07:21:31', '1'),
(10, 15, 27, '2017-05-14 08:51:10', '0'),
(11, 34, 15, '2017-05-15 03:08:18', '1'),
(12, 35, 15, '2017-05-15 05:20:05', '1'),
(13, 36, 15, '2017-05-15 09:47:54', '1'),
(14, 37, 15, '2017-05-15 13:50:39', '1'),
(15, 39, 15, '2017-05-16 13:15:16', '1'),
(16, 40, 15, '2017-05-16 16:06:58', '1'),
(17, 42, 15, '2017-05-17 11:03:09', '1'),
(18, 43, 15, '2017-05-17 15:37:17', '1'),
(19, 44, 15, '2017-05-17 21:46:24', '1'),
(20, 45, 15, '2017-05-18 02:49:38', '1'),
(21, 46, 15, '2017-05-18 14:55:11', '1'),
(22, 47, 15, '2017-05-19 01:36:50', '1'),
(23, 48, 15, '2017-05-20 17:07:22', '1'),
(24, 49, 15, '2017-05-21 23:54:02', '1'),
(25, 50, 15, '2017-05-22 03:04:32', '1'),
(26, 51, 15, '2017-05-22 22:02:30', '1'),
(27, 54, 15, '2017-05-23 06:00:11', '1'),
(28, 56, 15, '2017-05-24 07:20:50', '1'),
(29, 57, 15, '2017-05-24 15:36:48', '1'),
(30, 58, 15, '2017-05-25 06:53:32', '1'),
(31, 60, 15, '2017-05-26 02:21:47', '1'),
(32, 61, 15, '2017-05-27 05:36:30', '1'),
(33, 62, 15, '2017-05-30 01:45:55', '1'),
(34, 63, 15, '2017-05-31 16:52:10', '1'),
(35, 64, 15, '2017-06-05 06:24:01', '1'),
(36, 65, 15, '2017-06-07 17:50:04', '1'),
(37, 66, 15, '2017-06-08 00:08:51', '1'),
(38, 67, 15, '2017-06-09 07:49:08', '1');
-- --------------------------------------------------------
--
-- Table structure for table `likes`
--
CREATE TABLE IF NOT EXISTS `likes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`liker_id` int(11) NOT NULL,
`status_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `liker_id` (`liker_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;
--
-- Dumping data for table `likes`
--
INSERT INTO `likes` (`id`, `liker_id`, `status_id`) VALUES
(3, 15, 1),
(31, 15, 10);
-- --------------------------------------------------------
--
-- Table structure for table `notifications`
--
CREATE TABLE IF NOT EXISTS `notifications` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`initiator_id` int(11) NOT NULL,
`app` varchar(255) NOT NULL,
`note` varchar(255) NOT NULL,
`did_read` enum('0','1') NOT NULL DEFAULT '0',
`date_time` datetime NOT NULL,
`status_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `initiator_id` (`initiator_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=53 ;
--
-- Dumping data for table `notifications`
--
INSERT INTO `notifications` (`id`, `user_id`, `initiator_id`, `app`, `note`, `did_read`, `date_time`, `status_id`) VALUES
(1, 15, 19, 'Accepted Request', 'juanjose accepted your friend request:<br /><a href="user.php?u=juanjose">Say something to juanjose</a>', '1', '2017-05-13 04:50:41', NULL),
(2, 15, 28, 'Accepted Request', 'alok accepted your friend request:<br /><a href="user.php?u=alok">Say something to alok</a>', '1', '2017-05-13 13:24:24', NULL),
(4, 29, 15, 'Status Post', 'RHNyOWRr', '0', '2017-05-13 13:56:30', 9),
(5, 16, 15, 'Status Post', 'RHNyOWRr', '0', '2017-05-13 13:56:30', 9),
(6, 18, 15, 'Status Post', 'RHNyOWRr', '0', '2017-05-13 13:56:30', 9),
(7, 19, 15, 'Status Post', 'RHNyOWRr', '0', '2017-05-13 13:56:30', 9),
(8, 21, 15, 'Status Post', 'RHNyOWRr', '0', '2017-05-13 13:56:30', 9),
(9, 23, 15, 'Status Post', 'RHNyOWRr', '0', '2017-05-13 13:56:30', 9),
(10, 28, 15, 'Status Post', 'RHNyOWRr', '0', '2017-05-13 13:56:30', 9),
(11, 29, 15, 'Status Post', 'RHNyMTBkaw', '1', '2017-05-13 13:57:37', 10),
(12, 16, 15, 'Status Post', 'RHNyMTBkaw', '0', '2017-05-13 13:57:37', 10),
(13, 18, 15, 'Status Post', 'RHNyMTBkaw', '0', '2017-05-13 13:57:37', 10),
(14, 19, 15, 'Status Post', 'RHNyMTBkaw', '0', '2017-05-13 13:57:37', 10),
(15, 21, 15, 'Status Post', 'RHNyMTBkaw', '0', '2017-05-13 13:57:37', 10),
(16, 23, 15, 'Status Post', 'RHNyMTBkaw', '0', '2017-05-13 13:57:37', 10),
(17, 28, 15, 'Status Post', 'RHNyMTBkaw', '0', '2017-05-13 13:57:37', 10),
(19, 15, 42, 'Status Reply', 'RHNyM2Rr', '1', '2017-05-17 11:07:14', NULL),
(20, 42, 15, 'Status Reply', 'RHNyM2Rr', '0', '2017-05-17 14:17:13', NULL),
(21, 15, 47, 'Status Post', 'RHNyMTRkaw', '1', '2017-05-19 02:12:16', 14),
(22, 47, 15, 'Status Reply', 'RHNyMTRkaw', '0', '2017-05-19 07:14:01', NULL),
(48, 15, 62, 'Status Reply', 'RHNyM2Rr', '1', '2017-05-30 01:47:19', NULL),
(49, 42, 62, 'Status Reply', 'RHNyM2Rr', '0', '2017-05-30 01:47:19', NULL),
(50, 15, 62, 'Status Reply', 'RHNyM2Rr', '1', '2017-05-30 01:47:37', NULL),
(51, 42, 62, 'Status Reply', 'RHNyM2Rr', '0', '2017-05-30 01:47:37', NULL),
(52, 15, 17, 'Accepted Request', 'giofrak accepted your friend request:<br /><a href="user.php?u=giofrak">Say something to giofrak</a>', '1', '2017-05-30 18:21:04', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `reports`
--
CREATE TABLE IF NOT EXISTS `reports` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`reporter_id` int(11) NOT NULL,
`status_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `reporter_id` (`reporter_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `reports`
--
INSERT INTO `reports` (`id`, `reporter_id`, `status_id`) VALUES
(1, 15, 14);
-- --------------------------------------------------------
--
-- Table structure for table `status`
--
CREATE TABLE IF NOT EXISTS `status` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`osid` int(11) DEFAULT NULL,
`account_id` int(11) NOT NULL,
`author_id` int(11) NOT NULL,
`type` enum('a','b','c','d') NOT NULL,
`data` longtext NOT NULL,
`postdate` datetime NOT NULL,
`postimage` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `account_id` (`account_id`),
KEY `author_id` (`author_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=19 ;
--
-- Dumping data for table `status`
--
INSERT INTO `status` (`id`, `osid`, `account_id`, `author_id`, `type`, `data`, `postdate`, `postimage`) VALUES
(3, 3, 15, 15, 'a', 'Simple CSS Loader #css \nhttp://codepen.io/dsr/pen/XRrwxP', '2017-05-12 15:50:23', NULL),
(4, 4, 15, 15, 'a', '<img class="img-responsive" src="permUploads/darshan1494605617.jpg" />', '2017-05-12 16:13:42', 'darshan1494605617.jpg'),
(6, 6, 15, 15, 'a', 'Funky Sidebar [ HTML CSS ]\nhttps://codepen.io/dsr/pen/mmLqLr\nCodepen Link - https://codepen.io/dsr/pen/mmLqLr', '2017-05-13 04:28:49', NULL),
(9, 9, 15, 15, 'a', 'Paint Webapp [ p5.js ]\nhttp://codepen.io/dsr/pen/peXzyK\nCodepen link - http://codepen.io/dsr/pen/peXzyK', '2017-05-13 13:56:30', NULL),
(10, 10, 15, 15, 'a', 'Toggle Button [ CSS ]\nhttp://codepen.io/dsr/pen/ryENWx\nCodepen link - http://codepen.io/dsr/pen/ryENWx', '2017-05-13 13:57:37', NULL),
(12, 3, 42, 42, 'b', 'Very nice!!', '2017-05-17 11:07:14', NULL),
(13, 3, 15, 15, 'b', 'thanks mate', '2017-05-17 14:17:13', NULL),
(14, 14, 47, 47, 'a', 'no entiendo ahora este sitio web :S', '2017-05-19 02:12:16', NULL),
(15, 14, 15, 15, 'b', 'En este sitio web puedes publicar enlaces de códigos, preguntar dudas, publicar trucos, etc. Sólo para codificadores', '2017-05-19 07:14:01', NULL),
(18, 3, 62, 62, 'b', 'Thats cool!', '2017-05-30 01:47:37', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `useroptions`
--
CREATE TABLE IF NOT EXISTS `useroptions` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`background` varchar(255) NOT NULL,
`question` varchar(255) DEFAULT NULL,
`answer` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(25) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`gender` enum('m','f') DEFAULT NULL,
`website` varchar(255) DEFAULT NULL,
`country` varchar(255) DEFAULT NULL,
`userlevel` enum('a','b','c','d') NOT NULL DEFAULT 'a',
`avatar` varchar(255) DEFAULT NULL,
`ip` varchar(255) NOT NULL,
`signup` datetime NOT NULL,
`lastlogin` datetime NOT NULL,
`notescheck` datetime NOT NULL,
`activated` enum('0','1') NOT NULL DEFAULT '0',
`bio_data` mediumtext,
`city` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`,`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=68 ;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `email`, `password`, `gender`, `website`, `country`, `userlevel`, `avatar`, `ip`, `signup`, `lastlogin`, `notescheck`, `activated`, `bio_data`, `city`) VALUES
(15, 'darshan', 'darshan3217@gmail.com', '5c0ec6e2d6a7da137ed29cc65d9818956a60bc71', 'm', 'http://codingflag.in', NULL, 'a', '623138125892.jpg', '103.87.55.110', '2017-05-12 15:21:21', '2017-06-09 07:58:12', '2017-05-12 15:21:21', '1', 'I am not qualified for any of this.', 'Mumbai'),
(16, 'shahzad', 'shahzadwaris81@gmail.com', '6b1992eb8cf675641ccba473874f6fdae4892c71', NULL, NULL, NULL, 'a', NULL, '39.60.167.254', '2017-05-12 16:51:41', '2017-05-12 16:58:37', '2017-05-12 16:51:41', '1', NULL, NULL),
(17, 'giofrak', 'casgio.c@gmail.com', '9d4445a9a534e5a7ab90a7bb6925f008776f26ca', NULL, NULL, NULL, 'a', NULL, '190.236.73.249', '2017-05-12 20:09:10', '2017-05-30 18:20:50', '2017-05-12 20:09:10', '1', NULL, NULL),
(18, 'steven17', 'myweb017@gmail.com', 'a143e8cf75e2d37b9332ba958dace613e7c73cb1', NULL, NULL, NULL, 'a', NULL, '60.50.160.112', '2017-05-13 03:52:43', '2017-05-13 04:37:43', '2017-05-13 03:52:43', '1', NULL, NULL),
(19, 'juanjose', 'jhanjhuse@gmail.com', '01b307acba4f54f55aafc33bb06bbbf6ca803e9a', NULL, NULL, NULL, 'a', NULL, '167.0.3.235', '2017-05-13 04:40:48', '2017-05-13 04:49:14', '2017-05-13 04:40:48', '1', NULL, NULL),
(20, 'Vinit', 'dev.vinit@outlook.com', '9986e7486d616d0340a425cb89f86ddee3cd68bc', NULL, NULL, NULL, 'a', NULL, '47.29.66.211', '2017-05-13 04:51:24', '2017-05-13 04:51:24', '2017-05-13 04:51:24', '0', NULL, NULL),
(21, 'JustinG', 'justingeluzofficial@yahoo.com', '4ae41d11e2b7787dd9d17ddb842feb1844a5878b', NULL, NULL, NULL, 'a', NULL, '49.149.100.109', '2017-05-13 05:07:50', '2017-05-13 05:07:50', '2017-05-13 05:07:50', '1', NULL, NULL),
(22, 'user', 'user221user@gmail.com', '540fff0e45e46290fb994ff79a4b5692e8f89342', NULL, NULL, NULL, 'a', NULL, '47.9.189.76', '2017-05-13 05:09:27', '2017-05-13 05:09:27', '2017-05-13 05:09:27', '0', NULL, NULL),
(23, 'wellget6', 'wellget6@gmail.com', 'cc4624b1fbe6c20e5fa951ca9d3b8b42d31da19f', NULL, NULL, NULL, 'a', NULL, '123.136.151.207', '2017-05-13 06:05:25', '2017-05-13 06:05:25', '2017-05-13 06:05:25', '1', NULL, NULL),
(24, 'Raj', 'raju.panchal710@gmail.com', '977ddd13b1074450e021f2efe93f39e7e03ce006', NULL, NULL, NULL, 'a', NULL, '203.88.134.109', '2017-05-13 06:38:12', '2017-05-13 06:38:12', '2017-05-13 06:38:12', '0', NULL, NULL),
(25, 'awalimam', 'awaluzzal42@gmail.com', '9b660bf29f174712914545e615fd5e2ddf51a208', NULL, NULL, NULL, 'a', NULL, '103.198.137.253', '2017-05-13 09:04:09', '2017-05-13 09:04:09', '2017-05-13 09:04:09', '0', NULL, NULL),
(26, 'kajan', 'nagakajan@gmail.com', '9082f04afa99c86773939b006342694448029b98', NULL, NULL, NULL, 'a', NULL, '112.134.112.125', '2017-05-13 09:33:26', '2017-05-13 09:38:11', '2017-05-13 09:33:26', '1', NULL, NULL),
(27, 'ZakaCoding', 'zakanoor@outlook.co.id', 'e69363529f5f37e4b4d1c906cd2ea29ac876858b', NULL, NULL, NULL, 'a', NULL, '114.125.164.175', '2017-05-13 10:21:28', '2017-05-13 10:21:28', '2017-05-13 10:21:28', '1', NULL, NULL),
(28, 'alok', '13alokshukla@gmail.com', '0c4ffcb6ada38674d2ce31d4023a09ca9cb50433', NULL, NULL, NULL, 'a', NULL, '43.255.220.226', '2017-05-13 13:14:18', '2017-05-13 13:19:10', '2017-05-13 13:14:18', '1', NULL, NULL),
(29, 'dsr', 'darshanrajadhyaksha22@gmail.com', '5c0ec6e2d6a7da137ed29cc65d9818956a60bc71', NULL, NULL, NULL, 'a', '342845261702.png', '43.255.223.109', '2017-05-13 13:45:45', '2017-05-19 00:18:47', '2017-05-13 13:45:45', '1', NULL, NULL),
(30, 'inehosa1', 'chanix1998@gmail.com', 'dcd1b376be6ec2c03af58d14aa4ef9a9f6b8d02f', NULL, NULL, NULL, 'a', NULL, '181.49.188.5', '2017-05-13 18:45:08', '2017-05-13 18:45:08', '2017-05-13 18:45:08', '0', NULL, NULL),
(31, 'josbert', 'hernandezjosbert@gmail.com', '57505ccca939ed87adfa9432ec9ba513dd643c19', NULL, NULL, NULL, 'a', NULL, '190.78.155.234', '2017-05-13 21:02:39', '2017-05-13 21:02:39', '2017-05-13 21:02:39', '0', NULL, NULL),
(32, 'qwe', 'qwe@mail.com', '141f87be1330a105a87923f4ee6383bd7de46541', NULL, NULL, NULL, 'a', NULL, '109.172.209.63', '2017-05-14 00:27:04', '2017-05-14 00:27:04', '2017-05-14 00:27:04', '0', NULL, NULL),
(33, 'qweqweqwe', 'wh7q0@wimsg.com', '141f87be1330a105a87923f4ee6383bd7de46541', NULL, NULL, NULL, 'a', NULL, '109.172.209.63', '2017-05-14 07:21:16', '2017-05-14 07:21:39', '2017-05-14 07:21:16', '1', NULL, NULL),
(34, 'efren123', 'esbe.efre@hotmail.com', '40d43ee449c64ab3faa48add80a61016c30a4a79', NULL, NULL, NULL, 'a', NULL, '190.233.151.178', '2017-05-15 03:07:53', '2017-05-15 03:08:28', '2017-05-15 03:07:53', '1', NULL, NULL),
(35, 'maherbilal', 'maherbilal70@gmail.com', '5c774974bfbe5bd2f0a7fcba7dbb4f9c8d383b86', NULL, NULL, NULL, 'a', NULL, '39.45.55.242', '2017-05-15 05:14:30', '2017-05-29 04:31:59', '2017-05-15 05:14:30', '1', NULL, NULL),
(36, 'ZaouiAymen', 'zaoui.aymen03@gmail.com', 'd5495f929afc4ca7eab72faea0650f61eb71de52', NULL, NULL, NULL, 'a', NULL, '41.228.14.134', '2017-05-15 09:40:55', '2017-05-15 09:48:02', '2017-05-15 09:40:55', '1', NULL, NULL),
(37, 'asadujjaman', 'asadujjamanrajib@yahoo.com', 'abf0a50346e923e0cc8a8d3c5a39a24736c89547', NULL, NULL, NULL, 'a', NULL, '103.63.159.90', '2017-05-15 13:47:58', '2017-05-15 13:50:45', '2017-05-15 13:47:58', '1', NULL, NULL),
(38, 'rizwan', 'rizwanrana727@gmail.com', '7c4a8d09ca3762af61e59520943dc26494f8941b', NULL, NULL, NULL, 'a', NULL, '111.68.104.129', '2017-05-16 04:18:34', '2017-05-16 04:38:40', '2017-05-16 04:18:34', '0', NULL, NULL),
(39, 'aj160', 'ahsan-jamal@hotmail.com', 'b1b3773a05c0ed0176787a4f1574ff0075f7521e', NULL, NULL, NULL, 'a', NULL, '42.201.248.146', '2017-05-16 13:14:55', '2017-05-16 13:15:24', '2017-05-16 13:14:55', '1', NULL, NULL),
(40, 'rolas91', 'rsanchezbaltodano@gmail.com', 'e801bacc977257a802949583bdcd5de76a6620c7', NULL, NULL, NULL, 'a', NULL, '64.71.171.84', '2017-05-16 15:55:55', '2017-05-16 16:07:23', '2017-05-16 15:55:55', '1', NULL, NULL),
(41, 'edias', 'edu16rodriguesdias@hotmail.com', 'a5e25e2a03824068b60d1f8b69411565af8f0464', NULL, NULL, NULL, 'a', NULL, '187.108.33.246', '2017-05-17 10:37:30', '2017-05-17 10:37:30', '2017-05-17 10:37:30', '0', NULL, NULL),
(42, 'ediaS1812', 'edu16rodrigues@gmail.com', '7c4a8d09ca3762af61e59520943dc26494f8941b', NULL, NULL, NULL, 'a', NULL, '187.108.33.246', '2017-05-17 10:48:02', '2017-05-17 11:05:52', '2017-05-17 10:48:02', '1', NULL, NULL),
(43, 'RamonAdriano', 'ramonomar151878@gmail.com', '88bce84a0e5d220c8787712bb7cd818319c3eaab', NULL, NULL, NULL, 'a', NULL, '189.204.113.115', '2017-05-17 15:33:00', '2017-05-17 15:36:32', '2017-05-17 15:33:00', '1', NULL, NULL),
(44, 'EkZa', 'ekza97@gmail.com', '74471feaafbbe479927a3744c6062917bb199f89', NULL, NULL, NULL, 'a', NULL, '125.162.245.192', '2017-05-17 21:41:44', '2017-05-17 21:46:46', '2017-05-17 21:41:44', '1', NULL, NULL),
(45, 'theoneaboveall', 'jaysoncleofas22@gmail.com', 'b1bbae47d368b0858840f502687095550d3cdb60', NULL, NULL, NULL, 'a', NULL, '112.198.72.163', '2017-05-18 02:33:05', '2017-05-18 02:49:57', '2017-05-18 02:33:05', '1', NULL, NULL),
(46, 'mangao05', 'mangao_jeric@yahoo.com', 'b2df5845a5e8376f4a6e87b396440224915fc838', NULL, NULL, NULL, 'a', NULL, '121.54.32.173', '2017-05-18 14:44:21', '2017-05-18 14:57:26', '2017-05-18 14:44:21', '1', NULL, NULL),
(47, 'avancini1', 'vanciniap@gmail.com', '9828cc454d436a1c36e122f64500d3c9da982345', NULL, NULL, NULL, 'a', NULL, '190.206.176.47', '2017-05-18 22:58:42', '2017-05-19 02:06:33', '2017-05-18 22:58:42', '1', NULL, NULL),
(48, 'gveriello', 'qdg99098@tipsb.com', '1dbfdcc77df30e10a4acfb6629260bbb1b0b6f03', NULL, NULL, NULL, 'a', NULL, '87.7.58.99', '2017-05-20 17:06:58', '2017-05-20 17:09:13', '2017-05-20 17:06:58', '1', NULL, NULL),
(49, 'fgelsano', 'fgelsano.virus@gmail.com', '8473dd1dfb6e3187c82760baccab53be9d6c4f99', NULL, NULL, NULL, 'a', NULL, '180.190.204.83', '2017-05-21 13:50:49', '2017-05-22 04:13:37', '2017-05-21 13:50:49', '1', NULL, NULL),
(50, 'abbycbcngn', 'marianabigail.cabacungan@benilde.edu.ph', '9ff8b6652a81d324a55cde1b940c9f92ede1d0ec', NULL, NULL, NULL, 'a', NULL, '124.83.99.142', '2017-05-22 03:03:41', '2017-05-22 03:04:52', '2017-05-22 03:03:41', '1', NULL, NULL),
(51, 'alexlhc906', 'luisstation@hotmail.com', '02a5c465ff8050104c39ca692f824182c9143a00', NULL, NULL, NULL, 'a', NULL, '200.66.94.162', '2017-05-22 22:02:09', '2017-05-22 22:03:07', '2017-05-22 22:02:09', '1', NULL, NULL),
(52, 'darshana', 'darshanr562@gmail.com', '9c0e69c50937bcb57978a4c8fe64bda4905269d2', NULL, NULL, NULL, 'a', NULL, '43.255.223.109', '2017-05-23 03:31:15', '2017-05-23 03:31:15', '2017-05-23 03:31:15', '0', NULL, NULL),
(53, 'daa', 'dsrdkkdsrdkkk32123423@gmaila.cc', '20eabe5d64b0e216796e834f52d61fd0b70332fc', NULL, NULL, NULL, 'a', NULL, '43.255.223.109', '2017-05-23 03:32:57', '2017-05-23 03:32:57', '2017-05-23 03:32:57', '0', NULL, NULL),
(54, 'djrcsanvictores', 'rcsnvctrs@gmail.com', 'd0a3fe7df70929e0922b3ef23b22eed2b6cfbe0d', NULL, NULL, NULL, 'a', NULL, '180.191.151.242', '2017-05-23 05:54:46', '2017-05-23 06:01:02', '2017-05-23 05:54:46', '1', NULL, NULL),
(55, 'Akshay', 'Sawantakshay08@gmail.Com', 'a79b30a5ff81460be50db86109358126ac6a597f', NULL, NULL, NULL, 'a', NULL, '49.128.160.54', '2017-05-24 06:27:04', '2017-05-24 16:29:42', '2017-05-24 06:27:04', '0', NULL, NULL),
(56, 'Imdk', 'darshanraja32@gmail.com', '7c4a8d09ca3762af61e59520943dc26494f8941b', NULL, NULL, NULL, 'a', NULL, '43.255.223.48', '2017-05-24 06:53:14', '2017-05-24 07:21:19', '2017-05-24 06:53:14', '1', NULL, NULL),
(57, 'johnaustingeluz', 'justingeluzofficial@gmail.com', '4ae41d11e2b7787dd9d17ddb842feb1844a5878b', NULL, NULL, NULL, 'a', NULL, '49.146.146.221', '2017-05-24 15:31:13', '2017-05-24 15:31:13', '2017-05-24 15:31:13', '1', NULL, NULL),
(58, 'waqas4978', 'm.waqas4978@gmail.com', '7b6ee52ad59e2f5351b67857afe34b3c52c0e3ce', NULL, NULL, NULL, 'a', NULL, '39.46.231.200', '2017-05-25 06:48:30', '2017-05-25 06:54:12', '2017-05-25 06:48:30', '1', NULL, NULL),
(59, 'kapilthakur1496', 'kapil.thakur1496@gmail.com', '5139d91bde5a89373c53175c91a1cc5e906eae18', NULL, NULL, NULL, 'a', NULL, '49.207.53.59', '2017-05-25 18:08:27', '2017-05-25 18:13:40', '2017-05-25 18:08:27', '0', NULL, NULL),
(60, 'john', 'johnwick12@outlook.es', '26671fe93677348b4c36cb220b7ce1123d5ed336', NULL, NULL, NULL, 'a', NULL, '190.212.159.51', '2017-05-26 02:21:13', '2017-05-26 02:22:08', '2017-05-26 02:21:13', '1', NULL, NULL),
(61, 'Nitishnce', 'nitisharyan93@gmail.com', 'f16684fe75e12b7b09318014b3d28c180ba744b7', NULL, NULL, NULL, 'a', NULL, '101.63.19.147', '2017-05-27 05:29:51', '2017-05-29 17:04:48', '2017-05-27 05:29:51', '1', NULL, NULL),
(62, 'jonjie0317', 'jonjie17@outlook.com', '371d128addebe293d35ed12f6b3dcf7cfc7614fc', NULL, NULL, NULL, 'a', NULL, '122.54.119.169', '2017-05-30 01:44:14', '2017-05-30 01:46:12', '2017-05-30 01:44:14', '1', NULL, NULL),
(63, 'rats5200', 'tiwiinzo.07@gmail.com', 'c519356fef37e55897de4228f5b1407d2e9ed053', NULL, NULL, NULL, 'a', NULL, '179.7.94.65', '2017-05-31 16:45:20', '2017-05-31 16:50:24', '2017-05-31 16:45:20', '1', NULL, NULL),
(64, 'ibrahim69', 'nuzulianuzul@gmail.com', 'a765fd044fa7fd99a7b2d7c809e2363b778d4b56', NULL, NULL, NULL, 'a', NULL, '125.166.231.223', '2017-06-05 06:22:54', '2017-06-05 06:24:18', '2017-06-05 06:22:54', '1', NULL, NULL),
(65, 'giiacommo', 'edwin15_94@hotmail.com', 'd59db0f483ff44ce188f8d19830fd4e9b1413d24', NULL, NULL, NULL, 'a', NULL, '177.238.251.25', '2017-06-07 17:49:20', '2017-06-07 18:07:09', '2017-06-07 17:49:20', '1', NULL, NULL),
(66, 'deadsans', 'yuossef96@gmail.com', '1f418775d4147d23457d5cbc2c232cf01f3e7306', NULL, NULL, NULL, 'a', NULL, '187.146.112.201', '2017-06-08 00:03:37', '2017-06-08 00:09:03', '2017-06-08 00:03:37', '1', NULL, NULL),
(67, 'masterboy', 'sanketbaviskar01@gmail.com', 'd2a9fefea7f21ecf6fb6364f5ef9cf12d706cb59', NULL, NULL, NULL, 'a', NULL, '103.76.57.123', '2017-06-09 07:44:37', '2017-06-09 07:46:47', '2017-06-09 07:44:37', '1', NULL, NULL);
--
-- Constraints for dumped tables
--
--
-- Constraints for table `friends`
--
ALTER TABLE `friends`
ADD CONSTRAINT `friends_ibfk_1` FOREIGN KEY (`user1_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `friends_ibfk_2` FOREIGN KEY (`user2_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `likes`
--
ALTER TABLE `likes`
ADD CONSTRAINT `likes_ibfk_1` FOREIGN KEY (`liker_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `notifications`
--
ALTER TABLE `notifications`
ADD CONSTRAINT `notifications_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `notifications_ibfk_2` FOREIGN KEY (`initiator_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `reports`
--
ALTER TABLE `reports`
ADD CONSTRAINT `reports_ibfk_1` FOREIGN KEY (`reporter_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `status`
--
ALTER TABLE `status`
ADD CONSTRAINT `status_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `users` (`id`),
ADD CONSTRAINT `status_ibfk_2` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`);
--
-- Constraints for table `useroptions`
--
ALTER TABLE `useroptions`
ADD CONSTRAINT `useroptions_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java
|
UTF-8
| 651 | 2.9375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package kilim.test.ex;
import kilim.Pausable;
public class ExFlow {
void loop() throws Pausable {
ExA a = null;
int i;
for (i = 0; i < 10; i++) {
if (i < 5) {
a = new ExC();
} else {
a = new ExD();;
}
}
// at join, the stack must have types of [I,Lkilim.test.ex.ExFlow; and Lkilim.test.ex.ExA;
// local vars-> 0:Lkilim.test.ex.ExFlow; 1:Lkilim.test.ex.ExA; 2:int 3:UNDEFINED
int x = 10 * join(a);
System.out.println(i);
System.out.println(x);
}
int join(ExA a) throws Pausable { return 10;}
}
|
Markdown
|
UTF-8
| 1,830 | 3.734375 | 4 |
[] |
no_license
|
### 130. 被围绕的区域
难度:Middle
相关话题:`深度优先搜索`、`广度优先搜索`、`并查集`
给定一个二维的矩阵,包含 `'X'` 和 `'O'` (**字母 O** )。
找到所有被 `'X'` 围绕的区域,并将这些区域里所有的 `'O'` 用 `'X'` 填充。
**示例:**
```
X X X X
X O O X
X X O X
X O X X
```
运行你的函数后,矩阵变为:
```
X X X X
X X X X
X X X X
X O X X
```
**解释:**
被围绕的区间不会存在于边界上,换句话说,任何边界上的 `'O'` 都不会被填充为 `'X'` 。 任何不在边界上,或不与边界上的 `'O'` 相连的 `'O'` 最终都会被填充为 `'X'` 。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
-----
思路:
题目也给了提示,只需要对边上的`O`进行`dfs`遍历,找出所有和它相连的`O`,改变为`S`。
最后再将所有的`O`改变为`X`,将所有的`S`改变为`O`。
```
/**
* @param {character[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var solve = function(board) {
if(board.length===0)return
let m=board.length,n=board[0].length
let moves=[[-1,0],[1,0],[0,-1],[0,1]]
function dfs([x,y]){
board[x][y]="S"
for(let [dx,dy] of moves){
let nx=x+dx,ny=y+dy
if(nx<0 || ny<0 || nx>=m || ny>=n)continue
if(board[nx][ny]!=="O")continue
dfs([nx,ny])
}
}
for(let i=0;i<m;i++){
if(board[i][0]==="O")dfs([i,0])
if(board[i][n-1]==="O")dfs([i,n-1])
}
for(let i=1;i<n-1;i++){
if(board[0][i]==="O")dfs([0,i])
if(board[m-1][i]==="O")dfs([m-1,i])
}
for(let i=0;i<m;i++){
for(let j=0;j<n;j++){
if(board[i][j]==="O")board[i][j]="X"
else if(board[i][j]==="S")board[i][j]="O"
}
}
};
```
|
Java
|
UTF-8
| 1,506 | 2.234375 | 2 |
[] |
no_license
|
package com.example.medical_record.service.impl;
import com.example.medical_record.dao.RecordDao;
import com.example.medical_record.dao.UserDao;
import com.example.medical_record.entity.po.Record;
import com.example.medical_record.entity.po.User;
import com.example.medical_record.entity.vo.RecordVo;
import com.example.medical_record.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@Service
@Transactional
public class RecordServiceImpl implements RecordService {
@Autowired
private RecordDao recordDao;
@Autowired
private UserDao userDao;
@Override
public void addRecord(RecordVo recordVo, Integer did) {
Record record = new Record();
User user = userDao.findUserByName(recordVo.getUserName());
if (user == null) {
throw new RuntimeException("该患者不存在!");
}
record.setUid(user.getId());
record.setDid(did);
record.setDescription(recordVo.getDescription());
record.setState(recordVo.getState());
record.setDate(new Date(System.currentTimeMillis()));
recordDao.addRecord(record);
}
@Override
public void deleteRecord(Integer id) {
recordDao.deleteById(id);
}
@Override
public void updateRecord(RecordVo recordVo) {
recordDao.updateRecord(recordVo);
}
}
|
JavaScript
|
UTF-8
| 6,348 | 2.65625 | 3 |
[] |
no_license
|
import annyang from 'annyang'
export default class Speech{
constructor(scroll, notify = false){
fetch('/resources/jokes.json').then(res => res.json())
.then(jokes => this.jokes = jokes).then(jokes => localStorage.setItem('jokes', JSON.stringify(jokes)))
.catch(() => this.jokes = JSON.parse(localStorage.getItem('jokes')) || []);
this.scroll = scroll;
this.notify = notify;
this.a = annyang;
this.a.setLanguage('de-DE');
this.a.addCommands({
"debug an": () => this.a.debug(true),
"debug aus": () => this.a.debug(false),
"Hallo": () => this.speak("Hallo!"),
"Kopf oder Zahl": () => this.speak(this.randomPick(['Kopf', 'Zahl'])),
"(nenn mir) (eine) Zahl zwischen :low und :high": (low, high) => this.speak(Math.floor(Math.random()*(~~high - ~~low + 1) + ~~low)),
"(ich) suche nach *wort": (query) => this.search(query),
"(hey Alexa) spiel despacito": () => this.goto("https://www.youtube.com/watch?v=kJQP7kiw5Fk"),
"(hey Alexa) play despacito": () => this.goto("https://www.youtube.com/watch?v=kJQP7kiw5Fk"),
"Allahu akbar": () => this.goto("https://www.youtube.com/watch?v=aCUAXVueCbk"),
"sage :wort": (wort) => this.speak(wort),
"(Seite) ganz nach oben": () => this.scroll.scrollToPageTop(),
"(Seite) ganz nach unten": () => this.scroll.scrollToPageBottom(),
"(Seite) zum Anfang": () => this.scroll.first(),
"(Seite) nach oben": () => this.scroll.prev(),
"(Seite) nach unten": () => this.scroll.next(),
"(Seite) zum Ende": () => this.scroll.last(),
"(Seite) nächster Abschnitt": () => this.scroll.next(),
"(Seite) weiter": () => this.scroll.next(),
"(Seite) zurück": () => this.scroll.prev(),
"(Seite) vorheriger Abschnitt": () => this.scroll.prev(),
"buchstabiere :wort": (wort) => this.spell(wort),
"erzähl (mir) einen Witz": () => this.speak(this.randomPick(this.jokes)),
"(Oh) magische Miesmuschel *frage": () => this.speak(this.randomPick(['Ja','Definitiv','Vielleicht','Nein','Auf gar keinen Fall'])),
"Stein Schere Papier": () => this.speak(this.randomPick(['Stein','Schere','Papier'])),
"Wo findet :event statt": (event) => this.speak(this.schedule({event}).location),
"Wann findet :event statt": (event) => this.speak(this.schedule({event}).start),
"Was ist (der)(die)(das) :event": (event) => this.speak(this.schedule({event}).description),
"Was findet am :day um :time statt": (day, time) => this.speak(this.schedule({day, time}).name),
"Was findet am :day statt": (day) => this.speak(this.schedule({day})),
"JBS": () => this.speak('Jay B S is love, Jay B S is life','en-US'),
"GPS": () => this.speak('Jay B S is love, Jay B S is life','en-US'),
"Marco": () => this.speak('Polo'),
"Ich liebe dich": () => this.speak('Ha, gay!!!','en-US'),
"Wie geht es dir": () => this.speak('Ich kann nicht klagen, das wurde nicht vorgesehen'),
"Was ist die Fachschaft": () => this.speak('Jeder Student eines Fachbereichs. Der Fachschaftsrat sind die gewählten Vertreter, der Fachschaftsraum der Sitz des Rates'),
"Dahm": () => this.speak("Hätten sie in MCI besser aufgepasst, wüssten sie, warum das hier für Usability und Accessibility eine schlechte Idee ist"),
"Gesundheit": () => this.speak("Ich hab mir wohl einen Virus eingefangen"),
"zeig mir Katzen": () => this.goto('https://www.youtube.com/watch?v=8ZkOf4iaP8c'),
"ich habe Hunger": () => this.goto('https://www.google.de/maps/search/Restaurant'),
"ich habe Durst": () => this.goto('https://www.google.de/maps/search/Kneipe'),
"Bahnverbindungen": () => this.goto('http://efa.vrr.de/vrrstd/XSLT_TRIP_REQUEST2?language=de&itdLPxx_transpCompany=vrr'),
"Danke": () => this.speak('Kein Problem')
});
this.a.start({autoRestart: true, continuous: false});
}
stop(){
this.a.abort();
}
randomPick(arr){
const len = arr.length;
return arr[Math.floor(Math.random() * len)];
}
speak(text, lang='de'){
if(window.speechSynthesis){
lang = lang.toLowerCase();
let voice = window.speechSynthesis.getVoices().filter(voice => voice.lang && voice.lang.toLowerCase().startsWith(lang))
if(voice) voice = voice[0];
else throw new Error('No supported voice for the given Language');
let utterance = new SpeechSynthesisUtterance(text);
utterance.voice = voice;
window.speechSynthesis.speak(utterance)
}else{
throw new Error('no speech synthesis support');
}
if(this.notify){
const n = new Notification('Die Antwort ist:',{
body: text,
lang: 'de-DE',
icon: 'https://esag.fachschaftmedien.de/static/images/icons/favicon.png',
id: text
});
const t = setTimeout(() => {
n.close();
clearTimeout(t);
}, 3000);
}
}
spell(word){
this.speak(word.split('').join('! ')+' ... '+word);
}
search(term){
window.location.href= 'https://google.de/search?q='+window.encodeURIComponent(term);
}
goto(url){
window.location.href = url;
}
schedule(query){
const entrylist = (schedule) => Object.keys(schedule.days).reduce((all, day) => all.concat(schedule.days[day].map(entry => entry.day = day)));
const awaitSchedule = new Promise(resolve => {
fetch("https://esag.fachschaftmedien.de/resources/calendar.json")
.then(response => {
if(response.ok) return response.json()
else throw new Error();
})
.then(entries => resolve(entrylist(entries)))
.catch(err => {
console.error(err);
resolve(entrylist(localStorage.getItem('calendar')));
})
});
if(query.event){
return awaitSchedule
.then(entries => entries.filter(entry => entry.name === query.event))
}else if(query.day && query.time) {
return awaitSchedule
.then(entries => entries.filter(entry => entry.day === query.day && entry.time === query.time))
}else if(query.day){
return awaitSchedule
.then(entries => entries.filter(entry => entry.day === query.day))
}else if(query.location){
return awaitSchedule
.then(entries => entries.filter(entry => entry.location === query.location))
}else{
return {}
}
}
}
|
Markdown
|
UTF-8
| 7,596 | 3.171875 | 3 |
[] |
no_license
|
---
title: 如何优化数据导入
date: 2019-09-012 21:39:21
tags: MySQL
---
## 前言
我们有时会遇到批量数据导入的场景,而数据量稍微大点,会发现导入非常耗时间。这篇博客将介绍一些常用的加快数据导入的方法。
## 一次插入多行的值
插入行所需的时间由以下因素决定(参考MySQL 5.7参考手册:[8.2.4.1优化INSERT语句](https://dev.mysql.com/doc/refman/5.7/en/insert-optimization.html))
* 连接:30%
* 向服务器发送查询:20%
* 解析查询:20%
* 插入行:10% * 行的大小
* 插入索引:10% * 索引数
* 结束:10%
可发现大部分时间耗费在客户端与服务端通信的时间,因此可以使用 insert 包含多个值来减少客户端和服务器之间的通信。
我们通过实验来验证下一次插入多行与一次插入一行的效率对比。
### 环境准备
```sql
use muke; /* 使用muke这个database */
drop table if exists t1; /* 如果表t1存在则删除表t1 */
CREATE TABLE `t1` ( /* 创建表t1 */
`id` int(11) NOT NULL AUTO_INCREMENT,
`a` varchar(20) DEFAULT NULL,
`b` int(20) DEFAULT NULL,
`c` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8mb4 ;
drop procedure if exists insert_t1; /* 如果存在存储过程insert_t1,则删除 */
delimiter ;;
create procedure insert_t1() /* 创建存储过程insert_t1 */
begin
declare i int; /* 声明变量i */
set i=1; /* 设置i的初始值为1 */
while(i<=10000)do /* 对满足i<=1000的值进行while循环 */
insert into t1(a,b) values(i,i); /* 写入表t1中a、b两个字段,值都为i当前的值 */
set i=i+1; /* 将i加1 */
end while;
end;;
delimiter ;
call insert_t1(); /* 运行存储过程insert_t1 */
```
### 导出一条 SQL 包含多行数据的数据文件
为了获取批量导入数据的 SQL,首先对测试表的数据进行备份,备份的 SQL 为一条 SQL 包含多行数据的形式(执行环境为 Centos7 命令行)。
````sql
mysqldump -utest_user3 -p'userBcdQ19Ic' -h127.0.0.1 --set-gtid-purged=off --single-transaction --skip-add-locks muke t1 >t1.sql
````
这里对上面 mysqldump 所使用到的一些参数做下解释:
| 参数 | 注释 |
| :---: | :---: |
| -utest_user3 | 用户名,这里使用的是root用户 |
| -p’userBcdQ19Ic’ | 密码 |
| -h127.0.0.1 | 连接的MySQL服务端IP |
| set-gtid-purged=off | 不添加SET @@GLOBAL.GTID_PURGED |
| –single-transaction | 设置事务的隔离级别为可重复读,即REPEATABLE READ,这样能保证在一个事务中所有相同的查询读取到同样的数据 |
| –skip-add-locks | 取消每个表导出之前加lock tables操作 |
| muke | 库名 |
| t1 | 表名 |
| t1.sql | 导出数据到这个文件 |
查看文件 t1.sql 内容,可看到数据是单条 SQL 有多条数据,如下:
```sql
DROP TABLE IF EXISTS `t1`;
/* 按照上面的备份语句备份的数据文件包含drop命令时,需要特别小心,在后续使用备份文件做导入操作时,应该确定所有表名,防止drop掉业务正在使用
......
CREATE TABLE `t1`......
......
INSERT INTO `t1` VALUES (1,'1',1,'2019-05-24 15:44:10'),(2,'2',2,'2019-05-24 15:44:10'),(3,'3',3,'2019-05-24 15:44:10')...
```
### 导出一条SQL只包含一行数据的数据文件
```sql
mysqldump -utest_user3 -p'userBcdQ19Ic' -h127.0.0.1 --set-gtid-purged=off --single-transaction --skip-add-locks --skip-extended-insert muke t1 >t1_row.sql
```
mysqldump命令参数解释:
| 参数 | 注释 |
| :---: | :---: |
| –skip-extended-insert | 一条SQL一行数据的形式导出数据 |
备份文件t1_row.sql内容如下:
```sql
INSERT INTO `t1` VALUES (1,'1',1,'2019-05-24 15:44:10');
INSERT INTO `t1` VALUES (2,'2',2,'2019-05-24 15:44:10');
INSERT INTO `t1` VALUES (3,'3',3,'2019-05-24 15:44:10');
...
```
### 导入时间的对比
首先导入一行 SQL 包含多行数据的数据文件:
```sql
root@mysqltest ~]# time mysql -utest_user3 -p'userBcdQ19Ic' -h127.0.0.1 muke <t1.sql
real 0m0.230s
user 0m0.007s
sys 0m0.003s
```
耗时0.2秒左右。
导入一条SQL只包含一行数据的数据文件:
```sql
[root@mysqltest ~]# time mysql -utest_user3 -p'userBcdQ19Ic' -h127.0.0.1 muke <t1_row.sql
real 0m31.138s
user 0m0.088s
sys 0m0.126s
```
耗时31秒左右。
### 结论
一次插入多行(一次插入)花费时间0.2秒,一次插入一行(多次插入)花费了31秒,对比效果明显,因此建议有大批量导入时,推荐一条insert语句插入多行数据。
## 关闭自动提交
### 对比开启和关闭自动提交的效率
auto commit 开启时会为每个插入执行提交。可以在InnoDB导入数据时,关闭自动提交。如下:
```sql
SET autocommit=0;
INSERT INTO `t1` VALUES (1,'1',1,'2019-05-24 15:44:10');
INSERT INTO `t1` VALUES (2,'2',2,'2019-05-24 15:44:10');
INSERT INTO `t1` VALUES (3,'3',3,'2019-05-24 15:44:10');
......
COMMIT;
```
### 环境准备
使用上方生成的t1_row.sql,
在insert前增加:SET autocommit=0;
在insert语句后面增加:COMMIT;
### 测试
```sql
[root@mysqltest muke]# time mysql -utest_user3 -p'userBcdQ19Ic' -h127.0.0.1 muke <t1_row.sql
real 0m1.036s
user 0m0.062s
sys 0m0.108s
```
开启自动提交的情况下导入是31秒。关闭自动提交的情况下导入是1秒左右,因此导入多条数据时,关闭自动提交,让多条 insert 一次提交,可以大大提升导入速度。
### 原因分析
与本节前面讲的一次插入多行能提高批量插入速度的原因一样,因为批量导入大部分时间耗费在客户端与服务端通信的时间,所以多条 insert 语句合并提交可以减少客户端与服务端通信的时间,并且合并提交还可以减少数据落盘的次数。
## 参数调整
影响MySQL写入速度的主要两个参数:innodb_flush_log_at_trx_commit、sync_binlog。
### 参数解释
innodb_flush_log_at_trx_commit:控制重做日志刷新到磁盘的策略,有0 、1和2三种值。
* 0:master线程每秒把redo log buffer写到操作系统缓存,再刷到磁盘;
* 1:每次提交事务都将redo log buffer写到操作系统缓存,再刷到磁盘;
* 2:每次事务提交都将redo log buffer写到操作系统缓存,由操作系统来管理刷盘。
具体原理会在后续的事务这章进行详细描述。
sync_binlog:控制binlog的刷盘时机,可配置0、1或者大于1的数字。
* 0:二进制日志从不同步到磁盘,依赖OS刷盘机制;
* 1:二进制日志每次提交都会刷盘;
* n(n>1) : 每n次提交落盘一次。
innodb_flush_log_at_trx_commit设置为0、同时sync_binlog设置为0时,
写入数据的速度是最快的。如果对数据库安全性要求不高(比如你的测试环境),
可以尝试都设置为0后再导入数据,能大大提升导入速度。
## 总结
今天一起研究了怎样提高 MySQL 批量导入数据的速度。根据测试,总结了加快批量数据导入有如下方法:
* 一次插入多行的值;
* 关闭自动提交,多次插入数据的 SQL 一次提交;
* 调整参数,innodb_flush_log_at_trx_commit 和 sync_binlog 都设置为0(当然这种情况可能会丢数据)
|
C++
|
UTF-8
| 6,518 | 3.09375 | 3 |
[] |
no_license
|
/*
* EdgeDetection.cpp
*
* Created on: Dec 15, 2014
* Author: hyzor
*/
#include "EdgeDetection.h"
EdgeDetection::EdgeDetection()
{}
EdgeDetection::~EdgeDetection()
{}
cv::Mat EdgeDetection::ProcessImg(const cv::Mat* img, unsigned int parallelMethod, unsigned int num_threads)
{
if (!img->data)
{
std::cout << __FUNCTION__ << ": Could not load image " << "\n";
return cv::Mat::zeros(0, 0, 0);
}
const cv::Mat* img_src = img;
cv::Mat img_dest = img->clone();
// Clear the data in our destination image - we don't want the source image data
for (int y = 0; y < img_src->rows; ++y)
{
for (int x = 0; x < img_src->cols; ++x)
{
img_dest.at<uchar>(y, x) = 0.0;
}
}
//-------------------------------------------
// Process image using no parallelism
//-------------------------------------------
if (parallelMethod == ParallelMethod::NONE)
{
//std::cout << "Running sequential version...\n";
// Now process our destination image with edge detection using the Sobel operator
for (int y = 1; y < img_src->rows - 1; ++y)
{
for (int x = 1; x < img_src->cols - 1; ++x)
{
img_dest.at<uchar>(y, x) = ImageProcessingUtil::GetSobelOperator(img_src, x, y);
}
}
//std::cout << "...Done!\n";
}
//-------------------------------------------
// Process image using threads and locks
//-------------------------------------------
else if (parallelMethod == ParallelMethod::THREADS_AND_LOCKS)
{
//std::cout << "Running threads and locks version...\n";
std::mutex mtx;
// Number of rows are less than the amount of threads requested,
// spawn threads equal to the number of rows
if ((unsigned int)img_src->rows < num_threads)
{
num_threads = (unsigned int)img_src->rows;
}
// Spawn the maximum number of threads
else
{
// Calculate the number of rows per thread, also calculate
// if there is an uneven number of rows per thread
unsigned int rowsPerThread = (unsigned int)img_src->rows / num_threads;
unsigned int rows_rest = (unsigned int)img_src->rows % num_threads;
std::cout << "Rows/thread: " << rowsPerThread << "\n";
std::cout << "Rest rows: " << rows_rest << "\n";
std::thread myThreads[num_threads];
// There is an equal amount of rows per thread
//std::cout << "There is an equal amount of rows per threads!\n";
for (unsigned int i = 0; i < num_threads; ++i)
{
unsigned int curRowsPerThread = rowsPerThread
+ (i < rows_rest ? 1 : 0); // Add rest row, if any
unsigned int rowStart = (i * curRowsPerThread) + 1;
myThreads[i] = std::thread(&EdgeDetection::ThreadFunc, this, img_src,
&img_dest, rowStart, (rowStart + curRowsPerThread),
std::ref(mtx));
}
for (unsigned int i = 0; i < num_threads; ++i)
{
myThreads[i].join();
}
}
//std::cout << "...Done!\n";
}
//-------------------------------------------
// Process image using tasks
//-------------------------------------------
else if (parallelMethod == ParallelMethod::TASKS)
{
//std::cout << "Running tasks version...\n";
unsigned int tasksPerThread = 2;
// Number of rows are less than the amount of threads requested,
// spawn threads equal to the number of rows
if ((unsigned int)img_src->rows < num_threads)
{
num_threads = (unsigned int)img_src->rows;
tasksPerThread = 1;
}
ThreadPool* pool = new ThreadPool(num_threads);
std::vector<std::future<unsigned int>> results;
unsigned int numTasks = num_threads * tasksPerThread;
unsigned int rowsPerTask = (unsigned int)img_src->rows / numTasks;
unsigned int rows_rest = (unsigned int)img_src->rows % numTasks;
std::cout << "Tasks: " << numTasks << "\n" <<
"Rows/task: " << rowsPerTask << "\n";
std::cout << "Rows rest: " << rows_rest << "\n";
Task(img_src, 0, (0 + 0), 0, &img_dest);
// Add all the tasks, and store their results
for (unsigned int i = 0; i < numTasks; ++i)
{
unsigned int curRowsPerTask = rowsPerTask
+ (i < rows_rest ? 1 : 0); // Add rest row, if any
unsigned int rowStart = (i * curRowsPerTask) + 1;
results.emplace_back(
// Wrap task function into the lamba function
pool->AddTask([](EdgeDetection* edgeObj, const cv::Mat* img_src, unsigned int rowStart,
unsigned int rowEnd, unsigned int id, cv::Mat* img_dest)
{
return edgeObj->Task(img_src, rowStart, rowEnd, id, img_dest);
}, this, img_src, rowStart, (rowStart + curRowsPerTask), i, &img_dest)
);
}
// Collect results when all tasks have finished
//for (unsigned int i = 0; i < results.size(); ++i)
//{
//std::cout << results[i].get() << "\n";
//}
// Shutdown thread pool
pool->Shutdown();
delete pool;
//std::cout << "...Done!\n";
}
return img_dest;
}
unsigned int EdgeDetection::Task(const cv::Mat* img_src, unsigned int rowStart,
unsigned int rowEnd, unsigned int id, cv::Mat* img_dest)
{
//unsigned int numRows = rowEnd - rowStart;
//std::map<int, int**> map;
// Cache local pixel data for this task
for (unsigned int y = rowStart; y < rowEnd; ++y)
{
for (int x = 1; x < img_src->cols - 1; ++x)
{
//pixelData[y][x] = ImageProcessingUtil::GetSobelOperator(img_src, x, (y + rowStart));
img_dest->at<uchar>(y, x) = ImageProcessingUtil::GetSobelOperator(img_src, x, y);
}
}
//map[id] = pixelData;
return id;
}
void EdgeDetection::ThreadFunc(const cv::Mat* img_src,
cv::Mat* img_dest,
unsigned int rowStart,
unsigned int rowEnd,
std::mutex& mtx)
{
unsigned int numRows = rowEnd - rowStart;
int pixelData[numRows][img_src->cols];
/*
// Write directly to the destination image data
for (unsigned int y = rowStart; y < rowEnd; ++y)
{
for (int x = 1; x < img_src->cols - 1; ++x)
{
img_dest->at<uchar>(y, x) = ImageProcessingUtil::GetSobelOperator(img_src, x, y);
}
}
*/
// Cache local pixel data for this thread
for (unsigned int y = 0; y < numRows; ++y)
{
for (int x = 1; x < img_src->cols - 1; ++x)
{
pixelData[y][x] = ImageProcessingUtil::GetSobelOperator(img_src, x, (y + rowStart));
}
}
bool hasFinished = false;
// Now try to lock the shared data (our destination image data)
// and write our local cache to it
while (!hasFinished)
{
if (mtx.try_lock())
{
for (unsigned int y = 0; y < numRows; ++y)
{
for (int x = 1; x < img_src->cols - 1; ++x)
{
img_dest->at<uchar>((y + rowStart), x) = pixelData[y][x];
}
}
hasFinished = true;
mtx.unlock();
}
}
}
|
C
|
UTF-8
| 404 | 3.109375 | 3 |
[] |
no_license
|
#include <stdio.h>
int main()
{
int n,i,j;
printf("Enter the number of Pages: ");
scanf("%d",&n);
int p[n];
for(i=0;i<n;i++)
{
scanf("%d",&p[i]);
}
int m[4]={0};
int f=0,fault=0,flag=0;
for(i=0;i<n;i++)
{
flag=0;
for(j=0;j<4;j++)
{
if(p[i]==m[j])
{
flag=1;
break;
}
}
if(!flag)
{
m[f%4]=p[i];
f++;
fault++;
}
}
printf("No of Faults= %d",fault);
}
|
C++
|
UTF-8
| 3,226 | 2.59375 | 3 |
[] |
no_license
|
/*
KCANVAS PROJECT
Common 2D graphics API abstraction with multiple back-end support
(c) livingcreative, 2015 - 2017
https://github.com/livingcreative/kcanvas
05bitmaps.cpp
Bitmaps example
*/
#include "kcanvas/canvas.h"
#include "common/bmp.h"
using namespace c_util;
using namespace k_canvas;
const char *TITLE = "kcanvas - Bitmaps example";
// this is global variables, don't use this in real projects ;)
// they are used only for simplicity of examples
static kBitmap *bitmap = nullptr;
static kBitmap *mask = nullptr;
void Initialize()
{
// Example applications are supposed to be run from "bin" directory
// inside kcanvas project directory, so all paths to media data are relative to
// "bin" directory
// Load color bitmap with alpha channel
{
BitmapData data("../../examples/media/stone.bmp");
if (data.bpp() == 24) {
bitmap = new kBitmap(data.width(), data.height(), kBitmapFormat::Color32BitAlphaPremultiplied);
bitmap->Update(nullptr, kBitmapFormat::Color32BitAlphaPremultiplied, data.pitch(), data.data());
}
}
// Load mask (monochrome) bitmap
{
BitmapData data("../../examples/media/mask.bmp");
if (data.bpp() == 8) {
mask = new kBitmap(data.width(), data.height(), kBitmapFormat::Mask8Bit);
mask->Update(nullptr, kBitmapFormat::Mask8Bit, data.pitch(), data.data());
}
}
}
static void DrawBitmapExample(kCanvas &canvas)
{
// paint whole bitmap at (10, 10) with 0.75 opacity
canvas.DrawBitmap(*bitmap, kPoint(10, 10), 0.75f);
// paint part of the bitmap
canvas.DrawBitmap(*bitmap, kPoint(50, 40), kPoint(40, 30), kSize(80));
// paint scaled part of the bitmap
canvas.DrawBitmap(
*bitmap,
kPoint(270, 10), kSize(256),
kPoint(40, 30), kSize(80)
);
}
static void FillMaskExample(kCanvas &canvas)
{
kGradient gradient0(kColor(255, 177, 125), kColor(237, 28, 36));
kGradient gradient1(kColor(130, 218, 255), kColor(63, 72, 204));
kBrush fill0(kPoint(10, 10), kPoint(230, 410), gradient0);
kBrush fill1(kPoint(10, 10), kPoint(230, 245), gradient1);
for (int n = 0; n < 5; ++n) {
canvas.DrawMask(
*mask, n & 1 ? fill0 : fill1,
kPoint(kScalar(n * 30) + 10, 10), kSize(kScalar(n * 10) + 50),
kPoint(), mask->size()
);
}
}
static void BitmapBrushExample(kCanvas &canvas)
{
kBrush brush(kExtendType::Wrap, kExtendType::Wrap, *bitmap);
canvas.RoundedRectangle(kRect(10, 25, 100, 115), kSize(10), nullptr, &brush);
canvas.Ellipse(kRect(120, 25, 210, 115), nullptr, &brush);
}
void Example(kCanvas &canvas)
{
if (!bitmap || !mask) {
kFont font("Tahoma", 12);
kBrush brush(kColor::Black);
canvas.Text(kPoint(5), "Couldn't load required media!", -1, font, brush);
return;
}
DrawBitmapExample(canvas);
canvas.SetTransform(kTransform::construct::translate(550, 0));
FillMaskExample(canvas);
canvas.SetTransform(kTransform::construct::translate(800, 0));
BitmapBrushExample(canvas);
}
void Shutdown()
{
delete bitmap;
delete mask;
}
|
C++
|
UTF-8
| 1,062 | 2.765625 | 3 |
[] |
no_license
|
#include "TestBlueFilter.h"
/**
* @brief TestBluefilter::TestApplyBluefilter
* Prueba para la clase blue filter, verifica que realmente
* se modifico el valor de azul en todos los pixeles
*/
void TestBluefilter::TestApplyBluefilter()
{
string path;
for (int i = 1; i < 8; i++) {//se obtiene cada una de las 7 imagenes en la carpeta test
path = "../Test/TestFiles/img" + to_string(i) + ".jpg";
test = new BlueFilter(path);
test -> applyFilter();
Mat img = imread("../Test/RBAcache/blue.jpg");
int red = 0;
int blue = 0;
int green = 0;
for(int j = 0; j < img.rows; j++) {
for (int k = 0; k <img.cols; k++)
{
Vec3b pixel = img.at<Vec3b>(j,k);
blue += (int)pixel[0];
green += (int)pixel[1];
red += (int)pixel[2];
}
}
CPPUNIT_ASSERT(blue >= green && blue >= red);//se verifica que el valor azul sea mayor que los demas
}
}
|
C++
|
UTF-8
| 12,558 | 2.59375 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <string>
#include <cstdint>
using namespace std;
unsigned char songlength;
int16_t maxRows = -1;
bool verbose = false;
uint8_t *xmdata = NULL;
uint16_t notes[257][8];
uint16_t noteRows[1936][8];
ifstream XMFILE;
ofstream ASMFILE;
bool isPatternUsed(int patnum);
bool verifyXMParams(uint8_t numberOfChannels);
uint16_t assignNoteRow(int row);
int main(int argc, char *argv[]){
cout << "XM 2 OCTODE2k16 CONVERTER\n";
//check for "-v" flag
string arg = "";
if (argc > 1) arg = argv[1];
if (arg == "-v") verbose = true;
//create music.asm
ASMFILE.open ("music.asm", ios::out | ios::trunc);
if (!ASMFILE.is_open()) {
cout << "Error: Could not create music.asm - need to set write permission?\n";
return -1;
}
//open music.xm
XMFILE.open ("music.xm", ios::in | ios::binary);
if (!XMFILE.is_open()) {
cout << "Error: Could not open music.xm\n";
return -1;
}
//get filesize
XMFILE.seekg(0,ios_base::end);
int32_t filesize = XMFILE.tellg();
//read XM file into array
xmdata = new uint8_t[filesize];
char cp;
for (int32_t i = 0; i < filesize; i++) {
XMFILE.seekg(i, ios::beg);
XMFILE.read((&cp), 1);
xmdata[i] = static_cast<uint8_t>(cp);
}
XMFILE.close();
//verify XM parameters
if (!verifyXMParams(10)) return -1;
//read global song parameters
uint8_t uniqueptns = xmdata[70];
uint16_t xmHeaderLength = (xmdata[61]<<8) + xmdata[60];
songlength = xmdata[64];
if (verbose) {
cout << "song length: " << +xmdata[64] << "\nunique patterns: " << +xmdata[70] << "\nglobal speed: " << +xmdata[76] << endl;
cout << "XM header length: " << +xmHeaderLength << endl;
}
//locate the pattern headers and read pattern lengths
uint16_t ptnOffsetList[256], ptnLengths[256];
int32_t fileOffset = xmHeaderLength + 60;
ptnOffsetList[0] = xmHeaderLength + 60;
for (int i = 0; i < uniqueptns; i++) {
ptnLengths[i] = xmdata[fileOffset+5];
ptnOffsetList[i+1] = ptnOffsetList[i] + xmdata[fileOffset] + xmdata[fileOffset+7] + (xmdata[fileOffset+8]<<8);
fileOffset = fileOffset + xmdata[fileOffset+7] + (xmdata[fileOffset+8]<<8) + 9;
if (verbose) cout << "pattern " << i << " starts at " << ptnOffsetList[i] << ", length " << ptnLengths[i] << " rows\n";
}
//generate pattern sequence
uint8_t sequence[songlength];
if (verbose) cout << "song sequence: ";
for (fileOffset = 80; fileOffset < static_cast<uint8_t>(songlength+80); fileOffset++) {
sequence[fileOffset-80] = xmdata[fileOffset];
if (verbose) cout << " - " << +sequence[fileOffset-80];
}
if (verbose) cout << endl;
//define note value arrays
const uint16_t notetab[85] = { 0,
0x100, 0x10F, 0x11F, 0x130, 0x142, 0x155, 0x16A, 0x17F, 0x196, 0x1AE, 0x1C8, 0x1E3,
0x200, 0x21E, 0x23F, 0x261, 0x285, 0x2AB, 0x2D4, 0x2FF, 0x32D, 0x35D, 0x390, 0x3C7,
0x400, 0x43D, 0x47D, 0x4C2, 0x50A, 0x557, 0x5A8, 0x5FE, 0x65A, 0x6BA, 0x721, 0x78D,
0x800, 0x87A, 0x8FB, 0x984, 0xA14, 0xAAE, 0xB50, 0xBFD, 0xCB3, 0xD74, 0xE41, 0xF1A,
0x1000, 0x10F4, 0x11F6, 0x1307, 0x1429, 0x155C, 0x16A1, 0x17F9, 0x1966, 0x1AE9, 0x1C82, 0x1E34,
0x2000, 0x21E7, 0x23EB, 0x260E, 0x2851, 0x2AB7, 0x2D41, 0x2FF2, 0x32CC, 0x35D1, 0x3905, 0x3C68,
0x4000, 0x43CE, 0x47D6, 0x4C1C, 0x50A3, 0x556E, 0x5A83, 0x5FE4, 0x6598, 0x6BA3, 0x7209, 0x78D1 };
//convert pattern data
uint8_t ctrlb, temp;
int dch;
uint8_t noteVals[257][8];
int16_t loopPoint = 0;
uint8_t pSpeeds[uniqueptns][257];
uint8_t pDrums[uniqueptns][257]; //0 = no drum, 1..0x80 noise/vol, >0x80 = kick
uint8_t pDrumTrigs[uniqueptns][257];
uint16_t pRowPntr[uniqueptns][257]; //row pointers
uint8_t detune[8] = { 8, 8, 8, 8, 8, 8, 8, 8 };
for (int ptn = 0; ptn < uniqueptns; ptn++) {
if (isPatternUsed(ptn)) {
fileOffset = ptnOffsetList[ptn] + 9;
noteVals[0][0] = 0;
noteVals[0][1] = 0;
noteVals[0][2] = 0;
noteVals[0][3] = 0;
noteVals[0][4] = 0;
noteVals[0][5] = 0;
noteVals[0][6] = 0;
noteVals[0][7] = 0;
notes[0][0] = 0;
notes[0][1] = 0;
notes[0][2] = 0;
notes[0][3] = 0;
notes[0][4] = 0;
notes[0][5] = 0;
notes[0][6] = 0;
notes[0][7] = 0;
pSpeeds[ptn][0] = xmdata[76];
pDrums[ptn][0] = 0;
pDrumTrigs[ptn][0] = 0;
for (int row = 1; row <= ptnLengths[ptn]; row++) {
detune[0] = 8;
detune[1] = 8;
detune[2] = 8;
detune[3] = 8;
detune[4] = 8;
detune[5] = 8;
detune[6] = 8;
detune[7] = 8;
noteVals[row][0] = noteVals[row-1][0];
noteVals[row][1] = noteVals[row-1][1];
noteVals[row][2] = noteVals[row-1][2];
noteVals[row][3] = noteVals[row-1][3];
noteVals[row][4] = noteVals[row-1][4];
noteVals[row][5] = noteVals[row-1][5];
noteVals[row][6] = noteVals[row-1][6];
noteVals[row][7] = noteVals[row-1][7];
notes[row][0] = notetab[noteVals[row-1][0]];
notes[row][1] = notetab[noteVals[row-1][1]];
notes[row][2] = notetab[noteVals[row-1][2]];
notes[row][3] = notetab[noteVals[row-1][3]];
notes[row][4] = notetab[noteVals[row-1][4]];
notes[row][5] = notetab[noteVals[row-1][5]];
notes[row][6] = notetab[noteVals[row-1][6]];
notes[row][7] = notetab[noteVals[row-1][7]];
pSpeeds[ptn][row] = pSpeeds[ptn][row-1];
pDrums[ptn][row] = 0;
pDrumTrigs[ptn][row] = 0;
dch = 0xff;
for (int ch = 0; ch < 10; ch++) {
ctrlb = xmdata[fileOffset];
if (ctrlb >= 0x80) { //have compressed pattern data
fileOffset++;
if (ctrlb != 128) {
temp = xmdata[fileOffset];
if ((ctrlb & 1) == 1) { //if bit 0 is set, it's note -> counter val.
if (temp == 97) temp = 0; //silence
if ((ch < 8) && (temp > 84)) {
cout << "Warning: Out-of-range note in pattern " << +ptn << ", channel " << +ch << " replaced with a rest.\n";
temp = 0;
}
if (ch < 8) noteVals[row][ch] = temp;
fileOffset++;
}
temp = 0;
if ((ctrlb&2) == 2) { //if bit 1 is set, it's instrument
if ((ch < 8) && (xmdata[fileOffset] > 1)) noteVals[row][ch] = 0;
if ((pDrumTrigs[ptn][row]) && (xmdata[fileOffset] > 1)) cout << "Warning: More than one drum in pattern " << +ptn << ", channel " << +ch << endl;
if (xmdata[fileOffset] == 2) pDrumTrigs[ptn][row] = 4; //kick
if (xmdata[fileOffset] == 3) pDrumTrigs[ptn][row] = 0x80; //snare
if (xmdata[fileOffset] == 4) pDrumTrigs[ptn][row] = 1; //hihat
if (xmdata[fileOffset] > 1) pDrums[ptn][row] = 0x80;
dch = ch;
fileOffset++;
}
if ((ctrlb&4) == 4) { //if bit 2 is set, it's volume (applies to noise drum only)
if (dch == ch) {
pDrums[ptn][row] = (xmdata[fileOffset]-0x10) * 2;
}
fileOffset++;
}
if ((ctrlb&8) == 8) { //if bit 3 is set, it's an fx command
temp = xmdata[fileOffset];
fileOffset++;
}
if ((ctrlb&16) == 16) { //if bit 4 is set, it's an fx parameter
//Bxx
if (temp == 0xb) loopPoint = xmdata[fileOffset];
//E5x
if ((temp == 0xe) && ((xmdata[fileOffset] & 0xf0) == 0x50) && (ch < 8)) detune[ch] = xmdata[fileOffset] & 0xf;
//Fxx
if ((temp == 0xf) && (xmdata[fileOffset] < 0x20)) pSpeeds[ptn][row] = xmdata[fileOffset];
fileOffset++;
}
}
} else { //uncompressed pattern data
//read notes
temp = ctrlb;
if (temp == 97) temp = 0; //silence
if ((ch < 8) && (temp > 84)) {
cout << "Warning: Out-of-range note in pattern " << +ptn << ", channel " << +ch << " replaced with a rest.\n";
temp = 0;
}
if (ch < 8) noteVals[row][ch] = temp;
fileOffset++;
//read instruments
if ((ch < 8) && (xmdata[fileOffset] > 1)) noteVals[row][ch] = 0;
if ((pDrumTrigs[ptn][row]) && (xmdata[fileOffset] > 1)) cout << "Warning: More than one drum in pattern " << +ptn << ", channel " << +ch << endl;
if (xmdata[fileOffset] == 2) pDrumTrigs[ptn][row] = 4; //kick
if (xmdata[fileOffset] == 3) pDrumTrigs[ptn][row] = 0x80; //snare
if (xmdata[fileOffset] == 4) pDrumTrigs[ptn][row] = 1; //hihat
if (xmdata[fileOffset] > 1) pDrums[ptn][row] = 0x80;
dch = ch;
fileOffset++;
//read volume
if (dch == ch) pDrums[ptn][row] = (xmdata[fileOffset]-0x10) * 2;
fileOffset++;
//read fx command
temp = xmdata[fileOffset];
fileOffset++;
//read fx parameter
//Bxx
if (temp == 0xb) loopPoint = xmdata[fileOffset];
//E5x
if ((temp == 0xe) && ((xmdata[fileOffset] & 0xf0) == 0x50) && (ch < 8)) detune[ch] = xmdata[fileOffset] & 0xf;
//Fxx
if ((temp == 0xf) && (xmdata[fileOffset] < 0x20)) pSpeeds[ptn][row] = xmdata[fileOffset];
fileOffset++;
}
}
for (int ch = 0; ch < 8; ch++) {
notes[row][ch] = notetab[noteVals[row][ch]];
notes[row][ch] = notes[row][ch] - static_cast<uint16_t>(notes[row][ch]*(8-detune[ch])/100);
}
pRowPntr[ptn][row] = assignNoteRow(row);
if (pRowPntr[ptn][row] > 1935) {
cout << "Error: Song too large.\n";
delete[] xmdata;
xmdata = NULL;
return -1;
}
}
}
}
//construct music.asm
ASMFILE << ";sequence\n";
//print sequence
for (int i = 0; i < songlength; i++) {
if (i == loopPoint) ASMFILE << "loop\n";
ASMFILE << "\tdw ptn" << hex << +sequence[i] << endl;
}
ASMFILE << "\tdw 0\n\n";
//print patterns
for (int i = 0; i < uniqueptns; i++) {
if (isPatternUsed(i)) {
ASMFILE << "ptn" << hex << +i << endl;
for (int j = 1; j <= ptnLengths[i]; j++) {
ASMFILE << "\tdw #" << +pSpeeds[i][j];
if (pDrumTrigs[i][j] != 0x80) ASMFILE << "0";
ASMFILE << +pDrumTrigs[i][j] << ",";
if (pDrumTrigs[i][j]) ASMFILE << "#00" << hex << +pDrums[i][j] << ",";
ASMFILE << "row" << hex << pRowPntr[i][j] << endl;
}
ASMFILE << "\tdb #40\n\n";
}
}
//print row buffers
ASMFILE << "\n\n;row buffers\n";
for (int i = 0; i <= maxRows; i++) {
ASMFILE << "row" << hex << +i << "\tdw ";
for (int j = 0; j < 8; j++) {
ASMFILE << "#" << +noteRows[i][j];
if (j == 7) ASMFILE << endl;
else ASMFILE << ",";
}
}
cout << "Success!\n";
delete[] xmdata;
xmdata = NULL;
ASMFILE.close();
return 0;
}
//return the number of the row buffer that represents the current row of the current pattern, creating a new row buffer if necessary
uint16_t assignNoteRow(int row) {
int assign = 0;
bool matchFound = false;
while (assign < maxRows && !matchFound) {
assign++;
if (assign > 1935) return assign;
if (noteRows[assign][0] == notes[row][0] && noteRows[assign][1] == notes[row][1] && noteRows[assign][2] == notes[row][2]
&& noteRows[assign][3] == notes[row][3] && noteRows[assign][4] == notes[row][4] && noteRows[assign][5] == notes[row][5]
&& noteRows[assign][6] == notes[row][6] && noteRows[assign][7] == notes[row][7]) matchFound = true;
}
if (!matchFound) {
maxRows++;
assign = maxRows;
for (int i = 0; i < 8; i++) {
noteRows[assign][i] = notes[row][i];
}
}
return assign;
}
//verify XM parameters
bool verifyXMParams(uint8_t numberOfChannels) {
char tbuf[16];
const string xmheader = "Extended Module:";
bool xmValid = true;
xmheader.copy(tbuf, 16, 0);
for (int i = 0; i < 16; i++) {
if (tbuf[i] != static_cast<char>(xmdata[i])) xmValid = false;
}
if (!xmValid) {
cout << "Error: Not a valid XM file.\n";
delete[] xmdata;
xmdata = NULL;
return false;
}
if (xmdata[58] != 4) {
cout << "Error: Obsolete XM version 1.0" << +xmdata[58] << ", v1.04 required." << endl;
delete[] xmdata;
xmdata = NULL;
return false;
}
if (xmdata[68] != numberOfChannels) {
cout << "Error: XM has " << +xmdata[68] << " channels instead of " << +numberOfChannels << ".\n";
delete[] xmdata;
xmdata = NULL;
return false;
}
return true;
}
//check if a pattern exists in sequence
bool isPatternUsed(int patnum) {
bool usage = false;
for (int32_t fileOffset = 80; fileOffset < static_cast<int32_t>(songlength + 80); fileOffset++) {
if (patnum == xmdata[fileOffset]) usage = true;
}
return(usage);
}
|
Java
|
UTF-8
| 780 | 3.953125 | 4 |
[] |
no_license
|
//创建工厂类
public class Factory{
public static Shape getShape(String shapeType){
if(shapeType == null)
return null;
if(shapeType.equalsIgnoreCase("")){
return new Circle();
}else if(shapeType.equalsIgnoreCase("")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("")){
return new Square();
}
return null;
}
}
//创建一个接口
interface Shape{
void draw();
}
//创建实现接口的实体类
class Rectangle implements Shape{
@override
public void draw(){
System.out.println("Inside Rectangle");
}
}
class Square implements Shape{
@override
public void draw(){
System.out.println("Inside Square");
}
}
class Circle implements Shape{
@override
public void draw(){
System.out.println("Inside Circle");
}
}
|
JavaScript
|
UTF-8
| 672 | 2.515625 | 3 |
[] |
no_license
|
export function selectDough(dough) {
// selectDough is an ActionCreator, it needs to return an action,
// an object with a type property.
return {
type: "DOUGH_SELECTED",
payload: dough
};
}
export function selectIngredient(ingredient) {
// selectIngredient is an ActionCreator, it needs to return an action,
// an object with a type property.
return {
type: "INGREDIENT_SELECTED",
payload: ingredient
};
}
export function removeIngredient(ingredient) {
// selectIngredient is an ActionCreator, it needs to return an action,
// an object with a type property.
return {
type: "INGREDIENT_REMOVED",
payload: ingredient
};
}
|
Java
|
UTF-8
| 823 | 3.328125 | 3 |
[] |
no_license
|
package main.Week8.Prerequisites.ShortestPath;
import java.util.*;
class GraphImpl implements Graph {
private Map<Integer, Vertex> vertices;
public GraphImpl() {
this.vertices = new HashMap<>();
}
public void addVertex(Vertex v) {
this.vertices.put(v.getId(), v);
}
@Override
public Collection<Vertex> getAllVertices() {
return this.vertices.values();
}
@Override
public List<Vertex> getNeighbours(Vertex v) {
List<Vertex> neigh = new ArrayList<>(((VertexImpl) v).getNeighbours());
Collections.sort(neigh);
return neigh;
}
public void addEdge(Vertex v, Vertex w) {
VertexImpl realV = (VertexImpl) v;
VertexImpl realW = (VertexImpl) w;
realV.addNeighbour(w);
realW.addNeighbour(v);
}
}
|
Python
|
UTF-8
| 2,463 | 2.6875 | 3 |
[] |
no_license
|
"""
Model and handler for tracking latest e-mails for a fetching
"""
from fetching.models import Fetching
from helpers.clean import clean_str
from google.appengine.ext import db
import random
import logging, time
class FetchedMessage(db.Model):
"""
Represents a single fetched message
"""
fetching = db.ReferenceProperty(Fetching)
gmail_message_id = db.StringProperty()
from_email = db.EmailProperty(indexed=False)
from_name = db.StringProperty(indexed=False)
to_emails = db.ListProperty(db.Email, indexed=False)
to_names = db.StringListProperty(indexed=False)
subject = db.StringProperty(indexed=False)
date = db.DateTimeProperty()
@classmethod
def from_context(cls, msg):
"""
Creates object from Context.IO type, does not put
"""
params = {}
from_person = msg.addresses['from']
if from_person:
if from_person.email:
params['from_email'] = db.Email(from_person.email)
if from_person.name:
params['from_name'] = clean_str(from_person.name)
to_persons = msg.addresses['to'] or []
params['to_emails'] = []
params['to_names'] = []
for person in to_persons:
if person.email:
params['to_emails'].append(db.Email(person.email))
if person.name:
params['to_names'].append(clean_str(person.name))
else:
params['to_names'].append("")
params['subject'] = clean_str(msg.subject)
params['date'] = msg.date
params['gmail_message_id'] = msg.gmail_message_id
return cls(**params)
# Processor base class
from fetching.meta import MessageProcessor
class SaveFetchedMsg(MessageProcessor):
def __init__(self, *args, **kwds):
self.messages = []
super(SaveFetchedMsg, self).__init__(*args, **kwds)
def process(self, msg, extras={}):
"""
Randomly creates messages addressed to user
"""
if not extras.get('from_user') and \
random.randint(0,32) == 27:
msg = FetchedMessage.from_context(msg)
msg.fetching = self.request_handler.fetching_key
self.messages.append(msg)
def commit(self, extras={}):
"""
Saves messages to datastore
"""
db.put(self.messages)
|
Java
|
UTF-8
| 386 | 2.640625 | 3 |
[] |
no_license
|
import javax.swing.JOptionPane;
public class exitclass implements Runnable
{
Thread t1;
exitclass()
{
JOptionPane.showMessageDialog(null, "Admin has terminated subscription");
t1=new Thread(this);
t1.start();
}
public void run()
{
try
{
t1.sleep(5000);
System.exit(0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
|
Java
|
UTF-8
| 748 | 2.65625 | 3 |
[] |
no_license
|
package com.example.gradiuation.stopwatch;
/**
* Created by eagle-eye on 27/07/15.
*/
public class logs {
private String name;
private String time;
private String clock;
public logs(String name, String time, String clock) {
super();
this.name = name;
this.time = time;
this.clock = clock;
}
public void setName(String nameText) {
name = nameText;
}
public String getName() {
return name;
}
public void setTime(String time) {
this.time = time;
}
public String getTime() {
return time;
}
public void setClock(String clock) {
this.clock = clock;
}
public String getClock() {
return clock;
}
}
|
Markdown
|
UTF-8
| 1,149 | 2.921875 | 3 |
[] |
no_license
|
# KeyInPicture
That script can crypt message in the picture. You can decrypt picture only if you have secret code.
## Installing:
git clone https://github.com/wannaWhat/KeyInPicture.git
cd KeyInPicture
pip install -r requirements.txt
## How to use:
### Help menu:
python keyInPicture.py --help
positional arguments:
inPhoto Input photo
optional arguments:
-h, --help show this help message and exit
-o OUTPHOTO Output photo
-s SECRETWORD Message for crypt
-p PASSWORD Password for decode
### For crypt photo:
```diff
- ORIGINAL PHOTO MUST BE IN .jpeg FORMAT
```
python keyInPicture.py [path to original photo] -o [name of output photo] -s [message for crypt]
#### Output:
Secret code: [your code]
### For decrypt photo:
python keyInPicture.py [path to original photo] -p [your secret code]
#### Output:
Youre secret message
|
Markdown
|
UTF-8
| 1,334 | 3.703125 | 4 |
[
"MIT"
] |
permissive
|
---
title: 'toPlainEnglish'
date: '2021-08-28'
type: 'javascript'
draft: false
summary: 'Replace all VNese letters with the corresponding English accents'
---
Replace all `VNese` letters with the corresponding English accents
```js
const toPlainEnglish = (str) => {
str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, 'a')
str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, 'e')
str = str.replace(/ì|í|ị|ỉ|ĩ/g, 'i')
str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, 'o')
str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, 'u')
str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, 'y')
str = str.replace(/đ/g, 'd')
str = str.replace(/À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ/g, 'A')
str = str.replace(/È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ/g, 'E')
str = str.replace(/Ì|Í|Ị|Ỉ|Ĩ/g, 'I')
str = str.replace(/Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ/g, 'O')
str = str.replace(/Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ/g, 'U')
str = str.replace(/Ỳ|Ý|Ỵ|Ỷ|Ỹ/g, 'Y')
str = str.replace(/Đ/g, 'D')
// OPTIONAL - Remove special chars
// str = str.replace(/[^a-zA-Z0-9 \s]/g, "")
return str
}
console.log(toPlainEnglish('Serấj Vahdati')) // => "Seraj Vahdati"
```
|
TypeScript
|
UTF-8
| 604 | 3.375 | 3 |
[
"MIT"
] |
permissive
|
enum shortOrLong {
"ascending" = "ascending",
"descending" = "descending"
}
function sorter <T> (option : shortOrLong, returnAmount : number, ...arrs : T[][]) {
let container = [...arrs];
if (option == shortOrLong.ascending){
container.sort((a : T[],b: T[])=>{
return a.length - b.length;
})
}
else {
container.sort((a, b)=>{
return b.length - a.length;
})
}
return container.slice(0,returnAmount);
}
sorter(shortOrLong.ascending, 3,[1,2],[1,2,3],[1]); //?
sorter(shortOrLong.descending, 1,[1,2],[1,2,3],[1]); //?
|
Markdown
|
UTF-8
| 1,565 | 2.859375 | 3 |
[] |
no_license
|
---
layout: post
title: "t-distributed stochastic nieghbor embedding"
date: 2019-09-19
---
Construction site ....
# When can I use it?
# How does it work?
Two probability distributions are fit to the sample units (e.g. sites). The first, lets call it f_{full}() describes the distribution of the sample units in a space defined by all species, i.e. in a high dimensional space. The second, which we will call f_{reduced}() describes the distribution of the sample units in a lower dimensional space (how are the number of lower dimensions set?). The method tries to minimize the Kullback-Leibler(link) divergence between the two.
A Gaussian kernel(link) is used on each sampling point to determine the probability that another sample is its "neighbor" in the high dimensional space descirbed by f_{full}().
In the low dimensional space a student's t-distribution kernal is used insted. t-distributions have longer tails hence emphasize samller neighborhoods (why?)
The positioning of points in the low dimensional space is optimized via stochastic gradient descent algorithm (link)
# Used by
The method is used by Roberts (2019) in his comparison of distance and model based ordinations.
## References
van der Maaten, L. 2014. Accelerating t-SNE using tree-based algorithms. Journal of Machine Learning Research 15:3221– 3245.
van der Maaten, L., and G. E. Hinton. 2008. Visualizing data using t-SNE. Journal of Machine Learning Research 9:2431– 2456.
van der Maaten, L., S. Schmidtlein, and M. D. Mahecha. 2012. Analyzing floristic inventories with multiple maps. Ecological Informatics 9:1–10.
|
C++
|
UTF-8
| 2,460 | 2.703125 | 3 |
[] |
no_license
|
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "model.h"
#include "shader.h"
#include "camera.h"
#include "render-target.h"
#include "rasterizer-state.h"
namespace Seed
{
class Renderer
{
public:
Renderer(void)
: rasterizer_state_(RS_CW)
, viewport_(VP_SIMPLE)
, depth_stencil_(DS_SIMPLE)
, render_targets_({ RT_BACKBUFFER })
, setup_textures_({ RT_NONE })
, shader_file_("simple3d-backbuffer")
, model_file_("jeep")
, priority_(0)
{}
private:
RS rasterizer_state_;
VP viewport_;
DS depth_stencil_;
std::vector<RT> render_targets_;
std::vector<RT> setup_textures_;
std::string shader_file_;
std::string model_file_;
std::vector<void*> constant_buffer_;
unsigned int priority_;
public:
const RS & rasterizer_state(void) const { return this->rasterizer_state_; }
const VP & viewport(void) const { return this->viewport_; }
const DS & depth_stencil(void) const { return this->depth_stencil_; }
const std::vector<RT> & render_targets(void) const { return this->render_targets_; }
const std::vector<RT> & setup_textures(void) const { return this->setup_textures_; }
const std::string & shader_file(void) const { return this->shader_file_; }
const std::string & model_file(void) const { return this->model_file_; }
const std::vector<void*> & constant_buffer(void) const { return this->constant_buffer_;}
const unsigned int priority(void) const { return this->priority_; }
void set_rasterizer_state(const RS & rasterizer_state) { this->rasterizer_state_ = rasterizer_state; }
void set_viewport(const VP & viewport) { this->viewport_ = viewport; }
void set_depth_stencil(const DS & depth_stencil) { this->depth_stencil_ = depth_stencil; }
void set_render_targets(const std::vector<RT> & render_targets) { this->render_targets_ = render_targets; }
void set_setup_textures(const std::vector<RT> & setup_textures) { this->setup_textures_ = setup_textures; }
void set_shader_file(const std::string & shader_file) { this->shader_file_ = shader_file; }
void set_model_file(const std::string & model_file) { this->model_file_ = model_file; }
void set_constant_buffer(const unsigned int & num, void * constant_buffer)
{
if(this->constant_buffer_.size() < num + 1)
this->constant_buffer_.resize(num + 1);
this->constant_buffer_[num] = constant_buffer;
}
void set_priority(const unsigned int & priority) { this->priority_ = priority; }
};
}
|
Swift
|
UTF-8
| 495 | 2.65625 | 3 |
[] |
no_license
|
//
// IterationTests.swift
// IterationTests
//
// Created by Adrian McDaniel on 12/14/16.
// Copyright © 2016 dssafsfsd. All rights reserved.
//
//import XCTest
//@testable import Iteration
//class ForwardBackwardTests: XCTestCase {
// func testForwardBackward() {
// let list = forwardBackward(input: [1, 2, 3, 4, 5].makeIterator())
// let result = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]
// XCTAssertEqual(list, result)
// }
//}
|
Java
|
UTF-8
| 353 | 2.875 | 3 |
[] |
no_license
|
import java.util.Scanner;
class Main {
public static void main (String[] args){
// Type your code here
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int sum=0;
int temp=0;
int i=n%10;
while(n!=0)
{
temp=n;
n=n/10;
}
sum=i+temp;
System.out.println(sum);
}
}
|
Java
|
UTF-8
| 698 | 2.390625 | 2 |
[] |
no_license
|
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class SearchPage {
WebDriver driver;
private By SEARCHWINDOW = By.id("ss");
private By SEARCHBUTTON = By.cssSelector(".sb-searchbox__button ");
public SearchPage(WebDriver driver) {
this.driver = driver;
}
public WebElement getSearchWindow() {
return driver.findElement(SEARCHWINDOW);
}
public WebElement getSearchButton() {
return driver.findElement(SEARCHBUTTON);
}
public void search(String hotelName) {
getSearchWindow().sendKeys(hotelName);
getSearchButton().click();
}
}
|
Markdown
|
UTF-8
| 872 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
---
name: Opdagelses­rejsende
tags:
- De grønne pigespejdere
- forløb
- udgået
age: 9-16
image: dgp-opdagelsesrejsende.jpg
infolink: http://pigespejder.dk/forside/for-pigespejdere/aktivitetsmateriale/udfordringsmaerker-for-spejdere-seniorspejdere/stifinderen/opdagelsesrejsende/
buylink: http://www.55nord.dk/de-gr%C3%B8nne-pigespejdere/shop-de-groenne-pigespejdere/maerker-2/opdagelsesrejsende-de-groenne-pigespejdere
discontinued: true
---
Formålet med dette mærke er meget oplevelsesbaseret, og udfordrer pigerne på deres
iagttagelsesevner. Pigerne bringes ud på ukendt grund for derefter helt selv at skulle finde hen til et
bestemt punkt, hvilket gør dem bedre til at tro på, at de selv kan. Samtidig får pigerne et
praktisk kendskab til, hvilke teknikker, der historisk er blevet brugt til at dokumentere områder
med og hvilke, der bruges i nutiden.
|
Java
|
UTF-8
| 673 | 2.046875 | 2 |
[] |
no_license
|
package com.retargeting_branding.repositories;
import com.retargeting_branding.models.Advertiser;
import com.retargeting_branding.models.Impression;
import com.retargeting_branding.models.Website;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ImpressionRepository extends JpaRepository<Impression, Long> {
Page<Impression> findByIsDeleted(Boolean isDeleted, Pageable pageable);
Page<Impression> findByAdvertiser(Advertiser advertiser, Pageable pageable);
Page<Impression> findByWebsite(Website website, Pageable pageable);
}
|
Ruby
|
UTF-8
| 1,575 | 3.40625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# game
# frame
# score
module Bowling
class Game
def initialize(game_str)
@game_str = game_str
end
# == Parameters:
#
# game: "[[1,1],[2,3],...]"
#
# ex.
# [[5,3],[7,2],[8,/],[X],[7,1],[9,-],[6,2],[X],[6,/],[8,-]]
# score: 126
#
# []: 1フレーム
# n: 倒したピンの数
# X: ストライク
# /: スペア
# -: ガター
#
def score
total_score = 0
last_flame = nil
last_last_flame = nil
flames.each do |flame|
unless flame.strike?
score1 = flame.score1
score1 = 0 if score1 == :-
if last_flame && last_flame.spare?
total_score += 10 + score1
end
score2 = flame.score2
score2 = 0 if score2 == :-
if last_flame && last_flame.strike?
if last_last_flame && last_last_flame.strike?
total_score += 20 + score1
end
total_score += 10 + score1 + score2
end
if !flame.spare? and !flame.strike?
total_score += score2 + score1
end
end
last_last_flame = last_flame
last_flame = flame
end
total_score
end
def flames
return @flames if defined?(@flames)
filtered_game = @game_str.dup
filtered_game.gsub!(%r{-}, ':-')
filtered_game.gsub!(%r{/}, ':/')
filtered_game.gsub!('X', ':X')
flames_ = eval(filtered_game)
@flames = flames_.map { |flame| Flame.new(flame) }
end
end
end
|
C++
|
UTF-8
| 793 | 2.65625 | 3 |
[] |
no_license
|
#include "GameScreenMenu.h"
GameScreenMenu::GameScreenMenu(SDL_Renderer* renderer) : GameScreen(renderer)
{
SetUpScreen();
}
bool GameScreenMenu::SetUpScreen()
{
//Load the menu texture
menuBackgroundTexture = new Texture2D(mRenderer);
if (!menuBackgroundTexture->LoadFromFile("Images/CopytightThis.jpg"))
{
std::cout << "Failed to load Menu texture";
return false;
}
return true;
}
GameScreenMenu::~GameScreenMenu()
{
delete menuBackgroundTexture;
menuBackgroundTexture = NULL;
delete gameScreenManager;
gameScreenManager = NULL;
}
void GameScreenMenu::Render()
{
//draw the menu background
menuBackgroundTexture->Render(Vector2D(), SDL_FLIP_NONE);
}
void GameScreenMenu::Update(float deltaTime, SDL_Event e)
{
}
|
Java
|
UTF-8
| 3,215 | 2.03125 | 2 |
[] |
no_license
|
package cdm.event.common.functions;
import cdm.legalagreement.master.EquitySwapMasterConfirmation2018;
import cdm.product.asset.InterestRatePayout;
import cdm.product.asset.InterestRatePayout.InterestRatePayoutBuilder;
import cdm.product.common.schedule.CalculationPeriodDates;
import cdm.product.common.schedule.PaymentDates;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.rosetta.model.lib.expression.CardinalityOperator;
import com.rosetta.model.lib.functions.RosettaFunction;
import com.rosetta.model.lib.mapper.MapperS;
import com.rosetta.model.lib.validation.ModelObjectValidator;
import java.util.Arrays;
import static com.rosetta.model.lib.expression.ExpressionOperators.*;
@ImplementedBy(NewFloatingPayout.NewFloatingPayoutDefault.class)
public abstract class NewFloatingPayout implements RosettaFunction {
@Inject protected ModelObjectValidator objectValidator;
/**
* @param masterConfirmation
* @return interestRatePayout
*/
public InterestRatePayout evaluate(EquitySwapMasterConfirmation2018 masterConfirmation) {
InterestRatePayout.InterestRatePayoutBuilder interestRatePayoutHolder = doEvaluate(masterConfirmation);
InterestRatePayout.InterestRatePayoutBuilder interestRatePayout = assignOutput(interestRatePayoutHolder, masterConfirmation);
// post-conditions
assert
com.rosetta.model.lib.mapper.MapperUtils.toComparisonResult(com.rosetta.model.lib.mapper.MapperUtils.from(() -> {
if (exists(MapperS.of(masterConfirmation)).get()) {
return areEqual(MapperS.of(interestRatePayout).<CalculationPeriodDates>map("getCalculationPeriodDates", _interestRatePayout -> _interestRatePayout.getCalculationPeriodDates()), MapperS.of(masterConfirmation).<CalculationPeriodDates>map("getEquityCalculationPeriod", _equitySwapMasterConfirmation2018 -> _equitySwapMasterConfirmation2018.getEquityCalculationPeriod()), CardinalityOperator.All).and(areEqual(MapperS.of(interestRatePayout).<PaymentDates>map("getPaymentDates", _interestRatePayout -> _interestRatePayout.getPaymentDates()), MapperS.of(masterConfirmation).<PaymentDates>map("getEquityCashSettlementDates", _equitySwapMasterConfirmation2018 -> _equitySwapMasterConfirmation2018.getEquityCashSettlementDates()), CardinalityOperator.All));
}
else {
return MapperS.ofNull();
}
})).get()
: "Interest rate payout must inherit terms from the Master Confirmation Agreement when it exists.";
if (interestRatePayout!=null) objectValidator.validateAndFailOnErorr(InterestRatePayout.class, interestRatePayout);
return interestRatePayout;
}
private InterestRatePayout.InterestRatePayoutBuilder assignOutput(InterestRatePayout.InterestRatePayoutBuilder interestRatePayout, EquitySwapMasterConfirmation2018 masterConfirmation) {
return interestRatePayout;
}
protected abstract InterestRatePayout.InterestRatePayoutBuilder doEvaluate(EquitySwapMasterConfirmation2018 masterConfirmation);
public static final class NewFloatingPayoutDefault extends NewFloatingPayout {
@Override
protected InterestRatePayout.InterestRatePayoutBuilder doEvaluate(EquitySwapMasterConfirmation2018 masterConfirmation) {
return InterestRatePayout.builder();
}
}
}
|
Java
|
UTF-8
| 1,234 | 2.453125 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bankproject;
import controllers.ClientFinder;
import java.io.IOException;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.stage.Stage;
/**
*
* @author Andoni
*/
public class BankProject extends Application {
private static final Logger LOGGER = Logger.getLogger
(BankProject.class.getPackage() + "." + BankProject.class.getName());
@Override
public void start(Stage stage) throws IOException {
FXMLLoader loader = new FXMLLoader(
getClass().getResource("/fxmlWindows/clientFinder.fxml"));
Parent root = (Parent) loader.load();
ClientFinder controller = (ClientFinder) loader.getController();
controller.setStage(stage);
LOGGER.info("Cargando ClientFinder");
controller.initStage(root);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
|
Python
|
UTF-8
| 415 | 3.5625 | 4 |
[] |
no_license
|
mystr = input()
count = 0
max_count = -1
max_occr=''
ans = list()#if we have multiple answer
for i in mystr:
count = mystr.count(i)
if(count > max_count):
max_count = count
max_occr = i
for i in mystr:
count = mystr.count(i)
if(count == max_count):
if(i not in ans):
ans.append(i)
for i in ans:
print(i," ",end='')
|
C++
|
UTF-8
| 724 | 2.640625 | 3 |
[] |
no_license
|
#include "person.h"
#include "ui_person.h"
Person::Person(QWidget *parent) :
QDialog(parent),
ui(new Ui::Person)
{
ui->setupUi(this);
}
Person::Person(const Person &obj) {
name = obj.name;
//dok = obj.dok;
diag = obj.diag;
}
Person::~Person() {
delete ui;
}
void Person::on_Name_textEdited(const QString &arg1) {
name = arg1;
qDebug () << name;
}
void Person::on_psss_or_diag_textEdited(const QString &arg1) {
diag = arg1;
qDebug() << diag;
}
void Person::on_pushButton_clicked() {
if(name.isEmpty() || diag.isEmpty())
close();
else {
flag = false;
write.push_back(Person(*this));
qDebug() << write[0].name;
close();
}
}
|
Ruby
|
UTF-8
| 1,107 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'optparse'
require 'noaa_weather_client'
def strip_coordinates!(args)
coordinates = args.last(2).select { |arg| arg =~ /-?\d{1,2}\.\d{2,}/ }
args.pop(2) if coordinates.size == 2
end
opts = OpenStruct.new(
postal_code: nil,
features: [ :observations ],
coordinates: strip_coordinates!(ARGV)
)
option_parser = OptionParser.new do |options|
options.set_banner "Usage: noaa_weather_client [options] latitude longitude"
options.separator ""
options.separator "Specific options:"
options.on("-p", "--postal_code CODE", "Resolve five digit postal code to coordinate.") do |postal_code|
opts.postal_code = postal_code
end
options.on("-f", "--forecast", "Include forecast for the location.") do |forecast|
opts.features << :forecast
end
options.on_tail("-h", "--help", "You're looking at it!") do
$stderr.puts options
exit 1
end
end
option_parser.parse!
if opts.postal_code
NoaaWeatherClient::CLI.postal_code_to_coordinate(opts.postal_code)
else
app = NoaaWeatherClient::CLI.new(*opts.coordinates)
app.render(*opts.features)
end
|
Java
|
UTF-8
| 21,702 | 2.1875 | 2 |
[] |
no_license
|
/**
* This file is part of the Joana IFC project. It is developed at the
* Programming Paradigms Group of the Karlsruhe Institute of Technology.
*
* For further details on licensing please read the information at
* http://joana.ipd.kit.edu or contact the authors.
*/
package edu.kit.joana.ifc.sdg.graph.slicer.conc.dynamic.krinke;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import edu.kit.joana.ifc.sdg.graph.SDG;
import edu.kit.joana.ifc.sdg.graph.SDGEdge;
import edu.kit.joana.ifc.sdg.graph.SDGNode;
import edu.kit.joana.ifc.sdg.graph.SDGNodeTuple;
import edu.kit.joana.ifc.sdg.graph.chopper.TruncatedNonSameLevelChopper;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.CFG;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.Context;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.ContextManager;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.FoldedCFG;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.StaticContextManager;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.DynamicContextManager.DynamicContext;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.building.GraphFolder;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.building.ICFGBuilder;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.threads.MHPAnalysis;
import edu.kit.joana.ifc.sdg.graph.slicer.graph.threads.PreciseMHPAnalysis;
/**
* This class realizes Krinke's optimized Algorithm for threaded interprocedural slicing.
* Uses thread regions.
*
* @author Dennis Giffhorn
* @version 1.0
*/
public class Slicer implements edu.kit.joana.ifc.sdg.graph.slicer.Slicer {
private class Visited {
private HashMap<Context, List<States>> markedStates;
private Visited() {
markedStates = new HashMap<Context, List<States>>();
}
private void add(WorklistElement w) {
// get the place for the context
List<States> s = markedStates.get(w.getContext());
if (s == null) {
s = new LinkedList<States>();
markedStates.put(w.getContext(), s);
}
// add the state tuple
s.add(w.getStates());
}
/** Checks if the given worklist element is restrictive according to a list of states.
* @param check The element to check.
* @param marked Contains the state tuple list for the context of check.
*/
private boolean isRedundant(WorklistElement check) {
List<States> oldStates = markedStates.get(check.getContext());
if (oldStates == null) return false;
// iterate over all states
for (States old : oldStates) {
// check for restrictiveness
if (isRestrictive(check.getStates(), old)){
return true;
}
}
return false;
}
/** Checks if a state tuple `actual' is restrictive to a state tuple `previous'
*
*/
private boolean isRestrictive(States actual, States previous) {
// iterate over all states
for (int i = 0; i < previous.size(); i++) {
if (previous.state(i) == States.NONRESTRICTIVE) {
continue;
} else if (actual.state(i) == States.NONRESTRICTIVE) {
return false;
} else if (actual.state(i) == States.NONE) {
continue;
} else if (previous.state(i) == States.NONE) {
return false;
} else if (!reaches(actual.state(i), previous.state(i))) {
return false;
}
}
return true;
}
}
public static long elems = 0L;
private static boolean TIME_TRAVELS = true;
/** the corresponding interprocedural control flow graph */
protected CFG icfg;
/** The graph to be sliced. */
protected SDG sdg;
/** The folded ICFG. */
protected FoldedCFG foldedIcfg;
protected ContextManager conMan;
/** A reachability checker for control flow graphs. */
protected ReachabilityChecker reachable;
/** the call site of the threads of the program to slice */
protected SDGNode threadCall;
/** the call site for the main() thread **/
protected SDGNode mainCall;
protected Context2PhaseSlicer c2pSlicer;
/** A summary slicer. */
protected SummarySlicer summarySlicer;
/** A truncated non-same-level chopper. */
protected TruncatedNonSameLevelChopper truncated;
protected MHPAnalysis mhp;
protected LinkedList<Context> empty = new LinkedList<Context>();
protected Visited visited;
/** DEBUG information*/
public static long eingefuegt = 0l;
public static int aufruf = 0;
public static int chopaufruf = 0;
public static int summaryaufruf = 0;
public long eingefuegt() {
return eingefuegt;
}
public int optimierung = 0;
public int opt() {
return optimierung;
}
public int opt1Sliced, opt1NotSliced = 0;
public String opt1() {
return "(slicer: "+opt1Sliced + ", map: "+opt1NotSliced+")";
}
public int noReach, reach, reducedReach = 0;
public String opt2() {
return "(no reach: "+noReach+", CFG: "+reach + ", reduced CFG: "+reducedReach+")";
}
public Slicer() { }
/**
* Creates a new instance of this slicer.
*
* @param graph A threaded interprocedural program dependencies graph that shall be sliced.
* It has to contain control flow edges.
*/
public Slicer(SDG graph) {
setGraph(graph);
}
/**
* Initializes the fields of the slicer.
*
* @param graph A threaded interprocedural program dependencies graph that shall be sliced.
* It has to contain control flow edges.
*/
public void setGraph(SDG graph) {
// init context-using 2-phase slicer
sdg = graph;
conMan = StaticContextManager.create(sdg);
// build the threaded ICFG
icfg = ICFGBuilder.extractICFG(sdg);
// fold ICFG with Krinke's two-pass folding algorithm
foldedIcfg = GraphFolder.twoPassFolding(icfg);
c2pSlicer = new Context2PhaseSlicer(sdg, conMan);
// a simple 2-phase slicer
// the summary slicer shall not traverse interference edges
summarySlicer = new SummarySlicer(sdg);
// a truncated non-same-level chopper
truncated = new TruncatedNonSameLevelChopper(sdg);
mhp = PreciseMHPAnalysis.analyze(sdg);
// a reachability checker for ICFGs
reachable = new ReachabilityChecker(foldedIcfg);
}
public Collection<SDGNode> slice(SDGNode criterion) {
return slice(Collections.singleton(criterion));
}
/**
* The slicing algorithm.
*
* @param criterion Contains a node and a thread ID for which the program
* shall be sliced.
*/
public Collection<SDGNode> slice(Collection<SDGNode> criteria) {
// the slice
HashSet<SDGNode> slice = new HashSet<SDGNode>();
/*** slicing.. ***/
// sequential slice for the contexts of the slicing criteria
Collection<SDGNode> interferingNodes = summarySlicer.slice(criteria, slice);
if (interferingNodes.isEmpty()) {elems++;
return slice;
} else {
Collection<SDGNode> chop = truncated.chop(interferingNodes, criteria);
krinkeSlice(criteria, chop, slice);
return slice;
}
}
private void krinkeSlice(Collection<SDGNode> criteria, Collection<SDGNode> restrict, Collection<SDGNode> slice) {
// all appeared state tuples for every appeared context
visited = new Visited();
// the three worklists
LinkedList<WorklistElement> w = initialWorklist(criteria);
LinkedList<WorklistElement> w0 = new LinkedList<WorklistElement>();
for(WorklistElement o : w){
visited.add(o);
elems++;
}
threadLocalSlice(w, slice, w0, restrict);
while (!w0.isEmpty()) {
LinkedList<WorklistElement> next = new LinkedList<WorklistElement>();
WorklistElement elem = w0.poll();
next.add(elem);
for (WorklistElement we : w0) {
if (we.getThread() == elem.getThread()) {
next.add(we);
}
}
w0.removeAll(next);
Collection<SDGNode> interferingNodes = c2pSlicer.contextSlice(next, slice);
if (!interferingNodes.isEmpty()) {
HashSet<SDGNode> nodes = new HashSet<SDGNode>();
next.add(elem);
for (WorklistElement we : next) {
nodes.add(we.getNode());
}
restrict = truncated.chop(interferingNodes, Collections.singleton(elem.getNode()));
threadLocalSlice(next, slice, w0, restrict);
}
}
}
private void threadLocalSlice(Collection<WorklistElement> elem, Collection<SDGNode> slice,
LinkedList<WorklistElement> wNext, Collection<SDGNode> restrict) {
LinkedList<WorklistElement> w1 = new LinkedList<WorklistElement>();
LinkedList<WorklistElement> w2 = new LinkedList<WorklistElement>();
w1.addAll(elem);
while (!w1.isEmpty()) {
// process the next element
WorklistElement next = w1.poll();
Context context = next.getContext();
States states = next.getStates();
int thread = next.getThread();
slice.add(next.getNode());
// handle all incoming edges of 'next'
for(SDGEdge e : sdg.incomingEdgesOf(next.getNode())) {
if (!e.getKind().isSDGEdge()) continue;
SDGNode source = e.getSource();
if (e.getKind().isThreadEdge()) {
for (int t : source.getThreadNumbers()) {
// make sure we in fact change threads
if (t != thread || mhp.isDynamic(thread)) {
// get all valid context for 'source'
Collection<Context> valid = reachingContexts(source, t, next);
// create new worklist elements
for (Context con : valid) {
States newStates = update(states, con);
WorklistElement we = new WorklistElement(con, newStates);
if (!visited.isRedundant(we)) {
visited.add(we);
wNext.add(we);
elems++;
}
}
}
}
} else if (restrict.contains(source)) {
// distinguish between different kinds of edges
if (e.getKind() == SDGEdge.Kind.PARAMETER_IN
&& source.getKind() == SDGNode.Kind.FORMAL_OUT) {
// Class initializer methods have a special integration into our SDGs.
// Their formal-out vertices have outgoing param-in edge, which connect them with
// the rest of the SDG.
Collection<Context> newContexts = conMan.getAllContextsOf(source);
// update the worklist
for (Context con : newContexts) {
States newStates = update(states, con);
WorklistElement we = new WorklistElement(con, newStates);
if (!visited.isRedundant(we)) {
visited.add(we);
w1.add(we);
}
}
} else if (e.getKind() == SDGEdge.Kind.CALL
|| e.getKind() == SDGEdge.Kind.PARAMETER_IN) {
// go to the calling procedure
if (source.isInThread(thread) && context.isInCallingProcedure(source)) {
SDGNodeTuple callSite = sdg.getCallEntryFor(e);
Context[] newContexts = conMan.ascend(source, callSite, context);
for (Context con : newContexts) {
if (con != null) {
States newStates = update(states, con);
WorklistElement we = new WorklistElement(con, newStates);
if (!visited.isRedundant(we)) {
visited.add(we);
w1.add(we);
}
}
}
}
} else if (e.getKind() == SDGEdge.Kind.PARAMETER_OUT) {
// go to the called procedure
SDGNodeTuple callSite = sdg.getCallEntryFor(e);
Context con = conMan.descend(source, callSite, context);
States newStates = update(states, con);
WorklistElement we = new WorklistElement(con, newStates);
if (!visited.isRedundant(we)) {
visited.add(we);
w2.add(we);
}
} else {
// intra-procedural traversal
Context con = conMan.level(source, context);
States newStates = update(states, con);
WorklistElement we = new WorklistElement(con, newStates);
if (!visited.isRedundant(we)) {
visited.add(we);
w1.add(we);
}
}
}
}
}
// slice
while(!w2.isEmpty()) {
// process the next element
WorklistElement next = w2.poll();
Context context = next.getContext();
States states = next.getStates();
int thread = next.getThread();
slice.add(next.getNode());
// handle all incoming edges of 'next'
for(SDGEdge e : sdg.incomingEdgesOf(next.getNode())){
if (!e.getKind().isSDGEdge()) continue;
SDGNode source = e.getSource();
if (e.getKind().isThreadEdge()) {
for (int t : source.getThreadNumbers()) {
// make sure we in fact change threads
if (t != thread || mhp.isDynamic(thread)) {
// get all valid context for 'source'
Collection<Context> valid = reachingContexts(source, t, next);
// create new worklist elements
for (Context con : valid) {
States newStates = update(states, con);
WorklistElement we = new WorklistElement(con, newStates);
if (!visited.isRedundant(we)) {
visited.add(we);
wNext.add(we);
elems++;
}
}
}
}
} else if (restrict.contains(source)) {
// distinguish between different kinds of edges
if (e.getKind() == SDGEdge.Kind.CALL || e.getKind() == SDGEdge.Kind.PARAMETER_IN) {
// skip
} else if (e.getKind() == SDGEdge.Kind.PARAMETER_OUT) {
// go to the called procedure
SDGNodeTuple callSite = sdg.getCallEntryFor(e);
Context con = conMan.descend(source, callSite, context);
States newStates = update(states, con);
WorklistElement we = new WorklistElement(con, newStates);
if (!visited.isRedundant(we)) {
visited.add(we);
w2.add(we);
}
} else {
// intra-procedural traversal
Context con = conMan.level(source, context);
States newStates = update(states, con);
WorklistElement we = new WorklistElement(con, newStates);
if (!visited.isRedundant(we)) {
visited.add(we);
w2.add(we);
}
}
}
}
}
}
/**
* Computes all valid contexts according to an interference edge traversion.
* It creates all possible contexts and performs a reaching analysis with
* regard to a given state tuple.
*
* @param source The node the interference edge is traversed to.
* @param thread The node's thread..
* @param w The worklist element representing the point where the old thread is left.
* It contains the state tuple for the reaching analysis.
*/
private Collection<Context> reachingContexts(SDGNode source, int thread, WorklistElement w) {
Collection<Context> reached = new LinkedList<Context>();
Context target = w.getStates().state(thread);
if (target == States.NONRESTRICTIVE || !TIME_TRAVELS) {
// if the thread was not visited yet, all contexts are valid
return conMan.getContextsOf(source, thread);
} else if (target == States.NONE) {
return empty;
} else {
// retrieve all possible contexts for source in its thread
Collection<Context> contextList = conMan.getContextsOf(source, thread);
// return every context of source that reaches target
for (Context s : contextList) {
// if reachable, add context to reached list
if (reaches(s, target)) {
reached.add(s);
}
}
}
return reached;
}
/**
* Creates the initial worklist for the slicing algorithm.
* It consists of a LinkedList containing one ThreadedWorklistElement for
* every context which can reach the given starting criterion.
*
* @param data.node The starting criterion.
* @return A LinkedList, maybe empty.
*/
private LinkedList<WorklistElement> initialWorklist(Collection<SDGNode> criteria) {
LinkedList<WorklistElement> s = new LinkedList<WorklistElement>();
for (SDGNode node : criteria) {
int[] threads = node.getThreadNumbers();
for (int thread : threads) {
Collection<Context> contexts = conMan.getContextsOf(node, thread);
for (Context con : contexts) {
States newStates = update(new States(sdg.getNumberOfThreads()), con);
WorklistElement w = new WorklistElement(con, newStates);
if (!visited.isRedundant(w)) {
visited.add(w);
s.add(w);
}
}
}
}
return s;
}
/** Maps a SDG-Context to a CFG-Context.
* This mapping is nessecary as SDG and CFG are folded differently.
*
* @param origin A SDG-Context.
* @param foldedCall The call graph.
* @param foldedIcfg The CFG
* @return A CFG-Context.
*/
private DynamicContext map(Context origin) {
// list for building the context that maps to Context 'con'
LinkedList<SDGNode> res = new LinkedList<SDGNode>();
// for every vertex in the call stack of 'con' determine the fold vertex in graph 'to'
for (SDGNode node : origin.getCallStack()) {
// add found vertex to list 'res'
if (node.getKind() == SDGNode.Kind.FOLDED) {
// If the folded node is induced by a cycle of return edges,
// and the topmost call site of 'context' is the folded call cycle
// according to the return-cycle, create a context without this
// topmost call site and add it to the initial worklist.
if (node.getLabel() == GraphFolder.FOLDED_RETURN) {
// creates a context without the the folded call cycle
// according to the return-cycle
SDGNode call = returnCall(node);
if (res.size() == 0 || call != res.getLast()) {
res.addLast(call);
}
}
// maps node to the belonging node of the CFG
SDGNode x = map(node);
// prohibit redundant piling of Contexts
if (res.size() == 0 || x != res.getLast()) {
res.addLast(x);
}
} else {
res.addLast(foldedIcfg.map(node));
}
}
SDGNode node = foldedIcfg.map(origin.getNode());
if (res.size() > 0 && node == res.getLast()) {
res.removeLast();
}
return new DynamicContext(res, node, origin.getThread());
}
/** Maps a SDG-node to a CFG-node.
*
* @param node A SDG-node.
* @param foldedCall The call graph.
* @param foldedIcfg The CFG
* @return A CFG-node.
*/
private SDGNode map(SDGNode node) {
// 1. get one of the unmapped nodes
SDGNode unmapped = conMan.unmap(node);
// 2. get mapping in the other graph
return foldedIcfg.map(unmapped);
}
/** Computes the folded call cycle belonging to a folded return cycle.
*
* @param returnFold The folded return cycle.
* @return The belonging call cycle.
*/
private SDGNode returnCall(SDGNode returnFold) {
LinkedList<SDGNode> worklist = new LinkedList<SDGNode>();
SDGNode callFold = null;
worklist.add(returnFold);
// find the corresponding folded call cycle
loop:
while (!worklist.isEmpty()) {
SDGNode next = worklist.poll();
for (SDGEdge cf : foldedIcfg.getIncomingEdgesOfKind(next, SDGEdge.Kind.CONTROL_FLOW)) {
if (cf.getSource().getKind() == SDGNode.Kind.FOLDED
&& cf.getSource().getLabel() == GraphFolder.FOLDED_CALL) {
callFold = cf.getSource();
break loop;
}
worklist.addFirst(cf.getSource());
}
}
return callFold;
}
private boolean reaches(Context start, Context target) {
// map the target to the folded ICFG
DynamicContext mappedTarget = map(target);
DynamicContext mappedStart = map(start);
return reachable.reaches(mappedStart, mappedTarget);
}
protected States update(States s, Context c) {
States newStates = s.clone();
int thread = c.getThread();
for (int x = 0; x < sdg.getNumberOfThreads(); x++) {
if (x == thread) {
if (!mhp.isDynamic(x)) {
// adjust the state of the thread
newStates.set(x, c);
} else System.out.println(2);
} else if (newStates.state(x) == States.NONE) {
if (mhp.mayExist(x, c.getNode(), thread)) {
// activate that thread
newStates.set(x, States.NONRESTRICTIVE);
}
} else if (!mhp.mayExist(x, c.getNode(), thread)) {
// activate that thread
newStates.set(x, States.NONE);
}
}
return newStates;
}
}
|
Java
|
UTF-8
| 529 | 2.609375 | 3 |
[] |
no_license
|
package com.accolite.bookingBus;
import com.accolite.bookingTemplate.BookingTemplate;
public class BookingBus extends BookingTemplate{
// Declaring transport name and its value
private final static String transportName = "Bus";
// Get mode of transport
public void getModeOfTransport() {
System.out.println("Mode of Transport: "+transportName);
}
// Get report
public void getReport() {
this.getCustomerDetails();
this.getTransportDetails();
System.out.println("Mode of transport: " + transportName);
}
}
|
C++
|
GB18030
| 974 | 3.25 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
#include "Database.h"
#include "Function.h"
using namespace std;
int main()
{
//ѭڵĴͨmainChoiceʵֳ˳ݿĴ˵ѡ˳ѭbreakѡ˴µݿ⣬ѭڵڶѭڱǶ̬ѭڴģ³ʼ
Database MyData("MyData");
cout << "ӭʹMyDataݿϵͳDOS1.0V!" << endl;
pause();
system("cls");
while (true)
{
int mainChoice = 0;
string preName = "MyData";
static int posNum = 0;
string name = preName + to_string(posNum);
Database MyData(name);
function_main(MyData, mainChoice);
posNum++;//ݿԶĺݿⴴ
if (mainChoice == -1)
break;
if (mainChoice == 1)
continue;
}
cout << "ӭٴʹñݿ!" << endl;
return 0;
}
|
Markdown
|
UTF-8
| 2,418 | 3.046875 | 3 |
[
"Apache-2.0"
] |
permissive
|
SimplicityJS
============
Pattern matching in JavaScript
A port of [Simplicity for C#](https://github.com/becdetat/Simplicity) to JavaScript.
## Installation
npm install --save-dev simplicityjs
**Note that the NPM package name is `simplicityjs`, not `simplicity` (which was already taken). Add a reference to `./node_modules/simplicityjs/dist/simplicity.js`.**
## Usage
These examples are in ES6.
import match from 'simplicityjs'
var letter = 'f';
var result = match(letter)
.with('a', 'Letter is A')
.with('b', 'Letter is B')
.with(x => 'c' <= x && x <= 'h', x => 'Letter ' + x + ' is between c and h')
.else(x => 'Letter ' + x + ' is out of range')
.do();
// result = 'Letter f is between c and h'
Call it without a value and call `toFunc()` at the end of the method chain to get a function value that can be reused:
var formatFuzzyAmount = match()
.with(0, 'None')
.with(x => 0 < x && x <= 0.125, 'Just a bit')
.with(x => 0.125 < x && x <= 0.29, 'About one quarter')
.with(x => 0.29 < x && x <= 0.41, 'About one third')
.with(x => 0.41 < x && x <= 0.58, 'About half')
.with(x => 0.58 < x && x <= 0.7, 'About two thirds')
.with(x => 0.7 < x && x <= 0.875, 'About three quarters')
.with(x => 0.875 < x && x < 1, 'Almost all')
.else('All')
.toFunc();
var oneQuarter = formatFuzzyAmount(0.25);
var twoThirds = formatFuzzyAmount(0.66);
// oneQuarter = 'About one quarter'
// twoThirds = 'About two thirds'
## Building and contributing
1. Install NPM
2. Clone the SimplicityJS repo
3. `npm install`
SimplicityJS's source is in ES6, transpiled to ES5 (the widely currently supported version of JavaScript in browsers) using Babel via a Gulp script. To build, install Gulp globally (`sudo npm install -g gulp`) and run `gulp` from the repo root. The default Gulp task will run Babel and write the result to `./dist/simplicity.js`.
## Deploying to NPN
These are instructions to myself ;-)
1. `npm login`, provide creds
2. `npm publish`
that was easy
## Versions
- 3.0.1 - *sigh* need to `export default` not just `export`. if only _someone_ had written a test suite for this library.
- 3.0.0 - Whoops, didn't actually build the dist js... Also removed support for distribution via Bower
- 2.0.0 - use ES6 export, don't add it to `window` - breaking change
- 1.0.0 - version bump because yay NPM publishing!
- 0.1.0 - first version, port of Simplicity for C#
|
Java
|
UTF-8
| 1,652 | 2.515625 | 3 |
[] |
no_license
|
package com.servi.cloud.consumer.util.proxy.jdk;
import sun.misc.ProxyGenerator;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test {
private static void saveProxyFile() {
FileOutputStream out = null;
try {
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", RealHandlerInterface.class.getInterfaces());
out = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\IHandlerInterface" + "$Proxy0.class");
out.write(classFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
saveProxyFile();
Object target = new RealHandlerInterface();
/**
* loader:业务对象的类加载器
* interfaces:业务对象实现的所有接口
* public static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)
*/
Class<?> proxyClass = Proxy.getProxyClass(RealHandlerInterface.class.getClassLoader(), RealHandlerInterface.class.getInterfaces());
InvocationHandler handler = new Handler(target);
IHandlerInterface userDao = (IHandlerInterface) proxyClass.getConstructor(InvocationHandler.class).newInstance(handler);
userDao.test();
}
}
|
C
|
UTF-8
| 12,401 | 2.53125 | 3 |
[
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LGPL-2.0-only",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only"
] |
permissive
|
/*
* GraphApp - Cross-Platform Graphics Programming Library.
*
* File: menus.c -- creating menus, menubars, etc.
* Platform: Windows Version: 2.35 Date: 1998/04/04
*
* Version: 1.00 Changes: Original version by Lachlan Patrick.
* Version: 2.00 Changes: New object class system.
* Version: 2.15 Changes: Added submenu creation function.
* Version: 2.20 Changes: New menuitem constructor.
* Version: 2.30 Changes: Modified the shortcut key selector.
* Version: 2.35 Changes: New reference count technique.
*/
/* Copyright (C) 1993-1998 Lachlan Patrick
This file is part of GraphApp, a cross-platform C graphics library.
GraphApp is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License.
GraphApp is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY.
See the file COPYLIB.TXT for details.
*/
/*
* When you create menubars, menus and menuitems, they are added
* to the currentwindow. Menus are added to the current_menubar and
* menuitems are added to the current_menu.
*/
/* Copyright (C) 2004 The R Foundation
Change for R - Chris Jackson. Enabled menu shortcut keys, don't
execute shortcut if menu item is grayed out */
#include "internal.h"
/*#include "config.h" */
#include <wchar.h>
#define mbs_init(x) memset(&x,0,sizeof(x))
size_t Rf_mbrtowc(wchar_t *wc, const char *s, size_t n, mbstate_t *ps);
/*
* Menu variables.
*/
PROTECTED int menus_active = 1;
PROTECTED menubar current_menubar = NULL;
PROTECTED menu current_menu = NULL;
static int id = MinMenuID;
PROTECTED HACCEL hAccel = 0;
/*
* Initialise menus. Actually, all we do here is load accelerators.
* The accelarator resource must have the name "ACCELS".
* If there are no accelerator resources, hAccel will be zero.
*/
PROTECTED
void init_menus(void)
{
if (this_instance != 0)
hAccel = LoadAccelerators(this_instance, "ACCELS");
}
/*
* Find the position of a menu on its parent menubar.
* Return zero for the first menu, one for the next etc.
*/
static int find_menu_position(menu parent, char *name)
{
menu m, first;
int which = 0;
first = m = parent->child;
if (first) {
do {
if (strcmp(m->text, name) == 0)
break;
which ++;
m = m->next;
} while (m != first);
}
return which;
}
/*
* Private menu deletion function.
*/
static void private_delmenu(menu m)
{
window w = parentwindow(m);
if (m->kind == MenuitemObject)
RemoveMenu(m->parent->handle, m->id, MF_BYCOMMAND);
else if (m->kind == MenuObject) {
DeleteMenu(m->parent->handle,
find_menu_position(m->parent, m->text),
MF_BYPOSITION);
}
else
DestroyMenu(m->handle);
if (w)
DrawMenuBar(w->handle);
}
/*
* Find a char within a string.
* Return -1 if not found, or a number from 0 to strlen(str)-1
* to indicate where the char is.
*/
char *Rf_strchr(const char *s, int c); /* from util.c, MBCS-aware */
static int find_char(int ch, const char *str)
{
char *p;
p = Rf_strchr(str, ch);
if(!p) return -1; else return p - str;
}
/*
* This function forms a search string, to look for the best
* letter to underline in a menu item. It first tries the
* accelerator key, then the uppercase letters from the menu name,
* then the digits, and finally the lowercase letters.
* It ignores spaces.
*/
static void set_search_string(char *search, const char *name, int key)
{
int source;
int dest = 0;
int mb_len;
mbstate_t mb_st;
/* handle a couple of special cases first */
if (! string_diff(name, "Cut")) search[dest++] = 't';
if (! string_diff(name, "Exit")) search[dest++] = 'x';
if (! string_diff(name, "?")) search[dest++] = '?';
{
/* If there is an '&' in the string, use the next letter first */
char *p = strchr(name, '&');
if (p && *(p+1)) search[dest++] = *(p+1);
}
/* add the accelerator key if it is in the name string */
if (key) {
key = toupper(key);
if (find_char(key, name) >= 0)
search[dest++] = (char) key;
else {
key = tolower(key);
if (find_char(key, name) >= 0)
search[dest++] = (char) key;
}
}
/* add the uppercase letters */
for (source=0; name[source]; source++) {
mbs_init(mb_st);
mb_len = Rf_mbrtowc(NULL, name + source, MB_CUR_MAX,&mb_st);
if (mb_len > 1) source += mb_len-1;
else
if (isupper(name[source])) search[dest++] = name[source];
}
/* add the digits */
for (source=0; name[source]; source++) {
mbs_init(mb_st);
mb_len = Rf_mbrtowc(NULL, name + source, MB_CUR_MAX,&mb_st);
if (mb_len > 1) source += mb_len-1;
else
if (isdigit(name[source])) search[dest++] = name[source];
}
/* add the lowercase letters */
for (source=0; name[source]; source++) {
mbs_init(mb_st);
mb_len = Rf_mbrtowc(NULL, name + source, MB_CUR_MAX,&mb_st);
if (mb_len > 1) source += mb_len-1;
else
if (islower(name[source])) search[dest++] = name[source];
}
/* end the search string */
search[dest] = '\0';
}
/*
* Look through the list of siblings of the given object, and
* find a shortcut key from the search string which hasn't already
* been used by some other object. Return the valid shortcut char,
* or else zero if we can't find one.
*/
static int find_shortcut(object me, char *search)
{
int source;
object first, obj;
first = me->parent->child;
for (source = 0; search[source]; source++)
{
int mb_len;
mbstate_t mb_st;
mbs_init(mb_st);
mb_len = Rf_mbrtowc(NULL, search + source, MB_CUR_MAX, &mb_st);
if ( mb_len > 1 ) {
source += mb_len - 1;
} else
/* for each character in the search string */
/* look through every sibling object */
for (obj = first; obj; obj = obj->next)
{
if (obj == me) /* at end of list, success! */
return search[source];
/* use uppercase comparisons */
if (obj->shortcut == toupper(search[source]))
break; /* can't use this shortcut */
}
}
return 0;
}
/*
* Take "Open..." and 'O' and produce the string "Open...\tCtrl+O".
* This function also sets an object's shortcut key, which is the
* underlined letter in a menu item in Windows or X-Windows.
*/
static void setmenustring(object obj, char *buf, const char *name, int key)
{
char search[256];
int ch, where, source, dest = 0;
char *extra = "\tCtrl+";
set_search_string(search, name, key);
ch = find_shortcut(obj, search);
if (ch) /* found a valid shortcut key */
{
obj->shortcut = toupper(ch); /* case-insensitive */
where = find_char(ch, name);
for (source=0; source < where; source++)
{
int mb_len;
int i;
mbstate_t mb_st;
mbs_init(mb_st);
mb_len = Rf_mbrtowc(NULL, name + source, MB_CUR_MAX, &mb_st);
if ( mb_len > 1 ) {
for (i = 0 ; i < mb_len ; i++)
buf[dest++] = name[source+i];
source += mb_len-1;
} else if(name[source] == '&') {
/* skip it */
} else
buf[dest++] = name[source];
}
buf[dest++] = '&';
for (; name[source]; source++)
buf[dest++] = name[source];
}
else /* no shortcut key, just copy the name string except '&' */
{
for (source = 0; name[source]; source++)
if(name[source] != '&') buf[dest++] = name[source];
}
if (key) {
for (source=0; extra[source]; source++)
buf[dest++] = extra[source];
buf[dest++] = key;
}
buf[dest] = '\0';
}
/*
* Menu functions.
*/
menubar newmenubar(actionfn adjust_menus)
{
object obj;
HMENU hm;
if (! current_window) {
current_window = simple_window();
show(current_window);
}
hm = CreateMenu();
obj = new_object(MenubarObject, hm, current_window);
if (obj) {
current_window->menubar = obj;
obj->menubar = NULL;
obj->die = private_delmenu;
obj->id = id++;
obj->action = adjust_menus;
obj->text = new_string("Menubar");
current_menubar = obj;
SetMenu(current_window->handle, hm);
}
return (menubar) obj;
}
BOOL myAppendMenu(HMENU h, UINT flags, UINT_PTR id, LPCTSTR name)
{
if(localeCP > 0 && (localeCP != GetACP())) {
wchar_t wc[100];
mbstowcs(wc, name, 100);
return AppendMenuW(h, flags, id, wc);
} else
return AppendMenuA(h, flags, id, name);
}
menu newsubmenu(menu parent, const char *name)
{
object obj;
HMENU hm;
UINT flags = MF_POPUP;
char str[256];
if (! parent) {
if (! current_menubar)
current_menubar = newmenubar(NULL);
parent = current_menubar;
}
if (! parent)
return NULL;
if (! name)
name = "";
if (name[0] == '\t') {
name += 1;
flags |= MF_HELP;
}
if (parent->kind == WindowObject)
hm = CreatePopupMenu();
else
hm = CreateMenu();
obj = new_object(MenuObject, hm, parent);
if (obj) {
obj->die = private_delmenu;
obj->id = id++;
obj->text = new_string(name);
setmenustring(obj, str, name, 0);
name = str;
current_menu = obj;
}
if (parent->kind != WindowObject)
myAppendMenu(parent->handle, flags, (UINT_PTR) hm, name);
if (parent == current_menubar)
DrawMenuBar(current_menubar->parent->handle);
return (menu) obj;
}
menu newmenu(const char *name)
{
return newsubmenu(current_menubar, name);
}
menuitem newmenuitem(const char *name, int key, menufn fn)
{
object obj;
UINT flags;
char str[256];
if (! current_menu)
current_menu = newmenu("Special");
if (! current_menu)
return NULL;
if (! name)
name = "-"; /* separator */
key = toupper(key); /* make it uppercase */
obj = new_object(MenuitemObject, 0, current_menu);
if (obj) {
obj->die = private_delmenu;
obj->id = id++;
obj->key = key;
obj->action = fn;
obj->value = 0;
obj->text = new_string(name);
obj->state |= Enabled;
if (name[0] == '-') {
flags = MF_SEPARATOR;
name = NULL;
} else {
flags = MF_STRING;
setmenustring(obj, str, name, key);
name = str;
}
myAppendMenu(current_menu->handle, flags, obj->id, name);
}
return (menuitem) obj;
}
/*
* Find various parent objects of a menu (or any object).
*/
#if 0
PROTECTED
object parent_menubar(object obj)
{
while (obj) {
if (obj->kind == MenubarObject)
break;
obj = obj->parent;
}
return obj;
}
PROTECTED
object parent_menu(object obj)
{
while (obj) {
if (obj->kind == MenuObject)
break;
obj = obj->parent;
}
return obj;
}
#endif
/*
* The adjust_menu function is called just after the program
* receives a WM_INITMENU message. This message is sent even if
* the user is attempting to use the system menu, which is nice.
* We use this function to keep menubars and menus up-to-date by
* calling their respective action functions.
*/
PROTECTED
void adjust_menu(WPARAM wParam)
{
object obj;
obj = find_by_handle((HANDLE)wParam);
if (obj) {
activatecontrol(obj);
if (obj->kind == MenubarObject)
DrawMenuBar(obj->parent->handle);
}
}
/*
* Handle the menu selection. wParam is what WM_[SYS]COMMAND sets
* it to i.e. the object id number. The menus will already have
* received WM_INITMENU messages so they will be up-to-date.
*/
PROTECTED
void handle_menu_id (WPARAM wParam)
{
object obj;
obj = find_by_id(wParam);
if (obj)
activatecontrol(obj);
}
/*
* Handle a menu accelerator key. The key will be a normal char,
* in the range of 0..9 or A..Z (not a..z because we use KEYDOWNs).
* Uses a recursive function to call the menu adjustor functions
* in order from menubar down to popup menu.
*/
static void adjust_menus_top_down(object obj)
{
/* Recursively step up the list. */
if (! obj)
return;
adjust_menus_top_down(obj->parent);
/* Adjust menubar then child menus as we descend. */
if (obj->kind == MenubarObject) {
activatecontrol(obj);
DrawMenuBar(obj->parent->handle);
}
else if (obj->kind == MenuObject)
activatecontrol(obj);
}
/* Only search for the key within the menus of the focused window.
If key is not found fall through to user's key handler. CJ */
PROTECTED
int handle_menu_key(WPARAM wParam)
{
object win, obj;
win = find_by_handle(GetFocus());
if (win) {
if (win->kind != WindowObject)
win = win->parent;
obj = find_by_key(win, wParam);
if (obj) {
adjust_menus_top_down(obj);
if (isenabled(obj)) /* Don't do menu actions which are greyed out. CJ */
activatecontrol(obj);
return 1;
}
}
return 0;
}
|
Shell
|
UTF-8
| 2,609 | 4.34375 | 4 |
[] |
no_license
|
#! /bin/bash
# bash colors
COL_GREEN="\e[1;32m"
COL_YELLOW="\e[1;33m"
COL_RED="\e[1;31m"
COL_BLUE="\e[1;34m"
COL_CYAN="\e[1;36m"
COL_STOP="\e[0m"
# Build Phi firmware but check some stuff first
echo -e $COL_CYAN
echo '****************'
echo '* Build Phi *'
echo '****************'
echo -e $COL_STOP
# get hostname to use as part of directory names
HOST_NAME=`uname -n`
# temporary directory for cmake files so they don't
# end up all mixed up with the source.
TMP_DIR="cmake.tmp.$HOSTNAME"
#
# process arguments
#
DEBUG_MODE=false
for var in "$@"
do
if [[ $var == debug ]] ; then
DEBUG_MODE=true
TMP_DIR="$TMP_DIR.dbg"
elif [[ $var == clean ]] ; then
echo "### cleaning target ###"
cd $TMP_DIR
make clean
echo done.
exit 0
elif [[ $var == clean_cmake ]] ; then
echo "## cleaning cmake cache ##"
rm -rf $TMP_DIR
echo done.
exit 0
else
echo "### Invalid argument \"$var\" ###"
exit 1
fi
done
if [[ $DEBUG_MODE == true ]] ; then
echo 'Selecting *** DEBUG *** mode'
BUILD_TYPE="-DCMAKE_BUILD_TYPE=Debug"
BIN_DIR="bin-debug"
else
echo Selecting RELEASE mode
BUILD_TYPE="-DCMAKE_BUILD_TYPE=Release"
BIN_DIR="bin"
fi
TARGET_FN=$BIN_DIR/phi-$HOST_NAME
# create TMP_DIR if it doesn't exist
if [ ! -e $TMP_DIR ] ; then
echo "Creating directory for cmake tmp files : $TMP_DIR"
mkdir $TMP_DIR
else
echo "Reusing cmake tmp dir : $TMP_DIR"
fi
#
# check build environment
#
echo Checking build environment ...
echo
# check that we have new version of pthread
PTHREAD_IMPL=`getconf GNU_LIBPTHREAD_VERSION`
if grep -q NPTL <<EOF
$PTHREAD_IMPL
EOF
then
echo -e "$COL_GREEN"OK"$COL_STOP" : PThread version is $PTHREAD_IMPL
else
echo -e "$COL_RED"FAIL"$COL_STOP" : PThread version obsolete - version is $PTHREAD_IMPL
exit
fi
# OK ... everything looks good
echo -e "$COL_GREEN"OK"$COL_STOP" : All tests complete
echo
# create makefiles with CMake
#
# Note: switch to tmp dir and build parent which
# is a way of making cmake tmp files stay
# out of the way.
#
# Note2: to clean up cmake files, it is OK to
# "rm -rf" the tmp dirs
echo Creating Makefiles with cmake ...
cd $TMP_DIR
cmake $BUILD_TYPE ..
# run makefile (in tmp dir)
echo
echo Starting build ...
make
MAKE_RET=$?
# if successful ... copy executable to bin dir
echo
if [ $MAKE_RET == 0 ] ; then
echo -e "$COL_GREEN"SUCCESS"$COL_STOP - copying PHI to ./$TARGET_FN"
cp ./src/phi "../$TARGET_FN"
else
echo -e "$COL_RED"BUILD FAILED"$COL_STOP"
echo
exit
fi
# done
echo
exit
|
TypeScript
|
UTF-8
| 1,740 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import chai from 'chai';
import fs from 'fs';
import waitOn from 'wait-on';
const expect = chai.expect;
import { createLogger } from '../../src/logger/logger';
const waitOnOptions = {
delay: 500,
interval: 500,
resources: ['app.log'],
timeout: 3000
};
function deleteLogFile(callback: any) {
fs.unlink('app.log', (error) => {
if (error && error.errno === -2 && error.code === 'ENOENT') {
console.log('deleteLogFile: Since the log file does not exist there is nothing to delete.');
}
callback();
});
}
describe('iot-device-information', () => {
describe('logger', function() {
this.timeout(5000);
before('delete log file', (done) => {
deleteLogFile((error: any) => {
if (error) {
done(error);
} else {
done();
}
});
});
it('should check whether a log file is created', (done) => {
const logger = createLogger();
logger.info('test log entry');
waitOn(waitOnOptions, (errorWaitOn) => {
if (errorWaitOn) {
done(errorWaitOn);
} else {
fs.readFile('app.log', (errorFileAccess, content) => {
if (errorFileAccess) {
done(errorFileAccess);
} else {
const logEntry = Buffer.from(content).toString();
expect(logEntry).to.contain('test log entry');
done();
}
});
}
});
});
});
});
|
Java
|
UTF-8
| 1,041 | 2.28125 | 2 |
[] |
no_license
|
package app.servlets;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "MngPhotoServlet", urlPatterns = {"/mphoto"})
public class MngPhotoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getSession().getAttribute("admin")==null){
response.sendRedirect("/admin");
}
else {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/photoM.html");
requestDispatcher.forward(request, response);
}
}
}
|
JavaScript
|
UTF-8
| 680 | 3.71875 | 4 |
[] |
no_license
|
const colours=["green","red","rgba(133,122,200)","#f15025","yellow","blue","purple","teal","pink","orange"];
const btn=document.getElementById("btn");
const color=document.querySelector(".colour");
btn.addEventListener("click",function(){
/*to get different background colors, we are using a random n umber having value
between 0 and 3....so as to access the array.*/
console.log("Hey! Its working");
const randomNumber= getRandonNumber();
document.body.style.backgroundColor=colours[randomNumber];
color.textContent=colours[randomNumber];
})
function getRandonNumber(){
const random=Math.random();
return Math.floor(random*colours.length);
}
|
TypeScript
|
UTF-8
| 1,192 | 2.609375 | 3 |
[] |
no_license
|
import { createSlice, PayloadAction, createSelector } from '@reduxjs/toolkit';
import { RootState } from 'app/store';
import { City } from 'models';
export interface CityState {
loading: boolean;
cityList: Array<City>;
}
const initialState: CityState = {
cityList: [],
loading: false,
};
const citySlide = createSlice({
name: 'city',
initialState,
reducers: {
fetchCityList: (state) => {
state.loading = true;
},
fetchCityListSuccess: (state, action: PayloadAction<City[]>) => {
state.loading = false;
state.cityList = action.payload;
},
fetchCityListError: (state) => {
state.loading = false;
},
},
});
export const cityActions = citySlide.actions;
//selector
export const cityList = (state: RootState) => state.city.cityList;
export const mapCityList = createSelector(cityList, (cityList) => {
return cityList.reduce((map: { [key: string]: City }, city) => {
map[city.code] = city;
return map;
}, {});
});
export const cityOptions = createSelector(cityList, (cityList) =>
cityList.map((item) => ({ label: item.name, value: item.code }))
);
const cityRedecer = citySlide.reducer;
export default cityRedecer;
|
Java
|
UTF-8
| 5,020 | 2.296875 | 2 |
[] |
no_license
|
package com.ruider.service.impl;
import com.ruider.mapper.LeaveingManageMapper;
import com.ruider.model.LeaveingManage;
import com.ruider.model.User;
import com.ruider.service.LeaveingManageService;
import com.ruider.service.UserService;
import com.ruider.utils.MailUtil.EmailCreator;
import com.ruider.utils.MailUtil.EmailSendInfo;
import com.ruider.utils.MailUtil.EmailSender;
import org.apache.ibatis.annotations.Options;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
@EnableScheduling
public class LeaveingManageServiceImpl implements LeaveingManageService {
private Logger logger = LoggerFactory.getLogger(LeaveingManageServiceImpl.class);
@Autowired
private LeaveingManageMapper leaveingManageMapper;
@Autowired
private UserService userService;
/**
* 每一天定时查看是否有「写给未来的ta」信件
*/
@Scheduled(fixedDelay = 24 * 60 * 60 *1000)
public void checkTimeOut () {
try {
logger.info("【每24小时执行一次,检查是否有需要发送给「未来的ta」的信件开始】checkTimeOut start");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
String nowStr = simpleDateFormat.format(now);
List<LeaveingManage> list = leaveingManageMapper.getTimeoutComplaints(simpleDateFormat.parse(nowStr));
for (LeaveingManage leaveingManage : list) {
User user = userService.getUserDetails(leaveingManage.getUserId());
EmailSendInfo emailSendInfo = EmailCreator.createEmail(leaveingManage.getMark() , user.getNickName(), leaveingManage.getContent());
EmailSender.sendTextMail(emailSendInfo);
logger.info("【「写给未来的ta」的信件发送成功】");
}
logger.info("【所有信件-->每24小时执行一次,检查是否有需要发送给「未来的ta」的信件成功】checkTimeOut succeed");
}
catch (Exception e) {
logger.error("【每24小时执行一次,检查是否有需要发送给「未来的ta」的信件失败】checkTimeOut failed",e);
}
}
/**
* 添加留言
* @param paramMap
* @return
* @throws Exception
*/
@Override
public int addLeaveingManage (HashMap<String,Object> paramMap) throws Exception {
LeaveingManage leaveingManage = new LeaveingManage();
leaveingManage.setCategoryId(Integer.valueOf(paramMap.get("categoryId").toString()));
leaveingManage.setUserId(Integer.valueOf(paramMap.get("userId").toString()));
leaveingManage.setContent(paramMap.get("content").toString());
if (!paramMap.get("mark").toString().equals("") ) {
leaveingManage.setMark(paramMap.get("mark").toString());
}
leaveingManage.setCreateTime(new Date());
return leaveingManageMapper.addLeaveingManage(leaveingManage);
}
/**
* 获取所有留言以及各个留言对应的发表者信息
* @return
* @throws Exception
*/
@Override
public ArrayList<HashMap<String,Object>> getAllLeaveingManage(int categoryId) throws Exception {
ArrayList<HashMap<String,Object>> result = new ArrayList<>();
List<LeaveingManage> list = leaveingManageMapper.getAllLeaveingManage(categoryId);
for (LeaveingManage leaveingManage : list) {
HashMap<String,Object> map = new HashMap<>();
int userId = leaveingManage.getUserId();
User user = userService.getUserDetails(userId);
map.put("userInfo", user);
map.put("leaveingManage", leaveingManage);
result.add(map);
}
return result;
}
/**
* 写给未来的ta
* @param paramMap
* @return
* @throws Exception
*/
@Override
public int writeToFuture(HashMap<String,Object> paramMap) throws Exception {
LeaveingManage leaveingManage = new LeaveingManage();
leaveingManage.setCategoryId(Integer.valueOf(paramMap.get("categoryId").toString()));
leaveingManage.setUserId(Integer.valueOf(paramMap.get("userId").toString()));
leaveingManage.setContent(paramMap.get("content").toString());
String futureStr = paramMap.get("future").toString();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date future = simpleDateFormat.parse(futureStr);
leaveingManage.setFuture(future);
leaveingManage.setMark(paramMap.get("mark").toString());
leaveingManage.setCreateTime(new Date());
return leaveingManageMapper.addLeaveingManage(leaveingManage);
}
}
|
C#
|
UTF-8
| 4,420 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
//---------------------------------------------------------------------
// <copyright file="BasicUnpackStreamContext.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Archivers.Internal.Compression
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
/// <summary>
/// Stream context used to extract a single file from an archive into a memory stream.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public class BasicUnpackStreamContext : IUnpackStreamContext
{
private Stream archiveStream;
private Stream fileStream;
/// <summary>
/// Creates a new BasicExtractStreamContext that reads from the specified archive stream.
/// </summary>
/// <param name="archiveStream">Archive stream to read from.</param>
public BasicUnpackStreamContext(Stream archiveStream)
{
this.archiveStream = archiveStream;
}
/// <summary>
/// Gets the stream for the extracted file, or null if no file was extracted.
/// </summary>
public Stream FileStream
{
get
{
return this.fileStream;
}
}
/// <summary>
/// Opens the archive stream for reading. Returns a DuplicateStream instance,
/// so the stream may be virtually opened multiple times.
/// </summary>
/// <param name="archiveNumber">The archive number to open (ignored; 0 is assumed).</param>
/// <param name="archiveName">The name of the archive being opened.</param>
/// <param name="compressionEngine">Instance of the compression engine doing the operations.</param>
/// <returns>A stream from which archive bytes are read.</returns>
public Stream OpenArchiveReadStream(int archiveNumber, string archiveName, CompressionEngine compressionEngine)
{
return new DuplicateStream(this.archiveStream);
}
/// <summary>
/// Does *not* close the stream. The archive stream should be managed by
/// the code that invokes the archive extraction.
/// </summary>
/// <param name="archiveNumber">The archive number of the stream to close.</param>
/// <param name="archiveName">The name of the archive being closed.</param>
/// <param name="stream">The stream being closed.</param>
public void CloseArchiveReadStream(int archiveNumber, string archiveName, Stream stream)
{
// Do nothing.
}
/// <summary>
/// Opens a stream for writing extracted file bytes. The returned stream is a MemoryStream
/// instance, so the file is extracted straight into memory.
/// </summary>
/// <param name="path">Path of the file within the archive.</param>
/// <param name="fileSize">The uncompressed size of the file to be extracted.</param>
/// <param name="lastWriteTime">The last write time of the file.</param>
/// <returns>A stream where extracted file bytes are to be written.</returns>
public Stream OpenFileWriteStream(string path, long fileSize, DateTime lastWriteTime)
{
this.fileStream = new MemoryStream(new byte[fileSize], 0, (int) fileSize, true, true);
return this.fileStream;
}
/// <summary>
/// Does *not* close the file stream. The file stream is saved in memory so it can
/// be read later.
/// </summary>
/// <param name="path">Path of the file within the archive.</param>
/// <param name="stream">The file stream to be closed.</param>
/// <param name="attributes">The attributes of the extracted file.</param>
/// <param name="lastWriteTime">The last write time of the file.</param>
public void CloseFileWriteStream(string path, Stream stream, FileAttributes attributes, DateTime lastWriteTime)
{
// Do nothing.
}
}
}
|
Java
|
UTF-8
| 2,556 | 2.109375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package fr.univnantes.termsuite.engines.contextualizer;
/*******************************************************************************
* Copyright 2015-2016 - CNRS (Centre National de Recherche Scientifique)
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*******************************************************************************/
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright 2, 2013nership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public interface AssociationRate {
public double getValue(ContextData contextData);
@SuppressWarnings("unchecked")
public static Class<? extends AssociationRate>[] values() {
return new Class[]{
MutualInformation.class,
LogLikelihood.class
};
}
public static Class<? extends AssociationRate> forName(String name) {
for(Class<? extends AssociationRate> cls:values()) {
if(cls.getName().equals(name)
|| cls.getCanonicalName().equals(name)
|| cls.getSimpleName().equals(name))
return cls;
}
throw new IllegalArgumentException("No such " + AssociationRate.class.getSimpleName() + ": " + name);
}
}
|
Markdown
|
UTF-8
| 2,813 | 2.734375 | 3 |
[] |
no_license
|
# X61HMM
## 支持型号
- ThinkPad X60
(MT 1706,1707,1708,1709,2509以及2510)
- ThinkPad X60s
(MT 1702,1703,1704,1705,2507,2508,2533以及2534)
- ThinkPad X61
(MT 7673,7674,7675,7676,7678以及7679)
- ThinkPad X61s
(MT 7666,7667,7668,7669,7670以及7671)
## 供电检查
为了检查该供电系统,应当进行以下操作:
1. 关闭计算机
2. 移除电池
3. 连接交流电源适配器
4. 尝试开机检查是否供电
5. 关闭计算机
6. 移除交流电源适配器并插入已经充好电的电池组
7. 开机检查是否供电
#### 如果以上步骤当中,有部分步骤不能正常的运行,那么请通过以下步骤来检测电源
1. 检查交流电源适配器
2. 检查工作时的充电
3. 检查电池
4. 检查BIOS电池
### 检查交流电源适配器
你查看这部分内容因为电脑只在连接交流电源适配器时出现问题
- 如果电源问题仅仅出现在接口拓展部分,那么更换接口拓展器
- 如果开机指示灯没有点亮,请检查电源连接线是否正确的连接并检查电源线的连通性
- 如果电脑在使用的过程中没有进行充电,请查看“检查工作中的电源”部分
#### 为了检查交流电源适配器,进行以下步骤
1. 拔下交流电电源线
2. 测量电源的输出电压,应为+19.5v到+21.0v
3. 如果电压不正确,那么更换电源适配器
4. 如果电压在可接受的范围内,进行以下步骤
- 更换系统主板
- 如果问题持续,前往P34的产品概述
> 注意:从电源适配器中串出的噪音并不一定预示着电源适配器的损坏
### 检查工作时的充电
为了检查在工作中电池是否能够适当的充电,使用一块电量小于50%的电池撞到计算机上
进行工作中充电测试,如果电池状态指示灯没有亮起,移除电源并让他散热到室温。重新插入电源,如果充电指示灯仍然没有亮起,那么更换电源
如果电源指示灯仍然没有亮起,那么更换主板,然后重新插入电池。如果仍然没有进行充电,那么进入下一过程
### 检查电池
电源充电在电量小于95%时才会开始。在这种情况下,电池将会充满到100%。这个过程将会保护电池防止被过度充电并最后可以延长电池的使用时间
为了检查电池的状态,将你的鼠标指针移到位于Windows任务栏的电量表图标处并等待一会(但是不要点击),然后电源剩余电量的百分比就会显示出来。为了获得细节信息,双击电量表图标。
> *注意:如果电池变得发热,那么可能不能够充电。这时将其从电脑张移除并等其冷却到室温,之后重新插上并且重新充电*
|
Python
|
UTF-8
| 683 | 3.09375 | 3 |
[] |
no_license
|
# model.py
from mesa import Agent, Model
from mesa.time import RandomActivation
class MoneyAgent(Agent):
def __init__(self, unique_id, model,p):
super().__init__(unique_id, model)
print(p)
def step(self):
self.otherAgents = self.model.schedule.agents
print(self.otherAgents)
class MoneyModel(Model):
def __init__(self, N):
self.num_agents = N
self.schedule = RandomActivation(self)
# Create agents
for i in range(self.num_agents):
a = MoneyAgent(i, self, 3)
self.schedule.add(a)
def step(self):
self.schedule.step()
empty_model = MoneyModel(10)
empty_model.step()
|
JavaScript
|
UTF-8
| 2,492 | 3.28125 | 3 |
[] |
no_license
|
import React, { useState, useEffect } from 'react';
const TodoList = (props) => {
// const [ phonesCount, setPhonesCount ] = useState(0);
// const [ counter, setCounter ] = useState(0);
// (1) without dependecy array: React specifies all of the variables as dependencies.
// useEffect(() => {
// console.log('useEffect called!');
// console.log('props length: ', props.items.length);
// });
// (2) with empty dependecy array: call the function once the component creates.
// useEffect(() => {
// console.log('useEffect called!');
// console.log('props length: ', props.items.length);
// }, []);
// (3) with dependecy array: call the function when one of the dependencies changed.
// useEffect(() => {
// console.log('useEffect called!');
// console.log('props length: ', props.items.length);
// // setPhonesCount(props.items.length);
// }, [props]);
// useEffect(() => {
// console.log('useEffect called!');
// console.log('props length: ', props.items.length);
// // setPhonesCount(props.items.length);
// }, [props, counter]);
// (4) with clean up
// useEffect(() => {
// console.log('useEffect called!');
// console.log('props length: ', props.items.length);
// // clean up
// return setCounter(0);
// }, [props]);
// (5) two different useEffect()
// useEffect(() => {
// console.log('useEffect(1) called!');
// console.log('props length: ', props.items.length);
// }, [props]);
// useEffect(() => {
// console.log('useEffect(2) called!');
// console.log('clicked!!!');
// }, [counter]);
// const addCounterHandler = (event) => {
// // old counter + 1 => mutate state immutable!
// // xxx immutable
// // const newCounter = counter + 1;
// // setCounter(newCounter);
// // immutable way
// setCounter((prevCounter) => {
// return prevCounter + 1
// });
// }
return <ul>
<li>{props.items[0].task}</li>
<li>{props.items[1].task}</li>
<li>{props.items[2].task}</li>
<li>{props.items[3].task}</li>
<hr />
{/* <span> Count of numbers: { phonesCount }</span> */}
{/* <button onClick={addCounterHandler}>Add Counter</button>
<span> Counter: { counter } </span> */}
</ul>;
};
export default TodoList;
|
Ruby
|
UTF-8
| 685 | 2.875 | 3 |
[] |
no_license
|
require 'sikulix'
require './class/Faker.rb'
include Sikulix
def CreateCompany(arregloCom, arregloDom)
end
def TestMain()
intContador = 0
while intContador.to_i <= 0
intContador = input("Cantidad de compañias a crear?")
if intContador.to_i > 0
arreglo = GenerarCompanies(intContador.to_i)
CreateCompany(arreglo , GenerarCompanyDomain(arreglo))
else
popup("Ingrese un numero mayor a 0...")
end
end
end
#Comienzo del programa
if popAsk("El programa debe de comenzar en la pagina principal de hubspot. \n Desea continuar?...")
TestMain()
else
popup("Adios...")
p "Programa finalizado"
end
|
Java
|
UTF-8
| 3,117 | 2.5625 | 3 |
[] |
no_license
|
package Graphique;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
public class PanelSelection extends JPanel {
public PanelSelection() {
// Settings panel
this.setPreferredSize( new Dimension(1200,140) );
this.setBackground( Color.DARK_GRAY );
this.setLayout( new BorderLayout() );
this.setBorder( new EmptyBorder(8, 8, 8, 8) );
// Contenu
// Boutons
JPanel pnlBoutons = new JPanel();
pnlBoutons.setBackground(new Color(0,0,0,1));
pnlBoutons.setLayout( new GridLayout(2,8,8,8) );
BoutonOutil btnSeg = new BoutonOutil();
btnSeg.setText("Segment");
pnlBoutons.add(btnSeg);
BoutonOutil btnRect = new BoutonOutil();
btnRect.setText("Rectangle");
pnlBoutons.add(btnRect);
BoutonOutil btnCrcl = new BoutonOutil();
btnCrcl.setText("Cercle");
pnlBoutons.add(btnCrcl);
BoutonOutil btnTrg = new BoutonOutil();
btnTrg.setText("Triangle");
pnlBoutons.add(btnTrg);
BoutonOutil btnLsge = new BoutonOutil();
btnLsge.setText("Losange");
pnlBoutons.add(btnLsge);
BoutonOutil btnQuad = new BoutonOutil();
btnQuad.setText("Quadrangle");
btnQuad.setFont( new Font("Arial", Font.PLAIN, 12) );
pnlBoutons.add(btnQuad);
BoutonOutil btnEllipse = new BoutonOutil();
btnEllipse.setText("Ellipse");
pnlBoutons.add(btnEllipse);
BoutonOutil btnArc = new BoutonOutil();
btnArc.setText("Arc");
pnlBoutons.add(btnArc);
BoutonOutil btnMultSeg = new BoutonOutil();
btnMultSeg.setText("Multi-segments");
btnMultSeg.setFont( new Font("Arial", Font.PLAIN, 12) );
pnlBoutons.add(btnMultSeg);
BoutonOutil btnMultRect = new BoutonOutil();
btnMultRect.setText("Multi-rectangles");
btnMultRect.setFont( new Font("Arial", Font.PLAIN, 13) );
pnlBoutons.add(btnMultRect);
BoutonOutil btnMultCercle = new BoutonOutil();
btnMultCercle.setText("Multi-cercles");
btnMultCercle.setFont( new Font("Arial", Font.PLAIN, 11) );
pnlBoutons.add(btnMultCercle);
BoutonOutil btnMultEllipse = new BoutonOutil();
btnMultEllipse.setText("Multi-ellipses");
btnMultEllipse.setFont( new Font("Arial", Font.PLAIN, 11) );
pnlBoutons.add(btnMultEllipse);
BoutonOutil btnSuiteCercle= new BoutonOutil();
btnSuiteCercle.setText("Suite de Cercles");
btnSuiteCercle.setFont( new Font("Arial", Font.PLAIN, 14) );
pnlBoutons.add(btnSuiteCercle);
BoutonOutil btnAucun = new BoutonOutil();
btnAucun.setText("Aucun");
btnAucun.setEnabled(false);
pnlBoutons.add(btnAucun);
this.add(pnlBoutons, BorderLayout.WEST);
// Statut
JLabel lblStatut = new JLabel("Statut : Aucun");
lblStatut.setForeground(Color.WHITE);
lblStatut.setFont(new Font("Arial", Font.BOLD, 32));
lblStatut.setBorder( new EmptyBorder(2, 2, 2, 40) );
this.add(lblStatut, BorderLayout.EAST);
}
}
|
Python
|
UTF-8
| 1,304 | 3.203125 | 3 |
[] |
no_license
|
import pandas as pd
from itertools import compress
class NullsCalc:
def __init__(self, df):
self.df = df
self.numNulls = {}
self.percentNulls = {}
self._nullsDict()
def _nullsDict(self):
for colName in self.df.columns:
col = self.df[colName].values
boolMx = pd.isna(col)
nulls = sum(boolMx)
self.numNulls[colName] = nulls
self.percentNulls[colName] = nulls/len(boolMx)
def dropColNulls(self, fractionalMetric):
# fractionalMetric: % nulls in a col before we drop that col
toDrop = [ key for key, val in self.percentNulls.items() \
if val > fractionalMetric ]
self.df.drop(toDrop, axis=1, inplace=True)
# remove dict elements that were removed from df
for colName in toDrop:
if colName in self.numNulls: \
del self.numNulls[colName]
if colName in self.percentNulls: \
del self.percentNulls[colName]
def dropRowNulls(self, metric):
# metric: number nulls in a col before we start dropping rows
toDrop = []
for key, val in self.numNulls.items():
if val < metric: # if we are going to remove rows
nulls = self.df[key].isnull()
toDrop += list(compress(range(len(nulls)), nulls))
toDrop = list(set(toDrop))
self.df.drop(self.df.index[toDrop], inplace=True)
# will need to recalculate after rows are dropped
self._nullsDict()
|
Java
|
UTF-8
| 737 | 2.203125 | 2 |
[] |
no_license
|
package com.kucw.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CourseController {
// 取得該學生修的課的detail資訊
@RequestMapping("/course")
public ResponseEntity<String> getCourseByStudentId(@RequestParam Integer studentId) {
// 本來這裡應該也要做 HATEOAS,但是先專注在StudentController上的語法就好,所以這裡就隨意返回值了
return new ResponseEntity<>("success", HttpStatus.OK);
}
}
|
Markdown
|
UTF-8
| 3,171 | 2.9375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Machine Learning and Applied Data Science conference content
## NVIDIA RAPIDS: Open-Source GPU Data Science on Azure
Traditional machine-learning workloads have yet to be GPU-accelerated the way deep learning and other neural net methods have. RAPIDS aims to change that, while maintaining the ease of use of the PyData ecosystem. The goal is to build a ridiculously fast open-source data science platform that allows practitioners to explore data, train ML algorithms and build applications while primarily staying in GPU memory.
Materials contained here will provide a hands-on introduction to RAPIDS. It will begin with a brief introduction to RAPIDS and Azure ML (10-15 minutes). The remainder of the time will be a hands-on session on how to use RAPIDS to process and train a ML model.
We have two tracks:
1. `notebooks/intro` introduces the concepts of GPU computing and contrasts the runs with CPU
2. `notebooks/deep_dive` builds on the introductory scripts and provides more examples on how to extend and distrubute the workloads
## Presenters
* Tom Drabas is a Senior Data Scientist at Microsoft. He has over 15 years of international experience working in airline, telecommunication and technology industries. He holds PhD in airline operations research field from the University of New South Wales. During his time at Microsoft he has published multiple books and authored a video series on data science, machine learning and distributed computing in Spark. His research interests include parallel, deep learning and machine learning algorithms and their applications.
* Keith Kraus is a manager in the AI infrastructure team at NVIDIA. He is a core developer of RAPIDS and works extensively on the Python interface, API design, distributed computation architecture, and big data integration. Prior to joining NVIDIA, Keith worked in cybersecurity, focused on building a GPU-Accelerated big data solution for advanced threat detection. Keith holds an MEng in networked information systems from Stevens Institute of Technology.
* Paul Mahler is a Senior Data Scientist at NVIDIA in Boulder, CO. At NVIDIA, Paul’s focus has been on building tools that accelerate data science workflows by leveraging the power of GPU technology. Prior to NVIDIA, Paul worked as a data scientist at a Fin Tech start-up in San Francisco, and as an associate manager in Accenture Tech Labs. In a different life, Paul was an economist who worked at the World Bank and Fannie Mae.
* Brad Rees
## Greater team
* Joshua Patterson, General Manager of AI Infrastructure, NVIDIA Josh leads engineering for RAPIDS.AI, and is a former White House Presidential Innovation Fellow. Prior to NVIDIA, Josh worked with leading experts across public sector, private sector, and academia to build a next-generation cyber defense platform. His current passions are graph analytics, machine learning, and large-scale system design. Josh also loves storytelling with data and creating interactive data visualizations. Josh holds a B.A. in economics from the University of North Carolina at Chapel Hill and an M.A. in economics from the University of South Carolina Moore School of Business.
* Bartley Richardson
* Brad Rees
* Michael Beaumont
|
C++
|
UTF-8
| 856 | 3.046875 | 3 |
[] |
no_license
|
#pragma once
#include <string>
using namespace std;
double const SAVINGS_INTEREST = 1.01;
double const CD_INTEREST = 0.0185; //This is different because it has to be to implement it the right way.
int const CD_DURATION = 120; // There was no duration given, so the bank defaults the required duration at 10 years (or 120 months);
double const PENALTY = 5;
double const UNDER_MINIMUM = 6;
class BankAccount // it doesn't make sense to me to have open and closing as member functions.
{
public:
BankAccount(int, double, string);
string getOwner();
int getNumber();
string getType();
double getBalance();
virtual void advanceMonth();
virtual void withdraw(double);
virtual void deposit(double);
virtual string tostr();
protected:
int account_number;
double current_balance;
string owner;
int months; //in existence
string accountType;
};
|
Python
|
UTF-8
| 1,605 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
from .help import *
from .internal import *
from typing import List
import pandas as pd
hash_col = "--HASHCOL--"
lagged_time_col = "--LAGGEDTIMECOL--"
lagged_hash_col = "--LAGGEDHASHCOL--"
def create_lag(
df,
target: str,
time_col: str,
lag: int,
group_cols: List[str]=[],
) -> str:
lag_feat_name = f"{target}-lag{lag}{time_col}"
for col in [hash_col, lagged_time_col, lagged_hash_col, lag_feat_name]:
assert not contains(df, col)
assert df[time_col].dtype == "int"
df[hash_col] = multi_concat_feat(df, group_cols + [time_col])
df[lagged_time_col] = df[time_col] + lag
df[lagged_hash_col] = multi_concat_feat(df, group_cols + [lagged_time_col])
assert already_grouped(df, hash_col, target)
df[lag_feat_name] = df[hash_col].map(
map_from(df, lagged_hash_col, target),
)
df.drop([hash_col, lagged_time_col, lagged_hash_col], axis=1, inplace=True)
return lag_feat_name
def already_grouped(df, group_col: str, target: str) -> bool:
groups = df.groupby(group_col).agg({target: ["min", "max"]})
return groups[(target, "min")].equals(groups[(target, "max")])
def create_grouped_lags(
df,
target: str,
time_col: str,
lag: int,
group_cols: List[str]=[],
aggs: str = ["mean"],
) -> None:
names = add_grouped_feats(df, group_cols + [time_col], target, aggs)
lag_names: List[str] = []
for name in names:
lag_name = create_lag(df, name, time_col, lag, group_cols)
df.drop([name], axis=1, inplace=True)
lag_names.append(lag_name)
return lag_names
|
C++
|
UTF-8
| 2,618 | 2.5625 | 3 |
[] |
no_license
|
/*# include <sbmt/search/unary_applications.hpp>
# include <sbmt/edge/null_info.hpp>
# include <sbmt/grammar/grammar_in_memory.hpp>
# include <sbmt/grammar/brf_file_reader.hpp>
# include <fstream>
# include <sstream>
# include <boost/test/auto_unit_test.hpp>
# include <boost/algorithm/string/trim.hpp>
using namespace sbmt;
using namespace std;
template class unary_applications< edge<null_info>, grammar_in_mem >;
void compare_edges_from_foo(string const& filebase)
{
typedef edge<null_info> edge_t;
typedef edge_equivalence<edge_t> edge_equiv_t;
edge_factory<edge_t> ef;
grammar_in_mem gram;
edge_equiv_t::max_edges_per_equivalence(ULONG_MAX);
score_combiner sc("scr:1.0");
ifstream file((SBMT_TEST_DIR + string("/") + filebase + ".brf").c_str());
ifstream edges((SBMT_TEST_DIR + string("/") + filebase + ".edges").c_str());
brf_stream_reader brf(file);
gram.load(brf,sc);
edge_equiv_t eq(new edge_equivalence_impl<edge_t>(ef.create_edge(gram,"FOO",span_t(0,1))));
std::vector<edge_equiv_t> v;
v.push_back(eq);
unary_applications<edge_t,grammar_in_mem> u(v.begin(), v.end(), gram, ef, true);
unary_applications<edge_t,grammar_in_mem>::iterator itr = u.begin(),
end = u.end();
multiset<string> actual, results;
for (; itr != end; ++itr) {
edge_equiv_t::edge_range er = const_cast<edge_equiv_t&>(*itr).edges_sorted();
edge_equiv_t::edge_iterator eitr = er.begin(), eend = er.end();
for (; eitr != eend; ++eitr) {
stringstream sstr;
sstr << print(*eitr,gram);
results.insert(boost::trim_copy(sstr.str()));
}
}
while (edges) {
string line;
getline(edges,line);
if (line != "") actual.insert(boost::trim_copy(line));
}
BOOST_CHECK_EQUAL(actual.size(),results.size());
BOOST_CHECK_EQUAL_COLLECTIONS( actual.begin(), actual.end()
, results.begin(), results.end() );
for (multiset<string>::iterator ai = actual.begin(); ai != actual.end(); ++ai) {
cerr << *ai << endl;
}
cerr << "================================" << endl;
for (multiset<string>::iterator ai = results.begin(); ai != results.end(); ++ai) {
cerr << *ai << endl;
}
}
BOOST_AUTO_TEST_CASE(test_unary_applications)
{
compare_edges_from_foo("unary1");
compare_edges_from_foo("unary2");
compare_edges_from_foo("unary3");
}*/
|
Python
|
UTF-8
| 1,645 | 3.5625 | 4 |
[] |
no_license
|
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else :
print(car.title())
# Python的真假值分别为Ture与False
# 函数lower() 不会修改存储在变量中的值
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
# and 相当于&&, or相当于 ||
requested_toppings = ['mushrooms', 'onions', 'pineapple']
if "mushrooms" in requested_toppings:
print("mushroom !!!")
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
age = 19
if age > 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
age = 12
price = 0
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
|
PHP
|
UTF-8
| 651 | 2.625 | 3 |
[] |
no_license
|
<?php
/**
* Copyright (c) 2020. Martynov AV email: sandysman@mail.ru
*/
namespace ParsingTags\DB\Tables;
class tableDescriptions extends table
{
protected $tableName = 'descriptions';
protected $tableColumnNameId = 'id_description';
protected $tableColumnNameName = 'description';
public function __construct(\ParsingTags\DB\DBwork $dbConnection)
{
$this->setQueryForSelectAllQueryByIdTag();
parent::__construct($dbConnection);
}
private function setQueryForSelectAllQueryByIdTag()
{
$this->strShowAllRecordsByForeignKey = 'select id_description, description from descriptions where id_tag = ?';
}
}
|
JavaScript
|
UTF-8
| 2,278 | 2.984375 | 3 |
[] |
no_license
|
import assert from 'assert';
import isNormalized from '../isNormalized.js';
describe('isNormalized', function() {
describe('returns a boolean', function() {
it('returns result type of boolean', function() {
assert.strictEqual(typeof isNormalized('2d6+5'), 'boolean');
});
});
describe('test edge cases', function() {
it('captures uppercase', function() {
assert.strictEqual(isNormalized('D20'), false);
});
it('captures space at the start', function() {
assert.strictEqual(isNormalized(' d4'), false);
});
it('captures spaces in between', function() {
assert.strictEqual(isNormalized('d6 + d4'), false);
});
it('captures space at the end', function() {
assert.strictEqual(isNormalized('d4 '), false);
});
it('captures d1', function() {
assert.strictEqual(isNormalized('1d1'), false);
});
it('captures 1dN at the start', function() {
assert.strictEqual(isNormalized('1d6'), false);
});
it('passes N1dN at the start', function() {
assert.strictEqual(isNormalized('11d6'), true);
});
it('captures 1dN in between', function() {
assert.strictEqual(isNormalized('d8+1d6'), false);
});
it('passes N1dN in between', function() {
assert.strictEqual(isNormalized('d8+11d6'), true);
});
it('captures negative dice without modifier', function() {
assert.strictEqual(isNormalized('-d6'), false);
});
it('captures negative dice with modifier', function() {
assert.strictEqual(isNormalized('d12-2d6'), false);
});
it('captures unsorted dice', function() {
assert.strictEqual(isNormalized('d4+d6'), false);
});
it('captures unsorted dice and modifier', function() {
assert.strictEqual(isNormalized('1+d4'), false);
});
it('captures ungroupped dice', function() {
assert.strictEqual(isNormalized('d4+d4'), false);
});
it('passes normalized notation', function() {
assert.strictEqual(isNormalized('2d6-1'), true);
});
it('throws an error on invalid exression passed', function() {
assert.throws(function() {
normalize('2d');
});
});
});
});
|
Markdown
|
UTF-8
| 18,334 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
---
title: Get to Know Gatsby Building Blocks
typora-copy-images-to: ./
disableTableOfContents: true
---
In the [**previous section**](/tutorial/part-zero/), you prepared your local development environment by installing the necessary software and creating your first Gatsby site using the [**"hello world" starter**](https://github.com/gatsbyjs/gatsby-starter-hello-world). Now, take a deeper dive into the code generated by that starter.
## Using Gatsby starters
In [**tutorial part zero**](/tutorial/part-zero/), you created a new site based on the "hello world" starter using the following command:
```shell
gatsby new hello-world https://github.com/gatsbyjs/gatsby-starter-hello-world
```
When creating a new Gatsby site, you can use the following command structure to create a new site based on any existing Gatsby starter:
```shell
gatsby new [SITE_DIRECTORY_NAME] [URL_OF_STARTER_GITHUB_REPO]
```
If you omit a URL from the end, Gatsby will automatically generate a site for you based on the [**default starter**](https://github.com/gatsbyjs/gatsby-starter-default). For this section of the tutorial, stick with the "Hello World" site you already created in tutorial part zero. You can learn more about [modifying starters](/docs/modifying-a-starter) in the docs.
### ✋ Open up the code
In your code editor, open up the code generated for your "Hello World" site and take a look at the different directories and files contained in the 'hello-world' directory. It should look something like this:

_Note: Again, the editor shown here is Visual Studio Code. If you're using a different editor, it will look a little different._
Let's take a look at the code that powers the homepage.
> 💡 If you stopped your development server after running `gatsby develop` in the previous section, start it up again now — time to make some changes to the hello-world site!
## Familiarizing with Gatsby pages
Open up the `/src` directory in your code editor. Inside is a single directory: `/pages`.
Open the file at `src/pages/index.js`. The code in this file creates a component that contains a single div and some text — appropriately, "Hello world!"
### ✋ Make changes to the "Hello World" homepage
1. Change the "Hello World!" text to "Hello Gatsby!" and save the file. If your windows are side-by-side, you can see that your code and content changes are reflected almost instantly in the browser after you save the file.
<video controls="controls" autoplay="true" loop="true">
<source type="video/mp4" src="./02-demo-hot-reloading.mp4" />
<p>Sorry! Your browser doesn't support this video.</p>
</video>
> 💡 Gatsby uses **hot reloading** to speed up your development process. Essentially, when you're running a Gatsby development server, the Gatsby site files are being "watched" in the background — any time you save a file, your changes will be immediately reflected in the browser. You don't need to hard refresh the page or restart the development server — your changes just appear.
2. Now you can make your changes a little more visible. Try replacing the code in `src/pages/index.js` with the code below and save again. You'll see changes to the text — the text color will be purple and the font size will be larger.
```jsx:title=src/pages/index.js
import React from "react"
export default function Home() {
return <div style={{ color: `purple`, fontSize: `72px` }}>Hello Gatsby!</div>
}
```
> 💡 We'll be covering more about styling in Gatsby in [**part two**](/tutorial/part-two/) of the tutorial.
3. Remove the font size styling, change the "Hello Gatsby!" text to a level-one header, and add a paragraph beneath the header.
```jsx:title=src/pages/index.js
import React from "react"
export default function Home() {
return (
{/* highlight-start */}
<div style={{ color: `purple` }}>
<h1>Hello Gatsby!</h1>
<p>What a world.</p>
{/* highlight-end */}
</div>
);
}
```

4. Add an image. (In this case, a random image from Unsplash).
```jsx:title=src/pages/index.js
import React from "react"
export default function Home() {
return (
<div style={{ color: `purple` }}>
<h1>Hello Gatsby!</h1>
<p>What a world.</p>
{/* highlight-next-line */}
<img src="https://source.unsplash.com/random/400x200" alt="" />
</div>
)
}
```

### Wait… HTML in our JavaScript?
_If you're familiar with React and JSX, feel free to skip this section._ If you haven't worked with the React framework before, you may be wondering what HTML is doing in a JavaScript function. Or why we're importing `react` on the first line but seemingly not using it anywhere. This hybrid "HTML-in-JS" is actually a syntax extension of JavaScript, for React, called JSX. You can follow along with this tutorial without prior experience with React, but if you're curious, here's a brief primer…
Consider the original contents of the `src/pages/index.js` file:
```jsx:title=src/pages/index.js
import React from "react"
export default function Home() {
return <div>Hello world!</div>
}
```
In pure JavaScript, it looks more like this:
```javascript:title=src/pages/index.js
import React from "react"
export default function Home() {
return React.createElement("div", null, "Hello world!")
}
```
Now you can spot the use of the `'react'` import! But wait. You're writing JSX, not pure HTML and JavaScript. How does the browser read that? The short answer: It doesn't. Gatsby sites come with tooling already set up to convert your source code into something that browsers can interpret.
## Building with components
The homepage you were just making edits to was created by defining a page component. What exactly is a "component"?
Broadly defined, a component is a building block for your site; It is a self-contained piece of code that describes a section of UI (user interface).
Gatsby is built on React. When we talk about using and defining **components**, we are really talking about **React components** — self-contained pieces of code (usually written with JSX) that can accept input and return React elements describing a section of UI.
One of the big mental shifts you make when starting to build with components (if you are already a developer) is that now your CSS, HTML, and JavaScript are tightly coupled and often living even within the same file.
While a seemingly simple change, this has profound implications for how you think about building websites.
Take the example of creating a custom button. In the past, you would create a CSS class (perhaps `.primary-button`) with your custom styles and then use it whenever you want to apply those styles. For example:
```html
<button class="primary-button">Click me</button>
```
In the world of components, you instead create a `PrimaryButton` component with your button styles and use it throughout your site like:
<!-- prettier-ignore -->
```jsx
<PrimaryButton>Click me</PrimaryButton>
```
Components become the base building blocks of your site. Instead of being limited to the building blocks the browser provides, e.g. `<button />`, you can easily create new building blocks that elegantly meet the needs of your projects.
### ✋ Using page components
Any React component defined in `src/pages/*.js` will automatically become a page. Let's see this in action.
You already have a `src/pages/index.js` file that came with the "Hello World" starter. Let's create an about page.
1. Create a new file at `src/pages/about.js`, copy the following code into the new file, and save.
```jsx:title=src/pages/about.js
import React from "react"
export default function About() {
return (
<div style={{ color: `teal` }}>
<h1>About Gatsby</h1>
<p>Such wow. Very React.</p>
</div>
)
}
```
2. Navigate to `http://localhost:8000/about/`

Just by putting a React component in the `src/pages/about.js` file, you now have a page accessible at `/about`.
### ✋ Using sub-components
Let's say the homepage and the about page both got quite large and you were rewriting a lot of things. You can use sub-components to break the UI into reusable pieces. Both of your pages have `<h1>` headers — create a component that will describe a `Header`.
1. Create a new directory at `src/components` and a file within that directory called `header.js`.
2. Add the following code to the new `src/components/header.js` file.
```jsx:title=src/components/header.js
import React from "react"
export default function Header() {
return <h1>This is a header.</h1>
}
```
3. Modify the `about.js` file to import the `Header` component. Replace the `h1` markup with `<Header />`:
```jsx:title=src/pages/about.js
import React from "react"
import Header from "../components/header" // highlight-line
export default function About() {
return (
<div style={{ color: `teal` }}>
<Header /> {/* highlight-line */}
<p>Such wow. Very React.</p>
</div>
)
}
```

In the browser, the "About Gatsby" header text should now be replaced with "This is a header." But you don't want the "About" page to say "This is a header." You want it to say, "About Gatsby".
4. Head back to `src/components/header.js` and make the following change:
```jsx:title=src/components/header.js
import React from "react"
// highlight-start
export default function Header(props) {
return <h1>{props.headerText}</h1>
// highlight-end
}
```
5. Head back to `src/pages/about.js` and make the following change:
```jsx:title=src/pages/about.js
import React from "react"
import Header from "../components/header"
export default function About() {
return (
<div style={{ color: `teal` }}>
<Header headerText="About Gatsby" /> {/* highlight-line */}
<p>Such wow. Very React.</p>
</div>
)
}
```

You should now see your "About Gatsby" header text again!
### What are "props"?
Earlier, you defined React components as reusable pieces of code describing a UI. To make these reusable pieces dynamic you need to be able to supply them with different data. You do that with input called "props". Props are (appropriately enough) properties supplied to React components.
In `about.js` you passed a `headerText` prop with the value of `"About Gatsby"` to the imported `Header` sub-component:
```jsx:title=src/pages/about.js
<Header headerText="About Gatsby" />
```
Over in `header.js`, the header component expects to receive the `headerText` prop (because you've written it to expect that). So you can access it like so:
```jsx:title=src/components/header.js
<h1>{props.headerText}</h1>
```
> 💡 In JSX, you can embed any JavaScript expression by wrapping it with `{}`. This is how you can access the `headerText` property (or "prop!") from the "props" object.
If you had passed another prop to your `<Header />` component, like so...
```jsx:title=src/pages/about.js
<Header headerText="About Gatsby" arbitraryPhrase="is arbitrary" />
```
...you would have been able to also access the `arbitraryPhrase` prop: `{props.arbitraryPhrase}`.
6. To emphasize how this makes your components reusable, add an extra `<Header />` component to the about page, add the following code to the `src/pages/about.js` file, and save.
```jsx:title=src/pages/about.js
import React from "react"
import Header from "../components/header"
export default function About() {
return (
<div style={{ color: `teal` }}>
<Header headerText="About Gatsby" />
<Header headerText="It's pretty cool" /> {/* highlight-line */}
<p>Such wow. Very React.</p>
</div>
)
}
```

And there you have it; A second header — without rewriting any code — by passing different data using props.
### Using layout components
Layout components are for sections of a site that you want to share across multiple pages. For example, Gatsby sites will commonly have a layout component with a shared header and footer. Other common things to add to layouts include a sidebar and/or a navigation menu.
You'll explore layout components in [**part three**](/tutorial/part-three/).
## Linking between pages
You'll often want to link between pages — Let's look at routing in a Gatsby site.
### ✋ Using the `<Link />` component
1. Open the index page component (`src/pages/index.js`), import the `<Link />` component from Gatsby, add a `<Link />` component above the header, and give it a `to` property with the value of `"/contact/"` for the pathname:
```jsx:title=src/pages/index.js
import React from "react"
import { Link } from "gatsby" // highlight-line
import Header from "../components/header"
export default function Home() {
return (
<div style={{ color: `purple` }}>
<Link to="/contact/">Contact</Link> {/* highlight-line */}
<Header headerText="Hello Gatsby!" />
<p>What a world.</p>
<img src="https://source.unsplash.com/random/400x200" alt="" />
</div>
)
}
```
When you click the new "Contact" link on the homepage, you should see...

...the Gatsby development 404 page. Why? Because you're attempting to link to a page that doesn't exist yet.
2. Now you'll have to create a page component for your new "Contact" page at `src/pages/contact.js` and have it link back to the homepage:
```jsx:title=src/pages/contact.js
import React from "react"
import { Link } from "gatsby"
import Header from "../components/header"
export default function Contact() {
return (
<div style={{ color: `teal` }}>
<Link to="/">Home</Link>
<Header headerText="Contact" />
<p>Send us a message!</p>
</div>
)
}
```
After you save the file, you should see the contact page and be able to follow the link to the homepage.
<video controls="controls" loop="true">
<source type="video/mp4" src="./10-linking-between-pages.mp4" />
<p>Sorry! Your browser doesn't support this video.</p>
</video>
The Gatsby `<Link />` component is for linking between pages within your site. For external links to pages not handled by your Gatsby site, use the regular HTML `<a>` tag.
## Deploying a Gatsby site
Gatsby is a _modern site generator_, which means there are no servers to set up or complicated databases to deploy. Instead, the Gatsby `build` command produces a directory of static HTML and JavaScript files which you can deploy to a static site hosting service.
Try using [Surge](https://surge.sh/) for deploying your first Gatsby website. Surge is one of many "static site hosts" which makes it possible to deploy Gatsby sites.
> Gatsby Cloud is another deployment option, built by the team behind Gatsby. In the next section, you'll find instructions for [deploying to Gatsby Cloud](/tutorial/part-one/#alternative-deploying-to-gatsby-cloud).
If you haven't previously installed & set up Surge, open a new terminal window and install their command-line tool:
```shell
npm install --global surge
# Then create a (free) account with them
surge login
```
Next, build your site by running the following command in the terminal at the root of your site (tip: make sure you're running this command at the root of your site, in this case in the hello-world folder, which you can do by opening a new tab in the same window you used to run `gatsby develop`):
```shell
gatsby build
```
The build should take 15-30 seconds. Once the build is finished, it's interesting to take a look at the files that the `gatsby build` command just prepared to deploy.
Take a look at a list of the generated files by typing in the following terminal command into the root of your site, which will let you look at the `public` directory:
```shell
ls public
```
Then finally deploy your site by publishing the generated files to surge.sh. For newly-created surge account, you need to verify your email with surge before publishing your site (check your inbox first and verify your email).
```shell
surge public/
```
> Note that you will have to press the `enter` key after you see the `domain: some-name.surge.sh` information on your command-line interface.
Once this finishes running, you should see in your terminal something like:

Open the web address listed on the bottom line (`lowly-pain.surge.sh` in this
case) and you'll see your newly published site! Great work!
### Alternative: Deploying to Gatsby Cloud
[Gatsby Cloud](https://gatsbyjs.com) is a platform built specifically for Gatsby sites, with features like real-time previews, fast builds, and integrations with dozens of other tools. It's the best place to build and deploy sites built with Gatsby, and you can use Gatsby Cloud free for personal projects.
To deploy your site to Gatsby Cloud, create an account on [GitHub](https://github.com) if you don't have one. GitHub allows you to host and collaborate on code projects using Git for version control.
Create a new repository on GitHub. Since you're importing your existing project, you'll want a completely empty one, so don't initialize it with `README` or `.gitignore` files.
You can tell Git where the remote (i.e. not on your computer) repository is like this:
```shell
git remote add origin [GITHUB_REPOSITORY_URL]
```
When you created a new Gatsby project with a starter, it automatically made an initial `git commit`, or a set of changes. Now, you can push your changes to the new remote location:
```shell
git push -u origin master
```
Now you're ready to link this GitHub repository right to Gatsby Cloud! Check out the reference guide on [Deploying to Gatsby Cloud](/docs/deploying-to-gatsby-cloud/#set-up-an-existing-gatsby-site).
## ➡️ What's Next?
In this section you:
- Learned about Gatsby starters, and how to use them to create new projects
- Learned about JSX syntax
- Learned about components
- Learned about Gatsby page components and sub-components
- Learned about React "props" and reusing React components
Now, move on to [**adding styles to your site**](/tutorial/part-two/)!
|
JavaScript
|
UTF-8
| 2,483 | 2.859375 | 3 |
[] |
no_license
|
const getBagIfContain = require("../days/day7").getBagIfContain
const filterFor = require("../days/day7").filterFor
const day7 = require("../days/day7").day7
const day7part2 = require("../days/day7").day7part2
const should = require('chai').should()
describe('test suite for problem 7 of advent of code 2020', () => {
it('Should return muted yellow for input muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.', () => {
const input = "muted yellow bags contain 2 shiny gold bags, 9 faded blue bags."
getBagIfContain(input, "shiny gold").should.equal("muted yellow")
})
it('Should return bright white,muted yellow ', () => {
const input = ["bright white bags contain 1 shiny gold bag.","muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.","shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags."]
filterFor(input, "shiny gold").join(",").should.equal("bright white,muted yellow")
})
it('Should return 4 for given example', () => {
const input = ["light red bags contain 1 bright white bag, 2 muted yellow bags.","dark orange bags contain 3 bright white bags, 4 muted yellow bags.","bright white bags contain 1 shiny gold bag.","muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.","shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.","dark olive bags contain 3 faded blue bags, 4 dotted black bags.","vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.","faded blue bags contain no other bags.","dotted black bags contain no other bags."]
day7(input, "shiny gold").should.equal(4)
})
it ('should return 32 for part 2 first exmaple', () => {
const input = ["faded blue bags contain no other bags.","dotted black bags contain no other bags.","vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.","dark olive bags contain 3 faded blue bags, 4 dotted black bags.","shiny gold bags contain 1 dark olive bags, 2 vibrant plum bags."]
day7part2(input, "shiny gold").should.equal(32)
})
it ('should return 126 for part 2 second exmaple', () => {
const input = ["shiny gold bags contain 2 dark red bags.","dark red bags contain 2 dark orange bags.","dark orange bags contain 2 dark yellow bags.","dark yellow bags contain 2 dark green bags.","dark green bags contain 2 dark blue bags.","dark blue bags contain 2 dark violet bags.","dark violet bags contain no other bags."]
day7part2(input, "shiny gold").should.equal(126)
})
})
|
JavaScript
|
UTF-8
| 7,145 | 3.265625 | 3 |
[] |
no_license
|
/**
Store edit js re-written.
*/
var defaultCloseTime = "1700";
/**
Returns the hours in the example format.
{
hours-1-day_1: "0600,1730",
...
}
The above example states that Sunday has an opening time of 6 am and closing time of 5.30 pm.
If the 24/7 checkbox is checked, then this will return the below.
{
hours-0-day_0: "xxxx,xxxx",
}
*/
function getHoursData() {
var data = {};
// check if 24/7
if ($("#hours-top input[type='checkbox']").first()[0].checked){
return { "hours-0-day_0": "xxxx,xxxx", };
}
$(".hours-form ul.hours-row").each(function() {
var self = $(this);
var openTime = self.find(".time.open select").val();
var closeTime = self.find(".time.close select").val();
// add all the active days
self.find(".days .active").each(function() {
data[$(this).attr("id")] = openTime+","+closeTime;
});
});
return data;
}
/**
This not only shows a textual preview but also handles hours validation response
from the server - enabling and disabling the submit button.
*/
function hoursPreview(){
$.ajax({
url: $("#hours_preview_url").val(),
data: getHoursData(),
type: "POST",
cache: false, // required to kill internet explorer 304 bug
success: function(res) {
if (res.result == "success") {
$("#store-hours-preview").html(res.html);
$("#hours_e > ul.errorlist > li").text("");
$("#save-button").removeClass("gray").addClass("blue");
} else {
$("#hours_e > ul.errorlist > li").text(res.html);
$("#save-button").removeClass("blue").addClass("gray");
}
},
});
}
/**
rowId is -x- in hours-x-row
*/
function bindOptionsClick(rowId) {
if (rowId == null) {
rowId = ".hours-row";
} else {
rowId = "#hours"+rowId+"row";
}
$(".hours-form ul"+rowId+" li.time select").change(function() {
// hours changed so update the preview
hoursPreview();
});
}
/**
rowId is -x- in hours-x-row
*/
function bindDaysClick(rowId) {
if (rowId == null) {
rowId = ".hours-row";
} else {
rowId = "#hours"+rowId+"row";
}
$(".hours-form ul"+rowId+" .days div").click(function() {
var self = $(this);
if (self.hasClass("active")) {
self.removeClass("active");
} else {
self.addClass("active");
}
// hours changed so update the preview
hoursPreview();
});
}
/**
rowId is -x- in hours-x-row
*/
function bindRemoveRow(rowId){
if (rowId == null) {
rowId = ".hours-row";
} else {
rowId = "#hours"+rowId+"row";
}
$(".hours-form ul"+rowId+" .buttons .remove").click(function() {
// do not remove the last row
if ($(".hours-form ul.hours-row").length > 1) {
$(this).closest("ul.hours-row").remove();
} else { // just deactivate all days
$(this).closest("ul.hours-row").find(".days div").removeClass("active");
}
// hours may have changed so update the preview
hoursPreview();
});
}
/**
Same code as rphours_util.py
Returns the text of the option given the value.
e.g. option_text("0630") returns 6:30 AM.
*/
function getReadableDay(value){
if (value == "0000") {
return "12 AM (Midnight)";
} else if (value == "1200") {
return "12 PM (Noon)";
} else {
var hour = Number(value.substring(0, 2));
var ampm = "";
if (hour >= 12) {
if (hour > 12) {
hour -= 12;
}
ampm = "PM";
} else {
if (hour == 0) {
hour = 12;
}
ampm = "AM";
}
return String(hour)+":"+value.substring(2,4)+" "+ampm;
}
}
/**
Hide all the hours-rows, including the add hours button, if checked.
Show all rows if not.
*/
function checkOpenAllWeek(self){
if (self[0].checked) {
$("#slide-container").slideUp();
} else {
$("#slide-container").slideDown();
}
hoursPreview();
}
function addHoursRow() {
var lastHours = $(".hours-form ul.hours-row:last");
var orig = $("#hours-clone");
var origId = lastHours.attr("id");
origId = origId.substring(origId.indexOf("-")+1, origId.lastIndexOf("-"));
var copyId = "-"+String(Number(origId) + 1)+"-";
// replace the -0- in hours-0-row with copyId
// also remove all active classes on days
lastHours.after(
"<ul id='hours"+copyId+"row' class='hours-row'>"+
orig.html().replace(new RegExp("-x-", 'g'), copyId).replace(/active|checked/g, "")+
"</ul>"
);
bindDaysClick(copyId);
bindRemoveRow(copyId);
bindOptionsClick(copyId);
}
function submitForm(submitButton){
if (submitButton.hasClass("gray")) {
return;
}
var loader = $(".form-options img");
if (loader.is(":visible")) { return; }
loader.show();
// update the phone number's value
$("#id_phone_number").val(new String($("#Ph1").val()) +
new String($("#Ph2").val()) + new String($("#Ph3").val()));
var form = $("#store-location-edit-form");
var data = form.serializeArray();
data.push({
name: "hours",
value: JSON.stringify(getHoursData()),
});
$.ajax({
url: form.attr("action"),
data: $.param(data),
type: "POST",
cache: false, // required to kill internet explorer 304 bug
success: function(res) {
loader.hide();
if (res.result == "success") {
window.location.replace(res.url);
} else if (res.result == "error" ) {
var newDoc = document.open("text/html", "replace");
newDoc.write(res.html);
newDoc.close();
}
},
});
}
$(document).ready(function(){
// clicks on days
bindDaysClick();
// clicks on remove hours
bindRemoveRow();
// clicks on add hours
$(".hours-form .add").click(function() {
addHoursRow();
});
// clicks on 24/7 checkbox
$("#hours-top input[type='checkbox']").change(function() {
checkOpenAllWeek($(this));
});
// clicks on options
bindOptionsClick();
// clicks on submit
$("#save-button").click(function() {
submitForm($(this));
});
var loader = $(".form-options img");
// clicks on cancel
$(".form-options a.red").click(function() {
return !loader.is(":visible");
});
// initial check if 24/7
checkOpenAllWeek($("#hours-top input[type='checkbox']"));
// initial preview
hoursPreview();
});
|
JavaScript
|
UTF-8
| 7,739 | 2.921875 | 3 |
[] |
no_license
|
DeviceFinder = (function() {
/**
* Finds available devices
*
* @param filter optional parameter used for filtering out unwanted devices, if no filter is used then all devices will be returned
* @return array of devices that matches the filter used
*/
function find(filter) {
//If no filter is specified, then set the filter to an empty filter.
if (!filter) {
filter = {};
}
//If the filter is a json array then loop through the array and concat all devices that matches the individual filters.
if (filter instanceof Array) {
var devices = [];
for (var i = 0; i < filter.length; i++) {
var matchingDevices = getDevices(filter[i]);
devices.concat(matchingDevices);
}
return devices;
} else { //If the filter is a single json object then get all devices that matches that one filter
return getDevices(filter);
}
}
/**
* Get all devices that matches the given filter
*
* @param filter the filter used to filter out unwanted devices
* @return array of devices that matches the filter
*/
function getDevices(filter) {
if (filter.controlUnitName || filter.owner || filter.apiKey) {
var controlUnits = getMatchingControlUnits(filter);
var uniqueControlUnitIds = getUniqueControlUnitIds(controlUnits);
filter.controlUnitIds = uniqueControlUnitIds;
}
var devices = filterDevices(filter);
if (filter.locationName) {
devices = filterByLocation(devices, filter);
}
if (filter.componentId || filter.componentType || filter.componentName) {
devices = filterComponents(devices, filter);
}
return devices;
}
/**
* Get control units that matches the given filter
*
* @param filter the filter used to filter out unwanted control units
* @return array of control units that matches the filter
*/
function getMatchingControlUnits(filter) {
var selector = {};
if (filter.controlUnitId)
selector.controlUnitId = filter.controlUnitId;
if (filter.controlUnitName)
selector.name = filter.controlUnitName;
if (filter.owner)
selector.owner = filter.owner;
if (filter.apiKey)
selector.apiKey = filter.apiKey;
return ControlUnits.find(selector).fetch();
}
/**
* Returns an array containing only the unique control unit ids
*
* @param controlUnits array of control units that we should get the control unit ids from
* @return array of control unit ids
*/
function getUniqueControlUnitIds(controlUnits) {
var uniqueControlUnitIds = new Array();
for (var i = 0; i < controlUnits.length; i++) {
var controlUnitId = controlUnits[i].controlUnitId;
if (uniqueControlUnitIds.indexOf(controlUnitId) === -1)
uniqueControlUnitIds.push(controlUnitId);
}
return uniqueControlUnitIds;
}
/**
* Fetches all devices from the Device collection that matches the filter
*
* @param filter filters out unwanted devices
* @return array of devices that matches the filter
*/
function filterDevices(filter) {
var selector = {};
//Control Units
if (filter.controlUnitIds) {
selector.controlUnitId = {
$in: filter.controlUnitIds
};
}
//Devices
if (filter.deviceId)
selector.id = filter.deviceId;
if (filter.deviceName)
selector.name = filter.deviceName;
if (filter.deviceType)
selector.type = filter.deviceType;
if (filter.userAccess)
selector['userAccess'] = {
$in: [filter.userAccess]
};
//Components
if (filter.componentId || filter.componentType || filter.componentName) {
selector['components'] = {};
selector['components']['$elemMatch'] = {};
}
if (filter.componentId)
selector['components']['$elemMatch']['id'] = filter.componentId;
//selector['components.id'] = filter.componentId;
if (filter.componentType)
selector['components']['$elemMatch']['type'] = filter.componentType;
//selector['components.type'] = filter.componentType;
if (filter.componentName)
selector['components']['$elemMatch']['name'] = filter.componentName;
//Property
if (filter.propertyName) {
if (selector['components'] === undefined) {
selector['components'] = {};
selector['components']['$elemMatch'] = {};
}
selector['components']['$elemMatch']['properties.' + filter.propertyName] = {
$exists: true
};
if (filter.propertyValue !== undefined) {
selector['components']['$elemMatch']['properties.' + filter.propertyName + ".value"] = filter.propertyValue;
}
}
//Method
if (filter.methodName)
selector['components.methods.' + filter.methodName] = {
$exists: true
};
return Devices.find(selector).fetch(); //Search the database for matching devices and return the result
}
/**
* Filters out unwanted components from the device
*
* @param filter filter that is used to remove unwanted components
* @return array of devices that matches the filter
*/
function filterComponents(devices, filter) {
_.each(devices, function(device) {
device.components = _.filter(device.components, function(component) {
if (filter.componentId && filter.componentId !== component.id) {
return false;
}
if (filter.componentType && filter.componentType !== component.type) {
return false;
}
if (filter.componentName && filter.componentName !== component.name) {
return false;
}
return true;
});
});
return devices;
}
/**
* Filters devices based on the location of the device
*
* @param filter filter that is used to remove devices that is not in the specified location
* @return array of devices that is in the specified location
*/
function filterByLocation(devices, filter) {
var location = Locations.findOne({
name: filter.locationName
});
//If no location exist with the name we are looking for then return an empty array,
//as no devices exist in the location with the specified name.
if (!location)
return [];
devices = devices.filter(function(device) {
if (!device.location) {
return false;
}
//If the device isn't inside the bounderies of the location we are looking for then remove this device
if (device.location.longitude < location.northWest.longitude || device.location.longitude > location.southEast.longitude ||
device.location.latitude > location.northWest.latitude || device.location.latitiude < location.southEast.latitude) {
return false;
}
return true;
});
return devices;
}
//Return public functions
return {
find: find
}
}());
|
JavaScript
|
UTF-8
| 594 | 3.03125 | 3 |
[
"Apache-2.0"
] |
permissive
|
class Link {
/**
* Create a level link
* @param {int} sourceX
* @param {int} sourceY
* @param {int} width
* @param {int} height
* @param {float} targetX
* @param {float} targetY
* @param {string} targetName
*/
constructor(sourceX, sourceY, width, height, targetX, targetY, targetName) {
if (arguments.length < 7) {
throw new Error('Missing arguments');
}
this.sourceX = sourceX;
this.sourceY = sourceY;
this.width = width;
this.height = height;
this.targetX = targetX;
this.targetY = targetY;
this.targetName = targetName;
}
}
module.exports = Link;
|
Python
|
UTF-8
| 148 | 2.90625 | 3 |
[] |
no_license
|
# Create a light at (10, 10, 10) shining at (0, 0, 1).
#
import pyvista as pv
light = pv.Light(position=(10, 10, 10))
light.focal_point = (0, 0, 1)
|
Python
|
UTF-8
| 2,730 | 2.703125 | 3 |
[] |
no_license
|
import sys
import math
Matrix = [ [[],[],[]], [[],[],[]], [[],[],[]] ]
Matrix_transposed=[]
Winning_move = False
for i in range(3):
line = input()
for j in range(len(line)):
Matrix[i][j]=line[j]
Dots_quantity=0
Rows_O = []
Rows_X = []
Col_O = []
Col_X = []
Dia_1_9 = []
Dia_3_7 = []
for i in range (len(Matrix)):
for x in Matrix[i]:
Dots_quantity_help = Matrix[i].count('.')
O_quantity= Matrix[i].count('O')
X_quantity= Matrix[i].count('X')
Rows_O.append(O_quantity)
Rows_X.append(X_quantity)
Dots_quantity = Dots_quantity + Dots_quantity_help
Matrix_transposed = list(zip(*Matrix) )
for i in range (len(Matrix)):
for x in Matrix_transposed[i]:
O_quantity= Matrix_transposed[i].count('O')
X_quantity= Matrix_transposed[i].count('X')
Col_O.append(O_quantity)
Col_X.append(X_quantity)
Matrix_transposed[i]=list(Matrix_transposed[i])
for i in range(len(Matrix)):
Counter=0
for x in Matrix[i]:
if Counter==i:
Dia_1_9.append(x)
Counter+=1
Counter =0
for x in Matrix[i]:
if Counter==2-i:
Dia_3_7.append(x)
Counter+=1
O_quantity_dia_1_9 = Dia_1_9.count('O')
X_quantity_dia_1_9 = Dia_1_9.count('X')
O_quantity_dia_3_7 = Dia_3_7.count('O')
X_quantity_dia_3_7 = Dia_3_7.count('X')
Winning_matrix=Matrix
Winning_matrix_transposed=list(Matrix_transposed)
Winning_row=''
if Dots_quantity >= 8:
Winning_move=False
for i in range (len(Rows_O)):
if Rows_O[i]-Rows_X[i]==2:
Winning_move=True
for j in range(len(Matrix)):
for x in Matrix[i]:
if x=='.':
Winning_matrix[i][j]= ('O')
break
elif Col_O[i]-Col_X[i]==2:
Winning_move=True
for j in range(len(Matrix_transposed)):
for x in Matrix_transposed[i]:
if x=='.':
Winning_matrix_transposed[i][j]= ('O')
Winning_matrix=list(zip(*Winning_matrix_transposed))
break
elif O_quantity_dia_1_9-X_quantity_dia_1_9==2:
Winning_move=True
for j in range (len(Rows_O)):
if Dia_1_9[j]=='.':
for x in Matrix[j]:
Winning_matrix[j][j]= ('O')
break
elif O_quantity_dia_3_7-X_quantity_dia_3_7==2:
Winning_move=True
for j in range (len(Rows_O)):
if Dia_3_7[j]=='.':
for x in Matrix[j]:
Winning_matrix[j][j]= ('O')
break
if Winning_move==True:
for j in range(len(Winning_matrix)):
for x in Winning_matrix[j]:
Winning_row= Winning_row + x
print(Winning_row[j*3:(j*3)+3])
else:
print('false')
|
Shell
|
UTF-8
| 165 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash
set -eu
echo -n '' > ./index.md
while read -r i; do
b=$(basename "$i")
echo "- [$b]($i)" >> ./index.md
done <<< "$(find . -type f | sort)"
|
C++
|
UTF-8
| 1,360 | 3.46875 | 3 |
[] |
no_license
|
#include <iostream>
#include <array>
using namespace std;
int main()
{
array <int ,7>alphabet={1,2,3,4,5,6,7};
cout<<"The sixth number of alphabet is :"<<alphabet[6]<<endl;
array<float,5>grades={10.3,25.6,22.3,77.8,99.2};
float y;
cout<<"Please input grade :";
cin>>y;
grades[4]=y;
for(float grade:grades)
{
cout<<grade<<" ";
}
cout<<endl;
array<int ,5>values={0,0,0,0,0};
for(int &valueRef:values)
{
valueRef=8;
}
for(int value:values)
{
cout<<"After"<<value<<endl;
}
double x=0.0;
double a=0.0
array<double ,100>temperatures;
for(int i=0;i<100;i++)
{
temperatures[i]=a;
a++;
}
for(double temperature:temperatures)
{
x=x+temperature;
}
cout<<"The sum is :"<<x<<endl;
array<double,11>a={1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0};
array<double,34>b={11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0};
for(int i=0;i<11;i++)
{
b[i]=a[i];
}
for(int a:b)
{
cout<<a<<" ";
}
cout<<endl;
array<double,99>w;
for(double a:w)
{
if(a<w[0])
w[0]=a;
}
cout<<"The max number is :"<<w[0]<<endl;
for(double a:w)
{
if(a>w[0])
w[0]=a;
}
cout<<"The min number is :"<<w[0]<<endl;
return 0;
}
|
C#
|
WINDOWS-1252
| 3,015 | 2.53125 | 3 |
[] |
no_license
|
////////////////////////////////////////////////////////////////////////////////
// Copyright 2002-2007 by Manfred Lange, Markus Renschler, Jake Anderson,
// and Piers Lawson. All rights reserved.
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the
// use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not claim
// that you wrote the original software. If you use this software in a
// product, the following acknowledgement must be included in the product
// documentation:
//
// Portions Copyright 2002-2007 by Manfred Lange, Markus Renschler,
// Jake Anderson, and Piers Lawson. All rights reserved.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace csUnit.Interfaces {
public interface IXmlDocument {
void Load(string pathName);
System.Xml.XmlNodeList SelectNodes(string p);
System.Xml.XmlElement CreateElement(string p);
/// <summary>
/// Adds the specified node to the end of the list of child nodes, of this node.
/// </summary>
/// <param name="newChild">The node to add. If it is a XmlDocumentFragment, the entire contents of the document fragment are moved into the child list of this node.</param>
/// <returns>The node added.</returns>
XmlNode AppendChild(System.Xml.XmlNode newChild);
System.Xml.XmlAttribute CreateAttribute(string p);
/// <summary>
/// Creates an XmlComment containing the specified data.
/// </summary>
/// <param name="data">The content of the new XmlComment.</param>
/// <returns>The new XmlComment.</returns>
XmlComment CreateComment(string data);
/// <summary>
/// Creates an XmlDeclaration node with the specified values.
/// </summary>
/// <param name="version">The version must be "1.0".</param>
/// <param name="encoding">The value of the encoding attribute.</param>
/// <param name="standalone">The value must be either "yes" or "no". If
/// this is a null reference (Nothing in Visual Basic) or String.Empty,
/// the Save method does not write a standalone attribute on the XML
/// declaration.</param>
/// <returns>The new XmlDeclaration node.</returns>
XmlDeclaration CreateXmlDeclaration(string version, string encoding,
string standalone);
void Save(string pathName);
}
}
|
Java
|
UTF-8
| 2,614 | 2.390625 | 2 |
[] |
no_license
|
package de.uzl.hsr.oaltl;
import de.uzl.hsr.oaltl.grammar.LTLLexer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class PrintTest {
@Test
public void testNextOperator() {
PrintingObjectFactory testFactory = new PrintingObjectFactory();
CharStream expression = CharStreams.fromString("XXp");
LTLLexer testLexer = new LTLLexer(expression);
assertEquals("X(X(p))", Run.buildObject(testFactory, testLexer, -1).print());
}
@Test
public void testNegOperator() {
PrintingObjectFactory testFactory = new PrintingObjectFactory();
CharStream expression = CharStreams.fromString("!p");
LTLLexer testLexer = new LTLLexer(expression);
assertEquals("!(p)", Run.buildObject(testFactory, testLexer, -1).print());
}
@Test
public void testFinOperator() {
PrintingObjectFactory testFactory = new PrintingObjectFactory();
CharStream expression = CharStreams.fromString("Fp");
LTLLexer testLexer = new LTLLexer(expression);
assertEquals("F(p)", Run.buildObject(testFactory, testLexer, -1).print());
}
@Test
public void testUntilOperator() {
PrintingObjectFactory testFactory = new PrintingObjectFactory();
CharStream expression = CharStreams.fromString("pUq");
LTLLexer testLexer = new LTLLexer(expression);
assertEquals("(p)U(q)", Run.buildObject(testFactory, testLexer, -1).print());
}
@Test
public void testAndOperator() {
PrintingObjectFactory testFactory = new PrintingObjectFactory();
CharStream expression = CharStreams.fromString("p&&q");
LTLLexer testLexer = new LTLLexer(expression);
assertEquals("(p)&&(q)", Run.buildObject(testFactory, testLexer, -1).print());
}
@Test
public void testOrOperator() {
PrintingObjectFactory testFactory = new PrintingObjectFactory();
CharStream expression = CharStreams.fromString("p||q");
LTLLexer testLexer = new LTLLexer(expression);
assertEquals("(p)||(q)", Run.buildObject(testFactory, testLexer, -1).print());
}
@Test
public void testAllOperators() {
PrintingObjectFactory testFactory = new PrintingObjectFactory();
CharStream expression = CharStreams.fromString("(!p&&Xq)UF(a||!b)");
LTLLexer testLexer = new LTLLexer(expression);
assertEquals("((!(p))&&(X(q)))U(F((a)||(!(b))))", Run.buildObject(testFactory, testLexer, -1).print());
}
}
|
Java
|
UTF-8
| 657 | 2.421875 | 2 |
[] |
no_license
|
package com.example.tourtracker.models;
public class ExpenseModel {
public String expId;
public String tourId;
public String title;
public double amount;
public long timeStamp;
public ExpenseModel() {
}
public ExpenseModel(String expId, String title, double amount) {
this.expId = expId;
this.title = title;
this.amount = amount;
}
public ExpenseModel(String expId, String tourId, String title, double amount, long timeStamp) {
this.expId = expId;
this.tourId = tourId;
this.title = title;
this.amount = amount;
this.timeStamp = timeStamp;
}
}
|
PHP
|
UTF-8
| 279 | 2.53125 | 3 |
[] |
no_license
|
<?php
namespace MerchantOfComplexity\Authters\Support\Exception;
class AuthorizationDenied extends AuthorizationException
{
public static function reason(string $message = null): AuthorizationDenied
{
return new self($message ?? 'Authorization denied');
}
}
|
Java
|
UTF-8
| 1,169 | 1.914063 | 2 |
[] |
no_license
|
package com.zx.emanage.inve.persist;
import java.util.Map;
import com.zx.emanage.util.gen.entity.WmsInveExtendInfo;
import com.zx.sframe.util.mybatis.BaseDao;
import com.zx.sframe.util.mybatis.MyBatisRepository;
@MyBatisRepository
public interface WmsInveExtendInfoDao extends BaseDao<WmsInveExtendInfo> {
/**
* @Title: getWmsInveExtendInfoByWmsInveTransaId
* @Description: 根据单据
* @param wms_inve_transa_id
* @return
* @author: DongHao
* @time:2017年2月27日 下午10:38:11
* history:
* 1、2017年2月27日 DongHao 创建方法
*/
WmsInveExtendInfo getWmsInveExtendInfoByWmsInveTransaId(Integer wms_inve_transa_id);
/**
* @Title: getCategoryTypeByWmsInveTransaProdId
* @Description: 根据上单产品表主键id获取对应的产品类型
* @param wms_inve_transa_prod_id 上单产品表主键
* @return 返回产品相关信息map集合
* @author: DongHao
* @time:2017年3月13日 下午4:16:14
* history:
* 1、2017年3月13日 DongHao 创建方法
*/
Map<String, Object> getCategoryTypeByWmsInveTransaProdId(String wms_inve_transa_prod_id);
}
|
JavaScript
|
UTF-8
| 4,056 | 2.609375 | 3 |
[] |
no_license
|
import * as fetchhJsonp from 'fetch-jsonp';
function getJson(url, params, setting) {
let me = this;
if (setting.syncId && BaseHttpRequest.requestSet.has(setting.syncId)) {
console.log('重复提交')
return;
}
let host = getGwHost();
if (url.indexOf('\/\/') == -1 && (url.indexOf('api/menu') == -1 && url.indexOf('api/user') == -1)) {
url = host + url;
}
let beforeResult = me.beforeRequest(params);
if (beforeResult != BEFORE_RESUlT.OK) {
return new Promise < BaseResponse < T >> (function (resolve, reject) {
throw new Error('请求被拦截');
});
}
if (params) {
let paramsArray = [];
Object.keys(params).forEach(key => {
let value = params[key];
var isJson = typeof(value) == 'object' &&
Object.prototype.toString.call(value).toLowerCase() == '[object object]' && !value.length;
let isArray = Array.isArray(value);
if (isJson || isArray) {
value = JSON.stringify(value);
}
paramsArray.push(key + '=' + value);
})
if (url.search(/\?/) === -1) {
url += '?' + paramsArray.join('&')
} else {
url += '&' + paramsArray.join('&')
}
}
return new Promise(function (resolve, reject) {
if (setting.syncId) {
BaseHttpRequest.requestSet.add(setting.syncId)
}
if (url.indexOf('\/\/') === 0 && url.indexOf('127.0.0.1') == -1) {
fetchJsonp(url, {
timeout: setting.timeout || 5000
}).then((response) => {
if (response.ok) {
return response.json();
} else {
console.log(response.status);
reject({
code: ERROR_MAP.OTHER_ERROR,
message: '出错啦'
})
}
})
.then((response) => {
if (setting.syncId) {
BaseHttpRequest.requestSet.delete(setting.syncId)
}
if (setting.noAuth) resolve(response);
else me.afterRequest(resolve, reject, response);
})
.catch((err) => {
if (setting.syncId) {
BaseHttpRequest.requestSet.delete(setting.syncId)
}
me.afterRequest(resolve, reject, {
code: ERROR_MAP.OTHER_ERROR,
data: null,
message: '出错啦'
});
});
} else {
fetch(url, {
method: 'GET',
headers: setting.headers
}).then((response) => {
if (setting.syncId) {
BaseHttpRequest.requestSet.delete(setting.syncId)
}
if (response.ok) {
return response.json();
} else {
me.afterRequest(resolve, reject, {
code: ERROR_MAP.OTHER_ERROR,
data: null,
message: '出错啦'
});
}
}).then((response: BaseResponse < T >) => {
if (setting.syncId) {
BaseHttpRequest.requestSet.delete(setting.syncId)
}
me.afterRequest(resolve, reject, response);
}).catch((err) => {
if (setting.syncId) {
BaseHttpRequest.requestSet.delete(setting.syncId)
}
console.log(err);
me.afterRequest(resolve, reject, {
code: ERROR_MAP.OTHER_ERROR,
data: null,
message: '出错啦'
});
})
}
})
}
function getGwHost(){
return ''
}
module.exports = getJson;
|
PHP
|
UTF-8
| 1,860 | 2.609375 | 3 |
[] |
no_license
|
<?php
namespace App\FamilyMembers;
use App\FamilyMembers\Members\Parents as Parents;
use App\FamilyMembers\Members\Animal as Animal;
use App\FamilyMembers\Members\Child as Child;
use App\FamilyMembers\Guardian\NeedsMum as NeedsMum;
use App\FamilyMembers\Guardian\NeedsParents as NeedsParents;
use App\FamilyMembers\Guardian\UniqueParent as UniqueParent;
use App\FamilyMembers\Utils as Utils;
class FamilyMembers
{
private $members;
public function __construct(Array $requestType, Array $jsonMembers)
{
$this->members = Utils::transformJsonMembers($jsonMembers);
Utils::pickMember($this, $requestType);
}
public function add_mum()
{
$this->jsonMembers = Parents::add("mum", 200, $this->members, new UniqueParent());
}
public function add_dad()
{
$this->jsonMembers = Parents::add("dad", 200, $this->members, new UniqueParent());
}
public function add_cat()
{
$this->jsonMembers = Animal::add("cat", 10, $this->members, new NeedsParents());
}
public function add_dog()
{
$this->jsonMembers = Animal::add("dog", 15, $this->members, new NeedsParents());
}
public function add_goldfish()
{
$this->jsonMembers = Animal::add("goldfish", 2, $this->members, new NeedsParents());
}
public function add_child()
{
$this->jsonMembers = Child::add("children", [150, 100], $this->members, new NeedsParents());
}
public function adapt_child()
{
$this->jsonMembers = Child::add("children", [150, 100], $this->members, new NeedsMum());
}
public function getMembersList()
{
return ["data" => [...$this->jsonMembers], "numbers" => ["cost" => Utils::SumUpCosts($this->jsonMembers), "totalMembers" => Utils::SumUpTotalMembers($this->jsonMembers)]];
}
}
|
C#
|
UTF-8
| 1,103 | 2.671875 | 3 |
[] |
no_license
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ObjectiveHandler : MonoBehaviour {
private List<GameObject> objectives;
private List<GameObject> prevObjectives;
private GameObject arrow;
private ArrowBehaviour ab;
private bool showArrow;
void Start () {
showArrow = false;
objectives = new List<GameObject> ();
prevObjectives = new List<GameObject>();
arrow = transform.GetChild (0).gameObject;
ab = arrow.GetComponent<ArrowBehaviour> ();
}
public void addObjective(GameObject g){
objectives.Add (g);
}
public void removeObjective(GameObject g){
prevObjectives.Add (g);
objectives.Remove (g);
}
public bool wasAnObjective(GameObject g){
return prevObjectives.Contains (g);
}
public bool isAnObjective(GameObject g){
return objectives.Contains (g);
}
public void toggleArrow(){
showArrow = !showArrow;
}
void Update () {
if (objectives.Count > 0 && showArrow) {
ab.gameObject.SetActive (true);
ab.setTarget (objectives [objectives.Count - 1]);
} else {
ab.gameObject.SetActive(false);
}
}
}
|
Java
|
UTF-8
| 833 | 2.390625 | 2 |
[] |
no_license
|
import com.sweethome.jimmy.mynews.Models.Article;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ArticleTest {
//Test Article
@Test
public void articleGetTest() {
Article article = new Article();
article.setStatus("ok");
article.setCopyright("authorization");
article.setSection("home");
article.setLastUpdated("01/01/1990");
article.setNumResults(1);
assertEquals("ok", article.getStatus());
assertEquals("authorization", article.getCopyright());
assertEquals("home", article.getSection());
assertEquals("01/01/1990", article.getLastUpdated());
assertEquals("1" , article.getNumResults().toString());
assertNull(article.getResults());
}
}
|
C++
|
UTF-8
| 18,368 | 2.796875 | 3 |
[] |
no_license
|
#include"Apstract.h"
Abs_Node tree;
int label = 0;
int temp = 0;
Code* C;
void code_gen(Abs_Node& n);
string getOpCode(OpCode op);
string newlabel() {
return "L" + to_string(++label);
}
string newtemp() {
return "T" + to_string(++temp);
}
string place(Abs_Node node) {
if (node.code == NULL)
return node.name;
else {
Code* c = node.code;
while (c->next != NULL)
c = c->next;
return c->dest;
}
}
Code* add(Code* code, Code* code2) {
Code* temp = code;
if (temp == NULL)
return code2;
while (temp->next != NULL)
temp = temp->next;
temp->next = code2;
//code = temp;
return code;
}
void PrintCode() {
cout << endl;
cout << "_________________________________________" << endl;
while (C->next != NULL) {
cout << getOpCode(C->op) << " " << C->s1 << " " << C->s2 << " " << C->dest << endl;
C = C->next;
}
}
Abs_parser::Abs_parser(string filename) :scan(filename) {
}
void Abs_parser::start()
{
curret_token = scan.getToken();
tree = program();
code_gen(tree);
C = tree.child[0].child[1].code;
PrintCode();
}
Abs_Node Abs_parser::program()
{
Abs_Node node = Abs_Node(1);
node.nodetype = PROGRAMM;
node.child[0] = block();
return node;
}
void Abs_parser::match(TokenType ttype)
{
if (curret_token.ttype == ttype)
{
curret_token = scan.getToken();
}
else
Syntax_error(curret_token.ttype);
}
void Abs_parser::Syntax_error(TokenType ttype)
{
this->curret_token = scan.getToken();
}
Abs_Node Abs_parser::block()
{
Abs_Node node = Abs_Node(2);
node.nodetype = BLOCK;
match(BEGIN_SY);
node.child[0] = dec_seq();
node.child[1] = command_seq();
match(END_SY);
return node;
}
Abs_Node Abs_parser::dec_seq()
{
Abs_Node node = dec();
bool enter = false;
while (curret_token.ttype == INTEGER_SY || curret_token.ttype == BOOLEAN_SY || curret_token.ttype == PROC_SY)
{
enter = true;
Abs_Node temp = Abs_Node(2);
temp.name = " ";
temp.child[0] = node;
temp.child[1] = dec();
node = temp;
}
if (enter)
node.nodetype = DEC_SEQ;
return node;
}
Abs_Node Abs_parser::dec()
{
//
Abs_Node node = Abs_Node(0);
if (curret_token.ttype == INTEGER_SY || curret_token.ttype == BOOLEAN_SY)
{
node = Abs_Node(2);
node.nodetype = DEC;
node.dectype = VARIBLE;
node.child[0] = type();
node.child[1] = name_list();
}
else if (curret_token.ttype == PROC_SY)
{
match(PROC_SY);
node = Abs_Node(3);
node.dectype = PROC;
node.nodetype = DEC;
node.child[0] = Abs_Node(0);
//node->dectype = VAR_ID;
//yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
node.child[0].name = curret_token.tname;
match(ID_SY);
if (curret_token.ttype == LPAREN_SY)
{
match(LPAREN_SY);
node.child[1] = param_list();
match(RPAREN_SY);
}
match(EQUAL_SY);
node.child[2] = command();
}
else {
Syntax_error(curret_token.ttype);
return NULL;
}
return node;
}
Abs_Node Abs_parser::type()
{
Abs_Node node = Abs_Node(0);
node.nodetype = TYPE;
if (curret_token.ttype == INTEGER_SY)
{
match(INTEGER_SY);
node.typeoft = INTEGER;
}
else if (curret_token.ttype == BOOLEAN_SY)
{
match(BOOLEAN_SY);
node.typeoft = BOOLEAN;
}
else
Syntax_error(curret_token.ttype);
return node;
}
Abs_Node Abs_parser::param_list()
{
Abs_Node node = Abs_Node(2);
node.nodetype = PARAM_LIST;
node.child[0] = type();
node.child[1] = name_list();
while (curret_token.ttype == SEMICOLON_SY)
{
match(SEMICOLON_SY);
Abs_Node temp = Abs_Node(2);
temp.nodetype = PARAM_LIST;
temp.name = ";";
temp.child[0] = node;
temp.child[1] = Abs_Node(2);
temp.child[1].child[0] = type();
temp.child[1].child[1] = name_list();
node = temp;
}
return node;
}
Abs_Node Abs_parser::name_list()
{
Abs_Node node = Abs_Node(0);
node.nodetype = IDN;
node.name = curret_token.tname;
match(ID_SY);
while (curret_token.ttype == COMMA_SY)
{
match(COMMA_SY);
Abs_Node temp = Abs_Node(2);
temp.nodetype = NAME_LIST;
temp.name = ",";
temp.child[0] = node;
temp.child[1] = Abs_Node(0);
temp.child[1].nodetype = IDN;
temp.child[1].name = curret_token.tname;
match(ID_SY);
node = temp;
}
return node;
}
Abs_Node Abs_parser::command_seq()
{
Abs_Node node = command();
bool enter = false;
while (curret_token.ttype == SEMICOLON_SY)
{
enter = true;
match(SEMICOLON_SY);
Abs_Node temp = Abs_Node(2);
temp.name = ";";
temp.child[0] = node;
temp.child[1] = command();
node = temp;
}
if (enter)
node.nodetype = COM_SEQ;
return node;
}
Abs_Node Abs_parser::command()
{
Abs_Node node = Abs_Node(0);
if (curret_token.ttype == ID_SY)
{
node = Abs_Node(2);
node.nodetype = COM;
node.commtype = Commtype::ASSIGNN;
node.child[0] = Abs_Node(0);
node.child[0].name = curret_token.tname;
match(ID_SY);
match(AHMED);
node.child[1] = expr();
}
else if (curret_token.ttype == READ_SY)
{
match(READ_SY);
node = Abs_Node(1);
node.nodetype = COM;
node.commtype = Commtype::READD;
node.child[0] = Abs_Node(0);
node.child[0].name = curret_token.tname;
match(ID_SY);
}
else if (curret_token.ttype == WRITE_SY)
{
match(WRITE_SY);
node = Abs_Node(1);
node.nodetype = COM;
node.commtype = Commtype::WRITEE;
node.child[0] = expr();
}
else if (curret_token.ttype == IF_SY)
{
match(IF_SY);
node = Abs_Node(3);
node.nodetype = COM;
node.commtype = Commtype::IF;
node.child[0] = expr();
match(THEN_SY);
node.child[1] = command();
if (curret_token.ttype == ELSE_SY)
{
match(ELSE_SY);
node.child[2] = command();
}
match(ENDIF_SY);
}
else if (curret_token.ttype == WHILE_SY)
{
match(WHILE_SY);
node = Abs_Node(2);
node.nodetype = COM;
node.commtype = WHILE;
node.child[0] = expr();
match(DO_SY);
node.child[1] = command_seq();
match(ENDWHILE_SY);
}
else if (curret_token.ttype == CALL_SY)
{
match(CALL_SY);
node = Abs_Node(2);
node.nodetype = COM;
node.commtype = CALLL;
node.child[0] = Abs_Node(0);
node.child[0].name = curret_token.tname;
match(ID_SY);
if (curret_token.ttype == LPAREN_SY)
{
match(LPAREN_SY);
node.child[1] = name_list();
match(RPAREN_SY);
}
}
else Syntax_error(curret_token.ttype);
return node;
}
Abs_Node Abs_parser::expr()
{
Abs_Node node = expr1();
while (curret_token.ttype == OR_SY)
{
match(OR_SY);
Abs_Node temp = Abs_Node(2);
temp.name = "or";
temp.nodetype = EXP;
temp.expertype = ExperType::ORR;
temp.child[0] = node;
temp.child[1] = expr1();
node = temp;
}
return node;
}
Abs_Node Abs_parser::expr1()
{
Abs_Node node = expr2();
while (curret_token.ttype == AND_SY)
{
match(AND_SY);
Abs_Node temp = Abs_Node(2);
temp.name = "and";
temp.nodetype = EXP;
temp.expertype = ExperType::ANDD;
temp.child[0] = node;
temp.child[1] = expr2();
node = temp;
}
return node;
}
Abs_Node Abs_parser::expr2()
{
if (curret_token.ttype == ID_SY || curret_token.ttype == NUMBER_SY || curret_token.ttype == LPAREN_SY)
{
Abs_Node node = expr3();
node.nodetype = EXP;
return node;
}
else if (curret_token.ttype == NOT_SY)
{
match(NOT_SY);
Abs_Node node = Abs_Node(1);
node.name = "not";
node.nodetype = EXP;
node.expertype = ExperType::NOTT;
node.child[0] = expr();
return node;
}
else {
Syntax_error(curret_token.ttype);
return NULL;
}
}
Abs_Node Abs_parser::expr3()
{
//
Abs_Node node = Abs_Node(0);
node = expr4();
while (curret_token.ttype == LTHAN_SY || curret_token.ttype == LOE_SY || curret_token.ttype == NOTEQUAL_SY
|| curret_token.ttype == GTHAN_SY || curret_token.ttype == GOE_SY || curret_token.ttype == EQUAL_SY)
{
Abs_Node temp = relation();
temp.child[0] = node;
temp.child[1] = expr4();
node = temp;
}
return node;
}
Abs_Node Abs_parser::expr4()
{
Abs_Node node = term();
while (curret_token.ttype == PLUS_SY || curret_token.ttype == MINUS_SY)
{
Abs_Node temp = weakop();
temp.child[0] = node;
temp.child[1] = term();
node = temp;
}
return node;
}
Abs_Node Abs_parser::term()
{
Abs_Node node = element();
while (curret_token.ttype == MULTI_SY || curret_token.ttype == DIV_SY)
{
Abs_Node temp = strongop();
temp.child[0] = node;
temp.child[1] = element();
node = temp;
}
return node;
}
Abs_Node Abs_parser::element()
{
Abs_Node node = Abs_Node(0);
if (curret_token.ttype == NUMBER_SY) {
node = Abs_Node(0);
node.nodetype = NodeType::ELEMENT;
node.elementtype = NUMBERR;
node.name = curret_token.tname;
node.nodetype = NUMERAL;
match(NUMBER_SY);
}
else if (curret_token.ttype == ID_SY)
{
node = Abs_Node(0);
node.nodetype = NodeType::ELEMENT;
node.elementtype = ID;
node.name = curret_token.tname;
match(ID_SY);
}
else if (curret_token.ttype == LPAREN_SY) {
match(LPAREN_SY);
node = expr();
match(RPAREN_SY);
}
else if (curret_token.ttype == TokenType::MINUS_SY)
{
match(MINUS_SY);
node.nodetype= ELEMENT;
node.elementtype = MIN;
node.name = "-";
return node;
}
else {
Syntax_error(curret_token.ttype);
return NULL;
}
return node;
}
Abs_Node Abs_parser::weakop() {
Abs_Node node = Abs_Node(2);
node.nodetype = EXP;
node.expertype = WEAK;
if (curret_token.ttype == PLUS_SY) {
node.name = "+";
match(PLUS_SY);
}
else {
Syntax_error(curret_token.ttype);
}
return node;
}
Abs_Node Abs_parser::strongop() {
Abs_Node node = Abs_Node(2);
node.nodetype = EXP;
node.expertype = STRONG;
if (curret_token.ttype == MULTI_SY) {
node.name = "*";
match(MULTI_SY);
}
else if (curret_token.ttype == DIV_SY) {
node.name = "/";
match(DIV_SY);
}
else {
Syntax_error(curret_token.ttype);
}
return node;
}
Abs_Node Abs_parser::relation() {
Abs_Node node = Abs_Node(2);
node.nodetype = EXP;
node.expertype = RELATIONn;
if (curret_token.ttype == GTHAN_SY) {
node.name = "<";
match(GTHAN_SY);
}
else if (curret_token.ttype == GOE_SY) {
node.name = "<=";
match(GOE_SY);
}
else if (curret_token.ttype == NOTEQUAL_SY) {
node.name = "<>";
match(NOTEQUAL_SY);
}
else if (curret_token.ttype == EQUAL_SY) {
node.name = "=";
match(EQUAL_SY);
}
else if (curret_token.ttype == LTHAN_SY) {
node.name = ">";
match(LTHAN_SY);
}
else if (curret_token.ttype == LOE_SY) {
node.name = "<=";
match(LOE_SY);
}
else {
Syntax_error(curret_token.ttype);
}
return node;
}
string getOpCode(OpCode op)
{
switch (op)
{
case GOTO:
{
return "GOTO";
}break;
case ADD:
{
return "ADD";
}
break;
case SUB:
{
return"SUB";
}
break;
case MULT:
{
return "MULT";
}
break;
case DIV:
{
return "DIV";
}
break;
case LTHAN:
{
return ">";
}
break;
case LEPREQ:
{
return ">=";
}
break;
case NEQ:
{
return "!=";
}
break;
case EQ:
{
return "=";
}
break;
case GTHAN:
{
return "<";
}
break;
case GEOPEQ:
{
return "<=";
}
break;
case AND:
{
return "AND";
}
break;
case OR:
{
return "OR";
}
break;
case OPUNDEFIEND:
{
return "undefinedop";
}
break;
case XOR:
{
return "XOR";
}
break;
case NEG:
{
return "NEG";
}
case LABEL:
{
return "label";
}
break;
case NOT:
{
return "NOT";
}
break;
case ASSIGN:
{
return "ASSIGN";
}
break;
case BIF:
{
return "BIE";
}
break;
case BNIF:
{
return "BNIF";
}
break;
case IFN:
{
return "IFN";
}
break;
case IFLT:
{
return "IFLT";
}
break;
case IFLE:
{
return "IFLE";
}
break;
case IFNE:
{
return "IFNE";
}
break;
case IFEQ:
{
return "IFNQ";
}
break;
case IFGE:
{
return "IFGE";
}
break;
case IFGT:
{
return "IFGT";
}
break;
case READ:
{
return "READ";
}
break;
case WRITE:
{
return "WRITE";
}
break;
case CALLOP:
{
return "CALL";
}
break;
case HALT:
{
return "HALT";
}
break;
case PARAM:
{
return "PARAM";
}
break;
default:
return "un";
break;
}
}
void code_gen(Abs_Node& root)
{
int size = root.child.size();
for (int i = 0; i < size; i++)
code_gen(root.child[i]);
switch (root.nodetype)
{
case PROGRAMM: {
Code* a = new Code(OpCode::OPUNDEFIEND);
root.code = add(root.child[0].code, a);
} break;
case BLOCK: {
root.code = root.child[1].code;
}break;
case COM_SEQ: {
for (auto& command : root.child) {
root.code = add(root.code, command.code);
}
}break;
case COM:
{
if (root.commtype == ASSIGNN) {
root.code = root.child[1].code;
Code* a = new Code(OpCode::ASSIGN, place(root.child[1]), "", place(root.child[0]));
root.code = add(root.code, a);
}
else if (root.commtype == READD) {
root.code = root.child[0].code;
Code* a = new Code(OpCode::READ, "", "", place(root.child[0]));
root.code = add(root.code, a);
}
else if (root.commtype == WRITEE) {
root.code = root.child[0].code;
Code* a = new Code(OpCode::WRITE, "", "", place(root.child[0]));
root.code = add(root.code, a);
}
else if (root.commtype == IF)
{
if (root.child.size() == 2) {
string lab1 = newlabel();
root.code = root.child[0].code;
Code* a = new Code(OpCode::IFN, place(root.child[0]), getOpCode(OpCode::GOTO) + lab1, "");
root.code = add(root.code, a);
root.code = add(root.code, root.child[1].code);
Code* aa = new Code(OpCode::LABEL, "", lab1 + ":", "");
root.code = add(root.code, aa);
}
else if (root.child.size() == 3) {
string lab1 = newlabel();
string lab2 = newlabel();
root.code = root.child[0].code;
Code* c = new Code(OpCode::IFN, place(root.child[0]), getOpCode(OpCode::GOTO) + lab1, "");
root.code = add(root.code, c);
root.code = add(root.code, root.child[1].code);
Code* c1 = new Code(OpCode::GOTO, lab2, "", "");
root.code = add(root.code, c1);
Code* c2 = new Code(OpCode::LABEL, "", lab1 + ":", "");
root.code = add(root.code, c2);
root.code = add(root.code, root.child[2].code);
Code* c3 = new Code(OpCode::LABEL, "", lab2 + ":", "");
root.code = add(root.code, c3);
}
}
else if (root.commtype == WHILE) {
string lab1 = newlabel();
string lab2 = newlabel();
Code* c = new Code(OpCode::LABEL, "", lab1 + ":", "");
root.code = c;
root.code = add(root.code, root.child[0].code);
Code* c1 = new Code(OpCode::IFN, place(root.child[0]), getOpCode(OpCode::GOTO) + lab2, "");
root.code = add(root.code, c1);
root.code = add(root.code, root.child[1].code);
Code* c2 = new Code(OpCode::GOTO, "", lab1, "");
root.code = add(root.code, c2);
Code* c3 = new Code(OpCode::LABEL, "", lab2 + ":", "");
root.code = add(root.code, c3);
}
else if (root.commtype == CALLL) {
long c = 0;
if (root.child[1].name != " ") {
Abs_Node t = root.child[1];
while (t.name == ",") {
c++;
}
c++;
}
Code* c1 = new Code(CALLOP, root.child[0].name, c == 0 ? "" : to_string(c), "");
root.code = c1;
}
}break;
case EXP:
{
if (root.expertype == ORR) {
string temp = newtemp();
Code* a = new Code(OpCode::OR, place(root.child[0]), place(root.child[1]), temp);
root.code = a;
}
else if (root.expertype == ANDD) {
string temp = newtemp();
Code* a = new Code(OpCode::ADD, place(root.child[0]), place(root.child[1]), temp);
root.code = a;
}
else if (root.expertype == NOTT) {
string temp = newtemp();
Code* c = new Code(OpCode::NOT, place(root.child[0]), "", temp);
root.code = c;
}
else if (root.expertype == RELATIONn) {
if (root.name == "<")
{
string temp = newtemp();
Code* c = new Code(OpCode::GTHAN, place(root.child[0]), place(root.child[1]), temp);
root.code = c;
}
else if (root.name == "<=")
{
string temp = newtemp();
Code* c = new Code(OpCode::GEOPEQ, place(root.child[0]), place(root.child[1]), temp);
root.code = c;
}
else if (root.name == "!=")
{
string temp = newtemp();
Code* c = new Code(NEQ, place(root.child[0]), place(root.child[1]), temp);
root.code = c;
}
else if (root.name == "=")
{
string temp = newtemp();
Code* c = new Code(OpCode::EQ, place(root.child[0]), place(root.child[1]), temp);
root.code = c;
}
else if (root.name == ">")
{
string temp = newtemp();
Code* c = new Code(OpCode::LTHAN, place(root.child[0]), place(root.child[1]), temp);
root.code = c;
}
else if (root.name == ">=")
{
string temp = newtemp();
Code* c = new Code(OpCode::LEPREQ, place(root.child[0]), place(root.child[1]), temp);
root.code = c;
}
}
else if (root.expertype == WEAK)
{
if (root.name == "+")
{
string temp = newtemp();
Code* a = new Code(ADD, place(root.child[0]), place(root.child[1]), temp);
root.code = a;
}
else if (root.name == "-")
{
string temp = newtemp();
Code* a = new Code(SUB, place(root.child[0]), place(root.child[1]), temp);
root.code = a;
}
}
else if (root.expertype == STRONG)
{
if (root.name == "*")
{
string temp = newtemp();
Code* a = new Code(MULT, place(root.child[0]), place(root.child[1]), temp);
root.code = a;
}
else if (root.name == "/")
{
string temp = newtemp();
Code* a = new Code(DIV, place(root.child[0]), place(root.child[1]), temp);
root.code = a;
}
}
}break;
case ELEMENT:
{
if (root.elementtype == ID)
{
root.code = NULL;
}
else if (root.elementtype == NUMBERR)
{
root.code = NULL;
}
else if (root.elementtype == EXPER)
{
string t = newtemp();
Code* a = new Code(OpCode::NEG, place(root.child[0]), "", t);
root.code = a;
}
else if (root.elementtype == MIN)
{
string t = newtemp();
Code* a = new Code(OpCode::NEG, place(root.child[0]), "", t);
root.code = a;
}
}break;
case NAME_LIST:
{
if (root.child[0].name != ",") {
string temp = newtemp();
Code* a = new Code(ASSIGN, root.child[0].name, "", temp);
root.code = a;
Code* b = new Code(PARAM, temp, "", "");
root.code = add(root.code, b);
}
string temp = newtemp();
Code* c = new Code(OpCode::ASSIGN, root.child[1].name, "", temp);
root.code = add(root.code, c);
Code* d = new Code(OpCode::PARAM, temp, "", "");
root.code = add(root.code, d);
}break;
}
}
/*
int main()
{
cout << "the code genrator for if" << endl;
Abs_parser IF_OPJ("if.txt");
IF_OPJ.start();
cout << "________________________________________" << endl;
cout << "the code genrator for while" << endl;
Abs_parser WHILE_OPJ("while.txt");
WHILE_OPJ.start();
cout << "________________________________________" << endl;
system("pause");
return 0;
}
*/
|
Java
|
UTF-8
| 2,523 | 2.125 | 2 |
[] |
no_license
|
package com.example.visit.planning;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.example.visit.MainActivity;
import com.example.visit.R;
import com.example.visit.explore.ExploreFragment;
import com.google.android.material.textfield.TextInputEditText;
public class ParticipantsFragment extends Fragment {
public ParticipantsFragment() {
// Required empty public constructor
}
public static ParticipantsFragment newInstance() {
return new ParticipantsFragment();
}
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_participants, container, false);
TextInputEditText participantsEdit = (TextInputEditText) view.findViewById(R.id.participantsEdit);
Button next = (Button) view.findViewById(R.id.next_participants);
Button cancel = (Button) view.findViewById(R.id.cancel_participants);
TextView continueExploring = (TextView) view.findViewById(R.id.continue_text);
if (TripPlanning.getParticipantsDescription() != null) {
participantsEdit.setText(TripPlanning.getParticipantsDescription());
}
next.setOnClickListener(view -> {
// Destination string holds the city user picked
String participants = participantsEdit.getText().toString();
// If user writes something in textbox, save it, but it is not required
if (participants.length() > 0) {
TripPlanning.setParticipantsDescription(participants);
}
MainActivity.changeFragment(requireActivity().getSupportFragmentManager(), new TripPlannerFragment(), true);
});
cancel.setOnClickListener(view -> {
MainActivity.changeFragment(requireActivity().getSupportFragmentManager(), new TripPlannerFragment(), true);
});
continueExploring.setOnClickListener(view -> {
MainActivity.changeFragment(requireActivity().getSupportFragmentManager(), new ExploreFragment(), true);
});
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
|
Java
|
UTF-8
| 3,354 | 1.875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2022 Red Hat
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.hal.core.mvp;
import org.jboss.hal.core.finder.Finder;
import org.jboss.hal.core.finder.FinderColumn;
import org.jboss.hal.core.finder.FinderContextEvent;
import org.jboss.hal.core.finder.FinderPath;
import org.jboss.hal.core.finder.FinderSegment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
/**
* Base class for all application presenters which interact with the finder. The presenter updates the breadcrumb by taking the
* information from {@link #finderPath()} and fires a {@link FinderContextEvent} in {@link #onReset()}.
*/
public abstract class ApplicationFinderPresenter<V extends HalView, Proxy_ extends ProxyPlace<?>>
extends ApplicationPresenter<V, Proxy_> implements HasFinderPath, SupportsExternalMode, Refreshable {
private static final Logger logger = LoggerFactory.getLogger(ApplicationFinderPresenter.class);
private final Finder finder;
protected ApplicationFinderPresenter(EventBus eventBus, V view, Proxy_ proxy, Finder finder) {
super(eventBus, view, proxy);
this.finder = finder;
}
/**
* Updates the breadcrumb by taking the information from {@link #finderPath()} and fires a {@link FinderContextEvent}.
* Finally calls {@code reload()}.
*/
@Override
protected void onReset() {
super.onReset();
updateBreadcrumb();
reload();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void updateBreadcrumb() {
FinderPath applicationPath = finderPath();
if (applicationPath != null) {
// try to connect segments with existing columns from the finder
for (FinderSegment<?> segment : applicationPath) {
FinderColumn column = finder.getColumn(segment.getColumnId());
if (column != null) {
segment.connect(column);
} else {
logger.warn("Unable to find column '{}' to connect breadcrumb segment '{}' for token '{}'",
segment.getColumnId(), segment, getProxy().getNameToken());
}
}
finder.getContext().reset(applicationPath);
}
// The breadcrumb is part of the header. Notify the header presenter to take care of updating the breadcrumb
getEventBus().fireEvent(new FinderContextEvent(finder.getContext()));
}
/**
* Override this method to
* <ol>
* <li>load the data from the backend and</li>
* <li>update the view</li>
* </ol>
* It's called as part of the {@link #onReset()} method.
*/
protected abstract void reload();
}
|
C++
|
UTF-8
| 231 | 2.546875 | 3 |
[] |
no_license
|
#include "OrderPTest.h"
Order::Order()
{
string orderName;
}
Order::Order(string n)
{
this->orderName = n;
}
Order::~Order()
{
orderName.clear();
}
string Order::getResult()
{
return orderName;
}
|
Python
|
UTF-8
| 565 | 3.109375 | 3 |
[] |
no_license
|
import numpy as np
data = np.loadtxt("/Users/Masaru/Desktop/data.txt",skiprows = 1)
N = 24
x = data[:,0]
y = data[:,1]
sum_x = np.sum(x for x in data[:,0])
sum_y = np.sum(y for y in data[:,1])
sum_xy = np.sum(x * y)
sum_x2 = np.sum(x**2 for x in data[:,0])
a = (N * sum_xy - sum_x * sum_y) / (N * sum_x2 - sum_x ** 2)
#回帰直線の傾き
b = (sum_x2 * sum_y - sum_xy * sum_x) / (N * sum_x2 - sum_x ** 2)
#回帰直線の切片
R = np.corrcoef(x, y)[0,1]
#相関係数
print("傾き: " + str(a))
print("切片: " + str(b))
print("相関係数: " + str(R))
|
C++
|
UTF-8
| 389 | 3.078125 | 3 |
[] |
no_license
|
// n-dimension vectors
// Vec<2, int> v(n, m) = arr[n][m]
// Vec<2, int> v(n, m, -1) default init -1
template<int D, typename T>
struct Vec : public vector<Vec<D-1, T>> {
template<typename... Args>
Vec(int n=0, Args... args) : vector<Vec<D-1, T>>(n, Vec<D-1, T>(args...)) {}
};
template<typename T>
struct Vec<1, T> : public vector<T> {
Vec(int n=0, T val=T()) : vector<T>(n, val) {}
};
|
C++
|
UTF-8
| 3,494 | 2.640625 | 3 |
[] |
no_license
|
#include "addconnectiondialog.h"
#include "ui_addconnectiondialog.h"
AddConnectionDialog::AddConnectionDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddConnectionDialog)
{
ui->setupUi(this);
// Initialize Id
P_id = 0;
M_id = 0;
personValid = false;
machineValid = false;
// Disable connect button
ui->connectButton->setEnabled(false);
}
AddConnectionDialog::~AddConnectionDialog()
{
delete ui;
}
// Set person model
void AddConnectionDialog::setPersonModel(QSortFilterProxyModel *p){
personsConnectionModel = p;
}
// Set machine model
void AddConnectionDialog::setMachineModel(QSortFilterProxyModel *m){
machinesConnectionModel = m;
}
// Display tables
void AddConnectionDialog::displayTables(){
// Set models
ui->machinesTable->setModel(machinesConnectionModel);
ui->personsTable->setModel(personsConnectionModel);
// Set properties
setTableProperties(ui->machinesTable);
setTableProperties(ui->personsTable);
// Hide columns
// Machine
ui->machinesTable->horizontalHeader()->hideSection(3);
ui->machinesTable->horizontalHeader()->hideSection(4);
ui->machinesTable->horizontalHeader()->hideSection(5);
// Person
ui->personsTable->horizontalHeader()->hideSection(2);
ui->personsTable->horizontalHeader()->hideSection(4);
}
void AddConnectionDialog::setTableProperties(QTableView *tab){
tab->setSelectionBehavior(QAbstractItemView::SelectRows);
tab->verticalHeader()->hide();
tab->horizontalHeader()->setStretchLastSection(true);
tab->horizontalHeader()->setSectionsClickable(true);
tab->setAlternatingRowColors(true);
tab->setSortingEnabled(true);
tab->sortByColumn(0, Qt::AscendingOrder);
tab->resizeColumnsToContents();
tab->horizontalHeader()->setHighlightSections(false);
tab->setSelectionMode(QAbstractItemView::SingleSelection);
}
// Verify that both IDs are set
void AddConnectionDialog::verifyIds(){
if(personValid && machineValid){
ui->connectButton->setEnabled(true);
}
}
// Get person Id
int AddConnectionDialog::getPersonId(){
return P_id;
}
// Get machine Id
int AddConnectionDialog::getMachineId(){
return M_id;
}
// Persons table -> clicked
void AddConnectionDialog::on_personsTable_clicked(const QModelIndex &index){
// Get name
QString name = utilities::getColumnData(ui->personsTable, index, 1);
// Display name
ui->personSelectedLabel->setText("Selected: " + name);
personValid = index.isValid();
verifyIds();
}
// Machines table -> clicked
void AddConnectionDialog::on_machinesTable_clicked(const QModelIndex &index){
// Get name
QString name = utilities::getColumnData(ui->machinesTable, index, 1);
// Display name
ui->machineSelectedLabel->setText("Selected: " + name);
machineValid = index.isValid();
verifyIds();
}
// Cancel button -> clicked
void AddConnectionDialog::on_cancelButton_clicked(){
this->done(0);
}
// Connect button -> clicked
void AddConnectionDialog::on_connectButton_clicked(){
// Set Person ID
QVector<int> ids = utilities::getSelectedTableViewIds(ui->personsTable);
// Only one row may be selected
if (ids.count() != 1) {
return;
}
P_id = ids[0];
// Set Machine ID
ids = utilities::getSelectedTableViewIds(ui->machinesTable);
// Only one row may be selected
if (ids.count() != 1) {
return;
}
M_id = ids[0];
this->done(1);
}
|
Java
|
UTF-8
| 67 | 1.75 | 2 |
[] |
no_license
|
package model;
public enum ShipSize {
SMALL,MEDIUM,LARGE;
}
|
Java
|
UTF-8
| 3,302 | 1.703125 | 2 |
[] |
no_license
|
package module.cr.entity;
import utility.CoreEntity;
/**
*
* @author user
*/
public class EntityCrSubmoduleList extends CoreEntity {
public static String ID = "ID";
public static String STATUS = "STATUS";
public static String INSERT_DATE = "INSERT";
public static String MODIFICATION_DATE = "MODIFICATION";
public static String FK_MODULE_ID = "FK";
public static String MODULE_NAME = "MODULE";
public static String subMODULE_NAME = "subMODULE";
public static String LI_SUBMODULE_STATUS = "LI";
public static String SUBMODULE_STATUS_NAME = "subMODULE";
public static String SUBMODULE_DESCRIPTION = "SUBMODULE";
public static String SORT_BY = "SORT";
public static String LANG = "LANG";
public static String SUBMODULE_TYPE = "submoduleType";
private String submoduleType = "";
public static String SUBMODULE_TYPE_NAME = "submoduleTypeName";
private String submoduleTypeName = "";
private String fkModuleId = "";
private String moduleName = "";
private String submoduleName = "";
private String liSubmoduleStatus = "";
private String submoduleStatusName = "";
private String submoduleDescription = "";
private String sortBy = "";
private String lang = "";
public String getSubmoduleType() {
return submoduleType;
}
public void setSubmoduleType(String submoduleType) {
this.submoduleType = submoduleType;
}
public String getSubmoduleTypeName() {
return submoduleTypeName;
}
public void setSubmoduleTypeName(String submoduleTypeName) {
this.submoduleTypeName = submoduleTypeName;
}
public String getFkModuleId() {
return fkModuleId;
}
public void setFkModuleId(String fkModuleId) {
this.fkModuleId = fkModuleId;
}
public String getModuleName() {
return moduleName;
}
public void setModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getSubmoduleName() {
return submoduleName;
}
public void setSubmoduleName(String submoduleName) {
this.submoduleName = submoduleName;
}
public String getLiSubmoduleStatus() {
return liSubmoduleStatus;
}
public void setLiSubmoduleStatus(String liSubmoduleStatus) {
this.liSubmoduleStatus = liSubmoduleStatus;
}
public String getSubmoduleStatusName() {
return submoduleStatusName;
}
public void setSubmoduleStatusName(String submoduleStatusName) {
this.submoduleStatusName = submoduleStatusName;
}
public String getSubmoduleDescription() {
return submoduleDescription;
}
public void setSubmoduleDescription(String submoduleDescription) {
this.submoduleDescription = submoduleDescription;
}
public String getSortBy() {
return sortBy;
}
public void setSortBy(String sortBy) {
this.sortBy = sortBy;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
@Override
public String selectDbname() {
return "apdvoice";
}
}
|
Java
|
UTF-8
| 1,570 | 1.96875 | 2 |
[] |
no_license
|
package com.huigou.uasp.bpm.engine.domain.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import com.huigou.data.domain.model.AbstractEntity;
/**
* 环节处理人手写意见
*
* @author gongmm
*/
@Entity
@Table(name = "WF_ProcUnitHandlerManuscript")
public class ProcUnitHandlerManuscript extends AbstractEntity {
private static final long serialVersionUID = 3814981128489972823L;
@Column(name="biz_id")
private String bizId;
@Column(name="proc_unit_handler_id")
private String procUnitHandlerId;
private Integer height;
@Column(name="opinion_30")
private String opinion30;
@Column(name="opinion_64")
private String opinion64;
public String getBizId() {
return bizId;
}
public void setBizId(String bizId) {
this.bizId = bizId;
}
public String getProcUnitHandlerId() {
return procUnitHandlerId;
}
public void setProcUnitHandlerId(String procUnitHandlerId) {
this.procUnitHandlerId = procUnitHandlerId;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public String getOpinion30() {
return opinion30;
}
public void setOpinion30(String opinion30) {
this.opinion30 = opinion30;
}
public String getOpinion64() {
return opinion64;
}
public void setOpinion64(String opinion64) {
this.opinion64 = opinion64;
}
}
|
C++
|
UTF-8
| 1,266 | 2.515625 | 3 |
[] |
no_license
|
#pragma once
#include "IDbPort.hpp"
#include "sqlite_orm.h"
namespace ue
{
inline auto create_storage(const std::string& path)
{
using namespace sqlite_orm;
return make_storage(path,
make_table("messages",
make_column("message_id", &message::messageId, autoincrement(), primary_key()),
make_column("sender_number", &message::senderNumber),
make_column("receiver_number", &message::receiverNumber),
make_column("text", &message::text),
make_column("read", &message::read)));
}
using dbStorage = decltype(create_storage(""));
class DbPort : public IDbPort
{
public:
DbPort(int number);
int saveMessageToDb(const common::PhoneNumber, std::string, isSender) override;
std::vector<message> getAllMessages() override;
message getMessageById(int message_id) override;
void removeMessageById(int message_id) override;
void removeAllMessages() override;
void markInDbAsRead(int) override;
private:
std::string _dbPath;
const int _number;
std::unique_ptr<dbStorage> _db;
};
};
|
Markdown
|
UTF-8
| 713 | 2.546875 | 3 |
[] |
no_license
|
---
layout: post
title: One must doubt
tags: politics
---
> William James used to preach the “will to believe.” For my part, I should wish to preach the “will to doubt.” None of our beliefs are quite true; all have at least a penumbra of vagueness and error. The methods of increasing the degree of truth in our beliefs are well known; they consist in hearing all sides, trying to ascertain all the relevant facts, controlling our own bias by discussion with people who have the opposite bias, and cultivating a readiness to discard any hypothesis which has proved inadequate. These methods are practised in science, and have built up the body of scientific knowledge.
Bertrand Russell, *Freedom and Official Propaganda*
|
JavaScript
|
UTF-8
| 912 | 2.71875 | 3 |
[] |
no_license
|
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
require("dotenv").config();
const app = express();
const data = require("./data.json");
// middlewares
app.use(express.json());
app.use(cors());
app.use(morgan("dev"));
app.post("/api/message", (req, res) => {
const { message } = req.body;
if (!message) {
return res.status(400).json({
success: false,
error: "Please do not leave the input field empty!!",
});
} else {
const resMsg = data.filter((q) => {
return q.question.match(req.body.message);
});
if (!resMsg.length) {
res.json({ result: "Did not get what did you say ? Please try again" });
}
res.json({ result: resMsg[0] });
}
});
// PORT
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
console.log(`Server running on port:${PORT}`);
console.log(`Ready for Q & A`);
});
|
C++
|
UTF-8
| 2,291 | 2.578125 | 3 |
[] |
no_license
|
/*
* main.cpp
*
* Created on: Apr 19, 2014
* Author: manoj
*/
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include "common.h"
#include "server.h"
using namespace std;
bool serverCompare(const server_info &a, const server_info &b) {
return a.id < b.id;
}
int main(int argc, char* argv[]) {
char input[] = "1tri.txt";
int timeout;
if (argc <= 4) {
cout << "Invalid Arguments!!" << endl;
return 0;
}
if (strcmp(argv[1], "-t") == 0 && strcmp(argv[3], "-i") == 0) {
timeout = atoi(argv[4]);
strcpy(input, argv[2]);
} else {
if (strcmp(argv[1], "-i") == 0 && strcmp(argv[3], "-t") == 0) {
timeout = atoi(argv[2]);
strcpy(input, argv[4]);
} else {
cout << "Invalid Arguments!!" << endl;
return 0;
}
}
std::ifstream infile(input);
std::string line;
std::vector<server_info> oServerList;
std::vector<neighbour_info> oNeighbourList;
std::getline(infile, line);
int i;
if (!checkInteger(line)) {
return 0;
}
int server_count = atoi(line.c_str());
std::getline(infile, line);
if (!checkInteger(line)) {
return 0;
}
int neighbr_count = atoi(line.c_str());
/*
* getting the server list information from the topology file
* */
for (i = 0; i < server_count; i++) {
std::getline(infile, line);
std::vector<string> splitVector;
splitVector = splitString(line, " ");
struct server_info oTemp;
oTemp.id = atoi(splitVector[0].c_str());
strcpy(oTemp.ip, splitVector[1].c_str());
oTemp.port = atoi(splitVector[2].c_str());
oServerList.push_back(oTemp);
}
std::sort(oServerList.begin(), oServerList.end(), serverCompare);
int myid;
/*
* getting the neighbor information from the topology file
* */
for (i = 0; i < neighbr_count; i++) {
std::getline(infile, line);
std::vector<string> splitVector;
splitVector = splitString(line, " ");
struct neighbour_info oTemp;
oTemp.source = atoi(splitVector[0].c_str());
myid = oTemp.source;
oTemp.dest = atoi(splitVector[1].c_str());
oTemp.cost = atoi(splitVector[2].c_str());
oTemp.status = 1;
oNeighbourList.push_back(oTemp);
}
startServer(oServerList, oNeighbourList, myid, timeout);
return 0;
}
|
Java
|
UTF-8
| 888 | 2.109375 | 2 |
[] |
no_license
|
package com.niit.digi.dazzle.test;
import java.util.Date;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.niit.digi.dazzle.dao.EventDao;
import com.niit.digi.dazzle.model.Event;
public class EventTest {
public static void main(String[] args) {
@SuppressWarnings("resource")
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.niit.digi.dazzle");
context.refresh();
EventDao eventDao = (EventDao) context.getBean("eventDao");
Event event = (Event) context.getBean("event");
event.setEid("E002");
event.setEname("Project");
event.setDate(new Date());
event.setVenue("ByePass");
event.setDescription("E-commerce");
eventDao.saveOrUpdate(event);
}
}
|
Python
|
UTF-8
| 919 | 3.265625 | 3 |
[] |
no_license
|
# Leetcode - https://leetcode.com/problems/merge-k-sorted-lists/
import heapq
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
print(lists)
if not lists:
return
if len(lists) == 1:
return lists[0]
mins = []
for i, n in enumerate(lists):
if not n:
continue
mins.append((n.val, i))
heapq.heapify(mins)
head = ListNode(0)
tmp = head
while mins:
v, i = heapq.heappop(mins)
tmp.next = lists[i]
tmp = tmp.next
if lists[i].next:
lists[i] = lists[i].next
heapq.heappush(mins, (lists[i].val, i))
return head.next
|
Python
|
UTF-8
| 13,831 | 3.03125 | 3 |
[] |
no_license
|
from jackGrammarVisitor import jackGrammarVisitor
from symbol_table import SymbolTable
from code_writer import CodeWriter
class jackVisitor(jackGrammarVisitor):
"""Clase que hereda del visitor para ir escribiendo en lenguaje de maquina virtual"""
def __init__(self):
"""Inciializa una tabald e simbolos y un ecritor de codigo junto con variables auxiliares"""
self.symbolTable = SymbolTable()
self.contWhile = -1
self.contIf = -1
self.nombreClase = ""
self.kindMetodo = ""
self.nombreMetodo = ""
self.vmWriter = CodeWriter()
self.vmWriter.vm = ""
self.nArgs = 0
def visitClasses(self, ctx):
"""Obtiene y guarda el nombre de la clase actualmente compilada"""
self.nombreClase = ctx.children[1].children[0].getText()
return self.visitChildren(ctx)
def visitClassVarDec(self, ctx):
"""Guarda en la tabla de simbolos cada uno de los fields variables taticas declaradas """
kind = ctx.children[0].getText()
tipo = ctx.children[1].children[0].getText()
i = 2
while ctx.children[i].getText() != ';':
name = ctx.children[i].getText()
if name == ',':
pass
else:
self.symbolTable.define(name, tipo, kind)
i +=1
return self.visitChildren(ctx)
def visitTypes(self, ctx):
return self.visitChildren(ctx)
def visitSubroutineDec(self, ctx):
"""Inicializa en la tabla de simbolos una subrotina, y en caso de se un metodo agrega this como parametro"""
self.kindMetodo = ctx.children[0].getText()
self.nombreMetodo = ctx.children[2].children[0].getText()
self.symbolTable.startSubroutine()
if self.kindMetodo == 'method':
self.symbolTable.define('this', self.nombreMetodo, 'argument')
return self.visitChildren(ctx)
def visitParameterList(self, ctx):
"""Agrega a la tabla de simbolos de la subroutina cada uno de los parametros """
if ctx.getChildCount() > 0:
tipo = ctx.children[0].children[0].getText()
nombre = ctx.children[1].children[0].getText()
self.symbolTable.define(nombre, tipo, 'argument')
i = 2
while i < len(ctx.children)-1 and ctx.children[i].getText() != ')':
tipo = ctx.children[i+1].getText()
nombre = ctx.children[i+2].getText()
self.symbolTable.define(nombre, tipo, 'argument')
i+=3
return self.visitChildren(ctx)
def visitSubroutineBody(self, ctx):
"""Despues de contar las variables locales escribe la funcion en
maquina virtual y dependiendo del tipo de funcion hace los llamados, push y pop correspondientes"""
i = 1
while ctx.children[i].children[0].getText() == "var":
self.visit(ctx.children[i])
i += 1
funcion = self.nombreClase +'.'+ self.nombreMetodo
numLcl = self.symbolTable.varCount('local')
self.vmWriter.writeFunction(funcion, numLcl)
if self.kindMetodo == 'constructor':
numFields = self.symbolTable.varCount('field')
self.vmWriter.writePush('constant', numFields)
self.vmWriter.writeCall('Memory.alloc', 1)
self.vmWriter.writePop('pointer', 0)
elif self.kindMetodo == 'method':
self.vmWriter.writePush('argument', 0)
self.vmWriter.writePop('pointer', 0)
while i < ctx.getChildCount():
self.visit(ctx.children[i])
i += 1
def visitVarDec(self, ctx):
"""Inicializa en la tabla de simbolos todas las variables locales de la subrutina para poder escribir la función"""
tipo = ctx.children[1].children[0].getText()
nombre = ctx.children[2].getText()
self.symbolTable.define(nombre, tipo, 'local')
i = 3
while ctx.children[i].getText() != ';':
nombre = ctx.children[i].getText()
if nombre == ',':
pass
else:
self.symbolTable.define(nombre, tipo, 'local')
i += 1
return self.visitChildren(ctx)
"""Llamados en los que no es necesario escribir codigo de VM"""
def visitClassName(self, ctx):
return self.visitChildren(ctx)
def visitSubroutineName(self, ctx):
return self.visitChildren(ctx)
def visitVarName(self, ctx):
return self.visitChildren(ctx)
def visitStatements(self, ctx):
return self.visitChildren(ctx)
def visitStatement(self, ctx):
return self.visitChildren(ctx)
def visitLetStatement(self, ctx):
"""Realiza los push y pop necesarios para guardar un valor y asignarle una posiicon en memoria"""
nombre = ctx.children[1].getText()
tipo = self.symbolTable.kindOf(nombre)
index = self.symbolTable.indexOf(nombre)
if tipo == None:
tipo = self.symbolTable.kindOf(nombre)
index = self.symbolTable.indexOf(nombre)
if ctx.children[2].getText() == '[':
self.visit(ctx.children[3])
self.vmWriter.writePush(tipo,index)
self.vmWriter.writeArithmetic('add')
self.visit(ctx.children[6])
self.vmWriter.writePop('temp', 0)
self.vmWriter.writePop('pointer', 1)
self.vmWriter.writePush('temp', 0)
self.vmWriter.writePop('that', 0)
else:
self.visit(ctx.children[3])
self.vmWriter.writePop(tipo,index)
def visitIfStatement(self, ctx):
"""Escribe los labels necesarios para manejar el flujo del programa de a cuerdo a lo indicado por la expresión"""
self.contIf += 1
cont = self.contIf
self.visit(ctx.children[2])
self.vmWriter.writeIf('IF_TRUE' + str(cont))
self.vmWriter.writeGoto('IF_FALSE' + str(cont))
self.vmWriter.writeLabel('IF_TRUE' + str(cont))
self.visit(ctx.children[5])
if ctx.getChildCount() > 7 :
if str(ctx.children[7]) == 'else':
self.vmWriter.writeGoto('IF_END' + str(cont))
self.vmWriter.writeLabel('IF_FALSE' + str(cont))
self.visit(ctx.children[9])
self.vmWriter.writeLabel('IF_END' + str(cont))
else:
self.vmWriter.writeLabel('IF_FALSE' + str(cont))
def visitWhileStatement(self, ctx):
"""Similar al if, escribe labels para que el flujo del programa se repita hasta que una condicion no se cumpla"""
self.contWhile += 1
contW = self.contWhile
self.vmWriter.writeLabel('WHILE_EXP' + str(contW))
self.visit(ctx.children[2])
self.vmWriter.writeArithmetic('not')
self.vmWriter.writeIf('WHILE_END' + str(contW))
self.visit(ctx.children[5])
self.vmWriter.writeGoto('WHILE_EXP' + str(contW))
self.vmWriter.writeLabel('WHILE_END' + str(contW))
def visitDoStatement(self, ctx):
"""Hago el llamado y posteriormente vuelvo a la función de donde hice el llamado"""
self.visitChildren(ctx)
self.vmWriter.writePop('temp', 0)
def visitReturnStatement(self, ctx):
"""Obtengo valor de retorno, si no hay, el valor de retorno es 0"""
if ctx.children[1].getText() != ';':
self.visit(ctx.children[1])
else:
self.vmWriter.writePush('constant', 0)
self.vmWriter.writeReturn()
def visitExpression(self, ctx):
"""Separo al expresion por partes para irla compilando"""
self.visit(ctx.children[0])
i = 2
while i < ctx.getChildCount():
self.visit(ctx.children[i])
self.visit(ctx.children[i-1])
i +=2
def visitTerm(self, ctx):
"""Determino el tipo de termino,si es un tipo de dato o un valor de un arreglo, dependiendo de esto obtengo
su valor si está en la tabla de simbolos o lo busco en un arreglo o busco el siguiente etrmino con el que opera y lo guardo en memoria"""
term = ctx.children[0].getText()
if ctx.getChildCount() == 1:
if term.isdigit():
self.vmWriter.writePush('constant', term)
elif term.startswith('"'):
term = term.strip('"')
tam = len(term)
self.vmWriter.writePush('constant', tam)
self.vmWriter.writeCall('String.new', 1)
for char in term:
self.vmWriter.writePush('constant', ord(char))
self.vmWriter.writeCall('String.appendChar', 2)
elif term in ['true', 'false', 'null', 'this']:
self.visitChildren(ctx)
elif term in self.symbolTable.subrutina.keys():
tipo = self.symbolTable.kindOf(term)
index = self.symbolTable.indexOf(term)
self.vmWriter.writePush(tipo,index)
elif term in self.symbolTable.clase.keys():
tipo = self.symbolTable.kindOf(term)
index = self.symbolTable.indexOf(term)
self.vmWriter.writePush(tipo,index)
else:
self.visitChildren(ctx)
else:
var = ctx.children[0].getText()
if ctx.children[1].getText() == '[':
index = self.symbolTable.indexOf(var)
segment = self.symbolTable.kindOf(var)
self.visit(ctx.children[2])
self.vmWriter.writePush(segment, index)
self.vmWriter.writeArithmetic('add')
self.vmWriter.writePop('pointer', '1')
self.vmWriter.writePush('that', '0')
elif term == '(':
self.visitChildren(ctx)
elif term == '-':
self.visit(ctx.children[1])
self.visit(ctx.children[0])
elif term == '~':
self.visit(ctx.children[1])
self.visit(ctx.children[0])
def visitSubroutineCall(self, ctx):
"""Ubica la subrutina de acuerdo a la clase en la que se encuentre y escribe en VM el respectivo llamado con su paso de parametros"""
nombre = ctx.children[0].children[0].getText()
funcion = nombre
args = 0
if ctx.children[1].getText() == '.':
nombreSubrutina = ctx.children[2].children[0].getText()
tipo = self.symbolTable.typeOf(nombre)
if tipo != None:
kind = self.symbolTable.kindOf(nombre)
index = self.symbolTable.indexOf(nombre)
self.vmWriter.writePush(kind, index)
funcion = tipo + '.' + nombreSubrutina
args += 1
else:
funcion = nombre + '.' + nombreSubrutina
elif ctx.children[1].getText() == '(':
funcion = self.nombreClase + '.' + nombre
args += 1
self.vmWriter.writePush('pointer', 0)
self.visitChildren(ctx)
args = args +self.nArgs
self.vmWriter.writeCall(funcion, args)
def visitExpressionList(self, ctx):
"""Evalua cada expresion indivudualmente"""
self.nArgs = 0
if ctx.getChildCount() > 0:
self.nArgs = 1
self.visit(ctx.children[0])
i = 2
while i < ctx.getChildCount():
self.visit(ctx.children[i])
self.visit(ctx.children[i-1])
self.nArgs += 1
i += 2
def visitOp(self, ctx):
"""Genera el comando de VM respectivo dependiendo del operador"""
op = ctx.children[0].getText()
if op == "+":
self.vmWriter.writeArithmetic('add')
elif op == "-":
self.vmWriter.writeArithmetic('sub')
elif op == "*":
self.vmWriter.writeArithmetic('call Math.multiply 2')
elif op == "/":
self.vmWriter.writeArithmetic('call Math.divide 2')
elif op == "&":
self.vmWriter.writeArithmetic('and')
elif op == "|":
self.vmWriter.writeArithmetic('or')
elif op == ">":
self.vmWriter.writeArithmetic('gt')
elif op == "<":
self.vmWriter.writeArithmetic('lt')
elif op == "=":
self.vmWriter.writeArithmetic('eq')
return self.visitChildren(ctx)
def visitUnaryop(self, ctx):
"""Determina el comando de VM para cada operaodr unario"""
op = ctx.children[0].getText()
if op == "~":
self.vmWriter.writeArithmetic('not')
elif op == "-":
self.vmWriter.writeArithmetic('neg')
def visitKeywordconstant(self, ctx):
"""Escribe el comando de VM para poder hacer uso de una palabra reservada espcifica"""
keyword = ctx.children[0].getText()
if keyword == 'this':
self.vmWriter.writePush('pointer', 0)
elif keyword in ['false','null']:
self.vmWriter.writePush('constant', 0)
elif keyword == 'true':
self.vmWriter.writePush('constant', 0)
self.vmWriter.writeArithmetic('not')
return self.visitChildren(ctx)
def crearArchivo(self,path):
"""Abre el archivo .vm donde se escribirán lso comandos de máquina virtual"""
filewrite = path.split('.jack') #Reemplazo el .jack con .xml si lo tiene
filewritef = filewrite[0]+'.vm' #Sino le agrego el .
codigoVM = self.vmWriter.vm
archivo = filewritef
try:
file = open(archivo,'w') #Abro el file en modo escribir
except FileNotFoundError:
print('ERROR:No hay directorio existente para escribir')
exit(1)
file.write(codigoVM)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.