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 |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 19,794 | 3.078125 | 3 | [] | no_license | import unittest
from multiset import *
class TestContained(unittest.TestCase):
def test_element_contained(self):
Multi1 = MultiSet()
Multi1.insert('a')
result = 'a' in Multi1
expected = True
self.assertEqual(result, expected)
def test_string_contained(self):
Multi = MultiSet()
Multi.insert('warblegarble')
result = 'warblegarble' in Multi
self.assertTrue(result)
def test_multiple_contained(self):
multi = MultiSet()
multi.insert(1)
multi.insert(2414)
multi.insert(24)
multi.insert(315)
result = 2414 in multi
self.assertTrue(result)
def test_multiple_string(self):
multi = MultiSet()
multi.insert('ga')
multi.insert('i hope a2 is easier')
multi.insert('and shorter')
multi.insert('since we dont have many weeks left')
result = 'and shorter' in multi
self.assertTrue(result)
def test_element_false(self):
multi = MultiSet()
multi.insert(1)
multi.insert(21433442)
result = 54553535 in multi
self.assertFalse(result)
class TestElementCount(unittest.TestCase):
def test_single_element_count(self):
Multi1 = MultiSet()
Multi1.insert('a')
result = Multi1.count('a')
expected = 1
self.assertEqual(result, expected)
def test_multiple_element_count(self):
multi = MultiSet()
multi.insert(1)
multi.insert(2)
multi.insert(4343)
multi.insert(1)
multi.insert(4343)
multi.insert(1)
result = multi.count(4343)
expected = 2
self.assertEqual(result, expected)
def test_multiple_string_element_count(self):
multi = MultiSet()
multi.insert('321321')
multi.insert('agdaf')
multi.insert('mindless string')
multi.insert('agdef')
multi.insert('agdaf')
multi.insert('Y AM I DOIN DIS')
multi.insert('agdaf')
result = multi.count('agdaf')
expected = 3
self.assertEqual(result, expected)
def test_empty_count(self):
multi = MultiSet()
result = multi.count('hehlol')
expected = 0
self.assertEqual(result, expected)
def test_bool_count(self):
x = MultiSet()
y = MultiSet()
x.insert(True)
result = x.count(1)
expected = 1
self.assertEqual(result, expected)
class TestElementInsert(unittest.TestCase):
def test_element_insert(self):
Multi1 = MultiSet()
Multi1.insert('b')
result = 'b' in Multi1
self.assertTrue(result)
def test_multiple_element_insert(self):
multi = MultiSet()
multi.insert(1)
multi.insert(2)
multi.insert(3)
result = (1 in multi)*(2 in multi)*(3 in multi)
expected = 1
self.assertEqual(result, expected)
def test_multiple_false_elements(self):
multi = MultiSet()
multi.insert('fad')
multi.insert('hi')
multi.insert('uwotm8')
result = 'wot' in multi
expected = False
class TestElementClear(unittest.TestCase):
def test_element_clear(self):
Multi1 = MultiSet()
Multi1.insert('a')
Multi1.insert('b')
Multi1.clear()
result = Multi1
expected = MultiSet()
self.assertEqual(result, expected)
def test_empty_set(self):
multi = MultiSet()
multi.clear()
result = multi
expected = MultiSet()
self.assertEqual(result, expected)
def test_false_clear(self):
multi = MultiSet()
multi.insert(1)
multi.insert(234)
multi1 = MultiSet()
multi1.insert(1)
multi.clear()
result = multi == multi1
self.assertFalse(result)
class TestLength(unittest.TestCase):
def test_length(self):
Multi = MultiSet()
Multi.insert('a')
Multi.insert('a')
Multi.insert('b')
result = len(Multi)
expected = 3
self.assertEqual(result, expected)
def test_empty_set(self):
multi = MultiSet()
result = len(multi)
expected = 0
self.assertEqual(result, expected)
def test_long_set(self):
multi = MultiSet()
multi.insert(1)
multi.insert(254)
multi.insert(345)
multi.insert(2)
multi.insert(32504984)
multi.remove(254)
result = len(multi)
expected = 4
self.assertEqual(result, expected)
class TestRepr(unittest.TestCase):
def test_repr(self):
Multi = MultiSet()
Multi.insert('a')
Multi.insert('b')
result = repr(Multi)
expected = 'MultiSet([\'a\', \'b\'])'
self.assertEqual(result, expected)
def test_integer_repr(self):
multi = MultiSet()
multi.insert(5)
multi.insert(435)
multi.insert(9)
multi.insert(24)
result = repr(multi)
expected = 'MultiSet([5, 9, 24, 435])'
self.assertEqual(result, expected)
def test_empty_set(self):
multi = MultiSet()
result = repr(multi)
expected = 'MultiSet([])'
self.assertEqual(result, expected)
class TestEquals(unittest.TestCase):
def test_equals(self):
Multi = MultiSet()
Multi1 = MultiSet()
Multi.insert('1234')
Multi.insert('4321')
Multi1.insert('4321')
Multi1.insert('1234')
result = Multi == Multi1
self.assertTrue(result)
def test_empty_set(self):
multi = MultiSet()
multi1 = MultiSet()
result = multi == multi1
self.assertTrue(result)
def test_different_length_equals(self):
multi = MultiSet()
multi.insert('x')
multi.insert('x')
multi1 = MultiSet()
multi1.insert('x')
result = multi == multi1
self.assertFalse(result)
def test_multiple_occurrences_equals(self):
multi = MultiSet()
multi.insert('a')
multi.insert('a')
multi.insert('y')
multi.insert('y')
multi1 = MultiSet()
multi1.insert('a')
multi1.insert('a')
multi1.insert('y')
multi1.insert('y')
result = multi == multi1
self.assertTrue(result)
class TestSubset(unittest.TestCase):
def test_subset(self):
multi = MultiSet()
multi1 = MultiSet()
multi1.insert('a')
multi.insert('b')
multi1.insert('b')
multi.insert('a')
multi1.insert('c')
result = (multi <= multi1)
self.assertTrue(result)
def test_empty_set(self):
multi = MultiSet()
multi1 = MultiSet()
result = multi <= multi1
self.assertTrue(result)
def test_string_set(self):
multi = MultiSet()
multi1 = MultiSet()
multi.insert('hi')
multi.insert('bye')
multi.insert('no')
multi1.insert('hi')
multi1.insert('bye')
multi1.insert('no')
multi1.insert('hajime no ippo is the best anime')
result = multi <= multi1
self.assertTrue(result)
def test_equal_set(self):
multi = MultiSet()
multi1 = MultiSet()
multi.insert(1)
multi1.insert(5)
multi1.insert(6)
multi.insert(6)
multi1.insert(1)
multi.insert(5)
result = multi <= multi1
self.assertTrue(result)
def test_not_subset(self):
multi = MultiSet()
multi1 = MultiSet()
multi.insert(1)
multi.insert(4101341304)
multi.insert(24325)
multi1.insert(5455)
multi1.insert(1)
multi1.insert(4101341304)
result = multi <= multi1
self.assertFalse(result)
def test_switched_subset(self):
multi = MultiSet()
multi1 = MultiSet()
multi.insert(1)
multi.insert(2)
multi.insert(3)
multi1.insert(1)
multi1.insert(2)
result = multi <= multi1
self.assertFalse(result)
def test_multiple_occurrences_subset(self):
multi = MultiSet()
multi.insert(1)
multi.insert(2)
multi.insert(2)
multi.insert(3)
multi.insert(3)
multi.insert(3)
multi1 = MultiSet()
multi1.insert(1)
multi1.insert(1)
multi1.insert(2)
multi1.insert(2)
multi1.insert(3)
multi1.insert(3)
multi1.insert(3)
multi1.insert(3)
result = multi <= multi1
self.assertTrue(result)
def test_single_occurrence_subset(self):
multi = MultiSet()
multi.insert(1)
multi.insert(10)
multi.insert(10)
multi.insert(30)
multi.insert(30)
multi.insert(30)
multi1 = MultiSet()
multi1.insert(1)
multi1.insert(10)
multi1.insert(10)
multi1.insert(10)
multi1.insert(30)
multi1.insert(30)
multi1.insert(30)
result = multi <= multi1
self.assertTrue(result)
def test_single_occurrences_false_subset(self):
multi = MultiSet()
multi.insert('a')
multi.insert('b')
multi.insert('b')
multi.insert('c')
multi1 = MultiSet()
multi1.insert('a')
multi1.insert('b')
multi1.insert('c')
multi1.insert('c')
multi1.insert('a')
result = multi <= multi1
self.assertFalse(result)
class TestSubtraction(unittest.TestCase):
def test_subtraction(self):
multi = MultiSet()
multi1 = MultiSet()
multi1.insert('a')
multi.insert('b')
multi1.insert('b')
multi.insert('a')
multi1.insert('c')
result = multi1 - multi
multi2 = MultiSet()
multi2.insert('c')
expected = multi2
self.assertEqual(result, expected)
def test_empty_set(self):
multi = MultiSet()
multi1 = MultiSet()
result = multi - multi1
expected = MultiSet()
self.assertEqual(result, expected)
def test_same_set(self):
x = MultiSet()
y = MultiSet()
x.insert('warble')
y.insert('warble')
x.insert('garble')
y.insert('garble')
x.insert('1234567890')
y.insert('1234567890')
result = x - y
expected = MultiSet()
self.assertEqual(result, expected)
def test_smaller_subtract_bigger_set(self):
x = MultiSet()
y = MultiSet()
x.insert(12)
x.insert(15)
x.insert(15)
x.insert(50)
x.insert(25)
x.insert(25)
x.insert(25)
y.insert(13)
y.insert(12)
y.insert(25)
y.insert(25)
y.insert(25)
y.insert(25)
y.insert(25)
y.insert(100)
result = x - y
z = MultiSet()
z.insert(15)
z.insert(15)
z.insert(50)
expected = z
self.assertEqual(result, expected)
class TestMutatedSubtraction(unittest.TestCase):
def test_mutated_subtraction(self):
multi = MultiSet()
multi1 = MultiSet()
multi1.insert('a')
multi.insert('b')
multi1.insert('b')
multi.insert('a')
multi1.insert('c')
multi1 -= multi
multi3 = MultiSet()
multi3.insert('c')
result = multi1
expected = multi3
self.assertEqual(result, expected)
def test_integer_mutated_subtraction(self):
x = MultiSet()
y = MultiSet()
x.insert(1)
x.insert(1)
x.insert(2)
x.insert(2)
y.insert(2)
y.insert(2)
z = MultiSet()
z.insert(1)
z.insert(1)
x -= y
result = x
expected = z
self.assertEqual(result, expected)
def test_disjoint_set(self):
x = MultiSet()
y = MultiSet()
x.insert('a')
x.insert('b')
x.insert('t')
x.insert('c')
x.insert('c')
y.insert('d')
y.insert('d')
y.insert('z')
y.insert('DYEL?')
x -= y
result = x
z = MultiSet()
z.insert('c')
z.insert('c')
z.insert('t')
z.insert('b')
z.insert('a')
expected = z
self.assertEqual(result, expected)
def test_equal_set(self):
multi = MultiSet()
multi1 = MultiSet()
multi.insert(1)
multi1.insert(5)
multi1.insert(6)
multi.insert(6)
multi1.insert(1)
multi.insert(5)
multi -= multi1
result = multi
expected = MultiSet()
self.assertEqual(result, expected)
class TestAddition(unittest.TestCase):
def test_addition(self):
multi = MultiSet()
multi1 = MultiSet()
multi1.insert('a')
multi.insert('b')
multi1.insert('b')
multi.insert('a')
multi1.insert('c')
result = multi1 + multi
multi2 = MultiSet()
multi2.insert('c')
multi2.insert('a')
multi2.insert('a')
multi2.insert('b')
multi2.insert('b')
expected = multi2
self.assertEqual(result, expected)
def test_empt_set(self):
x = MultiSet()
y = MultiSet()
result = x + y
expected = MultiSet()
self.assertEqual(result, expected)
def test_multiple_occurrences(self):
x = MultiSet()
y = MultiSet()
x.insert(5)
x.insert(5)
x.insert(10)
x.insert(10)
x.insert(10)
x.insert(17.5)
x.insert(17.5)
x.insert(0.5)
y.insert(17.5)
y.insert(10)
y.insert(3.14159)
y.insert(0.5)
y.insert(0.5)
result = x + y
z = MultiSet()
z.insert(5)
z.insert(5)
z.insert(10)
z.insert(10)
z.insert(10)
z.insert(17.5)
z.insert(17.5)
z.insert(0.5)
z.insert(17.5)
z.insert(10)
z.insert(3.14159)
z.insert(0.5)
z.insert(0.5)
expected = z
self.assertEqual(result, expected)
class TestMutatedAddition(unittest.TestCase):
def test_mutated_addition(self):
multi = MultiSet()
multi1 = MultiSet()
multi1.insert('a')
multi.insert('b')
multi1.insert('b')
multi.insert('a')
multi1.insert('c')
multi1 += multi
multi3 = MultiSet()
multi3.insert('c')
multi3.insert('a')
multi3.insert('a')
multi3.insert('b')
multi3.insert('b')
result = multi1
expected = multi3
self.assertEqual(result, expected)
def test_empty_set(self):
x = MultiSet()
y = MultiSet()
x += y
result = x
expected = MultiSet()
self.assertEqual(result, expected)
def test_disjoint_set(self):
x = MultiSet()
y = MultiSet()
x.insert('a')
x.insert('b')
x.insert('t')
x.insert('c')
x.insert('c')
y.insert('d')
y.insert('d')
y.insert('z')
y.insert('DYEL?')
x += y
result = x
z = MultiSet()
z.insert('c')
z.insert('c')
z.insert('t')
z.insert('b')
z.insert('a')
z.insert('d')
z.insert('d')
z.insert('z')
z.insert('DYEL?')
expected = z
self.assertEqual(result, expected)
def test_equal_set(self):
multi = MultiSet()
multi1 = MultiSet()
multi.insert(1)
multi1.insert(5)
multi1.insert(6)
multi.insert(6)
multi1.insert(1)
multi.insert(5)
multi += multi1
result = multi
z = MultiSet()
z.insert(1)
z.insert(1)
z.insert(6)
z.insert(6)
z.insert(5)
z.insert(5)
expected = z
self.assertEqual(result, expected)
class TestAnd(unittest.TestCase):
def test_and(self):
multi = MultiSet()
multi1 = MultiSet()
multi.insert('a')
multi.insert('b')
multi.insert('b')
multi1.insert('c')
multi1.insert('b')
multi.insert('a')
result = multi & multi1
multi2 = MultiSet()
multi2.insert('b')
expected = multi2
self.assertEqual(result, expected)
def test_empty_Set(self):
x = MultiSet()
y = MultiSet()
result = x & y
expected = MultiSet()
self.assertEqual(result, expected)
def test_disjoint_set(self):
x = MultiSet()
y = MultiSet()
x.insert('1')
x.insert('so many test cases...')
y.insert('61')
y.insert('its getting kinda annoying thinking of values')
result = x & y
expected = MultiSet()
self.assertEqual(result, expected)
def test_multiple_occurrences_set(self):
x = MultiSet()
y = MultiSet()
x.insert(1)
x.insert(5)
x.insert(5)
x.insert(7)
x.insert(7)
y.insert(10)
y.insert(5)
y.insert(7)
y.insert(5)
y.insert(7)
result = x & y
z = MultiSet()
z.insert(5)
z.insert(5)
z.insert(7)
z.insert(7)
expected = z
self.assertEqual(result, expected)
class TestMutatedAnd(unittest.TestCase):
def test_mutate_and_simple(self):
multi = MultiSet()
multi1 = MultiSet()
multi.insert('a')
multi.insert('b')
multi.insert('b')
multi1.insert('c')
multi1.insert('b')
multi.insert('a')
multi &= multi1
result = multi
multi2 = MultiSet()
multi2.insert('b')
expected = multi2
self.assertEqual(result, expected)
def test_empty_set(self):
x = MultiSet()
y = MultiSet()
x &= y
result = x
expected = MultiSet()
self.assertEqual(result, expected)
def test_disjoint_set(self):
x = MultiSet()
y = MultiSet()
x.insert('1')
x.insert('so many test cases...')
y.insert('61')
y.insert('its getting kinda annoying thinking of values')
x &= y
result = x
expected = MultiSet()
self.assertEqual(result, expected)
class TestIsDisjoint(unittest.TestCase):
def test_disjoint(self):
multi = MultiSet()
multi1 = MultiSet()
result = multi.isdisjoint(multi1)
self.assertTrue(result)
def test_subset_set(self):
x = MultiSet()
y = MultiSet()
x.insert(1)
y.insert(3)
x.insert(5)
y.insert(1)
result = x.isdisjoint(y)
self.assertFalse(result)
def test_multiple_occurrence_set(self):
x = MultiSet()
y = MultiSet()
x.insert('a')
x.insert('a')
x.insert('b')
x.insert('b')
x.insert('b')
x.insert('c')
y.insert('a')
y.insert('b')
y.insert('c')
result = x.isdisjoint(y)
self.assertFalse(result)
def test_true_disjoint(self):
x = MultiSet()
y = MultiSet()
x.insert(1)
y.insert(2)
x.insert(100)
y.insert(101)
x.insert(500024)
y.insert(999)
result = x.isdisjoint(y)
self.assertTrue(result)
def test_true_set(self):
x = MultiSet()
y = MultiSet()
x.insert(True)
y.insert(1)
result = x.isdisjoint(y)
self.assertTrue(result)
if __name__ == '__main__':
unittest.main(exit=False)
|
Markdown | UTF-8 | 892 | 3.046875 | 3 | [] | no_license | # QuizApp
This is a Science Quiz app that quizes a user about a general science Knowledge.
The app gets the user's name with an edit text view and get gender with a radio button.
the app comprises 10 questions, the questions with more than one correct option uses check boxes,
the questions with only one correct option uses radio buttons and radio button group.
the question with no option uses an edit text to get the answer as text.
the app also includes two buttons which are submit button and reset button.
the submit button displays a toast showing the user's name (Mr. or Mrs), and
the toast also shows the failed questions and hints to answer them.
the reset button take each question back to their default, so that another user can play.
the link below contains the apk file and screenshots of the project.
https://drive.google.com/drive/folders/1yX4YHkDnwlw6EYWd-km4BDn4N6Q13-5F
|
Python | UTF-8 | 1,389 | 3.046875 | 3 | [] | no_license | #!/usr/bin/env python3
# tratando de escribir el stdout a un archivo
import os, socket, subprocess
#Server
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234)) # socket.gethostname() = localhost
s.listen(1)
conn, addr = s.accept()
print(f"connected by {addr}")
#proc =
while(1):
data = conn.recv(1024) # data is binary type, must be decoded and converted to string to read received content
#print(type(data))
#print(data.decode("utf-8")) #used for debugging pruposes
if not data: break
while True:
if (data.decode("utf-8")) == 'ls':
print(data)
x = socket.os.listdir()
for i in x:
conn.sendall(''.join(map(str,i + '\n')).encode())
#because the executed command is a list, we have to strip the format and convert it to string and adding a newLine
if (data.decode('utf-8')) == 'uname':
x = socket.os.uname()
print(x)
conn.sendall(''.join(x).encode()) # just stripping the list format with the ''.join() function
if (data.decode('utf-8')) == 'pwd':
x = socket.os.getcwd()
conn.sendall(''.join(x).encode())
conn.close
if __name__=='__main__':
main()
|
C# | UTF-8 | 2,626 | 3.234375 | 3 | [] | no_license | using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SeleniumProject.ComponentHelper
{
public class ExcelReaderHelper_KD
{
private static IDictionary<string,IExcelDataReader> _cache;
private static FileStream stream;
private static IExcelDataReader reader;
static ExcelReaderHelper_KD()
{
_cache = new Dictionary<string, IExcelDataReader>();
}//adding it to cache makes the data driving much faster
private static IExcelDataReader GetExcelReader(string xlpath, string sheetName)
{//get into dictry mode n get the object from xls
if (_cache.ContainsKey(sheetName))
{
reader = _cache[sheetName];//returns obj of type reader
}
else
{
stream = new FileStream(xlpath, FileMode.Open, FileAccess.Read);
//returns Iexcelreaderobject
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
_cache.Add(sheetName, reader);
}
return reader;
}
public static object GetCellData(string xlpath, string sheetName, int row, int column) //obj is the return type of the data in the excel file
{
//gives the value of the specific cell
IExcelDataReader _reader = GetExcelReader(xlpath,sheetName);
DataTable table = _reader.AsDataSet().Tables[sheetName];
return GetData(table.Rows[row][column].GetType(), table.Rows[row][column]);
}
//type class gives us detail about the object type which we are retriving from the excel
private static object GetData(Type type, object data)
{//based on the data type returns us the tpe of object
switch(type.Name)
{
case "String":
return data.ToString();
case "Double":
return Convert.ToDouble(data);
case "DateTime":
return Convert.ToDateTime(data);
default:
return data.ToString();
}
}
//get total rows in excel
public static int GeTotalRows(string xlpath, string sheetName)
{
//cacahe method gets the reader object
IExcelDataReader _reader = GetExcelReader(xlpath, sheetName);
return reader.AsDataSet().Tables[sheetName].Rows.Count;
}
}
}
|
Markdown | UTF-8 | 9,407 | 3.0625 | 3 | [] | no_license | 具体查看:
[主题/theme/说明文档](https://vuepress.vuejs.org/zh/theme/)
[默认主题配置/说明文档](https://vuepress.vuejs.org/zh/theme/default-theme-config.html)
[自定义主题/说明文档](https://vuepress.vuejs.org/zh/theme/)
[默认主题配置/仓库](https://github.com/vuejs/vuepress/blob/master/packages/%40vuepress/theme-default) *继承默认主题,自定义主题*
通过上面的说明文档,就可以配置主题了!
- 导航栏: 页面标题、搜索框、 导航栏链接、多语言切换、仓库链接
- 侧边栏: 自动生成侧边栏、多侧边栏、无侧边栏
- 搜索框
- 最后更新时间
- 上/下一篇链接
- 个别页面设置自定义样式及布局
技巧: 看文档配置多试试就会了。
```?
FIXME 2021/09/17 星期五
侧边栏 displayAllHeaders 的效果没有看出来?
如何自定义主题?待看
```
---
## x、 侧边栏
一个文件夹中有多个文件,如何设置在一个侧边栏中?
侧边栏可以是数组对象表示有多个分组,侧边栏是对象表示有多个侧边栏。
多个侧边栏:
``` JS
// 单个侧边栏 (注意,观察/单个侧边栏/数据类型)
sidebar: [
// String 路径 '/path1/page1'
// Array [路径,名称] ['/path1/page1', '侧边栏显示名称']
// Object 分组对象 { title: '分组显示名称', path: '/path1/page1' } 具体示例看下面
]
// 多个侧边栏 (原理:一个路径/匹配/一个侧边栏/数据)
// 如何理解 sidebar 某个路径 key对应的数组?
// (把这个数组看成单个侧边栏 sidebar 去设置即可,数据类型看上面。)
sidebar: {
'路径1/对应/侧边栏': [],
'路径2/对应/侧边栏': [],
}
// 侧边栏分组 (原理:单个侧边栏/数据类型/支持/分组对象)
sidebar: [
// 分组对象
{
title: '分组显示名称',
path: '分组显示名称/点击跳转的路径(可以不写)',
sidebarDepth: '分组下的页面/自动显示侧边栏(标题链接)层级深度',
collapsable: '分组显示名称/是否展示收起按钮(不展示,默认全部展开)',
children: ['分组下的页面'],
}
// 可以,再来一个分组对象
// {...}
]
// 多个侧边栏/某个路径的侧边栏分组
// (原理:sidebar 某个路径 key对应的数组,等同于单个侧边栏 sidebar 的配置,且支持分组。)
sidebar: {
'路径1/对应/侧边栏': [
{
title: '分组1',
children: []
},
{
title: '分组2',
children: []
}
],
}
// 多个侧边栏/某个路径的侧边栏分组/嵌套/侧边栏分组
// 如何理解 children 对应的数组?
// (把这个数组看成单个侧边栏 sidebar 去设置即可,数据类型看上面。)
sidebar: {
'路径1/对应/侧边栏': [
{
title: '大标题(比如:路径1)',
children: [
{
title: '分组1',
children: []
},
{
title: '分组2',
children: []
}
]
}
],
}
```
### 侧边栏/路径
侧边栏,对应的路径写法,如下
``` JS
module.exports = {
themeConfig: {
sidebar: {
'/sl/': [
{
title: '使用指南',
path: '/sl/guide/', /* 对应文件 sl/guide/README.md */
collapsable: true,
sidebarDepth: 3,
children: [
// 分组/折叠面板/显示项
'/sl/guide/use', /* 对应文件 sl/guide/use.md */
'/sl/guide/link', /* 对应文件 sl/guide/link.md */
]
},
{
title: '插件应用',
path: '/sl/plugin/',
},
]
}
}
}
```
注意:
1. README.md 类型的文件 path 需要用 / 结尾表示
2. 所有的文件路径需要写完整,不要相对 侧边栏key 去写 (有坑)
### 复杂的侧边栏示例
侧边栏 支持 多语言 每种语言都包含多个产品的文档 每个产品包含多个功能模块文档
语言
语言/产品
语言/产品/功能
语言/产品/功能/细化
``` JS
// .vuepress/config.js
module.exports = {
// 自动显示所有页面的标题链接
displayAllHeaders: false, // 不自动
themeConfig: {
// 默认的语言/侧边栏/写在 themeConfig.sidebar 中
sidebar: {
// 产品/1
'p1': [
{
title: '产品/1/功能/1',
path: '/p1/f1/', /* 对应文件 p1/f1/README.md */
collapsable: true, /* 有点卡.... */
sidebarDepth: 3, /* 显示所有页面的标题链接,层级 */
children: [
'/p1/f1/t1', /* 对应文件 p1/f1/t1.md */
'/p1/f1/t2', /* 对应文件 p1/f1/t2.md */
]
},
{
title: '产品/1/功能/2',
path: '/p2/f2/', /* 对应文件 p1/f2/README.md */
}
],
// 产品/2
'/mp/': [
{
title: '产品/2/功能/1',
path: '/p2/f1/',
}
],
}
// 别的语言/侧边栏/写在 themeConfig.对应语言 中
// 默认的语言/侧边栏/写在 themeConfig.对应语言.sidebar 中
'/en/': {
sidebar: {
// 产品/2
'p1': [
{
title: '产品/1/功能/1',
path: '/en/p1/f1/', /* 对应文件 en/p1/f1/README.md */
collapsable: true,
sidebarDepth: 3,
children: [
'/en/p1/f1/t1', /* 对应文件 en/p1/f1/t1.md */
'/en/p1/f1/t2', /* 对应文件 en/p1/f1/t2.md */
]
},
{
title: '产品/1/功能/2',
path: '/en/p2/f2/', /* 对应文件 en/p1/f2/README.md */
}
],
// 产品/2
'/mp/': [
{
title: '产品/2/功能/1',
path: '/en//p2/f1/',
}
],
}
}
}
}
```
---
## x、修改默认页面
### 修改默认页面/404
404页面自定义修改,新建 `.vuepress/theme/layouts/NotFound.vue`,然后重启服务,就可以看到自定义的404页面了。
emm...404的页面是变了,但是别的页面也全都变化了...
因为这个操作等于使用了一个新的主题,该主题应该继承一下默认主题,所以需要新建 theme/index.js。
``` JS
module.exports = {
extend: '@vuepress/theme-default'
}
```
但是,发现 本地 / github.io 访问一个不存在的路径,可以正常显示404页面,不是重定向,而是在当前页面直接显示。
线上展示的却是 404 Not Found | nginx,应该是直接按照资源路径寻找没有找到,但是 vue 的 404 没有生效的感觉,需要配置 nginx 404 时指向 404.html。
备注:url没有变化,可能是访问的不存在的资源时,直接返回了 404.html 的内容。
<img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c2685eb9611a4f5e87a2647bcd771efd~tplv-k3u1fbpfcp-zoom-1.image" style="display:block;width: 600px;" />
---
## x、 首页/自定义样式
如何自定义首页样式? *--2021/09/17*
参考微信官方文档:https://developers.weixin.qq.com/doc/
---
## x、 网站icon
如何自定义网站的标签页icon? *--2021/09/17*
[设置icon](https://vuepress.vuejs.org/zh/config/#head)
---
## x、 导航栏
你可以通过 [开发主题/网站的元数据](https://vuepress.vuejs.org/zh/theme/writing-a-theme.html#%E7%BD%91%E7%AB%99%E5%92%8C%E9%A1%B5%E9%9D%A2%E7%9A%84%E5%85%83%E6%95%B0%E6%8D%AE) 来对用户开放一些自定义主题的配置 -- 比如指定目录或者页面的顺序,你也可以结合 $site.pages 来动态地构建导航链接。
### 导航栏/隐藏
1、首页没有显示导航栏
```?
FIXME 2021/09/17 星期五
2、下滑导航栏自动隐藏 ? (微信文档)
```
theme
自定义导航栏(navbar)、 侧边栏(sidebar)和 首页(homepage) 等
---
## x、 md/自定义样式
有如下3中自定义样式的方法,他们有什么区别?
### 特定页面的自定义布局
`特定页面的自定义布局` : 使用默认主题,只是某个页面用自己的 vue
[特定页面的自定义布局](https://vuepress.vuejs.org/zh/theme/default-theme-config.html#%E7%89%B9%E5%AE%9A%E9%A1%B5%E9%9D%A2%E7%9A%84%E8%87%AA%E5%AE%9A%E4%B9%89%E5%B8%83%E5%B1%80)
场景:自定义首页布局 `.vuepress/components/XmLayoutIndex.vue`
``` shell
# 在某个 md 中使用 XmLayoutIndex 布局
---
layout: XmLayoutIndex
---
```
### 主题的继承
`主题的继承` : 基于默认主题,自己写一整套主题
[主题的继承](https://vuepress.vuejs.org/zh/theme/inheritance.html)
场景:自定义每个页面的导航栏布局
``` JS
// .vuepress/theme/index.js
// 注意: 看到 vuepress 项目中有 `.vuepress/theme/index.js` ,内容如下,表示使用了继承默认主题的自定义主题哈~
export default {
extend: '@vuepress/theme-default'
}
```
FIXME 可能需要安装相关插件 访问父级组件
[示例/主题的继承](https://github.com/vuejs/vuepress/tree/master/packages/%40vuepress/theme-vue)
[默认主题](https://github.com/vuejs/vuepress/tree/master/packages/%40vuepress/theme-default) *基于默认主题,自己写一整套主题,需要查看*
### 开发主题
`开发主题` : 自己写一整套主题
[开发主题](https://vuepress.vuejs.org/zh/theme/writing-a-theme.html)
场景:大佬...
|
PHP | UTF-8 | 691 | 2.9375 | 3 | [] | no_license | <?php
/**
* Class CheckJoomlaCredentials
*/
class CheckJoomlaCredentials
{
/**
* @param string $username
* @param string $password
* @param \User $user
*
* @return bool
*/
public function checkLegacyJoomlaCredentials($username, $password, \User $user)
{
list($legacyPasswordHash, $legacyPasswordSalt) = explode(':', $user->password);
// Check if password matches
if ($legacyPasswordHash !== md5($password.$legacyPasswordSalt)) {
return false;
}
// Update password hash in database
$user->password = \Encryption::hash($password);
$user->save();
return true;
}
}
|
C# | UTF-8 | 3,036 | 3.1875 | 3 | [] | no_license | using System;
using System.Globalization;
namespace Telekad.Utils
{
public static class AttributeUtils
{
/// <summary>
/// Attempts to retrieve an attribute from a type
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static bool TryGetAttribute<TAttribute>(this Type type, out TAttribute attr)
where TAttribute : Attribute
{
object[] attrs = type.GetCustomAttributes(typeof(TAttribute), true);
if (attrs.Length > 0)
{
attr = attrs[0] as TAttribute;
return true;
}
attr = null;
return false;
}
/// <summary>
/// Retrieve an attribute from a type
/// </summary>
public static TAttribute GetAttribute<TAttribute>(this Type type)
where TAttribute : Attribute
{
TAttribute attr;
if (!type.TryGetAttribute(out attr))
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Expected '{0}' attribute not found!", typeof(TAttribute)));
return attr;
}
/// <summary>
/// Attempts to retrieve an attribute from an enum field
/// </summary>
public static bool TryGetFieldAttribute<TAttribute>(this Enum enumField, out TAttribute attr)
where TAttribute : Attribute
{
var fi = enumField.GetType().GetField(enumField.ToString());
if (fi != null)
{
var attrs = fi.GetCustomAttributes(typeof(TAttribute), true);
if (attrs.Length > 0)
{
attr = attrs[0] as TAttribute;
return true;
}
}
attr = null;
return false;
}
/// <summary>
/// Retrieves an attribute from an enum field (Throws an exception if not found)
/// </summary>
public static TAttribute GetFieldAttribute<TAttribute>(this Enum enumField)
where TAttribute : Attribute
{
TAttribute result;
if (!TryGetFieldAttribute(enumField, out result))
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Expected '{0}' attribute not found!", typeof(TAttribute)));
return result;
}
/// <summary>
/// Indicates whether an enum field is decorated with the specified attribute
/// </summary>
public static bool IsDecoratedWith<TAttribute>(this Enum enumField)
where TAttribute : Attribute
{
var fi = enumField.GetType().GetField(enumField.ToString());
if (fi != null)
{
var attrs = fi.GetCustomAttributes(typeof(TAttribute), true);
return attrs.Length > 0;
}
return false;
}
}
}
|
Ruby | UTF-8 | 3,061 | 2.734375 | 3 | [] | no_license | require 'util/http_verify_none.rb'
require 'net/https'
require 'uri'
require 'cgi'
require 'yaml'
class Autoingestion
ITUNES_URL = "https://reportingitc.apple.com/autoingestion.tft"
attr_accessor :username
attr_accessor :password
attr_accessor :vendor_number
attr_accessor :type_of_report
attr_accessor :date_type
attr_accessor :report_type
attr_accessor :report_date
def create_post_body
data = "USERNAME=" + CGI.escape(@username.to_s) + "&"
data += "PASSWORD=" + CGI.escape(@password.to_s) + "&"
data += "VNDNUMBER=" + CGI.escape(@vendor_number.to_s) + "&"
data += "TYPEOFREPORT=" + CGI.escape(@type_of_report.to_s) + "&"
data += "DATETYPE=" + CGI.escape(@date_type.to_s) + "&"
data += "REPORTTYPE=" + CGI.escape(@report_type.to_s) + "&"
data += "REPORTDATE=" + CGI.escape(@report_date.to_s)
end
def perform_request
uri = URI.parse(ITUNES_URL)
request = Net::HTTP.new(uri.host, uri.port)
request.use_ssl = true
body = create_post_body
headers = {'Content-Type' => 'application/x-www-form-urlencoded'}
response = request.post2(uri.path, body, headers)
if response['filename'] != nil
filename = response['filename']
f = File.new("output/" + filename, "w")
f.write(response.body)
f.close
puts "File Downloaded Successfully (#{filename})"
elsif response['errormsg'] != nil
puts response['errormsg']
else
puts "No recognized response, dumping headers.."
response.each_header do | key, value |
puts "#{key}: #{value}"
end
end
end
end
autoingestor = Autoingestion.new
yesterday = (Time.new - 24*60*60).strftime("%Y%m%d")
if File.exists?("config.yml")
config = YAML::load(File.open("config.yml"))
autoingestor.username = config['username']
autoingestor.password = config['password']
autoingestor.vendor_number = config['vendor_number']
else
print "iTunes Connect email address: "
autoingestor.username = gets.strip!
print "iTunes Connect password: "
begin # Don't show the user's password in the console
system("stty -echo")
autoingestor.password = gets.strip!
ensure
system("stty echo")
end
print "Vendor number: "
autoingestor.vendor_number = gets.strip!
print "Type of report: [Sales] "
autoingestor.type_of_report = gets.strip!
print "Date type: [Daily] "
autoingestor.date_type = gets.strip!
print "Report type: [Summary] "
autoingestor.report_type = gets.strip!
print "Report date: [#{yesterday}] "
autoingestor.report_date = gets.strip!
end
autoingestor.type_of_report = "Sales" if autoingestor.type_of_report.nil?
autoingestor.date_type = "Daily" if autoingestor.date_type.nil?
autoingestor.report_type = "Summary" if autoingestor.report_type.nil?
autoingestor.report_date = yesterday if autoingestor.report_date.nil?
autoingestor.perform_request
|
C++ | UTF-8 | 2,539 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
struct fuku_tds_section {
uint32_t offset;
uint32_t size;
uint16_t index;
uint16_t type;
};
enum fuku_tds_result {
tds_result_ok,
tds_result_error
};
struct fuku_tds_linenumbers_block {
uint32_t segment_id;
uint32_t block_start;
uint32_t block_end;
std::map<uint16_t, uint32_t> line_numbers; //linenumber : segment offset
};
struct fuku_tds_linenumbers {
std::string file_name;
std::vector<fuku_tds_linenumbers_block> blocks;
};
struct fuku_tds_function {
std::string function_name;
uint32_t segment_id;
uint32_t function_start;
uint32_t function_size;
uint32_t function_debug_size;
};
struct fuku_tds_data {
std::string data_name;
uint32_t segment_id;
uint32_t data_start;
};
struct fuku_tds_const {
std::string const_name;
uint32_t const_size;
std::vector<uint8_t> value;
};
struct fuku_tds_segment {
std::string segment_name;
uint32_t segment_id;
uint32_t segment_start;
uint32_t segment_size;
};
class fuku_tds {
std::vector<std::string> names_pool;
std::vector<uint8_t> tds_data;
std::vector<fuku_tds_segment> segments;
std::vector<fuku_tds_linenumbers> linenumbers;
std::vector<fuku_tds_function> functions;
std::vector<fuku_tds_data> datas;
std::vector<fuku_tds_const> consts;
std::string fuku_tds::get_name_by_id(uint32_t id) const;
uint32_t fuku_tds::get_id_by_name(const std::string &name) const;
void fuku_tds::load_names(uint8_t * names_ptr);
void fuku_tds::parse_modules(const uint8_t * start, const uint8_t * end);
void fuku_tds::parse_symbols(const uint8_t * start, const uint8_t * end);
void fuku_tds::parse_alignsym(uint8_t * start, uint8_t * end, int moduleIndex);
void fuku_tds::parse_globalsym(uint8_t * start);
void fuku_tds::parse_src_module(uint8_t * start, uint8_t * end); //linenumbers
public:
fuku_tds::fuku_tds();
fuku_tds::~fuku_tds();
fuku_tds_result fuku_tds::load_from_file(const std::string& tds_path);
fuku_tds_result fuku_tds::load_from_data(const std::vector<uint8_t>& tds_data);
public:
const std::vector<fuku_tds_segment>& fuku_tds::get_segments() const;
const std::vector<fuku_tds_linenumbers>& fuku_tds::get_linenumbers() const;
const std::vector<fuku_tds_function>& fuku_tds::get_functions() const;
const std::vector<fuku_tds_data>& fuku_tds::get_datas() const;
const std::vector<fuku_tds_const>& fuku_tds::get_consts() const;
};
|
PHP | UTF-8 | 202 | 3.0625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env php
<?php
$scope = 12;
$width = 4;
for($y = 1; $y <= $scope; ++$y)
{
for($x = 1; $x <= $scope; ++$x)
{
echo str_pad($x * $y, $width, ' ', STR_PAD_LEFT);
}
echo PHP_EOL;
}
|
C | UTF-8 | 15,528 | 2.5625 | 3 | [] | no_license | #include "ConsoleShell.h"
#include "Console.h"
#include "Keyboard.h"
#include "Utility.h"
#include "PIT.h"
#include "RTC.h"
#include "AssemblyUtility.h"
#include "Task.h"
#include "ShutDownPC.h"
// 커맨드 테이블 정의하기, 커맨드 테이블에서 문자열 비교후 함수 포인터를 사용해서 해당 커맨드를 실행할 것이다
SHELLCOMMANDENTRY gs_vstCommandTable[] =
{
{"help", "Show Help", kHelp},
{"cls", "Clear Screen", kCls},
{"totalram", "Show Total RAM Size", kShowTotalRAMSize},
{"strtod", "String To Decimal/Hex Convert", kStringToDecimalHexTest},
{"shutdown", "Shutdown And Reboot OS", kShutdown},
{"settimer", "Set PIT Controller Counter0, ex)settimer 10(ms) 1(periodic)", kSetTimer},
{"wait", "Wait ms Using PIT, ex)wait 100(ms)", kWaitUsingPIT},
{"rdtsc", "Read Time Stamp Counter", kReadTimeStampCounter},
{"cpuspeed", "Measure Processor Speed", kMeasureProcessorSpeed},
{"date", "Show Date And Time", kShowDateAndTime},
{"createtask", "Create Task, ex)createtask 1(type) 10(count)", kCreateTestTask},
{"changepriority", "Change Task Priority, ex)changepriority 1(ID) 2(Priority)", kChangeTaskPriority},
{"tasklist", "Show Task List", kShowTaskList},
{"killtask", "End Task, ex)killtask 1(ID)", kKillTask},
{"cpuload", "Show Processor Load", kCPULoad},
{"poweroff", "Shutdown PC", kPowerOffPC},
};
//======================
// 이제 실제 shell 코드
//======================
// 메인 루프
void kStartConsoleShell(void){
char vcCommandBuffer[CONSOLESHELL_MAXCOMMANDBUFFERCOUNT];
int iCommandBufferIndex = 0;
BYTE bKey;
int iCursorX, iCursorY;
// 프롬프트 출력 (키 입력 준비 완료 표시)
kLKYPrintf(PROMPTMESSAGE, CONSOLESHELL_PROMPTMESSAGE);
while(1){
// 키 수신 대기
bKey = kGetCh();
// Backspace (지우기) 처리
if(bKey == KEY_BACKSPACE){
// 커맨드 버퍼가 차있을 경우에만 지우기가 가능하므로 조건 처리한다
if(iCommandBufferIndex > 0){
// 커서 위치 앞으로 옮겨서 지우고 커맨드 버퍼에서 마지막 문자 지우기
kGetCursor(&iCursorX, &iCursorY);
kPrintStringXY(iCursorX -1, iCursorY, " ");
kSetCursor(iCursorX -1, iCursorY);
iCommandBufferIndex--;
}
}
// 엔터 키 처리
else if(bKey == KEY_ENTER){
kPrintf("\n");
// 커맨드 버퍼가 차있으면 해당 커맨드를 실행한다!
if(iCommandBufferIndex > 0){
vcCommandBuffer[iCommandBufferIndex] = '\0';
kExecuteCommand(vcCommandBuffer);
}
// 프롬프트 다시 출력하고 커맨드 버퍼는 초기화 한다
kLKYPrintf(PROMPTMESSAGE, CONSOLESHELL_PROMPTMESSAGE);
kMemSet(vcCommandBuffer, '\0', CONSOLESHELL_MAXCOMMANDBUFFERCOUNT);
iCommandBufferIndex = 0;
}
// Shift 등 나머지 특수키는 일단 무시
else if((bKey == KEY_LSHIFT) || (bKey == KEY_RSHIFT) || (bKey == KEY_CAPSLOCK) || (bKey == KEY_NUMLOCK) || (bKey == KEY_SCROLLLOCK)) ;
// 일반 문자 처리
else {
// TAB 일 경우, 커맨드 버퍼에는 공백으로 들어갈 것이기에 공백 처리
if(bKey == KEY_TAB) bKey = ' ';
// 버퍼에 공간이 있어야만 커맨드 버퍼에 문자 추가
if(iCommandBufferIndex < CONSOLESHELL_MAXCOMMANDBUFFERCOUNT){
vcCommandBuffer[iCommandBufferIndex++] = bKey;
kLKYPrintf(INPUTMESSAGE ,"%c", bKey);
}
else kLKYPrintf(ERRORMESSAGE, "\nToo Long Command, Press Enter First");
}
}
}
// 커맨드 버퍼에 있는 커맨드를 테이블과 비교해서 해당 함수 수행하는 함수
void kExecuteCommand(const char* pcCommandBuffer){
int i, iSpaceIndex;
int iCommandBufferLength, iCommandLength;
int iCount;
// 공백으로 커맨드 분리하여 추출함 (첫번째가 커맨드이기에 첫째 공백까지만 탐색)
iCommandBufferLength = kStrLen(pcCommandBuffer);
for(iSpaceIndex = 0; iSpaceIndex < iCommandBufferLength; iSpaceIndex++)
if(pcCommandBuffer[iSpaceIndex] == ' ') break;
// 커맨드 테이블에서 찾아보기
iCount = sizeof(gs_vstCommandTable) / sizeof(SHELLCOMMANDENTRY);
for(i = 0; i < iCount; i ++){
iCommandLength = kStrLen(gs_vstCommandTable[i].pcCommand);
// 길이, 내용까지 다 일치하는 지 확인하여 일치하면 해당 함수를 실행!
if((iCommandLength == iSpaceIndex) && (kMemCmp(gs_vstCommandTable[i].pcCommand, pcCommandBuffer, iSpaceIndex) == 0)){
gs_vstCommandTable[i].pfFunction(pcCommandBuffer + iSpaceIndex + 1); // 인자 넘기고 함수 실행
break;
}
}
// 테이블에 없으면 에러
if(i >= iCount)
kLKYPrintf(ERRORMESSAGE, "%s not defined\n", pcCommandBuffer);
}
// 파라미터 자료구조 초기화 하기, 여러개 파라미터는 공백으로 구분지어서 하나의 문자열로 주게 된다
void kInitializeParameter(PARAMETERLIST* pstList, const char* pcParameter){
pstList->pcBuffer = pcParameter;
pstList->iLength = kStrLen(pcParameter);
pstList->iCurrentPosition = 0;
}
// 다음 파라미터 가져오기
int kGetNextParameter(PARAMETERLIST* pstList, char* pcParameter){
int i;
int iLength;
// 파라미터가 없으면 걍 나감
if(pstList->iLength <= pstList->iCurrentPosition) return 0;
// 공백을 찾아서 해당 위치까지 파라미터를 복사하고, 현 위치를 업데이트 시켜주며 찾은 파라미터의 길이를 구해 반환한다, 복사해논 파라미터의 끝은 널문자를 추가한다
for(i = pstList->iCurrentPosition; i < pstList->iLength; i ++){
if(pstList->pcBuffer[i] == ' ') break;
}
kMemCpy(pcParameter, pstList->pcBuffer + pstList->iCurrentPosition, i);
iLength = i - pstList->iCurrentPosition;
pcParameter[iLength] = '\0';
pstList->iCurrentPosition += iLength + 1;
return iLength;
}
//====================
// 커맨드 처리 함수들
//====================
// 도움말 출력 함수
static void kHelp(const char* pcCommandBuffer){
int i;
int iCount;
int iCursorX, iCursorY;
int iLength, iMaxCommandLength = 0;
kPrintf("===================================================================\n");
kPrintf(" Shell Guide \n");
kPrintf("===================================================================\n");
iCount = sizeof(gs_vstCommandTable) / sizeof(SHELLCOMMANDENTRY);
// 가장 긴 커맨드 길이 계산, 이건 보기 좋은 포맷을 가지게 하기 위해 공백 처리 하려고
for(i = 0; i < iCount; i++){
iLength = kStrLen(gs_vstCommandTable[i].pcCommand);
if(iLength > iMaxCommandLength)
iMaxCommandLength = iLength;
}
// 도움말 출력 하기
for(i = 0; i < iCount; i ++){
kPrintf(gs_vstCommandTable[i].pcCommand);
kGetCursor(&iCursorX, &iCursorY);
kSetCursor(iMaxCommandLength, iCursorY);
kPrintf(" - %s\n", gs_vstCommandTable[i].pcHelp);
}
}
// 화면 지우기
static void kCls(const char* pcParameterBuffer){
kClearScreen();
// 맨 위는 인터럽트 표시용이라 비워둔다
kSetCursor(0, 1);
}
// 메모리 총 크기 출력
static void kShowTotalRAMSize(const char* pcParameterBuffer){
kPrintf("Total RAM Size is : %d MB\n", kGetTotalRAMSize());
}
// 숫자문자열을 숫자로 변환해서 출력함
static void kStringToDecimalHexTest(const char* pcParameterBuffer){
char vcParameter[100];
int iLength;
PARAMETERLIST stList;
int iCount = 0;
long lValue;
// 파라미터 초기화
kInitializeParameter(&stList, pcParameterBuffer);
while(1){
iLength = kGetNextParameter(&stList, vcParameter);
// 만약 다음 파라미터 길이가 0으로 나오면 없는거니까 종료
if(iLength == 0) break;
kPrintf("PARAM %d = '%s', Length = %d, ", iCount + 1, vcParameter, iLength);
// 0x로 시작하면 16진수로 바꾸고, 아니면 모두 10진수로 바꿔서 출력함
if(kMemCmp(vcParameter, "0x", 2) == 0){
lValue = kAToI(vcParameter + 2, 16);
kPrintf("HEX Value = %q\n", lValue);
}
else{
lValue = kAToI(vcParameter, 10);
kPrintf("Decimal Value = %d\n", lValue);
}
iCount ++;
}
}
// PC 재시작
static void kShutdown(const char* pcParameterBuffer){
kPrintf("System Shutdown Start...\n");
// 키보드 아무거나 눌러서 PC 재시작함
kPrintf("Press Any Key To Reboot PC...");
kGetCh();
kReboot();
}
// 타이머 시작!(Counter0 사용)
static void kSetTimer(const char* pcParameterBuffer){
char vcParameter[100];
PARAMETERLIST stList;
long lValue;
BOOL bPeriodic;
// 파라미터 초기화
kInitializeParameter(&stList, pcParameterBuffer);
// ms 추출
if(kGetNextParameter(&stList, vcParameter) == 0){
kLKYPrintf(ERRORMESSAGE, "ex)settimer 10(ms) 1(periodic)\n");
return;
}
lValue = kAToI(vcParameter, 10);
if(kMemCmp(vcParameter, "0x", 2) == 0) lValue = kAToI(vcParameter + 2, 16);
else lValue = kAToI(vcParameter, 10);
// Periodic 추출
if(kGetNextParameter(&stList, vcParameter) == 0){
kLKYPrintf(ERRORMESSAGE, "ex)settimer 10(ms) 1(periodic)\n");
return;
}
bPeriodic = kAToI(vcParameter, 10);
// 타이머 초기화
kInitializePIT(MSTOCOUNT(lValue), bPeriodic);
kPrintf("Time = %d ms, Periodic = %d Change Complete\n", ((WORD)(MSTOCOUNT(lValue) + 1)) * 1000 / PIT_FREQUENCY, bPeriodic);
}
// PIT 컨트롤러 사용 하여 ms 시간동안 대기시키기
static void kWaitUsingPIT(const char* pcParameterBuffer){
char vcParameter[100];
int iLength;
PARAMETERLIST stList;
long lMillisecond;
int i;
// 파라미터 초기화
kInitializeParameter(&stList, pcParameterBuffer);
if(kGetNextParameter(&stList, vcParameter) == 0){
kLKYPrintf(ERRORMESSAGE, "ex)wait 100(ms)\n");
return;
}
// 밀리세컨드 추출
lMillisecond = kAToI(vcParameter, 10);
kPrintf("%d ms Sleep start\n", lMillisecond);
// 인터럽트 비활성화 후 30ms 단위로 여러본 wait(30)을 호출시키고, 30으로 나눈 나머지만큼 한번 더 wait시킴
kDisableInterrupt();
for(i = 0; i < lMillisecond / 30; i ++) kWaitUsingDirectPIT(MSTOCOUNT(30));
kWaitUsingDirectPIT(MSTOCOUNT(lMillisecond % 30));
kEnableInterrupt();
kPrintf("%d ms Sleep Complete\n", lMillisecond);
// 타이머 복원
kInitializePIT(MSTOCOUNT(1), TRUE);
}
// 타임 스탬프 카운터 읽는 함수
static void kReadTimeStampCounter(const char* pcParameterBuffer){
QWORD qwTSC;
qwTSC = kReadTSC();
kPrintf("Time Stamp Counter = %q\n", qwTSC);
}
// 프로세서 속도 측정 함수
static void kMeasureProcessorSpeed(const char* pcParameterBuffer){
int i;
QWORD qwLastTSC, qwTotalTSC = 0;
kPrintf("Now Measuring.");
kDisableInterrupt();
// 10초 동안 변화한 타임 스탬프 카운터를 사용하여 프로세서 속도 측정함
for(i = 0; i < 200; i ++){
qwLastTSC = kReadTSC();
kWaitUsingDirectPIT(MSTOCOUNT(50));
qwTotalTSC += kReadTSC() - qwLastTSC;
kPrintf(".");
}
// 타이머 복원
kInitializePIT(MSTOCOUNT(1), TRUE);
kEnableInterrupt();
kPrintf("\nCPU Speed = %d MHz\n", qwTotalTSC / 10 / 1000 / 1000);
}
// RTC컨트롤러로 저아된 일자, 시간 표시
static void kShowDateAndTime(const char* pcParameterBuffer){
BYTE bSecond, bMinute, bHour;
BYTE bDayOfWeek, bDayOfMonth, bMonth;
WORD wYear;
// 읽어 오고
kReadRTCTime(&bHour, &bMinute, &bSecond);
kReadRTCDate(&wYear, &bMonth, &bDayOfMonth, &bDayOfWeek);
kPrintf("Date: %d/%d/%d %s, ", wYear, bMonth, bDayOfMonth, kConvertDayOfWeekToString(bDayOfWeek));
kPrintf("Time: %d:%d:%d\n", bHour, bMinute, bSecond);
}
// 태스크 테스트 :: 전환 함수
static void kTestTask1(void){
BYTE bData = 0;
int i = 0, iX = 0, iY = 0, iMargin, j;
CHARACTER* pstScreen = (CHARACTER*) CONSOLE_VIDEOMEMORYADDRESS;
TCB* pstRunningTask;
pstRunningTask = kGetRunningTask();
iMargin = (pstRunningTask->stLink.qwID & 0xFFFFFFFF) % 10;
for(j = 0; j < 20000; j ++)
{
switch(i)
{
case 0:
iX++;
if(iX >= (CONSOLE_WIDTH - iMargin)) i = 1;
break;
case 1:
iY++;
if(iY >= (CONSOLE_HEIGHT - iMargin)) i = 2;
break;
case 2:
iX--;
if(iX < iMargin) i = 3;
break;
case 3:
iY--;
if(iY < iMargin) i = 0;
break;
}
pstScreen[iY * CONSOLE_WIDTH + iX].bCharactor = bData;
pstScreen[iY * CONSOLE_WIDTH + iX].bAttribute = bData & 0x0F;
bData++;
//kSchedule();
}
kExitTask();
}
static void kTestTask2( void )
{
int i = 0, iOffset;
CHARACTER* pstScreen = (CHARACTER*)CONSOLE_VIDEOMEMORYADDRESS;
TCB* pstRunningTask;
char vcData[4] = {'-', '\\', '|', '/'};
pstRunningTask = kGetRunningTask();
iOffset = (pstRunningTask->stLink.qwID & 0xFFFFFFFF) * 2;
iOffset = CONSOLE_WIDTH * CONSOLE_HEIGHT - (iOffset % (CONSOLE_WIDTH * CONSOLE_HEIGHT));
while( 1 )
{
pstScreen[iOffset].bCharactor = vcData[i % 4];
pstScreen[iOffset].bAttribute = (iOffset % 15) + 1;
i++;
//kSchedule();
}
}
// 태스크 테스트 :: 생성 함수
static void kCreateTestTask(const char* pcParameterBuffer)
{
PARAMETERLIST stList;
char vcType[30];
char vcCount[30];
int i;
kInitializeParameter(&stList, pcParameterBuffer);
kGetNextParameter(&stList, vcType);
kGetNextParameter(&stList, vcCount);
switch(kAToI(vcType, 10))
{
case 1:
for(i = 0; i < kAToI(vcCount, 10) ; i ++)
if(kCreateTask(TASK_FLAGS_LOW, (QWORD)kTestTask1) == NULL) break;
kPrintf("Task1 %d Created\n", i);
break;
case 2:
default:
for(i = 0; i < kAToI(vcCount, 10) ; i++)
if( kCreateTask(TASK_FLAGS_LOW, (QWORD) kTestTask2) == NULL) break;
kPrintf( "Task2 %d Created\n", i );
break;
}
}
// 태스크 우선순위 변경
static void kChangeTaskPriority(const char* pcParameterBuffer){
PARAMETERLIST stList;
char vcID[30];
char vcPriority[30];
QWORD qwID;
BYTE bPriority;
// 파라미터 추출
kInitializeParameter(&stList, pcParameterBuffer);
kGetNextParameter(&stList, vcID);
kGetNextParameter(&stList, vcPriority);
// 우선순위 변경
if(kMemCmp(vcID, "0x", 2) == 0)qwID = kAToI(vcID + 2, 16);
else qwID = kAToI(vcID, 10);
bPriority = kAToI(vcPriority, 10);
kPrintf("Change Task Priority ID [0x%q] Priority[%d]", qwID, bPriority);
if(kChangePriority(qwID, bPriority) == TRUE)kPrintf("Success\n");
else kPrintf("Fail\n");
}
// 태스크 정보 출력
static void kShowTaskList(const char* pcParameterBuffer){
int i;
TCB* pstTCB;
int iCount = 0;
kPrintf("==========Task Total Count[%d]============\n", kGetTaskCount());
for(i = 0; i < TASK_MAXCOUNT; i ++){
// TCB를 구해서 사용중이면 ID 출력
pstTCB = kGetTCBInTCBPool(i);
if((pstTCB->stLink.qwID >> 32) != 0){
// 10 개 출력 될때마다 정보 표시 여부 확인
if((iCount != 0) && ((iCount % 10) == 0)){
kPrintf("Press Any key to continue ('q' is exit) :");
if(kGetCh() == 'q'){
kPrintf("\n");
break;
}
kPrintf("\n");
}
kPrintf("[%d] Task ID[0x%Q], Priority[%d], Flags[0x%Q]\n", 1 + iCount++, pstTCB->stLink.qwID, GETPRIORITY(pstTCB->qwFlags), pstTCB->qwFlags);
}
}
}
// 태스크 종료
static void kKillTask(const char* pcParameterBuffer){
PARAMETERLIST stList;
char vcID[30];
QWORD qwID;
// 파라미터 추출
kInitializeParameter(&stList, pcParameterBuffer);
kGetNextParameter(&stList, vcID);
// 태스크 종료
if(kMemCmp(vcID, "0x", 2) == 0) qwID = kAToI(vcID + 2, 16);
else qwID = kAToI(vcID, 10);
kPrintf("Kill Task ID [0x%q] : ", qwID);
if(kEndTask(qwID) == TRUE) kPrintf("Success\n");
else kPrintf("Fail\n");
}
// 프로세서의 사용률을 표시
static void kCPULoad(const char* pcParameterBuffer){
kPrintf("Processor Load : %d%%\n", kGetProcessorLoad());
}
static void kPowerOffPC(const char* pcParameterBuffer){
kShutDownPC();
}
|
C# | UTF-8 | 1,126 | 2.671875 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CellScript: MonoBehaviour
{
/**
* Ссылка на текстовое поле
*/
public Text textField;
/**
* Ссылка на кнопку
*/
public Button button;
/**
* Значение ячейки
*/
private int m_value = 0;
/**
* Цвет ячейки
*/
private Color m_color = Color.white;
/**
* Ссылка на скрипт игры
*/
private GameScript game;
public int GetValue()
{
return m_value;
}
public void SetValue(int value)
{
m_value = value;
textField.text = value.ToString();
}
public Color GetColor()
{
return m_color;
}
public void SetColor(Color color)
{
m_color = color;
ColorBlock cb = button.colors;
cb.normalColor = color;
button.colors = cb;
}
/**
* Привязать ячейку
*/
public void Bind(GameScript game)
{
this.game = game;
}
/**
* Обработчик клика по ячейке
*/
public void OnClick()
{
if ( game != null ) game.OnClick(this);
}
}
|
C | UTF-8 | 315 | 3.78125 | 4 | [] | no_license | #include<stdio.h>
//Program to swap two integers
void swap(int *c,int *d);
int main()
{
int a, b;
printf("Enter 2 numbers");
scanf("%d %d", &a, &b);
swap(&a, &b);
printf("swapping...\n");
printf("a = %d, b = %d\n", a, b);
}
void swap(int *c, int *d)
{
int temp = *c;
*c =*d;
*d = temp;
}
|
C | UTF-8 | 2,713 | 3.1875 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2018
** tests_count_len
** File description:
** Implementation of tests_count_len
*/
#include "mysh.h"
#include <criterion/criterion.h>
#include <criterion/redirect.h>
#include <stdio.h>
#include <ctype.h>
Test(count_len, my_strlen_ko)
{
int result = my_strlen(NULL);
cr_assert_eq(result, 0);
}
Test(count_len, my_strlen_ok)
{
int result = my_strlen("abc");
cr_assert_eq(result, 3);
}
Test(count_len, my_tab_len_ko)
{
int result = my_tablen(NULL);
cr_assert_eq(result, 0);
}
Test(count_len, my_tablen_ok)
{
char **cmd = malloc(sizeof(char *) * 3);
int result = 0;
cmd[0] = my_strdup("line 1");
cmd[1] = my_strdup("line 2");
cmd[2] = 0;
result = my_tablen(cmd);
cr_assert_eq(result, 2);
}
Test(my_str_to_word_array, test_ok)
{
char *cmd = my_strdup("salut ca va");
char **result = NULL;
result = my_str_to_word_array(cmd);
cr_assert_str_eq(result[0], "salut");
}
Test(my_get_nbr, get_ko)
{
int result = my_getnbr(NULL);
cr_assert_eq(result, 0);
}
Test(my_get_nbr, ok_positive)
{
int result = my_getnbr("5");
cr_assert_eq(result, 5);
}
Test(my_get_nbr, ok_neg)
{
int result = my_getnbr("-5");
cr_assert_eq(result, -5);
}
Test(my_get_nbr, big_nbr)
{
int result = my_getnbr("2147483648");
cr_assert_eq(result, 0);
}
Test(how_many_char, how_ko)
{
int result = how_many_char(NULL, 'a');
cr_assert_eq(result, 0);
}
Test(how_many_char, how_ok)
{
int result = how_many_char("abcabc", 'a');
cr_assert_eq(result, 2);
}
Test(how_many_simple, simple_ko)
{
int result = how_many_simple(NULL, 'b');
cr_assert_eq(result, 0);
}
Test(how_many_simple, simple_ok)
{
int result = how_many_simple("abcabcaab", 'a');
cr_assert_eq(result, 3);
}
Test(my_strcat_properly, no_str)
{
char *str = (char *)my_strcat_properly(NULL, NULL);
if (str && *str != '\0')
cr_assert_fail();
}
Test(my_strcat_properly, one_str)
{
char *str = (char *)my_strcat_properly("salut", NULL);
cr_assert_str_eq(str, "salut");
}
Test(my_strcat_properly, two_str)
{
char *str = (char *)my_strcat_properly(my_strdup("salut"),
my_strdup("coucou"));
cr_assert_str_eq(str, "salutcoucou");
}
Test(check_that_dir, no_filepath)
{
int result = check_that_dir(NULL);
cr_assert_eq(result, -1);
}
Test(check_that_dir, bad_file_path)
{
int result = check_that_dir("bad_test");
cr_assert_eq(result, 1);
}
Test(check_that_dir, good_file_path)
{
int result = check_that_dir("src");
cr_assert_eq(result, 0);
}
Test(check_that_dir, path_is_a_file)
{
int result = check_that_dir("Makefile");
cr_assert_eq(result, -1);
} |
JavaScript | UTF-8 | 2,136 | 2.796875 | 3 | [] | no_license | const { Usuario } = require('../models/usuario');
const { ObjectID } = require('mongodb');
module.exports = {
// Gets all the users
index: async (req, res, next) => {
const users = await Usuario.find({});
res.status(200).json(users);
},
// Creates a new user
postUser: async (req, res, next) => {
try {
const newUser = new Usuario(req.body);
await newUser.save();
// Verify likes & dislikes items
if (newUser.meGusta && newUser.noMeGusta) {
const sameItem = newUser.meGusta.find(meGusta => {
return newUser.noMeGusta.find(noMeGusta => {
return meGusta == noMeGusta;
});
});
if (sameItem) {
throw new Error('Error: Same meGusta && noMeGusta item');
}
}
res.status(201).json(newUser);
} catch (err) {
res.status(400).json({ error: "Pedido equivocado. Faltan datos de usuario o están equivocados" });
}
},
// Gets a user's details
getUser: async (req, res, next) => {
try {
const { idUsuario } = req.params;
if (!ObjectID.isValid(idUsuario)) {
throw new Error('Error: idUsuario no válido')
}
const user = await Usuario.findById(idUsuario);
if (user) {
return res.status(200).json(user);
} else {
throw new Error('Error: usuario null')
}
} catch (err) {
return res.status(404).json({error: err});
}
},
// Modifies a user's details
putUser: async (req, res, next) => {
const { idUsuario } = req.params;
if (!ObjectID.isValid(idUsuario)) {
return res.status(404).json({error: "idUsuario no es válido"});
}
try {
const newUser = req.body;
await Usuario.findByIdAndUpdate(idUsuario, newUser);
res.status(200).json(newUser);
} catch (err) {
res.status(400).json({error: "Fallo en actualizar los datos del usuario"});
}
},
// Deletes a user
deleteUser: async (req, res, next) => {
const { idUsuario } = req.params;
if (!ObjectID.isValid(idUsuario)) {
return res.status(404).json({error: "idUsuario no es válido"});
}
const deletedUser = await Usuario.findByIdAndDelete(idUsuario);
res.status(200).json(deletedUser);
}
} |
Markdown | UTF-8 | 3,162 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | ## Spring 整合 JMS
Spring 对一些模版方法进行了一些封装。
1. Spring 配置文件
```xml
<beans>
<bean id="connectionFactory" class="org.apache,.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<value>tcp://localhost:61616</value>
</property>
</bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<propety name="connectionFactory">
<ref bean="connectionFactory"/>
</propety>
</bean>
<bean id="detination" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg index="0">
<value>HelloWorldQueue</value>
</constructor-arg>
</bean>
</beans>
```
2. 发送端
模版方法,利用 JmsTemplate 进行发送和接受消息。
## JmsTemplate
1. **通用代码抽取**
**JmsTemplate#send**
```java
@Override
public void send(final Destination destination, final MessageCreator messageCreator) throws JmsException {
execute(session -> {
doSend(session, destination, messageCreator);
return null;
}, false);
}
```
**JmsTemplate#execute**
```java
@Nullable
public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException {
Assert.notNull(action, "Callback object must not be null");
Connection conToClose = null;
Session sessionToClose = null;
try {
Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(
obtainConnectionFactory(), this.transactionalResourceFactory, startConnection);
if (sessionToUse == null) {
conToClose = createConnection();
sessionToClose = createSession(conToClose);
if (startConnection) {
conToClose.start();
}
sessionToUse = sessionToClose;
}
if (logger.isDebugEnabled()) {
logger.debug("Executing callback on JMS Session: " + sessionToUse);
}
return action.doInJms(sessionToUse);
}
catch (JMSException ex) {
throw convertJmsAccessException(ex);
}
finally {
JmsUtils.closeSession(sessionToClose);
ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection);
}
}
```
2. 发送消息的实现
基于回调的方式,一步步封装了细节。
```java
protected void doSend(Session session, Destination destination, MessageCreator messageCreator)
throws JMSException {
Assert.notNull(messageCreator, "MessageCreator must not be null");
MessageProducer producer = createProducer(session, destination);
try {
Message message = messageCreator.createMessage(session);
if (logger.isDebugEnabled()) {
logger.debug("Sending created message: " + message);
}
doSend(producer, message);
// Check commit - avoid commit call within a JTA transaction.
if (session.getTransacted() && isSessionLocallyTransacted(session)) {
// Transacted session created by this template -> commit.
JmsUtils.commitIfNecessary(session);
}
}
finally {
JmsUtils.closeMessageProducer(producer);
}
}
```
3. 接收消息
和上面差不多 |
JavaScript | UTF-8 | 1,824 | 2.515625 | 3 | [
"MIT"
] | permissive | import ProxyPlatform from '../Proxy/ProxyPlatform';
import {DIRECTION_NONE, DIRECTION_UP, DIRECTION_DOWN, DIRECTION_RIGHT, DIRECTION_LEFT} from '../Entity/Item';
export default class KeyboardController {
_proxy: ProxyPlatform;
constructor(game, proxy: ProxyPlatform) {
this._proxy = proxy;
this._game = game;
window.addEventListener('keydown', this.keyDownEvent.bind(this));
}
keyDownEvent(event) {
switch(event.keyCode) {
case 80: // P
this._game.togglePause();
break;
case 81: // Q
if(this._game.paused()) {
this._game.stepAnimation();
}
break;
case 87: // W
case 65: // A
case 83: // S
case 68: // D
case 32: // Space
if(!this._game.paused()) {
this._moveProxy(event.keyCode);
}
break;
}
}
_moveProxy(keyCode: number) {
switch(keyCode) {
case 68: // D
this._proxy.setDirections(DIRECTION_RIGHT, DIRECTION_NONE);
this._proxy.move();
break;
case 65: // A
this._proxy.setDirections(DIRECTION_LEFT, DIRECTION_NONE);
this._proxy.move();
break;
case 87: // W
this._proxy.setDirections(DIRECTION_NONE, DIRECTION_UP);
this._proxy.move();
break;
case 83: // S
this._proxy.setDirections(DIRECTION_NONE, DIRECTION_DOWN);
this._proxy.move();
break;
case 32: // Space
this._proxy.unbindBall();
break;
}
}
}
|
C++ | UTF-8 | 1,784 | 3.09375 | 3 | [] | no_license | #pragma once
#ifdef MYDLLLOADLIB_EXPORTS
#define MYDLLLOADLIB_API __declspec(dllexport)
#else
#define MYDLLLOADLIB_API __declspec(dllimport)
#endif
class IDoubleLinkedList
{
public:
virtual ~IDoubleLinkedList() { ; }
virtual void Clean() = 0;
virtual bool Empty() = 0;
// Add a new element at the head of the list
virtual void PushFront(int item) = 0;
// Add a new element at the tail of the list
virtual void PushBack(int item) = 0;
// Add a new element after an element with key value
virtual bool PushAfterKey(int item, int key) = 0;
// Remove an element from the head
virtual int RemoveFront() = 0;
// Remove an element from the tail
virtual int RemoveBack() = 0;
// Remove an element with key value from the list
virtual bool RemoveKey(int key) = 0;
virtual bool Find(int item) = 0;
virtual int Size() = 0;
virtual void Print() = 0;
};
struct Node
{
public:
Node *prev;
Node *next;
int data;
Node();
Node(int item);
void Print();
};
struct DoubleLinkedList : public IDoubleLinkedList
{
private:
Node *head;
Node *tail;
public:
DoubleLinkedList();
DoubleLinkedList(int item);
// Remove all elements in our list
void Clean();
bool Empty();
// Add a new element at the head of the list
void PushFront(int item);
// Add a new element at the tail of the list
void PushBack(int item);
// Add a new element after an element with key value
bool PushAfterKey(int item, int key);
// Remove an element from the head
int RemoveFront();
// Remove an element from the tail
int RemoveBack();
// Remove an element with key value from the list
bool RemoveKey(int key);
bool Find(int item);
int Size();
void Print();
};
extern "C" MYDLLLOADLIB_API DoubleLinkedList* _cdecl Create();
typedef DoubleLinkedList* (*CREATE_LIST) ();
|
SQL | UTF-8 | 2,924 | 3.40625 | 3 | [] | no_license | CREATE TABLE IF NOT EXISTS plots(
x INT NOT NULL,
y INT NOT NULL,
wood INT,
clay INT,
iron INT,
stone INT,
food INT,
total INT,
background INT,
plot_type VARCHAR(50),
layer INT,
region INT,
hospital BOOLEAN,
sovable BOOLEAN,
passable BOOLEAN,
npc BOOLEAN,
brg BOOLEAN,
food_sum INT,
total_sum INT,
PRIMARY KEY(x, y)
);
DROP INDEX IF EXISTS plots_food_idx;
CREATE INDEX plots_food_idx ON plots(food);
DROP INDEX IF EXISTS plots_total_idx;
CREATE INDEX plots_total_idx ON plots(total);
DROP INDEX IF EXISTS plots_sovable_idx;
CREATE INDEX plots_sovable_idx ON plots(sovable);
DROP INDEX IF EXISTS plots_food_sum_idx;
CREATE INDEX plots_food_sum_idx ON plots(food_sum);
DROP INDEX IF EXISTS plots_total_sum_idx;
CREATE INDEX plots_total_sum_idx ON plots(total_sum);
CREATE TABLE IF NOT EXISTS creatures(
x INT NOT NULL,
y INT NOT NULL,
name VARCHAR(100),
id VARCHAR(100),
amount VARCHAR(100),
PRIMARY KEY(x, y)
);
CREATE TABLE IF NOT EXISTS deposits(
x INT NOT NULL,
y INT NOT NULL,
type INT NOT NULL,
PRIMARY KEY(x, y, type)
);
CREATE TABLE IF NOT EXISTS resources(
x INT NOT NULL,
y INT NOT NULL,
type INT,
rd VARCHAR(50),
r INT,
PRIMARY KEY(x, y)
);
DROP INDEX IF EXISTS resources_type_idx;
CREATE INDEX resources_type_idx ON resources(type);
CREATE TABLE IF NOT EXISTS town(
x INT NOT NULL,
y INT NOT NULL,
id INT,
owner_id INT,
"name" VARCHAR(100),
owner_name VARCHAR(100),
population INT,
alliance VARCHAR(100),
region INT,
race INT,
capital BOOLEAN,
protection BOOLEAN,
misc1 BOOLEAN,
abandoned BOOLEAN,
data VARCHAR(500),
PRIMARY KEY(x, y)
);
DROP INDEX IF EXISTS towns_owner_idx;
CREATE INDEX towns_owner_idx ON town(owner_name);
DROP INDEX IF EXISTS towns_alliance_idx;
CREATE INDEX towns_alliance_idx ON town(alliance);
DROP INDEX IF EXISTS towns_abandoned_idx;
CREATE INDEX towns_abandoned_idx ON town(abandoned);
DROP INDEX IF EXISTS towns_population_idx;
CREATE INDEX towns_population_idx ON town(population);
CREATE TABLE IF NOT EXISTS valid_plots(
x INT NOT NULL,
y INT NOT NULL,
restricted BOOLEAN,
total_sum INT,
food_sum INT,
sov_count INT,
PRIMARY KEY(x, y)
);
DROP INDEX IF EXISTS valid_plots_total_idx;
DROP INDEX IF EXISTS valid_plots_food_idx;
DROP INDEX IF EXISTS valid_plots_sov_idx;
DROP INDEX IF EXISTS valid_plots_restricted_idx;
CREATE INDEX valid_plots_total_idx ON valid_plots(total_sum);
CREATE INDEX valid_plots_food_idx ON valid_plots(food_sum);
CREATE INDEX valid_plots_sov_idx ON valid_plots(sov_count);
CREATE INDEX valid_plots_restricted_idx ON valid_plots(restricted);
CREATE TABLE IF NOT EXISTS whitelist_users(
user_name VARCHAR(50),
PRIMARY KEY(user_name)
);
INSERT INTO whitelist_users(user_name)
VALUES ('Link');
|
Python | UTF-8 | 922 | 3.90625 | 4 | [] | no_license | """
Robert Graham (rpgraham84@gmail.com)
Project Euler
Counting Sundays
Problem 19
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
Answer:
171
Rationale:
Python to the rescue again.
"""
import datetime
def problem_19():
d = datetime.datetime(1901, 1, 1)
count = 0
while d.year < 2001:
if d.weekday() == 6 and d.day == 1:
count += 1
d += datetime.timedelta(days=1)
return count
if __name__ == '__main__':
print(problem_19())
|
Swift | UTF-8 | 4,019 | 2.625 | 3 | [] | no_license | //
// CardViewController.swift
// oliginal game
//
// Created by kaoru akiba on 2017/05/21.
// Copyright © 2017年 kaoru akiba. All rights reserved.
//
import UIKit
class CardViewController: UIViewController {
@IBOutlet var label1: UILabel!//相手左から1番目
@IBOutlet var label2: UILabel!//相手左から2番目
@IBOutlet var label3: UILabel!//相手左から3番目
@IBOutlet var label4: UILabel!//相手左から4番目
@IBOutlet var label5: UILabel!//自分左から1番目
@IBOutlet var label6: UILabel!//自分左から2番目
@IBOutlet var label7: UILabel!//自分左から3番目
@IBOutlet var label8: UILabel!//自分左から4番目
var number: Int!
var number1: Int!
var number2: Int!
var number3: Int!
var number4: Int!
var number10: Int = 16
let saveData: UserDefaults = UserDefaults.standard
var numbers = UserDefaults.standard.array(forKey:"suuji") as? [Int] ?? [Int]()
var attackNumber = UserDefaults.standard.array(forKey: "attack")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label5.text = String(numbers[0])
label6.text = String(numbers[1])
label7.text = String(numbers[2])
label8.text = String(numbers[3])
number1 = numbers[4]
number2 = numbers[5]
number3 = numbers[6]
number4 = numbers[7]
}
override func viewWillAppear(_ animated: Bool) {
if saveData.object(forKey: "1") != nil{
label1.text = String(number1)
}else if saveData.object(forKey: "2") != nil{
label2.text = String(number2)
}else if saveData.object(forKey: "3") != nil{
label3.text = String(number3)
}else if saveData.object(forKey: "4") != nil{
label4.text = String(number4)
}
if number1 == number10 {
saveData.set(number1,forKey: "1")
aleart()
label1.text = String(number1)
}else if number2 == number10 {
saveData.set(number2,forKey: "2")
aleart()
label2.text = String(number2)
}else if number3 == number10 {
saveData.set(number3,forKey: "3")
aleart()
label3.text = String(number3)
}else if number4 == number10 {
saveData.set(number4,forKey: "4")
aleart()
label4.text = String(number4)
}else if number10 == 16 {
number10 = 16
}else{
//alertを出す
let alert: UIAlertController = UIAlertController(title: "不正解...", message: "",preferredStyle: .alert)
//OKボタン
alert.addAction(
UIAlertAction(
title: "次へ",
style: .default,
handler: {action in
}
)
)
present(alert, animated: true, completion: nil)
}
if saveData.object(forKey: "suuji") != nil{
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func hint () {
}
@IBAction func attack () {
}
func aleart () {
//alertを出す
let alert: UIAlertController = UIAlertController(title: "正解!", message: "",preferredStyle: .alert)
//OKボタン
alert.addAction(
UIAlertAction(
title: "次へ",
style: .default,
handler: {action in
}
)
)
present(alert, animated: true, completion: nil)
}
}
|
Markdown | UTF-8 | 3,280 | 2.953125 | 3 | [
"MIT"
] | permissive | # Ring Contrastive Learning
A PyTorch implementation of *Conditional Negative Sampling for Contrastive Learning of Visual Representations* (https://arxiv.org/abs/2010.02037).
## Abstract
Recent methods for learning unsupervised visual representations, dubbed contrastive learning, optimize the noise-contrastive estimation (NCE) bound on mutual information between two views of an image. NCE uses randomly sampled negative examples to normalize the objective. In this paper, we show that choosing difficult negatives, or those more similar to the current instance, can yield stronger representations. To do this, we introduce a family of mutual information estimators that sample negatives conditionally -- in a "ring" around each positive. We prove that these estimators lower-bound mutual information, with higher bias but lower variance than NCE. Experimentally, we find our approach, applied on top of existing models (IR, CMC, and MoCo) improves accuracy by 2-5% points in each case, measured by linear evaluation on four standard image datasets. Moreover, we find continued benefits when transferring features to a variety of new image distributions from the Meta-Dataset collection and to a variety of downstream tasks such as object detection, instance segmentation, and keypoint detection.
### Main Intuition
Negative samples in many contrastive algorithms are typically drawn i.i.d. but this may not be the best option. One way wish to vary the "difficulty" of negative samples during training in order to learn a stronger representation. While there are many ways to do this, we want to do it in a way that preserves nice properties.
## Setup/Installation
We use Python 3, PyTorch 1.7.1, PyTorch Lightning 1.1.8, and a conda environment. Consider a variation of the commands below:
```
conda create -n ring python=3 anaconda
conda activate ring
conda install pytorch=1.7.1 torchvision -c pytorch
pip install pytorch-lightning=1.1.8
pip install tqdm dotmap
```
## Data
This repo only contains implementations for CIFAR10, CIFAR100, and STL10, all of which is in torchvision.
## Usage
For every fresh terminal instance, you should run
```
source init_env.sh
```
to add the correct paths to `sys.path` before running anything else.
The primary script is found in the `scripts/run.py` file. It is used to run pretraining and linear evaluation experiments. You must supply it a configuration file, for which many templates are in the `configs/` folder. These configuration files are not complete, you must supply a experiment base directory (`exp_base`) to point to where in your filesystem model checkpoints will go. You must also supply a root directory where data should be downloaded to.
Example usage:
```
python scripts/run.py config/pretrain/nce/nce.json
```
For linear evaluation, in the config file, you must provide the `exp_dir` and `checkpoint_name` (the file containing the epoch name) for the pretrained model.
## Citation
If you find this useful for your research, please cite:
```
@article{wu2020conditional,
title={Conditional negative sampling for contrastive learning of visual representations},
author={Wu, Mike and Mosse, Milan and Zhuang, Chengxu and Yamins, Daniel and Goodman, Noah},
journal={arXiv preprint arXiv:2010.02037},
year={2020}
}
```
|
PHP | UTF-8 | 1,474 | 3.359375 | 3 | [] | no_license | <?php
namespace App\Presentation\DTO;
use App\Domain\Entity\Board;
use App\Domain\ValueObject\Sign;
class GameState
{
/**
* @var Sign[][]
*/
private $boardState;
/**
* @var string
*/
private $nextMove;
/**
* @var bool
*/
private $isOver;
/**
* @var string
*/
private $playerSign;
/**
* @var string
*/
private $winner;
/**
* @param Board $board
*/
public function __construct(Board $board)
{
$this->boardState = $board->getBoardState()->getState();
$this->nextMove = $board->getLastMove()->getOppositeSign();
$this->isOver = $board->isGameOver();
$this->winner = $board->getWinner() ? $board->getWinner()->getValue() : null;
$this->playerSign = $board->getPlayerSign()->getValue();
}
/**
* @return Sign[][]
*/
public function getBoardState(): array
{
return $this->boardState;
}
/**
* @return string
*/
public function getNextMove(): string
{
return $this->nextMove;
}
/**
* @return bool
*/
public function isOver(): bool
{
return $this->isOver;
}
/**
* @return string
*/
public function getPlayerSign(): string
{
return $this->playerSign;
}
/**
* @return string|null
*/
public function getWinner(): ?string
{
return $this->winner;
}
}
|
Markdown | UTF-8 | 637 | 2.640625 | 3 | [] | no_license | ## To start the app
1. `yarn` to install dev dependencies
2. `yarn start-server` to run the server.
3. `yarn start` to run the frontend. Go to **http://lvh.me:8080** in your browser where you can see the web application running.
4. For production run the `yarn build` command.
## Deployment
You can easily deploy server app with pm2. Check the `ecosystem.config.js` for details.
Install pm2:
```bash
$ yarn global add pm2
```
If you deploy to new environment, then configure server in `ecosystem.config.js` and run:
```bash
$ pm2 deploy ecosystem.config.js SERVER_NAME setup
```
And run
```bash
$ pm2 deploy SERVER_NAME
```
|
Markdown | UTF-8 | 4,101 | 2.65625 | 3 | [] | no_license | # Auto_Operation_WeChat_robot
这个项目是一个微信机器人,由广东海洋大学互联网社群技术部开发。通过本机器人可以实现自动化的管理社群涉及的大量群聊,减轻管理人员的压力。
## 功能一:定时向指定群聊发送新闻
自动爬取网页信息,然后对信息进行处理之后,发送到特定微信群的中。有以下这些功能:
### 1、定时(15min)爬取readhub.me的新闻内容
### 2、将新闻内容存入到数据库当中
数据库长这样:

### 3、定时从数据库中获取新闻内容发送到指定的微信群
#### 机器人能够同时管理多个群
### 4、由于信息量较大,为防止发送速度过快,影响群秩序与网络正常通信,因此获取到的内容每隔1min发送一条
### 5、新闻内容形式:【标题】+ 内容 + 链接
sample:
【放弃 WP 是必然:微软持续推进 Surface Phone】
之前微软曾宣布,从 2 月 20 日起,Windows Phone 7 以及 Windows Phone 8 系统的手机用户,将不再支持通知信息推送,而一些有价值的动态方块更新功能也将停止 ... 了,Windows Phone 8.1、Windows 10 移动版的用户将依然享受上述功能,不过这样状况也不会持续太久,仅仅只是维持,因为微软已经从根本上放弃了这个移动系统 ... 从外媒给出的最新报道称,放弃 WP 系统后,微软目前仍然在秘密暗中推进自家的 Surface Phone 项目,这不仅仅是一台手机那么简单,而众多专利图显示,该设备采用双屏折叠设计,合起来是手机的形态,而展开后就是个微型电脑,属于 One Core 大框架下的产品。
http://tech.sina.com.cn/mobile/n/n/2018-02-22/doc-ifyrswmu8256844.shtml
## 功能二、机器人放在服务器上 24h 运行
## 功能三、回复关键字自动拉人进群
## 功能四、回复关键字自动回复相关的新闻信息(待实现)
## 功能五、建设黑名单,禁止违反群规人士进群(待实现)
## 功能六、建设机器人的client与server互通,实现client远程控制(待实现)
## 功能七、client的GUI可视化界面
### (一些想法)
* IOS、Android、Win三平台通用,使用前端通用框架建设应用!
### feature:
* 获取远程的二维码,扫码登录,自动提示登录成功
* 自动拉取群列表、自主选择需要机器人管理的群
* 查看各群的群员信息情况,获取群的男女比例,城市分布
### 机器人properties的修改:
* 每个群的关键字可以自定义
* 自动添加好友,请求关键字自定义
* 黑名单的管理
## 功能八、机器人的属性热修改,更新参数不需要重启。
## 数据库设计
1、创建一个数据库,名为info_crbotdb (你也可以自定义名字,但需要更改程序)
2、创建一个名为information的表,表结构设计如下:

表结构代码如下:
```sql
CREATE TABLE information
(
time DATETIME NULL,
title VARCHAR(256) NULL,
content TEXT NULL,
link TEXT NULL,
src_website TEXT NULL,
CONSTRAINT information_title_uindex
UNIQUE (title)
)
COMMENT '新闻信息'
ENGINE = InnoDB;
```
如果遇到数据库报错:
Incorrect string value: '...' for column 'title' at row 1
执行以下sql命令解决:
```sql
alter table information convert to character set utf8mb4 collate utf8mb4_bin
```
## wxpy模块的用法
使用wxpy模块可实现操作。
为了能够正常获得群对象,需要登录前保证在群说一句话,把群冒上来。谨记!!!
```python
import wxpy
bot = wxpy.Bot() # 扫码登录,获取一个微信机器人对象
friend = bot.search('群的名字或者具体一个人的昵称、备注')
# 也可以使用 bot.groups() 获取所有群组
```
详情查看模块文档:
http://wxpy.readthedocs.io/zh/latest/
## 开发人员名单
1、Mr.YYM
|
Markdown | UTF-8 | 1,772 | 3.109375 | 3 | [] | no_license | # Main Project:
* Create 2 Receivers and 3 Senders where the Senders are sending data to the Receivers.
* The 5 Programs are running concurrently on the same machine.
# Jobs
## Sender
* Create a random 32 bit number generator for each of the senders
* Assign and store the values **251, 257, or 997** to the respective project where each of the senders will **behave differently**
* **Sender #997**
* Sends to who:
* Sends each event to *ALL RECEIVERS*
* Requirements:
* Requires acknowledgement for each message from *BOTH RECEIVERS* before it continues execution
* Termination cause:
* Terminates when it gets/observes a *RANDOM NUMBER SMALLER THAN 100*
* **Sender #251**
* Sends to who:
* Sends each event to only *ONE RECEIVER*
* Requirements:
* Does not accept any acknowledgement messages
* Termination cause:
* Terminates on a *“KILL” COMMAND FROM A SEPARATE TERMINAL*
* The above will be supplied by the professor as a patch code to be integrated with this sender
* **Sender #257**
* Sends to who:
* Sends each event to only *ONE RECEIVER*
* Requirements:
* Does not accept any acknowledgement messages
* Termination cause:
* Terminates when *ITS RECEIVER STOPS RECEIVING EVENT NOTIFICATIONS*
## Receiver
* Each receiver repeatedly gets a message and displays the value and the Sender’s identity
* **Receiver #1**
* Accepts from who:
* Only accepts messages from *251 AND 997 SENDERS*
* Termination cause:
* Terminates after BOTH OF ITS SENDERS HAVE TERMINATED
* **Receiver #2**
* Accepts from who:
* Only accepts messages from *257 AND 997 SENDERS*
* Termination cause:
* Terminates after it has *RECEIVED A TOTAL OF 5000 MESSAGES*
|
Python | UTF-8 | 2,756 | 3.546875 | 4 | [] | no_license | # Welcome to Po's Python Pong Game
# By Po Kealiinohomoku
# Intensive Project 1
import turtle
# Screen setup
win = turtle.Screen()
win.title("Po's Python Pong")
win.bgcolor("black")
win.setup(width=800, height=600)
win.tracer(0)
# Gameplay objects
# Score Variables
score_a = 0
score_b = 0
# Player 1 Paddle
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)
# Player 2 Paddle
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)
# Game Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
# Scoreboard
title = turtle.Turtle()
title.speed(0)
title.color("white")
title.penup()
title.hideturtle()
title.goto(0, 260)
title.write("P1 score: 0 | P2 score: 0",
align="center", font=("Chiller", 22, "normal"))
# Game Ball Physics
ball.dx = 4
ball.dy = 2
# Player Input Functions
# Paddle a
def paddle_a_up():
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
# Paddle b
def paddle_b_up():
y = paddle_b.ycor()
y += 20
paddle_b.sety(y)
def paddle_b_down():
y = paddle_b.ycor()
y -= 20
paddle_b.sety(y)
win.listen()
win.onkeypress(paddle_a_up, "w")
win.onkeypress(paddle_a_down, "s")
win.onkeypress(paddle_b_up, "Up")
win.onkeypress(paddle_b_down, "Down")
# Main Game Loop
while True:
win.update()
# Move Ball Code
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Basic Border Checking
if ball.xcor() > 390:
ball.dx *= -1
ball.goto(0, 0)
title.clear()
score_a += 1
title.write("P1 score: " + str(score_a) + " | P2 score: " +
str(score_b), align="center", font=("Courier", 22, "normal"))
if ball.xcor() < -390:
ball.dx *= -1
ball.goto(0, 0)
title.clear()
score_b += 1
title.write("P1 score: " + str(score_a) + " | P2 score: " +
str(score_b), align="center", font=("Courier", 22, "normal"))
if ball.ycor() > 290:
ball.dy *= -1
if ball.ycor() < -290:
ball.dy *= -1
# Collision Dectecting
if(ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor()+50 and ball.ycor() > paddle_b.ycor()-50):
ball.dx = ball.dx * -1
if(ball.xcor() > -350 and ball.xcor() < -340) and (ball.ycor() < paddle_a.ycor()+50 and ball.ycor() > paddle_a.ycor()-50):
ball.dx = ball.dx * -1
|
C++ | UTF-8 | 1,135 | 2.875 | 3 | [] | no_license | #include "list_layout.h"
ui::uint ui::ListLayout::width_horizontal() const {
ui::uint pad1 = padding();
ui::uint width = pad1;
for(uint i = 0 ; i < childrenCount() ; i++) {
View* currChild = getChild(i);
width += currChild->width() + pad1;
}
return width;
}
ui::uint ui::ListLayout::width_vertical() const {
ui::uint pad2 = 2*padding();
ui::uint width = 0;
for(uint i = 0 ; i < childrenCount() ; i++) {
View* currChild = getChild(i);
width = std::max(width, currChild->width()+pad2);
}
return width;
}
ui::uint ui::ListLayout::height_horizontal() const {
ui::uint pad2 = 2*padding();
ui::uint height = 0;
for(uint i = 0 ; i < childrenCount() ; i++) {
View* currChild = getChild(i);
height = std::max(height, currChild->height()+pad2);
}
return height;
}
ui::uint ui::ListLayout::height_vertical() const {
ui::uint pad = padding();
ui::uint height = pad;
for(uint i = 0 ; i < childrenCount() ; i++) {
View* currChild = getChild(i);
height += currChild->height() + pad;
}
return height;
}
|
C | UTF-8 | 694 | 2.9375 | 3 | [
"MIT"
] | permissive | /**
\file crc16.h
\brief functions for calculating 16 bit cyclic redundancy codes
\CRC-16/IBM/SDLC
*/
#ifndef CRC16_H
#define CRC16_H
#include <stddef.h>
#include <stdint.h>
/**
\brief initial crc value
*/
#define CRC16_INIT (0xffff)
/**
\brief finalize crc value
\param val an initialized crc value
\return a finalized crc value
*/
#define CRC16_FINALIZE(val) (val ^ 0xffff)
/**
\brief computes the crc for data and uses crc for the result
\param crc pointer to initialized crc value
\param data pointer to data over which to calculate crc
\param size number of bytes of data
\return 0 if successful
*/
int crc16(uint16_t *crc, const uint8_t *data, size_t size);
#endif /* CRC16_H_ */
|
Java | UTF-8 | 760 | 2.953125 | 3 | [] | no_license | package sa.main.controller;
import sa.main.model.Obstacle;
import sa.main.model.Player;
public class GameController {
private Player player;
private Obstacle obstacle;
private boolean touched;
public GameController(Player player, Obstacle obstacle){
this.player = player;
this.obstacle = obstacle;
}
public boolean getTouched(){
return touched;
}
public void setTouched(boolean touched){
this.touched = true;
}
public void update() {
if(player.getY() <= 0){
player.setyDirection(1);
}
if(player.getY() >= 22){
player.setyDirection(-1);
}
if(player.getY() == 220){
player.setJump(false);
}
player.setJump(this.getTouched());
player.update(System.currentTimeMillis());
obstacle.update();
}
}
|
Java | UTF-8 | 634 | 1.90625 | 2 | [] | no_license | package com.official.foundation.facade.user;
import com.official.foundation.domain.po.user.Account;
import com.official.foundation.facade.BaseFacadeService;
public interface AccountFacadeService extends BaseFacadeService<Account,Long>{
/**
* 根据用户名/邮箱/验证手机 获取账号信息
* @param username
* @return
*/
public Account getAccountByUsername(String username);
/**
* 用户注册
* @param account
* @return
*/
public Account register(Account account);
/**
* 更新账号信息
* @param account
* @return
*/
public Account updateAccount(Account account);
}
|
C++ | UTF-8 | 416 | 3.25 | 3 | [] | no_license | #include<stdio.h>
#include<vector>
#include<iostream>
#include<string>
using namespace std;
void all_permute(string &arr,int l,int r)
{
if(l==r)
cout<<arr<<endl;
else
{
for(int i=0;i<=r-l;i++)
{
swap(arr[l],arr[l+i]);
all_permute(arr,l+1,r);
swap(arr[l],arr[l+i]); //backtrack
}
}
}
int main()
{
string arr="abc";
all_permute(arr,0,arr.length()-1);
cin.get();
}
|
Python | UTF-8 | 313 | 2.5625 | 3 | [] | no_license | from numpy import*
m=array(eval(input("medias:")))
p=array(eval(input("presenca:")))
v3=int(input("carga horaria:"))
ap=0
rf=0
rn=0
v=zeros(3, dtype=int)
for i in range(size(m)):
y=v3*75/100
if(m[i]>=5 and p[i]>=y):
ap+=1
elif(m[i]<5):
rn=rn+1
elif(p[i]<y):
rf=rf+1
v[0]=ap
v[1]=rn
v[2]=rf
print(v)
|
TypeScript | UTF-8 | 217 | 2.796875 | 3 | [
"MIT"
] | permissive | /**
* @internal
*/
export interface SkyDateRange {
/**
* Specifies the last date in the date range.
*/
endDate?: Date;
/**
* Specifies the first date in the date range.
*/
startDate?: Date;
}
|
Python | UTF-8 | 1,294 | 3.296875 | 3 | [
"MIT"
] | permissive | #Crosby Ravert and Akshit Pathania
#Pitt-Bradford: Object Oriented Programming, Spring 21
from matplotlib.pyplot import plot, bar, show, subplots
import matplotlib.pyplot as plt
file = open("batting.csv")
file.readline()
year = []
battingAvg = []
bestAvg = []
tempYearAvgs = []
yearCounter = 1871
batterCount = 0
yearlyAvg = 0
for line in file:
value = line.split(',')
hits = int(value[8])
atBat = int(value[6])
statYear = int(value[1])
if atBat != 0:
if statYear == yearCounter:
avg = (hits / atBat)
tempYearAvgs.append(avg)
yearlyAvg += avg
batterCount += 1
else:
if batterCount != 0:
realYearlyAvg = yearlyAvg / batterCount
year.append(yearCounter)
battingAvg.append(realYearlyAvg)
bestAvg.append(max(tempYearAvgs))
yearCounter += 1
batterCount = 0
yearlyAvg = 0
tempYearAvgs.clear()
avg = (hits / atBat)
tempYearAvgs.append(avg)
yearlyAvg += avg
batterCount += 1
else:
continue
fig, (ax1, ax2) = subplots(2)
fig.suptitle("Average of yearly batting averages over the best average")
ax1.plot(year, battingAvg)
ax2.bar(year, bestAvg)
show() |
C++ | UTF-8 | 866 | 2.96875 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int myAtoi(string str) {
long long num=0;
bool negative = false;
int index = 0, sz = str.length();
while(index<sz && str[index]==' '){
index++;
}
if(index<sz){
if(str[index]=='-'){
negative = true;
index++;
}
else if(str[index]=='+')
{index++;}
}
while(index<sz && num <= INT_MAX){
char c = str[index];
index++;
if(c>='0' && c<='9'){
num=num*10+c-'0';
}
else{
break;
}
}
if(negative){
num = -num;
}
if(num<INT_MIN)
return INT_MIN;
if(num>INT_MAX)
return INT_MAX;
return num;
}
};
|
PHP | UTF-8 | 912 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace RabbitCMS\Templates\Http\Requests;
use Illuminate\Routing\Route;
use RabbitCMS\Carrot\Http\Request;
class TemplateRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @param Route $route
*
* @return array
*/
public function rules(Route $route)
{
$id = $route->hasParameter('id') ? $route->parameter('id') : 'NULL';
$locale = $this->input('locale');
$rules = [
'name' => 'required|unique:mail_templates,name,' . $id . ',id,locale,' . $locale,
'locale' => 'required',
'subject' => 'required',
'template' => 'required',
];
return $rules;
}
}
|
JavaScript | UTF-8 | 2,435 | 3.125 | 3 | [] | no_license | const pokemonList = document.querySelector('.pokemon--list');
const btn = document.querySelector('.btn-load-more');
const modal = document.querySelector('.modal');
const backdrop = document.querySelector('.backdrop');
const app = document.querySelector('.app');
let offset = 0;
let limit = 20;
const loadPokemones = offset => {
fetch(`https://pokeapi.co/api/v2/pokemon?offset=${offset}&limit=${limit}`)
.then(res => {
return res.json();
}).then((res) => {
let results = res.results;
// console.log(results);
let html = '';
results.forEach((pokemon) => {
html += `
<li class="list__item gotoPokemon" data-url="${pokemon.url}">
<img src="${getImageURL(pokemon.url)}" alt"${pokemon.name}"/>
<p>Nombre: ${pokemon.name.toUpperCase()}</p>
</li>
`;
});
pokemonList.innerHTML += html;
const btnPokemon = document.querySelectorAll('.gotoPokemon');
btnPokemon.forEach(btn => {
btn.addEventListener('click', () => showPokemon(btn));
});
})
.catch(err => {
console.error(err);
});
};
const showPokemon = btn => {
const url = btn.dataset.url;
console.log(url);
axios.get(url)
.then(res => {
console.log(res);
const pokemon = res.data;
const modalImg = document.querySelector('.modal__img');
const modalNamePokemon = document.querySelector('.modal__name-pokemon');
modalImg.src = pokemon.sprites.front_default;
modalNamePokemon.innerText = pokemon.name;
modal.style.display = 'block';
backdrop.style.display = 'block';
app.classList.add('blur');
})
.catch(err => console.error(err));
};
const getImageURL = url => {
let urlArray = url.split('/');
let imgId = urlArray[urlArray.length - 2];
return `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/${imgId}.png`;
};
backdrop.addEventListener('click', () => {
app.classList.remove('blur');
modal.style.display = 'none';
backdrop.style.display = 'none';
})
btn.addEventListener('click', () => {
offset += limit;
loadPokemones(offset);
})
window.addEventListener('DOMContentLoaded', () => {
loadPokemones(offset);
});
|
C# | UTF-8 | 3,503 | 3.203125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SOLIDBuzzFuzz
{
public class BuzzFuzz : IEnumerator<string>, IEnumerable<string>
{
internal class Substitution
{
public Substitution(int digit, string word)
{
Digit = digit;
Word = word;
_testChar = (Digit < 10) ? (char)(Digit+'0') : '_';
}
public int Digit { get; private set; }
public string Word { get; private set; }
private char _testChar;
public bool SayIt(int num, string text)=> (num%Digit)==0 || text.Contains(_testChar);
}
#region Private fields
private int _num;
private int _start = 1;
private int _end = Int32.MaxValue;
private readonly List<Substitution> _substitutions = new List<Substitution>();
#endregion
#region Constructors
public BuzzFuzz(int start)
{
_start = start;
_substitutions.Add(new Substitution(digit: 5, word: "Buzz" ));
_substitutions.Add(new Substitution ( digit: 7, word: "Fuzz" ));
Reset();
}
public BuzzFuzz() : this(1)
{
}
#endregion
#region IEnumerator<string> members
public string Current { get; private set; }
public bool MoveNext()
{
Current = _num.ToString(CultureInfo.InvariantCulture);
bool showWord = false;
var sb = new StringBuilder();
foreach (var sub in _substitutions)
{
if (sub.SayIt(_num, Current))
{
sb.Append(sub.Word);
showWord = true;
}
}
if (showWord)
Current = sb.ToString();
++_num;
return _num <= _end;
}
public void Reset()
{
_num = _start;
}
#endregion
#region Fluent Construction interface
public BuzzFuzz Add(int digit, string word)
{
_substitutions.Add(new Substitution {Digit = digit, Word = word});
return this;
}
public BuzzFuzz StartAt(int start)
{
_start = start;
Reset();
return this;
}
/// <summary>
/// Sets EXCLUSIVE ending value.
/// </summary>
/// <param name="term"></param>
/// <returns>If not set, enumeration continues to Int32.MaxValue</returns>
public BuzzFuzz StopAt(int term)
{
_end = term;
return this;
}
public BuzzFuzz Clear()
{
_substitutions.Clear();
return this;
}
#endregion
#region Unimportant methods
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
}
#endregion
#region IEnumerable methods
public IEnumerator<string> GetEnumerator()
{
return this;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this;
}
#endregion
}
internal class Buzz
{
public static BuzzFuzz Fuzz
{
get { return new BuzzFuzz(); }
}
}
}
#region Home of dead code
#if false
internal class BuzzFuzz_impl
{
internal int num = 1;
internal int term = Int32.MaxValue;
internal List<Substitution> substitutions = new List<Substitution>();
public IEnumerable<string> Generate()
{
while (num < term)
{
bool showWord = false;
var sb = new StringBuilder();
var strNum = num.ToString();
foreach (var sub in substitutions)
{
if ((num % sub.Digit == 0) ||
(sub.Digit < 10 && strNum.Contains(sub.Digit.ToString())))
{
sb.Append(sub.Word);
showWord = true;
}
}
if (showWord)
yield return sb.ToString();
else
yield return strNum
++num;
}
}
}
#endif
#endregion
|
Markdown | UTF-8 | 628 | 2.734375 | 3 | [
"MIT"
] | permissive | # Math-tokenizer #
[](https://travis-ci.org/DahlitzFlorian/math-tokenizer)
## Description ##
This is a simple and lightweighted tokenizer for mathematical functions written in pure Python. It was tested with Python >= 3.4.
version 1.0.1
## Features ##
* tokenize mathematical function
## Future features ##
* create own rules
## Installation ##
The package is available via ```pip```
```bash
pip install math-tokenizer
```
## Update ##
You can also update on the latest version via ```pip```
```bash
pip install math-tokenizer --upgrade |
Python | UTF-8 | 885 | 3.703125 | 4 | [] | no_license | from django.shortcuts import render, HttpResponse
# Create your views here.
def hello(request, nome, idade):
return HttpResponse(f'<h1>Hello {nome}, você tem {idade} anos, correto?</h1>')
def soma(request, numero1, numero2):
resultado = numero1 + numero2
return HttpResponse(f'<h1>A soma de {numero1} + {numero2} é igual a: {resultado} </h1>')
def sub(request, numero1, numero2):
resultado = numero1 - numero2
return HttpResponse(f'<h1>A subtração de {numero1} - {numero2} é igual a: {resultado} </h1>')
def divisao(request, numero1, numero2):
resultado = numero1 / numero2
return HttpResponse(f'<h1>A divisão de {numero1} / {numero2} é igual a: {resultado} </h1>')
def multi(request, numero1, numero2):
resultado = numero1 * numero2
return HttpResponse(f'<h1>A multiplicação de {numero1} x {numero2} é igual a: {resultado} </h1>') |
C# | UTF-8 | 3,498 | 3.125 | 3 | [
"BSD-2-Clause"
] | permissive | using System;
#if !NET35
using System.Collections.Concurrent;
#endif
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace SharpRaven.Utilities {
public class CircularBuffer<T>
{
#if NET35
private class ConcurrentQueue<T> : ICollection, IEnumerable<T>
{
private readonly Queue<T> _queue;
public ConcurrentQueue()
{
_queue = new Queue<T>();
}
public IEnumerator<T> GetEnumerator()
{
lock (SyncRoot)
{
foreach (var item in _queue)
{
yield return item;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void CopyTo(Array array, int index)
{
lock (SyncRoot)
{
((ICollection)_queue).CopyTo(array, index);
}
}
public int Count
{
get
{
lock (SyncRoot)
{
return _queue.Count;
}
}
}
public object SyncRoot
{
get { return ((ICollection)_queue).SyncRoot; }
}
public bool IsSynchronized
{
get { return true; }
}
public bool IsEmpty
{
get { return this.Count == 0; }
}
public void Enqueue(T item)
{
lock (SyncRoot)
{
_queue.Enqueue(item);
}
}
public T Dequeue()
{
lock (SyncRoot)
{
return _queue.Dequeue();
}
}
public T Peek()
{
lock (SyncRoot)
{
return _queue.Peek();
}
}
public void Clear()
{
lock (SyncRoot)
{
_queue.Clear();
}
}
public void TryDequeue(out T result)
{
try
{
result = Dequeue();
}
catch
{
result = default(T);
}
}
}
#endif
private readonly int size;
private ConcurrentQueue<T> queue;
public CircularBuffer(int size = 100)
{
this.size = size;
queue = new ConcurrentQueue<T>();
}
public List<T> ToList()
{
var listReturn = this.queue.ToList();
return listReturn.Skip(Math.Max(0, listReturn.Count - size)).ToList();
}
public void Clear()
{
queue = new ConcurrentQueue<T>();
}
public void Add(T item) {
if (queue.Count >= size)
{
T result;
this.queue.TryDequeue(out result);
}
queue.Enqueue(item);
}
public bool IsEmpty()
{
return queue.IsEmpty;
}
}
}
|
PHP | UTF-8 | 1,197 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Auth;
use App\EmailConfirmation;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class EmailVerificationController extends Controller
{
/**
* Verifies the user email
*
* @param $id
* @param $token
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function verify($id, $token)
{
$confirmation = EmailConfirmation::find($id);
if(
!$confirmation instanceof EmailConfirmation ||
!$confirmation->tokenValid($token) ||
$confirmation->isExpired()
) {
return view('auth.verify', ['success' => false]);
}
// Mark email as verified and update user email
$user = $confirmation->user;
$user->email_verified = true;
$user->email = $confirmation->email;
$user->save();
// Delete confirmation and all of its siblings
EmailConfirmation::withEmail($confirmation->email)->delete();
// Delete other expired verifications
EmailConfirmation::onlyExpired()->delete();
return view('auth.verify', ['success' => true]);
}
}
|
Swift | UTF-8 | 2,108 | 2.859375 | 3 | [] | no_license | //
// XMLExtensions.swift
// xccikit-cov
//
// Created by Tristian Azuara on 11/13/20.
//
import Foundation
//let XMLHeader = XMLElement(name: "?xml", attributes: [
// "version": "1.0",
// "encoding": "UTF-8",
// "standalone": "yes"
//])
//XMLHeader
//<!DOCTYPE report
// PUBLIC '-//JACOCO//DTD Report 1.0//EN'
// 'report.dtd'>
protocol XMLElementProtocol {
var xmlElement: XMLElement { get }
}
extension XMLElement: XMLElementProtocol {
var xmlElement: XMLElement { self }
}
internal extension XMLElement {
convenience init(name: String, attributes: [AnyHashable : Any] = [:], children: XMLElement...) {
self.init(name: name)
setAttributesAs(attributes)
addChildren(children)
}
convenience init<S : Sequence>(name: String, attributes: [AnyHashable : Any] = [:],
children: S) where S.Element : XMLElementProtocol {
self.init(name: name)
setAttributesAs(attributes)
addChildren(children)
}
func addChildren<Seq : Sequence>(_ sequence: Seq)
where Seq.Element : XMLElementProtocol {
sequence.map { $0.xmlElement }.forEach { self.addChild($0) }
}
}
internal extension Dictionary where Key == AnyHashable, Value == Any {
func merged(with other: Self) -> Self {
self.merging(other, uniquingKeysWith: {$1})
}
}
internal extension XMLNode {
static func attribute(_ name: String, _ value: CustomStringConvertible) -> XMLNode {
let node = XMLNode(kind: .attribute, options: .nodeUseDoubleQuotes)
node.name = name
node.stringValue = String(describing: value)
return node
}
}
internal extension XMLElement {
func addAttributes(_ nodes: XMLNode...) {
for node in nodes {
addAttribute(node)
}
}
}
extension String: XMLElementProtocol {
var xmlElement: XMLElement {
let textNode = XMLNode(kind: .text)
textNode.stringValue = self
let sourceElem = XMLElement(name: "source")
sourceElem.addChild(textNode)
return sourceElem
}
}
|
C++ | UTF-8 | 7,485 | 3.46875 | 3 | [] | no_license | //
// Map.cpp
// Proj2
//
// Created by Mitchell McLinton on 23/1/20.
// Copyright © 2020 Mitchell McLinton. All rights reserved.
//
#include "Map.h"
#include <iostream>
// TODO: Implement constructor
Map::Map() : m_nItems(0) {
dummy.next = &dummy;
dummy.prev = &dummy;
}
// TODO: Implement destructor
Map::~Map() {
Node* t = dummy.next;
while (t != &dummy) {
Node* delNode = t;
t = t->next;
delete delNode;
}
}
// TODO: Implement copy constructor
Map::Map(const Map& other) : m_nItems(other.m_nItems) {
if (other.empty()) {
dummy.next = &dummy;
dummy.prev = &dummy;
} else {
// dynamically allocate and copy item of first meaningful node
dummy.next = new Node;
dummy.next->item = other.dummy.next->item;
// pointers to track current node in traversal
Node* p1 = dummy.next;
Node* p2 = other.dummy.next;
for (int i=1; i < m_nItems; i++, p2 = p2->next) {
p1->next = new Node;
p1->next->item = p2->next->item; // copy item
Node* temp = p1; // linking nodes
p1 = p1->next;
p1->prev = temp;
}
p1->next = &dummy; // make linked list doubly and circular
dummy.prev = p1;
}
}
// TODO: Implement assignment operator
// Remember to check for aliasing issues, i.e. trying to call m = m;
// Remember to use the swap function
Map& Map::operator=(const Map& rhs) {
if (this != &rhs) {
Map temp(rhs);
swap(temp);
}
return *this;
}
// TODO: Implement empty() function
bool Map::empty() const {
return dummy.next == &dummy;
}
// TODO: Implement size() function
int Map::size() const {
return m_nItems;
}
// TODO: Implement insert() function
bool Map::insert(const KeyType& key, const ValueType& value) {
for (Node* t = dummy.next; t != &dummy; t = t->next)
if (t->item.key == key) return false; // trying to add duplicate key, so return false
Node* ptr = new Node;
ptr->next = &dummy; // by default we add to the back of the linked list
ptr->prev = dummy.prev;
ptr->prev->next = ptr;
dummy.prev = ptr;
ptr->item.key = key;
ptr->item.val = value;
m_nItems++;
return true;
}
// TODO: Implement update() function
bool Map::update(const KeyType& key, const ValueType& value) {
for (Node* t = dummy.next; t != &dummy; t = t->next) {
if (t->item.key == key) {
t->item.val = value;
return true;
}
}
return false;
}
// TODO: Implement insertOrUpdate() function
bool Map::insertOrUpdate(const KeyType& key, const ValueType& value) {
if (!update(key, value))
insert(key, value);
return true;
}
// TODO: Implement erase() function
bool Map::erase(const KeyType& key) {
if (empty())
return false;
for (Node* t = dummy.next; t != &dummy; t = t->next) {
if (t->item.key == key) {
t->prev->next = t->next;
t->next->prev = t->prev;
delete t;
m_nItems--;
return true;
}
}
return false;
}
// TODO: Implement contains() function
bool Map::contains(const KeyType& key) const {
for (Node* t = dummy.next; t != &dummy; t = t->next)
if (t->item.key == key) return true;
return false;
}
// TODO: Implement two parameter get() function
bool Map::get(const KeyType& key, ValueType& value) const {
for (Node* t = dummy.next; t != &dummy; t = t->next) {
if (t->item.key == key) {
value = t->item.val;
return true;
}
}
return false;
}
// TODO: Implement three parameter get() function
bool Map::get(int i, KeyType& key, ValueType& value) const {
if (i < 0 || i >= size())
return false;
int j = 0;
Node* t = dummy.next;
while (j <= i) {
key = t->item.key;
value = t->item.val;
t = t->next;
j++;
}
return true;
}
// TODO: Implement swap() function
void Map::swap(Map& other) {
Node* tempNext = dummy.next;
dummy.next = other.dummy.next;
other.dummy.next = tempNext;
tempNext->prev = &other.dummy;
dummy.next->prev = &dummy;
Node* tempPrev = dummy.prev;
dummy.prev = other.dummy.prev;
other.dummy.prev = tempPrev;
tempPrev->next = &other.dummy;
dummy.prev->next = &dummy;
int tempItems = m_nItems;
m_nItems = other.m_nItems;
other.m_nItems = tempItems;
}
void Map::dump() const {
std::cerr << std::endl << "=== dump() called ===" << std::endl;
std::cerr << "Size of Map is: " << m_nItems << std::endl;
std::cerr << "Printing contents of map: " << std::endl;
for (Node* t = dummy.next; t != &dummy; t = t->next)
std::cerr << "\t" << t->item.key << ": " << t->item.val << std::endl;
std::cerr << "=== dump() called ===" << std::endl << std::endl;
}
// TODO: Implement combine() function
bool combine(const Map& m1, const Map& m2, Map& result) {
Map combinedMap;
// fill in combinedMap with m1's values
for (int i=0; i < m1.size(); i++) {
KeyType m1key;
ValueType m1value;
m1.get(i, m1key, m1value);
combinedMap.insert(m1key, m1value);
}
bool returnFlag = true;
// now check each of m2's values against those in combinedMap, inserting/deleting according to spec rules
for (int i=0; i < m2.size(); i++) {
KeyType m2key;
ValueType m2value;
m2.get(i, m2key, m2value);
if (!combinedMap.contains(m2key)) {
combinedMap.insert(m2key, m2value);
} else {
ValueType resultValue;
combinedMap.get(m2key, resultValue);
if (resultValue == m2value)
continue;
else {
combinedMap.erase(m2key);
returnFlag = false;
}
}
}
result = combinedMap;
return returnFlag;
}
// TODO: Implement reassign() function
void reassign(const Map& m, Map& result) {
Map reassignedMap;
// if map only has one key-value pair, can't reassign anything, so result will just be m
if (m.size() == 1) {
reassignedMap = m;
return;
}
// use two int counters to keep track of pairs in Map m
for (int i = 0, j = 1; j < m.size() && i < m.size(); i += 2, j += 2) {
KeyType p1Key;
ValueType p1Val;
KeyType p2Key;
ValueType p2Val;
// get details of items
m.get(i, p1Key, p1Val);
m.get(j, p2Key, p2Val);
// swap them
reassignedMap.insertOrUpdate(p1Key, p2Val);
reassignedMap.insertOrUpdate(p2Key, p1Val);
}
// if m.size() returned an odd number, result wouldn't contain the very last item in Map m
// so we swap the values that the first and last keys have
if (m.size() % 2 != 0) {
KeyType hKey;
ValueType hValue;
KeyType tKey;
ValueType tValue;
m.get(m.size()-1, tKey, tValue); // take value of last item in m (not yet in result)
reassignedMap.get(0, hKey, hValue); // take new value of first item in result
reassignedMap.update(hKey, tValue); // reassign first item in result
reassignedMap.insert(tKey, hValue); // and add the last item to result
}
result = reassignedMap;
}
|
Markdown | UTF-8 | 1,608 | 3.078125 | 3 | [] | no_license | # Alphabet_Soup
## Project Description
The project consisted of creating a machine learning model to predict the success of a venture paid by Alphabet Soup.
## Resources
- Data source:
- charity_data.csv
- Software: Python 3.7.7, Jupyter Notebook, Visual Studio Code 1.43.1
## Preprocessing
* Dropped identification column (EIN). Each number appears only once in the dataset.
* Bucket NAME (frequency less than 10 = 'Other')
* Bucket APPLICATION_TYPE (frequency less than 100 = 'Other')
* Target variable: IS_SUCCESSFUL
## Model Optimization
__1.__ Number of neurons and layers selected for neural network model:\
Single layer with twice as many neurons as the number of input features.
__2.__ Steps taken to try and increase model performance:
* Made sure to not bucket together too many of the rare categorical values when preprocessing so as not to lose too much data;
* Increasing the number of neurons to 3x the number of input features did not improve accuracy significantly;
* Running more epochs (150) improved accuracy slightly, but not enough to justify the additional epochs;
* Creating a Deep Learning model by adding a second layer with 10 neurons resulted in the model overfitting the training data. Reducing the epochs to 50 and changing the number of neurons in the hidden layers to 30 and 10 did not improve it.
__3.__ Different model that could be implemented to solve this classification problem:\
Support Vector Machine - SVM. They are very effective in classifying and creating regression using two groups, which was the nature of the current project: binary classification.
|
Python | UTF-8 | 168 | 3.09375 | 3 | [
"CC0-1.0"
] | permissive |
f = open('temp.txt', 'w')
lines = ['line {}\n'.format(i) for i in range(10)]
f.writelines(lines)
f.close()
f = open('temp.txt', 'r+')
f.write('new line')
f.close()
|
JavaScript | UTF-8 | 1,396 | 2.796875 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | /* @flow */
import React, { Component } from 'react';
/**
* Implements a toolbar in React/Web. It is a strip that contains a set of
* toolbar items such as buttons.
*
* @class StatelessToolbar
* @extends Component
*/
export default class StatelessToolbar extends Component {
/**
* Base toolbar component's property types.
*
* @static
*/
static propTypes = {
/**
* Children of current React component.
*/
children: React.PropTypes.node,
/**
* Toolbar's class name.
*/
className: React.PropTypes.string,
/**
* Handler for mouse out event.
*/
onMouseOut: React.PropTypes.func,
/**
* Handler for mouse over event.
*/
onMouseOver: React.PropTypes.func
};
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render(): ReactElement<*> {
const {
className,
onMouseOut,
onMouseOver
} = this.props;
return (
<div
className = { `toolbar ${className}` }
onMouseOut = { onMouseOut }
onMouseOver = { onMouseOver }>
{
this.props.children
}
</div>
);
}
}
|
Markdown | UTF-8 | 2,820 | 2.59375 | 3 | [] | no_license |
# \raw_image_development_anchor
+ \raw_image_anchor file records image data captured by the camera's image sensor without any processing
+ things editable only with \raw_image_link\plural{s}:
+ white balance (thus don't worry about a white balance setting when shooting raw)
+ overexposed highlights which hid the details
## colour channels
+ a camera sensor determines the colour of light through sensor cells with either red, green or blue colour filters organized in a specific pattern: they make red, green and blue colour channels
+ each colour channel senses how much light entered it, but only up to a specific maximum value, the \clipping_value_anchor
+ if a channel reading is at the \clipping_value_link, the channel is ___clipped___
+ if a channel reading is below the \clipping_value_link, the channel is ___valid___
+ channel readings affecting the pixels:
+ all three channel are:
+ ___valid___: no correction needed, colour information correct
+ ___clipped___: nothing can be done, they must represent a very bright highlight
+ one or two channels are ___clipped___: no correct colour information, but a ___valid___ channel reading can be used to restore the correct tonal information
## an idiot's guide to \raw_image processing workflow with \digiKam
+ of course, first and foremost you need to enable \raw_image_link format in the camera before taking pictures
+ set the \key{Settings}→\key{Configure}→\key{Image Editor}→\key{RAW Behavior}→\key{Using the default settings, in 16 bit} option in \digiKam_link
+ after downloading the \raw_image_link\plural{s} to a \digiKam_link album, choose a \raw_image_link to edit, and open an \key{Image Editor}
+ use the following chain of tools:
+ \key{Enhance}→\key{Lens} to fix a lens distortion, choosing the appropriate lens, but make sure the final results is without artifacts at the edges, otherwise don't apply the correction
+ \key{Enhance}→\key{Local Contrast} to correct the underexposed areas
+ \key{Color}→\key{Auto-Correction}, \key{Color}→\key{Hue/Saturation/Lightness} to apply tonal adjustments
+ \key{Enhance}→\key{Noise Reduction}
+ \key{Enhance}→\key{Sharpen}→\key{Refocus} (the most advanced sharpening method in \digiKam_link):
+ \key{Circular Sharpness}: the default value of $1$ might not yield visible results, you can increase it, but increase the \key{Correlation} as well
+ \key{Correlation}: use $0.5$ with the \key{Circular Sharpness} of $1$, for the higher vaules of the former, increase the latter to a value close to $1$, e.g. $0.95$, to reduce artifacts
+ save the changes, e.g. as the `JPEG` image
+ the original \raw_image_link disappears from the album, but is still available from the \key{Image Editor}, should the final result be unsatisfactory
|
Java | UTF-8 | 1,200 | 2.015625 | 2 | [] | no_license | package com.kk.weather.entity;
/**
*
* @author KGZ
* @date 2018/11/26
*/
public class User {
private int userId;
private String nickName;
private String account;
private String password;
//星座
private String constellation;
private String email;
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConstellation() {
return constellation;
}
public void setConstellation(String constellation) {
this.constellation = constellation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
|
JavaScript | UTF-8 | 1,286 | 3.21875 | 3 | [] | no_license | let React = require('react');
let TemperatureInput = require('./TemperatureInput');
class Calculator extends React.Component{
constructor(props) {
super(props);
this.changeCelsius = this.changeCelsius.bind(this);
this.changeFarenheit = this.changeFarenheit.bind(this);
this.state = {temperatureC: 0, temperatureF : 0 };
}
toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
toFahrenheit(celsius) {
return (celsius * 9 / 5) + 32;
}
changeCelsius(e) {
let f = this.toFahrenheit(this.state.temperatureC);
this.setState({temperatureC: e.target.value, temperatureF: f});
}
changeFarenheit(e) {
let c = this.toCelsius(this.state.temperatureF);
this.setState({temperatureC: c, temperatureF: e.target.value});
}
render() {
const temperature = this.state.temperature;
return (
<div>
<TemperatureInput scale="c" temperature = {this.state.temperatureC} maxvalue={100} onTempChange={this.changeCelsius}/>
<TemperatureInput scale="f" temperature = {this.state.temperatureF} maxvalue={100} onTempChange={this.changeFarenheit}/>
</div>
);
}
}
module.exports = Calculator; |
Python | UTF-8 | 11,958 | 2.609375 | 3 | [] | no_license | #FIXME: This doesn't close its connections!!!!
import serial
import socket
import Queue
import thread
import threading
import time
import json
#TODO:redo this naming scheme
serialPortAddresses = ['/dev/ttyACM0', '/dev/ttyACM1', '/dev/ttyACM2', '/dev/ttyACM3', '/dev/ttyACM4', '/dev/ttyACM5', '/dev/ttyACM6', '/dev/ttyACM7'] #all USB device addresses listed here
frontMotorControllerAddress = '/dev/ttyACM2'#front motors microcontroller
rearMotorControllerAddress = '/dev/ttyACM3'#TODO
frontMotorControllerPort = None
rearMotorControllerPort = None
serialPorts = [] #all serial connections
launchpad1 = None;
launchpad2 = None;
launchpad3 = None;
launchpad4 = None;
launchpad5 = None;
launchpad6 = None;
gps = None;
sampleBayServo = None;
dataSocket = None #Network socket
BAUD = 9600 #USB microcontroller connnection baud rate
READ_TIMEOUT = 0.1 #0.1 second timeout on read opperations
HOST = 'r04jpjwxc.device.mst.edu' #FIXME: replace with proper address
#HOST = 'r03tjm6f4.device.mst.edu'
PORT = 55555 #FIXME: we need to pick a port to opperate on
#PORT = 30000
SOCKET_BUFF_SIZE = 1024 #FIXME: May need to change this
SOCKET_TIMEOUT = 0.05 #Timeout for reading data from the socket
commandQueue = Queue.Queue(0)#global, cross-thread data queue for command data
dataQueue = Queue.Queue(0)#global, cross-thread data queue for sensor data
safeprint = thread.allocate_lock()
shutdown = False
#==============================================================================
#Create USB connections to microcontrollers
def startSerial():
global launchpad1
global launchpad2
global launchpad3
global launchpad4
global launchpad5
global launchpad6
for address in serialPortAddresses:
log("Attempting connection on \"" + address + "\"")
try:
newPort = serial.Serial(address, BAUD)
newPort.timeout = READ_TIMEOUT
newPort.open()
newPort.write('1')#the microcontroller waits to receive this before its starts writing
newPort.flush()
log("Successfully opened serial connection")
identifier = newPort.readline()[0:11]
if(identifier == "launchpad_1"):
launchpad1 = newPort
serialPorts.append(launchpad1)#TODO: remove this
log("Launchpad 1 connected")
elif(identifier == "launchpad_2"):
launchpad2 = newPort
serialPorts.append(launchpad2)#REMOVE
log("Launchpad 2 connected")
elif(identifier == "launchpad_3"):
launchpad3 = newPort
serialPorts.append(launchpad3)#REMOVE
log("Launchpad 3 connected")
elif(identifier == "launchpad_4"):
launchpad4 = newPort
log("Launchpad 4 connected")
elif(identifier == "launchpad_5"):
launchpad5 = newPort
log("Launchpad 5 connected")
elif(identifier == "launchpad_6"):
launchpad6 = newPort
log("Launchpad 6 connected")
else:
log("Unidentified device connected on \"" + address + "\"")
#serialPorts.append(newPort)
except Exception as e:
log("Connection on \"" + address + "\" failed")
log(e)
# =================================================
# Deprecated motor controller initialization code
# try:
# frontMotorControllerPort = serial.Serial(frontMotorControllerAddress, BAUD)
# frontMotorControllerPort.timeout = READ_TIMEOUT
# frontMotorControllerPort.open()
#
# rearMotorControllerPort = serial.Serial(rearMotorControllerAddress, BAUD)
# rearMotorControllerPort.timeout = READ_TIMEOUT
# rearMotorControllerPort.open()
# except Exception:
# log('Failed to connect to motor controllers\' serial port')
# ============================================================
print "USB Serial connections initialized"
#Create client socket connection to base station server
def startSocket():
global dataSocket
dataSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dataSocket.connect((HOST, PORT)) #Connect to the base station's server socket
dataSocket.settimeout(SOCKET_TIMEOUT)
print "Socket successfully connected to server"
print dataSocket
#Starts the producer and consumer threads, socket thread
def startThreads():
startedThreads = []
sThread = threading.Thread(target=socketThread, args=())
sThread.start()
startedThreads.append(sThread)
cThread = threading.Thread(target=commandConsumer, args=())
cThread.start()
startedThreads.append(cThread)
dThread = threading.Thread(target=dataProducer, args=())
dThread.start()
startedThreads.append(dThread)
return startedThreads
#The function used by the command queue consumer thread
def commandConsumer():
#TODO
global commandQueue
with safeprint:
print "command queue in consumer thread:"
print commandQueue
while not shutdown:
try:
command = commandQueue.get(block = False) #Pop a command off the queue
except Queue.Empty:
pass
else:
handleCommand(command)#Handle the command (Send to microcontroller)
#The function used by the data queue producer thread
def dataProducer():
#TODO
global dataQueue
while not shutdown:
for port in serialPorts:
data = readData(port)
dataQueue.put(data)
#The server socket thread function
def socketThread():
global commandQueue
global dataSocket
global dataQueue
while not shutdown:
#read commands from the socket, write it to the queue
try:
command = dataSocket.recv(SOCKET_BUFF_SIZE)
except socket.timeout:
pass
else:
commands = command.split('\n')
for singleCommand in commands:
commandQueue.put(singleCommand.strip('\n'))
log("Put this in command queue: " + singleCommand)
#read data from the queue write it to the socket
try:
data = dataQueue.get(block = False) #Pop sensor data off the queue
except Queue.Empty:
pass
else:
#write sensor data to the socket
try:
if data is not None and isinstance(data, str):
dataSocket.sendall(data)
with safeprint:
print 'Sent: ' + data
except socket.error:
pass
#TODO: print error to console
#The function which handles commands
def handleCommand(command):
#TODO
#with safeprint:
#print(command)
#serialPorts[0].write(command + "\n")
#serialPorts[0].flush()
try:
jsonData = json.loads(command)
type = jsonData['type']
log(type)
if type == 'drive_motor':
handleDriveMotorCommand(jsonData)#TODO
elif type == 'box_drop':
handleBoxDropCommand(jsonData)#TODO
elif type == 'arm':
handleArmCommand(jsonData);#TODO
elif type == 'sample_bay':
handleSampleBayCommand(jsonData)#TODO
else:
log('Command type error. Command: ' + command)
except Exception as e:
log("Failed to parse JSON: " + command)
log(e)
#The function which reads data from a serial port
def readData(port):
#TODO
#Handle the data. The microcontroller will probably be sending raw ASCII data at this point
#We can serialize it to JSON/BSON here
try:
newLine = port.readline()
id = int(newLine[0:2])#get the launchpad id
newLine = newLine[3:]#strip out the id and delimeter
if id == 1:
parseLaunchpad1(newLine)
elif id == 2:
parseLaunchpad2(newLine)
elif id == 3:
parseLaunchpad3(newLine)
elif id == 4:
parseLaunchpad4(newLine)
elif id == 5:
parseLaunchpad5(newLine)
elif id == 6:
parseLaunchpad6(newLine)
elif id == 7:
parseLaunchpad7(newLine)
else:
log('Microcontroller id error. ID: ' + id + ' Data: ' + newLine)
except Exception:
pass #some sort of error, move on
#Parse data from launchpad #1
def parseLaunchpad1(data):
global dataQueue
allTempData = data.split(',')
for tempData in allTempData:
sensorTempMapping = tempData.split(':')#returns array with id and temperature reading
id = int(sensorTempMapping[0])
temperature = float(sensorTempMapping[1])
#Example:
#{"type":"temp", "source_id": 1, "temp": 72.5, "units": "F"}
dataArray = {'type': 'temp', 'source_id': id, 'temp': temperature}
dataQueue.put(json.dumps(dataArray))
#Parse data from launchpad #2
#DEBUG THIS
def parseLaunchpad2(data):
global dataQueue
allTempData = data.split(',')
for tempData in allTempData:
sensorTempMapping = tempData.split(':')#returns array with id and temperature reading
id = int(sensorTempMapping[0])
temperature = float(sensorTempMapping[1])
#Example:
#{"type":"temp", "source_id": 1, "temp": 72.5, "units": "F"}
dataArray = {'type': 'temp', 'source_id': id, 'temp': temperature}
dataQueue.put(json.dumps(dataArray))
#FIXME: this will need to be changed to add the altitude sensor
def parseLaunchpad3(data):
global dataQueue
allBatteryData = data.split(',')
for batteryData in allBatteryData:
batteryDataMapping = batteryData.split(':')
id = int(batteryDataMapping[0])
charge = float(batteryDataMapping[1])
#Example:
#{"type":"battery", "source_id": 1, "charge_percent":, 80.5}
dataArray = {'type': 'battery', 'source_id': id, 'charge': charge}
dataQueue.put(json.dumps(dataArray))
#TODO
def parseLaunchpad4(data):
#front motor controls; no data to read in
pass
#TODO
def parseLaunchpad5(data):
#rear motor controls; no data to read in
pass
#TODO
def parseLaunchpad6(data):
#auxillary controls; no data to read in
pass
#TODO
def parseLaunchpad7(data):
pass
#==============================================================================
#Command handlers
#TODO
def handleDriveMotorCommand(command):
global launchpad4
global launchpad5
try:
#parse data and send to launchpad
action = command['action']#the type of action the motor should take
motorID = int(command['id'])#id of the motor
log("Hi from drive motor function!")
commandString = 'M:0' + str(int(motorID)) + ','#DEBUG
log("315")#!!!!!!!!!!!!!!
if action == 'slew_axis':
speed = command['speed']
commandString += 'SL:' + str(motorNumFormat(speed))
log("319")#!!!!!!!!!!!!!!!!!!!!!!!
if motorID == 1 or motorID == 2:
if launchpad4 is not None:
log("Writing to lanuchpad4: " + commandString)
launchpad4.write(commandString)
launchpad4.flush()
else:
log("Unable to handle motor command, controller 4 not initialized.")
log(len(serialPorts))
elif motorID == 3 or motorID == 4:
if launchpad5 is not None:
launchpad5.write(commandString)
launchpad5.flush()
else:
log("Unable to handle motor command, controller 5 not initialized.")
elif action == 'move_relative':
pass#TODO
elif action == 'move_absolute':
pass#TODO
except Exception as e:
log('Failed to handle motor drive command. Error: ')
log(e)
#Formats an integer to always utilize four string characters
def motorNumFormat(value):
string = ''
if value < 10:
string += '000' + str(int(value))
elif value < 100:
string += '00' + str(int(value))
elif value < 1000:
string += '0' + str(int(value))
else:
string += str(int(value))
return string
#TODO
def handleBoxDropCommand(command):
pass
#TODO
def handleArmCommand(command):
pass
#TODO
def handleSampleBayCommand(command):
pass
#==============================================================================
def log(string):
with safeprint:
print string
#main thread
if __name__ == '__main__':
print "command queue in main:"
print commandQueue
print dataQueue
startSerial()
startSocket()
threads = startThreads()
for waitfor in threads: waitfor.join()
#time.sleep(20)#FIXME: This will only allow 20 minutes of executable time before crash; should actually use a join call
#main thread exits here
with safeprint:
print "Exiting main thread..." |
Python | UTF-8 | 125 | 3.5625 | 4 | [] | no_license | A = int(input("ingrese el valor(entero) A"))
B = int(input("ingrese el valor(entero) B"))
RES = (A + B)** (2 / 3)
print(RES)
|
C++ | UTF-8 | 293 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int group(int x) {
if (x == 2) return 0;
if (x == 4 || x == 6 || x == 9 || x == 11) return 1;
return 2;
}
int main(int argc, char *argv[]) {
int x, y;
cin >> x >> y;
if (group(x) == group(y)) printf("Yes\n");
else printf("No\n");
return 0;
} |
Python | UTF-8 | 2,157 | 3.46875 | 3 | [] | no_license | import pyglet
from pyglet.gl import *
#global size of all tiles
tile_size = 16
def set_tile_size(size):
tile_size = size
#class that defines all tiles
class tile:
def __init__(self):
#all tiles have the same size
self.size = tile_size
#use pyglet to create a texture
self.image = pyglet.image.Texture.create(self.size, self.size).get_image_data()
#then get data from it
self.data = list(self.image.get_data('RGBA', self.size*4))
#flag that marks if the image has changed
self.dirty = True
#set a pixel color [r,g,b,a] at position x, y
def set_pixel(self, x, y, color):
#test if inside the tile
if x < 0 or y < 0 or x >= tile_size or y >= tile_size:
return
#calculate the offset for the pixel that we want to change
pos = (x + y * self.size) * 4
#change accordingly
for i in range(0,4):
self.data[pos + i] = color[i]
self.dirty = True
#get a pixel color [r,g,b,a] at position x, y
def get_pixel(self, x, y):
#test if inside the tile
if x < 0 or y < 0 or x >= tile_size or y >= tile_size:
return [0,0,0,0]
#create the array for the pixel
pixel = [0,0,0,0]
#calculate the offset for the pixel that we want to sample
pos = (x + y * self.size) * 4
#fill the pixel array
for i in range(0,4):
pixel[i] = self.data[pos + i]
return pixel
#recreate the texture using pyglet
def update(self):
if not self.dirty:
return
#update the data
self.image.set_data('RGBA', self.size*4, bytes(self.data))
texture = self.image.get_texture()
#use openGL calls for setting the sampling strategy
glBindTexture(GL_TEXTURE_2D, texture.id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
self.dirty = False
def draw(self, x, y, size):
self.update()
self.image.blit(x = x, y = y, width = size, height = size)
|
C | UTF-8 | 352 | 3.734375 | 4 | [
"MIT"
] | permissive | #include <stdio.h>
void swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void sort(int *x, int *y, int *z){
if (*x < *y) swap(x, y);
if (*x < *z) swap(x, z);
if (*y < *z) swap(y, z);
}
int main(){
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
sort(&x, &y, &z);
printf("%d %d %d", x, y, z);
return 0;
} |
C# | UTF-8 | 2,255 | 2.71875 | 3 | [] | no_license | using System;
using System.IO;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Collections;
namespace Common {
[Serializable]
public class Path : IEquatable<Path> {
public String name;
public List<Node> points;
public float time;
public const int NOISE = -1;
public const int UNCLASSIFIED = 0;
public int clusterID;
public Path () {
points = new List<Node>();
}
public Path (List<Node> points) {
this.points = points;
if (points == null)
throw new ArgumentNullException ("Points can't be null");
}
public Path (Path p) {
this.points = new List<Node>();
foreach (Node n in p.points)
{
this.points.Add(new Node(n));
}
this.name = p.name;
this.time = p.time;
this.clusterID = p.clusterID;
if (points == null)
throw new ArgumentNullException ("Points can't be null");
}
public void ZeroValues () {
time = 0f;
}
public override string ToString () {
string str="";
foreach(Node node in points)
{
str += node.ToString();
}
if(str.Length==0){
return("()");
}
return str.Remove(str.Length-1);
}
public bool Equals(Path other)
{
if (points.Count != other.points.Count) return false;
for (int i = 0; i < points.Count; i ++)
{
if (!points[i].equalTo(other.points[i])) return false;
}
return true;
}
}
[XmlRoot("bulk"), XmlType("bulk")]
public class PathBulk {
public List<Path> paths;
public PathBulk () {
paths = new List<Path> ();
}
public static void SavePathsToFile (string file, List<Path> paths) {
XmlSerializer ser = new XmlSerializer (typeof(PathBulk));
PathBulk bulk = new PathBulk ();
bulk.paths.AddRange (paths);
using (FileStream stream = new FileStream (file, FileMode.Create)) {
ser.Serialize (stream, bulk);
stream.Flush ();
stream.Close ();
}
}
public static List<Path> LoadPathsFromFile (string file) {
XmlSerializer ser = new XmlSerializer (typeof(PathBulk));
PathBulk loaded = null;
using (FileStream stream = new FileStream (file, FileMode.Open)) {
loaded = (PathBulk)ser.Deserialize (stream);
stream.Close ();
}
return loaded.paths;
}
}
} |
Java | UTF-8 | 773 | 2.515625 | 3 | [] | no_license | package com.kevin.datastruct.controller;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author chenligeng
* guava 缓存限流
*/
@RestController
@Slf4j
public class GuavaRateLimit {
RateLimiter limiter = RateLimiter.create(2.0);
@GetMapping(value = "/limterData")
public String limterData(int count){
//每次消耗两个通行证
if (limiter.tryAcquire(count)){
log.info("ratelimit,{}",limiter.getRate());
return "success";
}else {
log.info("ratelimit,{}",limiter.getRate());
return "false";
}
}
}
|
Python | UTF-8 | 992 | 3.078125 | 3 | [] | no_license | '''
Bubble Charts(冒泡图)
'''
# 加载numpy和pandas包
import numpy as np
import pandas as pd
# 加载plotly包
import plotly as py
from plotly.offline import plot
# 加载数据
timesData = pd.read_csv("./timesData.csv")
import plotly.graph_objs as go
# 准备数据
x2011 = timesData.student_staff_ratio[timesData.year == 2011]
x2012 = timesData.student_staff_ratio[timesData.year == 2012]
trace1 = go.Histogram(
x=x2011,
opacity=0.75,
name = "2011",
marker=dict(color='rgba(171, 50, 96, 0.6)'))
trace2 = go.Histogram(
x=x2012,
opacity=0.75,
name = "2012",
marker=dict(color='rgba(12, 50, 196, 0.6)'))
data = [trace1, trace2]
# barmode : 直方图模式,如overlay,stack
layout = go.Layout(barmode='overlay',
title=' students-staff ratio in 2011 and 2012',
xaxis=dict(title='students-staff ratio'),
yaxis=dict( title='Count'),
)
fig = go.Figure(data=data, layout=layout)
plot(fig) |
PHP | UTF-8 | 190 | 2.875 | 3 | [] | no_license | <?php
$a = "testing srtlen";
echo strlen($a); //spasi ikut di hitung
echo "<br>";
echo str_word_count($a);
echo "<br>";
echo strrev($a);
echo "<br>";
echo str_replace("e", "a", $a);
?> |
JavaScript | UTF-8 | 2,850 | 2.609375 | 3 | [] | no_license | const axios = require('axios');
const request = require('request');
const yelp = require('yelp-fusion');
const mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser');
const { API_TOKEN } = require('./env/config.js');
const chalk = require('chalk');
let apiKey;
try {
apiKey = require('./env/config.js').API_TOKEN;
} catch (err) {
apiKey = process.env.TOKEN;
}
const client = yelp.client(apiKey);
// https://api.yelp.com/v3/businesses/search?term=burgers&location=10017&radius=20000&limit=50&open_now=true
// make call businesses/search using yelp-fusion.search
// https://www.yelp.com/developers/documentation/v3/business_search
const getRestaurants = (searchObj) => {
// @params: searchObj(type: obj, example: {term: 'tacos', loc: 10017})
const searchRequest = {
term: searchObj.term,
location: searchObj.loc,
offset: searchObj.offset,
limit: 50,
open_now: true
};
return client.search(searchRequest)
.then(data => data.jsonBody.businesses)
// @output: a promise with an array of the businesses
.catch((err) => {
console.log(chalk.bold.red('Encoutered error requesting restaurants from Yelp', err));
});
};
// make call to businesses/{id} using yelp-fusion.business
// https://www.yelp.com/developers/documentation/v3/business
const getRestaurantDetails = restaurantId => client.business(restaurantId).then((data) => {
// console.log(chalk.green('Retrieved', (data.body)));
return data.body;
}).catch((err) => {
console.log(chalk.bold.red('Encountered error requesting restaurant details from Yelp', err));
});
module.exports = {
getRestaurants: getRestaurants,
getRestaurantDetails: getRestaurantDetails,
};
/* TEST CALLS */
// getRestaurants({term: 'tacos', loc: 10017})
// .then(businesses => console.log(businesses)) // shows an array of the businesses
// //// teammates' removed code, saved below just in case
// .then((response) => {
// const firstResult = response.jsonBody.businesses[0];
// const prettyJson = JSON.stringify(firstResult, null, 4);
// console.log(prettyJson);
// })
// .then(data => console.log(data.jsonBody))
// .catch((e) => {
// console.log(e);
// });
// const getRestaurantDetails = (restaurantIdObj) => {
// client.search(restaurantIdObj)
// .then((response) => {
// const firstResult = response.jsonBody.businesses[0];
// const prettyJson = JSON.stringify(firstResult, null, 4);
// console.log(prettyJson);
// })
// .catch((e) => {
// console.log(e);
// });
// };
// const testId = 'SULHf6nGQ8sK0UpG1XU30w';
// // // getRestaurantDetails(testId).then(data => console.log(data));
// // // console.log(getRestaurantDetails(testId));
// getRestaurantDetails(testId)
// .then(data => console.log(data))
// .catch(err => console.log(err));
|
Java | UTF-8 | 823 | 2.671875 | 3 | [] | no_license | package com.example.personacrud.domain;
import com.example.personacrud.domain.values.IsProfessional;
import com.example.personacrud.domain.values.Name;
import com.example.personacrud.domain.values.Phone;
public final class PersonBuilder {
protected Name name;
protected Phone phone;
protected IsProfessional isProfessional;
private PersonBuilder() {
}
public static PersonBuilder aPerson() {
return new PersonBuilder();
}
public PersonBuilder withName(Name name) {
this.name = name;
return this;
}
public PersonBuilder withPhone(Phone phone) {
this.phone = phone;
return this;
}
public PersonBuilder withIsProfessional(IsProfessional isProfessional) {
this.isProfessional = isProfessional;
return this;
}
}
|
C | GB18030 | 4,046 | 2.84375 | 3 | [] | no_license | #include"DS1302.h"
#include "delay.h"
uint8_t read[7]={0x81,0x83,0x85,0x87,0x89,0x8b,0x8d};//롢֡ʱա¡ܡļĴַ
uint8_t write[]={0x80,0x82,0x84,0x86,0x88,0x8a,0x8c};//д롢֡ʱա¡ܡļĴַ
/*PA4.6Ϊ*/
/*PA5Ϊ©ģʽģʽܹʵ˫IO*/
void ds1302_GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Pin = ds1302clk|ds1302rst;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_InitStruct.GPIO_Pin = ds1302dat;
GPIO_Init(GPIOB, &GPIO_InitStruct);
}
void write_1302byte(uint8_t dat)//дһֽڵsckд
{
uint8_t i=0;
GPIO_ResetBits(GPIOB,ds1302clk);
//ds1302clk=0;
delay_us(2);//ʱԼ2us
for(i=0;i<8;i++)
{
GPIO_ResetBits(GPIOB,ds1302clk);
//ds1302clk=0;
if(dat&0x01)
GPIO_SetBits(GPIOB,ds1302dat);
else
GPIO_ResetBits(GPIOB,ds1302dat);
//ds1302dat=(dat&0x01);
delay_us(2);
GPIO_SetBits(GPIOB,ds1302clk);
//ds1302clk=1;
dat>>=1;
delay_us(1);
}
}
uint8_t read_1302(uint8_t add)//
{
uint8_t i=0,dat1=0x00;
GPIO_ResetBits(GPIOB,ds1302rst);
GPIO_ResetBits(GPIOB,ds1302clk);
//ds1302rst=0;
//ds1302clk=0;
delay_us(3);//ʱ2us
GPIO_SetBits(GPIOB,ds1302rst);
//ds1302rst=1;
delay_us(3);//ʱҪԼ3us
write_1302byte(add);//дĴĵַ
for(i=0;i<8;i++)
{
GPIO_SetBits(GPIOB,ds1302clk);
//ds1302clk=1;
dat1>>=1;
GPIO_ResetBits(GPIOB,ds1302clk);
//ds1302clk=0;//ʱߣԱݵĶ
if(GPIO_ReadInputDataBit(GPIOB,ds1302dat)==1)//ߴʱΪߵƽ
{dat1=dat1|0x80;}
}
delay_us(1);
GPIO_ResetBits(GPIOB,ds1302rst);
//ds1302rst=0;
return dat1;
}
void write_1302(uint8_t add,uint8_t dat)//ָĴдһֽڵ
{
GPIO_ResetBits(GPIOB,ds1302rst);
GPIO_ResetBits(GPIOB,ds1302clk);
//ds1302rst=0;
//ds1302clk=0;
delay_us(1);//ʱ
GPIO_SetBits(GPIOB,ds1302rst);
//ds1302rst=1;
delay_us(2);//ʱԼ2us
write_1302byte(add);
write_1302byte(dat);
GPIO_ResetBits(GPIOB,ds1302rst);
GPIO_ResetBits(GPIOB,ds1302clk);
//ds1302clk=0;
//ds1302rst=0;
delay_us(1);
}
void ds1302_init(uint8_t *write,uint8_t *time)//ʼ1302
{
uint8_t i=0,j=0;
write_1302(0x8e,0x00);//ȥд
for(i=0;i<7;i++)//תBCD
{
j=time[i]%10;//λ
time[i]=(time[i]/10)*16+j;
}
for(i=0;i<7;i++)//жʱ
{
write_1302(write[i],time[i]);
}
write_1302(0x8e,0x80);//д
}
void ds1302_data(uint8_t *read)//ݲͨڴӡ
{
// u8 buffer3[50];
uint8_t i=0,g[7],time[7];
for(i=0;i<7;i++)
{
time[i]=read_1302(read[i]);
}//Ѿ
for(i=0;i<7;i++)
{
g[i]=time[i]%16;//λ
time[i]=time[i]/16;//ʮλ
}
//ʱת10g[i]ŵʱĸλ
//ʱtimeiŵʱʮλ
Data1.YR[0]=0X32;
Data1.YR[1]=0X30;
Data1.YR[2]=0X30+time[6];
Data1.YR[3]=0X30+g[6];
Data1.MN[0]=0X30+time[4];
Data1.MN[1]=0X30+g[4];
Data1.MN[2]=0X30+time[3];
Data1.MN[3]=0X30+g[3];
Data1.HM[0]=0X30+time[2];
Data1.HM[1]=0X30+g[2];
Data1.HM[2]=0X30+time[1];
Data1.HM[3]=0X30+g[1];
// sprintf((char *)buffer3,"20%d%d%d%d%d%d%d%d:%d%d:%d%d %d\r\n",\
// time[6],g[6],time[4],g[4],time[3],g[3],time[2],g[2],time[1],g[1],time[0],g[0],g[5]);
// Debug((char *)buffer3);
// s=time[0]+g[0];
}
|
Java | UTF-8 | 425 | 2.890625 | 3 | [] | no_license | package Visual;
import java.awt.Color;
import java.awt.Frame;
public class FirstFrame extends Frame{
public static void main(String args[]){
FirstFrame fr=new FirstFrame("First container!");
fr.setSize(240,240);
fr.setBackground(Color.yellow);
fr.setVisible(true);
}
public FirstFrame(String str){
super(str); //call constructor from super class
}
public FirstFrame(){
}
}
|
Java | UTF-8 | 2,378 | 1.851563 | 2 | [] | no_license | package com.qdxy.app.lhjh.activities.storageRoom;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import com.lf.tempcore.tempActivity.TempActivity;
import com.qdxy.app.lhjh.R;
import com.qdxy.app.lhjh.emues.CommonType;
/**毛坯入库申请详情
* Created by mac on 2017/2/20.
*/
public class ActStorageDetail extends TempActivity {
private CommonType mType;
@Override
protected void initContentView(Bundle savedInstanceState) {
setContentView(R.layout.act_storage_detail_layout);
}
@Override
protected void findViews() {
// initToolbar("毛坯入库申请详情");
mType = (CommonType) getIntent().getSerializableExtra("type");
switch (mType) {
case MAO_PI_STORAGE_SQ:
initToolbar("毛坯入库申请详情");
break;
case MAO_PI_STORAGE_CJ:
initToolbar("毛坯入库抽检详情");
break;
case MAO_PI_STORAGE_SP:
initToolbar("毛坯入库审批详情");
break;
case MAO_PI_LY:
case MAO_PI_STORAGE_LY:
initToolbar("毛坯领用详情");
break;
case MATERIAL_SQ:
case MATERIAL_FH:
case MATERIAL_SP:
initToolbar("辅料领用详情");
break;
default:
initToolbar(getResources().getString(R.string.app_name));
}
}
@Override
protected void setListeners() {
}
@Override
protected void bindValues() {
//启动fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragTempDetail titleFragment = new FragTempDetail();
Bundle bundlePrdUnchecked = new Bundle();
bundlePrdUnchecked.putSerializable("type", mType);//类型
bundlePrdUnchecked.putInt("id", getIntent().getIntExtra("id",-1));//类型
titleFragment.setArguments(bundlePrdUnchecked);
fragmentTransaction.add(R.id.act_storage_detail_fragFrame, titleFragment);
fragmentTransaction.commit();
}
@Override
protected void OnViewClicked(View v) {
}
}
|
Go | UTF-8 | 247 | 3.21875 | 3 | [
"MIT"
] | permissive | package leap
// IsLeapYear check if the year is leap or not
func IsLeapYear(year int) bool {
leap := false
if year%4 == 0 {
leap = true
if year%100 == 0 {
leap = false
if year%400 == 0 {
leap = true
}
}
}
return leap
}
|
Java | UTF-8 | 4,563 | 3.78125 | 4 | [] | no_license | package com.udemy.trees;
import java.util.PriorityQueue;
public class Heap {
private int[] heap;
private int size;
public Heap(int capacity){
this.heap = new int[capacity];
}
/**
* Max heap
* First insert left most position
* then heapify by swapping with the parent until u get the right position
* @param value value to be inserted
*/
public void insert(int value){
if(isFull()){
throw new IndexOutOfBoundsException("Heap is full");
}
heap[size] = value;
fixHeapAbove(size);
size++;
}
/**
* Take the right most value to makes the tree complete and replace it with deleted part
* Heapify: If replacement is greater thatn the parent fix above otherwise fix below (replace the parent with
* larger value from the children)
* @param index index of the element to be deleted
* @return value that is removed
*/
public int delete(int index){
if(isEmpty())
throw new IndexOutOfBoundsException("Heap is empty");
int parent = getParent(index);
int deletedValue = heap[index];
heap[index] = heap[size - 1];
//heap[size - 1] = 0;//might not be needed
if(index == 0 || heap[index] < heap[parent]){
fixHeapBelow(index, size - 1);
}else {
fixHeapAbove((index));
}
size--;
return deletedValue;
}
/**
* For max heap the root is the largest elemnt
* Swap root with last element in the array
* heapify the tree exclude the ;ast element. after heapify the second largest element will be at the root.
* rinse and repeat
*/
public void sort(){
int lastHeapIndex = size -1;
for (int i = 0; i < lastHeapIndex; i++) {
int temp = heap[0];
heap[0] = heap[lastHeapIndex - i];
heap[lastHeapIndex - i] = temp;
fixHeapBelow(0, lastHeapIndex - i -1);
}
}
public int peek(){
if(isEmpty())
throw new IndexOutOfBoundsException("Heap is empty");
return heap[0];
}
private void fixHeapAbove(int index){
int newValue = heap[index];
while(index > 0 && newValue > heap[getParent(index)]){
heap[index] = heap[getParent(index)];
index = getParent(index);
}
heap[index] = newValue;
}
private void fixHeapBelow(int index, int lastHeapIndex){
int childToSwap;
while (index <= lastHeapIndex) {
int leftChild = getChild(index, true);
int rightChild = getChild(index, false);
if (leftChild <= lastHeapIndex) {
if (rightChild > lastHeapIndex) {
childToSwap = leftChild;
}
else {
childToSwap = (heap[leftChild] > heap[rightChild] ? leftChild : rightChild);
}
if (heap[index] < heap[childToSwap]) {
int tmp = heap[index];
heap[index] = heap[childToSwap];
heap[childToSwap] = tmp;
}
else {
break;
}
index = childToSwap;
}
else {
break;
}
}
}
public boolean isFull(){
return size == heap.length;
}
public int getParent(int index){
return (index - 1) / 2;
}
public boolean isEmpty(){
return size == 0;
}
public int getChild(int index, boolean left){
return 2 * index + (left ? 1 : 2);
}
public void printHeap() {
for (int i = 0; i < size; i++) {
System.out.print(heap[i]);
System.out.print(", ");
}
System.out.println();
}
public static void main(String[] args) {
Heap heap = new Heap(10);
heap.insert(80);
heap.insert(75);
heap.insert(60);
heap.insert(68);
heap.insert(55);
heap.insert(40);
heap.insert(52);
heap.insert(67);
/*heap.printHeap();
heap.delete(0);
heap.printHeap();*/
heap.sort();
heap.printHeap();
System.out.println(heap.peek());
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(25);
pq.offer(-22);
System.out.println(pq.peek());
System.out.println(pq.remove());
System.out.println(pq.poll());
}
}
|
Java | UTF-8 | 1,157 | 2.171875 | 2 | [] | no_license | package besttelecomspring.repository;
import besttelecomspring.domain.Mark;
import besttelecomspring.domain.Product;
import besttelecomspring.domain.Type;
import java.util.List;
import java.util.Optional;
public interface ProductRepository {
Product addProduct(Product product);
List<Type> getTypeList();
List<Mark> getMarkList();
Mark addMark(Mark mark);
Type addType(Type type);
long getTypeId(String typeName);
long getMarkId(String markName);
List<Product> getProductFilteredList(int start, int length, String query);
Optional<Product> getProductById(long id);
int getProductFilteredListCount(String query);
Product deleteProduct(Product product);
Product editProduct(Product product);
Mark editMark(Mark mark);
Type editType(Type type);
int getProductCount();
List<Product> getProductType();
List<Product> getProductMark();
List<Product> getProductList();
List<Product> getProductListByType(String type);
List<Product> getProductListByMark(String mark);
long getMaxPrice();
List<Product> getProductListByPrice(long price1, long price2);
}
|
PHP | UTF-8 | 960 | 2.515625 | 3 | [] | no_license | <?php declare(strict_types=1);
/**
* This file is part of AsyncVerimail.
*
* Copyright (c) 2020 Balovnev Anton <an43.bal@gmail.com>
*/
namespace App\Throttling;
use Closure;
use React\EventLoop\LoopInterface;
use React\Stream\ReadableStreamInterface;
class Factory
{
private LoopInterface $eventLoop;
public function __construct(LoopInterface $eventLoop)
{
$this->eventLoop = $eventLoop;
}
public function closure(Closure $closure, float $minIntervalSeconds): ClosureWrapper
{
return new ClosureWrapper($closure, $this->eventLoop, $minIntervalSeconds);
}
public function readableStream(
ReadableStreamInterface $innerStream,
float $minIntervalSeconds,
int $bufferSize = 1
): ThrottlingReadStreamWrapper {
return new ThrottlingReadStreamWrapper($innerStream, $this, [
'minIntervalSeconds' => $minIntervalSeconds,
'bufferSize' => $bufferSize,
]);
}
}
|
Java | UTF-8 | 5,730 | 2.1875 | 2 | [] | no_license | package com.example.adriana.news;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import static com.example.adriana.news.MainActivity.PUBLICATION_DATE;
import static com.example.adriana.news.MainActivity.RESPONSE;
import static com.example.adriana.news.MainActivity.RESULTS;
import static com.example.adriana.news.MainActivity.SECTION_NAME;
import static com.example.adriana.news.MainActivity.WEB_PUBLICATION_DATE;
import static com.example.adriana.news.MainActivity.WEB_TITLE;
import static com.example.adriana.news.MainActivity.WEB_URL;
/**
* Created by Adriana on 7/21/2018.
*/
public final class QueryUtils {
public static final String TAGS = "tags";
public static final String DEFAULT_VALUE_AUTHOR_NAME = "no author found";
public static final String REQUEST_METHOD = "GET";
public static final int SUCCESS_RESPONSE = 200;
public static final int READ_TIMEOUT = 10000;
public static final int CONNECT_TIMEOUT = 15000;
public static List<News> fetchNewsData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
e.printStackTrace();
}
List<News> newsList = extractFeatureFromJson(jsonResponse);
return newsList;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = ( HttpURLConnection ) url.openConnection();
urlConnection.setReadTimeout(READ_TIMEOUT /* milliseconds */);
urlConnection.setConnectTimeout(CONNECT_TIMEOUT /* milliseconds */);
urlConnection.setRequestMethod(REQUEST_METHOD);
urlConnection.connect();
if (urlConnection.getResponseCode() == SUCCESS_RESPONSE) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e("", "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<News> extractFeatureFromJson(String newsJSONResponse) {
if (TextUtils.isEmpty(newsJSONResponse)) {
return null;
}
List<News> newsList = new ArrayList<>();
try {
JSONObject response = new JSONObject(newsJSONResponse);
JSONObject responseJSONObject = response.getJSONObject(RESPONSE);
JSONArray results = responseJSONObject.getJSONArray(RESULTS);
for (int i = 0; i < results.length(); i++) {
JSONObject firstResultJSONObject = results.getJSONObject(i);
String title = firstResultJSONObject.getString(WEB_TITLE);
String date = "";
if (firstResultJSONObject.getString(PUBLICATION_DATE) != null)
date = firstResultJSONObject.getString(WEB_PUBLICATION_DATE);
String webUrl = firstResultJSONObject.getString(WEB_URL);
String topic = firstResultJSONObject.getString(SECTION_NAME);
String author = DEFAULT_VALUE_AUTHOR_NAME;
if (firstResultJSONObject.has(TAGS)) {
JSONArray tagsJSONArray = firstResultJSONObject.getJSONArray(TAGS);
if (tagsJSONArray != null) {
if (tagsJSONArray.length() > 0) {
JSONObject tagsJSONObject = tagsJSONArray.getJSONObject(0);
if (tagsJSONObject != null)
if (tagsJSONObject.has(WEB_TITLE))
author = tagsJSONObject.getString(WEB_TITLE);
}
}
}
News news = new News(title, author, date, topic, webUrl);
newsList.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
return newsList;
}
}
|
Java | UTF-8 | 7,827 | 2.359375 | 2 | [] | no_license | package com.spw.elife.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
/**
* 中华车险配置解析excel
* @author Administrator
*
*/
public class GetSQL {
private Logger log = Logger.getLogger(GetSQL.class);
@SuppressWarnings("static-access")
public String getValue(XSSFCell xssfRow) {
if(xssfRow==null){
return "";
}
if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfRow.getBooleanCellValue());
} else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
short format = xssfRow.getCellStyle().getDataFormat();
SimpleDateFormat sdf = null;
if(HSSFDateUtil.isCellDateFormatted(xssfRow)||format == 14 || format == 31 || format == 57 || format == 58){
sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = xssfRow.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
return sdf.format(date);
}
BigDecimal bd = new BigDecimal(xssfRow.getNumericCellValue());
return bd.toPlainString();
} else if(xssfRow.getCellType() == xssfRow.CELL_TYPE_BLANK ||xssfRow.getCellType() == xssfRow.CELL_TYPE_ERROR){
return "";
} else if(xssfRow.getCellType() == xssfRow.CELL_TYPE_FORMULA){
Workbook wb = xssfRow.getSheet().getWorkbook();
CreationHelper crateHelper = wb.getCreationHelper();
FormulaEvaluator evaluator = crateHelper.createFormulaEvaluator();
return getValue((XSSFCell)evaluator.evaluateInCell(xssfRow));
} else {
return String.valueOf(xssfRow.getStringCellValue()).trim();
}
}
/**
* Read the Excel 2003-2007
* @param path the path of the Excel
* @return
* @throws IOException
*/
public List<Staff> readXls(String path) throws IOException {
InputStream is = new FileInputStream(path);
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
Staff staff = null;
List<Staff> list = new ArrayList<Staff>();
for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
XSSFSheet hssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
XSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null && StringUtils.isNotBlank(getValue(hssfRow.getCell(0)))) {
staff = new Staff();
XSSFCell name = hssfRow.getCell(0);
XSSFCell idCard = hssfRow.getCell(1);
XSSFCell dxq = hssfRow.getCell(2);
staff.setName(getValue(name));
staff.setIdCard(getValue(idCard));
staff.setDxq(getValue(dxq));
list.add(staff);
}
}
}
return list;
}
class Staff {
private String name;
private String idCard;
private String fgs;
private String dxq;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getFgs() {
return fgs;
}
public void setFgs(String fgs) {
this.fgs = fgs;
}
public String getDxq() {
return dxq;
}
public void setDxq(String dxq) {
this.dxq = dxq;
}
}
public Properties getProp(){
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("configuration.properties");
Properties p = new Properties();
try {
p.load(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
}
return p;
}
public GetSQL() {
try {
List<Staff> list = readXls("D:/离职人员信息.xlsx");
String DB_URL = getProp().getProperty("jdbc.url");
String USER = getProp().getProperty("jdbc.username");
String PASS = getProp().getProperty("jdbc.password");
Connection conn = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
conn.setAutoCommit(false);
stmt = (Statement) conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
List<String> lists = new ArrayList<>();
for(int i = 0; i < list.size();i++){
String id = null;
String name = null;
String status =null;
String personType = null;
String phone_num = null;
stmt = (Statement) conn.createStatement();
String sql = "SELECT s.status from ms_staff s LEFT JOIN organization o on s.countyFranchisees_id = o.id ";
sql += "LEFT JOIN organization f on s.store_id = f.id where s.name = '"+list.get(i).getName()+"'";
sql += " or (s.name ='"+list.get(i).getName()+"' and o.name ='"+list.get(i).getIdCard()+"' )";
sql += " or (s.name ='"+list.get(i).getName()+"' and f.name ='"+list.get(i).getDxq()+"' )";
// String sql = "SELECT f.name from ms_staff_apply s LEFT JOIN ms_staff f on f.id = s.refer_id where s.name = '"+list.get(i).getName()+"' "
// + "and s.id_card ='"+list.get(i).getIdCard()+"'";
ResultSet rs = stmt.executeQuery(sql);
// rs.last(); //移到最后一行
// int rowCount = rs.getRow(); //得到当前行号,也就是记录数
// rs.beforeFirst(); //如果还要用结果集,就把指针再移到初始化的位置
// if(rowCount==1 && rs.next()){
if(rs.next()){
id = rs.getString(1);
// System.out.println("订单号:"+name+"状态:"+status+"人员类型:"+personType+"手机号:"+phone_num);
}
// System.out.println("--------------------");
// if(id!=null || id.contains(list.get(i).getDxq())){
if("0".equals(id)){
log.info(list.get(i).getName()+"-xxxxxxxxx-"+id);
}else{
// log.info(list.get(i).getName()+"-xxxxxxxxx-"+id);
}
// if(id!=null){
// String sql2 = "update ms_staff set work_num = '"+workNum+"' where id = '"+id+"'";
// System.out.println(sql2+";");
//
// }else{
// log.info(list.get(i).getName()+"-xxxxxxxxx-"+list.get(i).getIdCard());
// }
// stmt.execute(sql2);
}
conn.commit();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args){
new GetSQL();
}
} |
Java | UTF-8 | 336 | 1.546875 | 2 | [] | no_license | package com.shgx.subbus.subbusone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SubbusoneApplication {
public static void main(String[] args) {
SpringApplication.run(SubbusoneApplication.class, args);
}
}
|
Java | GB18030 | 900 | 2.140625 | 2 | [] | no_license | package cn.edu.cust.srvs;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.edu.cust.dao.DaoSupport;
import cn.edu.cust.util.Info;
@Service("/agencySrv")
public class AgencySrv {
@Resource(name="daoSupport")
private DaoSupport dao;
/**
* ѯ
* @param map jigouJuese Żɫʶ
* @return
* @throws Exception
*/
public Map queryAgencySrv(Map map) throws Exception{
Map reMap = new HashMap();
List list = dao.findList("agencyMapper.queryAgency", map);
if(list.size()>0){//ѯн,Ϣ
reMap.put("agencyResultInfo", Info.SUCCESS);
reMap.put("agencyList", list);
reMap.put("agencyListSize",list.size());
}else{//ѯûн
reMap.put("agencyResultInfo", Info.NO_RESULT);
}
return reMap;
}
}
|
Java | UTF-8 | 1,362 | 3.296875 | 3 | [
"Apache-2.0"
] | permissive | package rui.coder.algorithms.algs4.第一章_基础.a_第一节_基础编程模型.a_答疑;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class IntegerOverflowTest {
@Test
void abs() {
assertEquals(-2147483648,Math.abs(-2147483648));
System.out.println("Math.abs 是取这个值的绝对值");
System.out.println("因为最大值为2147483647,而绝对值为2147483648已经溢出,+1后变为最小值");
}
@Test
void maxInteger() {
int i= (int) (Math.pow(2,31)-2);
System.out.println(i+" 这个是int 类型内的值");
i= (int) (Math.pow(2,31)-1);
System.out.println(i+" 临界");
i= (int) (Math.pow(2,31));
System.out.println(i+" 超过了,损失精度");
i= (int) (Math.pow(2,31)+1);
System.out.println(i+ "超过了,损失精度");
}
@Test
void name() {
System.out.println(Integer.toBinaryString(-1));
}
@Test
@DisplayName("无符号右移:低位溢出,高位补0")
void unsignedRightShift(){
System.out.println(Integer.toBinaryString(-1));
assertEquals(Integer.MAX_VALUE,-1>>>1);
System.out.println(Integer.toBinaryString(Integer.MAX_VALUE));
System.out.println(-1>>>31);
}
} |
Python | UTF-8 | 1,189 | 2.5625 | 3 | [
"MIT"
] | permissive | import sys
import os
import time
import socket
import random
import time
import main
class portchange:
def attack(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
bytes = random._urandom(1490)
main.Hasky.clear(self)
print(os.system("figlet 'Port Change DDOS' -f digital -c"))
ip = input(main.color.GREEN + "IP Target : ")
port = int(input("Port : "))
main.Hasky.clear(self)
print(os.system("figlet 'Attack Start' -f digital -c"))
sent = 0
while True:
try:
sock.sendto(bytes, (ip,port))
sent = sent + 1
port = port + 1
print (main.color.RED + "Sent {0} packet to {1} throught port:{2}".format(sent,ip,int(port)))
if port == 65534:
port = 1
except KeyboardInterrupt:
print(main.color.CYAN + " [-] keyboard Intrupt ")
time.sleep(15)
main.Hasky.spot(self)
except Exception:
print(main.color.GREEN + " Server Error :")
if __name__ == "__main__":
poatt = portchange()
poatt.attack() |
Python | UTF-8 | 1,433 | 2.96875 | 3 | [] | no_license | # Problem from UVA
# https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2498
parent = dict()
ranks = dict()
members = dict()
def make_set():
global parent, ranks, members
parent = dict()
ranks = dict()
members = dict()
def find_set(u):
if parent.get(u) is not None and parent[u] is not u:
parent[u] = find_set(parent[u])
else:
parent[u] = u
return parent[u]
def union_set(u, v):
up = find_set(u)
vp = find_set(v)
if ranks.get(up) is None:
ranks[up] = 1
if ranks.get(vp) is None:
ranks[vp] = 1
if members.get(up) is None:
members[up] = 1
if members.get(vp) is None:
members[vp] = 1
if up == vp:
return members[vp]
if ranks[up] > ranks[vp]:
parent[vp] = up
members[up] = members[up] + members[vp]
return members[up]
elif ranks[up] < ranks[vp]:
parent[up] = vp
members[vp] = members[vp] + members[up]
return members[vp]
else:
parent[up] = vp
ranks[vp] += 1
members[vp] = members[vp] + members[up]
return members[vp]
def solution():
T = int(input())
for t in range(T):
F = int(input())
make_set()
for i in range(F):
u, v = map(str, input().split())
current_members = union_set(u, v)
print(current_members)
solution()
|
C++ | UTF-8 | 3,048 | 2.90625 | 3 | [] | no_license | #include "trackIMU.h"
namespace rgbd
{
imuTrack::imuTrack()
{
theta = glm::vec3(0);
}
imuTrack::~imuTrack()
{
}
void imuTrack::processGyro(k4a_imu_sample_t imuValues) {
if (first) // On the first iteration, use only data from accelerometer to set the camera's initial position
{
last_ts_gyro = imuValues.gyro_timestamp_usec;
return;
}
// Holds the change in angle, as calculated from gyro
glm::vec3 gyro_angle;
// Initialize gyro_angle with data from gyro
gyro_angle.z = -imuValues.gyro_sample.xyz.x; // Pitch
gyro_angle.x = -imuValues.gyro_sample.xyz.y; // Yaw
gyro_angle.y = imuValues.gyro_sample.xyz.z; // Roll
// Compute the difference between arrival times of previous and current gyro frames
double dt_gyro = (imuValues.gyro_timestamp_usec - last_ts_gyro) / 1000000.0;
last_ts_gyro = imuValues.gyro_timestamp_usec;
// Change in angle equals gyro measures * time passed since last measurement
gyro_angle = gyro_angle * dt_gyro;
// Apply the calculated change of angle to the current angle (theta)
std::lock_guard<std::mutex> lock(theta_mtx);
theta += glm::vec3(-gyro_angle.z, -gyro_angle.y, gyro_angle.x);
}
void imuTrack::processAccel(k4a_imu_sample_t imuValues) {
// Holds the angle as calculated from accelerometer data
glm::vec3 accel_angle;
// Calculate rotation angle from accelerometer data
accel_angle.z = atan2(imuValues.acc_sample.xyz.z, -imuValues.acc_sample.xyz.x);
accel_angle.x = atan2(-imuValues.acc_sample.xyz.y, sqrt(imuValues.acc_sample.xyz.z * imuValues.acc_sample.xyz.z + imuValues.acc_sample.xyz.x * imuValues.acc_sample.xyz.x));
// If it is the first iteration, set initial pose of camera according to accelerometer data (note the different handling for Y axis)
std::lock_guard<std::mutex> lock(theta_mtx);
if (first)
{
first = false;
theta = accel_angle;
// Since we can't infer the angle around Y axis using accelerometer data, we'll use PI as a convetion for the initial pose
theta.y = 3.14159265358979323846;
}
else
{
/*
Apply Complementary Filter:
- high-pass filter = theta * alpha: allows short-duration signals to pass through while filtering out signals
that are steady over time, is used to cancel out drift.
- low-pass filter = accel * (1- alpha): lets through long term changes, filtering out short term fluctuations
*/
theta.x = theta.x * alpha + accel_angle.x * (1 - alpha);
theta.z = theta.z * alpha + accel_angle.z * (1 - alpha);
}
}
glm::vec3 imuTrack::getTheta() {
std::lock_guard<std::mutex> lock(theta_mtx);
return theta;
}
void imuTrack::setTheta() {
theta = glm::vec3(0);
first = true;
}
} |
C++ | UTF-8 | 514 | 2.546875 | 3 | [] | no_license | #include "Headers/includes.hpp"
#include "Headers/window.h"
Window::Window(QWidget *parent): QWidget(parent=0)
{
grid = new QGridLayout(this);
grid->setOriginCorner(Qt::TopLeftCorner);
setLayout(grid);
}
void Window::addWidgetWindow(QWidget *widget, int x, int y, int dx, int dy){
if (dx != 0 && dy != 0){
grid->addWidget(widget,x,y,dx,dy);
}else{
grid->addWidget(widget,x,y);
}
}
void Window::resizeEvent(QResizeEvent *event){
emit size_changed(event->size().width(), event->size().height());
}
|
C++ | UTF-8 | 434 | 2.625 | 3 | [] | no_license | #include <bits/stdc++.h>
struct pe{
long long a, b, c;
}p[100005];
bool cmp(const pe &a, const pe &b){
return a.c<b.c;
}
int main(){
int n;
long long k1, k2, sum=1;
std::cin>>n>>k1>>k2;
for(int i=0;i<n;i++){
std::cin>>p[i].a>>p[i].b;
p[i].c=p[i].a*p[i].b;
}
std::sort(p, p+n, cmp);
for(int i=0;i<n-1;i++){
sum*=p[i].a;
if(p[i].a!=1){
std::cout<<p[i].a<<' '<<sum<<std::endl;
}
}
std::cout<<sum*k1/p[n-1].b;
}
|
Java | UTF-8 | 3,608 | 2.25 | 2 | [] | no_license | package com.wlyu.bubbles;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wlyu.bubbles.PullToRefreshListView.OnRefreshListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class HelloBubblesActivity extends Activity {
private com.wlyu.bubbles.DiscussArrayAdapter adapter;
private PullToRefreshListView lv;
private EditText editText1;
private Button buttonSend;
Bitmap imageLeft;
Bitmap imageRight;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discuss);
imageLeft=BitmapFactory.decodeStream(getResources().openRawResource(R.raw.left));
imageRight=BitmapFactory.decodeStream(getResources().openRawResource(R.raw.right));
lv = (PullToRefreshListView) findViewById(R.id.listView1);
lv.setOnRefreshListener(new OnRefreshListener(){
public void onRefresh() {
addItems();
}
});
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.listitem_discuss);
lv.setAdapter(adapter);
editText1 = (EditText) findViewById(R.id.editText1);
buttonSend=(Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
int count=adapter.getCount();
adapter.add(count, new OneComment(false, editText1.getText().toString(), imageRight, new HashMap<String, String>()));
lv.setSelection(count);
editText1.setText("");
}
});
addItems();
}
private void addItems() {
String url="https://bubble-chat.appspot.com/bubblechat1";
message.clear();
new DownloadFilesTask().execute(url, null, null);
}
ArrayList<Message> message=new ArrayList<Message>();
private class DownloadFilesTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(urls[0]));
content = response.getEntity().getContent();
} catch (Exception e) {
System.out.println(e.getMessage());
}
Gson gson = new Gson();
Reader reader=new InputStreamReader(content);
Type type = new TypeToken<Collection<Message>>(){}.getType();
message=gson.fromJson(reader, type);
return "";
}
protected void onProgressUpdate(Void... progress) {
}
protected void onPostExecute(String result) {
for(Message msg:message){
if(msg.left)
adapter.add(new OneComment(msg.left, msg.text, imageLeft, msg.pictures));
else
adapter.add(new OneComment(msg.left, msg.text, imageRight, msg.pictures));
}
lv.onRefreshComplete();
lv.setSelection(message.size()-1);
super.onPostExecute(result);
}
}
} |
Java | UTF-8 | 2,616 | 1.9375 | 2 | [] | no_license | package com.erzihutama.erzihutamaapps.View.profil;
import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.erzihutama.erzihutamaapps.R;
// Tanggal Pengerjaan : 5 mei 2019
// NIM : 10116479
// Nama : ERZI HUTAMA DWIRAMA PUTRA
// Kelas : AKB 11
public class AboutFragment extends Fragment {
Dialog myDialog;
Button btnFollow ;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View myFragmentView = inflater.inflate(R.layout.fragment_about, container, false);
Button dialogAbout = (Button)myFragmentView.findViewById(R.id.popup);
dialogAbout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getActivity());
dialog.setCancelable(true);
View view = getActivity().getLayoutInflater().inflate(R.layout.custompopup,null);
dialog.setContentView(view);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setTitle("ABOUT");
Button button = (Button)dialog.findViewById(R.id.btnclose);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
return myFragmentView;
}
// public void ShowPopup(View v) {
//
// Button btnFollow;
// myDialog.setContentView(R.layout.custompopup);
//
// btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
// btnFollow.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// myDialog.dismiss();
// }
// });
// myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// myDialog.show();
// }
}
|
JavaScript | UTF-8 | 1,401 | 2.578125 | 3 | [
"MIT"
] | permissive | 'use strict';
const R = require('ramda'),
__ = require('./_private.js');
const isNumberBetween = R.curry((min, max, n) => {
return R.is(Number, n) && n > min && n < max;
});
const isNumberBetweenInclusive = R.curry((min, max, n) => {
return R.is(Number, n) && n >= min && n <= max;
});
const numberIsOneOf = R.curry((selectionArr, num) => {
return R.allPass([R.is(Number), R.includes(R.__, selectionArr)])(num);
});
const isNumber = R.is(Number),
isPositiveNumber = R.allPass([isNumber, R.gt(R.__, 0)]),
isAtLeastZero = R.allPass([isNumber, R.gte(R.__, 0)]),
isNegativeNumber = R.allPass([isNumber, R.lt(R.__, 0)]),
isAtMostZero = R.allPass([isNumber, R.lte(R.__, 0)]),
isCalendarMonth = isNumberBetweenInclusive(1, 12),
isCalendarMonthZeroBased = isNumberBetweenInclusive(0, 11),
isEvenNumber = __.modTwoEq(0),
isOddNumber = __.modTwoEq(1),
isNumeric = v => !isNaN(parseInt(v, 10)),
isNumericBoolean = R.includes(R.__, [0, 1]);
module.exports = {
isNumber,
isNumberBetween,
isNumberBetweenInclusive,
isPositiveNumber,
isNegativeNumber,
isEvenNumber,
isOddNumber,
isAtLeastZero,
isAtMostZero,
isCalendarMonth,
isCalendarMonthZeroBased,
numberIsOneOf,
isNumeric,
isNumericBoolean
};
|
C | UTF-8 | 355 | 3.625 | 4 | [] | no_license | #include<stdio.h>
int main() {
int x; //入力される秒数
int a, b, c; //時間
//入力
printf("秒数を入力→ ");
scanf("%d", &x);
//処理
a = x / 3600;
b = x % 3600 / 60;
c = x % 3600 % 60;
//出力
printf("時, 分, 秒 = %d, %d, %d\n", a, b, c);//h, m, s
return 0;
}
|
Markdown | UTF-8 | 5,621 | 2.765625 | 3 | [] | no_license | +++
titre = "<em>Snatch, tu braques ou tu raques</em>, Guy Ritchie"
title = "Snatch, tu braques ou tu raques, Guy Ritchie"
url = "/snatch-braques-raques-ritchie"
date = "2015-08-02T18:43:41"
Lastmod = "2015-08-02T18:49:26"
cover = "https://voiretmanger.fr/wp-content/2015/08/snatch-brad-pitt.jpg"
categorie = [ "À voir" ]
tag = [ "Boxe", "Comédie", "Film de gangsters", "Humour", "Mafia", "Thriller" ]
createur = [ "Guy Ritchie" ]
acteur = [ "Alan Ford", "Benicio Del Toro", "Brad Pitt", "Dennis Farina", "Rade Serbedzija", "Stephen Graham", "Vinnie Jones" ]
annee = [ "2000" ]
weight = 2000
pays = [ "États-Unis", "Royaume-Uni" ]
+++
<p>Le deuxième long-métrage de Guy Ritchie appartient à la grande famille des films de gangsters. <em>Snatch, tu braques ou tu raques</em><sup id="fnref-14060-1"><a href="#fn-14060-1" rel="footnote">1</a></sup> n’est pas un film de gangsters très sérieux. Dans un esprit assez similaire à <em>Arnaques, Crimes et Botanique</em>, son premier film, c’est une comédie qui rassemble les pires malfrats qui soient, une bande de bras-cassés qui ne parvient jamais à rien. L’ensemble forme une sorte de thriller vraiment amusant, porté par quelques acteurs en grande forme. Quinze ans après sa sortie, <em>Snatch, tu braques ou tu raques</em> n’a pas vieilli et reste une excellente comédie, à (re)voir !</p>
<a href="http://www.allocine.fr/film/fichefilm_gen_cfilm=26251.html"><img class="aligncenter" src="https://voiretmanger.fr/wp-content/2015/08/snatch-braques-raques-ritchie.jpg" alt="Snatch braques raques ritchie" title="snatch-braques-raques-ritchie.jpg" width="2065" height="3000" /></a>
<p>Deux histoires se mêlent et s’entremêlent dans <em>Snatch, tu braques ou tu raques</em> pour former une intrigue particulièrement complexe à résumer. Mais au fond, elles ne sont pas si essentielles que ça et il suffit de dire que l’on baigne au cœur de la mafia. Il y a des matchs de boxe organisés illégalement et qui sont évidemment truqués, il y a d’énormes diamants volés, des braquages, pas mal de castagne et même quelques morts. Guy Ritchie pourrait dresser un portrait inquiétant de ce milieu, mais on comprend très vite que tous ces hommes ne sont pas vraiment faits pour la mafia. Il n’y en a pas un pour rattraper l’autre et tous les personnages du film sont plus ridicules que vraiment dangereux. Quelques scènes sont ainsi très drôles, à commencer par le braquage d’un centre qui recueille les paris par deux petites frappes embauchées par un Russe. La scène tourne vite au fiasco, rien ne se passe comme prévu et l’ensemble n’est vraiment pas très sérieux. <em>Snatch, tu braques ou tu raques</em> appartient ainsi beaucoup plus à la comédie qu’au thriller sérieux et le film est souvent très drôle, avec quelques trouvailles, à l’image du chien qui avale un cochon en plastique qui couine. Guy Ritchie se moque gentiment de tous ses personnages, même s’il y en a aussi quelques-uns de plus sérieux dans le lot. L’écriture et la mise en scène rappellent par moments le travail de Quentin Tarantino, on retrouve cette même tendance à l’absurde, mais aussi un travail d’écriture très précis pour les dialogues. Les répliques cultes ne manquent pas dans <em>Snatch, tu braques ou tu raques</em> et plusieurs séquences savoureuses sont liées à des discussions entre les personnages. À cet égard, on pense aussi aux réalisations des frères Coen, avec ce même sens de l’absurde et ces mêmes personnages supposés gangsters et en fait surtout ridicules.</p>
<img class="aligncenter" src="https://voiretmanger.fr/wp-content/2015/08/snatch-ade-robbie-gee-lennie-james.jpg" alt="Snatch ade robbie gee lennie james" title="snatch-ade-robbie-gee-lennie-james.jpg" width="2100" height="1400" />
<p>Le casting réuni par Guy Ritchie contribue aussi à la réussite de <em>Snatch, tu braques ou tu raques</em>. De Brad Pitt, parfait en boxeur gitan, jusqu’à Alan Ford qui excelle en parrain éleveur de cochons, en passant par un Jason Statham moins boudin qu’à l’accoutumée, les acteurs sont tous très bons et on rigole de bon cœur souvent grâce à leurs interprétations. Ajoutons à cela une bande originale éclectique et toujours de bon goût et on obtient une comédie très amusante. Certes, le cinéaste exploite déjà bien son style un petit peu outrancier, mais on l’oublie facilement dans <em>Snatch, tu braques ou tu raques</em>, sans doute grâce aux acteurs, aussi par le scénario finement écrit. Le bilan est excellent, on en redemande !</p>
<div class="amazon">
<h3>Vous voulez <a href="https://voiretmanger.fr/soutien/">m’aider</a> ?</h3>
<ul>
<li><a href="http://www.amazon.fr/gp/product/B002L7TMOK/ref=as_li_ss_tl?ie=UTF8&tag=leblogdenic07-21&linkCode=as2&camp=1642&creative=19458&creativeASIN=B002L7TMOK">Acheter le film en Blu-ray sur Amazon</a></li>
<li><a href="http://www.amazon.fr/gp/product/B00008GRAS/ref=as_li_ss_tl?ie=UTF8&tag=leblogdenic07-21&linkCode=as2&camp=1642&creative=19458&creativeASIN=B00008GRAS">Acheter le film en DVD sur Amazon</a></li>
<li><a href="https://itunes.apple.com/fr/movie/snatch/id542705952">Acheter ou louer le film sur l’iTunes Store</a></li>
<li><a href="http://www.netflix.com/title/60003388">Regarder le film sur Netflix</a></li>
</ul>
</div>
<div class="footnotes">
<hr />
<ol>
<li id="fn-14060-1">
Comment un tel titre français a pu être trouvé ? Le mystère reste entier… <a href="#fnref-14060-1" rev="footnote">↩</a>
</li>
</ol>
</div>
|
JavaScript | UTF-8 | 2,325 | 3.875 | 4 | [] | no_license |
const poem = `
The dogs are running.
The dogs are happy.
The owners are drunk.
No dogs survived.
`;
const sentenceStarterWords = [];
const createMarkovTable = text => {
const table = {};
let words = text.split(/[ ;\-\n]+/);
words = words.filter( word => word.length > 0 );
//
// words = words.filter( function(word){
// return word.length > 0;
// });
//
// const outputArray = [];
// for( let i = 0; i < words.length; i++ ){
// const word = words[i];
// if( word.length > 0 ){
// outputArray.push( word );
// }
// }
//
for( let i = 0; i < words.length - 1; i++ ){
const currentWord = words[i];
// Check if the current word is not already in the table:
if( !(currentWord in table) ){
table[currentWord] = []; // The first time we see this word, set its value to []
}
const nextWord = words[ i + 1 ]; // get the word that follows this word
table[currentWord].push( nextWord );
if( currentWord.match(/^[A-Z][a-z]/) ){
sentenceStarterWords.push( currentWord ); // keep track of sentence-starting (capitalized) words
}
} // for each word
return table;
};
const getRandomArrayElement = array => {
const randomIndex = Math.floor( Math.random() * array.length );
return array[ randomIndex ];
};
const generateMarkovText = (table, outputLength) => {
let currentWord = getRandomArrayElement( sentenceStarterWords );
let output = currentWord; // The first word we've chosen above is what starts the output
for( let i = 0; i < outputLength; i++ ){
// Pick a new following word for the output sentence by using the current
// word as an key into the table (object) of following words, and choosing
// a following word from that array, at random
currentWord = getRandomArrayElement( table[currentWord] );
// Add the new following word to the output string we are building up
output += ' ' + currentWord;
}
return output;
};
$.ajax('/bible.txt')
.done( data => {
console.log( data.length );
const markovTable = createMarkovTable( data );
// console.log( markovTable );
window.markov = markovTable; // save to a global variable for debugging
const newText = generateMarkovText( markovTable, 40 );
console.log(`%c${newText}`, 'font-size: 12pt; font-weight: bold');
});
|
Java | UTF-8 | 776 | 2.375 | 2 | [] | no_license | package com.alexandre.springmvc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class SpringmvcApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(SpringmvcApplication.class, args);
// System.out.println("***************** Beans *****************");
// System.out.println("Count: "+run.getBeanDefinitionCount());
// for(String name : run.getBeanDefinitionNames()){
// System.out.println(name);
// }
// System.out.println("***************** Finish beans *****************");
}
}
|
C++ | UTF-8 | 695 | 3.765625 | 4 | [] | no_license | #include <iostream>
#include <thread>
/*
* Compilation instructions
* $ g++ hello_world.cpp -std=c++0x -lpthread -o hello
* $ ./hello
*/
void add_2(int * temp)
{
*temp += 2;
return;
}
void divide_2(int * temp)
{
*temp /= 2;
return;
}
int main()
{
/*
* lambda expression:
* allows you to write local function,
* possibly capturing some local vars
* avoiding need to pass additional args
*/
std::thread my_thread([]{
int temp_var = 2;
add_2(&temp_var);
divide_2(&temp_var);
std::cout<< temp_var << "\n";
});
std::cout<< "Completed excution of main()\n";
// causes main() thread to wait for thread t
my_thread.join();
} |
Python | UTF-8 | 4,506 | 3.03125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | from enum import Enum
from math import sqrt
from test.lonestar.calculate_degree import calculate_degree
import numpy as np
from katana import do_all, do_all_operator
from katana.local import Graph, ReduceSum
class DegreeType(Enum):
IN = 1
OUT = 2
@do_all_operator()
def sum_degree_operator(
graph: Graph,
source_degree,
sum_source: ReduceSum[np.uint64],
destination_degree,
sum_destination: ReduceSum[np.uint64],
nid,
):
for edge in graph.out_edge_ids_for_node(nid):
sum_source.update(source_degree[nid])
dst = graph.out_edge_dst(edge)
sum_destination.update(destination_degree[dst])
def average_degree(graph: Graph, num_edges: int, source_degree, destination_degree):
"""
Calculate the average in or out degree for the source and destination nodes
Returns the result as a tuple in the form (average degree for source, average degree for destination)
"""
sum_source_degrees = ReduceSum[np.uint64](0)
sum_destination_degrees = ReduceSum[np.uint64](0)
do_all(
range(graph.num_nodes()),
sum_degree_operator(graph, source_degree, sum_source_degrees, destination_degree, sum_destination_degrees),
steal=True,
)
return (sum_source_degrees.reduce() / num_edges, sum_destination_degrees.reduce() / num_edges)
@do_all_operator()
def degree_assortativity_coefficient_operator(
graph: Graph,
source_degree,
source_average,
destination_degree,
destination_average,
product_of_dev: ReduceSum[float],
square_of_source_dev: ReduceSum[float],
square_of_destination_dev: ReduceSum[float],
nid,
):
# deviation of source node from average
source_dev = source_degree[nid] - source_average
for edge in graph.out_edge_ids_for_node(nid):
dst = graph.out_edge_dst(edge)
destination_dev = destination_degree[dst] - destination_average
product_of_dev.update(source_dev * destination_dev)
square_of_source_dev.update(source_dev * source_dev)
square_of_destination_dev.update(destination_dev * destination_dev)
def degree_assortativity_coefficient(
graph: Graph,
source_degree_type: DegreeType = DegreeType.OUT,
destination_degree_type: DegreeType = DegreeType.IN,
weight=None,
):
"""
Calculates and returns the degree assortativity of a given graph.
Paramaters:
* graph: the Graph to be analyzed
* source_degree_type: description of degree type to consider for the source node on an edge
expected values are DegreeType.IN or DegreeType.OUT
* destination_degree_type: description the degree type to consider for the destination node on an edge
expected values are DegreeType.IN or DegreeType.OUT
* weight (optional): edge property to use if using weighted degrees
"""
# get the tables associated with the degree types of the source and destination nodes
calculate_degree(graph, "temp_DegreeType.IN", "temp_DegreeType.OUT", weight)
source_degree = graph.get_node_property("temp_" + str(source_degree_type))
destination_degree = graph.get_node_property("temp_" + str(destination_degree_type))
try:
# Calculate the average in and out degrees of graph
# (with respect to number of edges, not number of nodes)
num_edges = graph.num_edges()
source_average, destination_average = average_degree(graph, num_edges, source_degree, destination_degree)
# Calculate the numerator (product of deviation from mean)
# and the factors of the denominator (square deviation from mean)
product_of_dev = ReduceSum[float](0)
square_of_source_dev = ReduceSum[float](0)
square_of_destination_dev = ReduceSum[float](0)
do_all(
range(graph.num_nodes()),
degree_assortativity_coefficient_operator(
graph,
source_degree,
source_average,
destination_degree,
destination_average,
product_of_dev,
square_of_source_dev,
square_of_destination_dev,
),
steal=True,
loop_name="degree assortativity coefficient calculation",
)
return product_of_dev.reduce() / sqrt(square_of_source_dev.reduce() * square_of_destination_dev.reduce())
finally:
graph.remove_node_property("temp_DegreeType.IN")
graph.remove_node_property("temp_DegreeType.OUT")
|
SQL | UTF-8 | 5,733 | 3.25 | 3 | [] | no_license | -- ------------------------------------------------------------------
-- Title: Extraction of treatments
-- Notes: This query extracts information about treatments that patients received during their ICU stay.
-- We can observed that treatments with the same name or same function were grouped.
-- For instance: 'Clopidogrel Bisulfate', 'Clopidogrel' -->> Clopidogrel_Bisulfate
-- ------------------------------------------------------------------
--- Step 1: extract treatments for each patient
drop view nstemi_treatments cascade;
create view nstemi_treatments as
select
ids.subject_id
,ids.hadm_id
,ids.icustay_id
,CASE WHEN pre.drug in ('Aspirin EC', 'Aspirin', 'Aspirin (Buffered)', 'Aspirin Desensitization (Angioedema)',
'aspirin', 'Aspirin (Rectal)') then '1' else '0' END as Aspirin
,CASE WHEN pre.drug in ('Clopidogrel Bisulfate', 'Clopidogrel') then '1' else '0' END as Clopidogrel_Bisulfate
,CASE WHEN pre.drug in ('Enoxaparin Sodium') then '1' else '0' END as Enoxaparin
,CASE WHEN pre.drug in ('Heparin_Sodium', 'Heparin', 'Heparin Flush CVL (100 units/ml)', 'Heparin Flush (10 units/ml)',
'Heparin (IABP)', 'Heparin Flush PICC (100 units/ml)', 'Heparin Flush (5000 Units/mL)',
'Heparin Flush (1000 units/mL)', 'Heparin Flush CRRT (5000 Units/mL)', 'Heparin Dwell (1000 Units/mL)',
'Heparin Flush (100 units/ml)', 'Heparin CRRT', 'Heparin Flush', 'HEPARIN', 'Heparin (CRRT Machine Priming)',
'Heparin Lock Flush', 'Heparin Flush Port (10units/ml)' ) then '1' else '0' END as Heparin
,CASE WHEN pre.drug in ('Nitroglycerin', 'Nitroglycerin SL', 'Nitroglycerin Ointment 2%',
'Nitroglycerin Oint. 2%', 'Nitroglycerin Patch', 'Isosorbide Dinitrate',
'Isosorbide Mononitrate', 'Isosorbide Mononitrate (Extended Release)') then '1' else '0' END as Oral_nitrates
,CASE WHEN pre.drug in ('Atorvastatin', 'Fluvastatin Sodium', 'Lescol',
'Pravastatin', 'Rosuvastatin Calcium' ) then '1' else '0' END as Statins
,CASE WHEN pre.drug in ('Tricor', 'Gemfibrozil') then '1' else '0' END as Fibrates
,CASE WHEN pre.drug in ('Acebutolol HCl', 'Atenolol', 'Metoprolol XL (Toprol XL)', 'Metoprolol Tartrate'
'Nadolol', 'Propranolol') then '1' else '0' END as Beta_blockers
,CASE WHEN pre.drug in ('Captopril', 'Enalapril Maleate', 'Lisinopril', 'Moexipril HCl',
'Quinapril', 'Ramipril', 'Trandolapril', 'Enalaprilat') then '1' else '0' END as ACE_inhibitors
,CASE WHEN pre.drug in ('irbesartan', 'Valsartan', 'Losartan Potassium') then '1' else '0' END as ARB
,CASE WHEN pre.drug in ('Chlorothiazide Sodium', 'Hydrochlorothiazide', 'Metolazone',
'Bumetanide', 'Furosemide', 'Torsemide', 'Amiloride HCl',
'Eplerenone', 'Spironolactone') then '1' else '0' END as diuretics
,CASE WHEN pre.drug in ('Amlodipine Besylate', 'Amlodipine', 'Diltiazem Extended-Release', 'Diltiazem'
'Felodipine', 'NiCARdipine IV', 'Nicardipine HCl IV', 'NIFEdipine CR'
'NIFEdipine', 'Verapamil', 'Verapamil HCl', 'Verapamil SR') then '1' else '0' END as calcium_antagonist
,CASE WHEN pre.drug in ('Amiodarone HCl', 'Amiodarone') then '1' else '0' END as Amiodarone
,CASE WHEN pre.drug in ('Digoxin') then '1' else '0' END as Digoxin
,CASE WHEN pre.drug in ('Dobutamine Hcl', 'DOBUTamine', 'Dobutamine', 'Dobutamine HCl') then '1' else '0' END as dobutamine
,CASE WHEN pre.drug in ('Dopamine HCl', 'DopAmine', 'DOPamine', 'Dopamine', 'Dopamine Hcl') then '1' else '0' END as dopamine
,CASE WHEN pre.drug in ('Metformin', 'MetFORMIN (Glucophage)', 'MetFORMIN XR (Glucophage XR)') then '1' else '0' END as oral_glucose_low_drugs
,CASE WHEN pre.drug in ('Insulin Glargine', 'Insulin Pump', 'Humulin-R Insulin', 'Insulin'
'Insulin Human Regular') then '1' else '0' END as Insulin
,CASE WHEN pre.drug in ('Potassium Chloride') then '1' else '0' END as Potassium_Chloride
,CASE WHEN pre.drug in ('Warfarin') then '1' else '0' END as Warfarin
,CASE WHEN pre.drug in ('Vancomycin HCl', 'Vancomycin', 'Vancomycin Enema', 'Vancomycin Oral Liquid') then '1' else '0' END as Vancomycin
from nstemi_ccu ids --- for stemi to use stemi_ccu
left join prescriptions pre
on ids.subject_id = pre.subject_id and ids.hadm_id = pre.hadm_id and ids.icustay_id = pre.icustay_id
where pre.startdate between ids.intime and ids.intime + interval '1' day ---- This is important: we only extracted treatments prescribed during the first 24 hours
and ids.los >1.0 ----length ICU stay > 24 hours
order by ids.subject_id;
--- Step 2: In order to have the same number of register for each clinical set (ej., demographic, complications, labs, etc); we crossed the table created
--- previously with the table nstemi_ccu. In this manner, we preserved the same number of record for all the clinical sets.
drop view treatments;
create view treatments as
select ids.subject_id
,ids.hadm_id
,ids.icustay_id
,pre.Aspirin
,pre.Clopidogrel_Bisulfate
,pre.Enoxaparin
,pre.Heparin
,pre.Oral_nitrates
,pre.Statins
,pre.Fibrates
,pre.Beta_blockers
,pre.ACE_inhibitors
,pre.ARB
,pre.diuretics
,pre.calcium_antagonist
,pre.Amiodarone
,pre.Digoxin
,pre.dobutamine
,pre.dopamine
,pre.oral_glucose_low_drugs
,pre.Insulin
,pre.Potassium_Chloride
,pre.Warfarin
,pre.Vancomycin
from nstemi_ccu ids --- for stemi to use stemi_ccu
left join nstemi_treatments pre
on ids.subject_id = pre.subject_id and ids.hadm_id = pre.hadm_id and ids.icustay_id = pre.icustay_id
where ids.los > 1.0
order by ids.subject_id;
\copy (SELECT * FROM treatments) to '/tmp/treatments.csv' CSV HEADER;
|
JavaScript | UTF-8 | 2,221 | 3.140625 | 3 | [] | no_license | /*
This has to be changed for different exercises.
Mainly the DOM Related parts - dealing with the model display
*/
class View extends ViewBase {
constructor(){
super(...arguments)
this.arrayBodyHelper = new Div ($ (ARRAY_BODY));
this.c = 0;
this.elementsByIndex = [ ];
}
// start up a new view
start () {
super.start.apply (this, arguments);
}
indexOf (element){
return this.elementsByIndex.indexOf (element);
}
findAtIndex (index) {
// TODO WE NEED AN ELEMENTS STACK
return this.elementsByIndex [index];
}
insertElementAtIndex (element, index){
this.elementsByIndex.splice (index, 0, element);
}
removeElementAtIndex (index){
this.elementsByIndex.splice (index, 1);
}
updateIndex (prevIndex, newIndex){
var element = this.findAtIndex (prevIndex);
this.removeElementAtIndex (prevIndex);
this.insertElementAtIndex (element, newIndex);
}
isElementOverModel () {
return true; // stuck within the div, so yeah
}
// draw an element within the model
drawWithinModel (element) {
this.displayElement (element, this.elementsByIndex.length);
}
displayElement (element, index){
var pos = this.arrayBodyHelper.fromOffset ({left: ELEMENT_X_SPACING * index + ELEMENT_X_START,
top: ELEMENT_Y_OFFSET
});
element.moveTo (pos);
this.insertElementAtIndex (element, index);
}
displayModel (m) {
// We have the Array Body div ...
// What we want is every element should be spaced at ELEMENT_X_SPACING
// So that element 0 is at ELEMENT_X_START,
// element 1 is at ELEMENT_X_START + ELEMENT_X_SPACING,
// element 2 is at ELEMENT_X_START + ELEMENT_X_SPACING*2,
// etc.
// Every element should be at ELEMENT_Y_OS from the top.
this.clear ();
m.each ((data,index)=>{
var newElem = this.addElement (data, {withinModel: false});
this.displayElement (newElem, index);
});
}
addElement (...args){
var newElem = super.addElement (...args);
if (newElem)
this.insertElementAtIndex (newElem, this.elementsByIndex.length);
return newElem;
}
}
|
Markdown | UTF-8 | 5,736 | 2.75 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: 2020《Paired Representation Learning for Event and Entity Coreference》
categories: [Note, Entity Coreference, Event Coreference]
description: 通过成对特征学习解决事件与实体同指
keywords: Joint Model,Cross-document,Coreference Resolution
mathjax: true
original: true
author: 黄琮程
authorurl: https://github.com/Ottohcc
---
> 2020《通过成对特征学习解决事件与实体同指》[(Paired Representation Learning for Event and Entity Coreference)](https://arxiv.org/pdf/2010.12808.pdf) 的阅读笔记
## 一、问题
本文研究了事件和实体的共指消解问题。共指消解通常被建模为二元分类问题,且一般分为如下两个步骤:首先,学习并得到每个(事件或实体)mention 的特征(向量),然后对每两个 mention 进行分类。其中,获取高质量的 mention 特征是至关重要的。作者认为前人的工作并没有获得强有力的 mention 特征,主要原因为以下两点:
+ 点方式(Point-wise)的特征学习
大多数的工作试图通过仅仅从每个独立事件句提取特征来学习 mention 向量。在判断是否同指时是以同指对的方式进行判断,而不是单个 mention,并且,在不同的上下文中,两个 mention 可以成为同指事件,也可能不同指。
+ 非结构化(Unstructured)的特征学习
事件 mention 会包含一些论元,大多数工作会将所有这些论元编码并拼接成一个向量,然后比较每对论元向量。用一个单一的拼接向量来表示论元,会让机器失去进行细粒度推理的机会,也不容易解释模型的预测。某些论元的不匹配可能是决定性的,或者比其他论元的不匹配更具决定性。例如,“四川省”与“神户”不匹配时,可以直接认定这两个事件是不同指的。
<div style="text-align: center;">
<img src="/images/blog/Paired-Representation-Learning-for-Event-and-Entity-Coreference-1.png" width="400px"/>
</div>
## 二、方案
为解决以上问题,本文提出如下方式。
### 成对特征学习
本文把每一对 mention 对而不是一个单一的 mention 作为特征学习的对象。
具体来说,本文将把两个事件句作为一个完整的序列,并将其输入到 RoBERTa 系统中。RoBERTa 将两句话中的每个 token(包括 mention span)在编码时就能够互相进行比较。作者认为这比在分别编码成一个向量之后比较两个 mention 的 token 要好。本文将这种**成对表示学习**应用于事件和实体同指消解任务。然后二元分类器将采用这对上下文化的 mention 中的每对论元信息判断最后结果。
### 模型
本文使用的是 gold 的事件句,并没有事件抽取这一步。
对于每一个事件句使用 SRL 模型(https://demo.allennlp.org/semantic-role-labeling/)去抽取预测论元包括施事者、受施者、地点、时间。
然后将两个事件句用 [SEP] 相隔,输入 RoBERTa,得到一对事件句的编码。
<div style="text-align: center;">
<img src="/images/blog/Paired-Representation-Learning-for-Event-and-Entity-Coreference-2.png" width="400px"/>
</div>
如图在得到事件对编码后,首先找到触发词的对应位置,将其词向量相加,压缩成一维后相拼接,得到一对触发词的表示。
$$v_t(i,j)=[v_t^i, v_t^j,v_t^i\circ v_t^j]$$
再找每个论元的位置,并将每个论元的词向量相加,压缩成一维。对于每一种论元,通过以下式子得到每对论元的表示 $$\rm {role} \in \{arg0, arg1, loc, time\}$$,再将上述得到的向量经过一个多层感知机($$\rm MLP_1$$)得到每对论元的表示$$a_{\mathrm {role}}(i,j)$$,之后再将上述的所有表示拼接起来,得到一对事件 mention 的最后表示 $$v(i,j)$$。
$$v_{\mathrm {role}}(i,j)=[v_{\mathrm {role}}^i, v_{\mathrm {role}}^j,v_{\mathrm {role}}^i\circ v_{\mathrm {role}}^j]$$
$$a_\mathrm{role}(i,j)=\mathrm{MLP}_1(v_\mathrm {role}(i,j))$$
$$v(i,j)=[v_t(i,j),a_{arg0},a_{arg1},a_{loc},a_{time}]$$
如果是实体同指,则 $$v(i,j)=v_t(i,j)$$。
<div style="text-align: center;">
<img src="/images/blog/Paired-Representation-Learning-for-Event-and-Entity-Coreference-3.png" width="400px"/>
</div>
如图,再将上一步中得到的事件 mention 对表示输入到 $$\mathrm {MLP}_2$$ 中,得到最后得到一个关于是否同指的二分类答案。
$$p(i,j)=\mathrm {MLP}_2(v(i,j))$$
## 三、结果及分析
### 跨文档(ECB+)
<div style="text-align: center;">
<img src="/images/blog/Paired-Representation-Learning-for-Event-and-Entity-Coreference-4.png" width="350px"/>
</div>
以上是 ECB+ 上的数据分布。对于 ECB+ 作者首先使用 SRL 系统对序列中的论元进行标注(训练时使用 gold 数据),然后使用 K-Means 算法对文章主题进行聚类(训练使用 gold topic),最后使用前文所描述的模型进行打分判断。
<div style="text-align: center;">
<img src="/images/blog/Paired-Representation-Learning-for-Event-and-Entity-Coreference-5.png" width="600px"/>
</div>
### 文档内(KBP)
<div style="text-align: center;">
<img src="/images/blog/Paired-Representation-Learning-for-Event-and-Entity-Coreference-6.png" width="350px"/>
</div>
以上是 KBP 语料库上的数据分布。在本实验中,事件 mention 使用的是 gold 的。也是先使用 SRL 系统对序列中的论元进行标注,然后对每篇文章中的每一对事件评分,然后得到结果。
<div style="text-align: center;">
<img src="/images/blog/Paired-Representation-Learning-for-Event-and-Entity-Coreference-7.png" width="550px"/>
</div>
|
C | UTF-8 | 1,162 | 2.703125 | 3 | [] | no_license | /*int path=0, i, j, k;
for(k=0; k<n; k++){
for(i=0; i<n; i++){
for(j=0; j<n; j++){
path+=m[i][k]*m[k][j];
}
}
}*/
#include<stdio.h>
int main(void)
{
int n;
int m[26][26],i,j,ed=0,nd=0,ad=0,aed=0;
int ch,ch1;
int path=0, k;
printf("enter:how many vertics: \n");
scanf("%d",&n);
printf("now enter your edges: \n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&m[i][j]);
}
}
for(i=0,ch=97;i<n;i++,ch++)
{
for(j=0,ch1=97;j<n;j++,ch1++)
{
if(m[i][j]!=0)
{
ed=ed+m[i][j];
if(m[i][j]>1)
{
ad=m[i][j]-1;
aed=aed+ad;
}
printf("%c is connected with %c in %d ways\n",ch,ch1,m[i][j]);
}
else
{
nd++;
}
}
}
for(k=0; k<n; k++){
for(i=0; i<n; i++){
for(j=0; j<n; j++){
path+=m[i][k]*m[k][j];
}
}
}
printf("Number of Total edges is %d\n",ed);
printf("number of total alternet edges is %d\n",aed);
printf("minimum %d edge are missing\n",nd);
}
|
Java | UTF-8 | 1,373 | 2.25 | 2 | [] | no_license | package tipqc.cite.techproject.magnacarta.iwatch.lawsearch.magnadatabase;
/**
* Created by Benjoe on 2/23/14.
*/
public class MagnaCartaTableDB {
String chapter = null;
String lawdescription = null;
String section = null;
String subsection = null;
String keywordtag = null;
String keywordeng = null;
public String getChapter(){
return chapter;
}
public void setChapter(String chapter){
this.chapter = chapter;
}
public String getLawdescription(){
return lawdescription;
}
public void setLawdescription(String lawdescription){
this.lawdescription = lawdescription;
}
public String getSection(){
return section;
}
public void setSection(String section){
this.section = section;
}
public String getSubsection(){
return subsection;
}
public void setSubsection(String subsection){
this.subsection = subsection;
}
public String getKeywordtag(){
return keywordtag;
}
public void setKeywordtag(String keywordtag){
this.keywordtag = keywordtag;
}
public String getKeywordeng(){
return keywordeng;
}
public void setKeywordeng(String keywordeng){
this.keywordeng = keywordeng;
}
}
|
Python | UTF-8 | 730 | 3.359375 | 3 | [
"MIT"
] | permissive | # Title: AMPPS_linker
# Author: Joseph Whittington
# Dependencies: python 2.7.*
# Description: This script links the directory it's in to AMPPS
# **run the program by typing "python linker.py with optional filepath"
import os
from sys import argv
def main(argv):
ampps_path = argv[1] if len(argv) > 1 else '/Applications/AMPPS/www'
try:
os.symlink(os.getcwd(), os.path.join(ampps_path ,os.path.basename(os.getcwd())))
except:
print('\nYour AMPPS root folder is not in the default location(/Applications/AMPPS/www)')
print('To use linker specify the path to current aamps root folder after the file name')
print('Ex: "python linker.py <ampps_path>"\n')
if __name__ == '__main__':
main(argv) |
Python | UTF-8 | 677 | 3.296875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
@Time : 2021/8/11 5:34 下午
@Auth : Codewyf
@File :HJ4 字符串分隔.py
@IDE :PyCharm
@Motto:Go Ahead Instead of Hesitating
"""
while True:
try:
inpt = input()
if len(inpt) < 8:
res = inpt + '0' * (8 - len(inpt))
print(res)
else:
time = int(len(inpt) // 8)
if len(inpt) % 8 == 0:
for i in range(time):
print(inpt[i*8: i*8+8])
else:
for i in range(time):
print(inpt[i*8: i*8+8])
print(inpt[time*8:] + '0' * (8 - len(inpt[time*8:])))
except:
break
|
Java | UTF-8 | 2,594 | 2.96875 | 3 | [] | no_license | package br.com.amil.model;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import static java.util.Map.Entry.comparingByValue;
public class Player implements Comparable<Player> {
private final String name;
private Integer kills;
private Integer deaths;
private Integer streak;
private Integer bestStreak;
private Integer streakTime;
private final Map<String, Integer> weaponsMapper;
private LocalDateTime streakTimeControl;
private boolean fiveTimesAward;
public Player(final String name) {
this.name = name;
this.kills = 0;
this.deaths = 0;
this.streak = 0;
this.bestStreak = 0;
this.streakTime = 0;
this.fiveTimesAward = false;
this.weaponsMapper = new HashMap<>();
}
public Player addKill(final LocalDateTime dateTime, final String weapon) {
kills++;
useWeapon(weapon);
calculateStreak(dateTime);
return this;
}
public Player addDeath() {
deaths++;
streak = 0;
return this;
}
public String getPrincipalWeapon() {
if (weaponsMapper.isEmpty()) return null;
return weaponsMapper.entrySet()
.stream()
.max(comparingByValue())
.get()
.getKey();
}
private void useWeapon(final String weapon) {
Integer usages = 1;
if (weaponsMapper.containsKey(weapon)) {
usages = weaponsMapper.get(weapon) + 1;
}
weaponsMapper.put(weapon, usages);
}
private void calculateStreak(final LocalDateTime dateTime) {
streak++;
if (bestStreak < streak) {
bestStreak = streak;
}
if (streakTimeControl != null
&& dateTime != null
&& Duration.between(streakTimeControl, dateTime).toMinutes() < 1L) {
streakTime++;
if (streakTime >= 5) {
fiveTimesAward = true;
}
} else {
streakTime = 1;
streakTimeControl = dateTime;
}
}
public Integer getKills() {
return kills;
}
public String getName() {
return name;
}
public Integer getDeaths() {
return deaths;
}
public Integer getBestStreak() {
return bestStreak;
}
public boolean isFiveTimesAward() {
return fiveTimesAward;
}
@Override
public int compareTo(Player o) {
return o.getKills().compareTo(kills);
}
}
|
Python | UTF-8 | 540 | 2.8125 | 3 | [] | no_license | class Solution(object):
def canWin(self, s):
"""
:type s: str
:rtype: bool
"""
memo={}
def can(piles):
piles=tuple(sorted(p for p in piles if p>=2))
if not piles in memo:
memo[piles]=any(not can(piles[:i]+(j, pile-2-j)+piles[i+1:])
for i, pile in enumerate(piles)
for j in range(pile/2))
return memo[piles]
return can(map(len, re.findall(r'\++', s))) |
Java | UTF-8 | 1,399 | 2.171875 | 2 | [] | no_license | package loginserver.network.gameserver.clientpackets;
import java.nio.ByteBuffer;
import loginserver.dao.AccountDAO;
import loginserver.model.Account;
import loginserver.network.gameserver.GsClientPacket;
import loginserver.network.gameserver.GsConnection;
import loginserver.network.gameserver.serverpackets.SM_LS_CONTROL_RESPONSE;
import commons.database.dao.DAOManager;
/**
*
* @author Aionchs-Wylovech
*
*/
public class CM_LS_CONTROL extends GsClientPacket
{
private String accountName;
private int param;
private int type;
private String playerName;
private String adminName;
private boolean result;
public CM_LS_CONTROL(ByteBuffer buf, GsConnection client)
{
super(buf, client, 0x05);
}
/**
* {@inheritDoc}
*/
@Override
protected void readImpl()
{
type = readC();
adminName = readS();
accountName = readS();
playerName = readS();
param = readC();
}
/**
* {@inheritDoc}
*/
@Override
protected void runImpl()
{
Account account = DAOManager.getDAO(AccountDAO.class).getAccount(accountName);
switch (type)
{
case 1:
account.setAccessLevel((byte)param);
break;
case 2:
account.setMembership((byte)param);
break;
}
result = DAOManager.getDAO(AccountDAO.class).updateAccount(account);
sendPacket(new SM_LS_CONTROL_RESPONSE(type, result, playerName, account.getId(), param, adminName));
}
}
|
C# | UTF-8 | 1,305 | 3.21875 | 3 | [] | no_license | using BDDSpecFlow.Example;
using NUnit.Framework;
using TechTalk.SpecFlow;
namespace BDDSpecFlow.Steps
{
[Binding]
public sealed class CalculatorStepDefinitions
{
private readonly ScenarioContext _scenarioContext;
private int result;
private Calculator calculator = new Calculator();
public CalculatorStepDefinitions(ScenarioContext scenarioContext)
{
_scenarioContext = scenarioContext;
}
[Given("o primeiro numero é (.*)")]
public void GivenTheFirstNumberIs(int number)
{
calculator.FirstNumber = number;
}
[Given("o segundo numero é (.*)")]
public void GivenTheSecondNumberIs(int number)
{
calculator.SecondNumber = number;
}
[When("a operacao sera (.*)")]
public void WhenTheTwoNumbersAreAdded(string operacao)
{
if (operacao.Equals("soma"))
result = calculator.Sum();
else if (operacao.Equals("subtracao"))
result = calculator.Subtraction();
}
[Then("o resultado deve ser (.*)")]
public void ThenTheResultShouldBe(int expectedResult)
{
Assert.AreEqual(expectedResult, result);
}
}
}
|
Java | UTF-8 | 385 | 1.96875 | 2 | [] | no_license | package com.spl.serendipity928.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Map;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ReportMessage {
/**
* 示例:{"e":1,"m":"今天已经填报了","d":{}}
*/
private Integer e;
private String m;
private Map<String, String> d;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.