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 |
|---|---|---|---|---|---|---|---|
C | UTF-8 | 2,098 | 2.578125 | 3 | [
"MIT"
] | permissive |
#include <stdio.h>
#include "i2c.h"
I2C_Device i2c1 = {
.instance = I2C1,
.state = 0,
};
int i = 0;
uint8_t data[10] = {};
#define I2C_FREQ 42
#define I2C_SPEED 210
#define I2C_RISE_T 43
void I2C_Init(void) {
GPIO_TypeDef *gpio = GPIOB;
RCC_TypeDef *rcc = RCC;
I2C_TypeDef *i2c = I2C1;
/* Enable I2C1 & GPIOB clock */
rcc->APB1ENR |= RCC_APB1ENR_I2C1EN;
rcc->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;
/* Reset I2C1 clock */
rcc->APB1RSTR |= RCC_APB1RSTR_I2C1RST;
rcc->APB1RSTR &= ~RCC_APB1RSTR_I2C1RST;
/* Use alternate function 4 */
gpio->MODER &= ~GPIO_MODER_MODER8;
gpio->MODER |= GPIO_MODER_MODER8_1;
gpio->AFR[1] &= ~(0xF << (0*4));
gpio->AFR[1] |= (4 << (0*4));
gpio->OTYPER |= (1 << 8);
gpio->MODER &= ~GPIO_MODER_MODER9;
gpio->MODER |= GPIO_MODER_MODER9_1;
gpio->AFR[1] &= ~(0xF << (1*4));
gpio->AFR[1] |= (4 << (1*4));
gpio->OTYPER |= (1 << 9);
i2c->CR1 &= ~I2C_CR1_SMBUS; // i2c mode
i2c->CR2 |= (I2C_FREQ & I2C_CR2_FREQ); // Peripheral clock frequency, <= 0b101010
i2c->CCR &= ~I2C_CCR_FS; // Set as standard mode (not fast)
i2c->CCR |= (I2C_SPEED & I2C_CCR_CCR); // Reset speed
/* T high = CCR * T PCLK1 --- T low = CCR * T PCLK1 */
i2c->TRISE &= ~I2C_TRISE_TRISE;
i2c->TRISE |= (I2C_RISE_T & I2C_TRISE_TRISE);
i2c->CR1 |= I2C_CR1_PE; // Peripheral enable
}
uint32_t I2C_Receive(I2C_TypeDef *i2c, uint8_t read_addr, uint8_t write_addr,
uint8_t register_addr, uint8_t *data, uint32_t len) {
i2c->CR1 |= I2C_CR1_START;
while(!(i2c->SR1 & I2C_SR1_SB));
i2c->DR = write_addr;
while(!(i2c->SR1 & I2C_SR1_ADDR));
if (!i2c->SR2) {
return 0;
}
i2c->DR = register_addr;
i2c->CR1 |= I2C_CR1_START;
while(!(i2c->SR1 & I2C_SR1_SB));
i2c->DR = read_addr;
while(!(i2c->SR1 & I2C_SR1_ADDR));
i2c->CR1 &= ~I2C_CR1_ACK;
i2c->CR1 |= I2C_CR1_POS;
if (!i2c->SR2) {
return 0;
}
while(!(i2c->SR1 & I2C_SR1_BTF));
i2c->CR1 |= I2C_CR1_STOP;
*data++ = i2c->DR;
*data++ = i2c->DR;
return 2;
}
|
PHP | UTF-8 | 1,763 | 2.625 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>TP 3 : exercice 2</title>
<meta name="auteur" content="Florent LUCET" />
<meta name="sujet" content="TP de LO07" />
<meta name="mots-cles" content="Programmation,Web,HTML,PHP" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- La feuille de styles "base.css" doit être appelée en premier. -->
<link rel="stylesheet" type="text/css" href="../styles/base.css" media="all" />
<link rel="stylesheet" type="text/css" href="../styles/modeleGeneral.css" media="screen" />
</head>
<body>
<div id="global">
<?php include "../general/entete.html"; ?>
<div id="centre">
<div id="navigation">
<ul>
<li><p><a href="./plan.php">Accueil du TP</a></p></li>
<li><p><a href="./EX1.php">Exercice précédent</a></p></li>
<li><p><a href="./EX3.php">Exercice suivant</a></p></li>
</ul>
</div><!-- #navigation -->
<div id="contenu">
<h2>Tableaux en PHP</h2>
<br/>
<?php
$tabCapitalesUSA = array("Montgomery", "Raleigh", "Tallahassee", "Atlanta", "Topeka", "Augusta", "Albany", "Nashville");
echo "Capitales des USA :";
?>
<pre>
<?php
print_r($tabCapitalesUSA);
?>
</pre>
<br/>
<?php
$nbValue = 0;
echo "Capitales des USA : <br/>";
foreach ($tabCapitalesUSA as $value) {
$nbValue++;
echo "$nbValue : $value <br/>";
}
echo "<br/>";
?>
<?php
$chaine = implode(', ', $tabCapitalesUSA);
echo "Capitales des USA : <br/> $chaine <br/>"
?>
</div><!-- #contenu -->
</div><!-- #centre -->
<?php include "../general/pied.html"; ?>
</div><!-- #global -->
</body>
</html> |
Python | UTF-8 | 1,126 | 3.234375 | 3 | [] | no_license | import pygame
pygame.init()
win = pygame.display.set_mode((500,400))
pygame.display.set_caption("Bubble Sort")
x = 40
y = 40
width = 20
# height of each bar (data to be sorted)
height = [200, 50, 130, 90, 250, 61, 110,
88, 33, 80, 70, 159, 180, 20]
run = True
def show(height):
for i in range(len(height)):
pygame.draw.rect(win,(255,245,78),(x + 30 * i,y,width,height[i]))
while run:
execute = False
pygame.time.delay(10)
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if keys[pygame.K_SPACE]:
execute = True
if execute == False:
win.fill((0,0,0))
show(height)
pygame.display.update()
else:
for i in range(len(height) - 1):
for j in range(len(height) -i - 1):
if height[j] > height[j+1]:
height[j],height[j+1] = height[j+1],height[j]
win.fill((0,0,0))
show(height)
pygame.time.delay(50)
pygame.display.update()
pygame.quit() |
JavaScript | UTF-8 | 3,457 | 2.875 | 3 | [
"MIT"
] | permissive | /*
* 将多个JS文件合并成一个JS文件
* @param{ Object } 压缩的参数
* path : 需要合并的JS文件所在的路径
* names : 需要合并的JS文件名
* output : 输出合并后的JS文件路径
* encoding : 文件编码
* format : 在合并文件时,用于格式化文件的函数
* comboComplete : 合并完后,输出文件前的回调
* compressComplete : 压缩完后,输出文件前的回调
* uglifyUrl : uglify的路径
*/
var combo = function( options ){
options.encoding = ( options.encoding || 'UTF-8' ).toUpperCase();
var fs = require( 'fs' ),
names = options.names.split( ' ' ),
isUTF8 = options.encoding === 'UTF-8',
output = options.output,
outputPath = output.slice( 0, output.lastIndexOf('/') ),
paths = [],
contents = '',
conten, uglify, jsp, pro, ast;
// 删除build文件夹下原来的所有文件
fs.readdirSync( outputPath ).forEach(function( file ){
var path = outputPath + '/' + file;
try{
fs.unlinkSync( path );
console.log( 'Delete the[' + path + '] success' );
}
catch( error ){
console.log( 'Delete file ' + error );
return;
}
});
console.log( '======================================' );
// 计算 paths
names.forEach(function( name ){
paths.push( options.path + name + '.js' );
});
// 合并文本内容
paths.forEach(function( path ){
// 读取
try{
content = fs.readFileSync( path, options.encoding );
}
catch( error ){
console.log( 'Read file ' + error );
return;
}
// utf-8 编码格式的文件可能会有 BOM 头,需要去掉
if( isUTF8 && content.charCodeAt(0) === 0xFEFF ){
content = content.slice( 1 );
}
// 格式化
if( options.format ){
content = options.format( content );
}
// 合并
contents += content + '\n';
console.log( 'Combo the [' + path + '] success.' );
});
// 合并好文本内容后的回调
if( options.comboComplete ){
contents = options.comboComplete( contents );
}
console.log( '======================================\n' +
'All of [' + paths.length + '] files combo success.\n' +
'======================================' );
// 写入文件
try{
fs.writeFileSync( output, contents, options.encoding );
}
catch( error ){
console.log( 'Output file ' + error );
return;
}
// 压缩文件
uglify = require( options.uglifyUrl );
jsp = uglify.parser;
pro = uglify.uglify;
ast = jsp.parse( contents );
ast = pro.ast_mangle( ast );
ast = pro.ast_squeeze( ast );
contents = pro.gen_code( ast );
// 合并好文本内容后的回调
if( options.compressComplete ){
contents = options.compressComplete( contents );
}
// 写入文件
try{
fs.writeFileSync( options.minOutput, contents, options.encoding );
}
catch( error ){
console.log( 'Output file ' + error );
return;
}
console.log( 'Compress success, output [' + options.minOutput + '].' );
};
exports.combo = combo; |
Python | UTF-8 | 788 | 4.28125 | 4 | [] | no_license | # g en alguna parte tiene un yield
#key: function(x) -> y
#ej: key: (lambda x: -x)
#key(g_1)<=key(g_2) ?
#key: (lambda x: x)
def bloques(g,key):
bloque = []
for elemento in g:
#bloque[0] -> bloque[-1] = bloque[len(bloque) - 1]
#me va a generar un bloque hasta que se rompa la condición
if len(bloque) == 0 or key(bloque[-1])<=key(elemento):
bloque.append(elemento)
else:
yield bloque
bloque = [elemento] # [4]
#si existe un bloque restante === len(bloque)>0
if len(bloque)>0:
yield bloque
g = [1,5,6,4,8,9,2,3,7]
key = (lambda x: x)
print( list( bloques( g,key) ) )
#actual bloque: [1,5,6]
#6 <= 4
#genero [1,5,6]
#empiezo con nuevo bloque: [4]
#...
#[2,3] -> 3 <= 7
#nuevo bloque: [2,3,7]
# |
Shell | UTF-8 | 245 | 3.3125 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/sh
#
initrd=${1:-initrd.img}
ramdisk=${2:-RAMDISK}
if [ ! -f $initrd ]; then
echo "$initrd does not exist."
exit 1
fi
if [ -d $ramdisk ]; then
rm $ramdisk -rf
fi
mkdir -p $ramdisk
zcat $initrd | ( cd $ramdisk; cpio -i )
|
Java | UTF-8 | 166 | 1.898438 | 2 | [] | no_license | package writxtr.listeners;
import java.io.File;
import writxtr.beans.SaveEvent;
public interface SaveListener {
void onSaveRequest(File file, SaveEvent event);
}
|
Python | UTF-8 | 613 | 2.625 | 3 | [] | no_license | import numpy as np
import pandas as pd
filename= 'CANdata.log'
#Handle the Raw Data
RawData=pd.read_csv(filename, header = None)
RawData.columns=['Time']
#Divide Data to 3 main Columns
RawData['Data'] = RawData['Time'].str.split(' ').str[2]
RawData['Connection'] = RawData['Time'].str.split(' ').str[1]
RawData['Time'] = RawData['Time'].str.split(' ').str[0]
#Seperate Can Data into ID¶m
RawData['canID']=RawData['Data'].str.extract('^(.+?)#')
RawData['Parameters']=RawData['Data'].str.extract('#(.+)')
RawData['Time'] = RawData['Time'].str.strip('[^("]|[)"$]')
#print(df)
print(RawData) |
Markdown | UTF-8 | 1,251 | 3.171875 | 3 | [] | no_license | # Note Taker Web Application
**Motivation**
This is a web based note taker application that allow a user to enter, save and delete notes.
**Build status**
The build status is complete.
**Code style**
The application is written in JavaScript and use Express.js to run the server side logic for the application. Front end JavaScript uses jquery for DOM navigation.
**Screenshots**

