language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 1,745 | 3.296875 | 3 | [
"Apache-2.0"
] | permissive | package org.javacord.bot.util.wiki.parser;
/**
* A class representing a page on the wiki.
*/
public class WikiPage implements Comparable<WikiPage> {
private final String title;
private final String[] keywords;
private final String path;
private final String content;
/**
* Creates a new wiki page.
*
* @param title The title of the page.
* @param keywords The keywords the page is tagged with.
* @param path The path of the page, relative to the wiki's base URL.
* @param content The content of the page.
*/
public WikiPage(String title, String[] keywords, String path, String content) {
this.title = title;
this.keywords = keywords;
this.path = path;
this.content = content;
}
/**
* Gets the title.
*
* @return The title of the page.
*/
public String getTitle() {
return title;
}
/**
* Gets the keywords.
*
* @return The keywords for the page.
*/
public String[] getKeywords() {
return keywords;
}
/**
* Gets the relative path.
*
* @return The page path.
*/
public String getPath() {
return path;
}
/**
* Gets the content.
*
* @return The content of the page.
*/
public String getContent() {
return content;
}
/**
* Gets a markdown-formatted link to the page.
*
* @return The markdown for a link to the page.
*/
public String asMarkdownLink() {
return String.format("[%s](%s)", title, WikiParser.BASE_URL + path);
}
@Override
public int compareTo(WikiPage that) {
return this.title.compareTo(that.title);
}
}
|
Markdown | UTF-8 | 3,346 | 3.6875 | 4 | [] | no_license | # CSL Lab 03 - Variables
## How can I create custom variables to hold values in my p5.js projects?
# Overview
In this learning activity, students create their own variables to set the position, size and grey scale color of their shapes without repeating code.
# Objectives
## Students will be able to:
* Identify repeated values in their code and use variables in their place.
* Create and implement custom variables
# Vocabulary
| **Variables** | In CS, variables hold an assigned value or data of a specific type, they can also hold arrays of values which will be introduced later. |
| --- | --- |
| **Width** | System variable that holds width of canvas as declared in set up. |
| **Height** | System variable that holds height of canvas as declared in setup. |
| **MouseX** | System variable that holds the current x-position of the mouse. |
| **MouseY** | System variable that holds the current y-position of the mouse. |
| **`console.log()`** | A function that logs a value to the console when the program is run. |
# Resources
* [Ellipse Variable Intro](http://alpha.editor.p5js.org/cs4all/sketches/rJsRRER7Q)
* [Code Along 2 (with original code)](http://alpha.editor.p5js.org/cs4all/sketches/H1zfOrRXX)
* Video Tutorial: [2.2 Variables in p5.js (make your own)](https://www.youtube.com/watch?v=Bn_B3T_Vbxs&index=6&list=PLRqwX-V7Uu6Zy51Q-x9tMWIv9cueOFTFA) | [Code](https://github.com/CodingRainbow/Rainbow-Code/tree/master/p5.js/2.2_Variables_in_p5.js_user_defined)
* [2.1 Variables in p5.js](https://www.youtube.com/watch?v=diGjw5tghYU)
* [2.2 Variables in p5.js (Make your own)](https://youtu.be/Bn_B3T_Vbxs)
# Instructions
## Center elements with built-in variables: width and height
We have already used two built-in variables in the previous learning activity: mouseX and mouseY. Variables are placeholder names for values that change over time. We type mouseX knowing that p5 will replace that name with a number that represents the latest X position of the mouse. This number will change as the user moves the mouse across the canvas.
Next we will use two other variables built into p5: width and height. In the following example, their values are 600 and 240 ––the dimensions we gave our canvas when we created it in the setup function.
```javascript
function setup() {
createCanvas(600, 240);
}
function draw() {
background(180);
//Draw the value of the width variable on the screen
text(width, 40, 40);
//Draw the value of the height variable on the screen
text(height, 40, 60);
}
```
In the sketch below we use `width` and `height` to place an ellipse at the center of the screen:
```javascript
function setup() {
createCanvas(600, 240);
}
function draw() {
background(180);
ellipse(width/2, height/2, 60, 60);
}
```
The advantage of using these variables to place our ellipse is that, if we change the size of our sketch later, the ellipse will still be centered. To prove this, try changing the width and height of the canvas to 500 and 200, and run the sketch again.
width and height can also be used to place shapes in positions like "a third of the screen across", or "two thirds of the screen across", or "two thirds of the screen down". Try drawing these:
* `ellipse(width/3, height/2, 60, 60);`
* `ellipse(2*width/3, height/2, 60, 60);`
* `ellipse(width/3, 2*height/3, 60, 60);`
|
Markdown | UTF-8 | 3,813 | 3.015625 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: CUDA与OPENGL 混合编程
subtitle:
date: 2020-03-30
author: infinityyf
header-img: img/tag-bg-o.jpg
catalog: true
tags:
- CUDA
- openGL
---
## 在cuda中注册一个texture 资源
使用`cudaGraphicsGLRegisterImage `,使用`cudaGraphicsResource**`来作为内存的映射指针,该函数接受GL的textureID或renderbufferID.
说明:
```c
cudaError_t cudaGraphicsGLRegisterImage(
struct cudaGraphicsResource** resource,
GLuint image, //ID
GLenum target,
unsigned int flags
)
```
*target*: If image is a texture resource, then target must be GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_3D, or GL_TEXTURE_2D_ARRAY. If the image refers to a render-buffer object, then target must be GL_RENDERBUFFER.
*flag*: cudaGraphicsRegisterFlagsNone:可读可写
cudaGraphicsRegisterFlagsReadOnly: 只读
cudaGraphicsRegisterFlagsWriteDiscard:只写
cudaGraphicsRegisterFlagsSurfaceLoadStore:
## 在cuda中注册一个VBO或PBO资源
使用`cudaGraphicsGLRegisterBuffer `
说明:
```c
cudaError_t cudaGraphicsGLRegisterBuffer(
struct cudaGraphicsResource** resource,
GLuint buffer,
unsigned int flags //见上面说明
)
```
## 在cuda中使用资源,map操作
使用`cudaGraphicsMapResources `
说明:
```c
cudaError_t cudaGraphicsMapResources (
int count, //需要映射的资源量
cudaGraphicsResource_t* resources, //一个对应资源的指针列表
cudaStream_t stream = 0
)
```
获取设备的内存指针以访问数据,如果是texture or render-buffer resource,使用`cudaGraphicsSubResourceGetMappedArray `映射成一个二维CUDA列表,如果是 vertex buffer or pixel buffer object使用`cudaGraphicsResourceGetMappedPointer `得到内存地址。
说明:
```c
cudaError_t cudaGraphicsResourceGetMappedPointer(
void** devPtr, //设备内存地址
size_t* size,
cudaGraphicsResource_t resource//之前被map过
)
```
在进行map之后,资源会被lock 需要在处理完成之后使用`cudaGraphicsUnmapResources`函数进行解除锁定
## 分配全局内存
使用`cudaMalloc`,使用`cudaFree`释放
```c
uchar4* dstBuffer = NULL;
size_t bufferSize = width * height * sizeof(uchar4);
cudaMalloc( &dstBuffer, bufferSize );
```
使用`cudaMemcpy`进行数据通信
```c
cudaError_t cudaMemcpy(
void* dst,
const void* src,
size_t count, //字节数
cudaMemcpyKind kind //复制方向(cudaMemcpyHostToHost,cudaMemcpyHostToDevice,cudaMemcpyDeviceToHost,cudaMemcpyDeviceToDevice)
)
```
`cudaMemcpyAsync`同样可以进行通信,但是是进行异步的数据同行,使用`cudaFreeHost`释放
cuda的内存包括本地内存,共享内存和全局内存。其中本地内存为线程私有,共享内存为线程块包含,所有线程都可以访问全局内存。
`cudaMallocHost`用于在host上开辟空间,具有比malloc更好的性能(从交换页面角度考虑)
## 核函数
__global__:在device上执行,从host中调用(一些特定的GPU也可以从device上调用),返回类型必须是void,不支持可变参数参数,不能成为类成员函数。注意用__global__定义的kernel是异步的,这意味着host不会等待kernel执行完就执行下一步。
__device__:在device上执行,单仅可以从device中调用,不可以和__global__同时用。
__host__:在host上执行,仅可以从host上调用,一般省略不写,不可以和__global__同时用,但可和__device__,此时函数会在device和host都编译。
## CUDA 和opengl 交互流程
1. 初始化VBO等数据,并开辟空间
2. 在CUDA中进行注册
3. 在CUDA中map,并获取数据进行计算
4. unmap并传回opengl中的对应内存 |
Markdown | UTF-8 | 1,239 | 2.625 | 3 | [] | no_license | ---
title: "Set up guide"
date: 2019-02-2
draft: false
weight: 70
---
# Set up guide
This page will guide you to set up this repository and get started contributing to this book.
We use a static site generator called as "Hugo". So before you get started, if will be helpful if you have some basic understanding of static site generators(you need not be an expert into this). You can refer :
https://learn.cloudcannon.com/jekyll/why-use-a-static-site-generator/
Steps :
1. Install hugo - brew install hugo
2. Clone below repository :
https://github.com/naikparag/simply-ios
3. Run below command in your project repository folder that you cloned in step 2 -
hugo server
4. It will start a server on your local host. You will message like below :
Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender
Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)
Press Ctrl+C to stop
5. Drag drop repo folder your favourite editor.
6. Now you are all ready to start contributing.
7. You can verify all your changes while editing/adding any content in the repo locally at http://localhost:1313/.
8. Once you want to commit a piece of content, push the repo on remote. |
Python | UTF-8 | 295 | 3.375 | 3 | [
"Apache-2.0"
] | permissive | #-----------Binary Tree------------
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
btn1 = BinaryTreeNode(1)
btn2 = BinaryTreeNode(2)
btn3 = BinaryTreeNode(3)
btn1.left = btn2
btn1.right = btn3
|
JavaScript | UTF-8 | 1,487 | 3.0625 | 3 | [] | no_license | const timer = document.querySelector('.timer__show');
const start = document.querySelector('.start');
const pause = document.querySelector('.pause');
const reset = document.querySelector('.reset');
let second =0;
let minute =0;
let houre = 0;
start.addEventListener('click', () => {
const Interval = setInterval(() => {
second +=1;
if (second > 59) {
minute += 1;
second = 0;
}
if (minute > 59) {
houre += 1;
minute = 0;
}
if (minute < 10 && second < 10 && houre < 10) {
timer.innerText = "0" + houre + ":" + "0" + minute + ":" + "0" + second;
} else if (minute < 10 && second > 10 && houre < 10) {
timer.innerText = "0" + houre + ":" + "0" + minute + ":" + second;
} else if (minute > 10 && second > 10 && houre < 10) {
timer.innerText = "0" + houre + ":" + minute + ":" + second;
} else if (minute > 10 && second > 10 || houre > 10) {
timer.innerText = houre + ":" + minute + ":" + second;
};
}, 1000);
pause.addEventListener('click', () => {
clearInterval(Interval);
});
reset.addEventListener('click', () => {
second = 0;
minute = 0;
houre = 0;
timer.innerText = "0" + houre + ":" + "0" + minute + ":" + "0" + second;
clearInterval(Interval);
})
});
|
C# | UTF-8 | 5,678 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | using System;
using System.Collections.Generic;
using System.Reflection;
using Nirvana.CQRS;
namespace Nirvana.Util.Extensions
{
public static class PropertyInfoExtensions
{
public static string WritePrimitiveType(this PropertyInfo propertyInfo)
{
var type = propertyInfo.PropertyType;
return WritePrimitiveType(type);
}
public static string WritePrimitiveType(this Type type)
{
if (type.IsString())
{
{
return "string";
}
}
if (type.IsType())
{
{
return "any";
}
}
if (type.IsNumber())
{
{
return "number";
}
}
if (type.IsDate())
{
{
return "Date";
}
}
if (IsBoolean(type))
{
{
return "boolean";
}
}
if (type.IsObject())
{
{
return "any";
}
}
if (type.IsObject())
{
{
return "any";
}
}
return string.Empty;
}
public static bool IsPrimitiveType(this PropertyInfo propertyInfo)
{
var propertyType = propertyInfo.PropertyType;
return IsPrimitiveType(propertyType);
}
public static bool IsPrimitiveType(this Type propertyType)
{
return propertyType.IsString()
|| propertyType.IsNumber()
|| IsBoolean(propertyType)
|| propertyType.IsDate()
|| propertyType.IsType()
|| IsObject(propertyType);
}
public static GenericMatch IsEnumType(this PropertyInfo propertyInfo)
{
var propertyType = propertyInfo.PropertyType;
return IsEnumType(propertyType);
}
public static GenericMatch IsEnumType(this Type propertyType)
{
Type[] types;
var isEnumType = propertyType.ClosesOrImplements(typeof(IEnumerable<>), out types);
var isArrayType = propertyType.IsArray;
if (isArrayType)
{
}
return new GenericMatch
{
Matches = isEnumType,
Arguments = types
};
}
public static GenericMatch IsPagedResult(this PropertyInfo propertyInfo)
{
var propertyType = propertyInfo.PropertyType;
return IsPagedResult(propertyType);
}
public static GenericMatch IsPagedResult(this Type propertyType)
{
Type[] types;
var isEnumType = propertyType.ClosesOrImplements(typeof(PagedResult<>), out types);
return new GenericMatch
{
Matches = isEnumType,
Arguments = types
};
}
public static bool IsHiddenProperty(this PropertyInfo propertyInfo)
{
return propertyInfo.Name == "AuthCode";
}
public static bool IsDate(this PropertyInfo prop)
{
var propType = prop.PropertyType;
return IsDate(propType);
}
public static bool IsDate(this Type propType)
{
return propType == typeof(DateTime)
|| propType == typeof(DateTime?);
}
public static bool IsType(this Type propType)
{
return propType == typeof(Type);
}
public static bool IsObject(this Type propType)
{
return propType == typeof(object)
|| propType == typeof(object)
|| propType == typeof(byte);
}
public static bool IsBoolean(this Type propType)
{
return propType == typeof(bool)
|| propType == typeof(bool)
|| propType == typeof(bool?);
}
public static bool IsNumber(this PropertyInfo prop)
{
var propType = prop.PropertyType;
return IsNumber(propType);
}
public static bool IsNumber(this Type propType)
{
return propType == typeof(int)
|| propType == typeof(int?)
|| propType == typeof(short)
|| propType == typeof(short?)
|| propType == typeof(long)
|| propType == typeof(long?)
|| propType == typeof(decimal)
|| propType == typeof(decimal?)
|| propType == typeof(double)
|| propType == typeof(double?)
|| propType == typeof(float)
|| propType == typeof(float?);
}
public static bool IsString(this PropertyInfo prop)
{
var propType = prop.PropertyType;
return IsString(propType);
}
public static bool IsString(this Type propType)
{
return propType == typeof(string)
|| propType == typeof(string)
|| propType == typeof(Guid)
|| propType == typeof(Guid?);
}
public class GenericMatch
{
public bool Matches { get; set; }
public Type[] Arguments { get; set; }
}
}
} |
C# | UTF-8 | 3,720 | 2.75 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CourseWork
{
public partial class AddNewField : Form
{
public AddNewField()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
int number;
if (Int32.TryParse(textBox1.Text, out number))
{
if (comboBox1.SelectedIndex != -1)
{
try
{
sqlConnection1.Open();
SqlCommand command1 = new SqlCommand("SELECT CropId FROM Crop WHERE CropName = @name", sqlConnection1);
command1.Parameters.AddWithValue("@name", comboBox1.SelectedItem.ToString());
SqlDataReader reader1 = command1.ExecuteReader();
reader1.Read();
var CropId = reader1[0]; //отримаємо код обраної культури
reader1.Dispose();
SqlCommand command = new SqlCommand("INSERT INTO Field(FieldNumber,CropId) Values(@number,@cropid)", sqlConnection1);
command.Parameters.AddWithValue("@number", number);
command.Parameters.AddWithValue("@cropid", CropId);
command.ExecuteNonQuery(); //додаємо у таблицю
sqlConnection1.Close();
MessageBox.Show("Запис успішно доданий.");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Ви не можете додавати поля з вже існуючими номерами"+ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
sqlConnection1.Close();
}
}
else
{
MessageBox.Show("Оберіть культуру у випадаючому списку");
}
}
else
{
MessageBox.Show("Номер поля має бути цілим числом(номера полів не можуть повторюватись)");
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void AddNewField_Load_1(object sender, EventArgs e)
{
try //заповнюємо comboBox1
{
// String number;
sqlConnection1.Open();
SqlCommand command = new SqlCommand("SELECT CropName FROM Crop", sqlConnection1);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString(0));
//comboBox1.DisplayMember = reader.GetString(1);;
//comboBox1.ValueMember = reader.GetInt32(0).ToString();
}
sqlConnection1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
|
Java | UTF-8 | 2,583 | 2.484375 | 2 | [] | no_license | package edu.washington.mhd94.quizdroid;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import java.lang.Object.*;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
ArrayList<String> subjects;
static QuizApp app = QuizApp.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
subjects = app.getRepository().initializeSubjects();
ListView listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, subjects);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long d) {
Intent nextActivity = new Intent(MainActivity.this, SecondActivity.class);
String subject = subjects.get(position);
if(subject.contains("Math")) {
nextActivity.putExtra("subject", "Math");
} else if(subject.contains("Physics")) {
nextActivity.putExtra("subject", "Physics");
} else {
nextActivity.putExtra("subject", "Marvel Super Heroes");
}
startActivity(nextActivity);
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent nextActivity = new Intent(MainActivity.this, Preferences.class);
startActivity(nextActivity);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
Java | UTF-8 | 375 | 1.84375 | 2 | [
"Apache-2.0"
] | permissive | package com.example.demo;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface TransactionRepository extends CrudRepository<Transaction, Long> {
List<Transaction> findByUserId(long userId);
List<Transaction> findByProductId(long productId);
List<Transaction> findByType(String type);
Transaction findById(long id);
} |
Java | UTF-8 | 2,017 | 2.171875 | 2 | [] | no_license | package com.iask.yiyuanlegou1.home.main.product;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.iask.yiyuanlegou1.R;
import com.iask.yiyuanlegou1.log.AndroidLogger;
import com.iask.yiyuanlegou1.log.Logger;
import com.iask.yiyuanlegou1.network.respose.product.ProductClassifyListBean;
import com.makeramen.roundedimageview.RoundedImageView;
import java.util.List;
public class ProductClassifyListAdapter extends BaseAdapter {
private List<ProductClassifyListBean> data;
private Context context;
private Logger logger = AndroidLogger.getLogger(getClass().getSimpleName());
public ProductClassifyListAdapter(List<ProductClassifyListBean> data, Context context) {
this.data = data;
this.context = context;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (null == convertView) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.listview_product_classify_item, parent, false);
holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_classify_name);
holder.ivHead = (RoundedImageView) convertView
.findViewById(R.id.iv_classify_icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ProductClassifyListBean bean = data.get(position);
return convertView;
}
class ViewHolder {
TextView tvTitle;
RoundedImageView ivHead;
}
}
|
Java | UTF-8 | 142 | 1.5625 | 2 | [
"Apache-2.0"
] | permissive | package com.alibaba.aliper.client.view;
public interface IView {
void fill(String agent,String chart,String line,long time,double value);
}
|
C | UTF-8 | 7,118 | 3.09375 | 3 | [] | no_license |
#include "tools.h"
/* in result, file pointer is pointing to the begin of i-node bitmap */
int copy_file_to_vd(char *filename, char *vd_name){
FILE *file_to_copy;
FILE *disk;
FILE *secondDescriptor; /* helper descriptor */
char *inode_bitmap;
char *data_bitmap;
char buffer[BLOCK_SIZE];
struct stat st;
double size_file_to_copy;
superblock block;
unsigned char mask;
unsigned char byte; /*variable for checking bitmaps and holding temporary bytes*/
int temp;
int counter;
inode temp_inode;
file_to_copy = fopen(filename, "rb");
if (file_to_copy == NULL){
perror("Cannot open file to copy disk");
return -1;
}
stat(filename, &st);
size_file_to_copy = st.st_size;
disk = fopen(vd_name, "r+b");
if (disk == NULL){
perror("Cannot open virtual disk");
return -1;
}
if (read_and_check_superblock(&block, disk) == -1){
return -1;
}
int blocks_needed_to_copy_file = ceil(size_file_to_copy / BLOCK_SIZE);
if (block.free_block_number < blocks_needed_to_copy_file){
printf("Too few space on virtual disk!");
return -1;
}
inode_bitmap = (char *)malloc(block.bytes_for_bitmap);
data_bitmap = (char *)malloc(block.bytes_for_bitmap);
read_bitmap_blocks(block.bytes_for_bitmap, inode_bitmap, data_bitmap, disk);
/* First, we have to check if we have file, which name is the same as file to copy*/
/* TODO: Add check to &IN USE */
secondDescriptor = fopen(vd_name, "r+b");
/* move second descriptor to the inode bitmap*/
kseek(disk, BLOCK_SIZE, SEEK_SET);
mask = 0x80;
counter = 0;
for (int i = 0; i < block.inode_number; i++){
byte = inode_bitmap[counter];
byte = mask & byte;
kread(&temp_inode, sizeof(inode), disk);
if (strcmp(filename, temp_inode.filename) == 0 && byte > 0){ /* We have file like that on disk - */
printf("jest taki sam");
/*we have to count, have many blocks this file consisted */
int blocks_for_old_file = ceil((double)temp_inode.size_of_file / BLOCK_SIZE);
if (blocks_needed_to_copy_file <= blocks_for_old_file + block.free_block_number){
remove_file_from_vd(filename, vd_name); /* Delete it */
/*File is removed, it's time to write new file*/
/*But first we have to re-check superblock - remove file could change it! */
kseek(disk, 0, SEEK_SET);
read_and_check_superblock(&block, disk);
break;
}
else{
printf("New file is too big!");
return -1;
}
}
if (fseek(disk, block.inode_size - sizeof(inode), SEEK_CUR) != 0){
perror("Cannot move file pointer");
}
if (mask == 0){
mask = 0x80;
counter ++;
}
}
fclose(secondDescriptor);
if (block.free_inode_number == 0){
printf("Too many files on virtual disk\n");
return -1;
}
kseek(disk, 3 * BLOCK_SIZE, SEEK_SET);
/* File pointer is at the beginning of inode structure table */
mask = 0x80;
short *pointers_to_blocks = (short *)malloc(sizeof(short) * block.block_number);
temp = 0; /* temporary variable, used to properly moving file pointer across inode table */
counter = 0;
for (int i = 0; i < block.inode_number; i++){
byte = inode_bitmap[counter];
unsigned char result = mask & byte;
if (result == 0){
/* We have found unused i-node */
/* Firstly move pointer to this inode in inode-table */
if (fseek(disk, i * block.inode_size, SEEK_CUR) != 0){
perror("Cannot move file pointer");
}
inode i_node;
write_string_to_array(filename, i_node.filename);
i_node.size_of_file = size_file_to_copy;
inode_bitmap[counter] = inode_bitmap[counter] | mask;
block.free_inode_number--;
/*Now write i-node description to i_node table */
// printf("przed zapisaniem inode description: %lu\n", ftell(disk));
kwrite(&i_node, sizeof(inode), disk);
/* Inode description is written - now if file is non 0 size - take care of data blocks */
/* Now read pointers, update them, and write to the */
kread(pointers_to_blocks, sizeof(short) * block.block_number, disk);
printf("rozmiar to %lf\n", size_file_to_copy);
if (size_file_to_copy > 0){
mask = 0x80;
counter = 0;
int pointer_counter = 0;
secondDescriptor = fopen(vd_name, "r+b");
temp = ceil((double)block.inode_size * block.block_number / BLOCK_SIZE); /*Block number for inode_structure_table */
kseek(secondDescriptor, (3 + temp) * BLOCK_SIZE, SEEK_CUR);
for(int i = 0; i < block.block_number; i++){
byte = data_bitmap[counter];
// printf("bajt ma: %x\n", byte);
// printf("maska ma: %x\n", mask);
result = mask & byte;
if (result == 0){/*We have found data block - bit is 0!*/
temp = size_file_to_copy > BLOCK_SIZE ? BLOCK_SIZE : size_file_to_copy;
size_file_to_copy -= BLOCK_SIZE;
kread(buffer, temp, file_to_copy);
// printf("Zapisuje na: %lu rozmiar: %d\n", ftell(secondDescriptor), temp);
kwrite(buffer, temp, secondDescriptor);
block.free_block_number --;
// printf("zapisujemy na pozycje: %d wartosc %d", pointer_counter, i);
pointers_to_blocks[pointer_counter] = i;
// printf("pointer: %d\n", pointers_to_blocks[pointer_counter]);
data_bitmap[counter] = data_bitmap[counter] | mask;
if (size_file_to_copy <= 0){
fclose(secondDescriptor);
kseek(disk, -sizeof(short) * block.block_number, SEEK_CUR);
kwrite(pointers_to_blocks, sizeof(short) * block.block_number, disk);
break;
}
pointer_counter++; // ZMIENIONE, NEWRALGICZNE
}/* do result */
else{
kseek(secondDescriptor, BLOCK_SIZE, SEEK_CUR);
}
mask = mask >> 1;
if (mask == 0){
mask = 0x80;
counter ++;
}
}/* do for */
}/* fo file size */
/* I-node is now used by the file system - wrote information about it into the bitmap file */
break;
}/* result */
mask = mask >> 1;
if (mask == 0){
mask = 0x80;
counter ++;
}
}/* koniec fora*/
// printf("Pointers: 1 : %d, 2: %d\n", pointers_to_blocks[0], pointers_to_blocks[1]);
kseek(disk, 0, SEEK_SET);
kwrite(&block, sizeof(superblock), disk);
kseek(disk, BLOCK_SIZE - sizeof(superblock), SEEK_CUR);
kwrite(inode_bitmap, block.bytes_for_bitmap, disk);
kseek(disk, 2 * BLOCK_SIZE, SEEK_SET);
kwrite(data_bitmap, block.bytes_for_bitmap, disk);
//Debug
free(inode_bitmap);
free(pointers_to_blocks);
free(data_bitmap);
fclose(file_to_copy);
fclose(disk);
return 0;
}
int main(int argc, char **argv){
char *vmachine;
if (argc < 3){
if (argc == 2 && strcmp(argv[1], "--help") == 0){
printf("Uzycie:\n./cpvd PLIKI[...] VIRTUAL FILE SYSTEM\n");
return 0;
}
else{
printf("Nieprawidlowe wywolanie. wywolaj z opcja --help: %s --help\n", argv[0]);
return -1;
}
}
char **arg_pointer = argv;
arg_pointer++;
while (*arg_pointer){
arg_pointer++;
}
arg_pointer--; // jestesmy na ostatnim wskazniku
vmachine = *arg_pointer;
printf("vmachine to : %s", vmachine);
arg_pointer = argv;
arg_pointer++;
while (*arg_pointer != vmachine){
printf("kopiujemy: %s\n", *arg_pointer);
if (copy_file_to_vd(*arg_pointer, vmachine) == -1){
return -1;
}
arg_pointer++;
}
return 0;
} |
JavaScript | UTF-8 | 3,168 | 2.9375 | 3 | [] | no_license | new Vue({
el:'#app',
data:{
playerHealth:100,
monsterHealth:100,
isGameOn:false,
count:0,
monAttack:0,
playAttack:0,
isShowLog:false
},
methods:{
startGame:function(){
this.isGameOn=true;
this.isShowLog=false;
this.playerHealth=100;
this.monsterHealth=100;
this.count=0;
},
attack:function(){
if(this.playerHealth<=0){
let con=confirm('You lose!, you want to play again?');
if(con){
this.startGame();
}else{
this.startGame();
this.isGameOn=false;
}
return;
}
if(this.monsterHealth<=0){
let con=confirm('You win!, you want to play again?');
if(con){
this.startGame();
}else{
this.startGame();
this.isGameOn=false;
}
return;
}
this.playAttack=this.attckFunction(10,3)
this.monsterHealth -=this.playAttack
if(this.monsterHealth<=0){
this.monsterHealth=0;
}
this.monAttack=this.attckFunction(10,3);
this.playerHealth -= this.monAttack;
if(this.playerHealth<=0){
this.playerHealth=0;
}
this.isShowLog=true;
},
specialAttack:function(){
this.count++;
if(this.count>3){
alert('You used all special attack move!');
return;
}
if(this.playerHealth<=0){
alert('You lose!')
return;
}
if(this.monsterHealth<=0){
alert('You win');
return;
}
this.playAttack=this.attckFunction(14,8);
this.monsterHealth -=this.playAttack;
this.monAttack=this.attckFunction(10,3);
this.playerHealth -= this.monAttack;
this.isShowLog=true;
},
heal:function(){
if(this.playerHealth> 0 && this.playerHealth<100 && this.monsterHealth>0){
this.playerHealth +=this.attckFunction(6,3);
this.monsterHealth +=this.attckFunction(8,3);
}else {
return;
}
},
giveUp:function(){
if(this.playerHealth==100 || this.monsterHealth==100 || this.playerHealth==0 || this.monsterHealth==0 ){
return;
}
if(this.playerHealth<this.monsterHealth){
if (confirm("Are you sure?")) {
this.startGame();
} else {
return;
}
}else{
var a=confirm('You are winning,Are you sure to giveup? ')
if(a){
this.startGame();
this.isGameOn=false;
}
}
},
attckFunction:function(max,min){
return Math.max(Math.floor(Math.random() * max),min);
}
}
});
|
PHP | UTF-8 | 2,041 | 2.5625 | 3 | [] | no_license | <?php
use App\Category;
use App\Circle;
use App\User;
use Illuminate\Database\Seeder;
class UserSeeder extends Seeder
{
private $storage = 'users';
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$images = $this->images;
if (env('SEED_TEST_USERS')) {
echo "Test users\n";
factory(User::class)->create([
'email' => 't@e.st',
'image' => $this->storage . '/' . array_pop($images),
]);
factory(User::class)->create([
'email' => 't2@e.st',
'image' => $this->storage . '/' . array_pop($images),
]);
factory(User::class)->create([
'email' => 't3@e.st',
'image' => $this->storage . '/' . array_pop($images),
]);
factory(User::class)->create([
'email' => 'ad@m.in',
'is_administrator' => true,
'image' => $this->storage . '/' . array_pop($images),
]);
}
$n = env('SEED_AMOUNT_USERS') ?: 50;
echo $n . " users\n";
for ($i=0; $i<$n; $i++) {
$user = factory(User::class)->create();
if (!sizeof($images)) {
$images = $this->images;
}
// set circle
$user->update([
'circle_id' => Circle::inRandomOrder()->first()->id,
'image' => $this->storage . '/' . array_pop($images),
]);
// add 1 to 3 categories
$categories = Category::inRandomOrder()->
select('id')->
limit(rand(1,3))->
get()->all();
$user->categories()->sync(array_column($categories, 'id'));
}
}
private $images = [
'Karen.jpg',
'Frank.jpg',
'Annamarie.jpg',
'Dennis.jpg',
'Hannah.jpg',
'Sander.jpg',
'Annamarie_02.jpg',
'Tim.jpg',
];
}
|
Python | UTF-8 | 895 | 3.296875 | 3 | [] | no_license | def saddle_points(matrix):
if len(matrix) == 0:
return []
## Raise ValueError if nested list element is not match in case irregular matrix.
element_count = len(matrix[0])
for sublist in matrix:
if len(sublist) != element_count:
raise ValueError("Irregular Matrix.")
## column formation
col_matrix = list()
for i in range(len(matrix[0])):
temp = list()
for sublist in matrix:
temp.append(sublist[i])
col_matrix.append(temp)
# output_list
output = list()
# find saddle point
for r,ri in zip(matrix,range(len(matrix))):
for c,ci in zip(col_matrix,range(len(col_matrix))):
if sorted(r)[-1] == sorted(c)[0]:
output.append({
"row": ri+1,
"column": ci+1
})
return output
saddle_points([]) |
JavaScript | UTF-8 | 493 | 2.578125 | 3 | [] | no_license | import React from 'react';
const Progress = (props) => {
let keyResults = props.data;
let score = 0;
let value = 0;
if(keyResults.length !== 0) {
score = keyResults.reduce((prev, keyResult) => {
return prev += +keyResult.score;
}, 0);
value = Math.round(100 * score / keyResults.length);
}
return (
<div className="progress-bar">
<progress max="100" value={ value }></progress>
<div className="progressValue">{ value }%</div>
</div>
)
}
export default Progress
|
Python | UTF-8 | 14,737 | 2.609375 | 3 | [] | no_license | from abc import ABC, abstractmethod
from screens.disposition_code import MenuAction
from screens.menu_renderer import StandardTextRenderer
from screens.menu_renderer import LazyTextRenderer
from screens.menu_renderer import HighlightStrategyNormal
from screens.menu_renderer import HighlightStrategyInputField
from gameplay.keys import GameKeys
from gameplay.keys import KeyFunction
# Responsible for building the MenuContext subclasses
class MenuContextFactory(object):
"""
Builds the various MenuContexts since they take a lot of dependencies
"""
def __init__(self, jukebox, key_change_publisher, game_keys, key_mapper, font_file, screen):
"""
Args:
jukebox (sound.audio.Jukebox): Provides control over the sound and music
key_change_publisher (gameplay.keys.KeyChangePublisher): allows the menu to change the key mappings
game_keys (gameplay.keys.GameKeys): Provides a registry of available keys in the game
key_mapper (gameplay.keys.KeyMapper): Allows the menu to see the current key mappings
font_file (str): the path to the file containing the font to use for the menu options
screen (pygame.display): provides access to the screen for rendering the menu
"""
self.jukebox = jukebox
self.key_change_publisher = key_change_publisher
self.game_keys = game_keys
self.key_mapper = key_mapper
self.font_file = font_file
self.screen = screen
def build_top_level_menu_screen(self, is_game_paused):
if is_game_paused:
return TopLevelPausedMenuContext(self, lambda name, labels: self._get_standard_builder(name, labels))
else:
return TopLevelMenuContext(self, lambda name, labels: self._get_standard_builder(name, labels))
def build_music_selection_screen(self):
return MusicSelectionMenuContext(
self,
lambda name, labels: self._get_standard_builder(name, labels),
self.jukebox)
def build_options_screen(self):
return OptionsMenuContext(
self,
lambda name, label_provider: self._get_lazy_builder(name, label_provider),
self.jukebox)
def build_key_changing_screen(self):
return KeySettingMenuContext(
self,
self.key_change_publisher,
self.game_keys,
self.key_mapper,
lambda name, label_provider, special_highlight_indicator: self._get_lazy_builder_special_highlight(
name, label_provider, special_highlight_indicator))
def _get_standard_builder(self, name, labels):
return MenuRenderInfo(
name,
StandardTextRenderer(self.font_file, self.screen.get_size(), labels),
HighlightStrategyNormal())
def _get_lazy_builder(self, name, label_provider):
return MenuRenderInfo(
name,
LazyTextRenderer(label_provider, self.font_file, self.screen.get_size()),
HighlightStrategyNormal())
def _get_lazy_builder_special_highlight(self, name, label_provider, special_highlight_indicator):
return MenuRenderInfo(name, LazyTextRenderer(label_provider, self.font_file, self.screen.get_size()),
HighlightStrategyInputField(special_highlight_indicator))
# Abstract base class for all menu and submenu contexts
class MenuContext(ABC):
"""
Args:
context_factory (): allows the menu to build a submenu when needed
render_info (screens.menu_handlers.MenuRenderInfo): Encapsulates certain information about the menu state in a
way that can be understood by the renderer
"""
# context_factory - allows the handler to create a new handler for a submenu it controls
def __init__(self, context_factory, render_info):
self.selected_index = 0
self.context_factory = context_factory
self.render_info = render_info
@abstractmethod
def execute_current_option(self):
""" Executes the menu option that is selected """
return None
@abstractmethod
def get_num_options(self):
"""
Returns:
int: the number of options there are in this menu
"""
return 0
def is_listening_for_key(self):
"""
Certain menus can intercept free-form keyboard input rather than just the navigation keys.
Returns:
bool: True if this menu wants to intercept keys, False if not
"""
return False
def handle_key_event(self, key):
"""
Used in tandem with is_listening_for_key. This is what sends the keypress event to the menu to handle
Args:
key (gameplay.keys.Key): the key that was pressed
"""
return
def get_render_info(self):
"""
Returns:
screens.menu_handlers.MenuRenderInfo: The MenuRenderInfo that is applicable for the current menu state
"""
return self.render_info
def get_context_factory(self):
"""
Returns:
screens.menu_handlers.MenuContextFactory: The factory that can be ued to build submenus
"""
return self.context_factory
def get_selected_index(self):
"""
Returns:
The index of the menu item that the cursor is on
"""
return self.selected_index
def move_to_next_option(self):
""" Sets the cursor the next menu option, looping back if it goes past the end. """
self.selected_index += 1
if self.selected_index >= self.get_num_options():
self.selected_index = 0
def move_to_previous_option(self):
""" Sets the cursor to the previous menu options, looping back if it goes past the beginning. """
self.selected_index -= 1
if self.selected_index < 0:
self.selected_index = self.get_num_options() - 1
# contains everything needed to render the menu
class MenuRenderInfo(object):
def __init__(self, title, text_renderer, highlight_strategy):
self.title = title
self.text_renderer = text_renderer
self.highlight_strategy = highlight_strategy
def get_labels(self):
return self.text_renderer.get_labels()
def get_text_renderer(self):
return self.text_renderer
def get_highlight_color(self):
return self.highlight_strategy.get_highlight_color()
class TopLevelMenuContext(MenuContext):
""" Represents the main menu, where no game is in progress """
def __init__(self, context_factory, render_info_builder):
render_info = render_info_builder("Main", ["New Game", "High Scores", "Options", "Quit"])
super(TopLevelMenuContext, self).__init__(context_factory, render_info)
def get_num_options(self):
return 4
def execute_current_option(self):
if self.get_selected_index() == 0:
return NextStateInfo(self, MenuAction.PLAY_GAME)
elif self.get_selected_index() == 1:
return NextStateInfo(self, MenuAction.SHOW_HIGH_SCORES)
elif self.get_selected_index() == 2:
return NextStateInfo(self.get_context_factory().build_options_screen(), MenuAction.MENU)
elif self.get_selected_index() == 3:
return NextStateInfo(self, MenuAction.QUIT)
class TopLevelPausedMenuContext(MenuContext):
def __init__(self, context_factory, render_info_builder):
render_info = render_info_builder(
"Main Paused",
["Resume Game", "New Game", "High Scores", "Options", "Quit"])
super(TopLevelPausedMenuContext, self).__init__(context_factory, render_info)
def get_num_options(self):
return 5
def execute_current_option(self):
if self.get_selected_index() == 0:
return NextStateInfo(self, MenuAction.PLAY_GAME)
elif self.get_selected_index() == 1:
# This is a hack to make sure the cursor ends up on "resume game" whenever the player escapes to the menu
# Otherwise the cursor would be left on "new game" and it could be frustrating.
self.selected_index = 0
return NextStateInfo(self, MenuAction.NEW_GAME)
elif self.get_selected_index() == 2:
return NextStateInfo(self, MenuAction.SHOW_HIGH_SCORES)
elif self.get_selected_index() == 3:
return NextStateInfo(self.get_context_factory().build_options_screen(), MenuAction.MENU)
elif self.get_selected_index() == 4:
return NextStateInfo(self, MenuAction.QUIT)
class MusicSelectionMenuContext(MenuContext):
def __init__(self, context_factory, render_info_builder, jukebox):
render_info = render_info_builder("Music Selection", jukebox.get_available_song_titles())
super(MusicSelectionMenuContext, self).__init__(context_factory, render_info)
self.songs = jukebox.get_available_song_titles()
self.jukebox = jukebox
def get_num_options(self):
return len(self.songs)
def execute_current_option(self):
selected_song = self.songs[self.get_selected_index()]
self.jukebox.set_song(selected_song)
return NextStateInfo(self, MenuAction.MENU)
class KeySettingMenuContext(MenuContext):
KEY_FUNCTIONS = [
KeyFunction.MOVE_LEFT,
KeyFunction.MOVE_RIGHT,
KeyFunction.MOVE_DOWN,
KeyFunction.DROP,
KeyFunction.ROTATE_LEFT,
KeyFunction.ROTATE_RIGHT]
LABELS_FOR_KEY_FUNCTION = {
KeyFunction.MOVE_LEFT: "Move Left: ",
KeyFunction.MOVE_RIGHT: "Move Right: ",
KeyFunction.MOVE_DOWN: "Move Down: ",
KeyFunction.DROP: "Drop Piece: ",
KeyFunction.ROTATE_LEFT: "Rotate Left: ",
KeyFunction.ROTATE_RIGHT: "Rotate Right: "
}
def __init__(self, context_factory, key_change_publisher, game_keys, key_mapper, render_info_builder):
render_info = render_info_builder("Keys", lambda: self.get_labels(), lambda: self.is_listening_for_key())
super(KeySettingMenuContext, self).__init__(context_factory, render_info)
self.key_change_publisher = key_change_publisher
self.game_keys = game_keys
self.key_mapper = key_mapper
self.dirty = True
self.listening_for_key = False
self.cached_labels = []
# provides the key name for the given key function
self.function_to_key_name = {
KeyFunction.MOVE_LEFT: key_mapper.get_key_by_function(KeyFunction.MOVE_LEFT).name,
KeyFunction.MOVE_RIGHT: key_mapper.get_key_by_function(KeyFunction.MOVE_RIGHT).name,
KeyFunction.MOVE_DOWN: key_mapper.get_key_by_function(KeyFunction.MOVE_DOWN).name,
KeyFunction.DROP: key_mapper.get_key_by_function(KeyFunction.DROP).name,
KeyFunction.ROTATE_LEFT: key_mapper.get_key_by_function(KeyFunction.ROTATE_LEFT).name,
KeyFunction.ROTATE_RIGHT: key_mapper.get_key_by_function(KeyFunction.ROTATE_RIGHT).name
}
# This is the order the menu options are presented in. This will be used to
# get the key function based on which menu item is selected.
self.index_to_function = [KeyFunction.MOVE_LEFT, KeyFunction.MOVE_RIGHT, KeyFunction.MOVE_DOWN,
KeyFunction.DROP, KeyFunction.ROTATE_LEFT, KeyFunction.ROTATE_RIGHT]
def get_num_options(self):
return len(self.index_to_function)
def execute_current_option(self):
self.listening_for_key = True
return NextStateInfo(self, MenuAction.MENU)
def is_listening_for_key(self):
return self.listening_for_key
# key - the Key that was pressed
def handle_key_event(self, key):
if not self.listening_for_key:
return
# The labels have changed
self.dirty = True
key_function = self.index_to_function[self.get_selected_index()]
self.function_to_key_name[key_function] = self.game_keys.by_id(key.id).name
# Notify all subscribers of the key change
self.key_change_publisher.on_key_change(key_function, key)
self.listening_for_key = False
def get_labels(self):
if not self.dirty:
return self.cached_labels
self.dirty = False
new_labels = []
for function in self.index_to_function:
new_labels.append(self.LABELS_FOR_KEY_FUNCTION[function] + '<' + self.function_to_key_name[function] + '>')
self.cached_labels = new_labels
return self.cached_labels
class OptionsMenuContext(MenuContext):
SOUND_ON = "Sound [On] / Off"
SOUND_OFF = "Sound On / [Off]"
MUSIC_ON = "Music [On] / Off"
MUSIC_OFF = "Music On / [Off]"
CHANGE_SONG = "Change Song"
CHANGE_KEYS = "Change Keys"
def __init__(self, context_factory, render_info_builder, jukebox):
render_info = render_info_builder("Options", lambda: self.get_labels())
super(OptionsMenuContext, self).__init__(context_factory, render_info)
self.jukebox = jukebox
self.sound_enabled = True
self.music_enabled = True
def get_num_options(self):
return 4
def execute_current_option(self):
if self.get_selected_index() == 0:
self.toggle_sound()
return NextStateInfo(self, MenuAction.MENU)
elif self.get_selected_index() == 1:
self.toggle_music()
return NextStateInfo(self, MenuAction.MENU)
elif self.get_selected_index() == 2:
return NextStateInfo(self.get_context_factory().build_music_selection_screen(), MenuAction.MENU)
elif self.get_selected_index() == 3:
return NextStateInfo(self.get_context_factory().build_key_changing_screen(), MenuAction.MENU)
def toggle_sound(self):
# this controls the text for the menu item
self.sound_enabled = not self.sound_enabled
self.jukebox.enable_sound(self.sound_enabled)
def toggle_music(self):
# this controls the text for the menu item
self.music_enabled = not self.music_enabled
self.jukebox.enable_music(self.music_enabled)
def get_labels(self):
sound = self.SOUND_ON if self.sound_enabled else self.SOUND_OFF
music = self.MUSIC_ON if self.music_enabled else self.MUSIC_OFF
return [sound, music, self.CHANGE_SONG, self.CHANGE_KEYS]
class NextStateInfo(object):
def __init__(self, active_menu_screen, game_state):
self.active_menu_screen = active_menu_screen
self.game_state = game_state
def get_active_menu_screen(self):
return self.active_menu_screen
def get_menu_action(self):
return self.game_state
|
PHP | UTF-8 | 452 | 2.71875 | 3 | [] | no_license | <?php
namespace App\Utils;
class Statuses
{
const TO_DO = 'To do';
const IN_PROGRESS = 'In progress';
const IN_QA = 'In QA';
const DONE = 'Done';
public static function all(): array
{
return [
Statuses::TO_DO,
Statuses::IN_PROGRESS,
Statuses::IN_QA,
Statuses::DONE,
];
}
public static function getDefault()
{
return Statuses::TO_DO;
}
} |
Java | UTF-8 | 9,595 | 2.203125 | 2 | [
"MIT"
] | permissive | /*
The MIT License (MIT)
Copyright (c) 2015 Terence Parr, Hanzhou Shi, Shuai Yuan, Yuanyuan Zhang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package wich.codegen;
import org.antlr.symtab.Utils;
import org.antlr.v4.runtime.misc.Pair;
import wich.codegen.model.CompositeModelObject;
import wich.codegen.model.ModelElement;
import wich.codegen.model.OutputModelObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
// listener methods:
// return null means delete. return same object means don't replace. return diff object means replace.
// invokes exact enter/exitModel(T); doesn't work for T subclasses. enter called at node discovery
// and then visitEveryModelObject(). After children, exitModel().
public class ModelWalker {
public static final Object NOTFOUND = new Object(); // can't use exact type here as we can't create MethodHandle for sentinel
public static final OutputModelObject NO_RESULT = new OutputModelObject();
public final String ENTER_METHOD_NAME = "enterModel";
public final String EXIT_METHOD_NAME = "exitModel";
protected final Object listener;
/** Track (methodname,argtype) -> method handle for firing listener events */
protected final Map<Pair<String,Class<?>>, Object> listenerMethodCache = new HashMap<>();
protected Object visitEveryModelObjectMethodCache = null;
public ModelWalker(Object listener) {
this.listener = listener;
}
public OutputModelObject walk(OutputModelObject omo) {
if ( omo==null ) return NO_RESULT;
// Exec the exit/every node methods.
// If there is a result for the specific node type (exitModel), return that
// else return visitEveryModelObject result.
// Returning null from either indicates caller should drop this node
// from its field.
final OutputModelObject result1 = enterModel(omo);
final OutputModelObject result2 = visitEveryModelObject(omo);
OutputModelObject replacement = result1 != NO_RESULT ? result1 : result2;
if ( replacement==null ) { // null means delete so nothing to walk and return nothing
return null;
}
if ( replacement!=NO_RESULT && replacement!=omo ) {
omo = replacement;
}
Class<? extends OutputModelObject> cl = omo.getClass();
Field[] allAnnotatedFields = Utils.getAllAnnotatedFields(cl);
List<Field> modelFields = new ArrayList<>();
for (Field fi : allAnnotatedFields) {
ModelElement annotation = fi.getAnnotation(ModelElement.class);
if ( annotation != null ) {
modelFields.add(fi);
}
}
// WALK EACH NESTED MODEL OBJECT MARKED WITH @ModelElement
for (Field fi : modelFields) {
ModelElement annotation = fi.getAnnotation(ModelElement.class);
if (annotation == null) continue;
String fieldName = fi.getName();
try {
Object o = fi.get(omo);
if ( o instanceof CompositeModelObject ) {
walkList(((CompositeModelObject)o).modelObjects);
}
else if ( o instanceof OutputModelObject ) { // SINGLE MODEL OBJECT?
OutputModelObject nestedOmo = (OutputModelObject)o;
replacement = walk(nestedOmo);
if ( replacement!=NO_RESULT && replacement!=nestedOmo ) {
fi.set(omo, replacement);
}
}
else if ( o instanceof OutputModelObject[] ) {
walkArray((OutputModelObject[]) o);
}
else if ( o instanceof List ) {
walkList((List<OutputModelObject>) o);
}
else if ( o instanceof Map ) {
walkMap((Map<Object, OutputModelObject>) o);
}
else if ( o!=null ) {
System.err.println("type of "+fieldName+"'s model element isn't recognized: "+o.getClass().getSimpleName());
}
}
catch (IllegalAccessException iae) {
System.err.printf("Can't access field: "+fieldName+" in "+cl.getSimpleName());
}
}
// Null from enter and exit both mean delete from parent node
// but enter returning null means children of omo aren't visited.
// So, to delete and avoid visiting children, have enter return null
// rather than this exit call.
return exitModel(omo);
}
protected void walkArray(OutputModelObject[] elems) {
int i = 0;
while ( i < elems.length ) {
OutputModelObject nestedOmo = elems[i];
if ( nestedOmo==null ) continue;
final OutputModelObject replacement = walk(nestedOmo);
if ( replacement==null ) { // null means delete (shift array elements down) (expensive)
System.arraycopy(elems,i+1,elems, i,elems.length-i-1);
continue; // skip i++ as we deleted
}
else if ( replacement!=NO_RESULT && replacement!=nestedOmo ) {
elems[i] = replacement;
}
i++;
}
}
protected void walkList(List<OutputModelObject> nestedOmos) {
int i = 0;
while ( i < nestedOmos.size() ) {
OutputModelObject nestedOmo = nestedOmos.get(i);
if ( nestedOmo!=null ) {
final OutputModelObject replacement = walk(nestedOmo);
if ( replacement==null ) { // null means delete
nestedOmos.remove(i);
continue; // skip i++ as we deleted
}
else if ( replacement!=NO_RESULT && replacement != nestedOmo ) {
nestedOmos.set(i, replacement);
}
}
i++;
}
}
protected void walkMap(Map<Object, OutputModelObject> nestedOmoMap) {
for (Map.Entry<?, OutputModelObject> entry : nestedOmoMap.entrySet()) {
final OutputModelObject nestedOmo = entry.getValue();
final OutputModelObject replacement = walk(nestedOmo);
if ( replacement==null ) { // null means delete
nestedOmoMap.remove(entry.getKey());
}
else if ( replacement!=NO_RESULT && replacement!=nestedOmo ) {
nestedOmoMap.put(entry.getKey(), replacement);
}
}
}
/** Use reflection to find & invoke overloaded enter/exitModel(modeltype) method */
protected OutputModelObject enterModel(OutputModelObject omo) {
final Method m = getListenerMethodForType(omo.getClass(), ENTER_METHOD_NAME);
return execListenerMethod(omo, m);
}
protected OutputModelObject exitModel(OutputModelObject omo) {
final Method m = getListenerMethodForType(omo.getClass(), EXIT_METHOD_NAME);
return execListenerMethod(omo, m);
}
protected OutputModelObject visitEveryModelObject(OutputModelObject omo) {
final Method m = getVisitEveryNodeMethod();
return execListenerMethod(omo, m);
}
protected OutputModelObject execListenerMethod(OutputModelObject omo, Method m) {
Object result = NO_RESULT;
if ( m!=null ) {
try {
// can't use invokeExact as listener looks like an Object but we bound to listener.getClass()
result = m.invoke(listener, omo);
}
catch (Throwable e) {
throw new RuntimeException(e);
}
}
return (OutputModelObject)result;
}
protected Method getListenerMethodForType(Class<?> argType, String methodName) {
final Pair<String,Class<?>> key = new Pair<>(methodName, argType);
Object m = listenerMethodCache.get(key); // reflection is slow; cache.
if ( m!=null ) {
if ( m==NOTFOUND ) {
return null;
}
return (Method)m;
}
try {
m = listener.getClass().getMethod(methodName, argType);
listenerMethodCache.put(key, m);
}
catch (NoSuchMethodException nsme) {
m = null;
listenerMethodCache.put(key, NOTFOUND);
}
return (Method)m;
}
protected Method getVisitEveryNodeMethod() {
if ( visitEveryModelObjectMethodCache!=null ) {
if ( visitEveryModelObjectMethodCache==NOTFOUND ) {
return null;
}
return (Method)visitEveryModelObjectMethodCache;
}
Method m;
try {
m = listener.getClass().getMethod("visitEveryModelObject", OutputModelObject.class);
visitEveryModelObjectMethodCache = m;
}
catch (NoSuchMethodException nsme) {
m = null;
visitEveryModelObjectMethodCache = NOTFOUND;
}
return m;
}
/** Starting at node model, find all nodes at or below model that
* test true for predicate (including model root itself).
*/
public static List<OutputModelObject> findAll(OutputModelObject model,
Predicate<OutputModelObject> predicate)
{
List<OutputModelObject> nodes = new ArrayList<>();
if ( predicate.test(model) ) {
nodes.add(model);
}
ModelWalker walker = new ModelWalker(new Object() {
public OutputModelObject visitEveryModelObject(OutputModelObject o) {
if ( predicate.test(model) ) {
nodes.add(o);
}
return o;
}
});
walker.walk(model);
return nodes;
}
public static void applyToAll(OutputModelObject model, Consumer<OutputModelObject> f) {
ModelWalker walker = new ModelWalker(new Object() {
public OutputModelObject visitEveryModelObject(OutputModelObject o) {
f.accept(o);
return o;
}
});
walker.walk(model);
}
}
|
Java | UTF-8 | 1,307 | 2.140625 | 2 | [] | no_license | /**
* (C) 2011-2012 Alibaba Group Holding Limited.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
*/
package com.juhuasuan.osprey;
import java.io.Serializable;
/**
* @author juxin.zj E-mail:juxin.zj@taobao.com
* @since 2012-3-15
* @version 1.0
*/
public class MessageInStore implements Serializable {
private static final long serialVersionUID = -4444632901328933770L;
private Message message = null;
private boolean enabledSend = true;
private long createTime;
public MessageInStore(Message message, boolean enabledSend) {
this.message = message;
this.enabledSend = enabledSend;
this.createTime = System.currentTimeMillis();
}
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
public boolean isEnabledSend() {
return enabledSend;
}
public void setEnabledSend(boolean enabledSend) {
this.enabledSend = enabledSend;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
}
|
Java | UTF-8 | 1,183 | 3.859375 | 4 | [] | no_license | package p_2_array_of_arrays;
import java.util.Arrays;
import java.util.Scanner;
/**
* Задана матрица неотрицательных чисел. Посчитать сумму элементов в каждом столбце. Определить, какой
* столбец содержит максимальную сумму.
*/
public class Task9 {
public static void main(String[] args)
{
int[][] mas = {
{3, 2, 1},
{6, 4, 5},
{10, 7, 8}};
System.out.println("Source array: ");
System.out.println(Arrays.deepToString(mas));
int[] sum = new int[mas[0].length];
for (int i = 0; i < mas[0].length; i++) {
for (int j = 0; j < mas.length; j++) {
sum[i] += mas[j][i];
}
}
int max = sum[0], maxi = 0;
for (int i = 0; i < sum.length; i++) {
if (max < sum[i]) {
max = sum[i];
maxi = i;
}
}
System.out.println("Sums: " + Arrays.toString(sum));
System.out.println("the largest amount in " + (maxi + 1) + " column");
}
}
|
Java | UTF-8 | 1,551 | 2.21875 | 2 | [] | no_license | package br.com.acad.dao.dieta.impl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import br.com.acad.dao.dieta.interf.SolicitacaoDietaDAO;
import br.com.acad.dao.generico.impl.DAOImpl;
import br.com.acad.model.dieta.SolicitacaoDieta;
import br.com.acad.model.pessoa.Aluno;
@Repository
public class SolicitacaoDietaDAOImpl extends DAOImpl<SolicitacaoDieta, Integer> implements SolicitacaoDietaDAO
{
public SolicitacaoDietaDAOImpl()
{
super();
}
@Override
public List<SolicitacaoDieta> buscarTodos()
{
TypedQuery<SolicitacaoDieta> q = em.createQuery("from SolicitacaoDieta", SolicitacaoDieta.class);
return q.getResultList();
}
@SuppressWarnings("unchecked")
@Override
public List<SolicitacaoDieta> buscarPorAluno(Aluno aluno)
{
Query q = em.createQuery("select s.id, s.dataSolicitacao from SolicitacaoDieta s where s.aluno.id = :id)");
q.setParameter("id", aluno.getId());
List<SolicitacaoDieta> solicitacoes = new ArrayList<SolicitacaoDieta>();
Collection<Object[]> resultado = q.getResultList();
for (Object[] o : resultado)
{
SolicitacaoDieta s = new SolicitacaoDieta((Integer) o[0], (Calendar) o[1]);
solicitacoes.add(s);
}
return solicitacoes;
}
}
|
Markdown | UTF-8 | 417 | 2.953125 | 3 | [] | no_license | # 🧭 Elegant scalable percentage based Compass drawn using relative and real screen values
## About
Elegant Compass View that uses percentage instead of fixed values to draw components to have
similar scales in both portrait and landscape orientations.
| Portrait | Landscape |
| ----------|-----------|
| <img src="./screenshots/compass_portrait.png"/> | <img src="./screenshots/compass_landscape.png"/> | |
PHP | UTF-8 | 8,286 | 2.546875 | 3 | [] | no_license | <?php
/**
* This is the model class for table "orders".
*
* The followings are the available columns in table 'orders':
* @property integer $id
* @property string $order_id
* @property integer $branch
* @property double $distcount
* @property double $price
* @property integer $status
* @property integer $author
* @property string $create_date
* @property string $d_update
*
* The followings are the available model relations:
* @property Listorder[] $listorders
*/
class Orders extends CActiveRecord {
/**
* @return string the associated database table name
*/
public function tableName() {
return 'orders';
}
/**
* @return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('branch, status, author', 'numerical', 'integerOnly' => true),
array('distcount, price', 'numerical'),
array('order_id', 'length', 'max' => 10),
array('create_date, d_update', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, order_id, branch, distcount, price, status, author, create_date, d_update', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'listorders' => array(self::HAS_MANY, 'Listorder', 'order_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'order_id' => 'รหัสรายการ',
'branch' => 'รหัสสาขา',
'distcount' => 'ส่วนลด',
'price' => 'ราคารวม',
'status' => 'สถานะสั่งซื่อ 0 = ยังไม่ได้ของ,1 = ปลายทางส่งของ,2 = ต้นทางรับของ',
'author' => 'ผู้สั่งของ',
'create_date' => 'วันที่สั่งของ',
'd_update' => 'D Update',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search() {
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('order_id', $this->order_id, true);
$criteria->compare('branch', $this->branch);
$criteria->compare('distcount', $this->distcount);
$criteria->compare('price', $this->price);
$criteria->compare('status', $this->status);
$criteria->compare('author', $this->author);
$criteria->compare('create_date', $this->create_date, true);
$criteria->compare('d_update', $this->d_update, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return Orders the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
function autoId($table, $value, $number) {
$rs = Yii::app()->db->createCommand("Select Max($value)+1 as MaxID from $table")->queryRow(); //เลือกเอาค่า id ที่มากที่สุดในฐานข้อมูลและบวก 1 เข้าไปด้วยเลย
$new_id = $rs['MaxID'];
if ($new_id == '') { // ถ้าได้เป็นค่าว่าง หรือ null ก็แสดงว่ายังไม่มีข้อมูลในฐานข้อมูล
$std_id = sprintf("%0" . $number . "d", 1); //ถ้าไม่ใช่ค่าว่าง
} else {
$std_id = sprintf("%0" . $number . "d", $new_id); //ถ้าไม่ใช่ค่าว่าง
}
return $std_id;
}
function Getlistorder($order_id = null, $branch = null) {
$sql = "SELECT l.id,l.product_id,l.number,
l.distcountpercent,l.distcountprice,pricetotal,
p.product_price,p.costs,c.unit,p.product_name,p.product_nameclinic,u.unit AS unitname
FROM listorder l INNER JOIN clinic_stockproduct c ON l.product_id = c.product_id
INNER JOIN center_stockproduct p ON c.product_id = p.product_id
LEFT JOIN unit u ON c.unit = u.id
WHERE l.order_id = '$order_id' AND c.branch = '$branch' ";
return Yii::app()->db->createCommand($sql)->queryAll();
}
function GetlistorderSum($order_id = null) {
$sql = "SELECT l.product_id,s.product_name,u.unit AS unitname,SUM(l.number) AS number
FROM orders o INNER JOIN listorder l ON o.order_id = l.order_id
INNER JOIN center_stockproduct s ON l.product_id = s.product_id
LEFT JOIN unit u ON s.unit = u.id
WHERE o.order_id = '$order_id'
GROUP BY l.product_id ";
return Yii::app()->db->createCommand($sql)->queryAll();
}
function GetorderInBranch($branch) {
$sql = "SELECT o.*,SUM(l.number) AS total,SUM(l.pricetotal) AS pricetotal
FROM orders o INNER JOIN listorder l ON o.order_id = l.order_id
WHERE o.branch = '$branch'
GROUP BY o.order_id ";
return Yii::app()->db->createCommand($sql)->queryAll();
}
function SearchOrder($datestart = null, $dateend = null, $status = null, $branch = null, $order_id = null) {
if ($order_id != '') {
$WAREORDER = "o.order_id = '$order_id'";
} else {
$WAREORDER = " 1=1";
}
if ($status != '') {
$WARESTATUS = " AND o.status = '$status' ";
} else {
$WARESTATUS = "";
}
if ($branch == "99") {
$wherebranch = "";
} else {
$wherebranch = " AND o.branch = '$branch' ";
}
$sql = "SELECT o.*,
SUM(l.number) AS total,
SUM(l.pricetotal) AS pricetotal,
e.name,
e.lname,
b.branchname
FROM orders o INNER JOIN listorder l ON o.order_id = l.order_id
LEFT JOIN employee e ON o.author = e.id
LEFT JOIN branch b ON o.branch = b.id
WHERE o.create_date BETWEEN '$datestart' AND '$dateend' AND $WAREORDER $wherebranch $WARESTATUS
GROUP BY o.order_id ";
return Yii::app()->db->createCommand($sql)->queryAll();
}
function SetstatusOrder($status = null) {
if ($status == '0') {
$statusVal = "รอยืนยัน";
} else if ($status == '1') {
$statusVal = "อยู่ระหว่างการจัดส่ง";
} else if ($status == '2') {
$statusVal = "จัดส่งสินค้าแล้ว";
} else if ($status == '3') {
$statusVal = "สินค้าถึงผู้รับ";
}
return $statusVal;
}
}
|
Python | UTF-8 | 3,440 | 3.515625 | 4 | [
"MIT"
] | permissive | import sys
def main():
game_start = int(input("Bem-vindo ao jogo do NIM!\nEscolha:\n\n1 - para jogar uma partida isolada\n2 - para jogar um campeonato\n"))
if game_start == 1:
print('Você escolheu um jogo isolado')
partida()
elif game_start == 2:
print('Voê selecionou um Campeonato!!')
campeonato()
else:
print('Digite a resposta corretamente')
main()
ponto_usuario =0
ponto_computador =0
def partida():
n = int(input("Escolha o número de peças inicais: "))
m = int(input('Escolha o número maximo de peças a ser retirada por partida: '))
if n and m < 0:
print('Insira valores maiores que 0')
partida()
else:
start(n, m)
def start(n, m):
if n % (m + 1) != 0:
print("Vou começar")
ordem1(n,m)
else:
print('Você começa')
ordem2(n,m)
def ordem1(n,m):
while n>0:
pc_ranger=computador_escolhe_jogada(n,m)
n=n-pc_ranger
if n==0:
z=1
print('Computador Ganhou')
return z
if n >0:
m1=usuario_escolhe_jogada(n,m)
n=n-m1
if n==0:
z=0
print('Jogador ganhou!!')
return z
def ordem2(n,m):
while n>0:
m1= usuario_escolhe_jogada(n, m)
n=n-m1
if n >0:
pc_ranger= computador_escolhe_jogada(n, m)
n=n-pc_ranger
if n==0:
z=1
print('Computador Ganhou')
return z
else:
print('Usuario Ganhou')
z=0
return z
def campeonato():
global ponto_usuario
global ponto_computador
camp= ponto_usuario + ponto_computador
while camp <3:
z=partida()
if z==0:
ponto_usuario +=1
print('Placar: Você %s X %s Computador'%(ponto_usuario,ponto_computador))
else:
ponto_computador +=1
print('Placar: Você %s X %s Computador'%(ponto_usuario,ponto_computador))
camp = ponto_usuario + ponto_computador
if ponto_computador > ponto_usuario:
print('Computador ganhou o Campeonato')
else:
print('Usuario Ganhou o Campeonato')
def computador_escolhe_jogada(n, m):
for pc_range in reversed(range(1, m + 1)):
if m>=n:
pc_range=n
n = n-pc_range
print('O Computador retirou %d peça(s)' % pc_range)
return pc_range
elif n%(m+1) >0:
pc_range = n%(m+1)
n = n - pc_range
print('O Computador retirou %d peça(s)' % pc_range)
print("Sua vez")
return pc_range
else:
n = n - pc_range
if n > 0:
print('O Computador retirou %d peça(s)' % pc_range)
print("Sua vez")
return pc_range
else:
computador_escolhe_jogada(n,m)
def usuario_escolhe_jogada(n: object, m: object) -> object:
m1 = int(input("Escolha a quantida de peças a ser retirada"))
while m1 <= 0 or m1 > m or m1 > n:
print("Jogada invalida")
m1 = int(input("Escolha a quantida de peças a ser retirada"))
n = n - m1
if n == 0:
print('Você retirou %d peça(s)' % m1)
return m1
else:
print('Você retirou %d peça(s)' % m1)
return m1
main() |
Java | UTF-8 | 2,729 | 2.828125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | package io.github.mdsimmo.bomberman.messaging;
import io.github.mdsimmo.bomberman.PlayerRep;
import io.github.mdsimmo.bomberman.commands.Cmd.Permission;
import java.util.List;
import java.util.Map;
import org.bukkit.command.CommandSender;
public abstract class Chat {
public static void sendMessage( Message message ) {
if ( message.isBlank() )
return;
messageRaw( getMessage( Text.MESSAGE_FORMAT, message.getSender() ).put( "message",
message ) );
}
public static void sendMap( Map<Message, Message> points ) {
for ( Map.Entry<Message, Message> point : points.entrySet() ) {
if ( point.getValue().isBlank() || point.getKey().isBlank() )
continue;
messageRaw( getMessage( Text.MAP_FORMAT, point.getKey().getSender() )
.put( "title", point.getKey() )
.put( "value", point.getValue() ) );
}
}
public static void sendList( List<Message> list ) {
for ( Message line : list ) {
if ( line.isBlank() )
continue;
messageRaw( getMessage( Text.LIST_FORMAT, line.getSender() ).put( "value",
line ) );
}
}
public static void messageRaw( Message message ) {
CommandSender sender = message.getSender();
if ( Permission.OBSERVER.isAllowedBy( sender ) )
sender.sendMessage( message.toString() );
}
public static void sendHeading( Message type , Message title ) {
messageRaw( getMessage( Text.HEADING_FORMAT, title.getSender() ).put( "type", type )
.put( "title", title ) );
}
/**
* Converts a phrase into being a Message which is in the player's language
* @param phrase the phrase to convert
* @param rep the {@link PlayerRep} receiving the message
* @return The created message
*/
public static Message getMessage( Phrase phrase, PlayerRep rep ) {
return getMessage( phrase, rep.getLanguage(), rep.getPlayer() );
}
/**
* Converts a phrase into the given {@link Language}
* @param phrase the phrase to convert
* @param lang the {@link Language} to convert into. Should be the language of {@code sender}.
* null for the default English.
* @param sender the {@link CommandSender} receiving to message
* @return the created message
*/
public static Message getMessage( Phrase phrase, Language lang, CommandSender sender ) {
if ( lang == null )
lang = Language.getLanguage( "english" );
return new Message( sender, lang.translate( phrase ) );
}
/**
* Converts a phrase into the language spoken by {@code sender}
* @param phrase the phrase to convert
* @param sender the {@link CommandSender} receiving to message
* @return the created message
*/
public static Message getMessage( Phrase phrase, CommandSender sender ) {
return getMessage( phrase, PlayerRep.getLanguage( sender ), sender );
}
} |
Java | UTF-8 | 7,289 | 1.945313 | 2 | [] | no_license | package program.sw8.sw8program;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
public class UserFragment extends Fragment {
private final int ContextUserImageRemove = 1;
private final int ContextUserImageChange = 2;
private final int SelectImage = 1;
private User Profile;
private ImageView UserImage;
ExpandableListPersonal listPersonalAdapter;
ExpandableListView explistPersonal;
List<String> listPersonalHeader;
HashMap<String, List<String[]>> listPersonalChild;
ExpandableListPreferences listPreferencesAdapter;
ExpandableListView explistPreferences;
List<String> listPreferencesHeader;
HashMap<String, List<String[]>> listPreferencesChild;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_user, container, false);
UserImage = (ImageView) rootView.findViewById(R.id.user_image);
TextView userName = (TextView) rootView.findViewById(R.id.user_name);
registerForContextMenu(UserImage);
//TODO: Remove testdata
Profile = new Account("CarstenHolstBaby", "123456", "@", "settings", "preferences");
if (Profile.hasImage()) {
UserImage.setImageResource(Profile.getImageId());
}
SharedPreferences session = getActivity().getApplicationContext().getSharedPreferences(getString(R.string.app_name), 0);
userName.setText(session.getString("alias", Profile.getAlias()));
// setting up data and adapter for Personal Information expandable list
explistPersonal = (ExpandableListView) rootView.findViewById(R.id.explist_personal);
preparePersonalData();
listPersonalAdapter = new ExpandableListPersonal(getActivity(), listPersonalHeader, listPersonalChild);
explistPersonal.setAdapter(listPersonalAdapter);
// setting up data and adapter for Preferences expandable list
explistPreferences = (ExpandableListView) rootView.findViewById(R.id.explist_preferences);
preparePreferencesData();
listPreferencesAdapter = new ExpandableListPreferences(getActivity(), listPreferencesHeader, listPreferencesChild);
explistPreferences.setAdapter(listPreferencesAdapter);
return rootView;
}
/*
* Preparing the list data
*/
private void preparePersonalData() {
listPersonalHeader = new ArrayList<String>();
listPersonalChild = new HashMap<String, List<String[]>>();
// Adding group data
listPersonalHeader.add("Personlig Information");
String[] name = new String[]{Profile.getUsername(),"name"};
String[] description = new String[]{"The Godfather","description"};
// Adding child data
List<String[]> PersonalInformation = new ArrayList<String[]>();
PersonalInformation.add(0, name);
PersonalInformation.add(1, description);
listPersonalChild.put(listPersonalHeader.get(0), PersonalInformation); // Header, Child data
}
private void preparePreferencesData() {
listPreferencesHeader = new ArrayList<String>();
listPreferencesChild = new HashMap<String, List<String []>>();
// Adding group data
listPreferencesHeader.add("Præferencer");
String[] price = new String[]{"50","price"};
String[] magic = new String[]{"50","magic"};
// Adding child data
List<String[]> preferences = new ArrayList<String[]>();
preferences.add(price);
preferences.add(magic);
listPreferencesChild.put(listPreferencesHeader.get(0), preferences); // Header, Child data
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
//Create menu entries to delete or change profile image
menu.add(Menu.NONE, ContextUserImageChange, Menu.NONE, getString(R.string.user_image_change));
menu.add(Menu.NONE, ContextUserImageRemove, Menu.NONE, getString(R.string.user_image_remove));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
//Figure what menu entry was pressed and handle it
switch (item.getItemId()) {
case ContextUserImageChange:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, getString(R.string.user_image_choose)), SelectImage);
return true;
case ContextUserImageRemove:
Profile.setUserImageId(0);
UserImage.setImageResource(R.drawable.profile);
return true;
default:
return false;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
//Perform actions based on result from whatever activity returned
switch (requestCode) {
case SelectImage:
//If we selected an image from gallery, get the) URI and do some string manipulation because fuck KitKat.
Uri uri = data.getData();
//TODO: Target height and width is just random numbers. Figure out something proper.
UserImage.setImageBitmap(getResizedBitmap(10, 10, ImageFilePath.getPath(getActivity(), uri)));
break;
}
}
public Bitmap getResizedBitmap(int targetW, int targetH, String imagePath) {
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
//inJustDecodeBounds = true <-- will not load the bitmap into memory
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = 5;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, bmOptions);
return(bitmap);
}
} |
Python | UTF-8 | 95 | 2.921875 | 3 | [] | no_license | R=[]
def lista_sufixos(R):
return R.split()
i=0
while i<len(R):
print(R[i])
i+=1 |
Swift | UTF-8 | 2,061 | 3.046875 | 3 | [] | no_license | import CoreData
import SwiftUI
public struct Create: View {
@State private var name: String = ""
@State private var req = 3
@State private var opt = 1
@State private var step = 3
@State var showImagePicker: Bool = false
@State var image: UIImage?
public var body: some View {
HStack(alignment: .top){
VStack{
VStack {
Image(name: "food-default.jpg")
.resizable()
.frame(width: 200.0, height: 165.0)
}
HStack {
Text("Menu name: ")
TextField(" Tom yum kung", text: $name)
.border(Color.init(red: 0.7, green: 0.7, blue: 0.7))
.frame(width: 200, alignment: .center)
}
VStack {
Stepper("Recipe Require (\(req))", value: $req, in: 3...15)
Stepper("Recipe Optional (\(opt))", value: $opt, in: 1...15)
Stepper("Step Cook (\(step))", value: $step, in: 3...15)
}
.frame(width: 250, alignment: .center)
NavigationLink(destination: RecipeCreate(
name: name,
req: req,
opt: opt,
step: step,
recipe_req: Array(repeating: "", count: req),
recipe_opt: opt > 0 ? Array(repeating: "", count: opt) : []
)) {
Text("Next")
.foregroundColor(.white)
.bold()
.frame(width: 250.0, height: 50.0, alignment: .center)
.background(name != "" ? Color.green : Color.gray)
.cornerRadius(25.0)
}
.allowsHitTesting(name != "" ? true : false)
}
}
.navigationTitle("Create " + (name == "" ? "Menu" : name))
}
}
|
C++ | UTF-8 | 3,747 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<to;x++)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
class BichromePainting {
public:
string isThatPossible(vector <string> S, int K) {
int N=S.size();
int x,y,ty,tx;
bool up=true;
while(up) {
up=false;
FOR(y,N) FOR(x,N) if(y+K-1<N && x+K-1<N) {
int w=0,b=0;
FOR(ty,K) FOR(tx,K) {
if(S[ty+y][tx+x]=='W') w++;
if(S[ty+y][tx+x]=='B') b++;
}
if(w&&b) continue;
if(w==0 && b==0) continue;
FOR(ty,K) FOR(tx,K) S[ty+y][tx+x]='?';
up=true;
}
}
FOR(y,N) FOR(x,N) if(S[y][x]!='?') return "Impossible";
return "Possible";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"BBBW",
"BWWW",
"BWWW",
"WWWW"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 3; string Arg2 = "Possible"; verify_case(0, Arg2, isThatPossible(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"WWB","WBB","BBW"
}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; string Arg2 = "Impossible"; verify_case(1, Arg2, isThatPossible(Arg0, Arg1)); }
void test_case_12() { string Arr0[] = {"BW",
"WB"}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; string Arg2 = "Impossible"; verify_case(1, Arg2, isThatPossible(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"BWBWBB",
"WBWBBB",
"BWBWBB",
"WBWBBB",
"BBBBBB",
"BBBBBB"}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; string Arg2 = "Possible"; verify_case(2, Arg2, isThatPossible(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {"BWBWBB",
"WBWBWB",
"BWBWBB",
"WBWBWB",
"BWBWBB",
"BBBBBB"}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; string Arg2 = "Impossible"; verify_case(3, Arg2, isThatPossible(Arg0, Arg1)); }
void test_case_4() { string Arr0[] = {"BWBWBB",
"WBWBWB",
"BWBWBB",
"WBWBWB",
"BWBWBB",
"BBBBBB"}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; string Arg2 = "Possible"; verify_case(4, Arg2, isThatPossible(Arg0, Arg1)); }
void test_case_5() { string Arr0[] = {"BB",
"BB"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; string Arg2 = "Possible"; verify_case(5, Arg2, isThatPossible(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main(int argc,char** argv) {
BichromePainting ___test;
___test.run_test((argc==1)?-1:atoi(argv[1]));
}
|
C++ | UTF-8 | 419 | 2.921875 | 3 | [] | no_license | #ifndef ELEMENTA_H
#define ELEMENTA_H
#include "ielement.h"
#include <string>
using std::string;
class ElementA : public IElement
{
public:
ElementA(const string &name) : m_name(name) {}
virtual void accept(IVisitor *visitor);
inline string name() { return this->m_name; }
virtual void setName(const std::string &name) { this->m_name = name; }
private:
string m_name;
};
#endif // ELEMENTA_H
|
Java | UTF-8 | 5,759 | 2.4375 | 2 | [
"MIT"
] | permissive | package cn.marwin.crawler;
import cn.marwin.classifier.MyClassifier;
import cn.marwin.entity.Weibo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.marwin.entity.Comment;
import cn.marwin.entity.Hot;
import redis.clients.jedis.Jedis;
import cn.marwin.util.RedisUtil;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
public class CrawlTask extends TimerTask {
public static final int HOT_LIST_SIZE = 10; // 从热搜榜上获取的热搜数量
public static final int WB_LIST_SIZE = 1; // 每条热搜获取的weibo数量
public static final int CM_LIST_SIZE = 5; // 每条weibo获取的评论页数,一页最多20条评论
public static final int KEY_EXPIRE_TIME = 60 * 60; // redis里key的过期时间,单位为秒
@Override
public void run() {
try {
long start = System.currentTimeMillis();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("### 开始爬取微博 " + formatter.format(LocalDateTime.now()) + " ###");
crawl();
long end = System.currentTimeMillis();
System.out.println("### 爬取微博结束,耗时:" + ((end - start) / 1000.0) + "s ###");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void crawl() throws InterruptedException{
long timestamp = System.currentTimeMillis();
Jedis jedis = RedisUtil.getJedis();
// 从热搜榜的请求里获取xhr的链接
String url = "https://m.weibo.cn/api/container/getIndex?containerid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot&title=%E5%BE%AE%E5%8D%9A%E7%83%AD%E6%90%9C";
List<Hot> hotList = WeiboParser.getHotList(url, HOT_LIST_SIZE);
int i = 1;
for (Hot hot: hotList) {
String hot_key = timestamp + ":hot:" + (i++); // timestamp:hot:{index}
insertHot(jedis, hot_key, hot);
List<Weibo> weiboList = WeiboParser.getWeiboList(hot, WB_LIST_SIZE);
// 汇总该热搜下所有weibo的评论情况
int allPosCount = 0;
int allNegCount = 0;
int j = 1;
for (Weibo weibo : weiboList) {
String wb_key = hot_key + ":wb:" + (j++); // timestamp:hot:{index}:wb:{index}
insertWeibo(jedis, wb_key, weibo);
List<Comment> commentList = WeiboParser.getCommentList(weibo, CM_LIST_SIZE);
String cm_key = wb_key + ":cm"; // timestamp:hot:{index}:wb:{index}:cm
// 统计该weibo下评论的情况
int posCount = 0;
int negCount = 0;
int otherCount = 0;
for (Comment comment: commentList) {
// 使用分类器评估评论的得分
double score = MyClassifier.getScore(comment.getText());
comment.setScore(score);
insertComment(jedis, cm_key, comment);
if (score > 0) {
posCount++;
allPosCount++;
} else if (score < 0) {
negCount++;
allNegCount++;
} else {
otherCount++;
}
}
jedis.expire(cm_key, KEY_EXPIRE_TIME);
// 追加设置weibo的加工信息
jedis.hsetnx(wb_key, "posCount", "" + posCount);
jedis.hsetnx(wb_key, "negCount", "" + negCount);
jedis.hsetnx(wb_key, "otherCount", "" + otherCount);
//为了防止爬取过快导致403或触发反爬,每个微博爬完暂停3s
Thread.sleep(3000);
}
// 追加设置hot的加工信息
double status = (allPosCount + allNegCount) == 0 ? 0 : 1.0 * (allPosCount - allNegCount) / (allPosCount + allNegCount);
jedis.hsetnx(hot_key, "status", "" + status);
}
jedis.lpush("timestamp", "" + timestamp); // 逆序存储,最新的时间在最左侧
RedisUtil.returnResource(jedis);
}
private void insertHot(Jedis jedis, String key, Hot hot) {
Map<String, String> hot_value = new HashMap<>();
hot_value.put("desc", hot.getDesc());
hot_value.put("scheme", hot.getScheme());
jedis.hmset(key, hot_value);
jedis.expire(key, KEY_EXPIRE_TIME);
System.out.println("Hot Insert: " + hot.getDesc());
}
private void insertWeibo(Jedis jedis, String key, Weibo weibo) {
Map<String, String> wb_value = new HashMap<>();
wb_value.put("id", weibo.getId());
wb_value.put("url", weibo.getUrl());
wb_value.put("user", weibo.getUser());
wb_value.put("pic", weibo.getPic());
wb_value.put("time", weibo.getTime());
wb_value.put("content", weibo.getContent());
jedis.hmset(key, wb_value);
jedis.expire(key, KEY_EXPIRE_TIME);
}
private void insertComment(Jedis jedis, String key, Comment comment) {
// 序列化为Json存储
ObjectMapper mapper = new ObjectMapper();
String cm_json = null;
try {
cm_json = mapper.writeValueAsString(comment);
jedis.rpush(key, cm_json);
} catch (JsonProcessingException e) {
System.out.println("Comment序列化失败!");
e.printStackTrace();
}
}
}
|
Java | UTF-8 | 6,191 | 3.875 | 4 | [] | no_license | package com.crownp.morethanjavacoding.Datastruct.SwardOffer.code02_String;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @Description TODO
* @Author qgp
* @Date 2019/12/5 9:56
**/
public class SwardOffer_String {
/**
* 【替换空格】
* 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*/
public String replaceSpace(StringBuffer str) {
StringBuffer out = new StringBuffer();
for (int i = 0; i < str.toString().length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
out.append("%20");
} else {
out.append(c);
}
}
return out.toString();
}
/**
* 【正则表达式匹配】 19题
* 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。
* 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
* 【思路】 递归解答
* 1.模式中第二个字符不是*
* 如果字符串中第一个字符与模式中第一个字符相匹配,那么两者都后移1个字符
* 如果不匹配,返回false
* 2.模式中第二个字符是*
* (1)如果字符串中第一个字符与模式的第一个不匹配,那么模式向后移2个字符。 相当于忽略掉了 a* 代表0个
* (2)如果匹配,可以有三种情况
* - 字符串不移,模式移动2个字符。像 ab 与 a*ab 的情况
* - 字符串移动1个字符,模式移动2个字符。像 abc 与 a*bc
* - 字符串移动1个字符,模式不懂。因为*可以匹配多个前面的字符,像 aaabc与a*bc
*/
public boolean match(char[] str, char[] pattern) {
if (str == null || pattern == null) {
return false;
}
int strIndex = 0;
int patternIndex = 0;
return matchCore(str, strIndex, pattern, patternIndex);
}
public boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {
//有效性检验:str到尾,pattern到尾,匹配成功
if (strIndex == str.length && patternIndex == pattern.length) {
return true;
}
//pattern先到尾,匹配失败
if (strIndex != str.length && patternIndex == pattern.length) {
return false;
}
//模式第2个是*,且字符串第1个跟模式第1个匹配,分3种匹配模式;如不匹配,模式后移2位
if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') { // 即 patternIndex != pattern.length
if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) {
return matchCore(str, strIndex, pattern, patternIndex + 2)//模式后移2,视为x*匹配0个字符
|| matchCore(str, strIndex + 1, pattern, patternIndex + 2)//视为模式匹配1个字符
|| matchCore(str, strIndex + 1, pattern, patternIndex);//*匹配1个,再匹配str中的下一个
} else {
return matchCore(str, strIndex, pattern, patternIndex + 2);
}
}
//模式第2个不是*,且字符串第1个跟模式第1个匹配,则都后移1位,否则直接返回false
if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) {
return matchCore(str, strIndex + 1, pattern, patternIndex + 1);
}
return false;
}
/**
* 【字符流中第一个不重复的字符】 50题
* 请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。
* 当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
* 如果当前字符流没有存在出现一次的字符,返回#字符。
* 【思路】
* 利用map的键值对的特性,将 char 作为 key,出现的次数为 value。而 LinkedHashMap是有序的
*/
//Insert one char from stringstream
private Map<Character, Integer> linkedHashMap = new LinkedHashMap();
public void Insert(char ch) {
if (linkedHashMap.containsKey(ch)){
linkedHashMap.put(ch,linkedHashMap.get(ch) + 1);
} else {
linkedHashMap.put(ch,1);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
for (Map.Entry<Character,Integer> set : linkedHashMap.entrySet()){
if (set.getValue() == 1){
return set.getKey();
}
}
return '#';
}
/**
* 【表示数值的字符串】
* 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。
* 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
*/
public boolean isNumeric(char[] str) {
return false;
}
public boolean isNumeric2(char[] str) {
//正则表达式解答
String string = String.valueOf(str);
return string.matches("[\\+\\-]?\\d*(\\.\\d+)?([eE][\\+\\-]?\\d+)?");
/*
正则说明:
[\\+\\-]? ->正或负符号出现与否
\\d* ->整数部分是否出现,如 -.34 或 +3.34 均符合
(\\.\\d+)? ->如果出现小数点,那么小数点后面必须有数字;否则一起不出现
([eE][\\+\\-]?\\d+)? ->如果存在指数部分,那么e或E肯定出现,+或-可以不出现,紧接着必须跟着整数,或者整个部分都不出现。
*/
}
}
|
JavaScript | UTF-8 | 3,227 | 2.546875 | 3 | [] | no_license | $(document).ready(function(){
$(".test1").click(function(){
$(this).hide();
});
$("#test1").click(function(){
$(this).hide();
});
$("#test2").click(function(){
alert("You clicked!");
});
$("#test3").dblclick(function(){
alert("You double clicked!");
});
$("#test4").mouseenter(function(){
alert("You entered!");
});
$("#test5").mouseleave(function(){
alert("You left!");
});
});
$(document).ready(function(){
$("#hide").click(function(){
$("#hs").hide();
});
$("#show").click(function(){
$("#hs").show();
});
});
$(document).ready(function(){
$("#fade").click(function(){
$("#div1").fadeIn(3000);
$("#div1").fadeOut(3000);
});
});
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
$("#fup").click(function(){
$("#panel").slideUp("slow");
});
});
$(document).ready(function(){
$("#animate").click(function(){
let div = $("#anime");
// div.animate({height: '300px', opacity: '0.4'}, "slow");
// div.animate({width: '300px', opacity: '0.8'}, "slow");
// div.animate({height: '100px', opacity: '0.4'}, "slow");
// div.animate({width: '100px', opacity: '0.8'}, "slow");
div.animate({height: '300px', opacity: '0.4'}, 1000);
div.animate({width: '300px', opacity: '0.8'}, 600);
div.animate({height: '100px', opacity: '0.4'}, 300);
div.animate({width: '100px', opacity: '0.8'}, 300);
});
});
$(document).ready(function(){
$("#cb").click(function(){
$("#cb-text").fadeOut("slow", function(){
alert("The paragraph is now hidden");
});
});
});
$(document).ready(function(){
$("#ch").click(function(){
$("#ch").css("color", "red")
.slideUp(1000)
.slideDown(1000);
});
});
$(document).ready(function(){
$("#get-content").click(function(){
let name = $("#content").val();
if(name === ""){
alert("Field is empty");
}else{
$("#namelist").append("<li>"+name+"</li>");
// $("#content").val("");
$("#content").val("");
}
});
});
$(document).ready(function(){
$("#txt-load").click(function(){
$("#div2").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
if(statusTxt === "success")
alert("External content loaded successfully!");
if(statusTxt === "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
});
});
});
$(document).ready(function(){
$("#get").click(function(){
console.log("Hello");
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
$(document).ready(function(){
$("#post").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
}); |
Markdown | UTF-8 | 8,166 | 2.59375 | 3 | [] | no_license | # 使用 TypeScript 开发 Vue 项目
## 19.1 环境说明
### Vue 项目中启用 TypeScript 支持
**使用 Vue CLI 脚手架工具创建 Vue 项目:**
对于全新项目,可以使用 Vue CLI 脚手架工具创建 Vue 项目

**添加 Vue 官方配置的 TS 适配插件:**
对于已有项目,可以添加 Vue 官方配置的 TypeScript 适配插件
使用 `@vue/cli` 安装 TypeScript 插件:
```shell
vue add @vue/typescript
```
### 关于编辑器
要使用 TypeScript 开发 Vue 应用程序,强烈建议使用 Visual Studio Code,它为 TypeScript 提供了极好的“开箱即用”支持。如果你正在使用 单文件组件 SFC,可以安装提供 SFC 支持以及其他更多实用功能的 Vetur 插件
WebStorm 同样为 TypeScript 和 Vue 提供了“开箱即用”的支持
## 19.2 TypeScript 相关配置介绍
(1)安装了 TypeScript 相关的依赖项
dependencies 依赖:
| 依赖项 | 说明 |
| :--------------------- | ----------------------------------------- |
| vue-class-component | 提供使用 Class 语法写 Vue 组件 |
| vue-property-decorator | 在 Class 语法基础之上提供了一些辅助装饰器 |
devDependencies 依赖:
| 依赖项 | 说明 |
| -------------------------------- | ------------------------------------------------------------ |
| @typescript-eslint/eslint-plugin | 使用 ESLint 校验 TypeScript 代码 |
| @typescript-eslint/parser | 将 TypeScript 转换为 AST 供 ESLint 校验使用 |
| @vue/cli-plugin-typescript | 使用 TypeScript + ts-loader + fork-ts-checker-webpack-plugin 进行更快的类型检查 |
| @vue/eslint-config-typescript | 兼容 ESLint 的 typeScript 的校验规则 |
| typescript | TypeScript 编译器,提供类型校验和转换 JavaScript 功能 |
(2)TypeScript 配置文件 `tsconfig.json`
```json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
```
(3)shims-vue.d.ts 文件的作用
```typescript
// import xxx from 'xxx.vue'
// ts 默认无法识别 .vue 结尾的模块
// 主要用于 TypeScript 识别 .vue 文件模块
// TypeScript 默认不支持导入 .vue 模块,这个文件告诉 TypeScript 导入 .vue 文件模块都按
// VueConstructor<Vue> 类型识别处理
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
```
(4)shims-tsx.d.ts 文件的作用
```typescript
// 为 jsx 组件莫模板补充类型声明
import Vue, { VNode } from 'vue'
declare global {
namespace JSX {
// tslint:disable no-empty-interface
interface Element extends VNode {}
// tslint:disable no-empty-interface
interface ElementClass extends Vue {}
interface IntrinsicElements {
[elem: string]: any
}
}
}
```
(5)TypeScript 模块都使用 `.ts` 后缀
## 19.3 使用 OptionsAPI 定义 Vue 组件
以往的写法:编译器类型提示不够严谨,且没有 TypeScript 编译期间的类型验证
```typescript
<script>
export default{
data () {
return { a : 1 }
},
methods: {
test () {
console.log(this.a)
}
}
}
</script>
```
**使用 OptionsAPI:**
- 组件仍然可以使用以前的方式定义(导出组件选项对象,或者使用Vue.extend())
- 但是当我们导出一个普通的对象,此时 TypeScript 无法推断出对应的类型
- 至于 VSCode 可以推断出类型成员的原因是因为我们使用了 Vue 插件
- 这个插件明确知道我们这里导出一个 Vue 对象
- 所以我们必须使用 `Vue.extend()` 方法确保 TypeScript 能够有正常的类型推断
```typescript
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
data () {
return { a : 1 }
},
methods: {
test () {
console.log(this.a)
}
}
})
</script>
```
## 19.4 使用 ClassAPIs 定义 Vue 组件
**使用 Class APIs:**
在 TypeScript 下,Vue 的组件可以使用一个继承自 Vue 类型的子类表示,这种类型需要使用 Component 装饰器去修饰
装饰器函数接收的参数就是以前的组件选项对象(data、props、methods之类)
```typescript
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class App extends Vue {
a = 1
test () {
console.log(this.a)
}
}
</script>
```
类的语法只是改变了一种类的书写方式,其内部做了一层转换,会把类里面的实例成员放到了 Vue 实例的 data 内部,方法作为了类的实例成员方法
需要注意的是,由于生命周期函数的使用与方法使用类似,会优先把其当做生命周期函数对待
如果我们注册子组件只需要`components: {OtherComponent}`
使用`props` 数据:需要先用 `Vue.extend`创建一个组件,里面再声明`props`得到一个返回值,再去定义一个类来继承它
```typescript
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
// Define the props by using Vue's canonical way.
const GreetingProps = Vue.extend({
props: {
name: String
}
})
// Use defined props by extending GreetingProps.
@Component
export default class Greeting extends GreetingProps {
get message(): string {
// this.name will be typed
return 'Hello, ' + this.name
}
}
</script>
```
更多详细用法可以参考 [class-component.vuejs.org](https://class-component.vuejs.org/)
## 19.5 Decorator 装饰器语法
在使用类的语法定义组件的时候,我们发现类的前面有 `@Component` 这行代码,它是干什么的呢?
这其实是一种装饰器语法,装饰器是 ES 草案中的一种新特性,不过这个草案最近可能发生重大调整,所以不建议在生产环境中使用
类的装饰器:
```js
function testable (target) {
target.isTestable = true
}
@testable
class MyTestableClass {
// ...
}
console.log(MyTestableClass.isTestable) // true
```
当我们定义好类并使用`@ + function`以后,回去自动调用这个 function,把这个类传递给这个函数。此时 target 就是 MyTestableClass,内部给 target 添加了一个 isTestable 的成员,因此 MyTestableClass 类就拥有了静态属性
装饰器的作用实际上就是去扩展类的属性里面的功能,具体可以参考 [ECMAScript 6入门](https://es6.ruanyifeng.com/#docs/decorator)
## 19.6 使用 VuePropertyDecorator 创建 Vue 组件
在前面我们使用官方提供的 VueClassComponent,它的一些功能写法可能不太好,比如 props,写起来比普通写法更麻烦
所以社区中出现 [VuePropertyDecorator](https://github.com/kaorun343/vue-property-decorator),它利用装饰器的特点做了一些简化的写法。在 VueClassComponent 基础上做了一些扩展,提供了一些快捷的装饰器
## 19.7 使用建议
个人建议:No Class APIs,只用 Options APIs
> Class 语法仅仅是一种写法而已,最终还是要转换为普通的组件数据结构
>
> 装饰器语法还没有正式定稿发布,建议了解即可,正式发布以后再选择使用也可以
使用 Options APIs 最好是使用 `export default Vue.extend({ ... })` 而不是 `export default { ... }`
|
Java | UTF-8 | 882 | 2.953125 | 3 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mygdx.game;
import com.badlogic.gdx.graphics.Texture;
/**
*
* @author Shezar Khan, Anthony Peragine, Jet Keonakhone
* Grass is a subclass of Terrain
*/
public class Grass extends Terrain {
// import image
private Texture img;
//used to identify the grass from other terrains
private int id = 1;
public Grass(int width, int height){
// width and height remain same
super(width, height);
// texture only exclusion
img = new Texture("grass.png");
}
// return image
public Texture getImg(){
return this.img;
}
// return ID
public int getId(){
return id;
}
// dispose of heavy objects
public void dispose(){
img.dispose();
}
}
|
Python | UTF-8 | 4,790 | 2.765625 | 3 | [] | no_license | import socket
import os
import sys
import tqdm
from math import ceil
from threading import Thread
clients = []
# Thread to listen one particular client
class ClientListener(Thread):
def __init__(self, id: str, sock: socket.socket):
super().__init__(daemon=True)
self.sock = sock
self.id = id
self.buffer_size = 1024
self.separator = ",,,"
self.block = False
# clean up
def _close(self):
clients.remove(self.sock)
self.sock.close()
print(self.id + ' disconnected')
def run(self):
while True:
if self.block == True:
self._close()
break
self.block = True
#Get required information for further processing
request_info = self.sock.recv(self.buffer_size).decode()
request_info_list = str(request_info).split(self.separator)
#Check whether client want to send or recieve file
#Upload file on server
if request_info_list[0] == "send":
#Get the data about file
file_name, file_size = request_info_list[1:3]
file_name = os.path.basename(file_name)
file_size = int(file_size)
#Check whether name of the file should be changed
nameChanged = False
#Change file name if file with same name exists
while(os.path.isfile(file_name)):
nameChanged = True
name, ext = file_name.split(".")
if "_copy_" in name:
init_name , copy_ind = name.split("_copy_")
copy_ind = int(copy_ind)+1
name = init_name+"_copy_"+str(copy_ind)
else:
name = name + "_copy_1"
file_name = name + "." + ext
#Print info in server console
print("Client with id:",self.id," sends a file with the name " +file_name)
if nameChanged:
print("File name is adjusted becouse there are already file(s) with same initial name.")
self.sock.sendall(file_name.encode())
else:
self.sock.sendall("NO_CHANGE_NAME".encode())
#Download file
with open(file_name, "wb") as server_file:
#Client end connection when file is downloaded from server
while True:
bytes_read = self.sock.recv(self.buffer_size)
if not bytes_read:
break
server_file.write(bytes_read)
#Print info about end of transfering file in server console
print("Transfer of file from client with id:",self.id,"is complete.")
#Send file from server
elif request_info_list[0] == "recv":
#Get the data about file
file_name = request_info_list[1]
file_name = os.path.basename(file_name)
try:
file_size = os.path.getsize(file_name)
#Send size of the requested file
self.sock.send(f"{file_size}".encode())
#Print info in server console
print("Client with id:",self.id,"start download a file with the name " +file_name)
#Send file
with open(file_name, "rb") as client_file:
for i in range(ceil(file_size/self.buffer_size)):
bytes_read = client_file.read(self.buffer_size)
if not bytes_read:
break
self.sock.sendall(bytes_read)
print(f"Client with id: {self.id} downloaded the file: {file_name}")
except Exception as e:
print("Client with id:",self.id,"tryed to download file with name: ", file_name)
print("but there is no such file.")
def main():
#Create server socket
next_id = 1
server_port = int(sys.argv[1])
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', server_port))
sock.listen()
while True:
con, addr = sock.accept()
clients.append(con)
id = str(next_id)
next_id += 1
print(str(addr) + ' connected with id:' + id)
ClientListener(id, con).start()
if __name__ == "__main__":
main()
|
Python | UTF-8 | 1,047 | 3.234375 | 3 | [] | no_license | """Models for adopt app."""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
DEFAULT_IMAGE_URL = 'https://cdn.dribbble.com/users/2095589/screenshots/4166422/user_1.png'
def connect_db(app):
"""Connect this database to provided Flask app.
You should call this in your Flask app.
"""
db.app = app
db.init_app(app)
class Pet(db.Model):
__tablename__ = 'pets'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
name = db.Column(db.String(30), nullable=False)
species = db.Column(db.String(30), nullable=False)
photo_url = db.Column(db.String(250), nullable=False, default=DEFAULT_IMAGE_URL)
age = db.Column(db.String(30), nullable=False) #make a dropdown for this one
notes = db.Column(db.String(300), nullable=False, default='')
available = db.Column(db.Boolean(), nullable=False, default=True)
def __repr__(self):
"""Show info about the pet."""
p = self
return f"<Per {p.name} {p.species} {p.photo_url} {p.age} {p.notes} {p.available}>" |
C++ | UTF-8 | 1,116 | 3.484375 | 3 | [] | no_license | ///
/// @file operator[].cpp
/// @iverson (1564329410@qq.com)
/// @date 2016-03-03 21:05:47
///
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
class CharSz{
public:
CharSz(int);
~CharSz();
/*以成员函数的形式重载下标运算符*/
char & operator[](int);
int getLen();
private:
int _len;
char *_pstr;
};
CharSz::CharSz(int len)
:_len(len)
,_pstr(new char[_len + 1])
{
cout<<"CharSz(int)"<<endl;
}
CharSz::~CharSz(){
cout<<"~CharSz()"<<endl;
delete[] _pstr;
}
char & CharSz::operator [](int i){
/*用于返回空字符时,由于返回类型为char &,不能直接
* return '\0';
*/
static char szNull = '\0';
if(i>=0 && i<_len){
return _pstr[i];
}else{
cout<<"下标越界"<<endl;
return szNull;
}
}
int CharSz::getLen(){
return _len;
}
int main(void){
char *p = "how are you";
/*对象sz中申请的动态内存大小为n,可存放n-1个有效字符('\0'除外)*/
CharSz sz(strlen(p)+1);
for(int i=0; i<(strlen(p)+1); ++i){
sz[i] = p[i];
}
for(int j=0; j<sz.getLen(); j++){
cout<<sz[j]<<" ";
}
cout<<endl;
return 0;
}
|
PHP | UTF-8 | 3,477 | 3.234375 | 3 | [] | no_license | <?php
namespace Curly\Ast\Node;
use Curly\ContextInterface;
use Curly\Ast\Node;
use Curly\Ast\NodeInterface;
use Curly\Io\Stream\OutputStreamInterface;
/**
* The Conditional node will evaluate one or more expression nodes into a boolean result.
*
* @author Chris Harris <c.harris@hotmail.com>
* @version 1.0.0
* @since 1.0.0
*/
class Conditional extends Node
{
/**
* A node which resembles the expression which will be evaluated.
*
* @var NodeInterface
*/
private $condition = null;
/**
* Construct a new Conditional.
*
* @param NodeInterface|null $condition (optional) the expression to evaluate, or null which evaluates to true.
* @param array|Traversable $nodes (optional) a collection of nodes.
* @param int $lineNumber (optional) the line number.
* @param int $flags (optional) a bitmask for one or more flags.
*/
public function __construct(NodeInterface $condition = null, $children = array(), $lineNumber = -1, $flags = 0x00)
{
parent::__construct($children, $lineNumber, $flags);
$this->setCondition($condition);
}
/**
* {@inheritDoc}
*/
public function render(ContextInterface $context, OutputStreamInterface $out)
{
foreach ($this->getChildren() as $node) {
$node->render($context, $out);
}
}
/**
* Returns true if the underlying condition of this node is satisfied.
*
* A {@link Conditional} which lacks a condition will always evaluate to true.
* These conditional nodes are always satisfied, and it usually implies that the
* node was created to satisy an else statement.
*
* @param ContextInterface $context the template context with which to render a node.
* @param OutputStreamInterface $out the output stream.
* @return bool true if the condition is satisfied, false otherwise.
*/
public function isTrue(ContextInterface $context, OutputStreamInterface $out)
{
$condition = $this->getCondition();
$satisfied = ($condition === null);
if ($condition instanceof NodeInterface) {
$satisfied = boolval($condition->render($context, $out));
}
return $satisfied;
}
/**
* Set the expression to evaluate, or null which is equivelant to an expression which evaluates to true.
*
* @param NodeInterface $node (optional) the expression to evaluate, or null which evaluates to true.
*/
public function setCondition(NodeInterface $node = null)
{
if ($node !== null) {
$this->disableStrictErrors($node);
}
$this->condition = $node;
}
/**
* Returns the expression to evaluate, or null which is equivelant to an expression which evaluates to true.
*
* @return NodeInterface|null the expression to evaluate, or null.
*/
private function getCondition()
{
return $this->condition;
}
/**
* Disable all strict errors for the specified node and all of it's children.
*
* @param NodeInterface $node the node whose strict error will be disabled.
*/
private function disableStrictErrors(NodeInterface $node)
{
$node->removeFlags(NodeInterface::E_STRICT);
$node->addFlags(NodeInterface::E_NONE);
foreach ($node->getChildren() as $child) {
$this->disableStrictErrors($child);
}
}
}
|
JavaScript | UTF-8 | 2,205 | 3 | 3 | [
"MIT"
] | permissive | "use strict";
// I got part of the following code from the following site
// https://gist.github.com/ccnokes/95cb454860dbf8577e88d734c3f31e08#file-store-js
// Import modules
const path = require('path');
const fs = require('fs');
const electron = require('electron');
class Store {
constructor(opts) {
const userDataPath = (electron.app || electron.remote.app).getPath('userData');
this.path = path.join(userDataPath, opts.configName + '.json');
this.data = parseDataFile(this.path, opts.defaults); // In case the db hasn't been created until now
}
/**
* Retreives a specific note
* @param {number} key Note's ID
* @return {object} A note
*/
get(key) {
return this.data[key];
}
/**
* Indexes a new note
* @param {object} val details of the note created
*/
set(val) {
this.data.push(val);
fs.writeFileSync(this.path, JSON.stringify(this.data));
}
/**
* Retreives all the notes
* @return {List Object} List of notes
*/
getAll() {
return this.data;
}
/**
* Total number of notes
* @return {number} number of notes
*/
getCount() {
return this.data.length;
}
/**
* Updates the current value of the different
* details that contains a specific card
*/
updateCard(details) {
const { id, title, content, priority } = details;
this.data[id].title = title;
this.data[id].content = content;
this.data[id].priority = priority;
fs.writeFileSync(this.path, JSON.stringify(this.data));
}
/**
* Updates the state of the card (todo, progress, done)
* @param {object} details details to change the state of the card
*/
updateCardState(details) {
const { index, nState } = details;
this.data[index].state = nState;
fs.writeFileSync(this.path, JSON.stringify(this.data));
}
/**
* Deletes a specific note
*/
delete(idcard){
this.data.splice(idcard, 1);
fs.writeFileSync(this.path, JSON.stringify(this.data));
}
deleteAll(){}
}
function parseDataFile(filePath, defaults) {
try {
return JSON.parse(fs.readFileSync(filePath));
} catch(error) {
return defaults;
}
}
// expose the class
module.exports = Store;
|
Java | UTF-8 | 2,973 | 2.546875 | 3 | [] | no_license | package model;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
public class Product implements Serializable, Parcelable {
private String id;
private String name;
private Integer price;
private String img;
private String categories;
private String description;
private Boolean status;
public Product(){
}
public Product(String id, String name, Integer price, String img, String categories, String description) {
this.id = id;
this.name = name;
this.price = price;
this.img = img;
this.categories = categories;
this.description = description;
}
protected Product(Parcel in) {
id = in.readString();
name = in.readString();
if (in.readByte() == 0) {
price = null;
} else {
price = in.readInt();
}
img = in.readString();
categories = in.readString();
description = in.readString();
byte tmpStatus = in.readByte();
status = tmpStatus == 0 ? null : tmpStatus == 1;
}
public static final Creator<Product> CREATOR = new Creator<Product>() {
@Override
public Product createFromParcel(Parcel in) {
return new Product(in);
}
@Override
public Product[] newArray(int size) {
return new Product[size];
}
};
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(name);
if (price == null) {
dest.writeByte((byte) 0);
} else {
dest.writeByte((byte) 1);
dest.writeInt(price);
}
dest.writeString(img);
dest.writeString(categories);
dest.writeString(description);
dest.writeByte((byte) (status == null ? 0 : status ? 1 : 2));
}
}
|
Python | UTF-8 | 17,647 | 3.078125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 14:33:23 2019
#@author: Jonathan Mushkin (Weizmann Institute of Science)
All functions related to the Keplerian Mechcnics of 3-body motion simulation
When possible, this code is made generic for N-bodies
"""
import numpy as np
from numpy.linalg import norm
from numba import njit
import hopon.util as util
import hopon.newton as newton
@njit('float64(float64,float64,int32)')
def inverse_kepler_eq(MeanAnom,ecc,n):
"""
Inverse Kepler Equation solver. Find eccentric anomaly from the mean
anomaly and eccentricity
INPUT:
MeanAnom : Mean anomaly (np array)
e: eccentricity (magnitude) (np array)
n: number of iteration to perform (int)
OUTPUT:
EccAnom: Eccentric anomaly (np array)
Testing showed n of about 10 is enough, meaning the difference
between outputs obtained from n=10 and n=10000 are below float64
precision, for a large random sample.
Method:
Use Halley's method Fixed Point solver
equation: want to solve eq. f(x) = 0.
For us,
f(E) = E-e*sin(E)-M = 0.
define df = df/dE, ddf = d^2f / dE^2
E(n+1) = E(n) - 2*f*df/(2*df^2 - f*ddf)
"""
EccAnom = MeanAnom
for i in range(n):
f = EccAnom - ecc * np.sin(EccAnom) - MeanAnom
df = 1 - ecc * np.cos(EccAnom)
ddf = ecc * np.sin(EccAnom)
EccAnom = EccAnom - 2 * f * df / (2*df**2 - f *ddf )
return EccAnom
@njit('float64(float64,float64)')
def mean_to_ecc_anomaly(MeanAnom,ecc):
"""
Transform mean anomaly to eccentric anomaly.
INPUTS:
MeanAnom: mean-anomaly of a binary.
ecc: scalar eccentricity of a binary
OUTPUTS:
eccentric anomaly of a binary
"""
return inverse_kepler_eq(MeanAnom,ecc,50)
@njit('float64(float64,float64)')
def ecc_to_mean_anomaly(EccAnom,ecc):
return EccAnom-ecc*np.sin(EccAnom)
@njit('float64(float64,float64)')
def true_to_ecc_anomaly(f,e):
"""
get the eccentric anomaly (E) of a keplerian orbit from the true anomaly (f)
and scalar eccentricity (e).
INPUTS:
f : true anomaly,
e : scalar eccentricity
OUTPUT:
E : eccentric anomaly
"""
C = ( e+ np.cos(f) )/ (1+e*np.cos(f))
S = (np.sin(f)*(1-e**2)**(0.5)) / (1+e*np.cos(f))
return np.mod(np.arctan2(S,C),2*np.pi)
@njit('float64(float64,float64)')
def ecc_to_true_anomaly(E,e):
"""
get the true anomaly (f) of a keplerian orbit from the eccentric anomaly (E)
and scalar eccentricity (e).
INPUTS:
E : eccentric anomaly
e : scalar eccentricity
OUTPUT:
f : true anomaly
"""
return np.mod(2*np.arctan( ( (1+e)/(1-e) )**0.5 * np.tan(E/2) ), np.pi*2)
@njit(\
'Tuple((float64[:], float64[:]))(float64,float64,float64,float64,float64,float64,float64)')
def rv_from_keplerian_elements(ecc_mag,a,f,inc,Omega,om,GM):
"""
Find position and velocity (vectors) of a body, given the orbital parameters and phase.
INPUTS:
ecc_mag : scalar eccentricity
a : semi-major axis
f : true anomaly
inc : inclination
Omega : longitude of ascending node
om : (lowe case omega) argument of periapsis
GM : gravitational parameter, acceleration = -GM/r^2
OUTPTS:
r : position vector at given parameters
v : velocity vector at given parameters
"""
h_mag = ((1-ecc_mag**2) * (GM*a))**(1/2) # r-cross-v
J_hat = np.array([np.sin(inc)*np.sin(Omega) ,\
-np.sin(inc)*np.cos(Omega) ,\
np.cos(inc)])
asc_node_hat = np.array([np.cos(Omega),np.sin(Omega),0.0])
t_hat = util.cross(J_hat,asc_node_hat)
ecc_hat = asc_node_hat * np.cos(om) + t_hat*np.sin(om)
q_hat = util.cross(J_hat, ecc_hat)
# no need to normalize it, as asc_node_hat and third_hat are both
# orthogonal to J_hat
radius = a*(1-ecc_mag**2)/ (1+ecc_mag*np.cos(f))
vf = h_mag /radius # in phi direction
vr = ecc_mag * np.sin(f)*h_mag/ a / (1-ecc_mag**2)
v = ecc_hat * (vr*np.cos(f) - vf*np.sin(f)) + q_hat*(vr*np.sin(f) + vf*np.cos(f))
r = ecc_hat * radius*np.cos(f) + radius*np.sin(f)*q_hat
return r, v
@njit(\
'Tuple((float64[:],float64,float64,float64,float64,float64))(float64[:],float64[:],float64)'\
)
def keplerian_elements_from_rv(r,v,GM):
"""
Find orbital parameters and phase of an orbit, given position and velocity (vectors).
INPUTS:
r : position vector
v : velocity vector
GM : gravitational parameter, acceleration = -GM/r^2
OUTPUTS:
ecc_vec : eccentricity vector
f : true anomaly
a : semi-major axis
inc : inclination
Omega : longitude of ascending node
om : argument of periapsis
"""
eps = 1e-15 # small number
r_mag = norm(r)
E = (np.sum(v**2)/2 - GM/r_mag) # energy per unit reduced mass
if E==0.0:
a = np.inf
else:
a = -GM / (2*E) # a> 0 for elliptic / circular orbits, a<0 for hyperbolic
r_hat = r/r_mag
h = util.cross(r,v) # angular momentum per unit reduced mass
J_hat = h/norm(h)
inc = np.arccos(J_hat[2])
x_hat = np.array([1.0,0.0,0.0])
z_hat = np.array([0.0,0.0,1.0])
# if the inclination is extremely close to 0 or pi, there is no ascending node. We set the asc_node to the x axis then.
if (np.abs(inc)<eps) | (np.abs(inc-np.pi)<eps):
asc_node_hat = x_hat
else:
asc_node_hat = util.cross(z_hat, J_hat)
asc_node_hat = asc_node_hat / norm(asc_node_hat)
Omega = np.arctan2(h[0],-h[1])
Omega = np.mod(Omega,2*np.pi)
ecc_vec = util.cross(v,h)/GM - r_hat
if norm(ecc_vec)>eps:
ecc_hat = ecc_vec / norm(ecc_vec)
om = np.arctan2(norm(util.cross(asc_node_hat,ecc_hat)), np.sum(asc_node_hat*ecc_hat) )
else:
ecc_hat = asc_node_hat
om = 0.0
if ecc_hat[2]<0:
om = np.pi*2 - om
q_hat = util.cross(J_hat,ecc_hat)
f = np.mod(np.arctan2(np.sum(r_hat*q_hat), np.sum(r_hat*ecc_hat) ),np.pi*2)
return ecc_vec, f, a, inc, Omega, om
@njit('float64(float64,float64,float64,float64)')
def advance_true_anomaly(f0, e, mean_motion, t ):
"""
Find the true anomaly of the orbit after time t
INPUTS:
f0 : current true anomaly (scalar)
e : scalar eccentricity (scalar)
mean_motion : mean-anomaly change rate (scalar)
t : scalar, time to advance the system by
OUTPUT:
ft : true anomaly of the orbit after time t (scalar)
"""
# initial eccentric and mean anomalies
ea = true_to_ecc_anomaly(f0,e)
ma = ecc_to_mean_anomaly(ea,e)
# tareget mean anomaly
ma_t = np.float64(np.mod(ma + t * mean_motion, 2*np.pi))
# target eccentric anomaly
ea_t = mean_to_ecc_anomaly(ma_t,e)
return ecc_to_true_anomaly(ea_t,e)
@njit('Tuple((float64[:,:],float64[:,:],float64))(float64[:,:], float64[:,:], int32[:],float64[:],float64)')
def double_keplerian_motion(R,V,i,M,G):
"""
Given 3 bodies in an hierarchical triplet, advance the outer orbit to the
point reflected by semi-major axis (f -> 2*pi-f), in an unpertubed way (i.e.,
not interaction between inner and outer orbits). Advance inner orbit according
to the time passes.
INPUTS :
R : numpy array of size 3x3, positions of bodies
V : numpy array of size 3x3, velocities of bodies
i : int array of length 3.
i[0] = index of first inner binary member.
i[1] = index of second inner binary member.
i[2] = index of tertiary, memeber of the outer binary
M : 1d array of length 3, masses of bodies
G : Universal Gravitational Constant
OUTPUTS:
R_new: 2d array of size 3x3, positions of bodies after motion
V_new: 2d array of size 3x3, velocities of bodies after motion
delta_t : time elapsed during motion
HOW TO READ:
suffix _i, _o stand for inner, outer orbits
suffix _t stand for target value, after the motion
e stand for scalar eccentricity
ea, ma stand for eccentric, mean anomaly
f stand for true anomaly
delta_t is the time passed during the Keplerian motion
"""
# find total and reduces mass of inner orbit
M_i = M[i[0]]+M[i[1]]
mu_i = M[i[0]]*M[i[1]]/M_i
# find total and reduced mass of outer orbit
M_o = np.sum(M)
mu_o = M[i[2]]*M_i/(M_o)
# find relative positions and center of masses of the two binaries
R_i = (R[i[0],:]*M[i[0]] + R[i[1],:]*M[i[1]])/M_i # inner binary's C.O.M
r_i = R[i[0],:]-R[i[1]] # inner binary's relative position
V_i = (V[i[0],:]*M[i[0]] + V[i[1],:]*M[i[1]])/M_i # inner binary's C.O.M velocity
v_i = V[i[0],:]-V[i[1],:] # inner binary's relative velocity
R_o = (R[i[0],:]*M[i[0]] + R[i[1],:]*M[i[1]] + R[i[2],:]*M[i[2]])/M_o # Outer binary's C.O.M
V_o = (V[i[0],:]*M[i[0]] + V[i[1],:]*M[i[1]] + V[i[2],:]*M[i[2]])/M_o # Outer binary's C.O.M
r_o = R_i-R[i[2],:] # outer binary's relative position
v_o = V_i-V[i[2],:] # outer binary's relative velocity
# find Keplerian parameters of both orbits
ecc_vec_i,f_i,a_i,inc_i,Omega_i,w_i = keplerian_elements_from_rv(r_i,v_i,G*M_i)
ecc_vec_o,f_o,a_o,inc_o,Omega_o,w_o = keplerian_elements_from_rv(r_o,v_o,G*M_o)
# find magnitude of ecc. vector
e_i = norm(ecc_vec_i)
e_o = norm(ecc_vec_o)
# advance the outer orbit from true anom. f to 2*pi-f
f_o_t = 2*np.pi - f_o
# find eccentric and mean anomalies (ea,ma) of outer orbit
ea_o = true_to_ecc_anomaly(f_o,e_o) # current outer eccentric anomaly
ea_o_t = true_to_ecc_anomaly(f_o_t,e_o) # target outer eccentric anoamly
ma_o = ecc_to_mean_anomaly(ea_o,e_o) # current outer mean anomaly
ma_o_t =ecc_to_mean_anomaly(ea_o_t,e_o) # target outer mean anoamly
mean_motion_o = (G*M_o)**(0.5) * a_o**(-3/2) # outer mean_motion = = 2*pi / Orbital Period
delta_t = (ma_o_t-ma_o)/mean_motion_o # time duration of keplerian motion
mean_motion_i = (G*M_i)**(0.5) * a_i **(-3/2) # inner mean motion
f_i_t = advance_true_anomaly(f_i,e_i,mean_motion_i ,delta_t ) # target inner mean anomaly
# find position of inner & outer orbits at target time
r_o_t, v_o_t = rv_from_keplerian_elements(e_o, a_o, f_o_t, inc_o, Omega_o, w_o, G*M_o)
r_i_t, v_i_t = rv_from_keplerian_elements(e_i, a_i, f_i_t, inc_i, Omega_i, w_i, G*M_i)
R_t = np.zeros((3,3), dtype = np.float64)
V_t = np.zeros((3,3), dtype = np.float64)
R_t[i[0],:] = R_o + mu_o/M_i * r_o_t + r_i_t*mu_i/M[i[0]]
R_t[i[1],:] = R_o + mu_o/M_i * r_o_t - r_i_t*mu_i/M[i[1]]
R_t[i[2],:] = R_o - mu_o/M[i[2]] * r_o_t
V_t[i[0],:] = V_o + mu_o/M_i * v_o_t + v_i_t*mu_i/M[i[0]]
V_t[i[1],:] = V_o + mu_o/M_i * v_o_t - v_i_t*mu_i/M[i[1]]
V_t[i[2],:] = V_o - mu_o/M[i[2]] * v_o_t
return R_t, V_t, delta_t
@njit('Tuple((int32,int32))(float64[:,:],float64[:,:],float64[:],float64,float64,float64,float64,int32[:,:])')
def choose_NKT(R,V,M,G,h1,h2,lengthscale, triplets):
"""
Choose whether to perform the next simulation step by (N)ewtonian dynamics,
(K)eplerian calculation, or to (T)erminate the simulation.
INPUTS:
R : N x 3 dimensional np.array-s of positions
V : N x 3 dimensional np.array-s of velocities
M : np.array of length N of masses
G : Universal Gravitational Constant, scalar
h1 : Separation criterion. K and T are selected only if one of the
bodies is at least h1 times farther away from the two closest bodies
than they are from each other.
h2 : Heirarchy criterion. We treat the motion as well separated
into inner and outer orbit if the outer radius axis
is h2 times bigger than the inner semi-major-axis. (h1 and h2 do not have to be the same, but it is a good practice).
lengthscale: additional criterion for heirarchy. Useful in cases of
small separation between two bodies, in such a way that
separation criterion is met (h1), and the energy has
deviations, which makes errors in the inner orbit's
semi-major-axis calculation. To avoid those errors,
we also demand that the outer radius is h2 times
larger than the lengthscale. ( A good selection is the initial inner orbit's semi-major axis).
triplets : a list specifing the exact indexing and members of each triplet.
For example, if the indexing means
0 : ((0,1),2). 1: ((0,2),1). 2: ((1,2),0)
then triplet index = [[0,1,2],[0,2,1],[1,2,0]]
OUTPUTS:
Tuple of 2 outputs.
output[0] : 'N', 'K' or 'T'. (char)
output[1] : triplet index. (int)
"""
# conditions
is_hierarchical = 0
triplet_index = 0
outer_orbit_bound = 0
positive_drodt = 0
D = util.pairwise_enod(R) # pairwise distances of bodies
DD = sorted(D)[0:2] # sorted
# inner separation (r_i) = DD[0]
# outer separation (r_o) >= DD[1].
triplet_index = np.argmin(D) # see util.pairwise_enod() and util.create_triplets() for indexing scheme
Ebs = newton.binary_single_energy(R,V,M,G)
Epw = newton.pairwise_energy(R,V,M,G)
E_i = Epw[triplet_index]
# decide if triplet is heirarchical.
# only if relative distances fit,
# add tests to make sure no numerical errors due to phase of inner binary,
# and to some absolute and relative length scales
# the three bodies are instantaneously separated, there is a point
# figuring if they are hierarchical.
# for example: if the inner orbit has SMA = 1 and e = 0.999...
# and the outer orbit has SMA = 3 and e = 0.5,
# in could be that r_i = 1e-3, r_o = 1, r_i<<r_o
# But making an analytical keplerian timestep would be wrong, as during
# the outer orbit, the inner orbit will reach r_i = 1.9999...
# Epw[triplet_index] = energy of the inner orbit
i0 = int(triplets[triplet_index,0])
i1 = int(triplets[triplet_index,1])
i2 = int(triplets[triplet_index,2])
a_i = - G * M[i0]*M[i1]/2 / E_i
r_o = -R[i2,:]+(M[i0]*R[i0,:]+M[i1]*R[i1,:])/(M[i0]+M[i1])
v_o = -V[i2,:]+(M[i0]*V[i0,:]+M[i1]*V[i1,:])/(M[i0]+M[i1])
# reason for tests below:
# 1. DD[0]*h1 < DD[1] : makes sure there is instantaneous separation
#
# 2. a_i*h2 < DD[1] : makes sure the instantaneous hierarchy, relative to the
# inner orbit's size. For example, if e_i = 0.999, a_i = 1 and r_o = 3,
# it might happen that r_i << r_o, even though r_i and r_o will be
# compareable within a short time. Test 2 is precaution against energy calculations errors that will fool test 1.
#
# 3. lengthscale*h2< DD[1] : precaution, compare not only to instantaneous separations but also to a constant lengthscale.
#
# 4. a_i*0.9 < DD[0] : make sure the inner binary is not too close to pericenter. At high e_i (0.999999....), the energy calculations may
# deviate significantlly due to the small separations.
#
# 5. E_i<0 : inner binary is bound
if (DD[0]*h1 < DD[1]) & ((a_i*h2) < DD[1]) & (lengthscale * h2 < DD[1]) & ((a_i*0.9) < DD[0]) & ( E_i<0 ) :
is_hierarchical = 1
# check if outer orbit is bound or not
if Ebs[triplet_index]<0 :
outer_orbit_bound = 1
# make sure if outer orbit is going towards or away from pericenter
if np.dot(r_o,v_o)>0 :
positive_drodt = 1
# Determine what to do in the next stetp: N, K or T
if (is_hierarchical==0) | (positive_drodt==0) :
next_step = 0 # Newtonian step
if (is_hierarchical==1) &(outer_orbit_bound ==1) & (positive_drodt==1):
next_step = 1 # Keplerian step
if (is_hierarchical==1) &(outer_orbit_bound ==0) & (positive_drodt==1):
next_step = 2 # Terminate
return next_step, triplet_index
class orbital_elements(object):
# obejct of orbital elements, calculable from position, velocity and masses
def __init__(self,r,v,M,mu,G ):
ecc_vec, f, a, inc, Omega, omega = keplerian_elements_from_rv(r,v,M*G)
self.r = r
self.v = v
self.ecc_vec = ecc_vec
self.ecc_mag = np.sum(ecc_vec**2)**(0.5)
self.E = -G*M*mu/2/a
self.a = a
if self.ecc_mag > 1.0 and a>0.0: # for hyperbolic orbits
self.E = np.abs(self.E)
self.a = -np.abs(a)
self.f = f
self.inc = inc
self.Omega = Omega
self.omega = omega
self.M = M
self.mu = mu
self.G = G |
JavaScript | UTF-8 | 5,390 | 3.015625 | 3 | [] | no_license | var readline = require('readline');
var readlineThing = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var game = {
start: function() {
initialize();
},
restart: function() {
game.start();
}
}
function initialize() {
readlineThing.question("What is your name? ", function(answer) {
Name(answer);
console.log('Hi there ' + answer + ", welcome to the game!")
askClass();
})
}
function askClass() {
readlineThing.question("Choose your class: (Mage, Warrior, Thief) ", function(answer) {
chooseClass(answer);
askGender();
})
}
function askGender() {
readlineThing.question("Choose your gender: ", function(answer) {
var genderCorrect = false;
if (answer.toLowerCase() == "male" || answer.toLowerCase() == "female") {
gender(answer);
genderCorrect = true;
} else {
askGender();
}
if (genderCorrect == true) {
scroll();
readlineThing.close();
}
})
}
var enemies = {
finalBoss: {
name: "Alan",
health: 100,
skill: {
attack: function() {
console.log("get rekt scrub, mlg 360 no scope");
Player.health = Player.health - 10;
},
taunt: function() {
console.log("go home noob");
}
}
},
ogres: {
name: "Rejected One",
health: 20,
skill: {
attack: function() {
console.log("get Shrekt")
Player.health = Player.health - 5;
},
ogreFood: function() {
console.log("Bweakfast")
enemies.ogre.health = enemies.ogre.health + 2
}
}
}
}
var location = {
town: {
name: "da village of derp",
NPC: [],
monsters: null
},
woods: {
NPC: [],
Monsters: enemies.finalBoss
}
}
var Player = {
name: "Alan",
race: "Human",
class: "Mage",
gender: "Male",
health: 20,
currentLocation: location.town,
currentEnemy: null,
skill: {
1: null,
2: null,
3: null
},
eat: function() {
if (Player.health == 19) {
health = 20;
} else if (Player.health == 20) {
console.log("You are on full health. Stop eating.");
} else {
health = health + 2;
}
}
}
var currentLocation = location.town;
function Name(answer) {
Player.name = answer;
}
function gender(answer) {
Player.gender = answer;
}
function chooseClass(answer) {
Player.class = answer;
Player.skill["1"] = function() {
console.log("Take this @#%!@#@!#!@!");
finalBoss.health = finalBoss.health - 10;
}
if (Player.class.toLowerCase() == "mage") {
//Player.health = 10;
Player.skill["2"] = function() {
console.log("Eat fire");
finalBoss.health = finalBoss.health - 20;
}
Player.skill["3"] = function() {
console.log("I haz more health");
if (Player.health > 10) {
Player.health = 20;
} else {
Player.health = Player.health + 10;
}
}
askGender();
} else if (Player.class.toLowerCase() == "thief") {
//Player.health = 10;
Player.skill["2"] = function() {
console.log("Stabby stab stab");
finalBoss.health = finalBoss.health - 20;
}
Player.skill["3"] = function() {
console.log("Eat my arrow");
finalBoss.health = finalBoss.health - 15;
}
askGender();
} else if (Player.class.toLowerCase() == "warrior") {
//Player.health = 10;
Player.skill["2"] = function() {
console.log("Shanking intensifies");
finalBoss.health = finalBoss.health - 10;
console.log("Shanking intensifies");
finalBoss.health = finalBoss.health - 10;
}
Player.skill["3"] = function() {
console.log("This skill is a placeholder. It does nothing.");
}
askGender();
} else {
readlineThing.question("Please enter a valid class: ", function(answer) {
chooseClass(answer);
})
}
}
function wait(ms) {
var start = new Date().getTime();
for (var end = start; end < start + ms;) {
end = new Date().getTime();
}
}
function scroll() {
console.log("The game begins!")
wait(1000)
console.log("You are " + Player.name + ", a great legend that lives in the garbage truck which is located in an abandoned street of Africa")
wait(4000)
console.log("The rats need you to fight for space because you're too fat")
wait(3000)
console.log("With the power and knowledge of your class " + Player.class + " and your rare ability in having a 6 cm radius brain, you must save yourself and your man-space")
wait(5000)
console.log("Steal the homes of all the monsters to prove who's boss and who's homeless ")
wait(3000)
}
game.start(); |
Python | UTF-8 | 1,643 | 3.5625 | 4 | [] | no_license | import math
import matplotlib.pyplot as plt
def phase_oscillation(g): # 引数は減衰比
x = [] # プロット用データ(x軸)
y = [] # プロット用データ(y軸)
for t in range(0, 40000): # プロットデータ作成
t *= 0.01
w = t # 入力の円振動数
try:
fi = math.atan(-2 * g * wn * w / (wn ** 2 - w ** 2)) / math.pi * 180 # 位相角φの値
except:
None
x.append(w / wn) # x軸データの追加 振動数比(円振動数/固有振動数)
if w / wn > 1: # 振動数比が1より大きいときの位相角の値
y.append(fi - 180) # y軸データの追加
else:
y.append(fi) # y軸データの追加
plt.plot(x, y, label="ζ = "+str(g))
m = 50 # 質量
k = 500000 # ばね定数
c = 100 # ダンパ
wn = (k / m) ** 0.5 # 固有振動数
phase_oscillation(0.05) # 減衰比0.05の時のプロット作成
phase_oscillation(0.07) # 減衰比0.07の時のプロット作成
phase_oscillation(0.10) # 減衰比0.10の時のプロット作成
phase_oscillation(0.20) # 減衰比0.20の時のプロット作成
phase_oscillation(0.50) # 減衰比0.50の時のプロット作成
plt.legend(prop={"family":"MS Gothic"}) # 凡例表示
plt.title("位相曲線", fontname="MS Gothic") # タイトル
plt.xlabel("ω/ωn", fontname="MS Gothic") # x軸タイトル
plt.ylabel("φ[°]", fontname="MS Gothic") # y軸タイトル
plt.grid() # グリッド線表示
plt.savefig("位相曲線.png") # 保存する
plt.show() # プロット表示
|
C++ | UTF-8 | 1,014 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "VoxelTest.h"
#include <algorithm>
namespace test {
TEST_F(VoxelTest, CreateTest)
{
ASSERT_TRUE(obj_ptr_);
voxel_ptr_ = std::make_unique<voxel::Voxel>(
*obj_ptr_,
glm::vec3{ 8.f, 8.f, 8.f });
EXPECT_TRUE(voxel_ptr_);
}
TEST_F(VoxelTest, InsiderTest)
{
ASSERT_TRUE(obj_ptr_);
voxel_ptr_ = std::make_unique<voxel::Voxel>(
*obj_ptr_,
glm::vec3{ 8.f, 8.f, 8.f });
ASSERT_TRUE(voxel_ptr_);
voxel::proto::VoxelFile voxel_file = voxel_ptr_->GetVoxelFile();
SaveProtoToJsonFile(voxel_file, "./Apple.json");
// Compute the max length of a diagonal.
glm::vec3 end = glm::vec3(
voxel_file.end_x(),
voxel_file.end_y(),
voxel_file.end_z());
glm::vec3 begin = glm::vec3(
voxel_file.begin_x(),
voxel_file.begin_y(),
voxel_file.begin_z());
float max_diag = glm::length(end - begin);
std::for_each(
voxel_file.data().cbegin(),
voxel_file.data().cend(),
[max_diag](float f)
{
EXPECT_GT(max_diag, f);
});
}
} // End namespace test.
|
C# | UTF-8 | 463 | 3.078125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
public class Program
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
List<string> list = new List<string>();
for (int i = 0; i < n; i++)
{
list.Add(Console.ReadLine());
}
var box = new Box<string>(list);
string toCompare = Console.ReadLine();
Console.WriteLine(box.CompareTo(toCompare));
}
}
|
Python | UTF-8 | 1,890 | 2.9375 | 3 | [] | no_license | #!/usr/bin/python
"""
LOG:
2016/12/16: Added handling of standard error messages
"""
USAGE = "Calculate the proportion of amino acids in correct positions"
import sys, os
###############################################################################
# call a external programm that returns a value running on "workingDir"
###############################################################################
def runProgram (listOfParams, workingDir):
import subprocess
value = subprocess.Popen (listOfParams, cwd=workingDir, stdout=subprocess.PIPE, stderr=sys.stderr).communicate()[0]
return value
#-------------------------------------------------------------
# Print a message to the error output stream
#-------------------------------------------------------------
def log (message):
string=">>> SecStrCrr: "
if type (message) != list:
string += str (message)
else:
for i in message: string += str (i) + " "
sys.stderr.write (string+"\n")
#-------------------------------------------------------------
# Define the output for errors and log messages
#-------------------------------------------------------------
def defineMessagesOutput ():
stderr = os.getenv ("EVAL_STDERR")
if stderr == None:
sys.stderr = sys.stdout
else:
sys.stderr = open (stderr, "a")
##################################################################
# MAIN
##################################################################
if __name__ == "__main__":
try:
defineMessagesOutput ()
if len (sys.argv) < 2:
print USAGE
sys.exit (0)
pdbReference = sys.argv[1]
pdbTarget = sys.argv[2]
outputDir = os.getcwd ()
value = float ( runProgram (["secondary_structures", "-correct", pdbReference, pdbTarget], outputDir).strip())
print value
except Exception as e:
print ">>> Eval error in secondary_structures_correct.py, parameters: ", pdbReference, pdbTarget
print e
|
Markdown | UTF-8 | 1,393 | 2.578125 | 3 | [] | no_license | #Overview
整个项目用javascript完成,数据库用的是MongoDB,http服务器用的是Express,后端基于NodeJS,通信用的是socket.io。由于客户端是基于web的,所以支持包括移动端,PC端等常用设备,当然也支持安卓设备。
Demo服务器可以通过校内网访问http://10.131.251.231:3000 测试。
#Front-End Architecture
## 用户界面
前端用户界面部分采用HTML编写,可以通过浏览器访问,具体实现见index.html
通过jquery操作DOM实现消息显示,具体见client.js
## 与后端通信
通过socket.io-client模块,实现客户端与服务器的端到端通信,具体见client.js
## 模块打包
前端所需的JS模块通过webpack加载并打包成bundle.js供客户端浏览器使用。
## 加密解密
用NodeJS的crypto和node-rsa模块,与后端相同。
#Back-End Architecture
##数据库
由db.js提供访问接口。
server在启动时将数据库信息load到内存中。
server在关闭时将修改写会数据库。
##HTTP服务器
用NodeJS的Express模块,具体实现见server.js
##端到端通信
用NodeJS的socket.io模块,具体实现见server.js
通信协议的实现server端见server.js,client端见client_util.js
##加密解密
用NodeJS的crypto和node-rsa模块,具体实现见cipher.js和decipher.js
##Email
用NodeJS的emailjs模块,具体实现见email_util.js |
Java | UTF-8 | 5,108 | 2.890625 | 3 | [] | no_license | package com.yangyue.crawler;
import com.alibaba.fastjson.JSONArray;
import com.yangyue.dao.bean.NewsBean;
import com.yangyue.dao.imp.NewsDao;
import com.yangyue.dao.inf.NewsDaoInf;
import com.yangyue.tools.HttpRequest;
import com.yangyue.tools.NewsCrawlerHelper;
/**
* Created by yangyue on 2016/11/2.
*/
public class SohuNewsCrawler {
private NewsDaoInf dao = new NewsDao("sohunews");// 引用dao进行对数据库的操作
private String urlPage;
public SohuNewsCrawler(String url){
this.urlPage=url;
}
public void getNews(){
String str = HttpRequest.sendGet(urlPage,"");
int linkbegin = str.indexOf(",item:");// 截取<a>链接字符串起始位置
int linkend = str.indexOf("}");// 截取<a>链接字符串结束位置
String subString = str.substring(linkbegin + ",item:".length(), linkend);
JSONArray jsonArray =JSONArray.parseArray(subString);
for (Object obj:jsonArray){
String strTemp = obj.toString();
JSONArray jsonArrayTemp=JSONArray.parseArray(strTemp);
String type=jsonArrayTemp.get(0).toString();
System.out.println("抓取类型:"+type);
String title=jsonArrayTemp.get(1).toString();
System.out.println("抓取标题:"+title);
String url=jsonArrayTemp.get(2).toString();
System.out.println("抓取链接:"+url);
String newsdate=jsonArrayTemp.get(3).toString();
System.out.println("抓取时间:"+newsdate);
String content= NewsCrawlerHelper.getNewsContent(url,"articleBody");
System.out.println("抓取内容:"+content);
/**
<div class="text clear" id="contentText">
<div itemprop="articleBody">
<p> 北京时间1月1日消息,元旦大战,斯蒂芬-马布里真急了,他甚至在次节用肩膀顶撞裁判,结果被吹了技术犯规。末节老马开启个人攻击模式,结果5投3中单节砍下7分。整场比赛,“马政委”13投5中交出17分6助攻2抢断1篮板的数据。</p>
<p> 2016年首战,老马打得很郁闷,他在第三节甚至没有1次运动战出手,首节也只在外线投了2球。比赛进行期间,老马总是在场上抱怨。“这是老马着急的表现,”著名评论员孟晓琦说道。</p>
<p> 次节还剩8分30秒,深圳队大外援麦克奎尔在1次进攻中造成莫里斯犯规。在一旁的老马对这一判罚颇为不满,在申辩过程中,老马有一个用肩膀顶撞裁判的动作。于是,裁判果断给了老马一个T。也就是在麦克奎尔执行完2次罚球后,又追加给深圳队1罚1掷。</p>
<p> “老马的这个动作有些不应该,不管是有意还是无意,裁判这个T没有任何问题,”孟晓琦说道。</p>
<p> 前三节北京队落后18分,按照常规末节伊始应该是莫里斯上场。但今晚,闵鹿蕾做出调整,老马第四节一开始就在场上。这标志着,北京队展开最后一搏。是的,老马开启个人攻击模式--他先是连续2次强突上篮得分,紧接着在外线命中三分。但之后,老马又在外线2次出手,结果都没命中。老马连砍7分并没有帮助北京队缩小分差,反倒是深圳队确立20+优势。</p>
<p> 在这样的背景下,老马末节只打了不到半节便被换下场。今晚,老马出手13次,其中三分10投仅3中。显然,马布里和北京队都需要调整。本周日,卫冕冠军将客战老对手广东队,这又将是一场硬仗。(jimmy)</p>
</div>
<div style="display:none;">
<span id="url" itemprop="url">http://sports.sohu.com/20160101/n433249559.shtml</span>
<span id="indexUrl" itemprop="indexUrl">sports.sohu.com</span>
<span id="isOriginal" itemprop="isOriginal">true</span>
<span id="sourceOrganization" itemprop="sourceOrganization" itemscope itemtype="http://schema.org/Organization"><span itemprop="name">搜狐体育</span></span>
<span id="author" itemprop="author" itemscope itemtype="http://schema.org/Organization"><span itemprop="name">jimmy</span></span>
<span id="isBasedOnUrl" itemprop="isBasedOnUrl">http://sports.sohu.com/20160101/n433249559.shtml</span>
<span id="genre" itemprop="genre">report</span>
<span id="wordCount" itemprop="wordCount">684</span>
<span id="description" itemprop="description">北京时间1月1日消息,元旦大战,斯蒂芬-马布里真急了,他甚至在次节用肩膀顶撞裁判,结果被吹了技术犯规。末节老马开启个人攻击模式,结果5投3中单节砍下7分。整场比</span>
</div>
</div>
*/
NewsBean newsBean = new NewsBean(0,title,content,url,newsdate,type);
dao.add(newsBean);
}
}
}
|
Java | UTF-8 | 622 | 2.109375 | 2 | [] | no_license | package doctor.service;
import doctor.models.security.ConfirmationToken;
import doctor.repository.ConfirmationTokenRepo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class ConfirmationTokenService {
private final ConfirmationTokenRepo confirmationTokenRepository;
public ConfirmationToken saveConfirmationToken(ConfirmationToken confirmationToken) {
return confirmationTokenRepository.save(confirmationToken);
}
void deleteConfirmationToken(Long id) {
confirmationTokenRepository.deleteById(id);
}
}
|
Java | UTF-8 | 1,050 | 2.09375 | 2 | [] | no_license | package cn.znh.rulerseebar;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private RulerSeekBar mRulerSeekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// TestCanvasView testCanvasView = new TestCanvasView(this);
mRulerSeekBar = findViewById(R.id.seek_bar);
mRulerSeekBar.setPadding(0,0,0,0);
int max = 1234604;
max = 300;
int progressPos = max/4;
// progressPos = 15;
int dotPos = progressPos;
// dotPos = 1200;
mRulerSeekBar.setRulerCount(3);
mRulerSeekBar.setRulerColor(Color.BLACK);
mRulerSeekBar.setRulerWidth(5);
mRulerSeekBar.setShowTopOfThumb(false);
mRulerSeekBar.setMax(max);
mRulerSeekBar.setProgress(progressPos);
mRulerSeekBar.setDotPostX((float)dotPos);
}
}
|
Go | UTF-8 | 5,327 | 2.71875 | 3 | [] | no_license | package main
import (
"fmt"
"math"
"os"
"time"
"github.com/project-draco/moea"
"github.com/project-draco/moea/binary"
"github.com/project-draco/moea/nsgaii"
)
const (
maxValue = float64(^uint32(0))
)
type problem struct {
numberOfValues int
bounds func(int) (float64, float64)
objectiveFunction func(moea.Individual) []float64
}
var sch = problem{
1,
func(i int) (float64, float64) { return -1000, 1000 },
func(individual moea.Individual) []float64 {
x := valueAsFloat(individual.Value(0), -1000, 1000)
return []float64{x * x, (x - 2.0) * (x - 2.0)}
},
}
var fon = problem{
3,
func(i int) (float64, float64) { return -4, 4 },
func(individual moea.Individual) []float64 {
s1, s2 := 0.0, 0.0
for i := 0; i < 3; i++ {
x := valueAsFloat(individual.Value(i), -4, 4)
s1 += math.Pow(x-1/math.Sqrt(3), 2)
s2 += math.Pow(x+1/math.Sqrt(3), 2)
}
return []float64{1 - math.Exp(-s1), 1 - math.Exp(-s2)}
},
}
var pol = problem{
2,
func(i int) (float64, float64) { return -math.Pi, math.Pi },
func(individual moea.Individual) []float64 {
x1 := valueAsFloat(individual.Value(0), -math.Pi, math.Pi)
x2 := valueAsFloat(individual.Value(1), -math.Pi, math.Pi)
a1 := 0.5*math.Sin(1) - 2*math.Cos(1) + math.Sin(2) - 1.5*math.Cos(2)
a2 := 1.5*math.Sin(1) - math.Cos(1) + 2*math.Sin(2) - 0.5*math.Cos(2)
b1 := 0.5*math.Sin(x1) - 2*math.Cos(x1) + math.Sin(x2) - 1.5*math.Cos(x2)
b2 := 1.5*math.Sin(x1) - math.Cos(x1) + 2*math.Sin(x2) - 0.5*math.Cos(x2)
return []float64{1 + math.Pow(a1-b1, 2) + math.Pow(a2-b2, 2),
math.Pow(x1+3, 2) + math.Pow(x2+1, 2)}
},
}
var kur = problem{
3,
func(i int) (float64, float64) { return -5, 5 },
func(individual moea.Individual) []float64 {
s1, s2 := 0.0, 0.0
for i := 0; i < 3; i++ {
x := valueAsFloat(individual.Value(i), -5, 5)
if i < 2 {
xx := valueAsFloat(individual.Value(i+1), -5, 5)
s1 += -10 * math.Exp(-0.2*math.Sqrt(x*x+xx*xx))
}
s2 += math.Pow(math.Abs(x), 0.8) + 5*math.Sin(x*x*x)
}
return []float64{s1, s2}
},
}
var zdt1 = problem{
30,
func(i int) (float64, float64) { return 0, 1 },
func(individual moea.Individual) []float64 {
x := valueAsFloat(individual.Value(0), 0, 1)
s := 0.0
for i := 1; i < 30; i++ {
s += valueAsFloat(individual.Value(i), 0, 1)
}
g := (1 + 9*s/29)
return []float64{x, g * (1 - math.Sqrt(x/g))}
},
}
var zdt2 = problem{
30,
func(i int) (float64, float64) { return 0, 1 },
func(individual moea.Individual) []float64 {
x := valueAsFloat(individual.Value(0), 0, 1)
s := 0.0
for i := 1; i < 30; i++ {
s += valueAsFloat(individual.Value(i), 0, 1)
}
g := (1 + 9*s/29)
return []float64{x, g * (1 - math.Pow(x/g, 2))}
},
}
var zdt3 = problem{
30,
func(i int) (float64, float64) { return 0, 1 },
func(individual moea.Individual) []float64 {
x := valueAsFloat(individual.Value(0), 0, 1)
s := 0.0
for i := 1; i < 30; i++ {
s += valueAsFloat(individual.Value(i), 0, 1)
}
g := (1 + 9*s/29)
return []float64{x, g * (1 - math.Sqrt(x/g) - x/g*math.Sin(10*math.Pi*x))}
},
}
var zdt4 = problem{
10,
func(i int) (float64, float64) {
if i == 0 {
return 0, 1
} else {
return -5, 5
}
},
func(individual moea.Individual) []float64 {
x := valueAsFloat(individual.Value(0), 0, 1)
g := 0.0
for i := 1; i < 10; i++ {
xx := valueAsFloat(individual.Value(i), -5, 5)
g += xx*xx - 10.0*math.Cos(4.0*math.Pi*xx)
}
g += 91.0
return []float64{x, g * (1.0 - math.Sqrt(x/g))}
},
}
var zdt6 = problem{
10,
func(i int) (float64, float64) { return 0, 1 },
func(individual moea.Individual) []float64 {
x := valueAsFloat(individual.Value(0), 0, 1)
s := 0.0
for i := 1; i < 10; i++ {
s += valueAsFloat(individual.Value(i), 0, 1)
}
g := 1 + 9*math.Pow(s/9.0, 0.25)
f1 := 1 - math.Exp(-4*x)*math.Pow(math.Sin(6*math.Pi*x), 6)
return []float64{f1, g * (1 - math.Pow(f1/g, 2))}
},
}
func valueAsFloat(value interface{}, from, to float64) float64 {
bs := value.(binary.BinaryString)
return (to-from)*float64(bs.Int().Int64())/maxValue + from
}
func main() {
problem := zdt6
rng := moea.NewXorshiftWithSeed(uint32(time.Now().UTC().UnixNano()))
lengths := make([]int, problem.numberOfValues)
for i := 0; i < problem.numberOfValues; i++ {
lengths[i] = 32
}
nsgaiiSelection := &nsgaii.NsgaIISelection{}
config := &moea.Config{
Algorithm: moea.NewSimpleAlgorithm(nsgaiiSelection, &moea.FastMutation{}),
Population: binary.NewRandomBinaryPopulation(100, lengths, nil, rng),
NumberOfValues: problem.numberOfValues,
NumberOfObjectives: 2,
ObjectiveFunc: problem.objectiveFunction,
MaxGenerations: 250,
CrossoverProbability: 0.9,
MutationProbability: 1.0 / (float64(problem.numberOfValues) * 32.0),
RandomNumberGenerator: rng,
}
result, err := moea.Run(config)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
for i, individual := range result.Individuals {
fmt.Printf("[")
for j := 0; j < config.NumberOfObjectives; j++ {
fmt.Printf("%.4f ", individual.Objective[j])
}
fmt.Printf("]")
for j := 0; j < problem.numberOfValues; j++ {
from, to := problem.bounds(j)
fmt.Printf(" %.2f", valueAsFloat(individual.Values[j], from, to))
}
fmt.Printf(" %v\n", nsgaiiSelection.Rank[i])
}
}
|
Python | UTF-8 | 3,220 | 2.75 | 3 | [] | no_license | import sys
import os
import re
import glob
import read_log as log
import input_adf
import input_g09
print 'python autorun.py flag'
print 'this script is run from a base directory'
print 'flag = int.int.int... where each int specifies some flag (separator is .)'
flag = sys.argv[1]
flags = flag.split('.')
cwd = os.getcwd()
def create_dirs(list_str):
"""creates directories depending on the specified levels
Args:
list_str: list of strings that describe the directory
Return:
None
"""
if len(list_str) >= 1:
if list_str[0] == 'help' or list_str == 'help':
all succeeding strings describe the name of the directory to be created, with the exception that the base is 0'
if list_str[0] =='0':
os.mkdir('base')
else:
try:
levels = ['base']+['level'+str(i) for i in range(1,int(list_str[0])+1)]
except ValueError:
levels = ['base']+list_str[1:]
for i,j in enumerate(levels):
path = os.path.join(cwd,*levels[:i+1])
if not os.path.isdir(path):
os.mkdir(path)
def get_list_files(level,ext):
"""returns list of files in provided level with extension given
Args:
level: string of form 'leveln' where n is an integer, or list of directories that describe the path
ext: extension of files to find of form (.ext)
Return:
list of strings (paths)
"""
if type(level) is str and re.search('^level\d+$',level):
levels = ['base'] + ['level'+str(i) for i in range(1,int(level[5:])+1)]
elif type(level) is list:
levels = level
else:
raise AssertionError, 'given levels is bad'
path = os.path.join(cwd,*levels)
files = os.path.join(path,'*'+ext)
return glob.glob(files)
def extract_files_log(program,extension,level):
"""extract the log file information from the given files (set by level and extension)
Args:
program: string \in {g09, adf}
extension: string
level: string
"""
filepaths = get_list_files(level, ext)
data = []
for i in filepaths:
data.append(log.LogData(inpdata=i,program=prog))
return data
def make_run(program,extension,level):
"""extract the log file information from the given files (set by level and extension)
Args:
program: string \in {g09, adf}
extension: string
level: string
"""
filepaths = get_list_files(level, ext)
data = []
for i in filepaths:
data.append(log.LogData(inpdata=i,program=prog))
return data
#create dirs
if flags[0] == '1':
list_str = sys.argv[2].split('.')
create_dirs(list_str)
#extract file information
if flags[0] == '2':
prog = sys.argv[2]
ext = sys.argv[3]
level = sys.argv[4]
data = extract_files_log(prog, ext, level)
#something with data
#create input
if flag[0] == '3':
prog = sys.argv[2]
filename = sys.argv[3]
template = sys.argv[4]
if prog == 'adf':
input = input_adf.ADF_input(template=template)
elif prog =='g09':
input = input_g09.g09_input(template=template)
input.write_input(filename)
|
PHP | UTF-8 | 3,632 | 2.828125 | 3 | [] | no_license | <?php
require("vendor/autoload.php");
use PHPUnit\Framework\TestCase;
use DV\DataValidator as Data;
class DataValidatorTest extends TestCase
{
/**
* CPF TESTS
*/
public function testShouldReturnFalseWhenCpfHasMoreDigits()
{
$this->assertFalse(Data::isCpf("56355065523"));
}
public function testShouldReturnFalseWhenCpfHasFewerDigits()
{
$this->assertFalse(Data::isCpf("5635506552"));
}
public function testShouldReturnFalseWhenCpfDoesNotValid()
{
$this->assertFalse(Data::isCpf("189.879.620-71"));
}
public function testShouldReturnTrueWhenCpfIsValid()
{
$this->assertTrue(Data::isCpf("189.879.680-73"));
}
public function testShouldReturnTrueifTheCpfWithCorrectPunctuation()
{
$this->assertEquals(Data::cpfWithScore("18987968073"), "189.879.680-73");
}
public function shouldReturnFalseIfTheCpfContainsAnyCharacterThatIsNotANumber()
{
$this->assertFalse(Data::isCpf("189.879.620-7A"));
}
/**
* CNPJ TESTS
*/
public function testShouldReturnFalseWhenCnpjHasMoreDigits()
{
$this->assertFalse(Data::isCnpj("069905900001232"));
}
public function testShouldReturnFalseWhenCnpjHasFewerDigits()
{
$this->assertFalse(Data::isCnpj("0699059000012"));
}
public function testShouldReturnFalseWhenCnpjDoesNotValid()
{
$this->assertFalse(Data::isCnpj("03.290.590/0001-23"));
}
public function testShouldReturnTrueWhenCnpjIsValid()
{
$this->assertTrue(Data::isCnpj("06.990.590/0001-23"));
}
public function testShouldReturnTrueifTheCnpjWithCorrectPunctuation()
{
$this->assertEquals(Data::cnpjWithScore("06990590000123"), "06.990.590/0001-23");
}
public function shouldReturnFalseIfTheCnpjContainsAnyCharacterThatIsNotANumber()
{
$this->assertTrue(Data::isCnpj("06.990.590/0001-2a"));
}
/**
* NAME TESTS
*/
public function testShouldReturnFalseWhenNameIsEmpty()
{
$this->assertFalse(Data::isName(""));
}
public function testShouldReturnFalseWhenNameIsNull()
{
$this->assertFalse(Data::isName(null));
}
public function testShouldReturnFalseWhenNameIsNumber()
{
$this->assertFalse(Data::isName("123"));
}
public function testShouldReturnTrueWhenNameIsValid()
{
$this->assertTrue(Data::isName("João"));
}
public function testShouldReturnTrueWhenNameIsValidWithSpaces()
{
$this->assertTrue(Data::isName("João da Silva"));
}
/**
* CEP TESTS
*/
public function testShouldReturnFalseWhenCepIsEmpty()
{
$this->assertFalse(Data::isCep(""));
}
public function testShouldReturnFalseWhenCepIsNull()
{
$this->assertFalse(Data::isCep(null));
}
public function testShouldReturnFalseWhenCepIsNumber()
{
$this->assertFalse(Data::isCep("123"));
}
public function testShouldReturnTrueWhenCepIsValid()
{
$this->assertTrue(Data::isCep("12345-678"));
}
/**
* RG TESTS
*/
public function testShouldReturnFalseWhenRgIsEmpty()
{
$this->assertFalse(Data::isRg(""));
}
public function testShouldReturnFalseWhenRgIsNull()
{
$this->assertFalse(Data::isRg(null));
}
public function testShouldReturnFalseWhenRgIsNumber()
{
$this->assertFalse(Data::isRg("123"));
}
public function testShouldReturnTrueWhenRgIsValid()
{
$this->assertTrue(Data::isRg("31.538.734-8"));
}
}
|
JavaScript | UTF-8 | 415 | 2.9375 | 3 | [
"MIT"
] | permissive | 'use strict'
var includes = require('./includes')
/**
* Pull values from an array.
*
* @param {*[]} array
* @param {*|*[]} values
* @return {*[]}
*/
module.exports = function pull (array, values) {
var i, j, k = [], l = 0, m
if (!Array.isArray(values)) values = [ values ]
for (i = 0, m = array.length; i < m; i++) {
j = array[i]
if (!includes(values, j))
k[l++] = j
}
return k
}
|
Markdown | UTF-8 | 724 | 2.78125 | 3 | [] | no_license | # blackjack
It's a practice on my javascript skill, which shows the game of casino blackjack abiding it's fundamental rules
It follows the rule of blackajck with little alteration
The kings,heart, and queen still have their values as 10 and ace can be 1 or 11 depending on the condition
Ace will be 11 if it won' exceed 42 when the card is sum together and 1 if if it will
The highest score for this game is 42, exceeding it means you loose
Their are four button there
New gane to start a new game
Cancel to cancel the current game
Hit to pick a card
Stay for the dealer to pick a card
Yield to admit defeat and share 40% from his bet
Once the new game button is hit, the player and the dealer will be shared two cards each
|
JavaScript | UTF-8 | 4,826 | 2.625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0"
] | permissive | var guides = [[0, 0], [1, 0], [2, 0.5], [3, 10]];
var svg = d3
.select("body")
.append("svg")
.attr("width", window.innerWidth)
.attr("height", window.innerHeight);
var xScale = d3.scaleLinear();
xScale.domain([0, 200]).range([0, window.innerWidth]);
var yScale = d3.scaleLinear();
yScale.domain([1, 8]).range([0, window.innerHeight]);
function on_window_resize() {
xScale.range([0, window.innerWidth]);
yScale.range([0, window.innerHeight]);
}
window.onresize = on_window_resize;
// function draw_qubit(qubit_data) {
// if qubit_data["type"] == "?" {
// d3
// }
// }
function draw_round(round_data) {
// input: take in the JSON of a round, and draw the qubit lines
// round_data format: (sample)
// {
// "qubit0": {
// "type": "Zterm",
// "targets": [
// 0
// ],
// "op": 3,
// "angle": 0.0350239283818972,
// "gate_id": 0
// },
// },
var qubit_group = svg.append("g");
var line = d3
.line()
.x(function(d) {
return xScale(d.qubit_id);
})
.y(function(d) {
return yScale(d.qubit_id);
})
.curve(d3.curveCatmullRomOpen);
qubit_group
.selectAll("path")
.data(round_data)
.enter()
.append("path")
.attr("d", line)
.style("fill", "none")
.style("stroke", "#999");
const nOfQubits = Object.keys(round_data).length;
for (i = 0; i < nOfQubits; i++) {
// we need to do something for each qubit
qubit_data = round_data["qubit" + i.toString()];
console.log(qubit_data);
console.log(qubit_data["type"]);
if (qubit_data["type"] == "?") {
// draw a normal line
} else {
// we can skip
console.log("im not bitter");
}
}
}
// begin by creating the qubit lines
// // const nOfQubits = 3;
// var sample_data = [
// [[0, 1], [1, 1]],
// [[0, 2], [1, 2], [2, 3], [3, 3]],
// [[0, 3], [1, 3], [2, 2], [3, 2]],
// ];
// var line = d3
// .line()
// .x(function(d) {
// return xScale(d[0]);
// })
// .y(function(d) {
// return yScale(d[1]);
// })
// .curve(d3.curveCatmullRomOpen);
// for (i = 0; i < nOfQubits; i++) {
// svg.append("path");
// }
// // var lines = line(sample_data);
// d3.selectAll("path")
// .data(sample_data)
// .attr("d", line)
// .style("fill", "none")
// .style("stroke", "#999");
// var link = d3.link().source(function(d) {
// return d[0];
// }).target(function(d){
// return d[1];
// });
var test_data = [[0, 0], [10, 10]];
// function test_json() {
// d3.json("./data/rounds.json", function(error, data) {
// d3.select("body").selectAll("p").data(data).enter().append("p").text(function(d) {return d;});
// });
// }
// test_json();
var json_data = d3.json("./data/rounds.json");
// json_data.then(function(data) {
// console.log(data);
// })
// json_data
// .then(function(data) {
// draw_round(data[0]);
// })
// .catch(console.log.bind(console));
function make_grid_of_points(qubits, gates) {
var data = new Array();
// starting positions
var xpos = 0;
var ypos = 0;
for (var row = 0; row < qubits; row++) {
data.push(new Array());
for (var column = 0; column < gates; column++) {
data[row].push({
x: xScale(xpos),
y: yScale(ypos),
});
// increment the x by 10
xpos += 1;
}
// increment the y by 10
ypos += 1;
xpos = 0;
}
return data;
}
numberOfQubits = json_data
.then(function(data) {
// I want to produce a series of dots from the data
// the xpositions of the dots are the index scaled
// the ypositions of the dots are the qubit indices scaled
numberOfQubits = Object.keys(data[0]).length;
numberOfGates = data.length;
svg.selectAll("g")
.data(make_grid_of_points(numberOfQubits, numberOfGates))
.enter()
.append("g")
.selectAll("circle")
.data(function(d, i) {return d;})
.enter()
.append("circle")
.attr("cx", function(d, i) {
return d.x;
})
.attr("cy", function(d, i) {
return d.y;
})
.attr("r", "0.5")
.attr("stroke", "black");
return numberOfQubits;
})
.catch(console.log.bind(console));
console.log(typeof numberOfQubits);
console.log(numberOfQubits);
|
Java | UTF-8 | 1,444 | 3.015625 | 3 | [] | no_license | package br.com.modulo1;
import java.util.*;
public class ExercicioLista {
public static void main(String[] args) {
//List<String> dia = new ArrayList<String>(Arrays.asList("red","blue","gray","purpll"));
//List<String> cores = Arrays.asList("red","blue","gray","purpll");
List<String> cores = new ArrayList<String>();
cores.add("Red");
cores.add("Green");
cores.add("Greedn");
cores.add("Orange");
cores.add("White");
cores.add("Black");
List<String> colors11 = Arrays.asList("red","Green","Black","While","Pink");
List<String> colors2 = Arrays.asList("red","Green","Black","Pink");
//colors11.retainAll(colors2);
colors2.retainAll(colors11);
System.out.println(colors2);
System.out.println("--------------------------");
System.out.println(cores);
Collections.sort(cores);
System.out.println(cores);
System.out.println("_______________________________");
Collections.reverse(cores);
System.out.println(cores);
System.out.println("_______________________________");
SortedSet<String> corres = new TreeSet<>();
corres.add("Red");
corres.add("Green");
corres.add("Green");
corres.add("Orange");
corres.add("White");
corres.add("Black");
System.out.println(corres);
}
}
|
JavaScript | UTF-8 | 329 | 2.59375 | 3 | [] | no_license |
import firebase from '../../firebase/config';
const SignUpRequest = async(email, password) => {
try {
return await firebase.auth().createUserWithEmailAndPassword(email, password);
console.log("HI ");
} catch (error) {
console.log("HI "+error)
alert(error)
return;
}
};
export default SignUpRequest; |
Markdown | UTF-8 | 1,117 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | ---
title: Flow Service Account
---
The Service Account is a special account in Flow that has special permissions to manage system contracts. It is able to mint tokens, set fees, and update network-level contracts. During Flow's Beta period, the Service Account is also the only account that is able to create new Flow accounts.
## Tokens & Fees
The Service Account has administrator access to the FLOW token smart contract, so it has authorization to mint and burn tokens. It also has access to the transaction fee smart contract and can adjust the fees charged for transactions execution on Flow.
## Network Management
The Service Account administrates other smart contracts that manage various aspects of the Flow network, such as epochs and validator staking auctions.
## Governance
Besides its special permissions, the Service Account is an account like any other in Flow. During the early phases of Flow's development, the account will be controlled by keys held by Dapper Labs. As Flow matures, the service account will transition to being controlled by a smart contract governed by the Flow community.
|
C# | UTF-8 | 2,723 | 2.703125 | 3 | [] | no_license | using CommandLine;
using System;
using System.IO;
using System.Reflection;
namespace ConfigFixerByEnv
{
class Program
{
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args)
.WithParsed<Options>(o =>
{
var currentdirectory = AppDomain.CurrentDomain != null ?
Path.Combine(AppDomain.CurrentDomain.BaseDirectory) :
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var environment1 = EnvironmentBySystemService.GetCurrentEnvironment(o.SubEnvironmentVariable1);
var environment2 = EnvironmentBySystemService.GetCurrentEnvironment(o.SubEnvironmentVariable2);
var environment = EnvironmentBySystemService.GetCurrentEnvironment(o.EnvironmentVariable);
var separator = o.Separator;
//Normalize
environment1 = !string.IsNullOrEmpty(environment1) ? string.Concat(environment1, separator) : environment1;
environment2 = !string.IsNullOrEmpty(environment2) ? string.Concat(environment2, separator) : environment2;
o.SourceFile = !string.IsNullOrEmpty(o.SourceFile) ? string.Concat(o.SourceFile, separator) : o.SourceFile;
if (string.IsNullOrEmpty(environment)) { throw new InvalidArgumentException("Undefined : o.EnvironmentVariable"); }
Console.WriteLine("[Main] >> Defined environment variable result -> Environment variable is : " + environment);
var configpath = string.Concat(o.SourceFile, environment1, environment2, environment, o.Extension);
Console.WriteLine("[Main] >> Source file path -> is : " + configpath);
if (!File.Exists(configpath)) { throw new InvalidFileparameterException("[Args] Invalid config file file or not found : " + configpath); }
Console.WriteLine("[Main] >> Deleting old main config file if exists -> is : " + o.MainConfigFile);
if (!string.IsNullOrEmpty(o.MainConfigFile) && File.Exists(o.MainConfigFile)) { File.Delete(o.MainConfigFile); }
Console.WriteLine("[Main] >> Deleting old main config file if exists -> is : " + o.DestinationFile);
if (!string.IsNullOrEmpty(o.DestinationFile) && File.Exists(o.DestinationFile)) { File.Delete(o.DestinationFile); }
Console.WriteLine("[Main] >> Copying -> : " + configpath + " to " + Path.Combine(currentdirectory, o.DestinationFile ));
File.Copy(configpath, Path.Combine(currentdirectory, o.DestinationFile));
});
}
}
}
|
Java | UTF-8 | 125 | 1.648438 | 2 | [] | no_license | package com.crv.ole.base;
/**
* Created by zhangbo on 2017/8/5.
*/
public interface BaseService<T> {
void clear();
}
|
PHP | UTF-8 | 2,771 | 2.671875 | 3 | [] | no_license | <?php
$mysqli = false;
function connectDB(){
global $mysqli;
$mysqli = new mysqli("localhost", "root", "", "myblog.ua");
$mysqli->query("SET NAMES 'utf8'");
}
function getAllArticles(){
return getAll("articles");
}
function getAllGuestBookComments(){
return getAll("guestbook");
}
function getAllBanners(){
return getAll("banners");
}
function getAll($table){
global $mysqli;
connectDB();
$result_set = $mysqli->query("SELECT * FROM `$table` ");
closeDB();
return resultSetToArray($result_set);
}
function addGuestBookComment($name, $comment){
global $mysqli;
connectDB();
$success = $mysqli->query("INSERT INTO `guestbook`(`name`,`comment`) VALUES ('$name','$comment')");
closeDB();
return $success;
}
function addUser($email, $password){
global $mysqli;
connectDB();
$success = $mysqli->query("INSERT INTO `users` (`email`, `password`) VALUES ('$email`,'$password'')");
closeDB();
return $success;
}
function checkUser($email, $password){
global $mysqli;
connectDB();
$result_set = $mysqli->query("SELECT * FROM `users` WHERE `email`='$email' AND `password`='$password'");
closeDB();
if ($result_set->fetch_assoc()) return true;
else return false;
}
function getArticle($id){
global $mysqli;
connectDB();
$result_set = $mysqli->query("SELECT * FROM `articles` WHERE `id`='$id'");
closeDB();
return $result_set->fetch_assoc();
}
function resultSetToArray($result_set){
$array = array();
while (($row = $result_set->fetch_assoc()) != false)
$array[] = $row;
return $array;
}
function searchArticles($words) {
$query_search = "";
$arraywords = explode(" ", $words);
foreach ($arraywords as $key => $value) {
if (isset($arraywords[$key - 1])) $query_search .= " OR ";
$query_search .= "(`full_text` LIKE '%$value%' OR `title` LIKE '%$value%')";
}
global $mysqli;
connectDB();
$result_set = $mysqli->query("SELECT * FROM `articles` WHERE $query_search ");
closeDB();
return resultSetToArray($result_set);
}
function isAdmin($email) {
global $mysqli;
connectDB();
$result_set = $mysqli->query("SELECT * FROM `users` WHERE `email`='$email'");
$row = $result_set->fetch_assoc();
closeDB();
return $row["admin"];
}
function closeDB(){
global $mysqli;
$mysqli->close();
}
?> |
JavaScript | UTF-8 | 929 | 2.546875 | 3 | [] | no_license | document.onmouseover = onmouseover;
document.onmouseout = onmouseout;
function onmouseover()
{
var e = window.event.srcElement;
var s = e.title.toString();
if(s == '' && e.tagName == 'A')
s = e.innerText;
if(s != '')
window.setTimeout('window.status=\''+s.split('\'').join('\\\'')+'\'', 1);
}
function onmouseout()
{
var e = window.event.srcElement;
var s = e.title.toString();
if(s == '' && e.tagName == 'A')
s = e.innerText;
if(s != '')
window.status = '';
}
document.onhelp = onhelp;
function onhelp()
{
var e = window.event.srcElement;
openHelp(window.location, e.name!=''?e.name:e.id);
event.returnValue = false;
return false;
}
function openHelp(url, id)
{
var wnd = window.open('help/help.asp?path='+escape(url)+'&id='+escape(id), 'help', 'left='+(window.screen.width-400-10)+',width=400,top=0,height=480,resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes');
wnd.focus();
}
|
Go | UTF-8 | 9,717 | 2.78125 | 3 | [
"MIT"
] | permissive | package create
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/browser"
"github.com/cli/cli/v2/internal/config"
"github.com/cli/cli/v2/internal/run"
"github.com/cli/cli/v2/pkg/cmd/gist/shared"
"github.com/cli/cli/v2/pkg/cmdutil"
"github.com/cli/cli/v2/pkg/httpmock"
"github.com/cli/cli/v2/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func Test_processFiles(t *testing.T) {
fakeStdin := strings.NewReader("hey cool how is it going")
files, err := processFiles(io.NopCloser(fakeStdin), "", []string{"-"})
if err != nil {
t.Fatalf("unexpected error processing files: %s", err)
}
assert.Equal(t, 1, len(files))
assert.Equal(t, "hey cool how is it going", files["gistfile0.txt"].Content)
}
func Test_guessGistName_stdin(t *testing.T) {
files := map[string]*shared.GistFile{
"gistfile0.txt": {Content: "sample content"},
}
gistName := guessGistName(files)
assert.Equal(t, "", gistName)
}
func Test_guessGistName_userFiles(t *testing.T) {
files := map[string]*shared.GistFile{
"fig.txt": {Content: "I am a fig"},
"apple.txt": {Content: "I am an apple"},
"gistfile0.txt": {Content: "sample content"},
}
gistName := guessGistName(files)
assert.Equal(t, "apple.txt", gistName)
}
func TestNewCmdCreate(t *testing.T) {
tests := []struct {
name string
cli string
factory func(*cmdutil.Factory) *cmdutil.Factory
wants CreateOptions
wantsErr bool
}{
{
name: "no arguments",
cli: "",
wants: CreateOptions{
Description: "",
Public: false,
Filenames: []string{""},
},
wantsErr: false,
},
{
name: "no arguments with TTY stdin",
factory: func(f *cmdutil.Factory) *cmdutil.Factory {
f.IOStreams.SetStdinTTY(true)
return f
},
cli: "",
wants: CreateOptions{
Description: "",
Public: false,
Filenames: []string{""},
},
wantsErr: true,
},
{
name: "stdin argument",
cli: "-",
wants: CreateOptions{
Description: "",
Public: false,
Filenames: []string{"-"},
},
wantsErr: false,
},
{
name: "with description",
cli: `-d "my new gist" -`,
wants: CreateOptions{
Description: "my new gist",
Public: false,
Filenames: []string{"-"},
},
wantsErr: false,
},
{
name: "public",
cli: `--public -`,
wants: CreateOptions{
Description: "",
Public: true,
Filenames: []string{"-"},
},
wantsErr: false,
},
{
name: "list of files",
cli: "file1.txt file2.txt",
wants: CreateOptions{
Description: "",
Public: false,
Filenames: []string{"file1.txt", "file2.txt"},
},
wantsErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ios, _, _, _ := iostreams.Test()
f := &cmdutil.Factory{
IOStreams: ios,
}
if tt.factory != nil {
f = tt.factory(f)
}
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
var gotOpts *CreateOptions
cmd := NewCmdCreate(f, func(opts *CreateOptions) error {
gotOpts = opts
return nil
})
cmd.SetArgs(argv)
cmd.SetIn(&bytes.Buffer{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetErr(&bytes.Buffer{})
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.wants.Description, gotOpts.Description)
assert.Equal(t, tt.wants.Public, gotOpts.Public)
})
}
}
func Test_createRun(t *testing.T) {
tempDir := t.TempDir()
fixtureFile := filepath.Join(tempDir, "fixture.txt")
assert.NoError(t, os.WriteFile(fixtureFile, []byte("{}"), 0644))
emptyFile := filepath.Join(tempDir, "empty.txt")
assert.NoError(t, os.WriteFile(emptyFile, []byte(" \t\n"), 0644))
tests := []struct {
name string
opts *CreateOptions
stdin string
wantOut string
wantStderr string
wantParams map[string]interface{}
wantErr bool
wantBrowse string
responseStatus int
}{
{
name: "public",
opts: &CreateOptions{
Public: true,
Filenames: []string{fixtureFile},
},
wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n",
wantStderr: "- Creating gist fixture.txt\n✓ Created public gist fixture.txt\n",
wantErr: false,
wantParams: map[string]interface{}{
"description": "",
"updated_at": "0001-01-01T00:00:00Z",
"public": true,
"files": map[string]interface{}{
"fixture.txt": map[string]interface{}{
"content": "{}",
},
},
},
responseStatus: http.StatusOK,
},
{
name: "with description",
opts: &CreateOptions{
Description: "an incredibly interesting gist",
Filenames: []string{fixtureFile},
},
wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n",
wantStderr: "- Creating gist fixture.txt\n✓ Created secret gist fixture.txt\n",
wantErr: false,
wantParams: map[string]interface{}{
"description": "an incredibly interesting gist",
"updated_at": "0001-01-01T00:00:00Z",
"public": false,
"files": map[string]interface{}{
"fixture.txt": map[string]interface{}{
"content": "{}",
},
},
},
responseStatus: http.StatusOK,
},
{
name: "multiple files",
opts: &CreateOptions{
Filenames: []string{fixtureFile, "-"},
},
stdin: "cool stdin content",
wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n",
wantStderr: "- Creating gist with multiple files\n✓ Created secret gist fixture.txt\n",
wantErr: false,
wantParams: map[string]interface{}{
"description": "",
"updated_at": "0001-01-01T00:00:00Z",
"public": false,
"files": map[string]interface{}{
"fixture.txt": map[string]interface{}{
"content": "{}",
},
"gistfile1.txt": map[string]interface{}{
"content": "cool stdin content",
},
},
},
responseStatus: http.StatusOK,
},
{
name: "file with empty content",
opts: &CreateOptions{
Filenames: []string{emptyFile},
},
wantOut: "",
wantStderr: heredoc.Doc(`
- Creating gist empty.txt
X Failed to create gist: a gist file cannot be blank
`),
wantErr: true,
wantParams: map[string]interface{}{
"description": "",
"updated_at": "0001-01-01T00:00:00Z",
"public": false,
"files": map[string]interface{}{
"empty.txt": map[string]interface{}{"content": " \t\n"},
},
},
responseStatus: http.StatusUnprocessableEntity,
},
{
name: "stdin arg",
opts: &CreateOptions{
Filenames: []string{"-"},
},
stdin: "cool stdin content",
wantOut: "https://gist.github.com/aa5a315d61ae9438b18d\n",
wantStderr: "- Creating gist...\n✓ Created secret gist\n",
wantErr: false,
wantParams: map[string]interface{}{
"description": "",
"updated_at": "0001-01-01T00:00:00Z",
"public": false,
"files": map[string]interface{}{
"gistfile0.txt": map[string]interface{}{
"content": "cool stdin content",
},
},
},
responseStatus: http.StatusOK,
},
{
name: "web arg",
opts: &CreateOptions{
WebMode: true,
Filenames: []string{fixtureFile},
},
wantOut: "Opening gist.github.com/aa5a315d61ae9438b18d in your browser.\n",
wantStderr: "- Creating gist fixture.txt\n✓ Created secret gist fixture.txt\n",
wantErr: false,
wantBrowse: "https://gist.github.com/aa5a315d61ae9438b18d",
wantParams: map[string]interface{}{
"description": "",
"updated_at": "0001-01-01T00:00:00Z",
"public": false,
"files": map[string]interface{}{
"fixture.txt": map[string]interface{}{
"content": "{}",
},
},
},
responseStatus: http.StatusOK,
},
}
for _, tt := range tests {
reg := &httpmock.Registry{}
if tt.responseStatus == http.StatusOK {
reg.Register(
httpmock.REST("POST", "gists"),
httpmock.StringResponse(`{
"html_url": "https://gist.github.com/aa5a315d61ae9438b18d"
}`))
} else {
reg.Register(
httpmock.REST("POST", "gists"),
httpmock.StatusStringResponse(tt.responseStatus, "{}"))
}
mockClient := func() (*http.Client, error) {
return &http.Client{Transport: reg}, nil
}
tt.opts.HttpClient = mockClient
tt.opts.Config = func() (config.Config, error) {
return config.NewBlankConfig(), nil
}
ios, stdin, stdout, stderr := iostreams.Test()
tt.opts.IO = ios
browser := &browser.Stub{}
tt.opts.Browser = browser
_, teardown := run.Stub()
defer teardown(t)
t.Run(tt.name, func(t *testing.T) {
stdin.WriteString(tt.stdin)
if err := createRun(tt.opts); (err != nil) != tt.wantErr {
t.Errorf("createRun() error = %v, wantErr %v", err, tt.wantErr)
}
bodyBytes, _ := io.ReadAll(reg.Requests[0].Body)
reqBody := make(map[string]interface{})
err := json.Unmarshal(bodyBytes, &reqBody)
if err != nil {
t.Fatalf("error decoding JSON: %v", err)
}
assert.Equal(t, tt.wantOut, stdout.String())
assert.Equal(t, tt.wantStderr, stderr.String())
assert.Equal(t, tt.wantParams, reqBody)
reg.Verify(t)
browser.Verify(t, tt.wantBrowse)
})
}
}
func Test_detectEmptyFiles(t *testing.T) {
tests := []struct {
content string
isEmptyFile bool
}{
{
content: "{}",
isEmptyFile: false,
},
{
content: "\n\t",
isEmptyFile: true,
},
}
for _, tt := range tests {
files := map[string]*shared.GistFile{}
files["file"] = &shared.GistFile{
Content: tt.content,
}
isEmptyFile := detectEmptyFiles(files)
assert.Equal(t, tt.isEmptyFile, isEmptyFile)
}
}
|
TypeScript | UTF-8 | 4,318 | 2.65625 | 3 | [] | no_license | /*
* Copyright (C) 2018 The DAD Authors
* This file is part of The DAD library.
*
* The DAD is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The DAD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The DAD. If not, see <http://www.gnu.org/licenses/>.
*/
import { Parameter, Transaction } from '../../index';
import { ParameterType } from '../abi/parameter';
import { Address } from './../../crypto/address';
import { makeInvokeTransaction } from './../../transaction/transactionBuilder';
const functionNames = {
Init: 'init',
Transfer: 'transfer',
BalanceOf: 'balanceOf',
TotalSupply: 'totalSupply',
Symbol: 'symbol',
Decimals: 'decimals',
Name: 'name'
};
/**
* Transaction builder for nep-5 contracts
*/
export default class Nep5TxBuilder {
/**
* Init the nep-5 smart contract
* @param contractAddr Address of contract
* @param gasPrice Gas price
* @param gasLimit Gas limit
* @param payer Payer's address to pay for gas
*/
static init(contractAddr: Address, gasPrice: string, gasLimit: string, payer?: Address): Transaction {
const funcName = functionNames.Init;
return makeInvokeTransaction(funcName, [], contractAddr, gasPrice, gasLimit, payer);
}
/**
* Make transaction for transfer
* @param contractAddr Address of nep-5 contract
* @param from Sender's address
* @param to Receiver's address
* @param amount Amountof asset to transfer
* @param gasPrice Gas price
* @param gasLimit Gas limit
* @param payer Payer's address to pay for gas
*/
static makeTransferTx(
contractAddr: Address,
from: Address,
to: Address,
amount: number,
gasPrice: string,
gasLimit: string,
payer: Address
): Transaction {
const funcName = functionNames.Transfer;
const p1 = new Parameter('from', ParameterType.ByteArray, from.serialize());
const p2 = new Parameter('to', ParameterType.ByteArray, to.serialize());
const p3 = new Parameter('value', ParameterType.Integer, amount);
return makeInvokeTransaction(funcName, [p1, p2, p3], contractAddr, gasPrice, gasLimit, payer);
}
/**
* Query the balance
* @param contractAddr Address of nep-5 contract
* @param address Address to query balance
*/
static queryBalanceOf(contractAddr: Address, address: Address): Transaction {
const funcName = functionNames.BalanceOf;
const p1 = new Parameter('from', ParameterType.ByteArray, address.serialize());
return makeInvokeTransaction(funcName, [p1], contractAddr);
}
/**
* Query the total supply of nep-5 contract
* @param contractAddr Address of nep-5 contract
*/
static queryTotalSupply(contractAddr: Address): Transaction {
const funcName = functionNames.TotalSupply;
return makeInvokeTransaction(funcName, [], contractAddr);
}
/**
* Query the total supply of nep-5 contract
* @param contractAddr Address of nep-5 contract
*/
static queryDecimals(contractAddr: Address): Transaction {
const funcName = functionNames.Decimals;
return makeInvokeTransaction(funcName, [], contractAddr);
}
/**
* Query the total supply of nep-5 contract
* @param contractAddr Address of nep-5 contract
*/
static querySymbol(contractAddr: Address): Transaction {
const funcName = functionNames.Symbol;
return makeInvokeTransaction(funcName, [], contractAddr);
}
/**
* Query the total supply of nep-5 contract
* @param contractAddr Address of nep-5 contract
*/
static queryName(contractAddr: Address): Transaction {
const funcName = functionNames.Name;
return makeInvokeTransaction(funcName, [], contractAddr);
}
}
|
JavaScript | UTF-8 | 904 | 2.640625 | 3 | [] | no_license | function SetHeight(iframeId, minHeight)
{
var iframe = document.getElementById(iframeId);
if (iframe && !window.opera)
{
if (iframe.contentDocument && iframe.contentDocument.body.offsetHeight)
{
iframe.height = iframe.contentDocument.body.offsetHeight;
}
else if (iframe.Document && iframe.Document.body.scrollHeight)
{
iframe.height = iframe.Document.body.scrollHeight;
}
if (minHeight > 0 && iframe.height < minHeight)
{
iframe.height = minHeight;
}
}
}
function SetHeightEX(iframeId, minHeight, totalMS)
{
var delayMS = 100;
SetHeight(iframeId, minHeight);
totalMS = totalMS - delayMS;
if (totalMS > 0)
{
window.setTimeout("SetHeightEX('" + iframeId + "', '" + minHeight + "', '" + totalMS + "')", delayMS);
}
}
|
C# | UTF-8 | 2,341 | 2.625 | 3 | [] | no_license | using Microsoft.VisualStudio.TestTools.UnitTesting;
using WBAC.DeveloperInterview.Model;
using WBAC.DeveloperInterview.EvaluationStrategies.AgeEvaluation;
namespace WBAC.DeveloperInterview.Tests.EvaluationStrategies.AgeEvaluation
{
[TestClass]
public class ZeroYearStrategyTests
{
[TestMethod]
public void When_CalculatePriceReductionByAge_Called_To_Calculate_Then_Result_ShouldBe_Expected()
{
// arrange
var expected = 2620.0m;
var zeroYearsStatery = new ZeroYearStrategy();
Vehicle vehicle = new Vehicle()
{
AgeInYears = 0,
BaseValuation = 13100,
};
// act
var result = zeroYearsStatery.CalculatePriceReductionByAge(vehicle);
// assert
Assert.AreEqual(expected, result);
}
[TestMethod]
public void When_CalculatePriceReductionByAge_Called_With_NullBasePrice_Then_Result_ShouldBe_Expected()
{
// arrange
var expected = 0m;
var zeroYearsStatery = new ZeroYearStrategy();
Vehicle vehicle = new Vehicle()
{
AgeInYears = 0,
BaseValuation = null
};
// act
var result = zeroYearsStatery.CalculatePriceReductionByAge(vehicle);
// assert
Assert.AreEqual(expected, result);
}
[TestMethod]
public void When_IsApplicable_Called_For_OlderCars_Then_Result_ShouldBe_False()
{
// arrange
var zeroYearsStatery = new ZeroYearStrategy();
var vehicaleAge = 1;
var expected = false;
// act
var result = zeroYearsStatery.IsApplicable(vehicaleAge);
// assert
Assert.AreEqual(expected, result);
}
[TestMethod]
public void When_IsApplicable_Called_For_NewCars_Then_Result_ShouldBe_True()
{
// arrange
var zeroYearsStatery = new ZeroYearStrategy();
var vehicaleAge = 0;
var expected = true;
// act
var result = zeroYearsStatery.IsApplicable(vehicaleAge);
// assert
Assert.AreEqual(expected, result);
}
}
}
|
Python | UTF-8 | 1,945 | 3.109375 | 3 | [] | no_license | #!/usr/bin/python3
# program to extract content from Setopati
# for Nepali ngram model
# http://virtualanup.com/nepali-ngram-models/
import urllib3
from bs4 import BeautifulSoup
import os
http = urllib3.PoolManager()
def checkDir(directory):
if not os.path.exists(directory):
os.makedirs(directory)
outputdirname = "setopatioutput"
setopatiurl = "http://setopati.com/bichar/"
# make sure the output directory exist
checkDir(outputdirname)
# iterate through the news artices.
for i in range(2000, 12000):
filename = os.path.join(outputdirname, str(i))
# if the output file for the news article already exist, skip it.
# this will prevent us from redoing much task if the script gets broken in the
# middle of extraction.
if os.path.exists(filename):
print("Skipping ", i)
continue
# try to get the HTML content of the URL
articleurl = setopatiurl+str(i)
print("Extracting content from ", i)
r = http.request('GET', articleurl)
# create a file
outputfile = open(filename, 'wb')
if r.status == 200:
try:
# success. Now try to extract the news portition using beautifulsoup
extractor = BeautifulSoup(r.data)
# the content inside division with ID 'newsbox' is the main content
newsbox = extractor.find("div", {"id": "newsbox"})
if len(newsbox) > 1:
# if there is news inside the news box, then it's length will be > 1
# remove the content inside span, h1, h2 etc
for htmltag in ['strong', 'h1','span', 'h2']:
for tag in newsbox.find_all(htmltag):
tag.decompose()
content = bytes(newsbox.get_text(), 'UTF-8')
outputfile.write(bytes(' ', 'UTF-8').join(content.split(bytes('\n', 'UTF-8'))))
except:
pass # do nohing in case of error
outputfile.close()
|
Java | UTF-8 | 1,780 | 2.25 | 2 | [] | no_license | package rocks.zipcodewilmington;
import com.sun.tools.javac.comp.Resolve;
import org.junit.Assert;
import org.junit.Test;
import rocks.zipcodewilmington.animals.Cat;
import rocks.zipcodewilmington.animals.Dog;
import rocks.zipcodewilmington.animals.animal_storage.CatHouse;
import rocks.zipcodewilmington.animals.animal_storage.DogHouse;
import sun.lwawt.LWWindowPeer;
import java.util.Date;
/**
* @author leon on 4/19/18.
*/
public class CatHouseTest {
@Test
public void addCatTest() {
Integer expectedNumberOfCats = 1;
CatHouse.add(new Cat(null, null, null));
Integer actualNumberOfCats = CatHouse.getNumberOfCats();
Assert.assertEquals(expectedNumberOfCats, actualNumberOfCats);
}
@Test
public void removeCatTest() {
Integer givenId = 1;
Cat Cat = new Cat(null, null, null);
CatHouse.clear();
CatHouse.add(Cat);
CatHouse.remove(Cat);
Assert.assertNull(CatHouse.getCatById(givenId));
}
@Test
public void getCatByIdTest() {
Integer givenId = 1;
CatHouse.clear();
CatHouse.add(new Cat(null, null, null));
Integer actualCats =CatHouse.getNumberOfCats();
Assert.assertEquals(givenId, actualCats);
}
@Test
public void getNumberOfCatsTest() {
Integer expected = 1;
CatHouse.clear();
CatHouse.add(new Cat(null, null, null));
Integer actualCats = CatHouse.getNumberOfCats();
Assert.assertEquals(expected, actualCats);
}
}
// TODO - Create tests for `void remove(Integer id)`
// TODO - Create tests for `void remove(Cat cat)`
// TODO - Create tests for `Cat getCatById(Integer id)`
// TODO - Create tests for `Integer getNumberOfCats()`
|
Python | UTF-8 | 4,540 | 2.640625 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[4]:
##Import all necessary packages
import os
import glob
import random
import pandas as pd
import concurrent.futures
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread
import PIL as image
import tensorflow_addons as tfa
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# In[5]:
tf.debugging.set_log_device_placement(True)
gpus = tf.config.experimental.list_logical_devices('GPU')
print(gpus)
# In[11]:
##Path to dataset
data_dir = '/storage/set_1_20J_test_train/'
train_path = data_dir+'train/classes/'
test_path = data_dir+'test/classes'
# In[12]:
image_shape = (192,192,3)
# In[ ]:
# In[13]:
#Create image generator with all necessary transformations
image_gen = ImageDataGenerator(rotation_range=45, # rotate the image 20 degrees
width_shift_range=0.10, # Shift the pic width by a max of 5%
height_shift_range=0.10, # Shift the pic height by a max of 5%
rescale=1/255, # Rescale the image by normalzing it.
horizontal_flip=True, # Allow horizontal flipping
vertical_flip=True, # Allow vertical flipping
fill_mode='nearest' # Fill in missing pixels with the nearest filled value
)
# In[14]:
image_gen.flow_from_directory(train_path)
# In[15]:
image_gen.flow_from_directory(test_path)
# In[16]:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense, Conv2D, MaxPooling2D, AveragePooling2D, BatchNormalization
# In[17]:
strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
model = Sequential()
model.add(AveragePooling2D(pool_size = (2,2),strides = 2,input_shape = image_shape))
model.add(Conv2D(filters=32, kernel_size=(5,5), strides=(1, 1), padding='same'))
# model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=2))
model.add(Conv2D(filters=32, kernel_size=(5,5), strides=(1, 1), padding='same'))
# model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=(3, 3), strides=2, padding='same'))
model.add(Conv2D(filters=64, kernel_size=(5,5), strides=(1, 1), padding='same'))
# model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=(3,3), strides=2, padding='same'))
model.add(Conv2D(filters=64, kernel_size=(5,5), strides=(1, 1)))
# model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(AveragePooling2D(pool_size=(3, 3), strides=2, padding='same'))
model.add(Conv2D(filters=128, kernel_size=(4, 4), strides=(1, 1)))
# model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Flatten())
# Dropouts help reduce overfitting by randomly turning neurons off during training.
# Here we say randomly turn off 40% of neurons.
model.add(Dropout(0.4))
# Last layer, remember its 5 classes so we use softmax
model.add(Dense(5))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# In[18]:
model.summary()
# In[19]:
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
filepath="weights-improvement-{epoch:02d}-{val_accuracy:.2f}.h5"
checkpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max')
early_stop = EarlyStopping(monitor='val_loss',patience=2)
# In[20]:
batch_size = 100
# In[21]:
train_image_gen = image_gen.flow_from_directory(train_path,
target_size = (192,192),
batch_size=batch_size)
# In[22]:
test_image_gen = image_gen.flow_from_directory(test_path,
target_size = (192,192),
batch_size=batch_size)
# In[23]:
train_image_gen.class_indices
# In[24]:
import warnings
warnings.filterwarnings('ignore')
# In[26]:
results = model.fit(train_image_gen,epochs=50,
validation_data=test_image_gen,
callbacks=[checkpoint])
# In[ ]:
|
Markdown | UTF-8 | 2,072 | 2.90625 | 3 | [] | no_license | # angular4-ns
A simple Angular 4 project
## Installation:
### Before npm install please have angular-cli installed
```bash
npm install -g @angular/cli
npm install
```
### Running the application
```bash
ng serve
```
Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
### Generating Components, Directives, Pipes and Services
You can use the `ng generate` (or just `ng g`) command to generate Angular components:
```bash
ng generate component my-new-component
ng g component my-new-component # using the alias
# components support relative path generation
# if in the directory src/app/feature/ and you run
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp
# but if you were to run
ng g component ../newer-cmp
# your component will be generated in src/app/newer-cmp
# if in the directory src/app you can also run
ng g component feature/new-cmp
# and your component will be generated in src/app/feature/new-cmp
```
You can find all possible blueprints in the table below:
Scaffold | Usage
--- | ---
[Component](https://github.com/angular/angular-cli/wiki/generate-component) | `ng g component my-new-component`
[Directive](https://github.com/angular/angular-cli/wiki/generate-directive) | `ng g directive my-new-directive`
[Pipe](https://github.com/angular/angular-cli/wiki/generate-pipe) | `ng g pipe my-new-pipe`
[Service](https://github.com/angular/angular-cli/wiki/generate-service) | `ng g service my-new-service`
[Class](https://github.com/angular/angular-cli/wiki/generate-class) | `ng g class my-new-class`
[Guard](https://github.com/angular/angular-cli/wiki/generate-guard) | `ng g guard my-new-guard`
[Interface](https://github.com/angular/angular-cli/wiki/generate-interface) | `ng g interface my-new-interface`
[Enum](https://github.com/angular/angular-cli/wiki/generate-enum) | `ng g enum my-new-enum`
[Module](https://github.com/angular/angular-cli/wiki/generate-module) | `ng g module my-module`
|
C++ | UTF-8 | 1,032 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <cmath>
#include "matrix.hpp"
int main() {
int numOfRows = 2;
int numOfColumns = 3;
auto **array = new double*[numOfRows];
for(int i = 0; i < numOfRows; i++) {
array[i] = new double[numOfColumns];
for(int j = 0; j < numOfColumns; j++)
array[i][j] = 1 + i + j;
}
std::cout << "Array:\n";
for(int i = 0; i < numOfRows; i++) {
for(int j = 0; j < numOfColumns; j++)
std::cout << array[i][j] << " ";
std::cout << "\n";
}
auto matrix1 = Matrix('A', numOfRows, numOfColumns, array);
std::cout << matrix1;
auto matrix2 = matrix1 * 2;
--matrix2;
matrix2.increaseName();
std::cout << matrix2;
matrix2 = ~matrix2;
std::cout << "Transpose Matrix B:\n";
std::cout << matrix2;
std::cout << "C = A * B\n";
auto matrix3 = matrix1 * matrix2;
std::cout << matrix3;
std::cout << "Modified Matrix C by sqrt():\n";
std::cout << matrix3.getModified(sqrt);
return 0;
}
|
Go | UTF-8 | 635 | 3.21875 | 3 | [] | no_license | package main
import "fmt"
func main() {
var t int
fmt.Scan(&t)
for i := 0; i < t; i++ {
var n, m int
fmt.Scan(&n, &m)
var mat = make([][]int, n, n)
for value := range mat {
mat[value] = make([]int, m)
}
fmt.Println(placeBridges(n, m, mat))
}
}
func placeBridges(n int, m int, mat [][]int) int {
var i int
for i = 0; i < n; i++ {
for j := i; j < m-(n-i-1); j++ {
if i == 0 {
mat[i][j] = 1
} else {
var sum int = 0
for k := i - 1; k < j; k++ {
sum += mat[i-1][k]
}
mat[i][j] = sum
}
}
}
var res int = 0
for j := i - 1; j < m; j++ {
res += mat[i-1][j]
}
return res
}
|
Markdown | UTF-8 | 18,102 | 2.609375 | 3 | [
"MIT"
] | permissive | ---
heading: Element Mapper
seo: Element Mapper Advanced Examples | Element Mapper | Cloud Elements API Docs
title: Advanced
description: View different advanced examples of Element Mapper in action.
layout: sidebarelementdoc
apis: API Docs
platform: organizations
breadcrumbs: /docs/guides/home.html
parent: Back to Guides
order: 4
---
{% include callout.html content="The documentation in this section is for Cloud Elements 1.0. Find Cloud Elements 2.0 documentation at <a href=../../guides/common-resources/index.html>Defining Common Resources & Transformations</a>." type="info" %}
# Advanced Examples
Below are a handful of advanced examples of leveraging Element Mapper.
# Create Custom Objects
### My Object
Add object definitions to resources like accounts and contacts so they can be mapped to other cloud service applications.
#### Currently Supported Services
The My Object resource can be used with Elements in all of our Hubs with the exception of Documents and Messaging.
This guide will walk you through the creation of an Object via <a href="#" data-toggle="tooltip" data-original-title="{{site.data.glossary.ce-ui}}">Cloud Elements</a> .
Log in to [Cloud Elements](https://console.cloud-elements.com/elements/jsp/login.jsp)
Click “My Objects”

Click “Add/Edit Object”

Click “New Object”

Name the Object
Select Object Level: Organization will include your company and your customers.
Click “Add Field”

Name your field to map.
Select which data type, e.g. string, number, etc.
Click “green check mark”

Click “Save” when you have finished entering the fields you wish to map to the resource.

Click “X” to close.

Click “My Instances”
Click “Transformations”
(Salesforce will be used for this demonstration)

Click “My Objects”
Select “MyContact”
(The object you created earlier in the workflow)

Click the drop down menu on the right.
Select “Contact” from the list of Salesforce resources

Drag and drop the fields you wish to map to Salesforce on top of the fields you created for the object.

Optionally decide whether or not to ignore the unmapped fields from Salesforce. We will ignore unmapped fields for this demonstration.
Click “Save”

Click “X” to close

Click “Documentation” to open API docs for the Salesforce instance
Scroll down towards the bottom of the list and select “GET /{objectName} to expand the docs.

Input “MyContact” in the objectName field
Click “Try it out!”

View the contact data displaying the fields mapped to that object.

# Array Support
#### Mapping Arrays to Flat Fields
Regular expressions are now available within an object via Element Mapper.
These expressions will give you the ability to map an array to a flat field.
Custom objects can be formatted in JSON, then created via the transformation APIs or via the Element Mapper UI.
The transformations APIs can be found under Platform APIs > Organizations > Create Transformations for Element in Organization of the documentation menu. Or, log in to the Cloud Elements API Manager and navigate to the API DOCS > Platform APIs > Organizations.
Let’s take a look at an example:
```JSON
{
"account": {
"vendorName": "Account",
"fields": [
{
"path": "AppleIpadName",
"vendorPath": "Products[id=4].name" //Get the value of the name field from the Products array where id = 4
},
{
"path": "AppleProductName",
"vendorPath": "Products[?(@.id==2)].name" //Get the value of the name field from the Products array where id = 2
},
{
"path": "AppleNewProductName",
"vendorPath": "details.Products[?(@.id==2)].name" //Get the details of an object from the Products array where id = 2
},
{
"path": "AppleProductTouchId",
"vendorPath": "Products[?(@.id==2)].features.touchId" // Get the touchId value from the Products array with id=2 which is inside the features object
},
{
"path": "AppleTouchProductId",
"vendorPath": "Products[?(@.features.touchId==true)].id" //Get the Id of the array where touchId = true
},
{
"path": "AppleProductId",
"vendorPath": "Products[0].id" //Id value of the Products array at index 0
},
{
"path": "AppleProductsCount",
"vendorPath": "Products[*].size()" //Count of the Products array
}
]
}
}
```
Mapping flat fields to an array can also be done via the Element Mapper UI.
A QuickBooks custom customer will be used. This document assumes a QuickBooks instance has been created. If an instance has not been created, please review the QuickBooks Documentation under Elements > QuickBooks > Endpoint Setup and Create Instance found in the left hand side of the documentation menu.
Log in to [Cloud Elements](https://console.cloud-elements.com/elements/jsp/login.jsp).
Navigate to ‘My Instances’
Navigate to the QuickBooks Instance and select ‘Transformations’ to open the Element Mapper UI

Select ‘customer’ from the dropdown list of objects

Select ‘New Object’

Name the object, myCustomers will be used for this example
Check ‘Yes’ for IGNORE UNMAPPED – this will only display the fields mapped to the myCustomers object. NOTE: A few fields have already been dragged and dropped from the right column for this example.
Click ‘+ Add Field’ A phone number will be added to this object and mapped to an array
Complete the following
* Name the field: myPhone
* Select data type: string
* Select the field to map: primaryPhone.freeFormNumber
Click the green check mark to save field
Click ‘Save’ to save the object
Click ‘Try it out’ to see your newly created object

View the transformed object and the original object
The primaryPhone.freeFormNumber field was mapped to the myPhone field – an array mapped to a flat field.

If you have any questions regarding mapping flat fields to an array, please contact [Cloud Elements Support](mailto:support@cloud-elements.com).
# Transformations API Usage
The purpose of the Transformation APIs (Beta) is to give you the option of defining what an object would look like in your app.
The Transformation APIs allow you to:
* manage custom object and custom data fields
* map custom data fields to and from the format that your application uses and expects
* programmatically persist and maintain transformations for each of your client’s CRM, Marketing, and Help Desk services
#### An important note concerning workflow:
__The objects referenced in your transform must exist (i.e. have been registered via the process outlined above), before registering the transform. Otherwise the transform registration will fail.
Below is an example of the Supplemental Address Object defined in Salesforce and SugarCRM, and what it would look like in your application by utilizing the Transformation APIs.__
In order to access the Organizations APIs, you must sign up for Cloud Elements Service. You will need your __Organization__ and __User Secrets__ to make successful Transformations API calls. These are generated for you when you sign up for our service. __Details on how to sign up and where to find your Organization and User Secrets are documented in the next section.__

#### Signup for the Cloud Elements Service
To sign up for the Cloud Elements service, using a web browser, go to: [https://console.cloud-elements.com/elements/jsp/signup.jsp](https://console.cloud-elements.com/elements/jsp/signup.jsp).
You can create a new account with Cloud Elements using the “Sign Up” link shown here, or sign up for Cloud Elements service using your Google or GitHub account. When signing up via GitHub, you must set a public email address in GitHub profile. Screen shots on how to set a public email are below. If you choose not to use GitHub to sign up, you will then be required to validate your new account via a confirmation link that will be sent to your email. You will reset your password to one of your choice after your initial login.

##### Setting a Public Email in GitHub
Navigate to your settings in GitHub.

Type in your public email in the designated field and click “Update Profile”.
All set!
The first step is to sign up for Cloud Elements Service.

After completing this process, click “Secrets” in the top right corner. Make note of the Org and User secrets as they needed to provision an Element Instance. The Secrets option is available from the top ribbon at all times.

#### How to Use the Transformation APIs
The first step is to create an object and define its properties. For instance, let’s assume you want your account object to contain the fields ID, First Name, and Last Name. You would define that object with those definitions. Next, create a transformation to map an account object from an endpoint to the account object created for you app. For example, the endpoint’s account object has SID, first_name, and last_name as its properties. You can map your object to reference the SID as ID, first_name as firstName, and last_name as lastName.
This document will show examples of how to create, retrieve, and delete an object. Next, examples on how to use the transformation APIs to map endpoint objects to your objects will be shown.
##### Example Object Definition API Calls
`POST /organizations/objects/{objectName}/definitions`
Create the default object of type {objectName} for an organization.
Below is an example cURL command demonstrating the `POST /organizations/objects/{objectName}/definitions` API call and successful response. The `-d` is the data needed for successful object creation. This is test data that was created for this demonstration. Please make sure your quotes are straight in the cURL command.
```bash
curl -X POST
-H 'Authorization: User , Organization '
-H 'Content-Type: application/json'
-d @account.json
'https://api.cloud-elements.com/elements/api-v2/organizations/objects/account/definitions'
```
account.json – JSON file needed to create object
```JSON
{
"fields": [
{
"path": "id",
"type": "string"
}
]
}
```
Example of Successful Response:
```JSON
{
"fields": [
{
"type": "string",
"path": "id"
}
],
"level": "organization"
}
```
`GET /organizations/objects/definitions`
Retrieve all of the object definitions within an organization.
Below is an example cURL command demonstrating the `GET /organizations/objects/definitions` API call and successful response. Please make sure your quotes are straight in the cURL command.
```bash
curl -X GET
-H 'Authorization: User , Organization '
-H 'Content-Type: application/json'
'https://api.cloud-elements.com/elements/api-v2/organizations/objects/definitions'
```
Example of Successful Response:
```JSON
{
"account": {
"fields": [
{
"type": "string",
"path": "id"
}
]
},
"contact": {
"fields": [
{
"type": "string",
"path": "id"
}
]
},
"lead": {
"fields": [
{
"type": "string",
"path": "id"
}
]
},
"opportunity": {
"fields": [
{
"type": "string",
"path": "id"
}
]
},
"product": {
"fields": [
{
"type": "string",
"path": "id"
}
]
},
"incident": {
"fields": [
{
"type": "string",
"path": "id"
}
]
},
"user": {
"fields": [
{
"type": "string",
"path": "id"
}
]
},
"level": "organization"
}
```
`DELETE /organizations/objects/definitions`
Delete all object definitions within an organization.
__NOTE: This API call will delete all of the objects you have defined at the Organization Level. Please be careful.__
Below is an example cURL command demonstrating the `DELETE /organizations/objects/definitions` API call and successful response. Please make sure your quotes are straight in the cURL command.
```bash
curl -X DELETE
-H 'Authorization: User , Organization '
-H 'Content-Type: application/json'
'https://api.cloud-elements.com/elements/api-v2/organizations/objects/definitions'
```
Example of Successful Response:
```bash
HTTP 200 on success
```
Transformations allow you to map an endpoint’s object to the custom object that you just created. For example to transform the account object you just created to the endpoint object, you would use the JSON below.
##### Example Transformations API Calls
`POST /organizations/elements/{key}/transformations/{objectName}`
Update the default transformation for an element within an organization. The key field denotes the Element being referenced in the API call, i.e. sfdc (Salesforce).
Below is an example cURL command demonstrating the `POST /organizations/elements/{key}/transformations/{objectName}`API call and successful response. The `-d `is the data needed for a successful update of a transformation. This is test data that was created for this demonstration. Please make sure your quotes are straight in the cURL command.
```bash
curl -X POST
-H 'Authorization: User , Organization '
-H 'Content-Type:application/json'
-d @posttransform.json
'https://api.cloud-elements.com/elements/api-v2/organizations/elements/sfdc/transformations/account'
```
createtransform.json: – JSON file needed to update transformation
```JSON
{
"vendorName": "Account",
"fields": [
{
"path": "id",
"vendorPath": "Id"
}
]
}
```
Example of Successful Response:
```JSON
{
"level": "organization",
"vendorName": "Account",
"startDate": "2014-12-12 18:03:32.012321",
"fields": [
{
"path": "id",
"vendorPath": "Id"
}
]
}
```
`GET /organizations/elements/{key}/transformations/{objectName}`
Retrieve the default transformation for a specific element within an organization. The key field denotes the Element being referenced in the API call, i.e. sfdc (Salesforce).
Below is an example cURL command demonstrating the `GET /organizations/elements/{key}/transformations/{objectName}` API call and successful response. Please make sure your quotes are straight in the cURL command.
```bash
curl -X GET
-H 'Authorization: User , Organization '
-H 'Content-Type:application/json'
'https://api.cloud-elements.com/elements/api-v2/organizations/elements/sfdc/transformations/account'
```
Example of Successful Response:
```JSON
{
"level": "organization",
"vendorName": "Account",
"startDate": "2014-12-12 18:03:32.012321",
"fields": [
{
"path": "id",
"vendorPath": "Id"
}
]
}
```
`DELETE /organizations/elements/{key}/transformations/{objectName}`
Delete the default transformation for an element within an organization. The key field denotes the Element being referenced in the API call, i.e. sfdc (Salesforce).
Below is an example cURL command demonstrating the `DELETE /organizations/elements/{key}/transformations/{objectName}` API call and successful response. Please make sure your quotes are straight in the cURL command.
```curl -X DELETE
-H 'Authorization: User , Organization '
-H 'Content-Type:application/json'
'https://api.cloud-elements.com/elements/api-v2/organizations/elements/sfdc/transformations/account'
```
Example of Successful Response:
```bash
HTTP 200 on success
```
#### Support
If you need any support integrating our APIs, please let us know. You can [email](mailto:support@cloud-elements.com) or give us a call at +1.866.830.3456. We will do our best to get back to you within 24 hours. Your success is our success.
|
C++ | UTF-8 | 2,539 | 2.6875 | 3 | [
"MIT"
] | permissive |
#include "SkipList.h"
#include "Arena.h"
#include "Random.h"
#include <gtest/gtest.h>
#include <atomic>
#include <set>
namespace zhanmm {
typedef uint64_t Key;
struct Comparator {
int operator()(const Key& a, const Key& b) const {
if (a < b) {
return -1;
} else if (a > b) {
return +1;
} else {
return 0;
}
}
};
TEST(SkipTest, Empty) {
Arena arena;
Comparator cmp;
SkipList<Key, Comparator> list(cmp, &arena);
ASSERT_TRUE(!list.Contains(10));
SkipList<Key, Comparator>::Iterator iter(&list);
ASSERT_TRUE(!iter.Valid());
iter.SeekToFirst();
ASSERT_TRUE(!iter.Valid());
iter.Seek(100);
ASSERT_TRUE(!iter.Valid());
iter.SeekToLast();
ASSERT_TRUE(!iter.Valid());
}
TEST(SkipTest, InsertAndLookup) {
const int N = 2000;
const int R = 5000;
Random rnd(1000);
std::set<Key> keys;
Arena arena;
Comparator cmp;
SkipList<Key, Comparator> list(cmp, &arena);
for (int i = 0; i < N; i++) {
Key key = rnd.Next() % R;
if (keys.insert(key).second) {
list.Insert(key);
}
}
for (int i = 0; i < R; i++) {
if (list.Contains(i)) {
ASSERT_EQ(keys.count(i), 1);
} else {
ASSERT_EQ(keys.count(i), 0);
}
}
{
SkipList<Key, Comparator>::Iterator iter(&list);
ASSERT_TRUE(!iter.Valid());
iter.Seek(0);
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.begin()), iter.key());
iter.SeekToFirst();
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.begin()), iter.key());
iter.SeekToLast();
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*(keys.rbegin()), iter.key());
}
for (int i = 0; i < R; i++) {
SkipList<Key, Comparator>::Iterator iter(&list);
iter.Seek(i);
std::set<Key>::iterator model_iter = keys.lower_bound(i);
for (int j = 0; j < 3; j++) {
if (model_iter == keys.end()) {
ASSERT_TRUE(!iter.Valid());
break;
} else {
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*model_iter, iter.key());
++model_iter;
iter.Next();
}
}
}
{
SkipList<Key, Comparator>::Iterator iter(&list);
iter.SeekToLast();
for (std::set<Key>::reverse_iterator model_iter = keys.rbegin();
model_iter != keys.rend(); ++model_iter) {
ASSERT_TRUE(iter.Valid());
ASSERT_EQ(*model_iter, iter.key());
iter.Prev();
}
ASSERT_TRUE(!iter.Valid());
}
}
} // zhanmm
GTEST_API_ int main(int argc, char ** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Python | UTF-8 | 776 | 2.78125 | 3 | [] | no_license | import csv
import json
filtered = []
with open('large_airports.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in spamreader:
filtered.append(row)
jsonObject = {}
for row in filtered:
jsonObject[row[7]] = {
'ident': row[0],
'lat': row[1],
'lon': row[2],
'elevation_ft': row[3],
'continent': row[4],
'iso_country': row[5],
'iso_region': row[6]
}
with open('locations.json', 'wb') as outfile:
json.dump(jsonObject, outfile, indent=4)
with open('large_airports.csv', 'wb') as airportcsv:
spamwriter = csv.writer(airportcsv, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in filtered:
spamwriter.writerow(row)
|
C# | UTF-8 | 3,048 | 3.265625 | 3 | [] | no_license | namespace AquaShop.Models.Aquariums
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AquaShop.Models.Decorations.Contracts;
using AquaShop.Models.Fish.Contracts;
using AquaShop.Utilities.Messages;
using Contracts;
public abstract class Aquarium : IAquarium
{
private string name;
private int capacity;
private List<IDecoration> decorations;
private List<IFish> fish;
public Aquarium(string name, int capacity)
{
this.Name = name;
this.Capacity = capacity;
this.fish = new List<IFish>();
this.decorations = new List<IDecoration>();
}
public string Name
{
get => this.name;
private set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(string.Format(ExceptionMessages.InvalidAquariumName));
}
this.name = value;
}
}
public int Capacity
{
get => this.capacity;
private set
{
if (value <= 0)
{
throw new ArgumentException(string.Format(ExceptionMessages.InvalidAquariumCapacity));
}
this.capacity = value;
}
}
public int Comfort => this.decorations.Sum(x => x.Comfort);
public ICollection<IDecoration> Decorations => this.decorations;
public ICollection<IFish> Fish => this.fish;
public void AddDecoration(IDecoration decoration)
{
this.decorations.Add(decoration);
}
public void AddFish(IFish fish)
{
if (this.Fish.Count < this.Capacity)
{
this.fish.Add(fish);
}
else
{
throw new InvalidOperationException(string.Format(OutputMessages.NotEnoughCapacity));
}
}
public void Feed()
{
this.fish.ForEach(x => x.Eat());
}
public string GetInfo()
{
var output = new StringBuilder();
output.AppendLine($"{this.Name} ({this.GetType().Name}):");
if (this.fish.Count > 0)
{
output.AppendLine($"Fish: {string.Join(", ", this.fish.Select(x=>x.Name))}");
}
else
{
output.AppendLine("Fish: none");
}
output.AppendLine($"Decorations: {this.decorations.Count}");
output.AppendLine($"Comfort: {this.Comfort}");
return output.ToString().TrimEnd();
}
public bool RemoveFish(IFish fish)
{
if (this.fish.Any(x => x.Name == fish.Name))
{
this.fish.Remove(fish);
return true;
}
return false;
}
}
}
|
SQL | WINDOWS-1250 | 2,163 | 3.765625 | 4 | [] | no_license | --1
--A)
CREATE TABLE Uczestnicy
(
PESEL VARCHAR(11) NOT NULL CONSTRAINT pk_uczest_PESEL PRIMARY KEY, --pk -> primary key
nazwisko VARCHAR(30) NOT NULL CONSTRAINT ck_uczest_nazw CHECK (nazwisko LIKE '[A-Z]%'),
miasto VARCHAR(30) CONSTRAINT ck_uczest_miast CHECK (miasto LIKE '[A-Z]%') DEFAULT 'Pozna',
);
--lub
CREATE TABLE Uczestnicy
(
PESEL INT NOT NULL CONSTRAINT pk_uczest_PESEL PRIMARY KEY, --pk -> primary key
nazwisko VARCHAR(30) NOT NULL CONSTRAINT ck_uczest_nazw CHECK (nazwisko LIKE '[A-Z]%'),
miasto VARCHAR(30) CONSTRAINT ck_uczest_miast CHECK (miasto LIKE '[A-Z]%') DEFAULT 'Pozna',
);
--lub
CREATE TABLE Uczestnicy
(
PESEL CHAR(11) PRIMARY KEY,
nazwisko VARCHAR(200) NOT NULL,
miasto VARCHAR(100) DEFAULT 'Pozna'
)
--B)
CREATE TABLE Kursy
(
Kod INT IDENTITY(1,1) PRIMARY KEY,
nazwa VARCHAR(30) UNIQUE,
liczba_dni INT CHECK (liczba_dni BETWEEN 1 AND 5),
cena AS (liczba_dni * 1000)
);
--lub
CREATE TABLE Kursy
(
Kod INT PRIMARY KEY IDENTITY(1,1),
nazwa VARCHAR(100) UNIQUE NOT NULL,
liczba_dni TINYINT CHECK (liczba_dni BETWEEN 1 AND 5),
cena AS liczba_dni * 1000
)
--C)
CREATE TABLE Udzial
(
uczestnik INT FOREIGN KEY REFERENCES Uczestnicy(Pesel),
kurs INT FOREIGN KEY REFERENCES Kursy(Kod),
data_od DATE,
data_do DATE,
status VARCHAR(15) CHECK (status IN ('w trakcie', 'ukonczony', 'nieukonczony')),
CONSTRAINT kolejnosc_dat CHECK (data_od<data_do)
);
--lub
CREATE TABLE Udzial
(
uczestnik VARCHAR(11) FOREIGN KEY REFERENCES Uczestnicy(Pesel),
kurs INT FOREIGN KEY REFERENCES Kursy(Kod),
data_od DATE,
data_do DATE,
status VARCHAR(15) CHECK (status IN ('w trakcie', 'ukonczony', 'nieukonczony')),
CONSTRAINT kolejnosc_dat CHECK (data_od<data_do)
);
--2
--A
ALTER TABLE Uczestnicy
ADD e-mail VARCHAR(50);
--B
ALTER TABLE Uczestnicy
ADD CONSTRAINT pesel_ok CHECK (PESEL NOT LIKE '&[^0-9]&' AND LEN(PESEL)=11);
--C
ALTER TABLE Udzial
ADD CONSTRAINT trojka PRIMARY KEY(uczestnik, kurs, data_od)
--D
ALTER TABLE Kursy
DROP CONSTRAINT ck_kursy_licz;
--E
ALTER TABLE Kursy
ADD Kod_2
--3
DROP TABLE Udzial
DROP TABLE Kursy
DROP TABLE Uczestnicy |
C | UTF-8 | 1,813 | 3.59375 | 4 | [] | no_license | #include <stdio.h>
void verifica(int a, int b, int c, int d, int e);
void ordena(int* a, int* b, int* c, int* d, int* e);
int main()
{
int a, b, c, d, e;
scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);
if((a < 0) || (b < 0) || (c < 0) || (d < 0) || (e < 0) || (a > 1000000) || (b > 1000000) || (c > 1000000)
|| (d > 1000000) || (e > 1000000)){
return 0;
}
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
ordena(&a, &b, &c, &d, &e);
verifica(a, b, c, d, e);
return 0;
}
void verifica(int a, int b, int c, int d, int e)
{
int razao;
if((a < b) && (b < c) && (c < d) && (d < e))
{//ordem crescente de entrada
if(((b/a) == (c/b)) && ((c/b) == (d/c)) &&((d/c) == (e/d)))
{
razao = b/a;
printf("S\n%d %d %d %d %d\n%d\n", a, b, c, d, e, razao);
}
else{
printf("N\n");
}
}
else
{
printf("N\n");
}
}
void ordena (int* a, int* b, int* c, int* d, int* e){
int aux;
if (*a > *b){
aux = *a;
*a = *b;
*b = aux;
}
else if (*a > *c){
aux = *a;
*a = *c;
*c = aux;
}
else if (*a > *d){
aux = *a;
*a = *d;
*d = aux;
}
else if (*a > *e){
aux = *a;
*a = *e;
*e = aux;
}
else if (*b > *c){
aux = *b;
*b = *c;
*b = aux;
}
else if (*b > *d){
aux = *b;
*b = *d;
*d = aux;
}
else if (*b > *e){
aux = *b;
*b = *e;
*e = aux;
}
else if (*c > *d){
aux = *c;
*c = *d;
*d = aux;
}
else if (*c > *e){
aux = *c;
*c = *e;
*e = aux;
}
else if (*d > *e){
aux = *d;
*d = *e;
*e = aux;
}
}
|
Java | UTF-8 | 4,752 | 2.75 | 3 | [] | no_license | import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.utils.SourceRoot;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<MyClass> allClasses = new ArrayList<>();
try {
// Get project directory from user
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the path of your Project (preferably the path to your Model):");
System.out.println("try this: testModel/ ... ");
String projectDirectory = scanner.nextLine();
//TODO: just for testing
if (projectDirectory.equals(" ")){
projectDirectory = "testModel/";
}
System.out.println("Path is : " + projectDirectory);
// Establish JavaParser AST root
ArrayList<File> files = new ArrayList<>();
File root = new File(projectDirectory);
SourceRoot sourceRoot = new SourceRoot(root.toPath());
// parse all java files under the package
sourceRoot.tryToParse("");
// Extract Info
List<CompilationUnit> cus = (ArrayList<CompilationUnit>) sourceRoot.getCompilationUnits();
System.out.println("Number of java files found: " + sourceRoot.getCompilationUnits().size());
for (CompilationUnit c : cus) {
MyClass one = new MyClass();
c.accept(new Visitor(), one);
// one.print();
allClasses.add(one);
}
for (MyClass c:allClasses){
c.findDependency();
}
MyClass.globalDep.forEach((e) -> {
System.out.println("\n" + e.toString());
});
// sourceRoot.saveAll();
// sourceRoot.parse("", new ParserConfiguration(), (SourceRoot.Callback) (path, absPath, result) -> {
//
// return SourceRoot.Callback.Result.SAVE;
// });
// Ask Target Class from user.
String target = "!@#!@#!@#";
System.out.println("Due to some constraints regarding the size limit of the Image, we only support showing a portion of the classes.");
System.out.println("Here are all Classes Found: " + MyClass.globalClasses.toString());
System.out.println("Please enter a class that you want to see in particular: (Enter nothing to view all)");
target = scanner.nextLine();
while (!checkExists(target)) {
System.out.println("Invalid Input: Try Again");
System.out.println("Here are all Classes Found: " + MyClass.globalClasses.toString());
target = scanner.nextLine();
}
// Draw diagram on Canvas using JFrame
initialize(allClasses, target);
if (System.getProperty("os.name").contains("Mac")) {
// cleanUpJavaCache();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean checkExists(String target) {
System.out.println( " asd asd a tage " + target);
if (target.equalsIgnoreCase("")) {
return true;
}
for (String s : MyClass.globalClasses){
if (s.equalsIgnoreCase(target)){
return true;
}
}
return false;
}
private static void initialize(ArrayList<MyClass> allClasses, String target){
JFrame jFrame = new JFrame(); //initialize
jFrame.setSize(1000, 770);// set size of window
jFrame.setBackground(Color.WHITE);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//set open-close model
jFrame.setContentPane(new DiagramGenerator(allClasses, target));// set content
jFrame.setTitle("UML Graph");//set title
jFrame.setVisible(true);// framework is visible
jFrame.setLocationRelativeTo(null);// the window at middle of the screen
}
// This method will only used for Mac OS.
private static void cleanUpJavaCache() throws IOException {
String[] productionPath = {"./out/production"};
Boolean isSuccess = true;
for (String filePath: productionPath){
if (new File(filePath).exists()) {
Runtime.getRuntime().exec("rm -r " + filePath);
} else {
isSuccess = false;
}
}
if (isSuccess){
System.out.println("Java cache is removed successfully.");
}
}
}
|
C | UTF-8 | 5,680 | 3.453125 | 3 | [] | no_license | /**
Skeleton code of assignment 2 (For reference only)
The time calculation could be confused, check the exmaple of gettimeofday on connex->resource->tutorial for more detail.
*/
struct customer_info{ /// use this struct to record the customer information read from customers.txt
int user_id;
int class_type
int service_time;
int arrival_time;
};
/* global variables */
struct timeval init_time; // use this variable to record the simulation start time; No need to use mutex_lock when reading this variable since the value would not be changed by thread once the initial time was set.
double overall_waiting_time; //A global variable to add up the overall waiting time for all customers, every customer add their own waiting time to this variable, mutex_lock is necessary.
int queue_length[NQUEUE];// variable stores the real-time queue length information; mutex_lock needed
int queue_status[NQUEUE]; // variable to record the status of a queue, the value could be idle (not using by any clerk) or the clerk id (1 ~ 4), indicating that the corresponding clerk is now signaling this queue.
int winner_selected[NQUEUE] = FALSE; // variable to record if the first customer in a queue has been successfully selected and left the queue.
/* Other global variable may include:
1. condition_variables (and the corresponding mutex_lock) to represent each queue;
2. condition_variables to represent clerks
3. others.. depend on your design
*/
int main() {
// initialize all the condition variable and thread lock will be used
/** Read customer information from txt file and store them in the structure you created
1. Allocate memory(array, link list etc.) to store the customer information.
2. File operation: fopen fread getline/gets/fread ..., store information in data structure you created
*/
//create clerk thread (optional)
for(i = 0, i < NClerks; i++){ // number of clerks
pthread_create(&clerkId[i], NULL, clerk_entry, (void *)&clerk_info[i]); // clerk_info: passing the clerk information (e.g., clerk ID) to clerk thread
}
//create customer thread
for(i = 0, i < NCustomers; i++){ // number of customers
pthread_create(&customId[i], NULL, customer_entry, (void *)&custom_info[i]); //custom_info: passing the customer information (e.g., customer ID, arrival time, service time, etc.) to customer thread
}
// wait for all customer threads to terminate
forEach customer thread{
pthread_join(...);
}
// destroy mutex & condition variable (optional)
// calculate the average waiting time of all customers
return 0;
}
// function entry for customer threads
void * customer_entry(void * cus_info){
struct customer_info * p_myInfo = (struct info_node *) cus_info;
usleep(/* the arrival time of this customer */);
fprintf(stdout, "A customer arrives: customer ID %2d. \n", p_myInfo->user_id);
/* Enqueue operation: get into either business queue or economy queue by using p_myInfo->class_type*/
pthread_mutex_lock(/* mutexLock of selected queue */);
{
fprintf(stdout, "A customer enters a queue: the queue ID %1d, and length of the queue %2d. \n", /*...*/);
enQueue();
queue_enter_time = getCurSystemTime();
queue_length[cur_queue]++;
while (TRUE) {
pthread_cond_wait(/* cond_var of selected queue */, /* mutexLock of selected queue */);
if (I_am_Head_of_the_Queue && !winner_selected[cur_queue]) {
deQueue();
queue_length[cur_queue]--;
winner_selected[cur_queue] = TRUE; // update the winner_selected variable to indicate that the first customer has been selected from the queue
break;
}
}
}
pthread_mutex_unlock(/*mutexLock of selected queue*/); //unlock mutex_lock such that other customers can enter into the queue
/* Try to figure out which clerk awoken me, because you need to print the clerk Id information */
usleep(10); // Add a usleep here to make sure that all the other waiting threads have already got back to call pthread_cond_wait. 10 us will not harm your simulation time.
clerk_woke_me_up = queue_status[cur_queue];
queue_status[cur_queue] = IDLE;
/* get the current machine time; updates the overall_waiting_time*/
fprintf(stdout, "A clerk starts serving a customer: start time %.2f, the customer ID %2d, the clerk ID %1d. \n", /*...*/);
usleep(/* as long as the service time of this customer */);
/* get the current machine time; */
fprintf(stdout, "A clerk finishes serving a customer: end time %.2f, the customer ID %2d, the clerk ID %1d. \n", /* ... */);\
pthread_cond_signal(/* convar of the clerk signaled me */); // Notify the clerk that service is finished, it can serve another customer
pthread_exit(NULL);
return NULL;
}
// function entry for clerk threads
void *clerk_entry(void * clerkNum){
while(TRUE){
/* selected_queue_ID = Select the queue based on the priority and current customers number */
pthread_mutex_lock(/* mutexLock of the selected queue */);
queue_status[selected_queue_ID] = clerkID; // The current clerk (clerkID) is signaling this queue
pthread_cond_broadcast(/* cond_var of the selected queue */); // Awake the customer (the one enter into the queue first) from the selected queue
winner_selected[selected_queue_ID] = FALSE; // set the initial value as the customer has not selected from the queue.
pthread_mutex_unlock(/* mutexLock of the selected queue */);
pthread_cond_wait(/* convar of the current clerk */); // wait for the customer to finish its service
}
pthread_exit(NULL);
return NULL;
}
|
Shell | UTF-8 | 1,065 | 3.171875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | #!/bin/bash
ANALYSIS=$1
FROMLIMIT=$4
mkdir -p $ANALYSIS
declare -A array=( [signal]=met [wmn]=singlemu [tmn]=singlemu [tme]=singlemu [wen]=singleele [ten]=singleele [tem]=singleele [zmm]=dimu [zee]=diele [pho]=pho )
if [ $ANALYSIS != 'monojet' ]
then
for SEL in signal wmn wen tmn ten zmm zee pho
do
source analysis.sh $ANALYSIS ${array[$SEL]} $SEL $FROMLIMIT
source analysis.sh $ANALYSIS ${array[$SEL]} ${SEL}_fail $FROMLIMIT
done
fi
if [ $ANALYSIS == 'monojet' ]
then
for SEL in signal wmn wen tmn ten zmm zee pho tme tem
do
# echo -e "source analysis.sh $ANALYSIS ${array[$SEL]} ${SEL}_$TAG $FROMLIMIT"
source analysis.sh $ANALYSIS ${array[$SEL]} ${SEL}_0tag $FROMLIMIT
source analysis.sh $ANALYSIS ${array[$SEL]} ${SEL}_1tag $FROMLIMIT
source analysis.sh $ANALYSIS ${array[$SEL]} ${SEL}_2tag $FROMLIMIT
done
fi
|
Markdown | UTF-8 | 2,406 | 3.75 | 4 | [] | no_license | # Description
[https://www.codewars.com/kata/523a86aa4230ebb5420001e1/train/javascript](https://www.codewars.com/kata/523a86aa4230ebb5420001e1/train/javascript)
What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:
```
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
```
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:
```
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
anagrams('laser', ['lazing', 'lazy', 'lacer']) => []
```
# Test Cases
```
Array.prototype.compare = function (array) {
if (!array) return false;
if (this.length != array.length) return false;
for (var i = 0; i < this.length; i++) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].compare(array[i]))
return false;
}
else if (this[i] != array[i]) {
return false;
}
}
return true;
}
function testAnagrams(word, result, wrong) {
var results = anagrams(word, result.concat(wrong).sort());
return results.sort().compare(result.sort());
}
var word0, result0, wrong0;
word0 = 'a';
result0 = ['a'];
wrong0 = ['b', 'c', 'd'];
Test.expect(testAnagrams(word0, result0, wrong0));
var word1, result1, wrong1;
word1 = 'ab'
result1 = ['ab', 'ba'];
wrong1 = ['aa', 'bb', 'cc', 'ac', 'bc', 'cd'];
Test.expect(testAnagrams(word1, result1, wrong1));
var word2, result2, wrong2;
word2 = 'abba';
result2 = ['aabb', 'bbaa', 'abab', 'baba', 'baab'];
wrong2 = ['abcd', 'abbba', 'baaab', 'abbab', 'abbaa', 'babaa'];
Test.expect(testAnagrams(word2, result2, wrong2));
var word3, result3, wrong3;
word3 = 'racer'
result3 = ['carer', 'arcre', 'carre']
wrong3 = ['racers', 'arceer', 'raccer', 'carrer', 'cerarr']
Test.expect(testAnagrams(word2, result2, wrong2));
var word4, result4, wrong4;
word4 = 'big'
result4 = [];
wrong4 = ['gig', 'dib', 'bid', 'biig'];
Test.expect(testAnagrams(word4, result4, wrong4));
```
# Solution
```
function anagrams(word, words) {
return words.filter(function(item){
return item.split('').sort().join('') === word.split('').sort().join('');
});
}
```
|
Python | UTF-8 | 1,581 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env python3
"""Tools for extracting job info from CSV files"""
import csv
import unittest
import ListShaper
def read_log(file_name):
#csvfile = open(file_name, newline='', encoding='latin-1', mode='r')
with open(file_name, newline='', encoding='latin-1', mode='r') as csvfile:
reader = csv.reader(x.replace('\0', '') for x in csvfile)
log = [log_items for log_items in reader]
return log
def find_in_csv(file_name, search_strings):
"""Find a string within a CSV file
Args:
file_name: Name of csv file to search
search_string: String to be searched for
Returns: A list of dates and print jobs
"""
with open(file_name, newline='', encoding='latin-1') as csvfile:
reader = csv.reader(x.replace('\0', '') for x in csvfile)
findings = list()
read = [r for r in reader]
for search_string in search_strings:
for r in read:
if len(r) > 1 and str(search_string) in str(r[1]):
findings.append([r[0], r[1]])
return findings
def list_jobs(file_name):
log = read_log(file_name)
jobs = ListShaper.job_lister(log)
return jobs
class CSVReader(unittest.TestCase):
def test_read_log(self):
#Arrange
log = read_log('TestData/ProofLog.csv')
expected = 'Tue May 16 12:09:08 2017'
#Act
actual = log[0][0]
#Assert
self.assertEqual(actual, expected)
#jobs = list_jobs('TestData/ProofLog.csv')
#print(jobs)
#if __name__ == '__main__':
# unittest.main()
|
Ruby | UTF-8 | 506 | 4.46875 | 4 | [] | no_license | # FizzBuzz App
#Write a program that prints the numbers from 1 to 100
#For multiples of three, print “Fizz” instead of the number
# For multiples of five, print “Buzz” instead of the number
# For numbers which are multiples of both three and five, print “FizzBuzz” instead of the number
number = 0
while number < 101
if number%3 == 0 && number %5 == 0
puts "FizzBuzz"
elsif number%3 == 0
puts "Fizz"
elsif number%5 == 0
puts "Buzz"
else
puts number
end
number+=1
end
|
C# | UTF-8 | 16,231 | 2.515625 | 3 | [
"MS-PL"
] | permissive | //-------------------------------------
// Copyright (c) Microsoft Corporation
//-------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using NModel.Terms;
using NModel;
using NModel.Execution;
using Action = NModel.Terms.Action;
namespace NModel.Conformance
{
//This part includes all the publicly configurable settings of the conformance tester
/// <summary>
/// Delegate for passing information about completed test runs.
/// </summary>
/// <param name="testResult">test result containig the verdict and the action trace</param>
/// <returns>testing stops if false is returned, testing continues otherwise</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public delegate bool TestResultDelegate(TestResult testResult);
/// <summary>
/// Delegate for returning the amount of time within which the given tester action
/// call to the implementation must return.
/// If the action does not return, a conformance failure occurs.
/// </summary>
/// <param name="state">given model state</param>
/// <param name="action">given tester action</param>
/// <returns>amount of time to wait</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")]
public delegate TimeSpan TesterActionTimeoutDelegate(IState state, CompoundTerm action);
partial class ConformanceTester
{
#region TestResultNotifier
/// <summary>
/// Test result delegate that is called each time a test run is completed.
/// </summary>
TestResultDelegate testResultNotifier;
/// <summary>
/// Gets or sets the test result delegate that is called each time a test run is completed.
/// The default notifier prettyprints the term representation of each test result to the console or
/// a logfile (if one is provided).
/// </summary>
public TestResultDelegate TestResultNotifier
{
get
{
return testResultNotifier;
}
set
{
if (value == null)
throw new ConformanceTesterException("TestResultNotifier cannot be set to null.");
testResultNotifier = value;
}
}
bool DefaultTestResultNotifier(TestResult testResult)
{
// Failed actions metrics
AddFailedActionsWithMessages(testResult);
using (StreamWriter sw = GetStreamWriter())
{
WriteLine(sw, "TestResult(" + testResult.testNr + ", "
+ "Verdict(\"" + testResult.verdict + "\"), \""
+ testResult.reason + "\",");
// Requirements metrics
if (showTestCaseCoveredRequirements == true)
AddExecutedRequirementsToTest(testResult, sw);
WriteLine(sw, " Trace(");
for (int i = 0; i < testResult.trace.Count; i++)
{
WriteLine(sw, " " + testResult.trace[i].ToString() +
(i < testResult.trace.Count - 1 ? "," : ""));
}
WriteLine(sw, " )");
}
if (!this.continueOnFailure)
{
return testResult.verdict == Verdict.Success;
}
else
{
return true;
}
}
#endregion
#region ContinueOnFailure
bool continueOnFailure = true;
/// <summary>
/// If set to false, the default test result notifier returns false when
/// a test case fails. Default is true.
/// This setting has no effect if the <see cref="TestResultNotifier"/> has been set
/// to a custom notifier.
/// </summary>
public bool ContinueOnFailure
{
get { return continueOnFailure; }
set { continueOnFailure = value; }
}
#endregion
#region StepsCnt
int stepsCnt = 0;
/// <summary>
/// The desired number of steps that a single test run should have.
/// After the number is reached, only cleanup tester actions are used
/// and the test run continues until an accepting state is reached or
/// the number of steps is MaxStepsCnt (whichever occurs first).
/// </summary>
/// <remarks>Negative value or 0 implies no bound and a test case is executed
/// until either a failure occurs or no more actions are enabled.
/// Default is 0.</remarks>
public int StepsCnt
{
get
{
return stepsCnt;
}
set
{
stepsCnt = value;
}
}
#endregion
#region MaxStepsCnt
int maxStepsCnt = 0;
/// <summary>
/// The maximum number of steps that a single test run can have. This value must be 0, which means that there is no bound, or greater than or equal to stepsCnt.
/// If stepsCnt is 0 then stepsCnt is set to be equal to maxStepsCnt.
/// </summary>
public int MaxStepsCnt
{
get
{
return maxStepsCnt;
}
set
{
if (value != 0 && value < stepsCnt)
throw new ConformanceTesterException("The maximum number of steps in a run cannot be less than the desired number of steps in a run.");
if (stepsCnt == 0)
stepsCnt = value;
maxStepsCnt = value;
}
}
#endregion
#region RunsCnt
int runsCnt = 0;
/// <summary>
/// The desired number of test runs. Must be nonnegative. Testing stops when this number has been reached.
/// Test runs are numbered from 0 to RunsCnt-1.
/// </summary>
/// <remarks>0 implies no bound. Default is 0.</remarks>
public int RunsCnt
{
get
{
return runsCnt;
}
set
{
if (value < 0)
throw new ConformanceTesterException("Number of test runs cannot be negative.");
runsCnt = value;
}
}
#endregion
#region TesterActionTimeout
/// <summary>
/// Returns the amount of time within which the given tester action
/// call to the implementation must return.
/// If the action does not return, a conformance failure occurs.
/// Default is 100ms.
/// </summary>
TesterActionTimeoutDelegate testerActionTimeout;
/// <summary>
/// Returns the amount of time within which the given tester action
/// call to the implementation must return.
/// If the action does not return, a conformance failure occurs.
/// Default is 100ms.
/// </summary>
public TesterActionTimeoutDelegate TesterActionTimeout
{
get
{
return testerActionTimeout;
}
set
{
if (value == null)
throw new ConformanceTesterException("TesterActionTimeout cannot be set to null");
testerActionTimeout = value;
}
}
#endregion
#region ObservableActionSymbols and testerActionSymbols
/// <summary>
/// Set of action symbols controlled by the tester.
/// Default is all action symbols of the model program.
/// </summary>
Set<Symbol> testerActionSymbols;
/// <summary>
/// Set of action symbols controlled by the implementation.
/// Default is the empty set.
/// </summary>
public Set<Symbol> ObservableActionSymbols
{
get
{
return this.model.ActionSymbols.Difference(testerActionSymbols);
}
set
{
if (value == null)
throw new ConformanceTesterException("ObservableActionSymbols cannot be set to null");
Set<Symbol> unknown = value.Difference(this.model.ActionSymbols);
if (!unknown.IsEmpty)
throw new ConformanceTesterException("Unexpected ObservableActionSymbols: " + unknown.ToString());
testerActionSymbols = this.model.ActionSymbols.Difference(value); ;
}
}
#endregion
#region CleanupActionSymbols
/// <summary>
/// Subset of tester action symbols that are cleanup action symbols.
/// Default is the empty set.
/// </summary>
Set<Symbol> cleanupActionSymbols;
/// <summary>
/// Subset of tester action symbols that are cleanup action symbols.
/// Default is the empty set.
/// </summary>
public Set<Symbol> CleanupActionSymbols
{
get
{
return cleanupActionSymbols;
}
set
{
if (value == null)
throw new ConformanceTesterException("CleanupActionSymbols cannot be set to null");
Set<Symbol> unknown = value.Difference(this.model.ActionSymbols);
if (!unknown.IsEmpty)
throw new ConformanceTesterException("Unexpected CleanupActionSymbols: " + unknown.ToString());
cleanupActionSymbols = value;
}
}
#endregion
#region InternalActionSymbols
/// <summary>
/// Subset of tester action symbols that are not shared with the implementation.
/// Default is the empty set.
/// </summary>
Set<Symbol> internalActionSymbols;
/// <summary>
/// Subset of tester action symbols that are not shared with the implementation.
/// Default is the empty set.
/// </summary>
public Set<Symbol> InternalActionSymbols
{
get
{
return internalActionSymbols;
}
set
{
if (value == null)
throw new ConformanceTesterException("InternalActionSymbols cannot be set to null");
Set<Symbol> unknown = value.Difference(this.model.ActionSymbols);
if (!unknown.IsEmpty)
throw new ConformanceTesterException("Unexpected InternalActionSymbols: " + unknown.ToString());
internalActionSymbols = value;
}
}
#endregion
#region Logfile
/// <summary>
/// Filename where test results are logged by the default test result notifier.
/// The console is used if no logfile is provided.
/// </summary>
string logfile;
/// <summary>
/// Filename where test results are logged by the default test result notifier.
/// The console is used if no logfile is provided.
/// </summary>
public string Logfile
{
get { return logfile; }
set { logfile = value; }
}
#endregion
#region OverwriteLog
/// <summary>
/// If true the log file is overwritten, otherwise the testresults are appended to the logfile (if provided).
/// </summary>
bool overwriteLog = true;
/// <summary>
/// If true the log file is overwritten, otherwise the testresults are appended to the logfile (if provided).
/// </summary>
public bool OverwriteLog
{
get { return overwriteLog; }
set { overwriteLog = value; }
}
#endregion
#region RandomSeed
/// <summary>
/// A number used to calculate the starting value for the pseudo-random number sequence
/// that is used by the global choice controller.
/// If a negative number is specified, the absolute value is used.
/// </summary>
int randomSeed;
/// <summary>
/// A number used to calculate the starting value for the pseudo-random number sequence
/// that is used by the global choice controller.
/// If a negative number is specified, the absolute value is used.
/// Setting this property resets the GlobalChoiceController with a new instance
/// of the System.Random class with the given random seed.
/// </summary>
public int RandomSeed
{
get
{
return randomSeed;
}
set
{
randomSeed = value;
NModel.Internals.HashAlgorithms.GlobalChoiceController = new Random(value);
}
}
#endregion
#region WaitAction
internal Set<Symbol> waitActionSet = new Set<Symbol>(Symbol.Parse("Wait"));
/// <summary>
/// A name of an action that is used to wait for observable actions in a
/// state where no controllable actions are enabled. A wait action is controllable
/// and internal and must take one integer argument that determines the time to
/// wait in milliseconds during which an observable action is expected. Default is "Wait".
/// Only used with IAsyncStepper.
/// </summary>
public string WaitAction
{
get
{
return waitActionSet.Choose().Name;
}
set
{
waitActionSet = new Set<Symbol>(Symbol.Parse(value));
}
}
#endregion
#region TimeoutAction
/// <summary>
/// A name of an action that happens when a wait action has been executed and no
/// obsevable action occurred within the time limit provided in the wait action.
/// A timeout action is observable and takes no arguments. Default is "Timeout".
/// Only used with IAsyncStepper.
/// </summary>
internal Action timeoutAction = Action.Create("Timeout");
/// <summary>
/// A name of an action that happens when a wait action has been executed and no
/// obsevable action occurred within the time limit provided in the wait action.
/// A timeout action is observable and takes no arguments. Default is "Timeout".
/// Only used with IAsyncStepper.
/// </summary>
public string TimeoutAction
{
get
{
return timeoutAction.Name;
}
set
{
timeoutAction = Action.Create(value);
}
}
#endregion
bool logFileWasAlreadyOpened;
StreamWriter GetStreamWriter()
{
if (String.IsNullOrEmpty(logfile))
return null;
else
{
StreamWriter sw;
if (logFileWasAlreadyOpened)
sw = new StreamWriter(logfile, true);
else
sw = new StreamWriter(logfile, !OverwriteLog);
logFileWasAlreadyOpened = true;
return sw;
}
}
static void WriteLine(StreamWriter sw, object value)
{
if (sw == null)
Console.WriteLine(value);
else
sw.WriteLine(value);
}
}
}
|
C++ | UTF-8 | 8,996 | 2.515625 | 3 | [] | no_license | #include "main.hpp"
using namespace DBL;
const char *Ai::aiType = "Ai";
const char *PlayerControlledAi::type = "PlayerControlledAi";
const char *WanderAimlesslyAi::type = "WanderAimlesslyAi";
const char *VillagerAi::type = "VillagerAi";
Ai::Ai(const char *componentSecondaryType): ActorComponent(aiType),
componentSecondaryType(componentSecondaryType)
{}
Ai *Ai::NewAiFromDeserialization(std::vector<std::string> tokens)
{
Ai *ret = NULL;
if(tokens.size() >= 2)
{
if(tokens[1] == PlayerControlledAi::type) ret = new PlayerControlledAi();
else if(tokens[1] == WanderAimlesslyAi::type) ret = new WanderAimlesslyAi();
else if(tokens[1] == VillagerAi::type) ret = new VillagerAi();
if(ret) ret->Deserialize(tokens);
}
return ret;
}
std::string PlayerControlledAi::Serialize()
{
std::ostringstream serial;
serial << ACT_COMP << componentType << DELIM << type;
return serial.str();
}
void PlayerControlledAi::Deserialize(std::vector<std::string> tokens)
{
//Don't need to load anything for now
}
void PlayerControlledAi::Act(Actor *owner)
{
hasActedRecently = false;
//This is where the player would check the input they were given
//If they were to attack something it would happen here
}
void PlayerControlledAi::RespondToMouseClick(Actor *owner, int tileClickedX, int tileClickedY, bool isLeftClick)
{
if(!hasActedRecently)
{
hasActedRecently = true;
int targetActorId = game->world.IsActorAtPosition(tileClickedX, tileClickedY, owner->position->depth);
auto box = isLeftClick?
game->world.combatUserInterface.GetLeftClick():
game->world.combatUserInterface.GetRightClick();
//there's an actor there
if(targetActorId)
{
auto targetActor = game->world.actorCollection.GetActor(targetActorId);
if(targetActor->villager && isLeftClick)
{
//left clicks on villagers are always to talk
//are we close enough to talk to the villager?
//TODO: get rid of the hardcoded 2, check line of sight and give reasonable distance away
if(owner->position->tile.distanceSquared(targetActor->position->tile) < 2)
{
game->SetNextScreen(new TalkToActorMenu(targetActorId));
}
}
else
{
//TODO: tell combat system player is attacking unarmed
CombatEvent ev(owner->id, tileClickedX, tileClickedY, box.itemId, box.abilityId, isLeftClick? 0: 1);
game->combatSystem.QueueCombatEvent(ev);
}
}
else //no actor there but try doing something other than moving?
{
CombatEvent ev(owner->id, tileClickedX, tileClickedY, box.itemId, box.abilityId, isLeftClick? 0: 1);
game->combatSystem.QueueCombatEvent(ev);
}
}
}
/*
if(isHoldingStill) //don't let player move
{
if(owner->movement->isMoving)
owner->movement->destination == owner->position->tile;
}*/
/*
int targetActorId = game->world.IsActorAtPosition(tileClickedX, tileClickedY, owner->position->depth);
if(targetActorId)
{
auto targetActor = game->world.actorCollection.GetActor(targetActorId);
if(targetActor != 0)
{
//If close enough we can interact with them
//If target is a villager
if(targetActor->villager)
{
//Close enough to talk to?
//If villager is in a combatant you'll want a different menu than a talk one
//TODO: get rid of the hardcoded 3, check line of sight and give reasonable distance away
if(owner->position->tile.distanceSquared(targetActor->position->tile) < 2)
{
game->SetNextScreen(new TalkToActorMenu(targetActorId));
}
else
{
//Too far away to talk to
game->movingActors.RegisterActorToMove(owner->id, tileClickedX, tileClickedY);
}
}
//If target is a hostile monster
//TODO: determine how far away player can attack and if they have line of sight
//If target is some non-descript actor (an object on the floor?)
else
{
game->movingActors.RegisterActorToMove(owner->id, tileClickedX, tileClickedY);
}
}
}
else
{
game->movingActors.RegisterActorToMove(owner->id, tileClickedX, tileClickedY);
}
*/
std::string WanderAimlesslyAi::Serialize()
{
std::ostringstream serial;
serial << ACT_COMP << componentType << DELIM << type;
return serial.str();
}
void WanderAimlesslyAi::Deserialize(std::vector<std::string> tokens)
{
//Doesn't need any additional information
}
void WanderAimlesslyAi::Act(Actor *owner)
{
//Occassionally pick an adjacent tile, go there
if(rng::OneOutOf(3))
{
bool isClear = false;
int moveAttempts = TOTAL_DIRECTIONS;
auto floor = game->world.levelCollection.levels[owner->position->depth].tiles;
auto pos = owner->position->tile;
int direction = rng::Rand(8); //mix a random first direction
do
{
switch(direction)
{
case DIR_UP: //0
if(pos.y > 0 && game->world.IsPositionClear(pos.x, pos.y-1, owner->position->depth))
{
pos.y--;
isClear = true;
}
break;
case DIR_DOWN: //4
if(pos.y < (int)floor[0].size()-1 && game->world.IsPositionClear(pos.x, pos.y+1, owner->position->depth))
{
pos.y++;
isClear = true;
}
break;
case DIR_UPRIGHT: //1
if(pos.y > 0 && pos.x < (int)floor.size()-1 && game->world.IsPositionClear(pos.x+1, pos.y-1, owner->position->depth))
{
pos.x++; pos.y--;
isClear = true;
}
break;
case DIR_DOWNLEFT: //5
if(pos.x > 0 && pos.y < (int)floor[0].size()-1 && game->world.IsPositionClear(pos.x-1, pos.y+1, owner->position->depth))
{
pos.x--; pos.y++;
isClear = true;
}
break;
case DIR_RIGHT: //2
if(pos.x < (int)floor.size()-1 && game->world.IsPositionClear(pos.x+1, pos.y, owner->position->depth))
{
pos.x++;
isClear = true;
}
break;
case DIR_LEFT: //6
if(pos.x > 0 && game->world.IsPositionClear(pos.x-1, pos.y, owner->position->depth))
{
pos.x--;
isClear = true;
}
break;
case DIR_DOWNRIGHT: //3
if(pos.x < (int)floor.size()-1 && pos.y < (int)floor[0].size()-1 && game->world.IsPositionClear(pos.x+1, pos.y+1, owner->position->depth))
{
pos.x++; pos.y++;
isClear = true;
}
break;
case DIR_UPLEFT: //7
if(pos.x > 0 && pos.y > 0 && game->world.IsPositionClear(pos.x-1, pos.y-1, owner->position->depth))
{
pos.x--; pos.y--;
isClear = true;
}
break;
}
//check them all
direction++;
if(direction == TOTAL_DIRECTIONS) direction = DIR_UP;
} while(!isClear && --moveAttempts > 0);
if(isClear)
{
int id = owner->id;
game->movingActors.RegisterActorToMove(owner->id, pos.x, pos.y, owner->position->depth);
}
//else not moving (the actor literally can't go any direction!)
}
//else do nothing
}
std::string VillagerAi::Serialize()
{
std::ostringstream serial;
serial << ACT_COMP << componentType << DELIM <<
type << DELIM <<
mentalState;
return serial.str();
}
void VillagerAi::Deserialize(std::vector<std::string> tokens)
{
mentalState = atoi(tokens[MENTAL_STATE].c_str());
}
void VillagerAi::Act(Actor *owner)
{
switch(mentalState)
{
case VILLAGER_TIME_FOR_FUN: DoActivitiesAroundTheVillage();
break;
case VILLAGER_BEDTIME: GoToBedAndSleepUntilMorning();
break;
case VILLAGER_LISTENS_QUIETLY: //do nothing, someone is talking to you; pay attention
break;
case VILLAGER_TIME_FOR_WORK: PerformYourJob();
break;
case VILLAGER_TIME_FOR_COMBAT: ConcernYourselfWithCombat();
break;
}
/*
Depending on the ai's state it wil either perform its villager functions,
stand there while talking to the player, be combat focused, etc
*/
}
void VillagerAi::DoActivitiesAroundTheVillage()
{
//TODO:
//If in the middle of an activity, finish it
//by continuing on the current item of todo list
//If it's bed time, go to bed
//If it's time for work, go to work
//If needing something to do, pick from list of things preferable to do
//add required steps to todo list
}
void VillagerAi::GoToBedAndSleepUntilMorning()
{
//TODO:
//If it's time to wake up
//create a todo list to get out of bed
//set mental state to time for fun
//If it's past bed time
//if in own bed do nothing
//else If not in bed go to own bed
}
void VillagerAi::PerformYourJob()
{
//TODO:
//If it's still time for work
//stay in work area and wait for player to interact with you
//If it's no longer time for work
//it's time to have fun
}
void VillagerAi::ConcernYourselfWithCombat()
{
//1st, 2nd, 3rd person order:
//TODO and figure out how TODO
//Check Self
//are you hurt?
//determine options
//are you in danger?
//determine options
//are you near a hostile creature?
//decide what to do
//are you way too far from player?
//or are you near the player?
//stay near the player
//Check player
//is player hurt?
//is player in danger?
//How are the monsters?
//is any of them about to do give up and can you finish them off?
//are any of them extremely dangerous?
//should they be avoided or nerfed?
//Determine most appropriate action and do it
}
|
Python | UTF-8 | 774 | 3 | 3 | [] | no_license | # import all the required modules
import numpy as np
import imageio
import scipy.ndimage
import cv2
# take image input and assign variable to it
img = "https://mubaarka.com/images/24.08.2021_18.33.35_REC.png"
# function to convert image into sketch
def rgb2gray(rgb):
# 2 dimensional array to convert image to sketch
return np.dot(rgb[..., :3], [0.299, 0.587, .114])
def dodge(front, back):
final_sketch = front*255/(255-back)
final_sketch[final_sketch > 255] = 255
final_sketch[back == 255] = 255
return final_sketch.astype('uint8')
ss = imageio.imread(img)
gray = rgb2gray(ss)
i = 255-gray
blur = scipy.ndimage.filters.gaussian_filter(i, sigma=13)
r = dodge(blur, gray)
cv2.imshow('image',r)
cv2.waitKey()
cv2.imwrite('4.png', r)
|
Markdown | UTF-8 | 4,263 | 2.71875 | 3 | [] | no_license | # Domino curriculum
This repository contains a course for learning [Domino Data Lab](https://docs.dominodatalab.com/en/4.2/).
Recorded Demo of Domino:
- [link](https://dominodatalab.zoom.us/rec/play/uMF_deCo_D03SIGd5gSDU6QtW460famsgHcdqPYPykfgUSUCZwHwZudDauYhg61yjIp9o4p0JQcOKrWc?continueMode=true)
- password: 4R*8MJ*T
The features highlighted in this course include:
1. Python/R work environments (combining Python and R, Python Dash and R Shiny dashboards)
2. Elastic compute to launch light and heavy calculations side by side and scale up and down as needed
3. Developing and deploying model endpoints
4. Scheduling and running repeatable reports, tweaked by use of parameters. E.g., multiple versions of a "performance tracker" deck
5. Easy interfaces for business users - to give business analysts and product managers the ability to monitor and update processes directly
6. Using Spark with Jupyter and Zeppelin
7. Building a deep learning application and training the NNs on GPUs.
8. Auto ML - using automation to train and deploy multiple models, tune hyper-parameters, and pick the best predictor using cross validation
9. Reproducing experiments by retrieving the data, code and other artifacts that were part of the original project. Also, employ this to demonstrate knowledge sharing by having one set of users deploy and update models built by others.
10. Model lifecycle - using the platform to practice implementing all phases of a model lifecycle – data prep, feature extraction, model selection, training, validation, deployment and governance.
## This course will be developed in phases:
### Phase 0:
One or more members of EIDS gains preliminary familiarity with the most aspects of Domino. Tutorials and documentation will be generated as appropriate.
### Phase 1:
Building on the lessons learned in Phase 0, a core group drawn from the union of EIDS and other teams will work collaboratively on 3-4 carefully selected projects. The scope of the projects will be molded to cover the most important features of Domino (e.g., dashboards, model lifecycle, distributed computing) we want to master during the trial.
Projects will be executed within a team consisting of multiple archetypical roles **(team structure is up for debate)**:
- Stake holder - A non-technical person respresenting the line of business
- End user - A minimally technical business analyst or product manager who consumes the dashboard and end points
- Data scientist - Person responsible for the modelling
- Engineer - Responsible for standing up and testing the final dashboards and end points
Running multiple (3-4) projects simultaneously will allow each member of the core group to play technical and non-technical roles in a project. Each participant will benefit from exposure to the technical and business aspects of a data science project.
Prospective projects and data sets include **(fierce debate is required here to get the project scope and the data source right)**:
| Project | Owner | Description | Dataset(s) |
| ----------- | ----------- | --------- | ---------- |
| Transactions | Bob | Detect fraud transactions and money laundering. | [kaggle](https://www.kaggle.com/apoorvwatsky/bank-transaction-data) |
| NPS | | | |
| Network growth | | | |
| Recommendation engine | | | |
| Name matching | | | |
| | | | |
| | | | |
Core group members will be expected to carefully document all the steps and progress made. These materials will be used to derive data science lectures and demonstrations given to broader audiences.
### Phase 2 (Subject to approval):
In this phase, knowledge is transferred to broader audiences through multiple channels, including:
- project demos
- weekly data science lectures (ideally given by different members of the core group)
- mentorship of other teams that want to practice building and deploying their own data science project
|
Java | UTF-8 | 2,756 | 3.421875 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | package org.jzy3d.io;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
public class SimpleFile {
public static void write(String content, String file) throws Exception {
createParentFoldersIfNotExist(file);
Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
out.write(content);
out.close();
}
public static void createParentFoldersIfNotExist(String file) {
File parent = (new File(file)).getParentFile();
if (parent != null && !parent.exists())
parent.mkdirs();
}
public static List<String> readFile(File file) throws IOException {
return read(file.getAbsolutePath());
}
public static List<String> read(String filename) throws IOException {
List<String> output = new ArrayList<String>();
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
while(dis.available() != 0){
output.add(dis.readLine());
}
fis.close();
bis.close();
dis.close();
return output;
}
public static String readAsString(String filename) throws Exception {
return readAsString(filename, "\n");
}
public static String readAsString(String filename, String newLineString) throws IOException {
StringBuffer sb = new StringBuffer();
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
while (dis.available() != 0) {
sb.append((new StringBuilder()).append(dis.readLine()).append(newLineString));
}
fis.close();
bis.close();
dis.close();
return sb.toString();
}
/**
* Return true if file1 is younger than file2, meaning it was last modified after file2.
* Always return false if file2 does not exist.
* Always return true if file1 does not exist.
*/
public static boolean isYounger(String file1, String file2) throws IOException {
File f1 = new File(file1);
File f2 = new File(file2);
if (!f2.exists())
return false;
if (!f1.exists())
return true;
else
return f1.lastModified() > f2.lastModified();
}
}
|
Java | UTF-8 | 144 | 2.453125 | 2 | [] | no_license | package DiamonProblem;
public interface C2 {
public default void method3() {
System.out.println("call default inteface c2");
}
}
|
JavaScript | UTF-8 | 704 | 3.5 | 4 | [] | no_license | const secondsHand = document.querySelector('[data-seconds-hand]')
const minuteHand = document.querySelector('[data-minute-hand]')
const hourHand = document.querySelector('[data-hour-hand]')
function timer(){
const currentTime = new Date();
const secondRatio = currentTime.getSeconds() / 60;
const minuteRatio = (secondRatio + currentTime.getMinutes()) / 60;
const hourRatio = (minuteRatio + currentTime.getHours()) / 12;
displayClock(secondsHand, secondRatio)
displayClock(minuteHand, minuteRatio)
displayClock(hourHand, hourRatio)
}
timer()
function displayClock(element, property){
element.style.setProperty('--rotation', property * 360)
}
setInterval(timer, 1000) |
Java | UTF-8 | 4,628 | 2.21875 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.jaxb;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.*;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.converters.ObjectTypeConverter;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.internal.oxm.mappings.Mapping;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedClassForName;
/**
* INTERNAL:
* <p><b>Purpose</b>:Provide a means to Convert an Enumeration type to/from either a string representation
* of the enum facet or a user defined value.
*
* <p><b>Responsibilities:</b><ul>
* <li>Initialize the conversion values to be the Enum facets</li>
* <li>Don't overwrite any existing, user defined conversion value</li>
*
*/
public class JAXBEnumTypeConverter extends ObjectTypeConverter {
private Class m_enumClass;
private String m_enumClassName;
private boolean m_usesOrdinalValues;
/**
* PUBLIC:
*/
public JAXBEnumTypeConverter(Mapping mapping, String enumClassName, boolean usesOrdinalValues) {
super((DatabaseMapping)mapping);
m_enumClassName = enumClassName;
m_usesOrdinalValues = usesOrdinalValues;
}
/**
* INTERNAL:
* Convert all the class-name-based settings in this converter to actual
* class-based settings. This method is used when converting a project
* that has been built with class names to a project with classes.
* @param classLoader
*/
public void convertClassNamesToClasses(ClassLoader classLoader){
try {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
m_enumClass = (Class)AccessController.doPrivileged(new PrivilegedClassForName(m_enumClassName, true, classLoader));
} catch (PrivilegedActionException exception) {
throw ValidationException.classNotFoundWhileConvertingClassNames(m_enumClassName, exception.getException());
}
} else {
m_enumClass = org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(m_enumClassName, true, classLoader);
}
} catch (ClassNotFoundException exception){
throw ValidationException.classNotFoundWhileConvertingClassNames(m_enumClassName, exception);
}
}
/**
* INTERNAL:
*/
public void initialize(DatabaseMapping mapping, Session session) {
Iterator<Enum> i = EnumSet.allOf(m_enumClass).iterator();
while (i.hasNext()) {
Enum theEnum = i.next();
if (this.getAttributeToFieldValues().get(theEnum) == null) {
Object existingVal = this.getAttributeToFieldValues().get(theEnum.name());
if (existingVal != null) {
this.getAttributeToFieldValues().remove(theEnum.name());
addConversionValue(existingVal, theEnum);
} else {
// if there's no user defined value, create a default
if (m_usesOrdinalValues) {
addConversionValue(theEnum.ordinal(), theEnum);
} else {
addConversionValue(theEnum.name(), theEnum);
}
}
}
}
super.initialize(mapping, session);
}
/**
* PUBLIC:
* Returns true if this converter uses ordinal values for the enum
* conversion.
*/
public boolean usesOrdinalValues() {
return m_usesOrdinalValues;
}
}
|
JavaScript | UTF-8 | 2,304 | 2.625 | 3 | [] | no_license | function modifier()
{
// 1. Interruption de l'envoi du formulaire
event.preventDefault();
// 2. Récupération des données du formulaire
const Nom = document.querySelector('#Nom');
const Prenom = document.querySelector('#Prenom');
const DatNaiss = document.querySelector('#DatNaiss');
const Genre = document.querySelector('#Genre');
const Pays = document.querySelector('#Pays');
// 3. Conditionnement des données
const data = new FormData();
data.append('nom', Nom.value);
data.append('prenom', Prenom.value);
data.append('datNaiss',DatNaiss.value);
data.append('genre',Genre.value);
data.append('pays',Pays.value);
// 4. Configuration d'une requête ajax en POST et envoie des données
const requeteAjax = new XMLHttpRequest();
requeteAjax.open('POST', 'PHP/modules/monCompte/modif_infoPerso.php');
requeteAjax.send(data);
}
function modifier2()
{
// 1. Interruption de l'envoi du formulaire
event.preventDefault();
// 2. Récupération des données du formulaire
const pseudo = document.querySelector('#ComptePseudo');
const bio = document.querySelector('#CompteBio');
const mail = document.querySelector('#contactTitle');
const curpwd = document.querySelector('#curpwd');
const newpwd = document.querySelector('#newpwd');
// 3. Conditionnement des données
const data = new FormData();
data.append('pseudo', pseudo.value);
data.append('bio', bio.value);
data.append('mail',mail.value);
data.append('curpwd',curpwd.value);
data.append('newpwd',newpwd.value);
// 4. Configuration d'une requête ajax en POST et envoie des données
const requeteAjax = new XMLHttpRequest();
requeteAjax.open('POST', 'PHP/modules/monCompte/modif_gesCompte.php');
requeteAjax.send(data);
}
function supprimer()
{
const requeteAjax = new XMLHttpRequest();
requeteAjax.open('POST', 'PHP/modules/monCompte/suppressionCompte.php');
requeteAjax.send();
}
// ajout des ecouteurs sur les formulaires et le bouton de suppression
document.querySelector('#form2').addEventListener('submit', modifier2);
document.querySelector('#supp').addEventListener('click', supprimer);
document.querySelector('#form1').addEventListener('submit', modifier); |
Java | UTF-8 | 1,972 | 2.0625 | 2 | [] | no_license | package com.david.freedom.plutus.request;
import com.david.freedom.plutus.common.request.BaseRequest;
import com.david.freedom.plutus.stats.RegistrationStatusEnum;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import javax.validation.constraints.NotNull;
/**
* @version $Id: null.java, v 1.0 2020/9/3 8:32 PM david Exp $$
* @Author:louwenbin(louwb@runyong.cn)
* @Description:登记信息入参
* @since 1.0
**/
public class AddRegistratioInfoRequest extends BaseRequest {
private static final long serialVersionUID = 6720283990065508200L;
/**
* 姓名
*/
@NotNull(message = "姓名不能为空")
private String userName;
/**
* 电话好吗
*/
@NotNull(message = "电话好吗不能为空")
private String telephone;
/**
* 身份证
*/
@NotNull(message = "身份证不能为空")
private String cretNo;
@NotNull(message = "注册类型不能为空")
@JsonDeserialize(converter = String2RegistrationConverter.class)
private RegistrationStatusEnum registrationStatusEnum;
public String getUserName() {
return userName;
}
public AddRegistratioInfoRequest setUserName(String userName) {
this.userName = userName;
return this;
}
public String getTelephone() {
return telephone;
}
public AddRegistratioInfoRequest setTelephone(String telephone) {
this.telephone = telephone;
return this;
}
public String getCretNo() {
return cretNo;
}
public AddRegistratioInfoRequest setCretNo(String cretNo) {
this.cretNo = cretNo;
return this;
}
public RegistrationStatusEnum getRegistrationStatusEnum() {
return registrationStatusEnum;
}
public AddRegistratioInfoRequest setRegistrationStatusEnum(RegistrationStatusEnum registrationStatusEnum) {
this.registrationStatusEnum = registrationStatusEnum;
return this;
}
}
|
Java | UTF-8 | 871 | 3.78125 | 4 | [] | no_license | package dsa.ch4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reverser {
private Stack<Character> chars;
public Reverser() {
this.chars = new Stack<Character>(Character.class);
}
public void reverse() throws IOException {
char[] chrs = read();
for (char c : chrs) {
chars.push(c);
}
int idx = 0;
while (!chars.isEmpty()) {
chrs[idx++] = chars.pop();
}
System.out.println("Reverse: " + new String(chrs));
}
public char[] read() throws IOException {
System.out.print("Please enter a string: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine();
System.out.println("String: " + str);
return str.toCharArray();
}
public static void main(String[] args) throws IOException {
new Reverser().reverse();
}
}
|
JavaScript | UTF-8 | 2,800 | 2.671875 | 3 | [
"MIT"
] | permissive | const streamify = require('stream-generators');
exports = module.exports = itf;
exports.contentType = 'application/octet-stream';
exports.extension = 'itf';
/*
ITF file format
see: https://developers.sygic.com/documentation.php?action=navifiles_ITF
Header (4 + 4 + 2 + 2 = 12 bytes)
00 UInt32 Time Creation time - count of seconds snce 1.1.2001
04 UInt32 Empty
08 UInt16 Visited Index short int 2 bytes Index of last visited point in itinerary
10 UInt16 Count of points unsigned short int 2 bytes Count of points in itinerary file
Point (4 + 4 + 1 + 1 + 2 + (strlen + 1) * 2 = 12 bytes + (strlen + 1) * 2
00 UInt32 Longitude in degrees x 100 000
04 UInt32 Latitude in degrees x 100 000
08 UInt8 Type Via Point = 1, Finish = 2, Start = 3, Invisible = 4.
09 UInt8 Empty
10 UInt16 Length of Point name in bytes ( wcslen(Name) + 1 ) * sizeof(wchar_t)
12 wchar_t[] Name of point. Unicode null terminated string.
*/
function toCoord(f) {
return Math.round(f * 1e5);
}
const REF_TIME = new Date('2001-01-01').getTime();
function time() {
return Math.round((Date.now() - REF_TIME) / 1000);
}
function header(count) {
const b = Buffer.allocUnsafe(12);
b.writeUInt32LE(time(), 0);
b.writeUInt32LE(0, 4); // empty
b.writeUInt16LE(0, 8); // visited
b.writeUInt16LE(count, 10);
return b;
}
// FIXME: get proper point type
function step2record({ name = '', coordinates }, type = 1) {
const headerLen = 12;
const nameLen = name.length * 2;
const len = headerLen + nameLen + 2;
const b = Buffer.allocUnsafe(len);
b.writeInt32LE(toCoord(coordinates.lon), 0);
b.writeInt32LE(toCoord(coordinates.lat), 4);
b.writeUInt8(type, 8);
b.writeUInt8(0, 9); // empty
b.writeUInt16LE(nameLen + 2, 10);
// HACK: this does not properly take into account 4 byte characters
b.write(name, headerLen, nameLen + 2, 'ucs2');
// 0 terminated
b.writeUInt16LE(0, len - 2);
return b;
}
function isValid(step) {
return step.coordinates ? 1 : 0;
}
function countValidSteps({ points }) {
return points.reduce((a, step) => a + isValid(step), 0);
}
function itf(out, { routes }) {
const count = routes.reduce((a, route) => a + countValidSteps(route), 0);
function* generate() {
yield header(count);
for(const { points: steps } of routes) {
for(let i = 0; i < steps.length; i++) {
const step = steps[i];
if (!isValid(step)) {
continue;
}
// invisible (4) for pass-through (0 duration) steps
let type = step.visit_duration > 0 ? 1 : 4;
if (i === 0) {
type = 3; // start
} else if (i === steps.length - 1) {
type = 2; // finish
}
yield step2record(step, type);
}
}
}
streamify(generate).pipe(out);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.