**Code Example**
```javascript
//Delete api target an object by the object's id in the db json file after a user deletes a note.
app.delete("/api/notes/:id", function deleteNote(req, res) {
var noteId = req.body.id;
fs.readFile("./db/db.json", "utf8", function getNoteId(err, d) {
console.log("this is the array", d);
noteArray = JSON.parse(d);
for (var i = 0; i < noteArray.length; i++) {
console.log(noteArray[i]);
if (noteArray[i].id === noteId) {
noteArray.splice(i, 1);
fs.writeFile("./db/db.json", JSON.stringify(noteArray), "utf8", err => {
if (err) throw err;
});
}
}
});
});
```
**Installation**
No installation necessary. Project is hosted here: https://note-taker-web-application.herokuapp.com/notes
|
Markdown | UTF-8 | 1,347 | 2.78125 | 3 | [] | no_license | ## Algoritmo de Strassen
## Requerimientos
- Python 3
- numpy, matplotlib
## Comandos para ejecutar Algoritmo
$ make
$ ./exev1 k n leaf_size reset
ejemplo de ejecucion:
$ ./exev1 1 100 20 1
- k y n corresponden a los parametros del problema
- leaf_size es el tamaño hasta donde se aplica Strassen
- reset corresponde a la cantidad de ejecuciones del algoritmo
## Comando para generar matrices
$ python gen_matrix.py M n m
ejemplo de ejecucion:
$ python gen_matrix.py A 100 100
- M corresponde a la matriz que se quiere generar (A o B)
- n a la cantidad de filas
- m a la cantidad de columnas
## Consideraciones:
- Las matrices generadas por gen_matrix.py quedan en matrixes/
- Los graficos generadas en plot.py se guardan en images/
- Las matrices resultantes de cada implementacion del algoritmo se guardan en output_Strassen, output_Winograd y output_traditional
- Los tiempos de cada algoritmo se guardan en distintos archivos con el siguiente formato: "k n leaf_size time"
- Se intento crear una segunda version del algoritmo de winograd (tercera algoritmo del informe) que no asignara memoria para tener un mejor desempeño pero no se logro buenos resultados con la implementacion. Es por esto, que los archivos que se utilizan para este trabajo son los v1, los que terminan en v2 son esta version que no esta completa
|
C++ | UTF-8 | 2,468 | 2.71875 | 3 | [
"BSD-2-Clause"
] | permissive | /*******************************************************************************
*
*Copyright: armuxinxian@aliyun.com
*
*Author: f
*
*File name: csf_platform.hpp
*
*Version: 1.0
*
*Date: 07-1月-2020 13:49:55
*
*Description: Class(csf_platform) 描述系统信息类,主要获取系统相关的信息
*
*Others:
*
*History:
*
*******************************************************************************/
#if !defined(CSF_PLATFORM_H_INCLUDED_)
#define CSF_PLATFORM_H_INCLUDED_
#include "csf_typedef.h"
#include "csf_system_interface.hpp"
using namespace csf::core::base;
namespace csf
{
namespace core
{
namespace system
{
namespace platform
{
/**
* 描述系统信息类,主要获取系统相关的信息
* @author f
* @version 1.0
* @updated 07-1月-2020 14:14:17
*/
class csf_platform : public csf::core::system::platform::csf_system_interface
{
public:
csf_platform();
virtual ~csf_platform();
/**
* 功能:
* 使用程序文件所在的目录作为工作目录,设置程序运行的工作目录
* 返回:
* 0 :表示成功;
* 非0 :表示失败;
*/
static csf_int32 set_work_directory() {
return set_work_directory(current_path());
}
/**
* 功能:
* 设置程序运行的工作目录
* 返回:
* 0 :表示成功;
* 非0 :表示失败;
*
* @param newVal 表示工作目录地址
*/
static csf_int32 set_work_directory(csf_string newVal);
/**
* 功能:
* 获取当前程序所在的目录地址
* 返回:
* 当前程序存放目录地址字符串,如果获取失败,则目录地址字符串为空。
*/
static csf_string current_path();
/**
* 功能:
* 获取当前进程的PID数值,用于记录使用
* 返回:
* 返回当前进程的PID数值,成功则返回非0;失败则返回0;
*/
static csf_uint32 get_pid();
/**
* 功能:
* 保存pid等信息到文件中
* 返回:
* csf_true : 表示保存pid信息成功;
* csf_false : 表示保存pid信息失败;
*
* @param file 表示需要将信息保存的目的文件地址
*/
static csf_bool save_pid(csf_string file);
};
}
}
}
}
#endif // !defined(CSF_PLATFORM_H_INCLUDED_)
|
Java | UTF-8 | 4,582 | 1.734375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.web.javascript.debugger.breakpoints;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.net.URL;
import org.netbeans.api.debugger.DebuggerManager;
import org.netbeans.api.debugger.DebuggerManagerAdapter;
import org.netbeans.api.debugger.Session;
import org.netbeans.modules.javascript2.debug.breakpoints.JSBreakpointsInfo;
import org.netbeans.modules.web.javascript.debugger.MiscEditorUtil;
import org.netbeans.modules.web.webkit.debugging.api.Debugger;
import org.openide.filesystems.FileObject;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author Martin
*/
@ServiceProvider(service = JSBreakpointsInfo.class)
public class WebBreakpointsActiveService implements JSBreakpointsInfo {
private volatile boolean active = true;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public WebBreakpointsActiveService() {
SessionActiveListener sal = new SessionActiveListener();
DebuggerManager.getDebuggerManager().addDebuggerListener(DebuggerManager.PROP_CURRENT_SESSION, sal);
}
@Override
public boolean areBreakpointsActivated() {
return active;
}
private void setActive(boolean active) {
if (this.active != active) {
this.active = active;
pcs.firePropertyChange(PROP_BREAKPOINTS_ACTIVE, !active, active);
}
}
@Override
public boolean isAnnotatable(FileObject fo) {
String mimeType = fo.getMIMEType();
return MiscEditorUtil.isJSOrWrapperMIMEType(mimeType);
}
@Override
public boolean isTransientURL(URL url) {
return false;
}
@Override
public void addPropertyChangeListener(PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener l) {
pcs.removePropertyChangeListener(l);
}
private class SessionActiveListener extends DebuggerManagerAdapter {
private Debugger currentDebugger;
public SessionActiveListener() {
currentDebugger = getCurrentDebugger();
if (currentDebugger != null) {
active = currentDebugger.areBreakpointsActive();
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (DebuggerManager.PROP_CURRENT_SESSION.equals(propertyName)) {
Debugger newDebugger = getCurrentDebugger();
synchronized (this) {
if (currentDebugger != null) {
currentDebugger.removePropertyChangeListener(this);
}
currentDebugger = newDebugger;
}
if (newDebugger != null) {
setActive(newDebugger.areBreakpointsActive());
} else {
setActive(true);
}
}
if (Debugger.PROP_BREAKPOINTS_ACTIVE.equals(propertyName)) {
setActive(((Debugger) evt.getSource()).areBreakpointsActive());
}
}
private Debugger getCurrentDebugger() {
Session s = DebuggerManager.getDebuggerManager().getCurrentSession();
if (s != null) {
Debugger debugger = s.lookupFirst(null, Debugger.class);
if (debugger != null) {
debugger.addPropertyChangeListener(this);
}
return debugger;
} else {
return null;
}
}
}
}
|
C# | UTF-8 | 1,090 | 2.546875 | 3 | [] | no_license | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Player : MonoBehaviour {
private string playerName;
private Color playerColor;
private int id;
private Image image;
private int position;
public int preTotal;
public bool preGuessed;
public void Awake()
{
image = transform.FindChild("Image").GetComponent<Image>();
}
public void setup(string name, Color color, int id, int position)
{
playerName = name;
image.color = color;
playerColor = color;
this.id = id;
this.position = position;
}
public string PlayerName {
get
{
return playerName;
}
}
public Color PlayerColor
{
get
{
return playerColor;
}
}
public int PlayerId
{
get
{
return id;
}
}
public int Position
{
get
{
return position;
}
set
{
position = value;
}
}
}
|
Java | UTF-8 | 939 | 2.25 | 2 | [] | no_license | package jp.techacademy.yuka.satou.originalapp;
import java.io.Serializable;
import java.util.Date;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class Report extends RealmObject implements Serializable {
private String start; //出勤時刻
private String end; //退勤時刻
private Date date; //日時
// id をプライマリーキーとして設定
@PrimaryKey
private int id;
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
Java | GB18030 | 528 | 1.859375 | 2 | [] | no_license | package com.accp.dao.tzy;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.accp.pojo.Firm;
public interface tzy_FirmMapper {
int deleteByPrimaryKey(Integer firmid);
int insert(Firm record);
int insertSelective(Firm record);
Firm selectByPrimaryKey(Integer firmid);
int updateByPrimaryKeySelective(Firm record);
int updateByPrimaryKey(Firm record);
//ѯȫӦ
List<Firm> queryfirm(@Param("firmname")String firmname);
} |
C | UTF-8 | 417 | 3.609375 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main(){
float alt,peso;
int selec;
printf("Digite o sua altura\n");
scanf("%f",&alt);
printf("Digite o seu sexo (1) para Masculino ou (0) para Feminino\n");
scanf("%d",&selec);
if(selec == 1){
peso = (72.7*alt) - 58;
}
if(selec == 0){
peso = (62.1*alt) - 44.7;
}
printf("O peso eh %.2f\n\n",peso);
system("pause");
return 0 ;
}
|
Markdown | UTF-8 | 5,183 | 3.046875 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: "Work with activities in the Kanban view in Dynamics 365 Sales"
description: "Use the opportunity Kanban view to visualize your activities with a card-based view and manage these activities quickly by moving them across the swim lanes."
ms.date: 10/25/2021
ms.topic: article
author: lavanyakr01
ms.author: lavanyakr
searchScope:
- D365-App-msdynce_saleshub
- D365-App-msdynce_salespro
- D365-Entity-activitypointer
- D365-UI-*
- Dynamics 365
- Sales
---
# Work with activities in the Kanban view
The Kanban view for activities helps salespeople to manage multiple activities quickly. Looking at the Kanban view, salespeople can quickly see the activities and the status they're in. In the Activity Kanban view, activities are represented visually with cards. The lanes represent the default statuses of activities. You can drag the activities to different lanes to move them from one status to another.
> [!NOTE]
> The Kanban view is not supported in the **Dynamics 365 for Phones** mobile app.
## License and role requirements
| Requirement type | You must have |
|-----------------------|---------|
| **License** | Dynamics 365 Sales Premium, Dynamics 365 Sales Enterprise, or Dynamics 365 Sales Professional <br>More information: [Dynamics 365 Sales pricing](https://dynamics.microsoft.com/sales/pricing/) |
| **Security roles** | Any primary sales role, such as salesperson or sales manager<br> More information: [Primary sales roles](security-roles-for-sales.md#primary-sales-roles)|
## Open a Kanban view
A Kanban view is available when the Kanban control is added to the Activity entity. If you don't see the Kanban view, check with your system customizer.
To open the Kanban view:
1. In the site map, select **Activities**.
2. On the command bar, select the **More commands** icon , and select **Show As** > **Kanban**.
> [!div class="mx-imgBorder"]
> 
The activities are shown in the Kanban view.
> [!div class="mx-imgBorder"]
> 
## Know your Kanban views
Here are some important things to know about your Kanban view:
- At the top of each lane, the count of activities in that lane is shown. At any given point, only the first 10 records/cards are shown in any lane. For example, if there are a total of 30 open activities, the count shows 10/30. To see more cards, scroll down in the lane. When you scroll down, the count changes to show 20/30, and so on.
> [!NOTE]
> If there are more than 50,000 records in a swim lane, the count of records is shown as 50000+.
- Selecting the card title opens the activity main form. When you close the Main form, the whole Kanban view is refreshed.
- The card fields are editable inline. You can quickly change details for the three fields of an activity record right from the card.
> [!div class="mx-imgBorder"]
> 
- When you select a different view or filter, cards in the lanes are refreshed to show the filtered activity records. For example, if you are currently using the All Activities view, and select the **Activity Type** filter to show only phone calls, the swim lanes are refreshed to show only the phone call activities.
- You can use the **Search** box to filter the records/cards in the swim lane based on the search criteria. For example, if you enter the keyword "Discuss," it will refresh the Kanban view to only show the activity records where the title begins with "Discuss".
> [!div class="mx-imgBorder"]
> 
- You can drag a card and move it to other lanes. When you drag a card from one lane to another, the activity status changes:
- The cards for the out-of-the-box activity types can be moved from Open to Completed and Canceled lanes. Once the card is moved to the Completed or Canceled lane, the activity status changes to closed, the activity card becomes inactive, and a lock icon is shown on the card. You can't change the fields on an inactive or locked card.
- You can't reopen an inactive activity other than the Campaign Response activity. An inactive/locked card of Campaign Response activity can be moved back from Completed or Canceled lanes to the Open lane.
- There's no restrictions on the movement of custom activity cards—they can be moved from any lane to any lane.
- When you're dragging a card to move to another lane, the lanes where the card can't be dropped appear dimmed.
[!INCLUDE [cant-find-option](../includes/cant-find-option.md)]
### See also
[Add the Kanban control to Opportunity or Activity entities](add-kanban-control.md)
[!INCLUDE[footer-include](../includes/footer-banner.md)]
|
Go | UTF-8 | 532 | 3.25 | 3 | [] | no_license | package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
user := make(map[string]string)
fmt.Println("Enter your name.")
if scanner.Scan() {
name := scanner.Text()
user["name"] = name
}
fmt.Println("Enter your address.")
if scanner.Scan() {
address := scanner.Text()
user["address"] = address
}
obj, err := json.MarshalIndent(user, "", " ")
if err != nil {
log.Fatal("Error is: ", err)
return
}
fmt.Println("Json object is ", string(obj))
}
|
Java | UTF-8 | 3,369 | 2.375 | 2 | [] | no_license | /*
* This file is part of Macchiato Doppio Java Game Framework.
* Copyright (C) Dec 1, 2010 Matthew Stockbridge
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* (but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* mdj
* org.mdj.core
* DefaultDecorator.java
*
* For more information see: https://sourceforge.net/projects/macchiatodoppio/
*
* This file is part of the Mark 3 effort in reorganizing Macchiato Doppio,
* and is therefore *non-final* and *not* intended for public use. This code
* is strictly experimental.
*/
package org.ajar.age;
import java.util.List;
/**
* DefaultDecorator is a general-purpose implementation of {@link Decorator}:
* It provides the expected delegation functionality of the <code>Decorator</code>
* interface without adding any additional functionality of its own.
* @see Node
* @see Decorator
* @author revms
* @since 0.0.0.153
*/
public class DefaultDecorator<A extends Attributes> implements Decorator<A> {
/**
* The <code>Node</code> beind decorated.
*/
protected final Node<A> node;
/**
* Constructs a new <code>DefaultDecorator</code> that is decorating the supplied <code>Node</code>.
* @param node the node that this decorator will decorate.
*/
public DefaultDecorator(Node<A> node){
this.node = node;
node.addDecorator(this);
}
@Override
public boolean hasChildren() {
return node.hasChildren();
}
@Override
public void addChild(Node<A> child) {
node.addChild(child);
}
@Override
public void addChild(int index, Node<A> child) {
node.addChild(index, child);
}
@Override
public boolean removeChild(Node<A> child) {
return node.removeChild(child);
}
@Override
public List<Node<A>> getChildren() {
return node.getChildren();
}
@Override
public Node<A> getParent() {
return node.getParent();
}
@Override
public A getAttributes() {
return node.getAttributes();
}
@Override
public boolean hasCapability(Class<? extends Decorator<A>> c) {
return node.hasCapability(c);
}
@Override
public <D extends Decorator<A>> D getDecorator(Class<D> c) {
return node.getDecorator(c);
}
@Override
public void addDecorator(Decorator<A> decorator) {
node.addDecorator(decorator);
}
@Override
public <D extends Decorator<A>> D removeDecorator(Class<D> c) {
return node.removeDecorator(c);
}
@Override
public Node<A> getUndecoratedNode() {
return node.getUndecoratedNode();
}
@Override
public void accept(Visitor<A> visitor) {
node.accept(visitor);
}
@Override
public boolean needsUpdate() {
return true;
}
/* (non-Javadoc)
* @see org.ajar.age.Node#getRoot()
*/
@Override
public Node<A> getRoot() {
return node.getRoot();
}
}
|
Java | UTF-8 | 149 | 1.867188 | 2 | [] | no_license | package com.anime.proxy.v1;
/**
* @author 陌上丶天琊
* @date 2019-10-30 13:11
* 描述:
*/
public interface Movable {
void move();
}
|
C++ | UTF-8 | 1,001 | 2.515625 | 3 | [] | no_license | //Center pin of for signal.
//Zener diod for 5 v.
const int analogInPin = A0;
const int analogOutPin = 12;
const int ledPin = LED_BUILTIN;
int sensorValue = 0;
int outputValue = 0;
unsigned long previousMillis = 0;
unsigned long time1 = 0;
bool stat = false;
const long interval = 10001;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
sensorValue = analogRead(analogInPin);
outputValue = map(sensorValue, 0, 1023, 0, 255);
analogWrite(analogOutPin, outputValue);
if (outputValue >= 100) {
digitalWrite(ledPin, HIGH);
previousMillis = millis();
stat = true;
}
if (millis() - previousMillis >= interval) {
digitalWrite(ledPin, LOW);
stat = false;
}
if (stat) {
time1 = millis() - previousMillis;
Serial.println(map(time1, 0, 20000, 0, 20));
}
/*
Serial.print(previousMillis);
Serial.print("Sensoe = ");
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
delay(200);*/
}
|
Markdown | UTF-8 | 3,232 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | This document describes production documentation tips.
Overview
=========
MapRoulette has been deployed successfully using uWSGI behind an nginx
web server.
Directory Layout
=================
The production environment we've used stores the base directory for
the web server as `/srv/www`, with the base directory for the
deployment as the fully qualified domain of the server, such as
`maproulette.org`, meaning that the base directory would be
`/srv/www/maproulette`.
Inside this directory, we will place the virtual environment used by
maproulette, in a directory called `venv`.
The app itself will live in the `app` directory in a
directory called `maproulette` (`app/maproulette`).
We will also directories for log files and the uwsgi socket.
In the end, you will end up with an directory structure like:
/srv/www/maproulette/app
/srv/www/maproulette/log
/srv/www/maproulette/venv
/srv/www/maproulette/uwsgi
All of these should be owned by the web server user. On Debian/Ubuntu,
this is `www-data`, so we will use that as the identifier of the web
user for the remainder of this guide. Feel free to change it as you
see fit on your own installation.
Getting from Git
=================
As the `www-data` user, run:
git clone https://github.com/osmlab/maproulette.git \
/srv/www/maproulette/app/maproulette
Virtualenv
==========
We will use `venv` to contain the directory. We should do this
as the final user, which we will assume to be `www-data` in this
guide.
As `www-data` run:
virtualenv /srv/www/maproulette/venv
You will need to be using the environment set up by that virtualenv,
so now run
source /srv/www/maproulette/venv/bin/activate
And finally, install the requirements for the project
pip install -r /srv/www/maproulette/app/maproulette/requirements.txt
UWSGI
======
We will use Uwsgi as the application container. To install it, run:
apt-get install uwsgi uwsgi-plugin-python
And then create a file `/etc/uwsgi/apps-available/maproulette.ini`
which contains the following:
[uwsgi]
plugin = python
vhost = true
socket = /srv/www/maproulette/uwsgi/socket
venv = /srv/www/maproulette/virtualenv
chdir = /srv/www/maproulette/app/maproulette
module = maproulette:app
Then, create a symlink from `/etc/uwsgi/apps-enabled/maproulette.ini`
to `/etc/uwsgi/apps-available/maproulette.org` with the command:
ln -s /etc/uwsgi/apps-available/maproulette.ini \
/etc/uwsgi/apps-available/maproulette.ini
Nginx
=====
We will use the Nginx web server to serve up our application. To install
it, just run:
apt-get install nginx
And then create a file in `/etc/nginx/sites-available/maproulette`
containing:
server {
listen 80;
server_tokens off;
server_name maproulette.org;
location / {
include uwsgi_params;
uwsgi_pass unix:/srv/www/maproulette/uwsgi/socket;
}
}
Create a symlink to the enabled sites directory:
ln -s /etc/nginx/sites-available/maproulette\
/etc/nginx/sites-enabled/
Finally
========
Restart the services
service uwsgi restart
service nginx restart
And the service should be up and running! |
C# | UTF-8 | 1,010 | 2.5625 | 3 | [] | no_license | using MvvmCrossTemplate.Contracts.Repository;
using MvvmCrossTemplate.Contracts.Services;
using MvvmCrossTemplate.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MvvmCrossTemplate.Services.Data
{
public class EmployeeDataService : IEmployeeDataService
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeDataService(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
public async Task<Employee> GetEmployeeDetails(int employeeId)
{
var employee = await _employeeRepository.GetEmployeeDetails(employeeId);
return employee;
}
public async Task<IEnumerable<Employee>> SearchEmployee(string employeeName, string employeeCharge, DateTime employeeStartDate)
{
return await _employeeRepository.SearchEmployee(employeeName, employeeCharge, employeeStartDate);
}
}
}
|
JavaScript | UTF-8 | 4,331 | 2.84375 | 3 | [] | no_license | import React, { Component } from 'react'
import { Formik, Form, Field, ErrorMessage } from 'formik'
import BookDataService from '../api/BookDataService'
export default class BookForm extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
book: {}
}
this.onSubmit = this.onSubmit.bind(this)
this.validate = this.validate.bind(this)
}
// populate when the page is opened, with Book JSON data
componentDidMount() {
if (this.state.id === -1) return
BookDataService.getBookById(this.state.id)
.then(response => this.setState({ book: response.data }))
}
// Formik onSubmit Button
onSubmit(values) {
console.log(values)
let book = {
bookId: this.state.id,
isbn: values.isbn,
title: values.title,
summary: values.summary
}
// if ID == -1, this is a NEW restaurant to add
if (this.state.id == -1) {
BookDataService.createBook(book)
.then(() => this.props.history.push(`/books`))
}
else {
//This is an edit of existing restaurant
BookDataService.updateBook(this.state.id, book)
.then(() => this.props.history.push(`/books`))
}
}
validate(values) {
let errors = {}
if (!values.isbn)
errors.isbn = "Please input book isbn"
if (!values.title)
errors.title = "Please input book title"
if (!values.summary)
errors.summary = "Please input book summary"
return errors
}
render() {
// IF this is EDIT, retrieve the initial values from Book JSON
// so we can populate the form
let { isbn, title, summary } = this.state.book
let displayBookId = this.state.id
return (
<div className="container">
<div className="m-5 p-5">
<h1>{`Book ID: ${displayBookId == -1 ? 'NEW' : displayBookId}`}</h1>
<Formik
// Formik Form initial values
initialValues={{ isbn, title, summary }}
// Click to submit --> Formik onSubmit
onSubmit={this.onSubmit}
// handle validation --> Formik validate
validateOnBlur={false}
validateOnChange={false}
validate={this.validate}
// allow the Formik form to get the state
enableReinitialize={true}
>
{
(props) =>
<Form >
<ErrorMessage name="isbn" component="p" className="alert alert-warning" />
<ErrorMessage name="title" component="p" className="alert alert-warning" />
<ErrorMessage name="summary" component="p" className="alert alert-warning" />
<fieldset className="form-group pb-3">
<label>Book ISBN</label>
<Field className="form-control" type="text" name="isbn" />
</fieldset>
<fieldset className="form-group pb-3">
<label>Book Title</label>
<Field className="form-control" type="text" name="title" />
</fieldset>
<fieldset className="form-group pb-5">
<label>Summary</label>
<Field className="form-control" as="textarea" rows="5" name="summary" />
</fieldset>
<button className="btn btn-primary " type="submit" name="submit">Submit</button>
</Form>
}
</Formik>
</div>
</div>
)
}
}
|
Markdown | UTF-8 | 2,208 | 3 | 3 | [
"MIT"
] | permissive | ---
title : "When Time became our God, and anxiety our companion."
author : "Obed Marquez Parlapiano"
date : "2019-01-05"
categories :
- thoughts
tags : ""
cover : "../images/black-sand-hourglass-standing-on-rocks-at-the-beach.jpg"
---
The time is so scarce, it is somewhat frustrating. To let go of things you love, just to make some space for the things you might have a lesser love for, but that has more value in general.
It is hard to understand if there is really little time when you see giants creating a rock empire in the same time a kid needs to make a sand castle that is going to be washed away with the next tidal wave.
And most of us stand in the middle, thinking of our clicking time as an unstoppable train, going forward and forward without any stops, once you pay your ticket and you get in, better to get comfy because... this is all there is and ever will be.
But is it really all there is? How can some people hop off the train, have a look, buy some souvenirs, hop back on, and arrive at the exact same time as the rest of us, who never made a stop?
Is it really true the old story about the rabbit and the turtle? The turtle winning the race even when the rabbit is way faster? Is it worth it the rush if you will end up sleeping under a tree?
it is a scary thought; the idea of Time. The only God we can all be sure exists, for it rules our lives.
Time never dies. It rules over everything there is, watches the birth and dead of every single thing, from stars to little humans and beyond. It gives everyone and everything the exact same chance to shine and fall apart.
But as the Gods in all our cultures, Time is not so fair. Einstein showed how some tricks can make us fool mighty Time.
But unless The Doctor decides to take you on a journey, you and I are stuck here, hearing the clock ticking and wondering what we're gonna do with our Time.
* * *
I originally wrote this post a long time ago. Can't tell you exactly when, since I seem to have lost its history, but at least a year ago.
I started going through my posts and found that I had almost 40 un-published blog posts (!). This is the first one to be fully edited and published, I actually loved it and was glad to find it.
|
C# | UTF-8 | 1,068 | 3.609375 | 4 | [] | no_license | using System;
namespace Wizard.Models
{
public class Ninja : Human
{
public Ninja(string name) : base(name)
{
Dexterity = 175;
}
public override int Attack(Human target)
{
int dmg = 5 * Dexterity;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"{Name} has struck down {target.Name} with might and strength!!!");
Console.ResetColor();
Random rand = new Random();
if(rand.Next(1,100) <= 20)
{
Console.WriteLine($"{Name} has kicked {target.Name} when they were down!!!");
dmg += 10;
}
return target.Damage(dmg);
}
public int Steal(Human target)
{
target.Damage(5);
health += 5;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"{Name} has taken 5 health from {target.Name}.");
Console.ResetColor();
return target.Health;
}
}
} |
Markdown | UTF-8 | 1,817 | 2.71875 | 3 | [
"MIT"
] | permissive | ---
title: "동분서주(東奔西走) - Korean 4 Character Idioms #12"
published: 2015-02-03
date: 2016-02-19
---
# 3 Speed Only
<iframe id="audio_iframe" src="https://www.podbean.com/media/player/fvnbq-538aca/initByJs/1/auto/1?skin=4" width="100%" height="100" frameborder="0" scrolling="no"></iframe>
# With Explanation
<iframe id="audio_iframe" src="https://www.podbean.com/media/player/m9zrn-538ae0/initByJs/1/auto/1?skin=4" width="100%" height="100" frameborder="0" scrolling="no"></iframe>
All of us are busy at some point because of the works. Thanks to them, we sometimes have to run to here and there. 동분서주 is the right expression for this situation.
동분서주 is the emphasized version of the word, 분주하다, a synonym of 바쁘다 in Korean. 분 and 주 means to run. 동 means east, 서 means the opposite direction of 동, west. The basic meaning of 동분서주 is to run to the east and west. Think about this situation, something happened in the east, so you ran there to solve it. Not so long after it is finished, other thing occurred in the west, so you had to run there to check it out. You would be really busy if you were in such a situation. That's why 동분서주 got this meaning, being really busy.
경찰은 범인을 잡기 위해 동분서주 중이다.
The police is really busy to get the criminal.
대한민국은 2002년에 월드컵을 한 번 유치했지만, 다시 한 번 유치해 보기 위해 동분서주 중이다.
Korea hosted World Cup once in 2002, but they are busy trying to host it again.
우리 학교가 더 좋은 학교가 되려면 학생 회장 뿐 아니라 모든 학생이 동분서주 노력해야 해.
If we want our school to be better, not only the president of student council but also every student should do their utmost.
|
Java | UTF-8 | 626 | 3.609375 | 4 | [] | no_license | package algorithms.Implementation;
import java.io.*;
import java.util.*;
// https://www.hackerrank.com/challenges/drawing-book/problem
public class DrawingBook {
static int pageCount(int n, int p) {
int left = (p/2);
int right = (n/2)-left;
return (Math.min(left, right));
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int n = scanner.nextInt();
int p = scanner.nextInt();
int result = pageCount(n, p);
System.out.println(result);
scanner.close();
}
}
|
Shell | UTF-8 | 538 | 2.71875 | 3 | [] | no_license | #!/bin/bash
set -e
set -u
DIR="$(dirname $0)"
echo $0
echo "Do we have OS password?"
echo $BEELDBANK_OBJECTSTORE_PASSWORD
#
dc() {
#docker-compose -p bb -f ../docker-compose.yml $*;
docker-compose $*;
}
# so we can delete named volumes
#dc stop
#dc rm -f -v
dc pull
dc up -d database
dc exec database update-table.sh bag bag_nummeraanduiding public beeldbank
dc exec database update-table.sh bag bag_verblijfsobject public beeldbank
dc run -T importer ./import-xml.sh
#python objectstore.py
#dc exec importer ./xmlparser
|
Java | UTF-8 | 6,580 | 2.078125 | 2 | [] | no_license | package com.bridgelabz.bookstore.controller;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.bridgelabz.bookstore.dto.LoginDto;
import com.bridgelabz.bookstore.dto.ResetPassword;
import com.bridgelabz.bookstore.dto.RegisterDto;
import com.bridgelabz.bookstore.entity.Admin;
import com.bridgelabz.bookstore.entity.Book;
import com.bridgelabz.bookstore.entity.Seller;
import com.bridgelabz.bookstore.entity.Users;
import com.bridgelabz.bookstore.exception.AdminException;
import com.bridgelabz.bookstore.exception.BookException;
import com.bridgelabz.bookstore.exception.ExceptionMessages;
import com.bridgelabz.bookstore.exception.S3BucketException;
import com.bridgelabz.bookstore.exception.SellerException;
import com.bridgelabz.bookstore.exception.UserException;
import com.bridgelabz.bookstore.response.Response;
import com.bridgelabz.bookstore.service.SellerService;
import com.bridgelabz.bookstore.utility.JwtService;
import com.bridgelabz.bookstore.utility.JwtService.Token;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/seller")
@CrossOrigin
public class SellerController {
@Autowired
private SellerService service;
/* API for seller registration */
@PostMapping("/registration")
@ApiOperation(value = "seller registration", response = Response.class)
public ResponseEntity<Response> register(@RequestBody RegisterDto dto, BindingResult res) {
if (res.hasErrors()) {
return ResponseEntity.badRequest()
.body(new Response(HttpStatus.NOT_ACCEPTABLE, ExceptionMessages.SELLER_ALREADY_MSG, dto));
}
Seller reg = service.register(dto);
return ResponseEntity.ok().body(new Response(HttpStatus.ACCEPTED, "Seller Registered Successfully", reg));
}
/* API for seller login */
@PostMapping("/login")
@ApiOperation(value = "login for seller", response = Response.class)
public ResponseEntity<Response> Login(@RequestBody LoginDto login, BindingResult res) {
if (res.hasErrors()) {
return ResponseEntity.badRequest()
.body(new Response(HttpStatus.NOT_ACCEPTABLE, ExceptionMessages.SELLER_NOT_FOUND_MSG, login));
}
Seller seller = service.login(login);
String token = JwtService.generateToken(seller.getSellerId(), Token.WITH_EXPIRE_TIME);
return ResponseEntity.ok().body(new Response(HttpStatus.ACCEPTED, "Login Successfully", token));
}
/* API for verifying the token generated for the email */
@PutMapping("/verifyemail/{token}")
@ApiOperation(value = "seller email verification", response = Response.class)
public ResponseEntity<Response> verify(@PathVariable("token") String token) throws Exception {
boolean verification = service.verify(token);
return ResponseEntity.ok().body(new Response(HttpStatus.ACCEPTED, "verified", verification));
}
/* API for seller forgetPassword */
@PostMapping("/forgotpassword")
@ApiOperation(value = "forgetpassword for seller", response = Response.class)
public ResponseEntity<Response> forgotPassword(@RequestParam("email") String email) throws SellerException {
Seller seller = service.forgetPassword(email);
return ResponseEntity.ok()
.body(new Response(HttpStatus.ACCEPTED, "resetpassword mail has send to email successfully", email));
}
/* API for seller updating password */
@PutMapping("/resetpassword/{token}")
@ApiOperation(value = "reset password for seller", response = Response.class)
public ResponseEntity<Response> resetPassword(@RequestBody ResetPassword update,
@PathVariable("token")String token, BindingResult res) throws SellerException {
if (res.hasErrors()) {
return ResponseEntity.badRequest()
.body(new Response(HttpStatus.NOT_ACCEPTABLE, ExceptionMessages.SELLER_NOT_FOUND_MSG, update));
}
Boolean passwordUpdate = service.resetPassword(update, token);
return ResponseEntity.ok()
.body(new Response(HttpStatus.ACCEPTED, "Password updated successfully", passwordUpdate));
}
@ApiOperation(value = "add profile to seller", response = Iterable.class)
@PutMapping("/profile")
public ResponseEntity<Response> addProfile(@RequestPart("file") MultipartFile file,
@RequestHeader("token") String token)
throws S3BucketException, AmazonServiceException, SdkClientException, AdminException, IOException {
Seller seller = service.addProfile(file, token);
return ResponseEntity.ok().body(new Response(HttpStatus.ACCEPTED, "profile added for seller", seller));
}
@ApiOperation(value="get the seller details by seller id" ,response = Iterable.class)
@GetMapping("/getseller")
public ResponseEntity<Response> getSeller(@RequestHeader("token") String token)
{
Seller seller = service.getSellerById(token);
return ResponseEntity.ok().body(new Response(HttpStatus.ACCEPTED, " seller details are...", seller));
}
@ApiOperation(value="remove profile to seller",response = Iterable.class )
@DeleteMapping("/removeprofile")
public ResponseEntity<Response> removeProfile(@RequestHeader("token") String token) throws S3BucketException{
Seller seller=service.removeProfile(token);
return ResponseEntity.ok()
.body(new Response(HttpStatus.ACCEPTED, "profile pic removed", seller));
}
@ApiOperation(value = "list of books added by seller", response = Iterable.class)
@GetMapping("/bookslist")
public ResponseEntity<Response> getBooks(@RequestParam String token) throws SellerException{
List<Book> books = service.getBooks(token);
return ResponseEntity.ok().body(new Response(HttpStatus.ACCEPTED, "List of books added by seller ",books));
}
}
|
C# | UTF-8 | 1,168 | 2.84375 | 3 | [
"MIT"
] | permissive | using SRDP.Domain.Enumerations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SRDP.Domain.ValueObjects
{
public class CondicionAlerta : ValueObject
{
public OperadorAlerta Operador { get; }
public string OperadorSql { get; }
private CondicionAlerta() { }
public CondicionAlerta(string operador)
{
if (operador.Trim().ToUpper() == "Y")
{
Operador = OperadorAlerta.Y;
OperadorSql = " AND ";
}
else if (operador.Trim().ToUpper() == "O")
{
Operador = OperadorAlerta.O;
OperadorSql = " OR ";
}
else
{
throw new DomainException("Operador inválido '" + operador + "'");
}
}
public override string ToString()
{
return Operador.ToString();
}
protected override IEnumerable<object> GetAtomicValues()
{
yield return Operador;
yield return OperadorSql;
}
}
}
|
Java | UTF-8 | 539 | 2.0625 | 2 | [
"MIT"
] | permissive | package com.someguyssoftware.dungeonsengine.builder;
import java.util.Random;
import com.someguyssoftware.dungeonsengine.config.LevelConfig;
import com.someguyssoftware.dungeonsengine.model.IRoom;
import com.someguyssoftware.gottschcore.positional.ICoords;
import net.minecraft.util.math.AxisAlignedBB;
public interface ISurfaceRoomBuilder {
/**
*
* @param random
* @param field
* @param startPoint
* @param config
* @return
*/
public IRoom buildEntranceRoom(Random random, ICoords startPoint, LevelConfig config);
} |
PHP | UTF-8 | 2,235 | 2.78125 | 3 | [] | no_license | <?php
$_GET['list'] = 'list=The Hobbit: The Battle of the Five Armies (adventure)- Ian McKellen, Martin Freeman, Richard Armitage, Cate Blanchett / 300
Night at the Museum: Secret of the Tomb (comedy)- Ben Stiller, Robin Williams, Owen Wilson, Dick Van Dyke / 200
Exodus: Gods and Kings (action)- Christian Bale, Joel Edgerton, Ben Kingsley, Sigourney Weaver / 250
Wild (drama)- Reese Witherspoon, Laura Dern, Gaby Hoffmann, Michiel Huisman / 150
Big Hero 6 (action)- Ryan Potter, Scott Adsit, Jamie Chung, T.J. Miller / 250
';
$_GET['minSeats'] = '160';
$_GET['maxSeats'] = '300';
$_GET['filter'] = 'comedy';
$_GET['order'] = 'ascending';
$screenings = preg_split("/\\r\\n/", $_GET['list'], -1, PREG_SPLIT_NO_EMPTY);
$genre = trim($_GET['filter']);
$minSeats = intval($_GET['minSeats']);
$maxSeats = intval($_GET['maxSeats']);
$order = $_GET['order'];
$movies = array();
$re = "/(.*?)\\(([a-z]+)\\)\\s*-\\s*([A-Za-z\\s,\\.]+)\\s*\\/\\s*(\\d+)/";
foreach ($screenings as $movie) {
$result = preg_match($re, $movie, $matches);
$movieTopic = trim($matches[1]);
$movieGenre = trim($matches[2]);
$movieActors = explode(', ', trim($matches[3]));
$movieSeats = intval(trim($matches[4]));
$movies[] = array(
'movie name' => $movieTopic,
'genre' => $movieGenre,
'stars' => $movieActors,
'seats filled' => $movieSeats
);
}
$movies = array_filter($movies, function($v) use ($minSeats, $maxSeats){
return $v['seats filled'] >= $minSeats && $v['seats filled'] <= $maxSeats;
});
if ($genre !== 'all') {
$movies = array_filter($movies, function($v) use ($genre){
return $v['genre'] === $genre;
});
}
usort($movies, function($a, $b) use ($order){
if ($a['movie name'] === $b['movie name']) {
return $a['seats filled'] - $b['seats filled'];
} else {
if ($order === 'ascending') {
return strcmp($a['movie name'], $b['movie name']);
} else {
return strcmp($b['movie name'], $a['movie name']);
}
}
});
foreach ($movies as $movie) {
echo '<div class="screening"><h2>'.htmlspecialchars($movie['movie name']).'</h2><ul>';
foreach ($movie['stars'] as $actor) {
echo '<li class="star">'.htmlspecialchars($actor).'</li>';
}
echo '</ul><span class="seatsFilled">'. $movie['seats filled'] .' seats filled</span></div>';
}
|
C# | UTF-8 | 2,000 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | using Microsoft.Extensions.Logging;
using Namespace2Xml.Semantics;
using Namespace2Xml.Syntax;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Namespace2Xml.Formatters
{
public class NamespaceFormatter : StreamFormatter
{
private readonly IReadOnlyList<string> outputPrefix;
private readonly string delimiter;
public NamespaceFormatter(Func<Stream> outputStreamFactory, IReadOnlyList<string> outputPrefix, string delimiter, ILogger<NamespaceFormatter> logger)
: base(outputStreamFactory, logger)
{
this.outputPrefix = outputPrefix;
this.delimiter = delimiter;
}
protected override async Task DoWrite(ProfileTree tree, Stream stream, CancellationToken cancellationToken)
{
using (var writer = new StreamWriter(stream))
foreach (var line in tree
.GetLeafs()
.OrderBy(pair => pair.leaf.SourceMark)
.SelectMany(pair => FormatEntry(pair.prefix, pair.leaf)))
await writer.WriteLineAsync(line.ToCharArray(), cancellationToken);
}
private IEnumerable<string> FormatEntry(QualifiedName prefix, ProfileTreeLeaf leaf)
{
var names = prefix.Parts
.Select(part => part.Tokens.Cast<TextNameToken>().Single().Text)
.Skip(1);
if (outputPrefix != null)
names = outputPrefix.Concat(names);
if (delimiter == ".")
names = names.Select(name => name.Replace(".", "\\."));
return leaf
.LeadingComments
.Select(comment => comment.ToString())
.Concat(new[] { $"{string.Join(delimiter, names)}={FormatValue(leaf.Value)}" });
}
protected virtual string FormatValue(string value) => value;
}
}
|
C++ | UTF-8 | 1,205 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
int dx[] = {2, 2, 1, -1}, dy[] = {1, -1, -2, -2};
map< pair<int, int>, int > mem;
bool Win(int x, int y, int n) {
if (-x+y >= n || x+y >= n || x-y >= n || -x-y >= n) return 1;
map< pair<int, int>, int >::iterator i = mem.find( make_pair(x, y) );
if (i != mem.end()) return i->second;
int& result = mem[make_pair(x, y)] = 0;
for (int i = 0; i < 4; ++i) {
if (!Win(x + dx[i], y + dy[i], n)) {
result = 1;
break;
}
}
return result;
}
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
int N;
cin >> N;
cout << 2 - Win(0, 0, N) << endl;
return 0;
}
|
JavaScript | UTF-8 | 10,238 | 2.65625 | 3 | [] | no_license |
/////////////////
// RidesScene
/////////////////
class RidesScene extends Phaser.Scene {
constructor() {
super('RidesScene')
this.ferrisWheelRotSpeed = 0.005;
this.bumperCarSpeed = 4500;
// hard coded tired
this.starsToCollect = 4;
}
create() {
this.add.image(config.width / 2, config.height / 2, "HomePageBG");
this.createTrain();
this.createFerrisWheel();
this.createBumperCar();
this.createSwingChair();
this.scene.get('HomePage').createSceneEssentials(this);
}
createSwingChair() {
let swingChairBase = this.add.image(450, 500, "SwingChair_BaseAnchor").setScale(2);
// swing chair header
let swingChairHeader = this.add.sprite(swingChairBase.x, swingChairBase.y - 130, "SwingChair_Header").setScale(2);
// create the swing chair header animation
this.anims.create({
key: "SwingChairHeaderAnim",
frames: this.anims.generateFrameNumbers('SwingChair_Header'),
frameRate: 5,
repeat: -1
});
swingChairHeader.play("SwingChairHeaderAnim");
// how far away are the chairs from centerPt
let radius = 10;
// how much to rotate from extreme left to extreme right
var maxChairSwingRotSpan = 100;
// how many chairs
var maxSwingChairCount = 4;
// angle diff between each chair
var angleSpacing = maxChairSwingRotSpan / maxSwingChairCount;
let centerPt = new Phaser.Math.Vector2(swingChairHeader.x, swingChairHeader.y);
let currChairPos = centerPt.add(Phaser.Math.Vector2.DOWN.scale(radius));
let startIndex = -(maxSwingChairCount / 2);
// creat the swing chairs
for (var index = startIndex; index <= maxSwingChairCount / 2; ++index) {
let swingChair = this.add.image(swingChairHeader.x, swingChairHeader.y, "SwingChair");
swingChair.setOrigin(0.5, -0.5);
let rotAngle = index * angleSpacing;
swingChair.angle += rotAngle;
this.add.tween({
targets: swingChair,
angle: { from: swingChair.angle + 20, to: swingChair.angle - 20 },
duration: 700,
repeat: -1,
yoyo: true
});
}
// create the star for swing chair
this.swingChairStar = this.add.image(swingChairBase.x, swingChairBase.y - 180, "StarIcon").setInteractive();
// starIcon pulse
let swingChairTween = this.add.tween({
targets: this.swingChairStar,
scaleX: 1.1,
scaleY: 1.1,
duration: 300,
yoyo: true,
repeat: -1
});
// star on click
this.swingChairStar.once('pointerup',
() => {
// stop the idle pulse
swingChairTween.stop();
this.sound.play('Correct_SFX');
this.sound.play('SwingChair_SFX');
--this.starsToCollect;
this.scene.get("HomePage").attainStar(this.swingChairStar.x, this.swingChairStar.y, this.swingChairStar, this, false);
});
// create bumper car word
let swingChairWord = this.add.image(swingChairBase.x + 230, swingChairBase.y + 45, "SwingChairWord");
let currAudioBtn = this.add.image(swingChairWord.x + 60, swingChairWord.y, "AudioButton").setScale(0.6, 0.6).setInteractive();
currAudioBtn.on('pointerdown', this.scene.get('HomePage').buttonAnimEffect.bind(this, currAudioBtn, () => this.sound.play('SwingChair_SFX')));
}
createBumperCar() {
let collisionPt = new Phaser.Math.Vector2(config.width / 2 + 250, config.height / 2);
let carA = this.add.image(0, collisionPt.y, "BumperCar_A");
let carB = this.add.image(config.width, collisionPt.y, "BumperCar_B");
// create bumper car word
let bumperCarWord = this.add.image(collisionPt.x, collisionPt.y - 30, "BumperCarWord");
let currAudioBtn = this.add.image(bumperCarWord.x + 60, bumperCarWord.y, "AudioButton").setScale(0.6, 0.6).setInteractive();
currAudioBtn.on('pointerdown', this.scene.get('HomePage').buttonAnimEffect.bind(this, currAudioBtn, () => this.sound.play('BumperCar_SFX')));
// create the hidden star
let bumperCarStar = this.add.image(collisionPt.x, collisionPt.y + 30, "StarIcon").setInteractive();
bumperCarStar.visible = false;
// show star upon first collision
this.time.delayedCall(this.bumperCarSpeed * 0.4, function () { bumperCarStar.visible = true; }, [], this);
// starIcon pulse
let bumperCarStarTween = this.add.tween({
targets: bumperCarStar,
scaleX: 1.1,
scaleY: 1.1,
duration: 300,
yoyo: true,
repeat: -1
});
bumperCarStar.once('pointerup',
() => {
// stop the idle pulse
bumperCarStarTween.stop();
this.sound.play('Correct_SFX');
this.sound.play('BumperCar_SFX');
--this.starsToCollect;
this.scene.get("HomePage").attainStar(bumperCarStar.x, bumperCarStar.y, bumperCarStar, this, false);
});
this.add.tween({
targets: carA,
x: collisionPt.x - carA.width / 2,
duration: this.bumperCarSpeed,
ease: 'Bounce.easeOut'
});
this.add.tween({
targets: carB,
x: collisionPt.x + carB.width / 2,
duration: this.bumperCarSpeed,
ease: 'Bounce.easeOut'
});
}
createTrain() {
this.trainGroup = this.add.group();
let train = this.trainGroup.create(-200, config.height / 2 - 50, "Train").setScale(1);
this.trainGroup.create(train.x, train.y + 30, "TrainWheels").setScale(1);
// add the word tag
let trainWord = this.trainGroup.create(train.x, train.y - 50, "TrainWord");
// offset the origin so it follows train nicely
trainWord.setOrigin(1.2, 0.6);
let currAudioBtn = this.trainGroup.create(trainWord.x, trainWord.y, "AudioButton").setScale(0.6, 0.6).setInteractive();
currAudioBtn.on('pointerdown', this.scene.get('HomePage').buttonAnimEffect.bind(this, currAudioBtn, () => this.sound.play('TrainWord_SFX')));
currAudioBtn.setOrigin(2.0, 0.6);
// add star icon last
let starIcon = this.trainGroup.create(train.x, train.y - 50, "StarIcon").setInteractive();
// starIcon pulse
let trainStarIconTween = this.add.tween({
targets: starIcon,
scaleX: 1.1,
scaleY: 1.1,
duration: 300,
yoyo: true,
repeat: -1
});
// star on click
starIcon.once('pointerup',
() => {
// stop the idle pulse
trainStarIconTween.stop();
this.sound.play('Correct_SFX');
this.sound.play('TrainWord_SFX');
--this.starsToCollect;
this.scene.get("HomePage").attainStar(starIcon.x, starIcon.y, starIcon, this, false);
});
// train drive from left to right
this.add.tween({
targets: this.trainGroup.getChildren(),
x: config.width + 200,
duration: 30000,
repeat: -1,
repeatDelay: 1000
});
// move up down train effect
this.add.tween({
targets: train,
y: '-=5',
duration: 200,
yoyo: true,
repeat: -1
});
}
//Create ferris wheel and it's carriages
createFerrisWheel() {
let ferrisWheelBase = this.add.image(150, 320, "FerrisWheel_Base");
// adding wheel and spinning it
this.ferrisWheel = this.add.image(ferrisWheelBase.x, ferrisWheelBase.y - 100, "FerrisWheel_Wheel");
this.ferrisWheelRotCenter = new Phaser.Math.Vector2(this.ferrisWheel.x, this.ferrisWheel.y + 30);
var maxCarriageCount = 5;
let angleSpacing = 360 / maxCarriageCount;
this.carriageGroup = this.add.group();
// adding ferris wheel word and audio btn
let wordTag = this.add.image(150, 420, "FerrisWheelWord");
let currAudioBtn = this.add.image(wordTag.x + 60, wordTag.y, "AudioButton").setScale(0.6, 0.6).setInteractive();
currAudioBtn.on('pointerdown', this.scene.get('HomePage').buttonAnimEffect.bind(this, currAudioBtn, () => this.sound.play('FerrisWheelWord_SFX')));
for (var index = 0; index < maxCarriageCount; ++index) {
let radius = 0.1;
// rotate dir along circle to create the carriages
var offsetDir = new Phaser.Math.Vector2(radius, 0);
let rotAngle = index * angleSpacing * Math.PI / 180;
offsetDir.rotate(rotAngle);
let carriagePos = new Phaser.Math.Vector2(this.ferrisWheel.x, this.ferrisWheel.y + 30);
offsetDir.scale(radius);
carriagePos = carriagePos.add(offsetDir);
// preparing a group for carriages
this.carriageGroup.create(carriagePos.x, carriagePos.y, 'FerrisWheel_Carriage').setScale(0.7);
// add hidden star
if (index == 0) {
this.ferrisWheelStarIcon = this.carriageGroup.create(carriagePos.x, carriagePos.y, "StarIcon").setInteractive().setScale(1);
this.ferrisWheelStarIcon.once('pointerup',
() => {
this.carriageGroup.remove(this.ferrisWheelStarIcon);
// stop the idle pulse
this.starIconTween.stop();
this.sound.play('Correct_SFX');
this.sound.play('FerrisWheelWord_SFX');
--this.starsToCollect;
this.scene.get("HomePage").attainStar(this.ferrisWheelStarIcon.x, this.ferrisWheelStarIcon.y, this.ferrisWheelStarIcon, this, false);
});
// pulse
this.starIconTween = this.add.tween({
targets: this.ferrisWheelStarIcon,
scaleX: this.ferrisWheelStarIcon.scaleX * 1.1,
scaleY: this.ferrisWheelStarIcon.scaleY * 1.1,
duration: 300,
yoyo: true,
repeat: -1
});
}
}
}
update() {
this.scene.get("HomePage").genericGameSceneUpdate(this);
// rotate the ferris wheel
Phaser.Actions.RotateAroundDistance(this.carriageGroup.getChildren(), this.ferrisWheelRotCenter, this.ferrisWheelRotSpeed, 122);
this.ferrisWheel.angle += this.ferrisWheelRotSpeed * 50;
}
// game timer expired
onTimerExpired() {
this.scene.get("HomePage").gameOver(this);
}
checkGameOverCondition() {
if (this.starsToCollect <= 0) {
this.scene.get("HomePage").gameOver(this);
}
}
}
|
Python | UTF-8 | 1,965 | 2.796875 | 3 | [] | no_license | from flask import Flask, request
from flask_restful import Resource, Api
from date_utils import DateUtils
from timezone_utils import TimeZoneUtils
from coordination_utils import CoordinationUtils
app = Flask(__name__, template_folder="templates")
api = Api(app)
def to_float(input, var_name):
try:
return float(input)
except:
raise TypeError(str.format("TypeError: %s with value %s can't be converted to float." % (var_name, input)))
# class used for the REST API
class GlareDetection(Resource):
# method
def post(self):
try:
# get input data as json and read required fields
some_json = request.get_json()
lat = to_float(some_json['lat'], 'lat')
long = to_float(some_json['long'], 'long')
epoch = to_float(some_json['epoch'], 'epoch')
orientation = to_float(some_json['orientation'], 'orientation')
if (lat < 0 or lat > 90):
raise ValueError("ValueError: lat out of range = [0 to 90]")
elif (long < -180 or long > 180):
raise ValueError("ValueError: long out of range = [-180 to 180")
elif (orientation < -180 or orientation > 180):
raise ValueError("ValueError: orientation out of range = [-180 to 180]")
elif (epoch < 0):
raise ValueError("ValueError: epoch out of range = [epoch > 0]")
else:
# create objects
tz_utils = TimeZoneUtils()
date_utils = DateUtils(tz_utils)
coord_utils = CoordinationUtils(date_utils, lat, long, epoch, orientation)
# compute glare and return results
return ({'glare': coord_utils.detect_glare()})
except Exception as e:
print(e)
return ({'Error': str(e)})
api.add_resource(GlareDetection, '/detect_glare')
if __name__ == '__main__':
app.run(debug=True)
|
C# | UTF-8 | 2,576 | 2.59375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SteamCNHelper
{
[Serializable]
class ForumThread
{
public int ID { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public DateTime PostTime { get; set; }
public DateTime LastModifiedTime { get; set; }
public ItemLine[] Lines { get; set; }
public ForumThread(string url)
{
string source;
try
{
source = Poster.GetStatic(url, Poster.LoginCookie).Replace("\t","");
}
catch(Exception e)
{
throw e;
}
ID = int.Parse(Common.StrBetween(url, "tid-", ".html"));
Name = Common.StrBetween(source, "<h3>", "</h3>");
Author = Common.StrBetween(source, "<p class=\"author\">\n<strong>", "</strong>");
//string tempTime = Common.StrBetween(source, "</strong>\n发表于 ", " </p>");
//if (tempTime[0] == '<')
//{
// tempTime = Common.StrBetween(tempTime, "<span title=\"", "\">");
//}
//PostTime = DateTime.Parse(tempTime);
//if (source.IndexOf("<h3>" + Name + "</h3>\n本帖最后由 " + Author + " 于 ") >= 0)
//{
// LastModifiedTime = DateTime.Parse(Common.StrBetween(source, "本帖最后由 " + Author + " 于 ", " 编辑 <br/>"));
//}
//else LastModifiedTime = PostTime;
string wholeThread = Common.StrBetween(source, "<p class=\"author\">\n", "<div class=\"page\">");
int pos = wholeThread.IndexOf("<p class=\"author\">");
if (pos >= 0)
{
wholeThread = wholeThread.Substring(0, pos);
}
string[] strlines = wholeThread.Replace("<br/>", "").Replace(" ", " ").Split('\n').Where(s => (s.Length < 4 || s.Substring(0, 4) != "<h3>") && s != "").ToArray();
int n = strlines.Length;
Lines = new ItemLine[n];
float context = 0f;
for (int i = 0; i < n; ++i)
{
string str = strlines[i];
float tmpContext;
if (Extractor.IsPriceContext(str, out tmpContext))
{
context = tmpContext;
}
Lines[i] = new ItemLine(str, Extractor.GetSellingItemPrice(str, context), ID);
}
}
}
}
|
Java | TIS-620 | 13,642 | 1.835938 | 2 | [] | no_license | /*
* PanelPregnanceANCPCU.java
*
* Created on 13 չҤ 2549, 15:33 .
*/
package com.generalpcu.gui.panel;
import com.generalpcu.control.ManageControlSubject;
import com.generalpcu.usecase.AllPanelSubject;
import com.generalpcu.usecase.GUISubject;
import com.generalpcu.control.ComboBoxControl;
import com.generalpcu.control.GeneralPCUControl;
import com.generalpcu.usecase.AllPanelResp;
import com.generalpcu.usecase.GUIResp;
import com.generalpcu.usecase.CardNameControl;
import com.generalpcu.utility.ComboboxModel;
import com.generalpcu.utility.Constant;
import com.generalpcu.utility.Report;
import com.generalpcu.gui.panel.DialogShowStatus;
import com.generalpcu.utility.Language;
import com.generalpcu.utility.TableModelGUI;
import javax.swing.table.DefaultTableCellRenderer;
import java.util.Vector;
import javax.swing.JOptionPane;
/**
*
* @author pu
*/
public class PanelPregnanceANCPCU extends javax.swing.JPanel implements
AllPanelResp,GUIResp,CardNameControl,Runnable
{
ManageControlSubject theMCS;
DialogShowStatus theDialogShowStatus;
ComboboxModel theComboboxModel;
DefaultTableCellRenderer rendererCenter;
DefaultTableCellRenderer rendererRight;
TableModelGUI theTableModelGUI;
Vector vVillage;
Vector vcData;
private String cardName;
private String startDate;
private String endDate;
private String[] headColumn ;
private Vector vcDataQuery;
private String village;
Thread theThread;
private boolean isDbBackup;
/**
* Creates new form PanelPregnanceANCPCU
*/
public PanelPregnanceANCPCU(ManageControlSubject mcs)
{
theMCS = mcs;
theMCS.theManageSubject.theGUISubject.registerGUIManage(this);
theMCS.theManageSubject.theAllPanelSubject.registerAllPanelManage(this);
initComponents();
cardName = ((Report)Constant.Report.get("5")).ENG_NAME;
theDialogShowStatus = new DialogShowStatus(theMCS.theUS.getJFrame(),false,theMCS);
theComboboxModel = new ComboboxModel();
setLanguage();
initComboBoxVillage();
}
private void initComboBoxVillage()
{
this.vVillage = this.theMCS.theManageControl.theComboBoxControl.listVillage();
theComboboxModel.initComboBox(this.jComboBoxVillage, this.vVillage);
theComboboxModel.setCodeComboBox(this.jComboBoxVillage, "0");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents()
{
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jLabelDescription = new javax.swing.JLabel();
jLabelVillage = new javax.swing.JLabel();
jComboBoxVillage = new javax.swing.JComboBox();
jPanel2 = new javax.swing.JPanel();
fixedColumnScrollPane1 = new com.hospital_os.utility.FixedColumnScrollPane();
jTablePregnance = new javax.swing.JTable();
setLayout(new java.awt.GridBagLayout());
jPanel1.setLayout(new java.awt.GridBagLayout());
jLabelDescription.setFont(new java.awt.Font("Dialog", 1, 12));
jLabelDescription.setText("Description");
jPanel1.add(jLabelDescription, new java.awt.GridBagConstraints());
jLabelVillage.setText("Village");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
jPanel1.add(jLabelVillage, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0);
jPanel1.add(jComboBoxVillage, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(3, 5, 0, 3);
add(jPanel1, gridBagConstraints);
jPanel2.setLayout(new java.awt.GridBagLayout());
jTablePregnance.setModel(new javax.swing.table.DefaultTableModel(
new Object [][]
{
},
new String []
{
}
));
jTablePregnance.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
fixedColumnScrollPane1.setViewportView(jTablePregnance);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel2.add(fixedColumnScrollPane1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 6, 0, 3);
add(jPanel2, gridBagConstraints);
}
// </editor-fold>//GEN-END:initComponents
/**
* 㹡ѺŨҡ ä 觤 panel
* ӡ Query Ф¡õ͡˹ͧ panel
* @param startDate String ѹ ٻẺ yyyy-mm-dd
* @param endDate String ѹش ٻẺ yyyy-mm-dd
**/
public void setQueryReport(String startDate, String endDate, boolean dbBackup)
{
this.startDate = startDate;
this.endDate = endDate;
isDbBackup = dbBackup;
startQuery();
}
private void startQuery()
{
theThread = new Thread(this);
theThread.start();
}
/**
*ҷҡô֧
*@return Vector ͧŷҡô֧§ҹ
*@Author pu
*@Date 13/03/2006
*/
public Vector getPregnancePCU()
{
return this.vcData;
}
public String getCardName()
{
return this.cardName;
}
public void notifySetInitAllGUI()
{
clearDataGUI();
}
public void notifyStopProcess()
{
try
{
if(theThread != null)
{
theThread.stop();
}
theThread = null;
System.out.println("In stop in PanelPregnancePCU");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void run()
{
this.village = this.theComboboxModel.getCodeComboBox(jComboBoxVillage);
queryPregnanceANCByDate();
}
/**
*Ң§ҹӹǹäԴ ѹ ش
*@Author pu
*@Date 23/02/2006
*/
private void queryPregnanceANCByDate()
{
if(this.theMCS.theManageControl.theGeneralPCUControl.setDateForQuery(this.startDate, this.endDate))
{
theDialogShowStatus.setVisible(true);
theDialogShowStatus.showDialog(Language.getTextBundle("PleaseWait"),false);
this.vcData = this.theMCS.theManageControl.theGeneralPCUControl.queryPregnanceANC(this.village, isDbBackup);
headColumn = new String[] {""};
vcDataQuery = null;
if(vcData != null)
{
headColumn = (String[])vcData.get(0);
vcDataQuery = (Vector)vcData.get(1);
}
showDataInTable(headColumn, vcDataQuery);
theDialogShowStatus.setVisible(false);
}
else
showMessageStartYearOver();
}
/**㹡 Clear ŷ躹ҧ*/
private void clearDataGUI()
{
vcData = null;
showDataInTable(null,null);
System.out.println("Clear Data in GUI");
}
/**ʴͤ ѹ ѹش ͧ ջ ǡѹ*/
private void showMessageStartYearOver()
{
JOptionPane.showMessageDialog(this, Language.getTextBundle("StartYearNotSameEndYear"),Language.getTextBundle("Warning"),JOptionPane.OK_OPTION);
}
private void showDataInTable(String[] columnname,Vector vc)
{
String[] col = columnname;
int size = 0;
if(vc != null)
{ theTableModelGUI= new TableModelGUI(col,vc.size());
size = vc.size();
//ǹٻ 1
for(int i=0 ;i<size; i++)
{ //ǹٻͧ column
String[] rowdata = (String[])vc.get(i);
for(int j = 0 ; j < rowdata.length ;j++)
{
theTableModelGUI.setValueAt(rowdata[j],i,j);
}
theTableModelGUI.setEditingCol(rowdata.length+1);
rowdata = null;
}
}
else
{ theTableModelGUI= new TableModelGUI(col,0);
}
this.jTablePregnance.setModel(theTableModelGUI);
//pu : Fix column áͧ GUI Ѻ
if(col!= null && col.length!= 0)
{
fixedColumnScrollPane1.setFixedColumnScrollPane(jTablePregnance, 1, 80);
//fixedColumnScrollPane1.setFixedColumnScrollPane(jTablePregnance, 2, 150);
setTableListReportPattern(col);
}
else
{
fixedColumnScrollPane1.setFixedColumnScrollPane(jTablePregnance, 0, 50);
setTableListReportPattern(new String[0]);
}
sendDataToMainReport(size);
}
/**㹡ʴҧͧ
*@param col Array ͧ String column ѺҹѺӹǹ Column ͧҧ㹵ҧ
*
*/
private void setTableListReportPattern(String [] col)
{
if(rendererCenter == null )
{
rendererCenter = new DefaultTableCellRenderer();
}
if(rendererRight == null)
{
rendererRight = new DefaultTableCellRenderer();
}
rendererCenter.setHorizontalAlignment(javax.swing.JLabel.CENTER);
rendererRight.setHorizontalAlignment(javax.swing.JLabel.RIGHT);
String[] col_number = col;
int size = col_number.length;
for(int i=0;i<size-1;i++)
{
if(i==0)
{
jTablePregnance.getColumnModel().getColumn(i).setPreferredWidth(150);
}
else if(i==1)
{
jTablePregnance.getColumnModel().getColumn(i).setPreferredWidth(150);
}
else if(i==2)
{
jTablePregnance.getColumnModel().getColumn(i).setCellRenderer(rendererRight);
jTablePregnance.getColumnModel().getColumn(i).setPreferredWidth(100);
}
else
{
jTablePregnance.getColumnModel().getColumn(i).setPreferredWidth(150);
}
}
}
/**
* 㹡ʶҹʴ ѹ֡ ¨еǨͺҡ size ͧҧ
*/
private void sendDataToMainReport(int size)
{
theMCS.theManageSubject.theMainReportSubject.notifyShowSaveToFile(false);
if(size >0)
{
theMCS.theManageSubject.theMainReportSubject.notifyShowSaveToFile(true);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private com.hospital_os.utility.FixedColumnScrollPane fixedColumnScrollPane1;
private javax.swing.JComboBox jComboBoxVillage;
private javax.swing.JLabel jLabelDescription;
private javax.swing.JLabel jLabelVillage;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTable jTablePregnance;
// End of variables declaration//GEN-END:variables
public void setLanguage()
{
jLabelDescription.setText(Language.getTextBundle(jLabelDescription.getText()));
jLabelVillage.setText(Language.getTextBundle(jLabelVillage.getText()));
}
}
|
Java | UTF-8 | 1,723 | 2.3125 | 2 | [] | no_license | package XMLCreation;
import java.io.File;
import java.io.UnsupportedEncodingException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import contants.TalentifyClientsConstants;
import services.TestSuiteServices;
import testCasePOJO.TestCase;
import testCasePOJO.TestSuite;
public class XMLServices {
public JSONArray readTestSuites() throws JAXBException, JSONException, UnsupportedEncodingException {
TestSuiteServices services = new TestSuiteServices();
JSONArray testSuiteJsonArray = new JSONArray();
File testSuiteFolder = new File(TalentifyClientsConstants.TestSuitePath);
JAXBContext context = JAXBContext.newInstance(TestSuite.class);
for (File testSuiteFile : testSuiteFolder.listFiles()) {
Unmarshaller unmarshaller = context.createUnmarshaller();
TestSuite suite = (TestSuite) unmarshaller.unmarshal(testSuiteFile);
JSONObject testSuiteJsonObject = new JSONObject();
testSuiteJsonObject.put("id", suite.getId());
testSuiteJsonObject.put("name", suite.getName());
JSONArray testCasesJsons = new JSONArray();
for (TestCase testCase : suite.getTestCase()) {
JSONObject testCaseJsonObject = new JSONObject();
testCaseJsonObject.put("name", testCase.getName());
testCaseJsonObject.put("URL", testCase.getUrl());
testCaseJsonObject.put("body",
services.getBody(testCase, services.getRuntimeVariablesConstants(suite)));
testCasesJsons.put(testCaseJsonObject);
}
testSuiteJsonObject.put("testCases", testCasesJsons);
testSuiteJsonArray.put(testSuiteJsonObject);
}
return testSuiteJsonArray;
}
}
|
Python | UTF-8 | 1,851 | 2.890625 | 3 | [] | no_license | import model
import csv
from datetime import datetime
def load_users(session, filename):
# use u.user
with open(filename, 'rb') as csvfile:
lines = csv.reader(csvfile, delimiter = '|')
for line in lines:
user = model.User()
user.user_id = line[0].strip()
user.age = line[1].strip()
user.zipcode = line[4].strip()
session.add(user)
session.commit()
def load_movies(session, filename):
# use u.item
with open(filename, 'rb') as csvfile:
lines = csv.reader(csvfile, delimiter = '|')
for line in lines:
movie = model.Movie()
movie.movie_id = line[0].strip()
movie.title = line[1].strip()
movie.title = movie.title[:-6]
movie.title = movie.title.decode("latin-1").strip()
movie.release_date = datetime.strptime(line[2].strip(),"%d-%b-%Y")
movie.imdb = line[4].strip()
session.add(movie)
session.commit()
def load_ratings(session, filename):
# use u.data
# when running for real, remove echo = true
with open(filename, 'rb') as temp_file:
for line in temp_file:
line = line.split()
rating = model.Rating()
rating.user_id = line[0].strip()
rating.movie_id = line[1].strip()
rating.rating = line[2].strip()
session.add(rating)
session.commit()
def main(session):
# when running for real, remove echo = true
# You'll call each of the load_* functions with the session as an argument
# load_movies(session, 'seed_data/u.item')
#load_ratings(session, 'seed_data/u.data')
# load_users(session,'seed_data/u.user')
if __name__ == "__main__":
s= model.connect()
main(s) |
Markdown | UTF-8 | 1,599 | 2.9375 | 3 | [
"MIT"
] | permissive | ## ZEV_induction_30min_delay
The goal of this experiment is to determine how induction performs on the McIsaac ZEV strains under a 30 minute flooding time when flooding plates with SC+2% galactose media (used to resuspend cells growing on an agarose plate). For this experiment we are testing induction on the CBF1 strain.
The basic procedure is to grow cells on agarose plates with synthetic complete medium plus 2% galactose (SCGal), resuspend cells by flooding the plates with a liquid and resuspending with a loop, add an estradiol dissolved in ethanol or just the ethanol (mock inducer), and take samples for RNA-Seq just before and at time points after the inducer or mock inducer has been added.
The fields needed to differentiate all the samples are
floodMedia -- the fluid used to resuspend cells growing on plates. One of:
• SCGal
inductionDelay -- the time between resuspension of cells and addition of inducer or mock inducer.
• 30 -- inducer or mock inducer added 30 minutes after cells are resuspended
treatment -- the inducer or mock inducer added. One of:
• Estradiol -- the ZEV inducer, dissolved in ethanol
• EtOH -- ethanol only, equal volume to the true induction
timePoint -- the time between addition of the inducer or mock inducer and cell harvesting. One of:
• -1 -- cells harvested 1 minute before addition of inducer or mock inducer
• 15 -- cells harvested 15 minutes after addition of inducer or mock inducer
• 90 -- cells harvested 90 minutes after addition of inducer or mock inducer
Details of the experiment design
|
JavaScript | UTF-8 | 22,985 | 2.71875 | 3 | [] | no_license | /**
* Created by sks on 2016/4/8.
*/
/**
* 人员选择器
*/
;(function(NAME, $) {
var _zIndex = 10000;
var zIndex = function() {
return ++_zIndex;
};
/**
* 组件类
* @param element
* @param options
* @constructor
*/
var Component = function() {
this._init.apply(this, Array.prototype.slice.call(arguments));
};
/**
* 组件的实现方法
*/
Component.prototype = {
constructor: Component,
/**
*
* @private
*/
_init: function(options) {
// var scrollTop=document.body.scrollTop;
// window.onscroll=function(){
// document.body.scrollTop = scrollTop;
// }
$('body').css('overflow','hidden');
this._setOptions(options);
if(options.type==1) {
this._enterHTML();
}else if(options.type==2){
this._nobtnHTML();
}else this._buildHTML();
},
/**
* 设置参数
* @param options
* @private
*/
_setOptions: function(options) {
this._options = $.extend({
parent: document.body
}, options);
},
/**
* 构建html
* @private
*/
_buildHTML: function() {
var options = this._options;
// 构建html
var html = [];
html.push('<div class="dialog-mask" style="display: none;">');
html.push('<div class="dialog-box">');
html.push('<div class="dialog-head clearfix">');
html.push('<h4 class="dialog-title">' + options.title + '</h4><a class="dialog-close" href="javascript:void(0)"></a>');
html.push('</div>');
html.push('<div class="dialog-body">');
html.push(options.body);
html.push('</div>');
html.push('</div>');
html.push('</div>');
var el = this._el = $(html.join('')).appendTo(this._options.parent);
// 获得基本控制元素
this._bodyEl = el.find('.dialog-body');
// 绑定事件
el.find(".dialog-close").click(this._onClickClose.bind(this));
},
/**
* 构建title 居中html
* @private
*/
_enterHTML: function() {
var options = this._options;
// 构建html
var html = [];
html.push('<div class="dialog-mask" style="display: none;">');
html.push('<div class="dialog-custom-box">');
html.push('<h4 class="dialog-custom-title">' + options.title + '</h4><a class="dialog-close" href="javascript:void(0)"></a>');
html.push('<div class="dialog-body">');
html.push(options.body);
html.push('</div>');
html.push('</div>');
html.push('</div>');
var el = this._el = $(html.join('')).appendTo(this._options.parent);
// 获得基本控制元素
this._bodyEl = el.find('.dialog-body');
// 绑定事件
el.find(".dialog-close").click(this._onClickClose.bind(this));
},
_nobtnHTML: function() {
var options = this._options;
// 构建html
var html = [];
html.push('<div class="dialog-mask" style="display: none;">');
html.push('<div class="dialog-box-no">');
html.push('<div class="dialog-head clearfix">');
html.push('<h4 class="dialog-title">' + options.title + '</h4>');
html.push('</div>');
html.push('<div class="dialog-body">');
html.push(options.body);
html.push('</div>');
html.push('</div>');
html.push('</div>');
var el = this._el = $(html.join('')).appendTo(this._options.parent);
// 获得基本控制元素
this._bodyEl = el.find('.dialog-body');
// 绑定事件
el.find(".dialog-close").click(this._onClickClose.bind(this));
},
/**
* 获得body容器对象
*/
getBodyEl: function() {
return this._bodyEl;
},
/**
* 单击关闭按钮后的处理方法
* @private
*/
_onClickClose: function() {
if($(".dialog-close").hasClass("stopevent")) return false;
var closeFn = this._options.close;
if (typeof closeFn == "function") closeFn(this);
this.destroy();
this.destroy();
},
/**
* 显示dialog
* @private
*/
show: function() {
this._el.css("zIndex", "99");
this._set2center(false);
this._el.show();
return this;
},
/**
* 隐藏dialog
* @private
*/
_hide: function() {
if(this._el){this._el.hide()};
// window.onscroll=null;
$('body').css('overflow','auto');
return this;
},
/**
* 设置到正中间
* @private
*/
_set2center: function(isHidden) {
// fixme
},
/**
* 重新设置位置
*/
resetPosition: function() {
this._set2center();
return this;
},
/**
* 销毁
*/
destroy: function() {
this._hide();
this._options = null;
this._bodyEl = null;
if(this._el) this._el.html('');
if(this._el) this._el = null;
// window.onscroll=null;
$('body').css('overflow','auto');
}
};
/*
页面中用弹窗中嵌入iframe页面
*/
var loadIframePage=function(options) {
$(".dialog-iframe-page").remove();
var opts = $.extend({
url : '', //内容
title :"支付宝付款",
top : '60',
width : '800', //宽度
height : '520', //高度
close : null //关闭回调函数
}, options || {});
var html="<div class='dialog-iframe-page'>";
html+= "<div style='top:"+opts.top+"px;width:"+opts.width+"px;height:"+opts.height+"px;margin-left:-"+parseInt(opts.width)/2+"px;' class='dialog-iframe-content'>";
html+= "<div class='dialog-iframe-title'>"+opts.title+"</div>";
html+= "<div class='dialog-iframe-loading'><div class='dialog-iframe-loading-img'></div></div>";
html+= "<a href='javascript:;' class='dialog-iframe-close'></a>";
html+= '<iframe onload="dialogHideIframe()" class="dialog-iframe-cont" width="'+opts.width+'" height="'+opts.height+'" sandbox="allow-forms allow-scripts allow-same-origin allow-top-navigation" frameborder="0" src="'+opts.url+'"></iframe>';
html+= "</div>";
html+= "</div>";
$("body").append(html);
$("body").on("click",".dialog-iframe-close",function(){
$(".dialog-iframe-page").remove();
// window.onscroll=null;
$('body').css('overflow','auto');
if(opts.close&&typeof opts.close == "function") opts.close();
})
window.dialogHideNum=0;
window.dialogHideIframe=function(){
if(window.dialogHideNum==1&&opts.title=="支付宝付款"){
window.dialogHideNum=0;
$(".dialog-iframe-loading").hide();
return false;
}else if(opts.title!="支付宝付款"){
$(".dialog-iframe-loading").hide();
}
window.dialogHideNum=1;
}
};
/**
* 显示dialog
* @param title
* @param content
* @param sureCallback
* @param cancelCallback
* @returns {*}
*/
var showDialog = function(title, content, sureCallback, cancelCallback,btnlefttext,btnrighttext) {
var isShowCancel = typeof cancelCallback == "function";
// 构建内容部分的html
var html = ['<div class="dialog-content">' + content + '</div>'];
html.push('<div class="dialog-action">');
html.push('<button type="button" class="dialog-sure">'+(btnlefttext?btnlefttext:"确认")+'</button>');
if (isShowCancel) html.push('<button type="button" class="dialog-cancel">'+(btnrighttext?btnrighttext:"取消")+'</button>');
html.push('</div>');
// 创建dialog
var dialog = new Dialog({
title: title,
body: html.join(''),
close: function() {
$('body').css('overflow','auto');
if (isShowCancel) cancelCallback(bodyEl);
}
});
// 获取控制元素
var bodyEl = dialog.getBodyEl();
var sureBtn = bodyEl.find('.dialog-sure');
// 绑定事件
sureBtn.click(function() {
var state ;
if (typeof sureCallback == "function") state=sureCallback(bodyEl);
console.log(state)
// 返回prevent 阻断弹窗销毁
if(state != 'prevent'){
dialog.destroy();
}
});
if (isShowCancel) {
bodyEl.find('.dialog-cancel').click(function() {
if($(this).hasClass("stopevent")) return false;
cancelCallback(bodyEl);
dialog.destroy();
});
}
// 显示dialog
return dialog.show();
};
/**
* 显示dialog
* @param title
* @param content
* @param sureCallback
* @param cancelCallback
* @returns {*}
*/
var nocheckDialog = function(title, content, sureCallback, cancelCallback,btnlefttext,btnrighttext) {
var isShowCancel = typeof cancelCallback == "function";
// 构建内容部分的html
var html = ['<div class="dialog-content">' + content + '</div>'];
html.push('<div class="dialog-action">');
html.push('</div>');
// 创建dialog
var dialog = new Dialog({
title: title,
type:2,
body: html.join(''),
close: function() {
$('body').css('overflow','auto');
if (isShowCancel) cancelCallback(bodyEl);
}
});
// 获取控制元素
var bodyEl = dialog.getBodyEl();
// // 显示dialog
setTimeout(function(){
$('.dialog-mask').hide();
// window.onscroll=null;
$('body').css('overflow','auto');
},1700);
return dialog.show();
};
var customDialog = function(title, content, sureCallback, cancelCallback,btnlefttext,btnrighttext) {
var isShowCancel = typeof cancelCallback == "function";
// 构建内容部分的html
var html = ['<div class="dialog-custom-content">' + content + '</div>'];
html.push('<div class="dialog-custom-action">');
html.push('<button type="button" class="dialog-sure">'+(btnlefttext?btnlefttext:"确认")+'</button>');
if (isShowCancel) html.push('<button type="button" class="dialog-cancel">'+(btnrighttext?btnrighttext:"取消")+'</button>');
html.push('</div>');
// 创建dialog
var dialog = new Dialog({
title: title,
type:1,
body: html.join(''),
close: function() {
if (isShowCancel) cancelCallback(bodyEl);
}
});
// 获取控制元素
var bodyEl = dialog.getBodyEl();
var sureBtn = bodyEl.find('.dialog-sure');
// 绑定事件
sureBtn.click(function() {
var state ;
if (typeof sureCallback == "function") state=sureCallback(bodyEl);
// console.log(state);
// 返回prevent 阻断弹窗销毁
if(state != 'prevent'){
dialog.destroy();
}
});
if (isShowCancel) {
bodyEl.find('.dialog-cancel').click(function() {
if($(this).hasClass("stopevent")) return false;
cancelCallback(bodyEl);
dialog.destroy();
});
}
// 显示dialog
return dialog.show();
};
var showTips=function(options) {
var opts = $.extend({
target : null, //目标元素,不能为空
position : 't', //提示框相对目标元素位置 t=top,b=bottom,r=right,l=left
align : 'c', //提示框与目标元素的对齐方式,自动调节箭头显示位置,指向目标元素中间位置,c=center, t=top, b=bottom, l=left, r=right [postion=t|b时,align=l|r有效][position=t|b时,align=t|d有效]
arrow : true, //是否显示箭头
content : '', //内容
width : 200, //宽度
height : 'auto', //高度
autoClose : true, //是否自动关闭
time : 2000, //自动关闭延时时长
leaveClose : false, //提示框失去焦点后关闭
close : null //关闭回调函数
}, options || {}),
$ao, $ai, w, h,
$pt = $('.pt'),
$target = $(opts.target),
top = $target.offset().top,
left = $target.offset().left,
width = $target.outerWidth(),
height = $target.outerHeight(),
position = opts.position,
align = opts.align,
arrow = opts.arrow,
constant = {b:'pt-up', t:'pt-down', r:'pt-left', l:'pt-right'}, //相对位置正好和箭头方向相反
arrowClass = constant[position] || constant.t;
//初始化元素,事件
function init() {
if(!opts.target) {
return;
}
if(!$pt.length) {
$pt = $('<div class="pt pt-down"><div class="cont"></div><b class="out"></b><b class="in"></b></div>').appendTo(document.body);
}
$pt.removeClass().addClass('pt ' + (arrow ? arrowClass : '')).find('.cont').html(opts.content).css({width:opts.width, height:opts.height});
$ao = $pt.find('.out').toggle(arrow);
$ai = $pt.find('.in').toggle(arrow);
w = $pt.outerWidth();
h = $pt.outerHeight();
arrow && autoAdjust(); //设置箭头自动居中
$pt.css(setPos()).show(); //设置显示框位置和自动隐藏事件
opts.leaveClose && leaveClose();//离开关闭
opts.autoClose && !opts.leaveClose && autoClose(opts.timeout); //默认自动关闭,优先离开关闭
return $pt;
}
//计算提示框应该出现在目标元素位置
function setPos() {
var btw = arrow ? parseInt($ao.css('border-top-width'), 10) : 3,
brw = arrow ? parseInt($ao.css('border-right-width'), 10) : 3,
result = {};
switch(align) {
case 'c': break;
case 't': result.top = top; break;
case 'b': result.top = top + height - h; break;
case 'l': result.left = left; break;
case 'r': result.left = left + width - w; break;
}
switch(position) {
case 't': result.top = top - h - brw; break;
case 'b': result.top = top + height + brw; break;
case 'l': result.left = left - w - btw; break;
case 'r': result.left = left + width + btw; break;
}
result.top || (result.top = top + height/2 - h/2);
result.left || (result.left = left + width/2 - w/2);
return result;
}
//设置箭头自动居中
function autoAdjust() {
var aop, aip, bw, auto='auto';
switch(position) {
case't':
bw = parseInt($ao.css('border-top-width'), 10);
aop = {bottom:-bw, left:w/2-bw, top:auto, right:auto};
alignLR();
aip = {top:auto, left:aop.left+1, bottom:aop.bottom+1, right:auto};
break;
case'b':
bw = parseInt($ao.css('border-bottom-width'), 10);
aop = {top:-bw, left:w/2 - bw, right:auto, bottom:auto};
alignLR();
aip = {top:aop.top+1, left:aop.left+1, bottom:auto, right:auto};
break;
case'l':
bw = parseInt($ao.css('border-left-width'), 10);
aop = {top:h/2 - bw, right:-bw, left:auto, bottom:auto};
alignTB();
aip = {top:aop.top+1, right:aop.right+1, left:auto, bottom:auto};
break;
case'r':
bw = parseInt($ao.css('border-right-width'), 10);
aop = {top:h/2 - bw, left:-bw, right:auto, bottom:auto};
alignTB();
aip = {top:aop.top+1, left:aop.left+1, right:auto, bottom:auto};
break;
}
//上下侧,左右对齐
function alignLR() {
if(align === 'l' && width/2 > bw && width/2 < w-bw) {
aop.left = width/2-bw/2;
} else if(align === 'r' && width/2 > bw && width/2 < w-bw) {
aop.left = w-width/2-bw/2;
}
}
//左右侧,上下对齐
function alignTB() {
if(align === 't' && height/2 > bw && height/2 < h-bw) {
aop.top = height/2 - bw;
} else if(align === 'b' && height/2 > bw && height/2 < h-bw) {
aop.top = h - height/2 - bw;
}
}
$ao.css(aop);
$ai.css(aip);
}
//设置提示框自动关闭
function autoClose() {
window.ptt && clearTimeout(ptt);
window.pta && clearTimeout(pta);
window.pta = setTimeout(function() {
$pt.hide();
$.isFunction(opts.close) && opts.close();
}, opts.time);
}
//设置提示框失去焦点关闭
function leaveClose() {
//先解绑再绑定,不然会形成事件链
$pt.unbind('mouseleave').mouseleave(function(e) {
$pt.hide();
$.isFunction(opts.close) && opts.close();
}).unbind('mouseenter').mouseenter(function() {
window.ptt && clearTimeout(ptt);
});
}
return init();
};
/**
* 显示信息
* @param message
* @param sureCallback 单击确定按钮指定的方法。注意:如果没有设置此方法,也会显示确定按钮
* @param cancelCallback 单击取消按钮指定的方法。注意:如果没有设置此方法,就不会显示取消按钮
*/
Component.message = function(message, sureCallback, cancelCallback) {
return showDialog("提示", message, sureCallback, cancelCallback);
};
/*
* 自定义title 和确认取消按钮名称
*/
Component.customMessage = function(message, sureCallback, cancelCallback,title,btnlefttext,btnrighttext) {
return showDialog('', message, sureCallback, cancelCallback,btnlefttext,btnrighttext);
};
/*
* 自定义结构内容 和确认取消按钮名称
*/
Component.customsMessage = function(message, sureCallback, cancelCallback,title,btnlefttext,btnrighttext) {
return customDialog(title, message, sureCallback, cancelCallback,btnlefttext,btnrighttext);
};
/**
* 成功信息
* @param message
* @param sureCallback 单击确定按钮指定的方法。注意:如果没有设置此方法,也会显示确定按钮
* @param cancelCallback 单击取消按钮指定的方法。注意:如果没有设置此方法,就不会显示取消按钮
*/
Component.succ = function(message, sureCallback, cancelCallback) {
return nocheckDialog("", '<div class="succ-box c_mt_15 c_box_cen"><img class="succ-img" src="/frontface/Public/news/img/icons/cb/ic_finished.png"/><span class="width0">' + message + '</span></div>', sureCallback, cancelCallback);
};
/**
* 成功信息 注:没有确认与取消按钮!
* @param message
*/
Component.Succ = function(message, sureCallback, cancelCallback) {
return nocheckDialog("", '<div class="succ-box c_mt_15 c_box_cen"><img class="succ-img" src="/frontface/Public/news/img/icons/cb/ic_finished.png"/><span class="width0">' + message + '</span></div>', sureCallback, cancelCallback);
};
/**
* 警示消息
* @param message
* @param sureCallback 单击确定按钮指定的方法。注意:如果没有设置此方法,也会显示确定按钮
* @param cancelCallback 单击取消按钮指定的方法。注意:如果没有设置此方法,就不会显示取消按钮
*/
Component.warn = function(message, sureCallback, cancelCallback) {
return showDialog(" ", '<img src="/frontface/Public/news/js/base/ui/dialog/img/warning.png" class="dialog-warn-imgs"/><span class="warn-msg">' + message + '</span>', sureCallback, cancelCallback);
};
/**
* 错误信息
* @param message
* @param sureCallback 单击确定按钮指定的方法。注意:如果没有设置此方法,也会显示确定按钮
* @param cancelCallback 单击取消按钮指定的方法。注意:如果没有设置此方法,就不会显示取消按钮
*/
Component.error = function(message, sureCallback, cancelCallback) {
return showDialog("", '<img src="/frontface/Public/news/js/base/ui/dialog/img/error.png" class="dialog-error"/><span class="error-mail">' + message + '</span>', sureCallback, cancelCallback);
};
/**
* 错误信息 注:没有确认与取消按钮
* @param message
*/
Component.Error = function(message, sureCallback, cancelCallback) {
return nocheckDialog("", '<img src="/frontface/Public/news/js/base/ui/dialog/img/error.png" class="dialog-error"/><span class="error-mail">' + message + '</span>', sureCallback, cancelCallback);
};
//tips提示窗口
Component.tips=function(option){
return showTips(option);
}
//嵌入iframe加载页面
Component.iframePage=function(option){
return loadIframePage(option);
}
this[NAME] = Component;
}).call(this, "Dialog", jQuery);
/*绑定手机*/
|
C | UTF-8 | 1,624 | 2.53125 | 3 | [
"FSFAP",
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | /** \file archdep_make_backup_filename.c
* \brief Generate a backup filename for a file
* \author Bas Wassink <b.wassink@ziggo.nl>
*/
/*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*
*/
#include "vice.h"
#include "archdep_defs.h"
#include "lib.h"
#include "util.h"
#include "archdep_make_backup_filename.h"
/** \brief Generate backup filename for \a fname
*
* \param[in] fname original filename
*
* \return backup filename (free with libfree())
*/
char *archdep_make_backup_filename(const char *fname)
{
#ifdef ARCGDEP_OS_WIN32
/* For some reason on Windows, we replace the last char with a tilde, which
* ofcourse is stupid idea since the last char could be a tilde.
*/
char *bak = lib_stralloc(fname);
bak[strlen(bak) = 1] = '~';
return bak
#else
return util_concat(fname, "~", NULL);
#endif
}
|
Java | UTF-8 | 562 | 2.15625 | 2 | [
"MIT"
] | permissive | package com.huajiao.comm.chatroomresults;
/**
* 成员退出的通知
* */
public class MemberQuitNotification extends DetailedResult {
private int _total_member_cnt;
public MemberQuitNotification(long sn, int result, byte[] reason, int total_member_count, String roomid, String roomname, String[] members) {
super(sn, result, reason, Result.PAYLOAD_MEMBER_QUIT, roomid, roomname, members);
_total_member_cnt = total_member_count;
}
/**
* @return 获取群成员数
*/
public int get_total_member_cnt() {
return _total_member_cnt;
}
}
|
PHP | UTF-8 | 1,376 | 2.65625 | 3 | [] | no_license | <?php
namespace Security\Mapper;
use Security\Entity\RoleEntityInterface;
use User\Entity\UserEntityInterface;
/**
* @author Rok Mohar <rok.mohar@gmail.com>
* @author Rok Založnik <tugamer@gmail.com>
*/
interface RoleMapperInterface
{
/**
* @param \Security\Entity\RoleEntityInterface $role
*/
public function insertRow(RoleEntityInterface $role);
/**
* @param array $where
* @param array $order
*
* @return mixed
*/
public function selectAll(array $where, array $order);
/**
* @param array $where
* @param array $order
*
* @return mixed
*/
public function selectRow(array $where, array $order);
/**
* @param \Security\Entity\RoleEntityInterface $role
*/
public function updateRow(RoleEntityInterface $role);
/**
* @param \User\Entity\UserEntityInterface $user
* @param \Security\Entity\RoleEntityInterface $role
*/
public function insertRole(UserEntityInterface $user, RoleEntityInterface $role);
/**
* @param \User\Entity\UserEntityInterface $user
* @param \Security\Entity\RoleEntityInterface $role
*/
public function deleteRole(UserEntityInterface $user, RoleEntityInterface $role);
/**
* @param \User\Entity\UserEntityInterface $user
*/
public function selectByUser(UserEntityInterface $user);
}
|
Java | UTF-8 | 2,328 | 2.046875 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package io.github.bpodolski.caspergis.project.project;
import io.github.bpodolski.caspergis.beans.MapBean;
import io.github.bpodolski.caspergis.beans.ProjectBean;
import io.github.bpodolski.caspergis.services.MapListMgr;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import org.openide.util.lookup.Lookups;
/**
*
* @author Bartłomiej Podolski <bartp@poczta.fm>
*/
@ActionID(
category = "Project",
id = "io.github.bpodolski.caspergis.system.action.NewMap"
)
@ActionRegistration(
iconBase = "io/github/bpodolski/caspergis/project/project/project_close.png",
displayName = "#CTL_NewMap"
)
@ActionReferences({
@ActionReference(path = "Menu/Project", position = 30),
@ActionReference(path = "Toolbars/Project", position = 30)
})
@NbBundle.Messages("CTL_NewMap=New Map")
public class NewMap implements ActionListener {
private final ProjectBean context;
public NewMap(ProjectBean context) {
this.context = context;
}
@Override
public void actionPerformed(ActionEvent e) {
DialogDescriptor.InputLine dd = new DialogDescriptor.InputLine("Map name:", "New map Dialog");
dd.setInputText("Layers");
if (DialogDisplayer.getDefault().notify(dd).equals(DialogDescriptor.OK_OPTION) && !dd.getInputText().isEmpty()) {
String s = (String) dd.getInputText();
MapListMgr mapListCoreService = Lookups.forPath("Core").lookupAll(MapListMgr.class).iterator().next();
MapListMgr mapListProjectService = Lookups.forPath("Project").lookupAll(MapListMgr.class).iterator().next();
MapBean mapBean = new MapBean(null,s);
mapListProjectService.add(mapBean, context);
mapListCoreService.add(mapBean, context);
}
}
}
|
C# | UTF-8 | 5,807 | 2.71875 | 3 | [] | no_license | using Discord;
using Discord.WebSocket;
using Modules.NotificationParser;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using YahurrFramework;
using YahurrFramework.Attributes;
namespace Modules
{
[Config(typeof(NotificationModuleConfig))]
[RequiredModule(typeof(JobModule))]
public class NotificationModule : YModule
{
public new NotificationModuleConfig Config
{
get
{
return (NotificationModuleConfig)base.Config;
}
}
private NotificationParser.NotificationParser NotificationParser { get; set; }
private JobModule JobModule { get; set; }
protected override async Task Init()
{
await LogAsync(YahurrFramework.Enums.LogLevel.Message, $"Initializing {this.GetType().Name}...");
NotificationParser = new NotificationParser.NotificationParser(Config);
JobModule = await GetModuleAsync<JobModule>();
await JobModule.RegisterJobAsync<NotificationJob>(SayNotificationJob);
}
#region Commands
/// <summary>
/// PArse a notification useing natural language
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[Example("!reminder 1h 2m say This is a notification to #general")]
[Example("!reminder 1 hour 2 min say This is a notification to #general")]
[Example("!reminder 1h 2m to #general say This is a notification")]
[Example("!reminder to me in 1h 2m say This is a notification")]
[Command("reminder"), Summary("Create a notification using natrual language.")]
public async Task ParseNotifcation(
[Summary("See examples for proper syntax.")] params string[] input)
{
string name = (Message.Author as IGuildUser)?.Nickname ?? Message.Author.Username;
if (!NotificationParser.TryParse(input, name, out NotificationJob job))
{
await RespondAsync("Invalid input.", false, false);
return;
}
await JobModule.AddJobAsync(job);
DateTime time = JobModule.GetNextCall(job);
await RespondAsync($"Notification added for: {time.ToString(Config.OutputTimeFormat)} to {string.Join(',', job.Channels)}", false, false);
}
/// <summary>
/// Get a list of all reminders a person has created
/// </summary>
/// <returns></returns>
[Summary("Get a list of all reminders you have created.")]
[Command("reminder", "list")]
public async Task NotificationList()
{
string name = (Message.Author as IGuildUser).Nickname ?? Message.Author.Username;
List<NotificationJob> jobs = await JobModule.GetJobsAsync<NotificationJob>(x => x.Creator == name);
await RespondAsync($"```Notifications by {name}:\n{NotificationsToString(jobs)}```", false, false);
}
/// <summary>
/// Get a list of all reminders.
/// </summary>
/// <returns></returns>
[Summary("Get a list of all reminders.")]
[Command("reminder", "list", "all")]
public async Task NotificationListAll()
{
List<NotificationJob> jobs = await JobModule.GetJobsAsync<NotificationJob>();
await RespondAsync($"```Notifications:\n{NotificationsToString(jobs)}```", false, false);
}
/// <summary>
/// Delete a notification
/// </summary>
/// <param name="reminder"></param>
/// <returns></returns>
[Summary("Delete a notification.")]
[Command("del")]
public async Task DeleteNotification(
[Summary("Reminder to delete.")]int reminder)
{
string name = (Message.Author as IGuildUser).Nickname ?? Message.Author.Username;
List<NotificationJob> jobs = await JobModule.GetJobsAsync<NotificationJob>(x => x.Creator == name);
if (reminder < 0 || reminder >= jobs.Count)
{
await RespondAsync("Index out of bounds.", false, false);
return;
}
await JobModule.Remove(jobs[reminder]);
await RespondAsync("Reminder removed.", false, false);
}
#endregion
/// <summary>
/// Say a servere notification to the correct channels
/// </summary>
/// <param name="job"></param>
/// <param name="context"></param>
/// <returns></returns>
async Task SayNotificationJob(NotificationJob job, MethodContext context)
{
SetContext(context);
foreach (string channel in job.Channels)
{
switch (channel)
{
case "pm": case "dm": case "me":
IGuildUser user = GetUser(job.Creator, true);
await user?.SendMessageAsync(job.Message);
break;
default:
IMessageChannel messageChannel = GetChannel<SocketGuildChannel>(channel, false) as IMessageChannel;
await messageChannel?.SendMessageAsync(job.Message);
break;
}
}
}
/// <summary>
/// Convert a list of notifications to a presentable string.
/// </summary>
/// <param name="jobs"></param>
/// <returns></returns>
string NotificationsToString(List<NotificationJob> jobs)
{
StringBuilder reply = new StringBuilder();
for (int i = 0; i < jobs.Count; i++)
{
NotificationJob job = jobs[i];
DateTime time = JobModule.GetNextCall(job);
string shorthand = job.Message;
if (shorthand.Length > 40)
shorthand = shorthand.Substring(0, 40) + "...";
reply.Append($"{i}: {time} to {string.Join(',', GetChannels(job.Channels))} by {job.Creator} say {shorthand}\n");
}
if (jobs.Count == 0)
reply.Append("No notifications.");
return reply.ToString();
}
/// <summary>
/// Parse channel names and use original names where it is not a guild channel name.
/// </summary>
/// <param name="channels"></param>
/// <returns></returns>
List<string> GetChannels(List<string> channels)
{
List<string> parsedChannels = new List<string>();
for (int i = 0; i < channels.Count; i++)
{
string channel = channels[i];
ISocketMessageChannel foundChannel = GetChannel<SocketGuildChannel>(channel, false) as ISocketMessageChannel;
parsedChannels.Add(foundChannel?.Name ?? channel);
}
return parsedChannels;
}
}
}
|
JavaScript | UTF-8 | 939 | 2.8125 | 3 | [] | no_license | var firstName = document.querySelector("#firstName");
var lastName = document.querySelector("#lastName");
var username = document.querySelector("#username");
// const email = document.querySelector("#email") as HTMLInputElement
var age = document.querySelector("#age");
var gender = document.querySelector("#gender");
var saveButton = document.querySelector("#saveButton");
var successMessageContainer = document.querySelector("#successMessageContainer");
saveButton.addEventListener("click", function (e) {
e.preventDefault();
window.localStorage.setItem("firstName", firstName.value);
window.localStorage.setItem("lastName", lastName.value);
window.localStorage.setItem("username", username.value);
// window.localStorage.setItem("email", email.value)
window.localStorage.setItem("age", age.value);
window.localStorage.setItem("gender", gender.value);
successMessageContainer.style.display = "block";
});
|
Markdown | UTF-8 | 2,663 | 2.953125 | 3 | [] | no_license | ## 关于宜春话 ##
很遗憾的一件事,就是不会说流利的宜春话,记得有一次做火车和一个大叔侃大山,他说江西就两种话好听,宜春话和萍乡话,一个是我出生的地方,一个是我祖籍的地方,多谢大叔称赞呵呵
不会说的原因是老妈的训练吧,很小就喜欢把我放在电视机前让我看天气预报....不过虽然说不利索,但作为地道的宜春人,还是很喜欢宜春话的,前段时间看校内有人共享宜春话简易教程,简单做一些补充呵呵
1.宜春话中的智慧
基本学所有的方言,都是从骂人开始的,宜春话中比较常用的一种说法是现世,引自中国古典某著名小说,原用为现世活宝,后简化为现世宝,在宜春话里简称现世,指一个人丢人现眼,发音略有不同/sian shi/都发第一声,拟声为/先失/
然后一句是用来表扬人的,拟声为/迂斯掰贴/,懂的人都该知道的,指干净,整洁,好的意思,这也是有出处的,原用为熨(yu第四声)帖,指干净,这个词基本上很少在现代汉语里用到,但在宜春话中用的频率很高,不过我也不知道斯掰是什么意思,可能是助语词,熨48帖,熨spa帖,这个词很好很强大,大家一定要会用
2.宜春话中的韵律
还是一句骂人的,宜春话里说一个人很弱,很差,用/suo/第一声,拟声为/缩/,但不是缩的意思,可能要被别人骂上几回才懂得其中真谛,而一般宜春话都有一些助语词,比如用很嗲的话老说一个人很差(一般用来批评小孩子),是/缩拉西/,用简谱表示就是567,所以小时候学<樱花>这首歌时经常被拿来笑别人,原谱是667667/拉拉西拉拉西/,结果变成/缩拉西缩拉西/
再来就是举一个特例,宜春话的发语习惯有很多细节,举一例,清,在宜春话中发声为锵/qiang/,宜春话里a经常被拿出来用;而底,在宜春话中发声为嘟/du/,比如骂人里有一句是蠢到了嘟,就是说笨透了,简称为蠢嘟,就是指呆子,傻子的意思.
合用一下就是"秀江河的水啊锵又锵,一眼望得到嘟",以前英语老师学这句特别像,很有韵律
3.宜春话的笑话
还有一个常用的词是没,在宜春话里发作/毛/;而宜春话一般用/里/音来做收尾,很厉害的一句骂人的话是错切里!!(这个大家表学)
过年的时候老爹请邻居吃饭,叫老妈拿一瓶他珍藏的马爹利(某品牌XO),可惜他忘了其实之前就喝掉了,对话如下:
老妈:拿什么酒啊
老爹:马爹利
老妈:马爹利
老爹:??
老妈:??
我:笑晕厥过去
其实老妈说的是/毛得里/,就是没有了.... |
JavaScript | UTF-8 | 10,159 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | /**
* Copyright (c) 2006, Opera Software ASA
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Opera Software ASA nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY OPERA SOFTWARE ASA AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL OPERA SOFTWARE ASA AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* JS functions for feed parsing.
* Requires function FeedItem( id, title, content, link, date )
*
* @see Feed.js
* @author Magnus Kristiansen, Opera Software ASA
*/
var parsers = {
'generic' : PatternHandler,
'rss' : rssPatternHandler,
'atom' : atomPatternHandler
};
function PatternHandler(xml) {
if (xml.documentElement.nodeName == 'feed') {
return atomPatternHandler(xml);
}
if (xml.documentElement.getElementsByTagName('channel').length > 0) {
return rssPatternHandler(xml);
}
opera.postError('Unable to recognize feed format, giving up.');
return [];
}
function rssPatternHandler(xml) {
var isHTML = false;
var rss = xml.getElementsByTagName('rss');
if (! rss.length) {
// RSS 0.90 or 1.0
isHTML = true;
} else {
// Any other version
switch ( rss[0].getAttribute('version') ) {
case '0.91' :
// Could be two kinds
isHTML = false;
break;
case '0.92' :
isHTML = true;
break;
case '0.93' :
isHTML = true;
break;
case '0.94' :
// Should check content type, but lazy
isHTML = true;
break;
case '2.0' :
// Could be three kinds
isHTML = true;
break;
default :
// What the hell is this thing
isHTML = false;
break;
}
}
var c = xml.documentElement.getElementsByTagName('item');
var ret = [];
for (var i = 0; i < c.length; i++) {
ret[ret.length] = rssPattern( c[i], isHTML );
}
return ret;
}
function rssPattern(item, isHTML) {
var title = item.getNodeValueByTagName('title');
var link = item.getNodeValueByTagName('link');
var guid = item.getNodeValueByTagName('guid');
if (! guid) {
guid = link + "?feedtitle=" + title;
}
var pubDate = item.getNodeValueByTagName('date');
if (! pubDate) pubDate = item.getNodeValueByTagName('pubDate');
pubDate = pubDate ? (parseRfcDate( pubDate ) || new Date( pubDate ) ) : null;
var content = item.getNodeValueByTagName('description');
if (content) {
if (isHTML) {
var rnode = document.createElement('div');
rnode.innerHTML = content;
content = document.createDocumentFragment();
while (rnode.firstChild) content.appendChild( rnode.firstChild );
} else {
content = document.createTextNode( content );
}
}
return new FeedItem( guid, title, content, link, pubDate );
}
function atomPatternHandler(xml) {
var legacy = ( xml.documentElement.getAttribute('version') == '0.3' );
var c = xml.documentElement.childNodes;
var ret = [];
for (var i = 0; i < c.length; i++) {
if (c[i].nodeName == 'entry') ret[ret.length] = atomPattern( c[i], legacy );
}
return ret;
}
function atomPattern(item, legacy) {
// Mandatory element
var id = item.getNodeValueByTagName('id');
// Mandatory element
var title = (legacy ? processAtomLegacyContent : processAtomContent)( item.getElementsByTagName('title')[0] );
// Mandatory element
var date = parseRfcDate( item.getNodeValueByTagName( legacy ? 'modified' : 'updated' ) );
// Not mandatory, but highly common
var cons = item.getElementsByTagName('summary');
if (cons.length) {
content = (legacy ? processAtomLegacyContent : processAtomContent)( cons[0] );
} else {
cons = item.getElementsByTagName('content');
if (cons.length) {
content = (legacy ? processAtomLegacyContent : processAtomContent)( cons[0], true );
} else {
content = null;
}
}
// Not mandatory in 1.0 [unless content is missing], but highly common
var links = item.getElementsByTagName('link');
var link = null;
for (var i = 0; i < links.length; i++) {
var rel = links[i].getAttribute('rel');
if (!rel || rel == 'alternate') {
link = links[i].getAttribute('href');
break;
}
}
return new FeedItem ( id, title, content, link, date );
}
function processAtomContent(el, contag) {
var content = null;
if (contag) {
var src = el.getAttribute('src');
if (src) {
return 'Linked content: <a href="' + src + '">' + src + '</a>'
+ ' (' + (el.getAttribute('type') || 'unknown') + ')';
}
}
var att = el.getAttribute('type');
switch ( att ) {
case 'xhtml' :
var rnode = document.importNode( el.getElementsByTagName('div')[0], true );
content = document.createDocumentFragment();
while (rnode.firstChild) content.appendChild( rnode.firstChild );
if (! content.hasChildNodes()) content = null;
break;
case 'html' :
var rnode = document.createElement('div');
rnode.innerHTML = el.getNodeValue()
content = document.createDocumentFragment();
while (rnode.firstChild) content.appendChild( rnode.firstChild );
if (! content.hasChildNodes()) content = null;
break;
case 'text' :
case null :
var tnode = el.getNodeValue();
content = tnode ? document.createTextNode( tnode ) : null;
break;
default :
if (! contag) {
content = document.createTextNode( 'Invalid content, unable to display' );
break;
}
if ( att.slice(0,5) == 'text/' ) {
// Text content
content = document.createTextNode( el.getNodeValue() );
break;
}
if ( att.slice(-4) != '/xml' && att.slice(-4) != '+xml' ) {
// Base 64 content
content = document.createTextNode( 'Base64 content, unable to display' );
break;
}
case 'text/xml' :
case 'application/xml' :
case 'text/xml-external-parsed-entity' :
case 'application/xml-external-parsed-entity' :
case 'application/xml-dtd' :
// XML content
var rnode = document.importNode( el.firstChild, true );
content = document.createDocumentFragment();
while (rnode.firstChild) content.appendChild( rnode.firstChild );
if (! content.hasChildNodes()) content = null;
break;
}
return content;
}
function processAtomLegacyContent(el) {
var content = null;
var subcontent = null;
if (el.getAttribute('type') == 'multipart/alternative') {
var types = {};
for (var i = 0; i < el.childNodes.length; i++) {
types[ el.childNodes[i].getAttribute('type') ] = i+1;
}
var wanted = [ 'application/xhtml+xml', 'text/html', 'text/plain' ];
for (var i = 0; i < wanted.length; i++) {
var val = types[ wanted[i] ];
if (val) return processAtomLegacyContent( el.childNodes[val - 1] );
}
return null;
}
switch ( el.getAttribute('mode') ) {
case 'escaped' :
subcontent = el.getNodeValue();
if (! subcontent) return null;
break;
case 'base64' :
return document.createTextNode( 'Base64 content, unable to display' );
break;
case 'xml' :
default :
var rnode = document.importNode(el, true);
subcontent = document.createDocumentFragment();
while (rnode.firstChild) subcontent.appendChild( rnode.firstChild );
if (! subcontent.hasChildNodes()) return null;
break;
}
switch ( el.getAttribute('type') ) {
case 'application/xhtml+xml' :
case 'text/html' :
case 'text/xml' :
if ( typeof subcontent == 'string' ) {
var rnode = document.createElement('div');
rnode.innerHTML = subcontent;
content = document.createDocumentFragment();
while (rnode.firstChild) content.appendChild( rnode.firstChild );
if (! content.hasChildNodes()) return null;
} else {
content = subcontent;
}
break;
case 'text/plain' :
default :
if ( typeof content == 'string' ) {
content = document.createTextNode( subcontent );
} else {
content = document.createTextNode( subcontent.getNodeValue() );
}
break;
}
return content;
}
function parseRfcDate( str ) {
var rfc3339 = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})/i;
var res, hoff, moff;
if (res = rfc3339.exec(str)) {
if (res[8] == 'Z') {
hoff = 0;
moff = 0;
} else {
var s = res[8].split(':');
hoff = + s[0];
moff = + s[1];
}
var ms = res[7] ? res[7] * Math.pow( 10, -res[7].length ) : 0;
return new Date( res[1], res[2] - 1, res[3], res[4] - hoff, res[5] - moff, res[6], ms );
} else {
return null;
}
}
Node.prototype.getNodeValue = function() {
var str = [];
for (var i = 0; i < this.childNodes.length; i++) {
str[str.length] = this.childNodes[i].nodeValue;
}
return str.join('');
}
Node.prototype.getNodeValueByTagName = function(tag) {
if (tag) tag = this.getElementsByTagName(tag);
return tag && tag.length ? tag[0].getNodeValue() : '';
} |
JavaScript | UTF-8 | 851 | 3.734375 | 4 | [] | no_license | // point 1
const geocodeFromRoppongiHills = { latitude: 35.6817124, longitude: 139.7166117 };
const geocodeFromAkihabara = { latitude: 35.7022077, longitude: 139.7722703 };
function getDistance (geocodeA, geocodeB) {
// point 1
const between2parallels = 111.3; // unit: km
const between2meridians = 71.5; // unit: km
const rad = 0.01745; // 1° = π/180 rad ≈ 0.01745
const lat = (geocodeA.latitude - geocodeB.latitude) / 2 * rad;
// point 2
const dx = between2meridians * Math.cos(lat) * (geocodeA.longitude - geocodeB.longitude);
const dy = between2parallels * (geocodeA.latitude - geocodeB.latitude);
// point 3
return Math.sqrt((dx * dx) + (dy * dy));
}
// point 2
const distanceInCentimeter = getDistance (
geocodeFromRoppongiHills,
geocodeFromAkihabara
);
// point 3
console.log (distanceInCentimeter);
|
Java | UTF-8 | 150 | 1.875 | 2 | [] | no_license |
/**
* @author Ezekiel Elin
* @version October 4, 2016
*/
public enum CellDirection {
UP, DOWN, RIGHT, LEFT, UPRIGHT, UPLEFT, DOWNRIGHT, DOWNLEFT
}
|
Markdown | UTF-8 | 848 | 3.03125 | 3 | [] | no_license | this is the javaScript basic project I'm gonna start, it should be difficult as the guide says so .
it is a pad of many square divs that changes darkness when mouse hovers on it.. that all I know for now
UPDATE:
well the project is done, and at the end it is a Sketch pad with the default density of 16 rows and 16 columns,
when the mouse hovers over each square ,the sqaure color changes from the default gray to a random color.
there's also a "Create New" button that you can use to have a clean sketch pad and start over.
the default density can also be changed when you click the "Create New" button and enter your desired density.
e.g if you enter 32 , you will have a new Sketch pad containing 32 rows and 32 columns, the size of the whole board is the same, so you will have a higher resolution board as it will have more squares in it.
|
PHP | UTF-8 | 1,944 | 2.875 | 3 | [] | no_license | <?php
namespace common\crpty;
/**
* error code 说明.
* <ul>
* <li>-40001: 签名验证错误</li>
* <li>-40002: xml解析失败</li>
* <li>-40003: sha加密生成签名失败</li>
* <li>-40004: encodingAesKey 非法</li>
* <li>-40005: appid 校验错误</li>
* <li>-40006: aes 加密失败</li>
* <li>-40007: aes 解密失败</li>
* <li>-40008: 解密后得到的buffer非法</li>
* <li>-40009: base64加密失败</li>
* <li>-40010: base64解密失败</li>
* <li>-40011: 生成xml失败</li>
* </ul>
*/
class WechatErrorCode
{
const OK = 0;
const VALIDATE_SIGNATURE_ERROR = -40001;
const PARSE_XML_ERROR = -40002;
const COMPUTE_SIGNATURE_ERROR = -40003;
const ILLEGAL_AES_KEY = -40004;
const VALIDATE_APPID_ERROR = -40005;
const ENCRYPT_AES_ERROR = -40006;
const DECRYPT_AES_ERROR = -40007;
const ILLEGAL_BUFFER = -40008;
const ENCODE_BASE64_ERROR = -40009;
const DECODE_BASE64_ERROR = -40010;
const GEN_RETURN_XML_ERROR = -40011;
public static function GetCryptErrorMessage($code) {
switch ($code) {
case self::VALIDATE_SIGNATURE_ERROR: $result = "签名验证错误";break;
case self::PARSE_XML_ERROR: $result = "xml解析失败";break;
case self::COMPUTE_SIGNATURE_ERROR: $result = "sha加密生成签名失败";break;
case self::ILLEGAL_AES_KEY: $result = "encodingAesKey 非法";break;
case self::VALIDATE_APPID_ERROR: $result = "appid 校验错误";break;
case self::ENCRYPT_AES_ERROR: $result = "aes 加密失败";break;
case self::DECRYPT_AES_ERROR: $result = "aes 解密失败";break;
case self::ILLEGAL_BUFFER: $result = "解密后得到的buffer非法";break;
case self::ENCODE_BASE64_ERROR: $result = "base64加密失败";break;
case self::DECODE_BASE64_ERROR: $result = "base64解密失败";break;
case self::GEN_RETURN_XML_ERROR: $result = "生成xml失败";break;
default: $result = "OK";break;
}
return $result;
}
}
?> |
Java | UTF-8 | 258 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | package property.enums;
public enum enumCautionKind {
NORMAL("green"),
CATUION("yellow"),
ERROR("red"),
INTERNAL_ERROR("red");
private String kind;
enumCautionKind(String str){
kind = str;
}
public String getString(){
return kind;
}
}
|
Java | UTF-8 | 1,695 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | package nl.pc.bookshop.category.repository;
import nl.pc.bookshop.category.model.Category;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
@SuppressWarnings("JpaQlInspection")
public class CategoryRepository {
private EntityManager em;
public CategoryRepository(final EntityManager em) {
this.em = em;
}
public Category addCategory(Category category) {
em.persist(category);
return category;
}
public Category findById(Long id) {
if (id == null) {
return null;
}
return em.find(Category.class, id);
}
public void update(Category category) {
em.merge(category);
}
public List<Category> findAll(String orderField) {
return em.createQuery("Select e From Category e Order by e." + orderField).getResultList();
}
public boolean alreadyExists(Category category) {
StringBuilder jpql = new StringBuilder();
jpql.append("Select 1 from Category e where e.name = :name");
if (category.getId() != null) {
jpql.append(" And e.id != :id");
}
Query query = em.createQuery(jpql.toString());
query.setParameter("name", category.getName());
if (category.getId() != null) {
query.setParameter("id", category.getId());
}
return query.setMaxResults(1).getResultList().size() > 0;
}
public boolean existsById(final Long id) {
return em.createQuery("Select 1 from Category e where e.id = :id")
.setParameter("id", id)
.setMaxResults(1)
.getResultList().size() > 0;
}
}
|
Java | UTF-8 | 1,000 | 2.734375 | 3 | [] | no_license | package bitTorrent.metainfo;
/**
*
* Describes the "info" dictionary in a Single Mode File.
*
*/
public class InfoDictionarySingleFile extends InfoDictionary {
//Length of the file in bytes.
private int length;
//(optional) a 32-character hexadecimal string corresponding to the MD5 sum of the file
private String md5sum;
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getMd5sum() {
return md5sum;
}
public void setMd5sum(String md5sum) {
this.md5sum = md5sum;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
if (this.length > 0) {
buffer.append("\nfile length: ");
buffer.append(this.length);
}
if (this.md5sum != null && !this.md5sum.trim().isEmpty()) {
buffer.append("\nmd5sum: ");
buffer.append(this.md5sum);
}
buffer.append(super.toString());
return buffer.toString();
}
} |
Markdown | UTF-8 | 3,307 | 2.5625 | 3 | [] | no_license | [](https://www.codacy.com/app/joesan/csv-parser?utm_source=github.com&utm_medium=referral&utm_content=joesan/csv-parser&utm_campaign=Badge_Grade)
[](https://travis-ci.org/joesan/csv-parser)
[]()
# csv-parser []()
A parser implementation for CSV files using the awesome Shapeless library! Just parse any CSV file of your choice.
All you have to specify is a case class that you want the CSV to parse into and of course the CSV file that you want to parse. With this information, the library can produce a Sequence of your case classes. Any errors are being logged and possibly ignored!
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
### Pre-requisites
```
1. Install Java Version 8
2. Install Scala Version 2.12.7
3. Install SBT version 1.2.8
4. Install IntelliJ - Latest community edition and then install the latest Scala / SBT plugins available
```
### Installing
Follow the steps below to import the project into IntelliJ
```
1. Clone the project from:
git clone https://github.com/joesan/csv-parser.git
2. Fire up IntelliJ and import the project
3. If you are opening IntelliJ for the first time, set up the Scala library in IntelliJ
```
### Running tests
You have the option here to either run tests from IntelliJ or from the command line
To run tests from the command line, do the following:
```
1. Open a terminal and navigate to the project root folder
2. Issue the following command:
sbt clean test
```
To run any specific tests from within IntelliJ, simply right click the test that you wish you
run and click Run
### Using the parser
This application is built as a standalone jar and published to the OSS Sonatype repos. To add the parser
as a dependency to your project's build.sbt:
```
libraryDependencies += "com.bigelectrons.csvparser" %% "csv-parser" % version
```
Latest `version`: [](https://index.scala-lang.org/bigelectrons/csv-parser/csv-parser)
Once added as a dependency, you can use the parser as below:
case class MeterData(meterId: String, dateTime: DateTime, meterReadings: Seq[Double])
val canonicalName = Some(classOf[MeterData].getCanonicalName)
val meterCsvParserCfg = CSVParserConfig(withHeaders = true, caseClassCanonicalName = canonicalName, splitterFn = Some(meterDataSplitter))
val meterCsv = "/path/to/csv/file/meterdata.csv"
val csvParser = CsvParser.apply[MeterData]
val meterDataSeq: Seq[MeterData] = csvParser.parse(meterCsv, meterCsvParserCfg)
## Built With
* [SBT](http://www.scala-sbt.org/) - Scala Build Tool
## Authors / Maintainers
* *Joesan* - [Joesan @ GitHub](https://github.com/joesan/)
## License
Feel free to use it
## Acknowledgments
* To everybody that helped in this project
* The [Shapeless library](https://github.com/milessabin/shapeless)
|
Ruby | UTF-8 | 1,086 | 3.84375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require "pry"
def sort_array_asc (array)
array.sort do |a, b|
if a == b
0
elsif a < b
-1
else a > b
1
end
end
end
def sort_array_desc (array)
array.sort do |a, b|
if a==b
0
elsif a<b
1
else a>b
-1
end
end
end
def sort_array_char_count (array)
array.sort do |a, b|
if a.length == b.length
0
elsif a.length < b.length
-1
else a.length > b.length
1
end
end
end
def swap_elements (array)
array.insert(1, array.delete_at(2))
end
def reverse_array (array)
array.reverse
end
def kesha_maker (array)
new_array = []
array.each do |element|
x = element.split("")
x.delete_at(2)
x.insert(2, "$")
new_array << x.join
end
new_array
end
def find_a (array)
array.collect do |element|
element if element.start_with?("a")
end.compact
end
def sum_array (array)
array.inject {|sum, n| sum + n}
end
def add_s(array)
array.collect.with_index do |element, index|
if index == 1
element
else
element + "s"
end
end
end
|
Python | UTF-8 | 5,795 | 2.703125 | 3 | [] | no_license | import sys
from pathlib import Path
from typing import Tuple
import torch
from torch.utils.tensorboard import SummaryWriter
from picogpt import utils
from picogpt.dataset import (
Tokenizer,
TransformerDataset,
CharTokenizer,
TiktokenTokenizer,
SentencePieceTokenizer,
HuggingFaceTokenizer,
split_dataset,
)
from picogpt.model import Transformer
from picogpt.trainer import Trainer
def sample_and_print(
tokenizer: Tokenizer,
model: Transformer,
device: torch.device,
top_k: int = None,
max_new_tokens: int = 500,
prompt: str = "Oh God! Oh God!",
):
"""
Sample from the model and print the decoded text.
"""
x_init = tokenizer.encode(prompt).to(device).view(1, -1)
x_sampled = model.generate(
x_init, max_new_tokens=max_new_tokens, top_k=top_k, do_sample=True
).to("cpu")
# x_sampled = x_sampled[:, len(prompt) :] # remove the prompt
print("Generated text example:")
print(tokenizer.decode(x_sampled[0]))
def create_dataset(
tokenizer: str,
input_path: Path,
save_path: Path,
context_len: int,
vocab_size: int | None = None,
input_test_path: Path = None,
) -> Tuple[Tokenizer, TransformerDataset]:
"""
Create or read the dataset from file if exists.
"""
print(f"Initializing tokenizer {tokenizer} based on {input_path}...")
if tokenizer == "tiktoken":
tokenizer = TiktokenTokenizer(encoding_name="gpt2")
elif tokenizer == "char":
tokenizer = CharTokenizer(input_path.open().read())
elif tokenizer == "sentencepiece":
tokenizer = SentencePieceTokenizer(input_path, vocab_size=vocab_size)
elif tokenizer == "huggingface":
tokenizer = HuggingFaceTokenizer(input_path, vocab_size=vocab_size)
print(f"Inferred vocabulary size: {tokenizer.vocab_size()}")
if save_path.exists():
print(f"Loading pickled dataset from {save_path}...")
dataset = torch.load(save_path)
else:
print(f"Creating dataset from file {input_path}...")
data = tokenizer.encode(input_path.open().read())
dataset = TransformerDataset(data, context_len)
if input_test_path is not None:
dataset.train = dataset
test_data = tokenizer.encode(open(input_test_path).read())
dataset.test = TransformerDataset(test_data, context_len)
else:
dataset.train, dataset.test = split_dataset(dataset)
print(
f"Created dataset of {len(dataset.data)} tokens, giving {len(dataset)} "
f"examples with context length {dataset.context_len}. Split the dataset "
f"into {len(dataset.train)} training and {len(dataset.test)} test examples"
)
print(f"Saving dataset to {save_path}...")
torch.save(dataset, save_path)
return tokenizer, dataset
datasets_path = (
next(
Path(p)
for p in ["/Users/vlad/googledrive", "/content/drive/MyDrive"]
if Path(p).exists()
)
/ "AI/datasets"
)
runs_saves_root = next(
Path(p)
for p in ["/content/drive/MyDrive/AI/hipogpt", Path(__file__).parent]
if Path(p).exists()
)
saves_path = runs_saves_root / "saves"
runs_path = runs_saves_root / "runs"
saves_path.mkdir(exist_ok=True)
runs_path.mkdir(exist_ok=True)
class Config:
sample_only: str = False
seed = 0
# Dataset
tokenizer: str = "sentencepiece"
input_path = datasets_path / "tinyshakespeare" / "tinyshakespeare.txt"
input_test_file = None
vocab_size: int = 2000
# Network
context_len: int = 32
emb_dim: int = 32
n_blocks: int = 2
n_heads: int = 4
# Optimization
batch_size: int = 32
learning_rate: float = 5e-4
weight_decay: float = 0.01
num_workers: int = 1
max_steps: int = 100_000
disable_cuda: bool = False
def main():
utils.set_seed(Config.seed)
device = utils.device(Config.disable_cuda)
dataset_name = f"{Config.input_path.stem}-{Config.tokenizer}"
model_save_path = saves_path / f"{dataset_name}-model.pt"
dataset_save_path = saves_path / f"{dataset_name}-dataset.pt"
tokenizer, dataset = create_dataset(
tokenizer=Config.tokenizer,
input_path=Config.input_path,
input_test_path=Path(Config.input_test_file) if Config.input_test_file else None,
save_path=dataset_save_path,
context_len=Config.context_len,
vocab_size=Config.vocab_size,
)
print()
print("Initialising the model...")
model = Transformer(
vocab_size=tokenizer.vocab_size(),
context_len=dataset.context_len,
emb_dim=Config.emb_dim,
n_heads=Config.n_heads,
n_layers=Config.n_blocks,
)
if model_save_path.exists():
print(f"Initializing from the existing model state {model_save_path}")
model.load_state_dict(torch.load(model_save_path))
if Config.sample_only:
if not model_save_path.exists():
print(f"No model file found at {model_save_path}, cannot sample")
sys.exit(1)
sample_and_print(tokenizer, model=model.to(device), device=device)
sys.exit(0)
print()
def _callback(*_):
sample_and_print(tokenizer, model=model, device=device)
trainer = Trainer(
model=model,
device=device,
train_set=dataset.train,
test_set=dataset.test,
batch_size=Config.batch_size,
num_workers=Config.num_workers,
learning_rate=Config.learning_rate,
weight_decay=Config.weight_decay,
max_steps=Config.max_steps,
save_path=model_save_path,
summary_writer=SummaryWriter(),
on_batch_end=_callback,
on_start=_callback,
)
trainer.run()
if __name__ == "__main__":
main()
|
JavaScript | UTF-8 | 1,176 | 3.359375 | 3 | [] | no_license | //Напиши скрипт который, при наборе текста в
//инпуте input#name-input (событие input),
//подставляет его текущее значение в span#name-output.
// Если инпут пустой, в спане должна отображаться
// строка 'незнакомец'.
let inputName = document.getElementById("name-input")
let outputName = document.getElementById("name-output")
inputName.addEventListener('input', (event) =>{
event.target.value === '' ? outputName.textContent = "незнакомец" : outputName.textContent = event.target.value
})
// Используй массив объектов images для создания тегов img вложенных в li.
// Для создания разметки используй шаблонные строки и insertAdjacentHTML().
// Все элементы галереи должны добавляться в DOM за одну операцию вставки.
// Добавь минимальное оформление галереи флексбоксами или гридами через css-классы.
|
Markdown | UTF-8 | 807 | 3.234375 | 3 | [
"MIT",
"CC-BY-SA-4.0"
] | permissive | # How to Know who is in charge of your campsite on Facebook
Local communities are ever-changing, and there can be more than one Volunteer Community Manager for your city. To become an Admin in the Facebook group, follow the steps below.
How to find out who is an Admin for your Local Group:
- First, click the Members tab below the cover photo. Then the click on the dropdown box that says "all members"**

- Next, use the drop down box to select "Admins"**

- You should now be able to see who is designated as an Admin for your Local Group.

Message this person to introduce yourself and let them know you're interested in being an admin. After this, go schedule your first meetup.
|
C | UTF-8 | 2,488 | 2.90625 | 3 | [
"BSD-4-Clause-UC"
] | permissive | #ifndef PARLIB_ARCH_BITMASK_H
#define PARLIB_ARCH_BITMASK_H
#include <string.h>
#include <sys/types.h>
#include <sys/param.h>
#include <arch/atomic.h>
#include <stdio.h>
#define DECL_BITMASK(name, size) \
uint8_t (name)[BYTES_FOR_BITMASK((size))]
#define BYTES_FOR_BITMASK(size) \
(((size) - 1) / 8 + 1)
#define BYTES_FOR_BITMASK_WITH_CHECK(size) \
((size) ? ((size) - (1)) / (8) + (1) : (0))
static bool GET_BITMASK_BIT(uint8_t* name, size_t bit)
{
return (((name)[(bit)/8] & (1 << ((bit) % 8))) ? 1 : 0);
}
#define SET_BITMASK_BIT(name, bit) \
((name)[(bit)/8] |= (1 << ((bit) % 8)));
/*
static void SET_BITMASK_BIT(uint8_t* name, size_t bit)
{
((name)[(bit)/8] |= (1 << ((bit) % 8)));
}
*/
#define CLR_BITMASK_BIT(name, bit) \
((name)[(bit)/8] &= ~(1 << ((bit) % 8)));
/*
static void CLR_BITMASK_BIT(uint8_t* name, size_t bit)
{
((name)[(bit)/8] &= ~(1 << ((bit) % 8)));
}
*/
static void SET_BITMASK_BIT_ATOMIC(uint8_t* name, size_t bit)
{
(atomic_orb(&(name)[(bit)/8], (1 << ((bit) % 8))));
}
#define CLR_BITMASK_BIT_ATOMIC(name, bit) \
(atomic_andb(&(name)[(bit)/8], ~(1 << ((bit) % 8))))
#define CLR_BITMASK(name, size) \
({ \
{TRUSTEDBLOCK \
memset((void*)((uintptr_t)(name)), 0, BYTES_FOR_BITMASK((size))); \
} \
})
#define FILL_BITMASK(name, size) \
({ \
{TRUSTEDBLOCK \
memset((void*)((uintptr_t)(name)), 255, BYTES_FOR_BITMASK((size))); \
} \
(name)[BYTES_FOR_BITMASK((size))-1] >>= (((size) % 8) ? (8 - ((size) % 8)) : 0 ); \
})
#define COPY_BITMASK(newmask, oldmask, size) \
({ \
{TRUSTEDBLOCK \
memcpy((void*)((uintptr_t)(newmask)), \
(void*)((uintptr_t)(oldmask)), \
BYTES_FOR_BITMASK((size))); \
} \
})
// this checks the entire last byte, so keep it 0 in the other macros
#define BITMASK_IS_CLEAR(name, size) ({ \
uint32_t __n = BYTES_FOR_BITMASK((size)); \
bool clear = 1; \
while (__n-- > 0) { \
if ((name)[__n]) { \
clear = 0; \
break;\
}\
} \
clear; })
static inline bool BITMASK_IS_FULL(uint8_t* map, size_t size)
{
int _size = size;
for (int i = 0; i < BYTES_FOR_BITMASK(size); i++) {
for (int j = 0; j < MIN(8,_size); j++)
if(!((map[i] >> j) &1))
return FALSE;
_size--;
}
return TRUE;
}
#define PRINT_BITMASK(name, size) { \
int i; \
int _size = size; \
for (i = 0; i < BYTES_FOR_BITMASK(size); i++) { \
int j; \
for (j = 0; j < MIN(8,_size); j++) \
printk("%x", ((name)[i] >> j) & 1); \
_size--; \
} \
printk("\n"); \
}
#endif /* PARLIB_ARCH_BITMASK_H */
|
Java | UTF-8 | 284 | 2.1875 | 2 | [] | no_license | package duke;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class EventTest {
@Test
public void testEvents() {
assertEquals("E | 0 | meeting | 2020-08-16", new Event("meeting", "2020-08-16").writeToFile());
}
}
|
Python | UTF-8 | 89 | 3.28125 | 3 | [] | no_license | a = [2,3,4,5,10]
b = []
sqr= [ i*i for i in a]
print('Positive list of numbers: ',sqr) |
Java | UTF-8 | 2,812 | 2.640625 | 3 | [] | no_license | package formdata;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/searchDate")
public class ServletSearchDate extends HttpServlet {
SimpleDateFormat simple = new SimpleDateFormat("dd-MM-yyyy");
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
List<MessageForm> saveMess = MessageData.getListMess();
List<MessageForm> res = new ArrayList<>();
String submit = request.getParameter("submitDate");
if(submit != null ) {
String dateSearch = request.getParameter("searchByDate");
try {
Date date = simple.parse(dateSearch);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
for(MessageForm m : saveMess) {
Calendar cald = Calendar.getInstance();
cal.setTime(m.getDate());
if(cal.get(Calendar.YEAR)== cald.get(Calendar.YEAR) && cal.get(Calendar.MONTH)== cald.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH)== cald.get(Calendar.DAY_OF_MONTH) ) {
res.add(m);
}
}
}catch (Exception e) {
}
// get response writer
}
PrintWriter pw = response.getWriter();
pw.println("<html><head>");
pw.println("<link rel='stylesheet' type='text/css' href='" + request.getContextPath() + "/Style/style.css' />");
if(res.size()!=0) {
pw.write("<h2> Following data received sucessfully.. <h2> <br>");
pw.println("<body>");
pw.println("<table>");
pw.println("<tr>");
pw.println("<th>FirstName</th>");
pw.println("<th>Message</th>");
pw.println("<th>Date</th>");
pw.println("</tr>");
for(MessageForm mess : res) {
pw.println("<tr>");
pw.println("<td>" + mess.getFirstName() + "</td>");
pw.println("<td>" + mess.getContentMessage() + "</td>");
pw.println("<td>" + simple.format(mess.getDate()) + "</td>");
pw.println("<td>" + "<img src='" + mess.getImage() + "' border=3 height=100 width=100></img>" + "</td>");
pw.println("</tr>");
}
pw.println("</table>");
pw.println("<button class='button'><a href='index.html'>BACK</a></button>");
pw.println("</body>");
}else {
pw.println("Not Found");
}
}
}
|
TypeScript | UTF-8 | 2,979 | 3.015625 | 3 | [
"ISC"
] | permissive | /*
File: src/pipeline/show-nonprinting.ts
cpuabuse.com
*/
/**
* Shows non-printing characters.
* Code converted from [coreutils repository](https://github.com/coreutils/coreutils/blob/master/src/cat.c).
*/
/**
* An empty string.
*/
const emptyString: string = "";
/**
* A delete character.
*/
const lastLowerChar: number = 127;
/**
* A space character.
*/
const printableChar: number = 32;
/**
* Nbsp.
*/
const middleHigherChar: number = 160;
/**
* Latin small letter y with diaeresis.
*/
const lastHigherChar: number = 255;
/**
* Euro sign.
*/
const firstHigherChar: number = 128;
/**
* At symbol.
*/
const firstAlphaChar: number = 64;
/**
* New line character.
*/
const newLineChar: number = 10;
/**
* Tab character.
*/
const tabChar: number = 9;
/**
* Return character.
*/
const returnChar: number = 13;
/**
* Do we treat carriage return as character or not.
*/
let treatCarriageReturnAsCharater: boolean = false;
// no-param-reassign is overriden in the body of the fucntion because array is used as a pointer
/**
* Replaces now printing character with others characters.
* @param text Text to process
*/
export function showNonPrinting(text: string): string {
let resultArray: Array<string> = text.split(emptyString);
resultArray.forEach(function(character, index, array) {
// Converts string to ASCII code
let characterCode: number = character.charCodeAt(0);
if (characterCode >= printableChar) {
// If character is in between 32 and 127, we do nothing
if (characterCode === lastLowerChar) {
array[index] = "^?"; // eslint-disable-line no-param-reassign
}
// Process for when the character is above 127
if (characterCode > lastLowerChar) {
// We firstly set to "M-"
array[index] = "M-"; // eslint-disable-line no-param-reassign
if (characterCode >= middleHigherChar) {
// For values between 160 and 255, we add respective printable character to "M-"
if (characterCode < lastHigherChar) {
// eslint-disable-next-line no-param-reassign
array[index] += String.fromCharCode(characterCode - firstHigherChar);
} else {
// For characters above 255, add "^?" to "M-"
array[index] += "^?"; // eslint-disable-line no-param-reassign
}
} else {
// For characters between 127 and 160, add also respective printable charater
// eslint-disable-next-line no-param-reassign
array[index] += `^${String.fromCharCode(characterCode - firstAlphaChar)}`;
}
}
} else if (
// "9" is "\t", "10" is "\n", "13" is "\r"
characterCode !== tabChar &&
characterCode !== newLineChar &&
(treatCarriageReturnAsCharater ? true : characterCode !== returnChar)
) {
array[index] = `^${String.fromCharCode(characterCode + firstAlphaChar)}`; // eslint-disable-line no-param-reassign
}
});
return resultArray.join(emptyString);
}
|
Markdown | UTF-8 | 1,554 | 3.109375 | 3 | [] | no_license | # The Carriage Environment
<img align="right" src="https://github.com/eishub/carriage/wiki/carriage.png"/>
The carriage environment consists of a *carriage* and *two robots* that can either *push* the carriage or do nothing, i.e., *wait*. The robots and the carriage are positioned on a ring with only three positions (top, left and right bottom). The robots, moreover, are each located on opposite sides of the carriage and if both push at the same time, the carriage does not move. If one robot pushes and the other robot waits, then the carriage moves one position.
The question is *which combination of strategies allows the robots to move to a particular position on the ring* (and stay there), or which strategies allow the robots to perform even more complicated dances on the ring (e.g., move to the top position, move to the left bottom position, and via the top position move to the right bottom position).
## Actions
The actions that a robot can perform are either a **push** or a **wait** action.
## Percept
The robots receive a percept of the form **carriagePos(X)** where `X` is either 0, 1, or 2.
# Releases
Releases can be found in eishub's maven repository [here](https://github.com/eishub/mvn-repo/tree/master/eishub/carriage).
Dependency information
=====================
```
<repository>
<id>eishub-mvn-repo</id>
<url>https://raw.github.com/eishub/mvn-repo/master</url>
</repository>
```
```
<dependency>
<groupId>eishub</groupId>
<artifactId>Carriage</artifactId>
<version>1.2.0</version>
</dependency>
```
|
Go | UTF-8 | 3,483 | 3.03125 | 3 | [] | no_license | // Package enc provides a simple interface for encrypting and decrypting data to
// a useful format.
//
// First, the data item is encoded to as a gob. Next, the encoding is compressed
// to the gzip format. This is encrypted with AES-256 in Galois/Counter mode.
// The input password is derived with argon2i and the hash is used as the key to
// AES. The output data is in the following format.
//
// [enc version][argon2 salt][AES nonce][encrypted data]
//
// This format aims for minimal data size (from gzip), data integrity (from
// GCM), and data confidentiality (from AES).
package enc
import (
"bytes"
"compress/gzip"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha512"
"encoding/binary"
"encoding/gob"
"errors"
"io"
"golang.org/x/crypto/argon2"
)
// Errors related to invalid input data.
var (
ErrNoNonce = errors.New("enc: data does not contain a nonce")
ErrNoSalt = errors.New("enc: data does not contain a salt")
ErrNoVersion = errors.New("enc: data does not contain a version")
ErrVersionInvalid = errors.New("enc: data contains an invalid version")
)
const saltSize = 64
// Version is the enc format version.
const Version uint64 = 1
// Decrypt data according to the specified format.
func Decrypt(data, password []byte, d interface{}) error {
if len(data) < 8 {
return ErrNoVersion
}
ver, data := data[:8], data[8:]
switch binary.LittleEndian.Uint64(ver) {
case 1:
break
default:
return ErrVersionInvalid
}
if len(data) < saltSize {
return ErrNoSalt
}
salt, data := data[:saltSize], data[saltSize:]
c, err := aes.NewCipher(derive(password, salt))
if err != nil {
return err
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return err
}
nonceSize := gcm.NonceSize()
if len(data) < nonceSize {
return ErrNoNonce
}
nonce, data := data[:nonceSize], data[nonceSize:]
plaintext, err := gcm.Open(data[:0], nonce, data, nil)
if err != nil {
return err
}
r, err := gzip.NewReader(bytes.NewReader(plaintext))
if err != nil {
return err
}
if err = gob.NewDecoder(r).Decode(d); err != nil {
_ = r.Close()
return err
}
return r.Close()
}
// Encrypt data according to the specified format. A SHA-512 hash of the output
// data is given in hash.
func Encrypt(password []byte, e interface{}) (data, hash []byte, err error) {
var encoded bytes.Buffer
if err = gob.NewEncoder(&encoded).Encode(e); err != nil {
return
}
var compressed bytes.Buffer
w := gzip.NewWriter(&compressed)
if _, err = w.Write(encoded.Bytes()); err != nil {
return
}
if err = w.Close(); err != nil {
return
}
salt := make([]byte, saltSize)
if _, err = rand.Read(salt); err != nil {
return
}
c, err := aes.NewCipher(derive(password, salt))
if err != nil {
return
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return
}
nonce := make([]byte, gcm.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return
}
var buf bytes.Buffer
sha := sha512.New()
mw := io.MultiWriter(&buf, sha)
ver := make([]byte, 8)
binary.LittleEndian.PutUint64(ver, Version)
if _, err = mw.Write(ver); err != nil {
return
}
if _, err = mw.Write(salt); err != nil {
return
}
if _, err = mw.Write(nonce); err != nil {
return
}
if _, err = mw.Write(gcm.Seal(nil, nonce, compressed.Bytes(), nil)); err != nil {
return
}
return buf.Bytes(), sha.Sum(nil), nil
}
func derive(password, salt []byte) []byte {
return argon2.Key(password, salt, 3, 32*1024, 4, 32)
}
|
Java | UTF-8 | 743 | 2.15625 | 2 | [
"MIT"
] | permissive | package ru.stud.person.mapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import ru.stud.person.Person;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Component
public class PersonMapperFromJsonImpl implements PersonMapper {
@Override
public List<Person> map() {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.readValue(new File("src/main/resources/generated.json"), new TypeReference<List<Person>>() { });
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
|
Markdown | UTF-8 | 4,772 | 3.015625 | 3 | [] | no_license | ----
Time: 20190527
译者:BING
----
[TOC]
# 2. 使用Python解释器
## 2.1 调用解释器
Python解释器通常安装在`/usr/localbin/python3.7`下,将`/usr/local/bin`放在Unix脚本搜索路径下,可以使得下面的命令可以在命令行执行:
```python
python3
```
解释器的安装位置是可选的,其他地方也是可以的。
在`Windows`机器上,`Python`安装通常在`C:\Python37`中,虽然你在运行安装时可能改变了位置。为了将这个文件夹添加到路径,可以用下面的命令:
```python
set path=%path%;C:\python37
```
输入字符结束符(Unix下用Ctrl+D,Windows下用Ctrl+Z)。如果不行的话,就输入`quit()`。
解释器允许交互式编辑,历史代码替代和系统代码补全支持读取行。快速检查命令行是否支持行编写的方式是按`Ctrl + P`,看是否会谈出上一行代码。如果有的话,你的解释器就支持行编写。
解释器运行有点像Unix脚本:交互读取命令和读取并执行脚本文件两种方式。
第二种开启解释器的方式是`python -c command [arg]...`,会直接执行命令,这可以类比到脚本中的`-c`选项。因为Python的语句常常包含空格和其他的属于脚本的特殊字符,因此常用引号把命令包围起来。
```python
python -c "import os; print(os.sys.executable)"
```
一些Python模块和脚本一样有用。这些可以这样调用:`python -m module[arg]...`,这会执行模块的源文件,只需要在命令行执行文件的全名即可。
使用脚本文件时,有时候先运行脚本,然后再进入交互模式很有用。可在脚本脚本前加`-i`选项。
所有的命令行选项在[这里](https://docs.python.org/3/using/cmdline.html#using-on-general)有详细描述。
### 2.1.1. 参数传递
当解释器知道了脚本的名字,以及额外的参数后,它们会被变成一个字符串数组,并且会被分配给`sys`模块下的`argv`变量。你可以通过执行`import sys`来访问这个列表。列表的长度至少为1,当没有脚本和没有参数时,`sys.argv[0]`是个空字符串。当脚本名字给的是`-`时(表示标准输入),`sys.argv[0]`被设置为`'-'`。当`-c`命令用上时, `sys.argv[0]` 被设置为 `'-c'`。当 [`-m`](https://docs.python.org/3/using/cmdline.html#cmdoption-m)用上时, `sys.argv[0]` 会被设置为该模块的全名。在 [`-c`](https://docs.python.org/3/using/cmdline.html#cmdoption-c)命令或者 [`-m`](https://docs.python.org/3/using/cmdline.html#cmdoption-m) 模块之后的选项没有被Python解释器的选项处理,会被留给`sys.argv` ,用于命令或模块来处理。
### 2.1.2. 交互模式
当命令被终端读入,解释器就进入交互模式。这个模式下,它会显示主提示符,提示输入下一条指令。通常用`>>>`表示,连续输入多行时,会显示次要提示符,默认是三个点`...`。解释器会打印出欢迎信息、版本信息、版权信息,然后会出现提示符:
```
$ python3.7
Python 3.7 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
多行命令在连续输入时需要。比如,`if`语句:
```
>>> the_world_is_flat = True
>>> if the_world_is_flat:
... print("Be careful not to fall off!")
...
Be careful not to fall off!
```
更多交互模式的内容,参考[交互模式](https://docs.python.org/zh-cn/3/tutorial/appendix.html#tut-interac)。
## 2.2. 解释器和运行环境
### 2.2.1. 源代码编码
默认情况下,Python源文件会视为`UTF-8`编码。这种编码下,大多数语言的字符都能同时用于字符串的字面值、变量和注释中。尽管标准库中只用常规的ASCII字符作为变量或函数名,这是任何可移植的代码需要遵守的约定。为了正确显示这些字符,你的编辑器必须能识别UTF-8编码的文件,且必须使用能支持打开的文件中所有字符的字体。
如果不使用默认编码,要声明文件所使用的编码,文件的 *第一* 行要写成特殊的注释。语法如下所示:
```
# -*- coding: encoding -*-
```
其中 *encoding* 可以是 Python 支持的任意一种 [`codecs`](https://docs.python.org/zh-cn/3/library/codecs.html#module-codecs)。
比如,要声明使用 Windows-1252 编码,你的源码文件要写成:
```
# -*- coding: cp1252 -*-
```
关于 *第一行* 规则的一种例外情况是,源码以 [UNIX "shebang" 行](https://docs.python.org/zh-cn/3/tutorial/appendix.html#tut-scripts) 开头。这种情况下,编码声明就要写在文件的第二行。例如:
```
#!/usr/bin/env python3
# -*- coding: cp1252 -*-
```
END. |
Shell | UTF-8 | 1,310 | 3.5625 | 4 | [
"MIT"
] | permissive | set -e
# bl: we only need to get docker tag info if we are deploying. if we're stopping, then we don't need it
if [ "${DEPLOY_TYPE}" != "stop" ]; then
# if auto deploy, find the latest version based on ./docker/export-narrative-build-vars.sh deploy
if [ "${DOCKER_TAG_DEPLOY}" == "" ]; then
echo "DOCKER_TAG_DEPLOY not defined. Finding tag based on ./docker/export-narrative-build-vars.sh deploy..."
# we LOCK to narrative-core version number
. ./docker/export-narrative-build-vars.sh deploy
else
# Safe/easy way to line up an auto deploy and Docker tag deploy so that we can Slack notify the tag
echo "${DOCKER_TAG_DEPLOY}" > ./DOCKER_TAG_DEPLOY
fi
. ./kubernetes/_docker_tag_deploy.sh
fi
# Get blue/green
. ./kubernetes/_deployment_information.sh
# Conditional time
if [ "${DEPLOY_TYPE}" == "blue-green" ]; then
. ./kubernetes/blue-green-deployment.sh
elif [ "${DEPLOY_TYPE}" == "stop" ]; then
echo "STOP-PODS.SH SCRIPT..."
. ./kubernetes/stop-pods.sh
elif [ "${DEPLOY_TYPE}" == "start" ]; then
echo "Running the rep-deployment script... (running ./kubernetes/rep-deployment.sh)"
./kubernetes/rep-deployment.sh
echo "START-PODS.SH SCRIPT..."
. ./kubernetes/start-pods-with-deploy.sh
else
echo "PANIC! DIDN'T FIND DEPLOY_TYPE VARIABLE. Exiting..."
exit 1
fi |
Java | UTF-8 | 191 | 1.6875 | 2 | [] | no_license | package com.example.fcode4;
/**
* Created by wuzhuojun on 2016/8/2 0002.
* 更新 UI 界面的接口
*/
public interface OnUpdateUIListener
{
void OnUpdateUIListener(String result);
} |
PHP | UTF-8 | 8,785 | 2.875 | 3 | [] | no_license | <?php
/**
* Metrou_Authenticator
*
* _set() auth.hashList to an array of HashAdapter objects.
* Any class that has hashPassword($password) and comparePasswordHash($password, $hash) will do.
*/
class Metrou_Authenticator {
public $handler = NULL;
public $handlerList = array();
public $ctx = NULL;
public $subject = NULL;
/**
* Authenticate the user, are they who they say they are
* based on the cookie submitted.
* Basically, attach a session to the user.
*/
public function authenticate($request, $response) {
$user = _make('user');
$session = _make('session');
$session->start();
$user->startSession($session);
}
/**
* Alias for process
*/
public function login($request, $response, $user) {
return $this->process($request, $response, $user);
}
/**
* Initialize a new handler for the given context.
* If no context is supplied, a default handler will be created.
* The default handler is based on the local mysql installation.
*/
public function process($request, $response, $user) {
$uname = $request->cleanString('username');
if ($uname == '') {
$uname = $request->cleanString('email');
}
$pass = $request->cleanString('password');
$configs = _get('auth_configs', array());
$this->handler = _make('auth_handler');
if ($this->handler == NULL || $this->handler instanceof Metrodi_Proto) {
$this->handlerList = _get('auth.handlerList');
}
if ($this->handler instanceof Metrou_Authiface) {
$this->handlerList = array($this->handler);
}
if ($this->handlerList == NULL || count($this->handlerList) == 0) {
$this->handlerList = array(new Metrou_Authdefault());
}
$hashAdapterList = _get('auth.hashList', array());
if ( !count($hashAdapterList) ) {
$hashAdapterList = array( _make('metrou/hash/bcrypt.php') );
if (version_compare(PHP_VERSION, '7.2.0') >= 0) {
array_unshift($hashAdapterList, _make('metrou/hash/argon2i.php') );
}
}
$this->subject = Metrou_Subject::createFromUsername($uname, $pass);
$successHandler = NULL;
foreach($this->handlerList as $handler) {
$handler->initContext($configs);
$handler->setHashAdapters($hashAdapterList);
$err = $handler->authenticate($this->subject);
//if success, then break
if (!$err) {
$successHandler = $handler;
break;
}
}
if ($err) {
$args = array(
'request'=>$request,
'response'=>$response,
'subject'=>$this->subject,
'user'=>$user
);
Metrofw_Kernel::emit('authenticate.failure', $this, $args);
return;
}
if ($request->appUrl == 'login') {
$response->redir = m_appurl();
}
@$successHandler->applyAttributes($this->subject, $user);
$args = array(
'request'=>$request,
'subject'=>$this->subject,
'user'=>$user
);
$user->password = $successHandler->hashPassword($pass);
Metrofw_Kernel::emit('authenticate.success', $this, $args );
$session = _make('session');
$user->login($session);
$args = array(
'user'=>$user
);
Metrofw_Kernel::emit('login.after', $this, $args);
}
}
interface Metrou_Authiface {
/**
* Must return a reference to this
*
* @return Object Metrou_Authiface
*/
public function initContext($ctx);
/**
* Return any positive number other than 0 to indicate an error
*
* @return int number greater than 0 is an error code, 0 is success
*/
public function authenticate($subject);
/**
* Save a connection to this user in the local user database.
*
* @return int number greater than 0 is an error code, 0 is success
*/
public function applyAttributes($subject, $existingUser);
/**
* Set a list of hash implementations
*/
public function setHashAdapters($hashList);
/**
* Compare a password against a list of adapters
*/
public function comparePasswordHash($pwd, $hash);
}
class Metrou_Authdefault implements Metrou_Authiface {
public $hashAdapters = array();
public function initContext($ctx) {
return $this;
}
/**
* Set a list of hash implementations
*/
public function setHashAdapters($hashList) {
$this->hashAdapters = $hashList;
}
/**
* Return any positive number other than 0 to indicate an error
*
* @return int number greater than 0 is an error code, 0 is success
*/
public function authenticate($subject) {
if (!isset($subject->credentials['passwordhash'])) {
$subject->credentials['passwordhash'] = $this->hashPassword($subject->credentials['password']);
}
$finder = _makeNew('dataitem', 'user_login');
$finder->andWhere('username', $subject->credentials['username']);
$finder->orWhereSub('email', $subject->credentials['username']);
$finder->_rsltByPkey = FALSE;
$results = $finder->findAsArray();
if (!count($results)) {
return 501;
}
if( count($results) !== 1) {
//too many results, account is not unique
return 502;
}
$candidate = $results[0];
if (!$this->comparePasswordHash($subject->credentials['password'], $candidate['password'])) {
return 501;
}
$subject->attributes = array_merge($subject->attributes, $results[0]);
return 0;
}
public function hashPassword($p) {
foreach ($this->hashAdapters as $_hash) {
$hashed = $_hash->hashPassword($p);
if ($hashed != FALSE) {
return $hashed;
}
}
return FALSE;
}
public function comparePasswordHash($pwd, $hash) {
foreach ($this->hashAdapters as $_hash) {
$match = $_hash->comparePasswordHash($pwd, $hash);
if ($match != FALSE) {
return $match;
}
}
return FALSE;
}
/**
* Save a connection to this user in the local user database.
*
* @return int number greater than 0 is an error code, 0 is success
*/
public function applyAttributes($subject, $user) {
$attribs = $subject->attributes;
$user->email = $attribs['email'];
$user->username = $attribs['username'];
$user->locale = $attribs['locale'];
$user->tzone = $attribs['tzone'];
$user->activeOn = $attribs['active_on'];
$user->userId = $attribs['user_login_id'];
$user->enableAgent = $attribs['enable_agent'] == '1'? TRUE : FALSE;
if ($user->enableAgent) {
$user->agentKey = $attribs['agent_key'];
}
return 0;
}
}
class Metrou_Authldap extends Metrou_Authdefault implements Metrou_Authiface {
public $dsn = '';
public $bindBaseDn = '';
protected $ldap = NULL;
public function initContext($ctx) {
$this->dsn = $ctx['dsn'];
$this->bindBaseDn = $ctx['bindDn'];
$this->authDn = $ctx['authDn'];
return $this;
}
public function setLdapConn($l) {
$this->ldap = $l;
}
public function getLdapConn() {
if ($this->ldap === NULL) {
$this->ldap = _make('ldapconn', $this->dsn);
}
return $this->ldap;
}
/**
* Return any positive number other than 0 to indicate an error
*
* @return int number greater than 0 is an error code, 0 is success
*/
public function authenticate($subject) {
if (!isset($subject->credentials['passwordhash'])) {
$subject->credentials['passwordhash'] = $this->hashPassword($subject->credentials['password']);
}
$rdn = sprintf($this->bindBaseDn, $subject->credentials['username']);
$ldap = $this->getLdapConn();
// $ldap->setBindUser($rdn, $subject->credentials['password']);
$result = $ldap->bind();
$basedn = $this->authDn;
//query for attributes
$res = $ldap->search($basedn, '(userid='.$subject->credentials['username'].')', array('entryUUID', 'mail', 'tzone', 'locale', 'dn', 'entryDN'));
if ($res === FALSE) {
//search failed
$ldap->unbind();
return 501;
}
$ldap->nextEntry();
$attr = $ldap->getAttributes();
$ldap->unbind();
foreach ($attr as $_attr => $_valList) {
if ($_attr == 'mail')
$subject->attributes['email'] = $_valList[0];
if ($_attr == 'entryDN')
$subject->attributes['dn'] = $_valList[0];
}
// $subject->attributes = array_merge($subject->attributes, $results[0]);
return 0;
}
/**
* Save a connection to this user in the local user database.
*
* @return int number greater than 0 is an error code, 0 is success
*/
public function applyAttributes($subject, $existingUser) {
$existingUser->username = $subject->credentials['username'];
$existingUser->password = $subject->credentials['passwordhash'];
$existingUser->idProviderToken = $subject->attributes['dn'];
//tell the subject that what its new ID is
$subject->attributes['user_login_id'] = $existingUser->userId;
return 0;
}
}
class Metrou_Subject {
public $credentials = array();
public $attributes = array();
public $domain = '';
public $domainId = 0;
public static function createFromUserName($uname, $pass) {
$subj = new Metrou_Subject();
$subj->credentials['username'] = $uname;
$subj->credentials['password'] = $pass;
return $subj;
}
}
|
C++ | UTF-8 | 1,206 | 3.40625 | 3 | [] | no_license | #include "card.h"
Card::Card(int nr, char suit)
: m_nr{nr}
, m_suit{suit}
{
}
std::ostream& operator << (std::ostream& valja, Card& c){
if(c.getNr()>1 && c.getNr()<11) return valja << c.getNr()
<< " " << c.getSuit();
else if(c.getNr() == 1) return valja << "A " << c.getSuit();
else if(c.getNr() == 11) return valja << "J " << c.getSuit();
else if(c.getNr() == 12) return valja << "Q " << c.getSuit();
else if(c.getNr() == 13) return valja << "K " << c.getSuit();
return valja << "None";
}
int Card::getRank(){
if(m_nr == 1) return 14;
else return m_nr;
}
QString Card::toQString(){
QString result;
if(m_nr == 1) result = QString("A");
else if(m_nr == 11) result = QString("J");
else if(m_nr == 12) result = QString("Q");
else if(m_nr == 13) result = QString("K");
else result = QString::number(m_nr);
return result;
}
bool Card::operator <(const Card& card)const{
if(m_nr == card.getNr())
return (m_suit < card.getSuit());
if(m_nr == 1 || card.getNr()==1) return (card.getNr() < m_nr);
return (m_nr < card.getNr());
}
|
C# | UTF-8 | 2,315 | 2.640625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using XNA3D.Collision.Interfaces;
namespace XNA3D.Collision.Bodies
{
public class CollisionLinkAABB2 : CollisionLink<ICollisionAABB, ICollisionAABB>
{
public CollisionLinkAABB2(ICollisionAABB c1, ICollisionAABB c2)
: base(c1, c2)
{
}
public override CollisionInformation collide()
{
CollisionInformation info = new CollisionInformation();
info.Offset = c1.BoxCenter - c2.BoxCenter;
info.Distance = info.Offset.Length();
Vector3 absOffset = new Vector3(
info.Offset.X < 0f ? -info.Offset.X : info.Offset.X,
info.Offset.Y < 0f ? -info.Offset.Y : info.Offset.Y,
info.Offset.Z < 0f ? -info.Offset.Z : info.Offset.Z
);
Vector3 displace = absOffset - (c1.BoxHalfSize + c2.BoxHalfSize);
float otherDepth;
float otherDepth2;
if (displace.X < displace.Y)
{
if (displace.X < displace.Z)
{
info.CollisionDepth = -displace.X;
otherDepth = -displace.Y;
otherDepth2 = -displace.Z;
}
else
{
info.CollisionDepth = -displace.Z;
otherDepth = -displace.Y;
otherDepth2 = -displace.X;
}
}
else
{
if (displace.Y < displace.Z)
{
info.CollisionDepth = -displace.Y;
otherDepth = -displace.X;
otherDepth2 = -displace.Z;
}
else
{
info.CollisionDepth = -displace.Z;
otherDepth = -displace.Y;
otherDepth2 = -displace.X;
}
}
if (info.CollisionDepth > 0f && otherDepth >= 0f && otherDepth2 >= 0f)
{
info.HasCollided = true;
}
else
{
info.HasCollided = false;
}
return info;
}
}
}
|
C++ | UTF-8 | 1,551 | 3.609375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct node{
int value;
struct node *left;
struct node *right;
};
struct node* createNode(int value){
struct node *root = (struct node *)malloc(sizeof(struct node));
root->value = value;
root->right = NULL;
root->left = NULL;
return root;
}
struct node* mirror(struct node *root){
if(!root)
return NULL;
struct node * temp = root->right;
root->right = root->left;
root->left = temp;
mirror(root->left);
mirror(root->right);
return root;
}
struct node* insert(struct node *root,int value){
if(!root)
return createNode(value);
if(root->value>value){
root->left = insert(root->left,value);
}else if(root->value<=value){
root->right = insert(root->right,value);
}
return root;
}
void preorder(struct node *root){
if(!root) return;
cout<<root->value<<" ";
preorder(root->left);
preorder(root->right);
}
int isBalancedUtil(struct node* root){
if(!root) return 0;
int left = isBalancedUtil(root->left);
if(left==-1) return -1;
int right = isBalancedUtil(root->right);
if(right==-1) return -1;
if(abs(left-right)>1) return -1;
return left>right?left+1:right+1;
}
int isBalanced(struct node* A) {
if(isBalancedUtil(A)==-1) return 0;
return 1;
}
int main(){
int n,v;
cin>>n;
struct node *root = (struct node *)malloc(sizeof(struct node));
for(int i=0;i<n;i++){
cin>>v;
root = insert(root,v);
}
preorder(root);
cout<<"\n";
root = mirror(root);
preorder(root);
return 0;
} |
C# | UTF-8 | 738 | 2.578125 | 3 | [] | no_license | using System;
[Serializable]
public class IntrigueCard : AbstractProgressCard
{
public IntrigueCard (int id) : base(id)
{
CardType = ProgressCardType.Politic;
}
public override void ExecuteCardEffect() {
GameManager.LocalPlayer.GetComponent<GamePlayer> ().intrigueProgressCardUsed = true;
UIIntrigueProgressCard pCardUi = GameManager.LocalPlayer.AddComponent<UIIntrigueProgressCard> ();
pCardUi.CurrentCard = this;
}
public override string GetTitle ()
{
return "Intrigue";
}
public override string GetDescription ()
{
return "You may displace one of your opponent’s knights, without using a knight of your own. The knight must be on an intersection connected to one of your roads or lines of ships.";
}
}
|
C++ | UTF-8 | 569 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
#define SENTENCE_LENGTH 65535
#ifndef _MSC_VER
#define gets_s gets
#endif
bool isVowel(char alphabet) {
return (alphabet == 'a') || (alphabet == 'A') || (alphabet == 'e') || (alphabet == 'E') ||
(alphabet == 'i') || (alphabet == 'I') || (alphabet == 'o') || (alphabet == 'O') || (alphabet == 'u') || (alphabet == 'U');
}
int main() {
for (int trial = 0; trial < 3; trial++) {
char a[SENTENCE_LENGTH];
gets_s(a);
for (int i = 0; a[i] && i < SENTENCE_LENGTH; i++) {
if (isVowel(a[i])) {
putchar(a[i]);
}
}
putchar(10);
}
} |
C++ | UTF-8 | 1,003 | 3.328125 | 3 | [] | no_license | #pragma once
#include <stdlib.h>
#include <string.h>
#include <boost/scoped_ptr.hpp>
namespace rage {
class Buffer // buffer for data storage
{
private:
boost::scoped_ptr<char> data; // data in buffer
unsigned int size; // total size of buf (in bytes)
protected:
char* getCBuffer() const { // get char data
return data.get();
}
public:
Buffer() : size(0) {}
Buffer(unsigned int sz) : size(0) {
resize(sz);
}
Buffer(void *dt, unsigned int sz) {
Buffer::Buffer(sz);
memcpy(getBuffer(), dt, sz);
}
Buffer::Buffer(const Buffer& b) {
Buffer::Buffer(b.getSize());
memcpy(getBuffer(), b.getBuffer(), b.getSize());
}
Buffer::~Buffer() {}
void* resize(unsigned int newSize); // resize for new sz
void clear();
void* getBuffer() const { // get data
return (void*)data.get();
}
unsigned int getSize() const { // get size of data buf
return size;
}
bool isEmpty() const { // check if buf is empty
return (size == 0);
}
};
}
|
Python | UTF-8 | 715 | 2.9375 | 3 | [
"MIT"
] | permissive | import os, json, sys
class Config(object):
def __init__(self):
script_dir = os.path.dirname(__file__)
config_rel_path = 'config.json'
config_abs_path = os.path.join(script_dir, config_rel_path)
try:
with open(config_abs_path) as config_file:
config = json.load(config_file)
self._config = config
except IOError:
print("Can't open configuration file "+config_abs_path)
sys.exit(0)
def get(self, property_name):
if property_name not in self._config.keys(): # we don't want KeyError
return None # just return None if not found
return self._config[property_name] |
Java | GB18030 | 4,089 | 3.65625 | 4 | [] | no_license | package com.just.play;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Hello {
public static void main(String[] args){
/*
* תdouble8ֽڣתΪint4ֽڣ
*/
double avg = 77.5;
int rise =5;
int avg2 = (int) (avg + rise);//ǿתݲǽСֽȥ
double arg3 = avg + rise;
System.out.println(avg2 + "-" + arg3);
/*
* ıı,һôд
*/
final String HELLO = "world";
System.out.println(HELLO);
/*
* ֵ
*/
int one = 10;
int two = 20;
two -= one;
System.out.println(two);
System.out.println(one > two);
/*
* && || ! ^()
*/
System.out.println( (one > two) && one < two);
/*
*
*/
String s = (2 > 1) ? "21" :"2С1";
System.out.println(s);
//ѭڻswitchʹbreakѭ
int num = 999;
int count = 0;
while(num != 0){
count++;
num /= 10;
}
System.out.println(count);
int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 2 != 0){
continue;
}
sum = sum + i;
System.out.print("ż" + i);
}
System.out.println("ż֮" + sum);
int score = 53;
int cal = 0;
while(score <= 60){
score++;
cal++;
}
System.out.println(cal);
//ַ
String[] str1 = new String[5]; //һΪ5String(ַ)͵һά
String[] str2 = new String[]{"","","","",""};
String[] str3= {"","","","",""};
String[] str = new String[]{"sports"," read", " listen music"};
for(int i = 0; i < str.length; i++){
System.out.print(str[i]);
}
int arr[] = new int[3];
Arrays.fill(arr, 2);
Arrays.fill(arr, 0, 1, 7);
Arrays.sort(arr);
Arrays.copyOf(arr, 3);
long a = Runtime.getRuntime().totalMemory();
// Arrays.fill(array, start, end, value);
for (int i : arr) {
System.out.print( "i =" + i + "\t");
}
// Hello.compare();
// Hello.random();
// Hello.showTop3();
// Hello.getNN();
// Hello.getint();
Hello.getMemory();
}
//һ㷽ҪСд
public static void compare(){
int[] a = new int[]{61, 23, 4, 74, 13, 148, 20};
int max = a[0];
int min = a[0];
for(int i = 0; i < a.length; i++){
if(a[i] > max){
max = a[i];
}
if(a[i] < min){
min = a[i];
}
}
System.out.println("max = " + max + " min = " + min);
}
/*
*
* ͬһУͬѾ˳ͬ
*/
public static int[] random(){
int[] inte = new int[8];
for(int i = 0; i < inte.length ; i++){
inte[i] = (int) (Math.random()*100);
System.out.print(inte[i] + " ");
}
return inte;
}
public static void showTop3(){
int[] scores = {89 , -23 , 64 , 91 , 119 , 52 , 73};
Arrays.sort(scores);
int num= 0;
for(int i = scores.length - 1; i >= 0 ; i--){
if( !(scores[i] >= 0 && scores[i] <=100)){
continue;
}
num ++;
if(num > 3){
break;
}
System.out.println(scores[i]);
}
}
public static void getNN(){
for(int i = 1; i <= 9; i++){
for(int j = 1; j <= i; j++){
System.out.print(j + "*" + i + "=" + i*j + "\t");// \t = " "
}
System.out.println();
}
}
public static int getint(){
int a = 0;
if(a < 10){
a++;
return 0;
}
System.out.println(a);
return a;
}
public static void getMemory(){
int num1 = 1024*1024*2;
int arr1[] = new int[num1];
for (int i = 0; i < arr1.length; i++) {
arr1[i] = i;
}
//ռڴ浥λתΪMB
long memory1 = Runtime.getRuntime().totalMemory()/1024/1024;
System.out.println("memory1 = " + memory1);
int num2 = 1024*1024;
int arr2[][] = new int[num2][2];
for (int i = 0; i < arr2.length; i++) {
arr2[i][0] = i;
arr2[i][1] = i;
}
long memory2 = Runtime.getRuntime().totalMemory()/1024/1024;
System.out.println("memory2 = " + memory2);
}
}
|
Shell | UTF-8 | 648 | 3.71875 | 4 | [
"MIT"
] | permissive | #!/bin/bash
# This script is to be run after the code is deployed to its hosting environment
user="$1"
if [ -z "$user" ]; then
echo "Please provide the username for the service to use as the first argument"
exit 1
fi
cat > /etc/systemd/system/mobro.service << HEREDOC_END
[Unit]
Description = Controls the MoBro service
Wants = network-online.target
After = network-online.target
[Service]
Type = simple
ExecStart = $(pwd)/start.sh
WorkingDirectory = $(pwd)
User = $user
[Install]
WantedBy = multi-user.target
HEREDOC_END
systemctl daemon-reload
systemctl enable mobro
|
Java | UTF-8 | 2,139 | 2.59375 | 3 | [] | no_license | package gr.ds.unipi.spades.queries;
import java.util.HashMap;
import org.apache.commons.lang3.StringUtils;
public class Query {
protected int jaccardCount;
protected int haversineCount;
protected int pairsCount;
protected int quadTreeDuplications;
protected int regularGridDuplications;
protected int mbrCount;
protected HashMap<Integer, Integer> bins = new HashMap<Integer, Integer>();
// File 1 Fields
protected int file1LonIndex, file1LatIndex;
// File 2 Fields
protected int file2LonIndex, file2LatIndex;
// File separator (must be the same for both files)
protected String separator;
// Index of tag in each record of a file (must be the same for both files)
protected int tagIndex;
public Query(int file1LonIndex, int file1LatIndex, int file2LonIndex,
int file2LatIndex, String separator, int tagIndex) {
this.file1LonIndex = file1LonIndex;
this.file1LatIndex = file1LatIndex;
this.file2LonIndex = file2LonIndex;
this.file2LatIndex = file2LatIndex;
this.separator = separator;
this.tagIndex = tagIndex;
}
public HashMap<Integer, Integer> getBins() {
return bins;
}
public void resetBins() {
bins.clear();
}
public void insertToBins(Integer key, Integer value) {
if (bins.containsKey(key)) return;
bins.put(key, value);
}
public void incrementBinsKey(Integer key) {
if (!bins.containsKey(key)) {
insertToBins(key, new Integer(1));
return;
}
bins.replace(key, new Integer(bins.get(key).intValue() + 1));
}
// Method for extracting a substring of a delimited String
protected String extractWord(String record, int index, String separator) {
String word;
int ordinalIndex;
if (index == 0) {
word = record.substring(0, record.indexOf(separator));
} else {
ordinalIndex = StringUtils.ordinalIndexOf(record, separator, index);
if (ordinalIndex == StringUtils.lastOrdinalIndexOf(record, separator, 1))
{
word = record.substring(ordinalIndex + 1);
} else {
word = record.substring(ordinalIndex + 1, StringUtils.ordinalIndexOf(record, separator, index + 1));
}
}
return word;
}
}
|
Java | UTF-8 | 629 | 2.015625 | 2 | [] | no_license | package com.gradle.gradle;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class GradleApplication {
public static void main(String[] args) {
SpringApplication.run(GradleApplication.class, args);
}
@RequestMapping(value = "/hello")
public String hello(){
return "hello manish";
}
@RequestMapping(value = "/msg")
public String getMsg(){
return "hello to java ";
}
}
|
C++ | UTF-8 | 602 | 3.234375 | 3 | [] | no_license | #include "Singleton.h"
#include <iostream>
using namespace std;
Singleton* Singleton::pInstance1 = NULL;
pthread_mutex_t Singleton::lock = PTHREAD_MUTEX_INITIALIZER;
Singleton::Singleton()
{
cout<< "Singleton..." << endl;
}
Singleton* Singleton::Instance()
{
if(NULL == pInstance1)
{
//Double-checked Locking
pthread_mutex_lock(&lock);
if (NULL == pInstance1)
{
pInstance1 = new Singleton();
}
pthread_mutex_unlock(&lock);
}
return pInstance1;
}
void Singleton::Destroy()
{
delete pInstance1;
pInstance1 = NULL;
cout<< "Destroy..." << endl;
}
|
Python | UTF-8 | 4,341 | 2.828125 | 3 | [] | no_license | from nltk.corpus import brown
import operator
import numpy as np
SENTENCES_KEEP_WORDS=['king',
'man',
'queen',
'woman',
'italy',
'rome',
'france',
'paris',
'london',
'britain',
'england'
]
class Sentences(object):
def __init__(self, n_sentences=None, keep_words=SENTENCES_KEEP_WORDS):
sentences = brown.sents()
if n_sentences is None:
self.sentences = sentences
if n_sentences > len(sentences):
self.sentences = sentences
else:
self.sentences = sentences[:n_sentences]
self.keep_words = set(keep_words)
self.indx_sent, self.word2idx, self.idx2word = self._build_idx()
def _build_idx(self):
indx_sents = []
idx2word = ['START', 'END']
word2idx = {'START' : 0,
'END' : 1
}
idx = len(word2idx.keys())
for sentence in self.sentences:
indx_sent = []
for token in sentence:
token = token.lower()
if token not in word2idx:
word2idx[token] = idx
idx2word.append(token)
idx += 1
indx_sent.append(word2idx[token])
indx_sents.append(indx_sent)
assert len(set(idx2word)) == len(idx2word)
return indx_sents, word2idx, idx2word
def limit_vocab(self, n_limit=500):
word2count = {word : 0 for word in self.word2idx.keys()}
for sentence in self.indx_sent:
for indx in sentence:
word2count[self.idx2word[indx]] += 1
word2count = sorted(word2count.items(),
key=operator.itemgetter(1),
reverse=True)
word2idx_limit = {'START' : 0,
'END' : 1
}
idx = len(word2idx_limit.keys())
for word in self.keep_words:
word2idx_limit[word] = idx
idx += 1
base_len = len(word2idx_limit.keys())
for word_tuple in word2count[:n_limit-base_len]:
word2idx_limit[word_tuple[0]] = idx
idx += 1
word2idx_limit['UNKNOWN'] = idx
idx2word_limit = {val : key for key, val in word2idx_limit.items()}
indx_sent_limit = []
for sentence in self.indx_sent:
if len(sentence) > 1:
new_indx_sent = [word2idx_limit[self.idx2word[idx]]
if self.idx2word[idx] in word2idx_limit.keys()
else n_limit-1
for idx in sentence]
indx_sent_limit.append(new_indx_sent)
return indx_sent_limit, word2idx_limit, idx2word_limit
def train_test_split_bigram(self, train_percentage=0.8, n_limit=500):
indx_sent, word2idx, idx2word = self.limit_vocab(n_limit=n_limit)
train_percentage = 0.8
n_vocab = len(word2idx.keys())+1
n_sentence = len(indx_sent)
n_train_sentence = round(n_sentence*train_percentage)
n_test_sentence = n_sentence - n_train_sentence
# TRAIN
train_sentence = indx_sent[:n_train_sentence]
n_train_word = sum(len(sentence)-1 for sentence in train_sentence)
X_train = np.zeros((n_vocab, n_train_word))
y_train = np.zeros(n_train_word)
j = 0
for sentence in train_sentence:
for idx in range(len(sentence)-1):
X_train[sentence[idx], j] = 1
y_train[j] = sentence[idx+1]
j += 1
# TEST
test_sentence = indx_sent[n_train_sentence:]
n_test_word = sum(len(sentence)-1 for sentence in test_sentence)
X_test = np.zeros((n_vocab, n_test_word))
y_test = np.zeros(n_test_word)
j = 0
for sentence in test_sentence:
for idx in range(len(sentence)-1):
X_test[sentence[idx], j] = 1
y_test[j] = sentence[idx+1]
j += 1
return X_train, y_train, X_test, y_test
#sentences = Sentences()
#print(sentences.limit())
|
Java | UTF-8 | 2,461 | 3.109375 | 3 | [] | no_license | package week3;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.Random;
public class Week3Test {
int[] arrayInit(int min){
Random rand = new Random();
int n = rand.nextInt(100);
int[] a = new int[n+1];
a[n] = min;
for(int i = n-1 ; i>=0 ; i--){
a[i] = rand.nextInt(100) + min;
}
return a;
}
// TODO: Viết 5 testcase cho phương thức max()
@Test
public void testMax1(){
assertEquals(1514, Week3.max(15, 1514));
}
@Test
public void testMax2(){
assertEquals(0, Week3.max(-6, 0));
}
@Test
public void testMax3(){
assertEquals(3, Week3.max(3, 3));
}
@Test
public void testMax4(){
assertEquals(10, Week3.max(10, 0));
}
@Test
public void testMax5(){
assertEquals(-15, Week3.max(-21, -15));
}
// TODO: Viết 5 testcase cho phương thức minOfArray()
@Test
public void testMinOfArray0(){
int[] a0 = new int[]{};
assertEquals(-1,Week3.minOfArray(a0));
System.out.println();
}
@Test
public void testMinOfArray1(){
int[] a1 = arrayInit(6);
assertEquals(6,Week3.minOfArray(a1));
}
@Test
public void testMinOfArray2(){
int[] a2 = arrayInit(-15);
assertEquals(-15,Week3.minOfArray(a2));
}
@Test
public void testMinOfArray3(){
int[] a3 = arrayInit(10);
assertEquals(10,Week3.minOfArray(a3));
}
@Test
public void testMinOfArray4(){
int[] a4 = arrayInit(100);
assertEquals(100,Week3.minOfArray(a4));
}
@Test
public void testMinOfArray5(){
int[] a5 = arrayInit(10);
assertEquals(10,Week3.minOfArray(a5));
}
// TODO: Viết 5 testcase cho phương thức calculateBMI()
@Test
public void testCalculateBMI1(){
assertEquals("Thừa cân",Week3.calculateBMI(60,1.60));
}
@Test
public void testCalculateBMI2(){
assertEquals("Bình thường",Week3.calculateBMI(49,1.60));
}
@Test
public void testCalculateBMI3(){
assertEquals("Thiếu cân",Week3.calculateBMI(52,1.70));
}
@Test
public void testCalculateBMI4(){
assertEquals("Béo phì",Week3.calculateBMI(90,1.70));
}
@Test
public void testCalculateBMI5(){
assertNull(Week3.calculateBMI(-5,1.60));
}
}
|
Java | UTF-8 | 230 | 1.703125 | 2 | [
"Apache-2.0"
] | permissive | package org.ithang.tools.model;
/**
* 常量类
* @author Administrator
*
*/
public class Const {
public final static int LogType_SystemBoot=1;//系统启动
public final static int LogType_SystemDonw=2;//系统关闭
}
|
Python | UTF-8 | 2,061 | 2.6875 | 3 | [
"MIT"
] | permissive | from pyaml import yaml
import argparse
import rl_learning as rl
def load_config(config_file):
with open(config_file) as f:
config = yaml.load(f)
return config
def train_rl_agent(config, train=True):
environment_params = config['environment_params']
rl_params = config['rl_params']
model_params = config['model_params']
bandit_params = config['bandit_params']
training_params = config['training_params']
testing_params = config['testing_params']
if train:
rl.train_with_threads(environment_params, rl_params, bandit_params, model_params,
num_of_threads=training_params['number_of_threads'], epochs=training_params['epochs'], train=True,
display_state=False, use_processes=training_params['use_processes'])
else:
stat = rl.test_trained_model_with_random_play(environment_params, test_games=testing_params['test_games'], render=False)
stat_for_display = rl.test_trained_model_with_random_play(environment_params, test_games=testing_params['display_games'],
render=True)
print stat
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Train or test the given environment')
parser.add_argument('--config', dest='config_file', type=str, required=True,
help='full path to the yaml configuration file')
parser.add_argument('--train', dest='train_and_test', action='store_true',
help='indicate whether to train and test the environment')
parser.add_argument('--test', dest='only_test', action='store_true',
help='indicate whether simply test the environment with existing trained model')
args = parser.parse_args()
rl_config = load_config(args.config_file)
if args.train_and_test:
train_rl_agent(rl_config, train=args.train_and_test)
if args.train_and_test or args.only_test:
train_rl_agent(rl_config, train=False)
|
Python | UTF-8 | 116 | 3.125 | 3 | [] | no_license | n=int(input())
for i in range(n):
m=int(input())
if(m%5==0):
print(-1)
else:
print(m%5) |
Python | UTF-8 | 3,270 | 2.578125 | 3 | [
"MIT"
] | permissive | from pynmmso.listeners.base_listener import BaseListener
class MultiListener(BaseListener):
"""
Listener that contains multiple listeners and calls them for each event.
"""
def __init__(self):
super().__init__()
self.listeners = []
def add_listener(self, listener):
"""
Adds a new listener.
Arguments
---------
listener
The listener to add.
"""
self.listeners.append(listener)
def set_nmmso(self, nmmso):
for listener in self.listeners:
listener.set_nmmso(nmmso)
def iteration_started(self):
for listener in self.listeners:
listener.iteration_started()
def location_evaluated(self, location, value):
for listener in self.listeners:
listener.location_evaluated(location, value)
def swarm_peak_changed(self, swarm, old_location, old_value):
for listener in self.listeners:
listener.swarm_peak_changed(swarm, old_location, old_value)
def swarm_created_at_random(self, new_swarm):
for listener in self.listeners:
listener.swarm_created_at_random(new_swarm)
def swarm_created_from_crossover(self, new_swarm, parent_swarm1, parent_swarm2):
for listener in self.listeners:
listener.swarm_created_from_crossover(new_swarm, parent_swarm1, parent_swarm2)
def merging_started(self):
for listener in self.listeners:
listener.merging_started()
def merged_close_swarms(self, swarm1, swarm2):
for listener in self.listeners:
listener.merged_close_swarms(swarm1, swarm2)
def merged_saddle_swarms(self, swarm1, swarm2):
for listener in self.listeners:
listener.merged_saddle_swarms(swarm1, swarm2)
def merging_ended(self):
for listener in self.listeners:
listener.merging_ended()
def incrementing_swarms_started(self):
for listener in self.listeners:
listener.incrementing_swarms_started()
def swarm_added_particle(self, swarm):
for listener in self.listeners:
listener.swarm_added_particle(swarm)
def swarm_moved_particle(self, swarm):
for listener in self.listeners:
listener.swarm_moved_particle(swarm)
def incrementing_swarms_ended(self):
for listener in self.listeners:
listener.incrementing_swarms_ended()
def hiving_swams_started(self):
for listener in self.listeners:
listener.hiving_swams_started()
def hiving_new_swarm(self, new_swarm, parent_swarm):
for listener in self.listeners:
listener.hiving_new_swarm(new_swarm, parent_swarm)
def hiving_swarms_ended(self):
for listener in self.listeners:
listener.hiving_swarms_ended()
def iteration_ended(
self, n_new_locations, n_mid_evals, n_evol_modes, n_rand_modes, n_hive_samples):
for listener in self.listeners:
listener.iteration_ended(
n_new_locations, n_mid_evals, n_evol_modes, n_rand_modes, n_hive_samples)
def max_evaluations_reached(self):
for listener in self.listeners:
listener.max_evaluations_reached()
|
Go | UTF-8 | 607 | 3.75 | 4 | [] | no_license | package main
import (
"fmt"
)
func main() {
array := [6]int{2, 3, 4, 5, 6, 7}
findMax(array[:])
findMin(array[:])
calculateAverage(array[:])
}
func findMax(arr []int) {
max := arr[0]
for _, v := range arr {
if v > max {
max = v
}
}
fmt.Println(max)
}
func findMin(arr []int) {
min := arr[0]
for _, v := range arr {
if v < min {
min = v
}
}
fmt.Println(min)
}
func calculateAverage(arr []int) {
ave := float64(0)
total := 0
for _, v := range arr {
total = total + (v)
ave = float64(total) / float64(len(arr)) // ave is needs to be of type float
}
fmt.Println(ave)
}
|
Python | UTF-8 | 235 | 3.1875 | 3 | [] | no_license | f = open("c:\python\scores.txt","r")
participants = {}
for line in f:
entry = line.strip().split(",")
participant = entry[0]
score = entry[1]
participants[participant] = score
print(participant + ":" + score)
f.close |
C++ | UTF-8 | 1,914 | 2.796875 | 3 | [
"MIT"
] | permissive | ///////////////////////////////////////////////////////////////////////////////
///
/// \file ObjectStore.hpp
/// Declaration of the ObjectStore.
///
/// Authors: Chris Peters
/// Copyright 2010-2011, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
DeclareEnum3(StoreResult, Added, Replaced, Failed);
/// Object cache is use to store objects at runtime.
class ObjectStore : public ExplicitSingleton<ObjectStore>
{
public:
ZilchDeclareType(TypeCopyMode::ReferenceType);
/// Set the object store name. This is to prevent
/// store name conflicts.
void SetStoreName(StringParam storeName);
/// Is there an entry record for the object in the store?
bool IsEntryStored(StringParam name);
/// Get number of entries in the ObjectStore.
uint GetEntryCount();
/// Get the ObjectStore entry at the specified index.
String GetEntryAt(uint index);
/// Store an object.
StoreResult::Enum Store(StringParam name, Cog* object);
/// Restore an object to the space.
Cog* Restore(StringParam name, Space* space);
/// Restore an object if it is not stored use the archetype to create it.
Cog* RestoreOrArchetype(StringParam name, Archetype* archetype, Space* space);
/// Attempts to remove an object from the store.
void Erase(StringParam name);
/// Clear the store
void ClearStore();
/// Returns the directory path to the object store
String GetDirectoryPath();
private:
//Helper function for file names.
String GetFile(StringParam name);
void SetupDirectory();
/// Populate the internal array of file names in the ObjectStore, if the proper
/// ObjectStore directory exists.
void PopulateEntries(StringParam storePath);
String mStoreName;
String mStorePath;
Array<String> mEntries;
};
}
|
Java | UTF-8 | 1,916 | 2.453125 | 2 | [] | no_license | package sk.lacko.reality_scanner;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.apache.commons.cli.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
@Autowired
private WebClient webClient;
@Autowired
private PageRunner pageRunner;
@Override
public void run(String... args) throws Exception {
Options options = new Options();
Option input = new Option("p", "page", true, "Page to scan. Supported pages: www.reality.sk");
input.setRequired(true);
options.addOption(input);
Option output = new Option("s", "search", true, "What to search. Supported values: F - flat, H - house");
output.setRequired(false);
options.addOption(output);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);
System.exit(1);
}
String[] inputFilePath = cmd.getOptionValues("page");
for (int i = 0; i < inputFilePath.length; i++) {
HtmlPage htmlPage = webClient.getPage(inputFilePath[i]);
pageRunner.runSearch(new SearchPage(htmlPage));
}
String[] outputFilePath = cmd.getOptionValues("search");
System.exit(1);
}
}
|
JavaScript | UTF-8 | 769 | 3.453125 | 3 | [] | no_license | //basic way
function MyClass(pArgs) {
this.construct = function () {
this.attr1 = 42;
this.attr2 = 42;
this.attr3 = 42;
this.attr4 = 42;
};
this.method1 = function () {
doStuffs;
};
this.method1 = function () {
doStuffs;
};
this.method1 = function () {
doStuffs;
};
this.method1 = function () {
doStuffs;
};
this.construct();
}
//modern way
class Myclass {
constructor() {
this.attr1 = 42;
this.attr2 = 42;
this.attr3 = 42;
this.attr4 = 42;
}
static staticMethod() {
//to call like MyClass.staticMethod();
}
method1() {
//no kw function
doStuff;
}
method2() {
doStuff;
}
method3() {
doStuff;
}
method4() {
doStuff;
}
};
|
Java | UTF-8 | 3,204 | 2.5 | 2 | [
"MIT"
] | permissive | package nbpio.project;
public final class LibraryDefinition {
private final int id;
private final String name;
private final AuthorDefinition[] authors;
private final String description;
private final RepositoryDefinition repository;
private final String[] frameworks;
private final String[] platforms;
private final String[] keywords;
private final String version;
private LibraryDefinition( Builder src ) {
this.id = src.id;
this.name = src.name;
this.repository = src.repository;
this.authors = src.authors;
this.frameworks = src.frameworks;
this.platforms = src.platforms;
this.keywords = src.keywords;
this.description = src.description;
this.version = src.version;
}
public AuthorDefinition[] getAuthors() {
return authors;
}
public String[] getFrameworks() {
return frameworks;
}
public String[] getKeywords() {
return keywords;
}
public String[] getPlatforms() {
return platforms;
}
public RepositoryDefinition getRepository() {
return repository;
}
public String getVersion() {
return version;
}
public String getDescription() {
return description;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public static class Builder {
private int id;
private String name;
private RepositoryDefinition repository;
private String description;
private AuthorDefinition[] authors;
private String[] frameworks;
private String[] platforms;
private String[] keywords;
private String version;
public Builder() {}
public Builder id(int id) {
this.id = id;
return this;
}
public Builder authors( AuthorDefinition[] authors ) {
this.authors = authors;
return this;
}
public Builder platforms( String[] platforms ) {
this.platforms = platforms;
return this;
}
public Builder frameworks( String[] frameworks ) {
this.frameworks = frameworks;
return this;
}
public Builder keywords( String[] keywords ) {
this.keywords = keywords;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder repository(RepositoryDefinition repository) {
this.repository = repository;
return this;
}
public Builder version(String version) {
this.version = version;
return this;
}
public LibraryDefinition build() {
return new LibraryDefinition( this );
}
}
}
|
TypeScript | UTF-8 | 232 | 2.734375 | 3 | [] | no_license | import {isNullOrUndefined} from 'util';
export class StringUtils {
static isEmpty(text: string): boolean {
if (isNullOrUndefined(text)) {
return true;
}
text = text.trim();
return text === '';
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.