language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 3,584 | 2.609375 | 3 | [] | no_license | package com.example.ccei.compoundwidget;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Created by ccei on 2016-07-06.
*/
// 본 클래스는 LinearLayouyt 의 상위객체로 볼 수 있다.
public class ImageTextCompoundWidget extends LinearLayout {
/*
* AttributeSet attrs 는 app 와 관련된 것
* init(attrs)의 attrs는 속성값
*/
Context context;
ImageView imageIcon;
TextView textTitle;
ImageTextData data;
OnCompoundTARAListener impListener;
/*
자체 리스너를 선언
*/
public interface OnCompoundTARAListener {
public void onImageTextClick(ImageTextCompoundWidget compoundWidget, ImageTextData data); //콜백메소드
}
public void setOnIamgeTextClickListener(OnCompoundTARAListener listener){
impListener = listener;
}
/*
복합위젯 결합을 위해 필요한 메소드
*/
public ImageTextCompoundWidget(Context context) {
super(context);
this.context = context;
init(null);
}
public ImageTextCompoundWidget(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init(attrs);
}
public ImageTextCompoundWidget(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
//AttributeSet : 호출한 IamgeTextCompoundWudget의 모든 속성값을 사용한다.
private void init(AttributeSet attrs) {
this.setOrientation(HORIZONTAL); // Layout Param. 이 코드는 LinearLayour을 상속 받고 있기 때문에 사용 가능함
View root = inflate(context, R.layout.image_view_compound_widget, this); // inflation : UI의 객체화 과정, 위젯 결합
// / image+text 라는 자식 위에 linear 라는 부모 루트가 존재
imageIcon = (ImageView)root.findViewById(R.id.iamge_icon);
textTitle = (TextView)root.findViewById(R.id.text_title);
imageIcon.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(impListener != null) {
impListener.onImageTextClick(ImageTextCompoundWidget.this, data);
}
}// delecate 패던 : 위임한다.
});
if(attrs != null) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageTextCompoundWidget);
String memeberName = ta.getString(R.styleable.ImageTextCompoundWidget_membername);
int imageResID = ta.getResourceId(R.styleable.ImageTextCompoundWidget_myimage, R.mipmap.ic_launcher); // imageResID : 현재이미지의 위치를 알 수 있다
imageIcon.setImageResource(imageResID);
textTitle.setText(memeberName);
}
}
/*
UI에 데이터를 세팅시키기 위한 헬퍼메소드
*/
public void setImageText(ImageTextData data) {
this.data = data;
imageIcon.setImageResource(data.iconID);
textTitle.setText(data.title);
}
/* public void setTextTitle(String title) {
if(data == null) {
data = new ImageTextData();
}
data.title = title;
}*/
}
|
PHP | UTF-8 | 1,095 | 2.640625 | 3 | [
"OSL-3.0",
"LicenseRef-scancode-unknown-license-reference",
"AFL-2.1",
"AFL-3.0",
"MIT"
] | permissive | <?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Usps\Model\Source;
use Magento\Shipping\Model\Carrier\Source\GenericInterface;
use Magento\Usps\Model\Carrier;
/**
* Generic source
*/
class Generic implements GenericInterface
{
/**
* @var \Magento\Usps\Model\Carrier
*/
protected $shippingUsps;
/**
* Carrier code
*
* @var string
*/
protected $code = '';
/**
* @param \Magento\Usps\Model\Carrier $shippingUsps
*/
public function __construct(Carrier $shippingUsps)
{
$this->shippingUsps = $shippingUsps;
}
/**
* Returns array to be used in multiselect on back-end
*
* @return array
*/
public function toOptionArray()
{
$options = [];
$codes = $this->shippingUsps->getCode($this->code);
if ($codes) {
foreach ($codes as $code => $title) {
$options[] = ['value' => $code, 'label' => __($title)];
}
}
return $options;
}
}
|
Python | UTF-8 | 2,639 | 3.96875 | 4 | [
"MIT"
] | permissive | '''
1091. Shortest Path in Binary Matrix Medium
In an N by N square grid, each cell is either empty (0) or blocked (1).
A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that:
Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner)
C_1 is at location (0, 0) (ie. has value grid[0][0])
C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])
If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).
Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.
Example 1:
Input: [[0,1],[1,0]]
Output: 2
Example 2:
Input: [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
Note:
1 <= grid.length == grid[0].length <= 100
grid[r][c] is 0 or 1
'''
from queue import Queue
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
'''
perform BFS
8 directions
get shortest path...
[[0,0,0,0,1],
[1,0,0,0,0],
[0,1,0,1,0],
[0,0,0,1,1],
[0,0,0,1,0]]
'''
r_size = len(grid)
c_size = len(grid[0])
# Check for edge cases
if grid[0][0] or grid[r_size-1][c_size-1]:
return -1
visited = {}
q = Queue()
# Put starting point
q.put((0,0,1))
# Loop while queue not empty
while(not q.empty()):
r, c, path_count = q.get()
# Check if end location
if r == len(grid)-1 and c == len(grid[0])-1:
return path_count
# Loop through 8 directions
for _r, _c in [(-1,-1), (0,-1),(1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)]:
# Test each direction
curr_r, curr_c = r+_r, c+_c
# Ensure within grid range
if 0 <= curr_r < len(grid) and 0 <= curr_c < len(grid[0]):
# Check if cell has been visited
if (curr_r, curr_c) in visited:
continue
else:
visited[(curr_r, curr_c)] = 1
# If path is available
if grid[curr_r][curr_c] == 0:
# Add new path to queue
q.put((curr_r, curr_c, path_count+1))
# No paths found, return -1
return -1
|
Go | UTF-8 | 2,885 | 2.515625 | 3 | [] | no_license | package service
import (
"allsum_oa/model"
"bytes"
"common/lib/push"
"encoding/json"
"fmt"
"github.com/astaxie/beego"
"net"
"net/http"
"time"
)
func CreateMsg(m *model.Message) (err error) {
err = model.NewOrm().Table(model.Public + "." + model.Message{}.TableName()).Create(m).Error
return
}
func GetHistoryMsg(company string, uid, minId int) (msgs []*model.Message, err error) {
msgs = []*model.Message{}
err = model.NewOrm().Table(model.Public+"."+model.Message{}.TableName()).
Where("id < ? and user_id = ? and company_no = ?", minId, uid, company).
Order("id desc").Limit(500).Find(&msgs).Error
return
}
func GetLatestMsg(company string, uid, maxId int) (msgs []*model.Message, err error) {
msgs = []*model.Message{}
err = model.NewOrm().Table(model.Public+"."+model.Message{}.TableName()).
Where("id > ? and user_id = ? and company_no = ?", maxId, uid, company).
Order("id desc").Find(&msgs).Error
return
}
func GetMsgsByPage(company string, uid, page, limit int) (sum int, msgs []*model.Message, err error) {
db := model.NewOrm().Table(model.Public+"."+model.Message{}.TableName()).
Where("user_id = ? and company_no = ?", uid, company)
err = db.Count(&sum).Error
if err != nil {
return
}
msgs = []*model.Message{}
err = db.Order("id desc").Offset(limit * (page - 1)).Limit(limit).Find(&msgs).Error
return
}
func DelMsgById(msgId int) (err error) {
m := &model.Message{Id: msgId}
err = model.NewOrm().Table(model.Public + "." + model.Message{}.TableName()).Delete(m).Error
return nil
}
func DelMsgByType(company string, uid, tp int) (err error) {
m := &model.Message{
CompanyNo: company,
UserId: uid,
MsgType: tp,
}
err = model.NewOrm().Where(m).Delete(m).Error
return
}
//将消息存到和数据库同时使用极光推送推到App
func SaveAndSendMsg(m *model.Message) (err error) {
err = CreateMsg(m)
if err != nil {
beego.Error("save an message failed:", err)
return
}
content, err := json.Marshal(m)
if err != nil {
return err
}
alias := fmt.Sprintf("%s_%d", m.CompanyNo, m.UserId)
//go sendMsgToWeb(m)
go push.JPushMsgByAlias([]string{alias}, string(content))
return nil
}
func sendMsgToWeb(m *model.Message) {
client := &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
deadline := time.Now().Add(time.Second * 10)
c, err := net.DialTimeout(netw, addr, 5*time.Second)
if err != nil {
return nil, err
}
c.SetDeadline(deadline)
return c, nil
},
},
}
webpush := beego.AppConfig.String("webpush")
body, err := json.Marshal(m)
if err != nil {
beego.Error("json marshal error:", err)
return
}
request, err := http.NewRequest("POST", webpush, bytes.NewReader(body))
if err != nil {
beego.Error("http.NewRequest:", err)
return
}
_, err = client.Do(request)
if err != nil {
beego.Error(err)
}
}
|
Markdown | UTF-8 | 3,855 | 2.703125 | 3 | [] | no_license | # CouchImport
## Introduction
When populating CouchDB databases, often the source of the data is initially a CSV or TSV file. CouchImport is designed to assist you with importing flat data into CouchDB efficiently.
* simply pipe the data file to 'couchimport' on the command line
* handles tab or comma separated data
* uses Node.js's streams for memory efficiency
* plug in a custom function to add your own changes before the data is written
* writes the data in bulk for speed

## Installation
Requirements
* node.js
* npm
```
sudo npm install -g couchimport
```
## Configuration
CouchImport's configuration parameters are stored in environment variables.
### The location of CouchDB - default "http://localhost:5984"
Simply set the "COUCH_URL" environment variable e.g. for a hosted Cloudant database
```
export COUCH_URL="https://myusername:myPassw0rd@myhost.cloudant.com"
```
or a local CouchDB installation:
```
export COUCH_URL="http://localhost:5984"
```
### The name of the database - default "test"
Define the name of the CouchDB database to write to by setting the "COUCH_DATABSE" environment variable e.g.
```
export COUCH_DATABASE="mydatabase"
```
### Transformation function - default nothing
Define the path of a file containing a transformation function e.g.
```
export COUCH_TRANSFORM="/home/myuser/transform.js"
```
The file should:
* be a javascript file
* export one function that takes a single doc and returns the transformed version synchronously
(see examples directory). N.B it's best to use full paths for the transform function.
### Delimiter - default "/t"
The define the column delimiter in the input data e.g.
```
export COUCH_DELIMITER=","
```
## Running
Simply pipe the text data into "couchimport":
```
cat ~/test.tsv | couchimport
```
This example downloads public crime data, unzips and imports it:
```
curl 'http://data.octo.dc.gov/feeds/crime_incidents/archive/crime_incidents_2013_CSV.zip' > crime.zip
unzip crime.zip
export COUCH_DATABASE="crime_2013"
export COUCH_DELIMITER=","
ccurl -X PUT /crime_2013
cat crime_incidents_2013_CSV.csv | couchimport
```
In the above example we use "(ccurl)[https://github.com/glynnbird/ccurl]" a command-line utility that uses the same environment variables as "couchimport".
## Output
The following output is visible on the console when "couchimport" runs:
```
******************
COUCHIMPORT - configuration
{"COUCH_URL":"https://****:****@myhost.cloudant.com","COUCH_DATABASE":"aaa","COUCH_TRANSFORM":null,"COUCH_DELIMITER":","}
******************
Written 500 ( 500 )
Written 500 ( 1000 )
Written 500 ( 1500 )
Written 500 ( 2000 )
.
.
```
The configuration, whether default or overriden from environment variables is show, followed by a line of output for each block of 500 documents written, plus a cumulative total.
## Environment variables
* COUCH_URL - the url of the CouchDB instance (required)
* COUCH_DATABASE - the database to deal with (required)
* COUCH_DELIMITER - the delimiter to use (default '\t')
* COUCH_TRANSFORM - the path of a transformation function (not required)
* COUCHIMPORT_META - a json object which will be passed to the transform function (not required)
## Command-line parameters
You can now optionally override the environment variables by passing in command-line parameters:
* --url - the url of the CouchDB instance (required)
* --db - the database to deal with (required)
* --delimiter - the delimiter to use (default '\t')
* --transform - the path of a transformation function (not required)
* --meta - a json object which will be passed to the transform function (not required)
e.g.
```
cat test.csv | couchimport --db bob --delimeter ","
```
|
Markdown | UTF-8 | 4,113 | 2.9375 | 3 | [
"LicenseRef-scancode-public-domain",
"Zlib"
] | permissive | Ed25519
-------
This is a portable implementation of [Ed25519](http://ed25519.cr.yp.to/) based
on the SUPERCOP "ref10" implementation. All code is in the public domain.
All code is pure ANSI C without any dependencies, except for the random seed
generation which uses standard OS cryptography APIs. If you wish to be entirely
portable define `ED25519_NO_SEED`. This disables the `ed25519_create_seed`
function, so if your application requires key generation you must supply your
own seeding function (simply a 32 byte random number generator).
Performance
-----------
On a machine with an Intel Pentium B970 @ 2.3GHz I got the following speeds (running
on only one a single core):
Seed + key generation: 345us
Message signing (short message): 256us
Message verifying (short message): 777us
The speeds on other machines may vary. Sign/verify times will be higher with
longer messages.
Usage
-----
Simply add all .c and .h files in the `src/` folder to your project and include
`ed25519.h` in any file you want to use the API. If you prefer to use a shared
library, only copy `ed25519.h` and define `ED25519_DLL` before importing. A
windows DLL is pre-built.
There are no defined types for seeds, private keys, public keys or signatures.
Instead simple `unsigned char` buffers are used with the following sizes:
```c
unsigned char seed[32];
unsigned char signature[64];
unsigned char public_key[32];
unsigned char private_key[64];
unsigned char scalar[32];
```
API
---
```c
int ed25519_create_seed(unsigned char *seed);
```
Creates a 32 byte random seed in `seed` for key generation. `seed` must be a
writable 32 byte buffer. Returns 0 on success, and nonzero on failure.
```c
void ed25519_create_keypair(unsigned char *public_key, unsigned char *private_key, const unsigned char *seed);
```
Creates a new key pair from the given seed. `public_key` must be a writable 32
byte buffer, `private_key` must be a writable 64 byte buffer and `seed` must be
a 32 byte buffer.
```c
void ed25519_sign(unsigned char *signature,
const unsigned char *message, size_t message_len,
const unsigned char *public_key, const unsigned char *private_key);
```
Creates a signature of the given message with the given key pair. `signature`
must be a writable 64 byte buffer. `message` must have at least `message_len`
bytes to be read.
```c
int ed25519_verify(const unsigned char *signature,
const unsigned char *message, size_t message_len,
const unsigned char *public_key);
```
Verifies the signature on the given message using `public_key`. `signature`
must be a readable 64 byte buffer. `message` must have at least `message_len`
bytes to be read. Returns 1 if the signature matches, 0 otherwise.
```c
void ed25519_add_scalar(unsigned char *public_key, unsigned char *private_key,
const unsigned char *scalar);
```
Adds `scalar` to the given key pair where scalar is a 32 byte buffer (possibly
generated with `ed25519_create_seed`), generating a new key pair. You can
calculate the public key sum without knowing the private key and vice versa by
passing in `NULL` for the key you don't know. This is useful for enforcing
randomness on a key pair while only knowing the public key, among other things.
Warning: the last bit of the scalar is ignored - if comparing scalars make sure
to clear it with `scalar[31] &= 127`.
Example
-------
```c
unsigned char seed[32], public_key[32], private_key[64], signature[64];
const unsigned char message[] = "TEST MESSAGE";
/* create a random seed, and a key pair out of that seed */
if (ed25519_create_seed(seed)) {
printf("error while generating seed\n");
exit(1);
}
ed25519_create_keypair(public_key, private_key, seed);
/* create signature on the message with the key pair */
ed25519_sign(signature, message, strlen(message), public_key, private_key);
/* verify the signature */
if (ed25519_verify(signature, message, strlen(message), public_key)) {
printf("valid signature\n");
} else {
printf("invalid signature\n");
}
```
|
C++ | SHIFT_JIS | 2,452 | 2.640625 | 3 | [] | no_license | #include "Enemy.h"
#include "EnemyAI.h"
#include "MessageManager.h"
/// <summary>
///
/// </summary>
/// <param name="_enemy">GIuWFNgւ̃|C^</param>
void EnemyAI::initialize(Enemy* _enemy) {
pos = &_enemy->pos;
vel = &_enemy->vel;
targetPos = nullptr;
}
/// <summary>
///
/// </summary>
/// <param name="_enemy">GIuWFNgւ̃|C^</param>
void EnemyAIPlayerChase::initialize(Enemy* _enemy) {
this->EnemyAI::initialize(_enemy);
targetPos = MessageManager::getIns()->sendMessage<Vector2*>(MessageType::GET_PLAYER_POS_PTR);
}
/// <summary>
/// XV
/// </summary>
void EnemyAIPlayerChase::update() {
*vel = Vector2::createWithAngleNorm(Vector2::atan2fbyVec2(*pos, *targetPos), 0.5f);
}
/// <summary>
///
/// </summary>
/// <param name="_enemy">GIuWFNgւ̃|C^</param>
void EnemyAIRandomTargetChase::initialize(Enemy * _enemy) {
this->EnemyAI::initialize(_enemy);
targetPos = MessageManager::getIns()->sendMessage<Vector2*>(MessageType::GET_RANDOM_FIELDOBJECT_POS_PTR);
}
/// <summary>
/// XV
/// </summary>
void EnemyAIRandomTargetChase::update() {
*vel = Vector2::createWithAngleNorm(Vector2::atan2fbyVec2(*pos, *targetPos), 0.5f);
if (Vector2::distanceSquare(*pos, *targetPos) <= 100.0f) {
targetPos = MessageManager::getIns()->sendMessage<Vector2*>(MessageType::GET_RANDOM_FIELDOBJECT_POS_PTR);
}
}
/// <summary>
///
/// </summary>
/// <param name="_enemy">GIuWFNgւ̃|C^</param>
void EnemyAIDashInLight::initialize(Enemy* _enemy) {
this->EnemyAI::initialize(_enemy);
if (GetRand(1)) {
targetPos = MessageManager::getIns()->sendMessage<Vector2*>(MessageType::GET_PLAYER_POS_PTR);
}
else {
targetPos = MessageManager::getIns()->sendMessage<Vector2*>(MessageType::GET_RANDOM_FIELDOBJECT_POS_PTR);
}
}
/// <summary>
/// XV
/// </summary>
void EnemyAIDashInLight::update() {
int a = MessageManager::getIns()->sendMessage<int>(MessageType::POS_TO_LIGHTDATA, pos);
if (a > 50) {
*vel = Vector2::createWithAngleNorm(Vector2::atan2fbyVec2(*pos, *targetPos), 1.0f);
}
else {
*vel = Vector2::createWithAngleNorm(Vector2::atan2fbyVec2(*pos, *targetPos), 0.2f);
}
if (Vector2::distanceSquare(*pos, *targetPos) <= 100.0f) {
targetPos = MessageManager::getIns()->sendMessage<Vector2*>(MessageType::GET_RANDOM_FIELDOBJECT_POS_PTR);
}
}
|
PHP | UTF-8 | 210 | 3.34375 | 3 | [
"MIT"
] | permissive | <?php
$firstNumber = doubleval(readline());
$secondNumber = doubleval(readline());
$eps = 0.000001;
$diff = abs($firstNumber - $secondNumber);
if ($diff < $eps) {
echo "True";
} else {
echo "False";
}
|
JavaScript | UTF-8 | 4,041 | 3.109375 | 3 | [] | no_license | import React, { useState } from "react";
import Header from "./components/Header";
// Putting the api key into a base and a key inside an object
// **********************************************************
const api = {
key: process.env.REACT_APP_WEATHER_KEY,
base: "https://api.openweathermap.org/data/2.5/",
};
const App = () => {
// setting query and weather to their defaults using useState
// **********************************************************
const [query, setQuery] = useState("");
const [weather, setWeather] = useState({});
// handling the search with aysnc await
// *************************************
const search = async (evt) => {
if (evt.key === "Enter") {
try {
const results = await fetch(
`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`
);
const resultsJSON = await results.json();
setWeather(resultsJSON);
setQuery("");
} catch (error) {
console.error(error);
}
}
};
// handling the dates to be displayed by passing in NewDate as d
// *************************************************************
// todo: use the format options on the getDate & new Date calls instead of using months
// and days arrays
const dateBuilder = (unformattedDate) => {
// Setting the date format by using toLocaleDateString with options
// *****************************************************************
const day = unformattedDate.toLocaleDateString("en-US", { weekday: 'long' });
const date = unformattedDate.toLocaleDateString("en-US", { day: 'numeric' });
const month = unformattedDate.toLocaleDateString("en-US", { month: 'long' });
const year = unformattedDate.toLocaleDateString("en-US", { year: 'numeric' });
return `${day} ${date} ${month} ${year}`;
};
return (
// handling the weather display to show different backgrounds depending on temperatures
// ************************************************************************************
<div
className={
typeof weather.main != "undefined"
? weather.main.temp > 16
? "app warm"
: "app"
: "app"
}
// main jsx for the app
//************************
>
<Header></Header>
<main>
<div className="search-box">
<input
type="text"
className="search-bar"
placeholder="Search..."
onChange={(e) => setQuery(e.target.value)}
value={query}
onKeyPress={search}
/>
</div>
{
// if a location is found display the following jsx
//*************************************************
typeof weather.main != "undefined" ? (
<div>
<div className="location-box">
<div className="location">
{weather.name}, {weather.sys.country}
</div>
<div className="date">{dateBuilder(new Date())} </div>
</div>
<div className="weather-box">
<div className="temp">{Math.round(weather.main.temp)}°c</div>
<div className="weather">
Current conditions: {weather.weather[0].description}
</div>
<div className="wind">
Wind: {Math.round(weather.wind.speed * 3.6)} km/h
</div>
</div>
</div>
) : // handle an unknown location
// ******************************
weather.cod === "404" ? (
<div className="weather-box">
<div className="error"> {weather.message}!</div>
</div>
) : (
// display no search results upon load or no search results when enter is hit
// **************************************************************************
""
)
}
</main>
</div>
);
};
export default App;
|
Python | UTF-8 | 1,168 | 2.796875 | 3 | [] | no_license | import tkinter
master = tkinter.Canvas(width=300, height=600)
master.pack()
files = ["karta1.png", "karta2.png", "karta3.png", "karta4.png"]
imgs = []
for i in range(len(files)):
imgs.append([tkinter.PhotoImage(file=files[i]), 1, 0])
master.create_image(150, 50 + 80*i, image = imgs[i][0])
imgs[i][2] = master.create_rectangle(45, 20 + 80*i, 255, 80 + 80*i, outline = "", fill = "", tag = str(i))
def update(x, imgs):
print("ide")
print(imgs[x][1])
if(imgs[x][1] == 1):
master.itemconfig(imgs[x][2], outline="black")
else:
master.itemconfig(imgs[x][2], outline="")
imgs[x][1] *= -1
for i in range(len(imgs)):
master.tag_bind(imgs[i][2], "<Button-1>", lambda e, x=i : update(x, imgs))
txt = master.create_text(150, 450, text="vyhodnot", tag="vyh")
def vyhodn(e):
global imgs
for i in range(len(imgs)):
if(imgs[i][1] == 1):
imgs[i][1]= 0
else:
imgs[i][1] = 1
r = imgs[3][1]*8 + imgs[2][1]*4 + imgs[1][1]*2 + imgs[0][1]*1
master.delete("x")
master.create_text(150, 550, text=str(r), tag="x")
master.tag_bind("vyh", '<Button-1>', vyhodn)
master.mainloop() |
C++ | UTF-8 | 588 | 3.375 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
const int arr_size = 10;
vector<int> ivec;
int ia[arr_size];
int num;
cout << "Push " << arr_size << " integers into the vector: " << endl;
for(int i = 0; i < arr_size; ++i) {
cin >> num;
ivec.push_back(num);
}
auto iter = ivec.cbegin();
for(auto &i : ia) {
i = *iter;
++iter;
}
cout << "Result:" << endl;
for(auto i : ia)
cout << i << " ";
cout << endl;
return 0;
}
|
Java | UTF-8 | 782 | 2.578125 | 3 | [] | no_license | package additionalInfo;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* Class to test results
*/
public class Tests {
public static void main(String[] args) {
Routes routes = new Routes();
ResultSet result;
try {
ArrayList<Integer> lineNamesAndTypes = routes.getLineNameAndTypeByTripId("3_3685186");
for (int i = 0; i < lineNamesAndTypes.size(); i=i+2) {
System.out.println(lineNamesAndTypes.get(i));
System.out.println(lineNamesAndTypes.get(i + 1));
}
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
|
JavaScript | UTF-8 | 3,416 | 3.015625 | 3 | [] | no_license | //This library handles the protocol buffers required to get the MTA data in a useful format
const MtaGtfsRealtimeBindings = require("mta-gtfs-realtime-bindings");
//Request-promise is used instead of something like axios because it's simpler to decode binary responses using a protocol buffer in r-p
const rp = require("request-promise");
//First, combine the phone's location data with the list of stations and a 'distance' helper function to get the current station
//Then, use the camera to ID the relevant line, which will be used to select the proper MTA data feed for query
//For the purposes of developing the API query code, the data feed URL, current station, and current line will be hardcoded
async function queryMTA() {
const MTA_URL =
"http://datamine.mta.info/mta_esi.php?key=3f1463633a6a8c127fcd6560f9d6299a&feed_id=1";
const CURRENT_STATION = { id: "230", name: "Wall St." }; //The 'N' refers to the train's direction
const CURRENT_LINE = "2";
let uptownArrivalTimes = [];
let downtownArrivalTimes = [];
//A helper funciton that filters the trains for schedules containing the current stop and then logs the arrival time at this stop
const filterAndLog = (scheduleArray, stopId, tripId) => {
//let filtered = scheduleArray.filter(stop => stop.stop_id === stopId)
let uptownTrains = [];
let downtownTrains = [];
scheduleArray.forEach(function(stop) {
if (stop.stop_id === stopId + "N") {
uptownTrains.push(stop);
} else if (stop.stop_id === stopId + "S") {
downtownTrains.push(stop);
}
});
uptownTrains.length > 0
? uptownArrivalTimes.push([
new Date(uptownTrains[0].arrival.time.low * 1000),
tripId, scheduleArray
])
: null;
downtownTrains.length > 0
? downtownArrivalTimes.push([
new Date(downtownTrains[0].arrival.time.low * 1000),
tripId, scheduleArray
])
: null;
//Currently this logs in UTC time. Will eventually want to convert it to EST time
//filtered.length > 0 ? arrivalTimes.push(new Date(filtered[0].arrival.time.low * 1000)) : null
};
//Need to send the r-p with null encoding because of the specifics of GTFS spec
let arrivals = await rp({
method: "GET",
url: MTA_URL,
encoding: null
})
.then(buf => {
const feed = MtaGtfsRealtimeBindings.transit_realtime.FeedMessage.decode(
buf
);
//This will hold the trains of the type we care about
let relevantTrains = [];
//entity = a single train
feed.entity.forEach(entity => {
//Each train's ID will include the number/letter of it's line
if (entity.trip_update) {
if (entity.trip_update.trip.route_id.includes(CURRENT_LINE)) {
//Pushing all the relevant trains to an array for filtering
relevantTrains.push(entity);
}
}
});
//Filtering for trains scheduled to stop at the current stop and then logging the arrival times
relevantTrains.forEach(train =>
filterAndLog(
train.trip_update.stop_time_update,
CURRENT_STATION.id,
train.trip_update.trip.trip_id
)
);
downtownArrivalTimes = downtownArrivalTimes.sort((a, b) => a - b);
return [uptownArrivalTimes, downtownArrivalTimes];
})
.catch(e => console.log(e));
console.log(arrivals[0][2][2][0]);
}
queryMTA();
|
Java | UTF-8 | 2,068 | 2.84375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package util;
/**
*
* @author ACER
*/
public class MyToys {
// bộ thư viện các hàm xài chung, cho nên chúng là static
//cF: compute factorial, tính n giai thừa n! = 1.2.3....n
//0! = 1
//n! tăng nhanh lắm, cho nên để long đỡ
public static long cF(int n){
if(n < 0 || n > 15)
throw new IllegalArgumentException("Sorry, n must be >= 0");
if(n == 0)
return 1;
//phần còn lại là hợp lệ, tính bình thường
long product = 1;
for(int i = 1; i <= n; i++)
product *= i;
return product;
}
}
//mọi đoạn code bạn viết ra, phải cố gắng đảm bảo rằng nó có chất lượng
//chất lượng nghĩa là: hàm trả về, xử lý đúng như mình dự kiến, kì vọng
//expected
//ví dụ tính giai thừa() thì ta đưa vào 5, hi vọng nhận về 120
//vậy ta phải chuẩn bị bộ dữ liệu để test từng hàm, đảm bảo nó xử lý đúng
//từng hàm xử lý đúng, class xử lý đúng
//việc đảm bảo cho từng class/module/từng đơn thể/từng hàm chạy như dự kiến
//->DEV CÓ TRÁCH NHIỆM VỤ NÀY, VIỆC NÀY SONG SONG VIẾT CODE
//QUÁ TRÌNH NÀY GỌI LÀ UNIT TESTING
//làm sao test hàm(), chạy đúng ko
//ch bị data -> đưa data -> gọi hàm -> nhìn kết quả -> so với dự kiến
//nhìn kết quả: mắt(nhìn con số trả ra, so với con số mong đợi)
// nhìn bằng màu, số trả ra khớp với số mong đợi -> XANH
// KO KHỚP -> ĐỎ
//mắt -> sout, JOptionPane, POPUP, LOG, xem luận anh hùng, luận kết quả
//màu -> JUnit, TestNG, xUnit, NUnit, CPPUnit, PHPUnit,...
// bộ thư viện, .dll, .jar, giúp chúng ta luận theo màu |
Go | UTF-8 | 982 | 2.578125 | 3 | [] | no_license | package main
import "ayu/server"
import "ayu/server/storage/local"
import "flag"
import "fmt"
import "log"
import "net/http"
var host = flag.String("host", "localhost", "Hostname to bind HTTP server on")
var port = flag.Int("port", 8027, "TCP port to bind HTTP server on")
var static_data_dir = flag.String("static_data_dir", "static", "Directory containing static files to serve")
var poll_delay = flag.Int("poll_delay", 55, "Maximum time to block on poll requests (in seconds)")
var storage_dir = flag.String("storage_dir", "var", "Directory where persistent data is stored")
func main() {
flag.Parse()
if len(flag.Args()) > 0 {
log.Fatalln("Extra command line arguments", flag.Args())
}
addr := fmt.Sprintf("%s:%d", *host, *port)
storage := local.LocalStorage{*storage_dir}
server.Setup(*static_data_dir, *poll_delay,
func(*http.Request) server.SaveLoader { return &storage })
log.Println("Binding to address:", addr)
log.Fatalln(http.ListenAndServe(addr, nil))
}
|
Java | UTF-8 | 17,103 | 2.09375 | 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 aoop_ecommerce1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author J . Renael
*/
public class FnbFrame extends javax.swing.JFrame {
/**
* Creates new form FnbFrame
*/
Connection con = null ;
Statement state = null;
ResultSet res = null;
public FnbFrame() {
initComponents();
}
/**
* 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
spinnerAlmond = new javax.swing.JSpinner();
jLabel4 = new javax.swing.JLabel();
btnCartAlmond = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
spinnerMacaron = new javax.swing.JSpinner();
jLabel5 = new javax.swing.JLabel();
btnCartMacaron = new javax.swing.JButton();
btnHome = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(68, 138, 255));
jLabel1.setFont(new java.awt.Font("Dialog", 1, 36)); // NOI18N
jLabel1.setText("FOOD AND BEVERAGES");
jPanel2.setBackground(new java.awt.Color(131, 185, 255));
jLabel2.setForeground(new java.awt.Color(0, 0, 0));
jLabel2.setText("Kacang Almond");
spinnerAlmond.setModel(new javax.swing.SpinnerNumberModel(0, 0, null, 1));
spinnerAlmond.setBorder(null);
jLabel4.setForeground(new java.awt.Color(0, 0, 0));
jLabel4.setText("Quantity");
btnCartAlmond.setBackground(new java.awt.Color(68, 138, 255));
btnCartAlmond.setForeground(new java.awt.Color(0, 0, 0));
btnCartAlmond.setText("Add to Cart");
btnCartAlmond.setBorder(null);
btnCartAlmond.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCartAlmondActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(spinnerAlmond, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)))
.addGap(101, 101, 101))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(btnCartAlmond, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel2)
.addGap(35, 35, 35)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(spinnerAlmond, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnCartAlmond, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addContainerGap())
);
jPanel3.setBackground(new java.awt.Color(131, 185, 255));
jLabel3.setForeground(new java.awt.Color(0, 0, 0));
jLabel3.setText("Macaron");
spinnerMacaron.setModel(new javax.swing.SpinnerNumberModel(0, 0, null, 1));
spinnerMacaron.setBorder(null);
jLabel5.setForeground(new java.awt.Color(0, 0, 0));
jLabel5.setText("Quantity");
btnCartMacaron.setBackground(new java.awt.Color(68, 138, 255));
btnCartMacaron.setForeground(new java.awt.Color(0, 0, 0));
btnCartMacaron.setText("Add to Cart");
btnCartMacaron.setBorder(null);
btnCartMacaron.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCartMacaronActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnCartMacaron, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(spinnerMacaron, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(30, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel3)
.addGap(34, 34, 34)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel5)
.addComponent(spinnerMacaron, javax.swing.GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnCartMacaron, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
btnHome.setBackground(new java.awt.Color(0, 94, 203));
btnHome.setText("Home");
btnHome.setBorder(null);
btnHome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(46, 46, 46)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnHome, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)))
.addContainerGap(23, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(btnHome, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(65, 65, 65)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(32, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnHomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHomeActionPerformed
// TODO add your handling code here:
this.setVisible(false);
new HomePageFrame().setVisible(true);
}//GEN-LAST:event_btnHomeActionPerformed
private void btnCartAlmondActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCartAlmondActionPerformed
if((Integer)spinnerAlmond.getValue()==0){
JOptionPane.showMessageDialog(null, "Quantity Minimum Zero !", "Error Message", JOptionPane.OK_OPTION);
}
else{
try {
int id = 0 ;
con = DriverManager.getConnection("jdbc:derby://localhost:1527/TokipedDB");
String query = "SELECT MAX(CartID) FROM Cart";
state = con.createStatement();
res = state.executeQuery(query);
if (res.next()) {
id = res.getInt(1) + 1 ;
}
String namaBarang = "Kacang Almond" ;
Integer quantity = (Integer)spinnerAlmond.getValue();
int harga = quantity * 3000 ;
System.out.println(id);
PreparedStatement add = con.prepareStatement("insert Into Cart values (?,?,?,?)");
add.setInt(1, id);
add.setString(2, namaBarang);
add.setInt(3, quantity);
add.setInt(4, harga);
add.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
this.setVisible(false);
new HomePageFrame().setVisible(true);
}
}//GEN-LAST:event_btnCartAlmondActionPerformed
private void btnCartMacaronActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCartMacaronActionPerformed
if((Integer)spinnerMacaron.getValue()==0){
JOptionPane.showMessageDialog(null, "Quantity Minimum Zero !", "Error Message", JOptionPane.OK_OPTION);
}
else{
try {
int id = 0 ;
con = DriverManager.getConnection("jdbc:derby://localhost:1527/TokipedDB");
String query = "SELECT MAX(CartID) FROM Cart";
state = con.createStatement();
res = state.executeQuery(query);
if (res.next()) {
id = res.getInt(1) + 1 ;
}
String namaBarang = "Macaron" ;
Integer q = (Integer)spinnerMacaron.getValue();
int harga = q * 5000 ;
System.out.println(id);
PreparedStatement add = con.prepareStatement("insert Into Cart values (?,?,?,?)");
add.setInt(1, id);
add.setString(2, namaBarang);
add.setInt(3, q);
add.setInt(4, harga);
add.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
this.setVisible(false);
new HomePageFrame().setVisible(true);
}
}//GEN-LAST:event_btnCartMacaronActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FnbFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FnbFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FnbFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FnbFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FnbFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCartAlmond;
private javax.swing.JButton btnCartMacaron;
private javax.swing.JButton btnHome;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSpinner spinnerAlmond;
private javax.swing.JSpinner spinnerMacaron;
// End of variables declaration//GEN-END:variables
}
|
Java | UTF-8 | 1,205 | 4.03125 | 4 | [] | no_license | package chapterfive.classdesign.understandingpolymorphism;
public class CastingObjects {
// polymorphism: the property of an object to take on many different forms
// 1 - Casting an object from a subclass to a superclass doesn’t require an explicit cast.
// 2 - Casting an object from a superclass to a subclass requires an explicit cast.
// 3 - The compiler will not allow casts to unrelated types.
// 4 - Even when the code compiles without issue, an exception may be thrown at runtime if
//the object being cast is not actually an instance of that class.
}
class Primate {
public boolean hasHair() {
return true;
}
}
interface HasTail {
public boolean isTailStriped();
}
class Lemur extends Primate implements HasTail {
public boolean isTailStriped() {
return false;
}
public int age = 10;
public static void main(String[] args) {
Lemur lemur = new Lemur();
System.out.println(lemur.age);
HasTail hasTail = lemur;
System.out.println(hasTail.isTailStriped());
Primate primate = lemur;
System.out.println(primate.hasHair());
}
}
/*10
false
true*/ |
Java | UTF-8 | 276 | 2.140625 | 2 | [] | no_license | package io.github.eugenezakhno;
public class Main {
public static void main(String[]args){
MyObject myObject = new MyObject();
myObject.i = 1;
MyObject myObject1 = myObject;
myObject.i = 2;
}
}
class MyObject {
int i;
}
|
Python | UTF-8 | 1,262 | 3.84375 | 4 | [] | no_license | # [8.8] Permutation with Dups: Write a method to computer all
# permutations of a string whose characters are not necessarily
# unique. The list of permutations should not have duplicates.
import unittest
def perms_with_dups(s):
char_count = get_char_count(s)
result = []
perms_with_dups_helper('', char_count, len(s), result)
return result
def perms_with_dups_helper(s, char_count, n, result):
if len(s) == n:
result.append(s)
for char in char_count:
if char_count[char] == 1:
del char_count[char]
else:
char_count[char] -= 1
perms_with_dups_helper(s + char, char_count, n, result)
if not char in char_count:
char_count[char] = 1
else:
char_count[char] += 1
def get_char_count(s):
char_count = {}
for char in s:
if char not in char_count:
char_count[char] = 1
else:
char_count[char] += 1
return char_count
class Test(unittest.TestCase):
def setUp(self):
self.result = ['aaac', 'aaca', 'acaa', 'caaa']
def test_perms_with_dups(self):
self.assertEqual(set(perms_with_dups('aaac')), set(self.result))
if __name__ == '__main__':
unittest.main()
|
PHP | UTF-8 | 1,869 | 2.96875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Apaar
* Date: 2016-03-06
* Time: 1:24 AM
*/
namespace Apaar\Chat;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
/**
* Class Server
* @package Apaar\Chat
*/
class Server implements MessageComponentInterface
{
/**
* @var ConnectionInterface[]
*/
private $clients;
/**
* Server constructor.
*/
public function __construct()
{
$this->clients = new \SplObjectStorage();
}
/**
* @inheritDoc
*/
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
$this->printMessage('New connection!', $conn);
}
/**
* @inheritDoc
*/
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
$this->printMessage('Connection closed!', $conn);
}
/**
* @inheritDoc
*/
public function onError(ConnectionInterface $conn, \Exception $e)
{
$this->printMessage('Error occurred!' . $e->getMessage(), $conn);
$conn->close();
}
/**
* @inheritDoc
*/
public function onMessage(ConnectionInterface $from, $msg)
{
$this->printMessage("Message received: {$msg}", $from);
$this->sendMessage($msg);
}
/**
* Sends message to attached clients except the one sending
*
* @param $message
*/
private function sendMessage($message)
{
foreach ($this->clients as $client) {
$client->send($message);
}
}
/**
* Prints the given message
*
* @param $message
* @param ConnectionInterface $connection
*/
private function printMessage($message, ConnectionInterface $connection)
{
echo $message . ' ' . $connection->resourceId ?? '' . PHP_EOL;
}
}
|
C# | UTF-8 | 2,051 | 2.65625 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destroyable : MonoBehaviour, IDamagable
{
[SerializeField]
float health = 50;
AudioSource audioSource;
ParticleSystem ps;
[SerializeField]
bool dealtDamage = false;
[SerializeField]
bool exploding;
[SerializeField]
bool explode = false;
[SerializeField]
bool touchingPlayer = false;
private void Start()
{
audioSource = GetComponent<AudioSource>();
ps = GetComponentInChildren<ParticleSystem>();
if(ps != null)
{
ps.Stop();
}
}
private void Update()
{
if (health < 25)
{
Spark();
}
if (health <= 0)
{
if (dealtDamage == false)
{
exploding = true;
}
StartCoroutine(Waiting());
if (explode)
{
Destroy(this.gameObject);
}
}
}
public void TakeDamage(float damage)
{
health -= damage;
}
void Spark()
{
if(ps == null)
{
Debug.Log("Ignore");
}
else
{
Debug.Log("Sparking");
ps.Play();
if(ps.isPlaying)
{
Debug.Log("Should Be Working");
}
}
}
private void OnCollisionStay(Collision collision)
{
touchingPlayer = true;
if (exploding)
{
if(collision.gameObject.GetComponent<IDamagable>() != null)
{
collision.gameObject.GetComponent<IDamagable>().TakeDamage(8);
dealtDamage = true;
exploding = false;
}
}
}
IEnumerator Waiting()
{
yield return new WaitForSeconds(1);
explode = true;
audioSource.Play();
yield return new WaitForSeconds(.5f);
}
}
|
JavaScript | UTF-8 | 357 | 3.171875 | 3 | [] | no_license | function getRandomIndex(array) {
const size = array?.length;
if (Array.isArray(array) && size > 0) {
const random = Math.floor(Math.random() * size);
if (random < 0) {
return 0;
} else if (random >= size) {
return size - 1;
} else {
return random;
}
} else {
return -1;
}
}
export default getRandomIndex;
|
Java | UTF-8 | 289 | 2.453125 | 2 | [] | no_license | package com.sofkau.exercises;
import Exercise17.Electrodomestico;
public class Controller_ex_17 {
public void excersice17_methods(){
Electrodomestico electro = new Electrodomestico();
double price = electro.final_price();
System.out.println(price);
}
}
|
C | UTF-8 | 1,854 | 3.125 | 3 | [] | no_license | /*
* Cliente con Transmission Control Protocol (TCP).
* Fecha 28/09/2014
* Lizandro Jose Ramirez Difo
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/types.h>
#define SERVER_PORT 9999
#define BUFFER_LEN 1024
#define IP_SERVER "138.100.154.59" /*"138.100.154.34"8*/
/*138.100.154.59:9999*/
int main(int argc, char *argv[])
{
int sockfd; /* descriptor a usar con el socket */
struct sockaddr_in their_addr; /* almacenara la direccion IP y numero de puerto del servidor */
struct hostent *he; /* para obtener nombre del host */
int numbytes; /* conteo de bytes a escribir */
char buf[BUFFER_LEN]; /* Buffer de recepción */
int addr_len;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
/*htons me blinda la direccion para que no importe el tipo de maquina que use, agrega formato canonico*/
their_addr.sin_family = AF_INET; /* usa host byte order */
their_addr.sin_port = htons(SERVER_PORT); /* usa network byte order */
their_addr.sin_addr.s_addr= inet_addr(IP_SERVER);/**((struct in_addr *)he->h_addr);*/
/*bzero(&(their_addr.sin_zero), 8); /* pone en cero el resto */
connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr));
/*connect devuelve -1 si no se ha conectado a nadad*/
write (sockfd,argv[1],strlen(argv[1]));
/*write me envia todo junto por una coneccion, osea si hago dos write con dos mensajes,
a quien lo envio lo vera como un solo mensaje, tengo que programar las barreras*/
int tot=strlen(argv[1]);
int n=0;
int rec;
/*una solucion para recibir y buscar sin saber el tamano, es leer de uno en uno*/
while(n<tot)
{
printf("Esperando respuesta del servidor... \n");
rec=read(sockfd,buf+n,tot-n);
n+=rec;
}
buf[rec]='\0';
printf("recibido: %s\n",buf);
close(sockfd);
}
|
Java | UTF-8 | 1,665 | 3.328125 | 3 | [] | no_license | package com.neuedu.GouZao;
public class hone1 {
//1 有五个学生,每个学生有3门课的成绩,从键盘输入以上数据(包括学生号,姓名,三门课成绩),计算出平均成绩
// public class Student {
// private String sname;
// private int sno;
// private int student1;
// private int student2;
// private int student3;
//
// public String getSname() {
// return sname;
// }
//
// public void setSname(String sname) {
// this.sname = sname;
// }
//
// public int getSno() {
// return sno;
// }
//
// public void setSno(int sno) {
// this.sno = sno;
// }
//
// public int getStudent1() {
// return student1;
// }
//
// public void setStudent1(int sachievement1) {
// this.student1 = sachievement1;
// }
//
// public int getStudent2() {
// return student2;
// }
//
// public void setStudent2(int sachievement2) {
// this.student2 = student2;
// }
//
// public int getStudent3() {
// return student3;
// }
//
// public void setStudent3(int sachievement3) {
// this.student3 = sachievement3;
// }
//
// @Override
// public String toString() {
// return "姓名为:"+getSname()+"学号为"+getSno()+"成绩1为"+getStudent1()+
// "成绩2为"+getStudent2()+"成绩3为"+getStudent3()+
// "平均成绩为:"+(getStudent1()+getStudent2()+getStudent3()/3);
// }
// }
}
|
Java | UTF-8 | 405 | 2.640625 | 3 | [] | no_license | package pl.sda.zadania_05_25.builder;
public class BuilderMain {
public static void main(String[] args) {
ChartDataBuilder builder = new ChartDataBuilder();
ChartData data = builder.build();
System.out.println(data);
builder.setMaxValue(30);
builder.setLineColour(12345);
ChartData data1 = builder.build();
System.out.println(data1);
}
}
|
Java | UTF-8 | 47,340 | 1.703125 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dataproc.v1;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.httpjson.longrunning.OperationsClient;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.paging.AbstractFixedSizeCollection;
import com.google.api.gax.paging.AbstractPage;
import com.google.api.gax.paging.AbstractPagedListResponse;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.dataproc.v1.stub.BatchControllerStub;
import com.google.cloud.dataproc.v1.stub.BatchControllerStubSettings;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Service Description: The BatchController provides methods to manage batch workloads.
*
* <p>This class provides the ability to make remote calls to the backing service through method
* calls that map to API methods. Sample code to get started:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* BatchName name = BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]");
* Batch response = batchControllerClient.getBatch(name);
* }
* }</pre>
*
* <p>Note: close() needs to be called on the BatchControllerClient object to clean up resources
* such as threads. In the example above, try-with-resources is used, which automatically calls
* close().
*
* <p>The surface of this class includes several types of Java methods for each of the API's
* methods:
*
* <ol>
* <li>A "flattened" method. With this type of method, the fields of the request type have been
* converted into function parameters. It may be the case that not all fields are available as
* parameters, and not every API method will have a flattened method entry point.
* <li>A "request object" method. This type of method only takes one parameter, a request object,
* which must be constructed before the call. Not every API method will have a request object
* method.
* <li>A "callable" method. This type of method takes no parameters and returns an immutable API
* callable object, which can be used to initiate calls to the service.
* </ol>
*
* <p>See the individual methods for example code.
*
* <p>Many parameters require resource names to be formatted in a particular way. To assist with
* these names, this class includes a format method for each type of name, and additionally a parse
* method to extract the individual identifiers contained within names that are returned.
*
* <p>This class can be customized by passing in a custom instance of BatchControllerSettings to
* create(). For example:
*
* <p>To customize credentials:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* BatchControllerSettings batchControllerSettings =
* BatchControllerSettings.newBuilder()
* .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
* .build();
* BatchControllerClient batchControllerClient =
* BatchControllerClient.create(batchControllerSettings);
* }</pre>
*
* <p>To customize the endpoint:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* BatchControllerSettings batchControllerSettings =
* BatchControllerSettings.newBuilder().setEndpoint(myEndpoint).build();
* BatchControllerClient batchControllerClient =
* BatchControllerClient.create(batchControllerSettings);
* }</pre>
*
* <p>To use REST (HTTP1.1/JSON) transport (instead of gRPC) for sending and receiving requests over
* the wire:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* BatchControllerSettings batchControllerSettings =
* BatchControllerSettings.newHttpJsonBuilder().build();
* BatchControllerClient batchControllerClient =
* BatchControllerClient.create(batchControllerSettings);
* }</pre>
*
* <p>Please refer to the GitHub repository's samples for more quickstart code snippets.
*/
@Generated("by gapic-generator-java")
public class BatchControllerClient implements BackgroundResource {
private final BatchControllerSettings settings;
private final BatchControllerStub stub;
private final OperationsClient httpJsonOperationsClient;
private final com.google.longrunning.OperationsClient operationsClient;
/** Constructs an instance of BatchControllerClient with default settings. */
public static final BatchControllerClient create() throws IOException {
return create(BatchControllerSettings.newBuilder().build());
}
/**
* Constructs an instance of BatchControllerClient, using the given settings. The channels are
* created based on the settings passed in, or defaults for any settings that are not set.
*/
public static final BatchControllerClient create(BatchControllerSettings settings)
throws IOException {
return new BatchControllerClient(settings);
}
/**
* Constructs an instance of BatchControllerClient, using the given stub for making calls. This is
* for advanced usage - prefer using create(BatchControllerSettings).
*/
public static final BatchControllerClient create(BatchControllerStub stub) {
return new BatchControllerClient(stub);
}
/**
* Constructs an instance of BatchControllerClient, using the given settings. This is protected so
* that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected BatchControllerClient(BatchControllerSettings settings) throws IOException {
this.settings = settings;
this.stub = ((BatchControllerStubSettings) settings.getStubSettings()).createStub();
this.operationsClient =
com.google.longrunning.OperationsClient.create(this.stub.getOperationsStub());
this.httpJsonOperationsClient = OperationsClient.create(this.stub.getHttpJsonOperationsStub());
}
protected BatchControllerClient(BatchControllerStub stub) {
this.settings = null;
this.stub = stub;
this.operationsClient =
com.google.longrunning.OperationsClient.create(this.stub.getOperationsStub());
this.httpJsonOperationsClient = OperationsClient.create(this.stub.getHttpJsonOperationsStub());
}
public final BatchControllerSettings getSettings() {
return settings;
}
public BatchControllerStub getStub() {
return stub;
}
/**
* Returns the OperationsClient that can be used to query the status of a long-running operation
* returned by another API method call.
*/
public final com.google.longrunning.OperationsClient getOperationsClient() {
return operationsClient;
}
/**
* Returns the OperationsClient that can be used to query the status of a long-running operation
* returned by another API method call.
*/
@BetaApi
public final OperationsClient getHttpJsonOperationsClient() {
return httpJsonOperationsClient;
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a batch workload that executes asynchronously.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
* Batch batch = Batch.newBuilder().build();
* String batchId = "batchId-331744779";
* Batch response = batchControllerClient.createBatchAsync(parent, batch, batchId).get();
* }
* }</pre>
*
* @param parent Required. The parent resource where this batch will be created.
* @param batch Required. The batch to create.
* @param batchId Optional. The ID to use for the batch, which will become the final component of
* the batch's resource name.
* <p>This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Batch, BatchOperationMetadata> createBatchAsync(
LocationName parent, Batch batch, String batchId) {
CreateBatchRequest request =
CreateBatchRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setBatch(batch)
.setBatchId(batchId)
.build();
return createBatchAsync(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a batch workload that executes asynchronously.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* String parent = LocationName.of("[PROJECT]", "[LOCATION]").toString();
* Batch batch = Batch.newBuilder().build();
* String batchId = "batchId-331744779";
* Batch response = batchControllerClient.createBatchAsync(parent, batch, batchId).get();
* }
* }</pre>
*
* @param parent Required. The parent resource where this batch will be created.
* @param batch Required. The batch to create.
* @param batchId Optional. The ID to use for the batch, which will become the final component of
* the batch's resource name.
* <p>This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Batch, BatchOperationMetadata> createBatchAsync(
String parent, Batch batch, String batchId) {
CreateBatchRequest request =
CreateBatchRequest.newBuilder()
.setParent(parent)
.setBatch(batch)
.setBatchId(batchId)
.build();
return createBatchAsync(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a batch workload that executes asynchronously.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* CreateBatchRequest request =
* CreateBatchRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setBatch(Batch.newBuilder().build())
* .setBatchId("batchId-331744779")
* .setRequestId("requestId693933066")
* .build();
* Batch response = batchControllerClient.createBatchAsync(request).get();
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Batch, BatchOperationMetadata> createBatchAsync(
CreateBatchRequest request) {
return createBatchOperationCallable().futureCall(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a batch workload that executes asynchronously.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* CreateBatchRequest request =
* CreateBatchRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setBatch(Batch.newBuilder().build())
* .setBatchId("batchId-331744779")
* .setRequestId("requestId693933066")
* .build();
* OperationFuture<Batch, BatchOperationMetadata> future =
* batchControllerClient.createBatchOperationCallable().futureCall(request);
* // Do something.
* Batch response = future.get();
* }
* }</pre>
*/
public final OperationCallable<CreateBatchRequest, Batch, BatchOperationMetadata>
createBatchOperationCallable() {
return stub.createBatchOperationCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a batch workload that executes asynchronously.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* CreateBatchRequest request =
* CreateBatchRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setBatch(Batch.newBuilder().build())
* .setBatchId("batchId-331744779")
* .setRequestId("requestId693933066")
* .build();
* ApiFuture<Operation> future = batchControllerClient.createBatchCallable().futureCall(request);
* // Do something.
* Operation response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<CreateBatchRequest, Operation> createBatchCallable() {
return stub.createBatchCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets the batch workload resource representation.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* BatchName name = BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]");
* Batch response = batchControllerClient.getBatch(name);
* }
* }</pre>
*
* @param name Required. The fully qualified name of the batch to retrieve in the format
* "projects/PROJECT_ID/locations/DATAPROC_REGION/batches/BATCH_ID"
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final Batch getBatch(BatchName name) {
GetBatchRequest request =
GetBatchRequest.newBuilder().setName(name == null ? null : name.toString()).build();
return getBatch(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets the batch workload resource representation.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* String name = BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]").toString();
* Batch response = batchControllerClient.getBatch(name);
* }
* }</pre>
*
* @param name Required. The fully qualified name of the batch to retrieve in the format
* "projects/PROJECT_ID/locations/DATAPROC_REGION/batches/BATCH_ID"
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final Batch getBatch(String name) {
GetBatchRequest request = GetBatchRequest.newBuilder().setName(name).build();
return getBatch(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets the batch workload resource representation.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* GetBatchRequest request =
* GetBatchRequest.newBuilder()
* .setName(BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]").toString())
* .build();
* Batch response = batchControllerClient.getBatch(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final Batch getBatch(GetBatchRequest request) {
return getBatchCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets the batch workload resource representation.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* GetBatchRequest request =
* GetBatchRequest.newBuilder()
* .setName(BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]").toString())
* .build();
* ApiFuture<Batch> future = batchControllerClient.getBatchCallable().futureCall(request);
* // Do something.
* Batch response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<GetBatchRequest, Batch> getBatchCallable() {
return stub.getBatchCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists batch workloads.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
* for (Batch element : batchControllerClient.listBatches(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The parent, which owns this collection of batches.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListBatchesPagedResponse listBatches(LocationName parent) {
ListBatchesRequest request =
ListBatchesRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.build();
return listBatches(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists batch workloads.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* String parent = LocationName.of("[PROJECT]", "[LOCATION]").toString();
* for (Batch element : batchControllerClient.listBatches(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The parent, which owns this collection of batches.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListBatchesPagedResponse listBatches(String parent) {
ListBatchesRequest request = ListBatchesRequest.newBuilder().setParent(parent).build();
return listBatches(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists batch workloads.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* ListBatchesRequest request =
* ListBatchesRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setFilter("filter-1274492040")
* .setOrderBy("orderBy-1207110587")
* .build();
* for (Batch element : batchControllerClient.listBatches(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListBatchesPagedResponse listBatches(ListBatchesRequest request) {
return listBatchesPagedCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists batch workloads.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* ListBatchesRequest request =
* ListBatchesRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setFilter("filter-1274492040")
* .setOrderBy("orderBy-1207110587")
* .build();
* ApiFuture<Batch> future =
* batchControllerClient.listBatchesPagedCallable().futureCall(request);
* // Do something.
* for (Batch element : future.get().iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*/
public final UnaryCallable<ListBatchesRequest, ListBatchesPagedResponse>
listBatchesPagedCallable() {
return stub.listBatchesPagedCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists batch workloads.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* ListBatchesRequest request =
* ListBatchesRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setFilter("filter-1274492040")
* .setOrderBy("orderBy-1207110587")
* .build();
* while (true) {
* ListBatchesResponse response = batchControllerClient.listBatchesCallable().call(request);
* for (Batch element : response.getBatchesList()) {
* // doThingsWith(element);
* }
* String nextPageToken = response.getNextPageToken();
* if (!Strings.isNullOrEmpty(nextPageToken)) {
* request = request.toBuilder().setPageToken(nextPageToken).build();
* } else {
* break;
* }
* }
* }
* }</pre>
*/
public final UnaryCallable<ListBatchesRequest, ListBatchesResponse> listBatchesCallable() {
return stub.listBatchesCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes the batch workload resource. If the batch is not in terminal state, the delete fails
* and the response returns `FAILED_PRECONDITION`.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* BatchName name = BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]");
* batchControllerClient.deleteBatch(name);
* }
* }</pre>
*
* @param name Required. The fully qualified name of the batch to retrieve in the format
* "projects/PROJECT_ID/locations/DATAPROC_REGION/batches/BATCH_ID"
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final void deleteBatch(BatchName name) {
DeleteBatchRequest request =
DeleteBatchRequest.newBuilder().setName(name == null ? null : name.toString()).build();
deleteBatch(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes the batch workload resource. If the batch is not in terminal state, the delete fails
* and the response returns `FAILED_PRECONDITION`.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* String name = BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]").toString();
* batchControllerClient.deleteBatch(name);
* }
* }</pre>
*
* @param name Required. The fully qualified name of the batch to retrieve in the format
* "projects/PROJECT_ID/locations/DATAPROC_REGION/batches/BATCH_ID"
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final void deleteBatch(String name) {
DeleteBatchRequest request = DeleteBatchRequest.newBuilder().setName(name).build();
deleteBatch(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes the batch workload resource. If the batch is not in terminal state, the delete fails
* and the response returns `FAILED_PRECONDITION`.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* DeleteBatchRequest request =
* DeleteBatchRequest.newBuilder()
* .setName(BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]").toString())
* .build();
* batchControllerClient.deleteBatch(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final void deleteBatch(DeleteBatchRequest request) {
deleteBatchCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes the batch workload resource. If the batch is not in terminal state, the delete fails
* and the response returns `FAILED_PRECONDITION`.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* DeleteBatchRequest request =
* DeleteBatchRequest.newBuilder()
* .setName(BatchName.of("[PROJECT]", "[LOCATION]", "[BATCH]").toString())
* .build();
* ApiFuture<Empty> future = batchControllerClient.deleteBatchCallable().futureCall(request);
* // Do something.
* future.get();
* }
* }</pre>
*/
public final UnaryCallable<DeleteBatchRequest, Empty> deleteBatchCallable() {
return stub.deleteBatchCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sets the access control policy on the specified resource. Replacesany existing policy.
*
* <p>Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* SetIamPolicyRequest request =
* SetIamPolicyRequest.newBuilder()
* .setResource(
* AutoscalingPolicyName.ofProjectRegionAutoscalingPolicyName(
* "[PROJECT]", "[REGION]", "[AUTOSCALING_POLICY]")
* .toString())
* .setPolicy(Policy.newBuilder().build())
* .setUpdateMask(FieldMask.newBuilder().build())
* .build();
* Policy response = batchControllerClient.setIamPolicy(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final Policy setIamPolicy(SetIamPolicyRequest request) {
return setIamPolicyCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Sets the access control policy on the specified resource. Replacesany existing policy.
*
* <p>Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* SetIamPolicyRequest request =
* SetIamPolicyRequest.newBuilder()
* .setResource(
* AutoscalingPolicyName.ofProjectRegionAutoscalingPolicyName(
* "[PROJECT]", "[REGION]", "[AUTOSCALING_POLICY]")
* .toString())
* .setPolicy(Policy.newBuilder().build())
* .setUpdateMask(FieldMask.newBuilder().build())
* .build();
* ApiFuture<Policy> future = batchControllerClient.setIamPolicyCallable().futureCall(request);
* // Do something.
* Policy response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() {
return stub.setIamPolicyCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets the access control policy for a resource. Returns an empty policyif the resource exists
* and does not have a policy set.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* GetIamPolicyRequest request =
* GetIamPolicyRequest.newBuilder()
* .setResource(
* AutoscalingPolicyName.ofProjectRegionAutoscalingPolicyName(
* "[PROJECT]", "[REGION]", "[AUTOSCALING_POLICY]")
* .toString())
* .setOptions(GetPolicyOptions.newBuilder().build())
* .build();
* Policy response = batchControllerClient.getIamPolicy(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final Policy getIamPolicy(GetIamPolicyRequest request) {
return getIamPolicyCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets the access control policy for a resource. Returns an empty policyif the resource exists
* and does not have a policy set.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* GetIamPolicyRequest request =
* GetIamPolicyRequest.newBuilder()
* .setResource(
* AutoscalingPolicyName.ofProjectRegionAutoscalingPolicyName(
* "[PROJECT]", "[REGION]", "[AUTOSCALING_POLICY]")
* .toString())
* .setOptions(GetPolicyOptions.newBuilder().build())
* .build();
* ApiFuture<Policy> future = batchControllerClient.getIamPolicyCallable().futureCall(request);
* // Do something.
* Policy response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() {
return stub.getIamPolicyCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Returns permissions that a caller has on the specified resource. If theresource does not exist,
* this will return an empty set ofpermissions, not a `NOT_FOUND` error.
*
* <p>Note: This operation is designed to be used for buildingpermission-aware UIs and
* command-line tools, not for authorizationchecking. This operation may "fail open" without
* warning.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* TestIamPermissionsRequest request =
* TestIamPermissionsRequest.newBuilder()
* .setResource(
* AutoscalingPolicyName.ofProjectRegionAutoscalingPolicyName(
* "[PROJECT]", "[REGION]", "[AUTOSCALING_POLICY]")
* .toString())
* .addAllPermissions(new ArrayList<String>())
* .build();
* TestIamPermissionsResponse response = batchControllerClient.testIamPermissions(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final TestIamPermissionsResponse testIamPermissions(TestIamPermissionsRequest request) {
return testIamPermissionsCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Returns permissions that a caller has on the specified resource. If theresource does not exist,
* this will return an empty set ofpermissions, not a `NOT_FOUND` error.
*
* <p>Note: This operation is designed to be used for buildingpermission-aware UIs and
* command-line tools, not for authorizationchecking. This operation may "fail open" without
* warning.
*
* <p>Sample code:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* try (BatchControllerClient batchControllerClient = BatchControllerClient.create()) {
* TestIamPermissionsRequest request =
* TestIamPermissionsRequest.newBuilder()
* .setResource(
* AutoscalingPolicyName.ofProjectRegionAutoscalingPolicyName(
* "[PROJECT]", "[REGION]", "[AUTOSCALING_POLICY]")
* .toString())
* .addAllPermissions(new ArrayList<String>())
* .build();
* ApiFuture<TestIamPermissionsResponse> future =
* batchControllerClient.testIamPermissionsCallable().futureCall(request);
* // Do something.
* TestIamPermissionsResponse response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsCallable() {
return stub.testIamPermissionsCallable();
}
@Override
public final void close() {
stub.close();
}
@Override
public void shutdown() {
stub.shutdown();
}
@Override
public boolean isShutdown() {
return stub.isShutdown();
}
@Override
public boolean isTerminated() {
return stub.isTerminated();
}
@Override
public void shutdownNow() {
stub.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return stub.awaitTermination(duration, unit);
}
public static class ListBatchesPagedResponse
extends AbstractPagedListResponse<
ListBatchesRequest,
ListBatchesResponse,
Batch,
ListBatchesPage,
ListBatchesFixedSizeCollection> {
public static ApiFuture<ListBatchesPagedResponse> createAsync(
PageContext<ListBatchesRequest, ListBatchesResponse, Batch> context,
ApiFuture<ListBatchesResponse> futureResponse) {
ApiFuture<ListBatchesPage> futurePage =
ListBatchesPage.createEmptyPage().createPageAsync(context, futureResponse);
return ApiFutures.transform(
futurePage, input -> new ListBatchesPagedResponse(input), MoreExecutors.directExecutor());
}
private ListBatchesPagedResponse(ListBatchesPage page) {
super(page, ListBatchesFixedSizeCollection.createEmptyCollection());
}
}
public static class ListBatchesPage
extends AbstractPage<ListBatchesRequest, ListBatchesResponse, Batch, ListBatchesPage> {
private ListBatchesPage(
PageContext<ListBatchesRequest, ListBatchesResponse, Batch> context,
ListBatchesResponse response) {
super(context, response);
}
private static ListBatchesPage createEmptyPage() {
return new ListBatchesPage(null, null);
}
@Override
protected ListBatchesPage createPage(
PageContext<ListBatchesRequest, ListBatchesResponse, Batch> context,
ListBatchesResponse response) {
return new ListBatchesPage(context, response);
}
@Override
public ApiFuture<ListBatchesPage> createPageAsync(
PageContext<ListBatchesRequest, ListBatchesResponse, Batch> context,
ApiFuture<ListBatchesResponse> futureResponse) {
return super.createPageAsync(context, futureResponse);
}
}
public static class ListBatchesFixedSizeCollection
extends AbstractFixedSizeCollection<
ListBatchesRequest,
ListBatchesResponse,
Batch,
ListBatchesPage,
ListBatchesFixedSizeCollection> {
private ListBatchesFixedSizeCollection(List<ListBatchesPage> pages, int collectionSize) {
super(pages, collectionSize);
}
private static ListBatchesFixedSizeCollection createEmptyCollection() {
return new ListBatchesFixedSizeCollection(null, 0);
}
@Override
protected ListBatchesFixedSizeCollection createCollection(
List<ListBatchesPage> pages, int collectionSize) {
return new ListBatchesFixedSizeCollection(pages, collectionSize);
}
}
}
|
Java | UTF-8 | 807 | 3.40625 | 3 | [] | no_license | package StringEquality;
public class StringEquality{
private String wordOne , wordTwo;
public StringEquality(){
wordOne = wordTwo = null;
}
public StringEquality(String tempOne , String tempTwo){
wordOne = tempOne;
wordTwo = tempTwo;
}
public void setWords(String tempOne , String tempTwo){
wordOne = tempOne;
wordTwo = tempTwo;
}
@Override
public String toString(){
if(wordOne.equals(wordTwo))
return wordOne + " does have the same letters as " + wordTwo + "\n";
return wordOne + " does not have the same letters as " + wordTwo + "\n";
}
}
|
C | UTF-8 | 128 | 2.71875 | 3 | [] | no_license | #include <errno.h>
void errore(char*str,int n)
{
printf(str);
printf("%s(%d)\n",strerror(errno),errno);
exit(n);
}
|
TypeScript | UTF-8 | 973 | 3.03125 | 3 | [] | no_license | export class Renter {
constructor(
public $key: string,
public title: string,
public type: string,
public name: string,
public phoneCell: string,
public phoneOffice: string,
public email: string,
public website: string,
public image: string,
public isActive: boolean,
public activeRent: number,
public totalDeptAmount: number) {
}
static fromJson({$key,
title,
type,
name,
phoneCell, phoneOffice, email, activeRent, isActive, website, image, totalDeptAmount}) {
return new Renter($key,
title,
type,
name,
phoneCell, phoneOffice, email, activeRent, isActive, website, image, totalDeptAmount);
}
static fromJsonArray(json: any[]): Renter[] {
return json.map(Renter.fromJson);
}
calcDeptAmount(rentAmount: number) {
this.totalDeptAmount += rentAmount;
}
} |
Markdown | UTF-8 | 1,470 | 2.78125 | 3 | [
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ---
---
---
title: 诚和气节 陶冶暴恶
---
遇欺诈之人,以诚心感动之;遇暴戾之人,以和气薰蒸之;遇倾邪私曲之人,以名义气节激励之。天下无不入我陶冶中矣。
释义
遇到狡猾欺诈的人,要用赤诚之心来感动他;遇到性情狂暴乖戾的人,要用温和态度来感化他;遇到行为不正自私自利的人,要用大义气节来激励他。假如能做到这几点,那天下的人都会受到我的美德感化了。
新解
以德化之,如春风潜入,徐徐铺展,则坚冰必摧,枯木吐新。在圣贤之人,此等胸怀自可备之,而在一般人,可不懈努力,尽心去做。清末,在捻军围攻河南固始时,蒯知县出布告招募死士守城,以他的闺女为赏格。有一人叫张曜,应募破敌,就娶蒯知县之女为妻,并且做了官。张曜不识字,公事都是他妻子看。后来张曜当河南藩司、御使,有个叫刘毓楠的,上奏参他“目不识丁”。张曜没办法,只好改武职,调补总兵,驻守南阳。那时,“文改武”是很丢面子的事,因此,张曜发愤向妻子学习,后来也能识字写信,重新为朝廷重用。刘毓楠告老归乡后,张曜送他一块匾,上刻“目不识丁”。张曜还按月敬奉他,以谢鞭策之恩,后来二人竟成终生至好。
注释
暴戾:残酷。薰蒸:薰是香草,此作沐化、感化的意思。 |
Java | UTF-8 | 295 | 1.945313 | 2 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | package org.immutizer4j.test.sample;
import lombok.Data;
/**
* A POJO that will be used as an ancestor for other POJOs
* Contains a mix of mutable and non-mutable fields
*/
@Data
public class ParentPojo {
private final int parentImmutableInt = 0;
private int paretMutableInt = 0;
}
|
C++ | UTF-8 | 1,765 | 2.5625 | 3 | [] | no_license | #include <larc.hh>
#include <organize.h>
#include <matrix_store.h>
#include "support.hh"
void initialize ( )
{
// Default hash exponent size
size_t hash_exponent_matrix = DEFAULT_MATRIX_STORE_EXPONENT;
size_t hash_exponent_op = DEFAULT_OP_STORE_EXPONENT;
int zerobitthresh = ZEROBITTHRESH_DEFAULT;
int sighash = SIGHASH_DEFAULT;
mat_level_t max_level = DEFAULT_MAX_LEVEL;
int verbose = 1;
initialize_larc ( hash_exponent_matrix ,
hash_exponent_op ,
max_level ,
sighash ,
zerobitthresh ,
verbose );
}
int main ( int argc , char *argv[] )
{
initialize();
uint64_t start_count = num_matrices_in_store ( );
for ( mat_level_t level = 0 ; level < 5 ; level++ ) {
LARC_t A ( level , level );
LARC_t B ( level , level );
LARC_t C ( level , level );
for ( mat_level_t r = 0 ; r < 1 << level ; r++ )
for ( mat_level_t c = 0 ; c < 1 << level ; c++ ) {
A[r][c] = r * 1001 + c + 1;
B[r][c] = c * 937 + r + 1;
}
C = (A - 2*B)*(B - A*2);
// Ensure that LARC_t sets holds on matrices
clean_matrix_storage ( );
for ( mat_level_t r = 0 ; r < 1 << level ; r++ )
for ( mat_level_t c = 0 ; c < 1 << level ; c++ ) {
ScalarType sum = 0;
for ( mat_level_t k = 0 ; k < 1 << level ; k++ ) {
ScalarType two = 2;
sum = sum + (A[r][k] - two*B[r][k]) * (B[k][c] - two*A[k][c]);
}
assert_equal ( sum , C[r][c] , "matrix algebra" );
}
}
// Ensure that LARC_t releases holds on matrices
clean_matrix_storage ( );
uint64_t end_count = num_matrices_in_store ( );
assert_equal ( end_count , start_count , "matrix store clean up" );
}
|
Java | UTF-8 | 688 | 1.90625 | 2 | [] | no_license | package com.speedata.webplus.system.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.speedata.webplus.common.persistence.BaseDaoImpl;
import com.speedata.webplus.common.service.BaseService;
import com.speedata.webplus.system.dao.DictDao;
import com.speedata.webplus.system.entity.Dict;
/**
* 字典service
*/
@Service
@Transactional(readOnly=true)
public class DictService extends BaseService<Dict, Integer> {
@Autowired
private DictDao dictDao;
@Override
public BaseDaoImpl<Dict, Integer> getEntityDao() {
return dictDao;
}
}
|
C# | UTF-8 | 2,605 | 3.09375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using HaminChecker.Declares;
namespace HaminChecker.Utils {
/// <summary>
/// DB検索
/// </summary>
public class DbSearch : IDisposable {
SQLiteConnection conn;
DateTime StandardTime;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="path">DBパス</param>
/// <param name="standard">無線局情報を再取得する基準時間</param>
public DbSearch(string path, DateTime standard) {
try {
conn = new SQLiteConnection("Data Source=" + path);
} catch (Exception e) {
throw e;
}
conn.Open();
StandardTime = standard;
}
public void Dispose() {
try {
conn?.Close();
conn?.Dispose();
} catch {
;
}
}
/// <summary>
/// DBから無線局情報を検索します。
/// </summary>
/// <param name="callsign">検索コールサイン</param>
/// <param name="isTimeCheck">基準時間確認するか</param>
public StationInfo Execute(string callsign, bool isTimeCheck) {
using (SQLiteCommand cmd = conn.CreateCommand()) {
cmd.CommandText = "select * from Station where Callsign = '" + callsign + "';";
using (var reader = cmd.ExecuteReader()) {
if (reader.Read()) {
var updated = Date.FromString(reader["Updated"].ToString());
if (!isTimeCheck || (isTimeCheck && updated > StandardTime)) {
return new StationInfo() {
Callsign = reader["Callsign"].ToString(),
Address = reader["Addresses"].ToString().Split(',').ToList()
};
} else {
return null;
}
}
}
}
return null;
}
/// <summary>
/// DBに無線局情報を登録します。
/// </summary>
/// <param name="station">登録する無線局情報</param>
public void Update(StationInfo station) {
bool hasRows;
using (SQLiteCommand cmd = conn.CreateCommand()) {
cmd.CommandText = "select * from Station where Callsign = '" + station.Callsign + "';";
using (var reader = cmd.ExecuteReader()) {
hasRows = reader.HasRows;
}
if (hasRows) {
cmd.CommandText = "update Station set Addresses = '" + string.Join(",", station.Address.ToArray()) + "', Updated = '" + Date.NowToString() + "' where Callsign = '" + station.Callsign + "';";
cmd.ExecuteNonQuery();
} else {
cmd.CommandText = "insert into Station(Callsign, Addresses, Updated) values('" + station.Callsign + "', '" + string.Join(",", station.Address.ToArray()) + "', '" + Date.NowToString() + "');";
cmd.ExecuteNonQuery();
}
}
}
}
}
|
Markdown | UTF-8 | 4,787 | 2.90625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Butler Configuration for supporting S3
## Overview
The butler configuration file is similar to that explained in the README.md file. But there are a few changes that need to made for it to fetch config files from AWS S3.
Only the Butler configuration fields that will be different for S3 are explained here. Everything else remains the same.
## AWS Credentials
### From IAM Roles
If you are running Butler on Amazon EC2, you can leverage EC2's IAM roles functionality in order to have credentials automatically provided to the instance.
If you have configured your instance to use IAM roles, Butler will automatically select these credentials for use in your application, and you do not need to manually provide credentials in any other format.
### From Environment Variables
By default, Butler will automatically detect AWS credentials set in your environment and use them for requests.
The keys that the SDK looks for are as follows:
```AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN```
## Managers / Manager Globals
### repos
The `repos` configuration option defines an array of repositories where butler is going to attempt to gather configuration files. The repositories will be folder names within the same S3 bucket where the config files may be stored.
#### Default Value
Empty Array
#### Example
`repos = ["Folder1", "Folder2"]`
## Repository Handler
Each Repository Handler configuration must be under the config Manager section, and must be one of the options which are defined under the `repos` option within the Manager definition.
For example, look at the following (incomplete) definition:
```
[globals]
config-managers = ["a", "b"]
...
[a]
^^^ Manager
repos = ["Folder1", "Folder2"]
...
[a.Folder1]
^^^^^^^^^^^^^^^^^^^^ This is where the Repository Handler configurationn option should reside.
```
There are 4 options that can be configured under the Repository Handler configuration section.
1. method
1. repo-path
1. primary-config
1. additional-config
### method
The `method` option defines what method to use for the retrieval of configuration files. Currently this option is only http/https and S3. In the future there will be added support for the following formats: file (local filesystem), blob (Azure Blob Storage)
#### Default Value
None
#### Example
1. `method = "S3"`
### repo-path
The `repo-path` option is the URI path to the configuration file on the local or remote filesystem. It should not be a relative path, and should not include any host information. In case of S3 this will be relative the folder names defined under `repos` and can be left blank.
#### Default Value
None
#### Example
`repo-path = "some/path"`
### primary-config
The `primary-config` option is an array of strings, that are configuration files which will get merged into the single configuration file referenced by `primary-config-name` under the Manager Globals section. You can include paths in the configuration file name, and the paths will be retrieved relative to the `repo` and `repo-path` that was defined previously. If the file is `additional/config2.yml`, then it will be retrieved from `Folder1/some/path/additional/config2.yml`
#### Default Value
[]
#### Example
`primary-config = ["config1.yml", "additional/config2.yml"]`
### additional-config
The `additional-config` option is an array strings, which are additional configuration files which will be put on the filesystem under `dest-path` as they are defined within the option. They will be retrieved relative to the `repo` and `repo-path`. If the file is called `additional/config2.yml`, then it will be retrieved from `Folder1/some/path/additional/config2.yml` and placed on the filesystem as `<dest-path>/additional/config2.yml`
#### Default Value
[]
#### Example
`additional-config = ["alerts/alerts1.yml", "extras/alertmanager.yml"]`
## Repository Handler Retrieval Options
The Repository Handler Retrieval Options must be defined under the Repository Handler using the name of the defined method.
For example, look at the following (incomplete) definition:
```
[globals]
config-managers = ["a", "b"]
...
[a]
repos = "Folder1", "Folder2"]
...
[a.Folder1]
method = "S3"
...
[a.Folder1.S3]
^^^^^^^^^^^^^^^^^^^^^^^^^ This is wehre the Repository Handler Retrieval Options should reside.
```
### bucket
The `bucket` is the AWS S3 bucket name where the files are hosted.
#### Example
`bucket = "bucket-name"`
### region
The 'region' is the AWS region of the bucket
#### Example
`region = "us-west-2"`
### access-key-id
The access-key-id for the s3 resource. If it is left blank, it will default to the environment.
### secret-access-key
The secret-access-key for s3 resource. If it is left blank, it will default to the environment.
|
Go | UTF-8 | 333 | 3.234375 | 3 | [] | no_license | package bubblesort
import "github.com/marksalpeter/algorithms/sortable"
// Sort implements the bubble sort algorithm
// O(n^2)
func Sort(s sortable.Sortable) {
swap := -1
for pass := 0; swap != 0; pass++ {
swap = 0
for i, l := 1, s.Len()-pass; i < l; i++ {
if !s.Less(i-1, i) {
s.Swap(i-1, i)
swap++
}
}
}
}
|
Markdown | UTF-8 | 2,304 | 2.75 | 3 | [] | no_license | # SYS: Income-Inequality & Personality Facets related to Agression (2019)
This dataset used included 1029 adolescents from the Saguenay Youth Study (SYS) who inhabit the Saguenay Lac Saint-Jean region in Quebec, Canada (data is proprietary so it cannot be released here). Information consisted of:
• Census Tract Area (for the Gini Index of Income-Inequality)
• Household Income/Income-to-needs ratio
• Personality (NEO PI-R)
The sample was filtered for participants who contained these features, which resulted in a total of n = 821 adolescents that were included in the analysis.
Cohort profile (SYS): https://www.ncbi.nlm.nih.gov/pubmed/27018016
This project examines differences in male-related characteristics among income and income-inequality groups, particularly in personality facets related to aggression.
Selection for certain personality facets was based off the results of a meta-analysis from Vize et al. (2018).
Participants below the median of the income-to-needs were split into the low-income group and those at the median and above were placed in the high-income group. Each income group was split again by income-inequality: those below the median of the Gini Index were placed in the low income-inequality group, and participants at the median and above were placed in the high income-inequality group. These 4 income income-inequality groups were analyzed by each sex (total 8 groups; LI-HII, HI-HII, LI-LII, HI-LII).
Initially, ANOVA was used to examine if there were any age differences within sexes by income income-inequality group.
Females showed no differences (F = 0.35, p = 0.79), however, males displayed age differences (F = 2.69, p = 0.046).
To account for the age difference among male groups, residual values were used in the linear mixed effects regression analysis for males.
The model examined the effects of age*group, and was adjusted for the randomized effect of Gini.CT to account for potential nesting of data within census tracts.
To adjust for multiple comparisons, false discovery rate (FDR) correction was evaluated using the ‘stats’ library in R.
Currently searching for the most suitable method of post hoc comparison to examine group differences among personality facets that survived FDR correction (for this particular model).
|
Python | UTF-8 | 1,171 | 3.84375 | 4 | [] | no_license |
num=100
for Number in range (1, num):
count = 0
for i in range(2, (Number//2 + 1)):
if Number % i == 0:
count = count + 1
break
if count == 0 and Number != 1:
print(Number, end = ' ')
'''
Test Cases:
1. Verify the program if number is 100 , all prime number should be displayed under 100
2. Verify the program if number is 99, all prime number should be displayed under 99
3. Verify the program if number is 101, all prime number should be displayed under 101
4. Verify the program if number is -100, Should not be displayed any thing
5. Verify the program if number is 100.0 , TypeError should shown and program finsished with error code 1
6. Verify the program if number is as string "100", TypeError should shown and program finsished with error code 1
7. Verify the program if number is as +100 , all prime number should be displayed under 100
8. Verify the program if number is as +-100 , Should not be displayed any thing
9. Verify the program if number is as 4e+30 , TypeError should shown and program finsished with error code 1
10. Verify the program if number is 0, Should not be displayed any thing
'''
|
TypeScript | UTF-8 | 2,892 | 3.25 | 3 | [] | no_license | /**
* board.js
*
* A JavaScript class to represent a board in our Agile Development Board.
*
* @author Ellery De Jesus
* @author Chris Wolf
* @version 2.0.0 (October 7, 2019)
*/
import { List } from '../lists/List';
import { ListFactory } from '../factories/ListFactory';
import { ListOptions } from '../enums/ListOptions';
export class Board {
private title: string;
private lists: List[];
private listFactory: ListFactory;
/**
* Generates the board object
*
* @param {string} title the title of the board
*/
constructor(title: string) {
this.title = title;
this.lists = [];
this.listFactory = new ListFactory();
} // end constructor
/**
* sets listFactory to something more specific
*
* @param {ListFactory} factory the new factory
*/
setListFactory(factory: ListFactory) {
this.listFactory = factory;
} // end setListFactory
/**
* adds a new list to our board
*
* @param {string} label the label for our new list
* @param {Colors} color the optional color value for our list
*/
addList(label: string) {
this.lists.push(new List(label));
} // end addList
/**
* Creates a task card within the specified list.
*
* @param {number} listID the list of we are trying to add a card to
* @param {string} label the label of the new task card
* @param {string} text the text in the new task card
*/
generateTaskCard(listID: number, label: string, text: string) {
this.lists[listID].addTask(label, text);
} // end generateTaskCard
/**
* Removes a task card from a specified list.
* @param {number} listID the ID we are removing a card from.
* @param {number} cardID the ID of the card we are removing.
*/
removeTaskCard(listID: number, cardID: number) {
this.lists[listID].removeTaskCard(cardID);
} // end removeTaskCard
/**
* Removes the specified list.
*
* @param {number} listID the ID of a list we are trying to remove
*/
removeList(listID: number) {
this.lists.splice(listID, 1);
} // end removeList
/**
* adds a new list using the ListFactory
*
* @param {ListOption} option the type of list we want to generate
*/
addListTemplate(option: ListOptions) {
this.lists.push(this.listFactory.generateList(option));
} // end addListTemplate
/**
* Loads in a list of lists into the 'lists' attribute in board.
* @param {lists[]} lists an array of lists to load into board.
*/
loadBoard(board: Board) {
let nlist: List;
this.lists = [];
this.title = board.title;
for (let list of board.lists) {
nlist = this.listFactory.generateList(null);
nlist.loadList(list);
this.lists.push(nlist);
} // end for
} // end loadLists
getTitle(): string {
return this.title;
} // end getTitle
getLists(): List[] {
return this.lists;
} // end getLists
} // end Board
|
Java | UTF-8 | 2,210 | 2.796875 | 3 | [] | no_license | package fr.gnokize.object;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class InventoryObject {
private String inventoryName;
private int inventorySize;
private Inventory inv;
private List<Items> items;
private Material mat;
private int slot;
public InventoryObject(String inventoryName, int inventorySize, List<Items> items, Material mat, int slot) {
this.inventoryName = inventoryName;
this.inventorySize = inventorySize;
this.slot = slot;
this.items = items;
this.mat = mat;
}
public int getSlot() {
return slot;
}
public String getInventoryName() {
return inventoryName.replace('&', '§');
}
public int getInventorySize() {
return inventorySize;
}
public void createInventory() {
inv = Bukkit.createInventory(null, getInventorySize(), getInventoryName());
}
public Inventory getInventory() {
return inv;
}
public List<Items> getItems() {
return items;
}
public Material getMaterial() {
return mat;
}
public void initialiseInventory() {
Map<Integer, ItemStack> it = new HashMap<>();
for(Items items : getItems()) {
List<String> lores = items.getItems().getItemMeta().getLore().stream()
.map(str -> str.replace("&", "§"))
.collect(Collectors.toList());
ItemStack stack = new ItemStack(items.getItems().getType(), 1);
ItemMeta s = stack.getItemMeta();
s.setDisplayName(items.getItems().getItemMeta().getDisplayName().replace('&', '§'));
s.setLore(lores);
stack.setItemMeta(s);
it.put(items.getSlot(), stack);
}
while(it.size() != 0) {
for(int i = 0; i <= inv.getSize(); i++) {
if(it.get(i) != null) {
inv.setItem(i, it.get(i));
it.remove(i);
}
}
}
ItemStack retour = new ItemStack(Material.BARRIER, 1);
ItemMeta r = retour.getItemMeta();
r.setDisplayName("§cRetour");
retour.setItemMeta(r);
inv.setItem(inv.getSize() - 1, retour);
}
}
|
Java | UTF-8 | 972 | 1.578125 | 2 | [] | no_license | //
// Decompiled by Procyon v0.5.30
//
package com.BV.LinearGradient;
import java.util.Arrays;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import java.util.Collections;
import com.facebook.react.bridge.JavaScriptModule;
import java.util.List;
import com.facebook.react.ReactPackage;
public class LinearGradientPackage implements ReactPackage
{
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(final ReactApplicationContext reactApplicationContext) {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(final ReactApplicationContext reactApplicationContext) {
return (List<ViewManager>)Arrays.asList(new LinearGradientManager());
}
}
|
Java | UTF-8 | 4,373 | 2.328125 | 2 | [] | no_license | package edu.cnt.peers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Vector;
import edu.cnt.common.Constants;
import edu.cnt.common.SortedArrayList;
import edu.cnt.message.P2PMessage;
/**
* @author pratiksomanagoudar
*
*/
public class PeerHandler {
private static ArrayList<String> interestedPeers = new ArrayList<String>();
private static HashMap<String, Integer> requestTracker = new HashMap<String, Integer>();
public static boolean isFilePresent;
public static LinkedHashMap<String,String> IpPeerMap=null;
public static LinkedHashMap<String,String> IpPortmap=null;
public static HashMap<String, String> peerIPMap = new HashMap<String, String>();
public static String hostIP;
public static int hostPort;
public static String hostPeerID;
private static String optimisticPeer = new String();
private static SortedArrayList<PeerDataHolder> sortedDataPeers= new SortedArrayList<PeerDataHolder>();
//public static Map<String, Long> peerDataMap= null;
//public static ArrayList<Peers> peer = new ArrayList<Peers>();
/**
*
*/
private static ArrayList<String> unChokedPeers = new ArrayList<String>();
public static boolean isFirstStart = true;
public static ArrayList<String> haveBroadCastPeers= new ArrayList<String>();
private static Vector<String> peerInterested = new Vector<String>();
/**
* @return the peerInterested
*/
public synchronized static Vector<String> getPeerInterested() {
return peerInterested;
}
public static void addInteredtedPeer(String IP){
interestedPeers.add(IP);
}
public static synchronized void removeInteredtedPeer(String IP){
if(interestedPeers.contains(IP)){
interestedPeers.remove(IP);
}
}
public synchronized static boolean noRequestsSentToIP(String IP) {
return !requestTracker.containsKey(IP);
}
public static synchronized ArrayList<String> getInterestedArray(){
return interestedPeers;
}
public synchronized static void addRequestToTracker(String IP, Integer seq){
requestTracker.put(IP, seq);
System.out.println("ADDED REQUEST"+ seq+" IN TRACKER FOR "+IP );
}
public synchronized static void removeRequestFromTracker(String IP){
if(requestTracker.containsKey(IP)){
requestTracker.remove(IP);
System.out.println("REMOVE REQUEST IN TRACKER FOR "+IP );
}
}
public static void setSelfDetails() {
//hostPeerID= Constants.MY_PEERID;
hostIP = peerIPMap.get(hostPeerID);
hostPort = Integer.parseInt((String)IpPortmap.get(hostIP));
}
public synchronized static void updatePeerDataReceived(String IP, P2PMessage msg){
for(PeerDataHolder peer : sortedDataPeers){
if(peer.equals(IP)){
peer.setData(peer.getData()+msg.getMsgLength());
}
}
}
public static synchronized ArrayList< String> getPreferredNeighbour(int size){
ArrayList<String> neighbours = new ArrayList<String>();
int count=sortedDataPeers.size()-1;
while(neighbours.size()!=size|| count < 0){
PeerDataHolder PD= sortedDataPeers.get(count);
if(interestedPeers.contains(PD.getPeerIP())){
neighbours.add(PD.getPeerIP());
}
count--;
}
return neighbours;
}
public static void initializePeerData() {
sortedDataPeers = new SortedArrayList<PeerDataHolder>();
for (String ip : PeerHandler.IpPeerMap.keySet()) {
if(!ip.equals(hostIP))
sortedDataPeers.insertSorted(new PeerDataHolder(ip, 0));
}
}
public static synchronized ArrayList<String> getUnChokedPeers() {
return unChokedPeers;
}
public static synchronized void setUnChokedPeers(ArrayList<String> unChokedPeers) {
PeerHandler.unChokedPeers = unChokedPeers;
}
public static synchronized boolean isNotRequestedSequence(int seq){
return !requestTracker.containsValue(seq);
}
public static synchronized boolean isUnchokedPeer(String IP){
return unChokedPeers.contains(IP);
}
public static synchronized void addPeerToSentInterested(String IP) {
if(!peerInterested.contains(IP)&&!IP.equals(hostIP)){
peerInterested.add(IP);
}
}
public static synchronized void removePeerToSentInterested(String IP) {
if(peerInterested.contains(IP)){
peerInterested.remove(IP);
}
}
public synchronized static String getOptimisticPeer() {
return optimisticPeer;
}
public synchronized static void setOptimisticPeer(String optimisticPeer) {
PeerHandler.optimisticPeer = optimisticPeer;
}
}
|
C++ | UTF-8 | 1,849 | 2.515625 | 3 | [] | no_license | #ifndef GAMEMANAGER_H
#define GAMEMANAGER_H
#include "Singleton.h"
#include "ScreenManager.h"
#include "DebugManager.h"
#include "InputManager.h"
#include "ShaderManager.h"
#include "Camera.h"
#include "Texture.h"
#include "Quad.h"
#include "GameObject.h"
#include "Cube.h"
#include "Light.h"
#include "Model.h"
#include "Material.h"
class GameManager
{
public:
friend class Singleton<GameManager>;
public:
GameManager();
void Initialize();
void GameSceneSetup();
void UpdateObjects();
void DrawObjects();
void GameLoop();
void DestroyObjects();
void Shutdown();
private:
const Uint8* keyStates = SDL_GetKeyboardState(NULL);
bool m_canMoveCrate;
Camera* m_camera = new Camera;
//Room Setup
GameObject* m_backWall;
GameObject* m_floor;
GameObject* m_leftWall;
GameObject* m_rightWall;
//Cubes
GameObject* m_crateOne;
GameObject* m_crateTwo;
//Blocks
GameObject* m_goldBlock;
GameObject* m_turquoiseBlock;
GameObject* m_emeraldBlock;
GameObject* m_obsidianBlock;
GameObject* m_silverBlock;
GameObject* m_copperBlock;
GameObject* m_chromeBlock;
//Shader Cubes
Cube* m_noiseCrate;
Cube* m_circleNoiseCrate;
Cube* m_colorChangeCrate;
Cube* m_fireBoxCrate;
//Skybox
Cube* m_sky;
//Quad
Quad* m_quad;
//Lights
static const int total_lights = 3;
Light* m_light[total_lights];
//Models
Model* m_bedModel;
Model* m_bedTableModel;
Model* m_tableModel;
Model* m_chairModel;
Model* m_showerModel;
Model* m_rugModel;
Model* m_plateModel;
Model* m_geckoModel;
Model* m_poufModel;
Model* m_binModel;
Model* m_spaceshipModel;
//Asteroids
static const int total_asteroids = 4;
Model* m_asteroidModel[total_asteroids];
bool isGameOver = false;
bool m_allLightsControl = true;
bool m_light1Control = false;
bool m_light2Control = false;
};
typedef Singleton<GameManager> TheGame;
#endif |
C++ | UTF-8 | 1,664 | 2.921875 | 3 | [] | no_license | // A program to select a region in an image
// Use for initial parameters to a tracker?
// Iain Wallace, 15/8/05
#include "CImg.h"
#include <iostream>
using namespace cimg_library;
using namespace std;
int main(int argc,char **argv)
{
if (argc != 2)
{
cout << "Usage: initTracker first_frame" << endl;
exit(1);
}
CImg<unsigned char> image(argv[1]);
CImg<unsigned char> orig(image);
CImgDisplay main_disp(image,"Click 2 points");
const unsigned char red[3]={255,0,0};
bool clicked_once = false;
int x1,y1,x2,y2;
while (!main_disp.closed)
{
main_disp.wait();
if (main_disp.button && main_disp.mouse_y>=0 && main_disp.mouse_x>=0)
{
if (!clicked_once)
{
y1 = main_disp.mouse_y;
x1 = main_disp.mouse_x;
clicked_once = true;
}
else
{
y2 = main_disp.mouse_y;
x2 = main_disp.mouse_x;
clicked_once = false;
image.draw_rectangle(x1,y1,x2,y2,red,0.4);
main_disp.display(image);
char response = 'n';
cout << "Selection ok? [y/n]: ";
cin >> response;
if ((response == 'y') || (response == 'Y'))
{
cout << "X1: " << x1 << endl << " Y1: " << y1 << endl;
cout << "X2: " << x2 << endl << " Y2: " << y2 << endl;
main_disp.close();
exit(0);
}
}
image = orig;
main_disp.display(image);
}
}
return 0;
}
|
Java | UTF-8 | 288 | 1.570313 | 2 | [
"MIT"
] | permissive | package OOD.LinuxFind;
public enum PlanNodeKind {
OPTION, // 全局的configuration
PREDICATE, // 各种 filter 和 operations(“与或非”逻辑联结词)可以合称为谓词 predicate,类似于SQL中的where语句
ACTION // 一些side effect操作
}
|
Swift | UTF-8 | 967 | 2.578125 | 3 | [
"MIT"
] | permissive | //
// EditAisleView.swift
// Shopper
//
// Created by John Forde on 13/5/18.
// Copyright © 2018 4DWare. All rights reserved.
//
import Stevia
import IGListKit
class EditAisleView: UIView {
let closeButton = UIButton()
let listView = ListCollectionView(frame: CGRect.zero, listCollectionViewLayout: ListCollectionViewLayout(stickyHeaders: true, scrollDirection: .vertical, topContentInset: 0, stretchToEdge: true))
convenience init() {
self.init(frame: CGRect.zero)
render()
}
func render() {
// Here we use Stevia to make our constraints more readable and maintainable.
sv(closeButton.style { b in
b.backgroundColor = UIColor.darkGray
b.setTitleColor(UIColor.textColor, for: .normal)
b.titleLabel?.font = UIFont.backButtonFont
b.text("Close")
},
listView)
backgroundColor = UIColor.darkGray
listView.backgroundColor = UIColor.darkGray
layout(50,
|-(>=16)-closeButton-16-|,
8,
|-listView-|,
8)
}
}
|
Java | UTF-8 | 233 | 2.96875 | 3 | [] | no_license | package numbers;
public class NumberGenerator implements INumberGenerator {
private int number = 0;
public int nextNumber() {
return number++;
}
public void setNextNumber(int value) {
number = value;
}
}
|
Markdown | UTF-8 | 3,652 | 2.96875 | 3 | [] | no_license | ---
title: "Cara membuat custom shortcode di Hugo"
date: 2021-09-13T19:16:27+07:00
draft: false
Author: "Surya Efendi"
Description: "di Hugo untuk membuat postingan pasti menggunakan markdown style, karena file-nya ditulis dengan format markdown, lalu kalian apabila ingin menambahkan syntax html di markdown tidak bisa di render menjadi html, karena bukan markdown style,"
Cover: "/img/hugo-shortcode.png"
Toc: true
TocTitle: "Daftar Isi"
tags: ["Hugo","GoLang","web","SSG"]
---
***Cara membuat custom shortcode di Hugo*** - di Hugo untuk membuat postingan pasti menggunakan markdown style, karena file-nya ditulis dengan format markdown, lalu kalian apabila ingin menambahkan syntax html di markdown tidak bisa di render menjadi html, karena bukan markdown style,
## Shortcode Hugo
untuk itu hugo menawarkan fitur `shortcode` untuk menambahkan syntax html didalam markdown, namun `shortcode` bawaan Hugo ini terbatas, hanya syntax tertentu yang ada di `shortcode` bawaan Hugo, untuk itu kita coba buat custom `shortcode` sendiri
## Lokasi File Shortcode
### Root folder
untuk membuat sebuah shortcode, buat file html dengan nama bebas di `layouts/shortcodes/namafile.html` kemudian untuk memanggil file shortcode cukup mudah dengan mengetik :
```go
{{- <namafile> }}
```
### Subfolder shortcode
kamu bisa mengelompokkan shortcode kamu menggunakan subfolder contohnya `layouts/shortcodes/namafolder/namafile.html`
kemudian untuk memanggil file shortcode cukup mudah dengan mengetik :
```go
{{- < namafolder/namafile > }}
```
## Susunan Tepmlate Shortcode Hugo
Susunan Template Shortcode di Hugo yaitu :
1. `/layouts/shortcodes/<SHORTCODE>.html`
2. `/themes/<THEME>/layouts/shortcodes/<SHORTCODE>.html`
Jadi shortcode akan dijalankan sesuai urutan diatas, apabila shortcode dipanggil maka Hugo akan mencari shortcode di folder projek kita terlebih dahulu kemudian, jika nggak ada maka akan mencari ke tema yang terinstal di projek kita
## Posisional Argument dan Named Parameter
kamu bisa membuat Shortcode dengan mengikuti tipe Parameter :
- Positional parameters
- Named parameters
- Positional or named parameters
### Posisional argumen
pada shortcode untuk memberi sebuah argumen bisa tanpa menggunakan named Parameter, contohnya seperti ini :
```go
{{- < gambar 'link/to/path/image.jpg' > }}
```
### Named Parameter
pada shortcode untuk memberi sebuah argumen menggunakan named Parameter, contohnya seperti ini :
```go
{{- < gambar src='link/to/path/image.jpg' > }}
```
### Positional or named parameters
pada shortcode untuk memberi sebuah argumen menggunakan named Parameter dan juga tanpa parameter secara bersamaan, contohnya seperti ini :
```go
{{- < gambar src='link/to/path/image.jpg' 'gambar' > }}
```
## Mengambil Parameter
Semua parameter pada Shortcode bisa diakses lewat method `.Get` , meskipun tanpa paramater atau dengan parameter
### Mengambil Parameter dengan named Parameter
Untuk mengambil parameter dengan nama, gunakan method `.Get` kemudian diikuti dengan nama parameter yang diapit 2 kutip
```go
{{- .Get "src" }}
```
### Mengambil Parameter dengan posisional Parameter
Untuk mengambil parameter tanpa nama, gunakan method `.Get` kemudian diikuti dengan nomor (nomor dimulai dari 0)
```go
{{- .Get 0 }}
```
## Kesimpulan
Begitulah cara membuat shortcode di Hugo, kurang lebihnya mohon maaf, sampai jumpa dia artikel berikutnya~~
**Referensi**
- {{< a href="https://gohugo.io/content-management/shortcodes/" teks="https://gohugo.io/content-management/shortcodes/" >}}
- {{< a href="https://gohugo.io/templates/shortcode-templates/" teks="https://gohugo.io/templates/shortcode-templates/" >}} |
Python | UTF-8 | 144 | 3.125 | 3 | [] | no_license |
div8 = [i for i in range(1001) if i % 8 == 0]
print(div8)
# a=[]
# for i in range(1001):
# if i%8==0:
# a.append(i)
# print(a)
|
C | UTF-8 | 245 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
int main(void)
{
int a[50],i,t,n,j;
scanf("%d",&n);
for(i=0;1<=3;i++)
{
scanf("%d",a[i]);
}
for(i=1;i<n;i++)
for(j=0;j<=n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf("%d",a[0]);
return 0;
}
|
Python | UTF-8 | 980 | 3.296875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Initialize parameters
"""
radius = 3.5 #Spiral radius [mm]
height = 18.0 #Spiral height [mm] (include 0.0)
nTurns = 6 #Number of turns of spiral
nPoints = 20 #Number of points per turn
pSpeed = 300 #Printer speed in [mm/min]
pitch = height/nTurns/nPoints #Height of each turn [mm]
import math
f = open('{:.1f}x{:.1f}mm_{}.gcode'
.format(radius, height, nTurns), 'w')
x = radius #initialize xyz position
y = 0
z = 0
theta = 0
f.write('G1 X{:0.2f} Y{:0.2f} Z{:0.2f} F{} ;move to starting location\n'
.format(x, y, z, pSpeed))
for turn in range(nTurns):
theta = 0
for point in range(nPoints):
theta = theta + (360/nPoints)*(math.pi/180)
z = z + pitch
x = radius*math.cos(theta)
y = radius*math.sin(theta)
f.write('G1 X{:0.2f} Y{:0.2f} Z{:0.2f} E{:0.1f} \n'
.format(x,y,z,z))
f.close() |
Java | UTF-8 | 524 | 2.34375 | 2 | [] | no_license | package com.example.db.dbflowtest.Utils;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author lijian
* @des
* @date 2019/3/9 14:19
**/
public class DateUtil {
public static final String DATETIME_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT_DEFAULT = "yyyy-MM-dd";
public static final String TIME_FORMAT_DEFAULT = "HH:mm:ss";
public static String getDate(Date date, String format) {
return new SimpleDateFormat(format).format(date);
}
}
|
Java | UTF-8 | 181 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package com.shengfq.designpatten.strategy.abs;
/**
* 样板抽象策略接口
* */
public interface StrategyInterfaceB extends GenericInterface<Integer> {
String handle();
}
|
SQL | UTF-8 | 160 | 2.828125 | 3 | [] | no_license | SELECT FirstName + ' ' + MiddleName + ' ' + LastName AS 'Full Name'
FROM Employees
WHERE Salary = 25000
OR Salary = 14000
OR Salary = 12500
OR Salary = 23600 |
Markdown | UTF-8 | 812 | 2.796875 | 3 | [] | no_license | Detect Spider EE2 Plugin
=============
Lightweight PHP plugin for EE2 that detects a search engine crawlers using PHP.
This is my first time writing any any sort of plugin for EE. I'm not a very strong PHP guy so go easy on me :-) Please post any suggestions, changes, bugs, requests, etc to GitHub issues.
----------
Installation
------------
Download and unzip the archive. Create a folder called `detect_spider`, place the file `pi.detect_spider.php` inside the folder and upload the `detect_spider` folder to /system/expressionengine/third_party/.
Basic Usage
-------------
**Check if any crawlers**
`{exp:detect_spider}` - returns true or false
**Conditional check for a crawler**
{if '{exp:detect_spider}'}
I am a search crawler
{if:else}
I am a normal visitor
{/if}
|
Java | UTF-8 | 6,243 | 1.648438 | 2 | [] | no_license | package com.frameworkui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.frameworkui.uicore.actionbar.ActionBar;
import com.frameworkui.uicore.actionbar.ActionBarMenu;
import com.frameworkui.uicore.actionbar.MenuDrawable;
import com.frameworkui.uicore.BaseFragment;
import com.frameworkui.uicore.BaseFragmentPagerAdapter;
import com.frameworkui.uicore.ChildFragmentManager;
import com.frameworkui.uicore.TabFragment;
/**
* Created by ThoLH on 10/05/2015.
*/
public class MainFragment extends BaseFragment implements BaseFragment.SingleInstance {
private ViewPager mViewPager;
private ActionBarMenu mMenu;
@Override
public boolean isEnableSwipeBack() {
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
hasMenu = true;
mFragmentView = inflater.inflate(R.layout.main_fragment, container, false);
// mFragmentView.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//// getBaseActivity().presentFragment(BaseActivity.FragmentType.PROFILE, null, 1111, BaseActivity.TRANSLATION_WITH_FADE_IN);
// Bundle bundle = new Bundle();
// bundle.putString("MainFragment", "Zalo");
// getActivity().getFragmentManagerLayout().showFragment(FragmentData.FragmentType.CHAT, bundle, 1111, false, false);
// }
// });
return mFragmentView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mViewPager = (ViewPager) view.findViewById(R.id.tabs);
mViewPager.setAdapter(new TabsAdapter(getChildFragmentManager()));
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("CurrentPosition")) {
mViewPager.setCurrentItem(savedInstanceState.getInt("CurrentPosition"));
}
}
final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
tabLayout.setScrollPosition(position, positionOffset, true);
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
@Override
public void onSetupActionBar() {
super.onSetupActionBar();
ActionBar actionBar = (ActionBar) getView().findViewById(R.id.custom_action_bar);
if (actionBar != null) {
actionBar.setTitle("Main Fragment");
actionBar.setBackButtonDrawable(new MenuDrawable());
actionBar.setSubtitle("Test Fragment");
}
// super.onSetupActionBar();
// ActionBar actionBar = getActivity().getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle("Main Fragment");
// }
}
@Override
public void onCreateOptionsMenu(ActionBarMenu menu) {
menu.addItem(1, getMenuMoreDrawable()).setIsSearchField(true);
}
@Override
public boolean onOptionItemSelected(int menuId) {
if (menuId == -1) {
getActivity().finish();
return true;
}
return false;
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1111 && resultCode == Activity.RESULT_OK) {
Toast.makeText(getActivity(), "Chat Fragment " + data.getExtras(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("CurrentPosition", mViewPager.getCurrentItem());
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (mViewPager != null)
mViewPager.setVisibility(View.VISIBLE);
}
@Override
public void onDetach() {
if (mViewPager != null)
mViewPager.setVisibility(View.GONE);
super.onDetach();
}
private class TabsAdapter extends BaseFragmentPagerAdapter {
private BaseFragment[] fragments = new BaseFragment[4];
private int mPreviousPosition = 0;
public TabsAdapter(ChildFragmentManager childFragmentManager) {
super(childFragmentManager);
}
@Override
public BaseFragment getItem(int position) {
BaseFragment f = fragments[position];
if (f == null) {
Bundle bundle = new Bundle();
bundle.putInt("position", position);
f = new TabFragment();
f.setArguments(bundle);
fragments[position] = f;
}
return f;
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
}
}
|
Java | UTF-8 | 1,110 | 2.03125 | 2 | [] | no_license | package com.example.stackoverflowapp.viewmodel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.paging.LivePagedListBuilder;
import androidx.paging.PageKeyedDataSource;
import androidx.paging.PagedList;
import com.example.stackoverflowapp.datasource.ItemDataSource;
import com.example.stackoverflowapp.datasource.ItemDataSourceFactory;
import com.example.stackoverflowapp.model.Item;
public class ItemViewModel extends ViewModel {
public LiveData<PagedList<Item>> itemPageList;
public LiveData<PageKeyedDataSource<Integer, Item>> liveDataSource;
public ItemViewModel() {
ItemDataSourceFactory itemDataSourceFactory = new ItemDataSourceFactory();
liveDataSource = itemDataSourceFactory.getItemLiveDataSource();
PagedList.Config config =
new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(ItemDataSource.PAGE_SIZE)
.build();
itemPageList = (new LivePagedListBuilder(itemDataSourceFactory, config))
.build();
}
}
|
Java | UTF-8 | 3,713 | 2.03125 | 2 | [] | no_license | package bus.uigen.viewgroups;
import java.beans.MethodDescriptor;
import java.util.Vector;
import bus.uigen.uiFrame;
import bus.uigen.introspect.ClassDescriptorCache;
import bus.uigen.introspect.MethodDescriptorProxy;
import bus.uigen.introspect.ClassDescriptorInterface;
import bus.uigen.misc.OEMisc;
import bus.uigen.oadapters.ObjectAdapter;
import bus.uigen.reflect.ClassProxy;
import bus.uigen.reflect.MethodProxy;
import bus.uigen.sadapters.RecordStructure;
import bus.uigen.sadapters.VectorStructure;
import bus.uigen.undo.CommandListener;
public class ForFutureUseTuple {
RecordStructure record;
VectorStructure rowObject;
uiFrame frame;
Vector filterIn = new Vector();
int row, column;
ObjectAdapter parentAdapter;
DescriptorViewSupport descriptorViewSupport;
String keyProperty;
Object keyValue;
public ForFutureUseTuple (RecordStructure theRecordStructure, String theKeyProperty, Object theKeyValue, int theRow, int theColumn, uiFrame theFrame, ObjectAdapter theParentAdapter) {
descriptorViewSupport = new DescriptorViewSupport();
ClassProxy c = theRecordStructure.getTargetClass();
ClassDescriptorInterface cd = ClassDescriptorCache.getClassDescriptor(c);
addMethods (theRecordStructure.getTargetObject(), cd.getMethodDescriptors());
init(theRecordStructure, theKeyProperty, theKeyValue, theRow, theColumn, theFrame, theParentAdapter);
/*
tuple = theRecordStructure;
frame = theFrame;
parentAdapter = theParentAdapter;
filterIn = (Vector) tuple.componentNames().clone();
index = theIndex;
filterIn(keyProperty, false);
*/
}
protected void init (RecordStructure theRecordStructure, String theKeyProperty, Object theKeyValue, int theRow, int theColumn, uiFrame theFrame, ObjectAdapter theParentAdapter) {
record = theRecordStructure;
frame = theFrame;
parentAdapter = theParentAdapter;
filterIn.clear();
filterIn = (Vector) record.componentNames().clone();
row = theRow;
column = theColumn;
keyProperty = theKeyProperty;
}
protected int getRow() {
return row;
}
protected int getColumn() {
return column;
}
protected RecordStructure getRecord() {
return record;
}
public String getVirtualClass() {
return record.getTargetClass().getName();
}
public String[] getDynamicProperties() {
Vector<String> allProperties = record.componentNames();
return add(keyProperty, allProperties);
/*
String[] retVal = new String[filterIn.size()];
filterIn.copyInto(retVal);
return retVal;
*/
}
protected String[] add (String firstElement, Vector<String> list) {
String[] retVal = new String[list.size() + 1];
retVal[0] = firstElement;
for (int i = 1; i < retVal.length; i++) {
retVal[i] = list.get(i-1);
}
return retVal;
}
public void setDynamicProperty(String name, Object newVal) {
//tuple.set(name, newVal, parentAdapter);
if (name.toLowerCase().equals(keyProperty.toLowerCase()))
return;
record.set(name, newVal);
}
public Object getDynamicProperty(String name) {
if (name.toLowerCase().equals(keyProperty.toLowerCase()))
return keyValue;
return record.get(name);
}
protected void addMethods (Object theTargetObject, MethodDescriptorProxy[] theMethods) {
descriptorViewSupport.addMethods(theTargetObject, theMethods);
/*
for (int i = 0; i < theMethods.size(); i++) {
virtualMethods.addElement(VirtualMethodDescriptor.getVirtualMethod(theMethods.elementAt(i)).moveFromObject(theTargetObject));
}
*/
}
public Vector<MethodProxy> getVirtualMethods() {
return descriptorViewSupport.getVirtualMethods();
/*
return virtualMethods;
*/
}
}
|
Java | UTF-8 | 4,744 | 2.21875 | 2 | [] | no_license | package de.blackforestsolutions.apiservice.service.supportservice;
import de.blackforestsolutions.datamodel.ApiTokenAndUrlInformation;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import java.io.UncheckedIOException;
import java.net.URL;
import java.util.Objects;
import static de.blackforestsolutions.apiservice.objectmothers.ApiTokenAndUrlInformationObjectMother.getLufthansaTokenAndUrl;
import static de.blackforestsolutions.apiservice.service.supportservice.HttpCallBuilder.*;
import static org.assertj.core.api.Assertions.assertThat;
class HttpCallBuilderServiceTest {
@Test
void test_buildUrlWith_protocol_host_port_path_http_returns_correcturl() {
ApiTokenAndUrlInformation testData = getLufthansaTokenAndUrl();
URL result = buildUrlWith(testData);
assertThat(result.getProtocol()).isEqualToIgnoringCase(testData.getProtocol());
assertThat(result.getHost()).isEqualToIgnoringCase(testData.getHost());
assertThat(result.getPort()).isEqualTo(testData.getPort());
assertThat(result.getPath()).isEqualToIgnoringCase(testData.getPath());
}
@Test
void test_buildUrlWith_protocol_host_port_path_https_returns_correcturl() {
ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder builder = new ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder(getLufthansaTokenAndUrl());
builder.setProtocol("https");
URL result = buildUrlWith(builder.build());
assertThat(result.getProtocol()).isEqualToIgnoringCase(builder.getProtocol());
assertThat(result.getHost()).isEqualToIgnoringCase(builder.getHost());
assertThat(result.getPort()).isEqualTo(builder.getPort());
assertThat(result.getPath()).isEqualToIgnoringCase(builder.getPath());
}
@Test
void test_buildUrlWith_wrong_protocol_host_port_path_throws_MalformedURLException() {
ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder builder = new ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder(getLufthansaTokenAndUrl());
builder.setProtocol("wrong");
org.junit.jupiter.api.Assertions.assertThrows(UncheckedIOException.class, () -> buildUrlWith(builder.build()));
}
@Test
void test_buildUrlWith_protocol_host_path_http_returns_correcturl() {
ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder builder = new ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder(getLufthansaTokenAndUrl());
builder.setPort(-1);
URL result = buildUrlWith(builder.build());
assertThat(result.getProtocol()).isEqualToIgnoringCase(builder.getProtocol());
assertThat(result.getHost()).isEqualToIgnoringCase(builder.getHost());
assertThat(result.getPort()).isEqualTo(builder.getPort());
assertThat(result.getPath()).isEqualToIgnoringCase(builder.getPath());
}
@Test
void test_buildUrlWith_protocol_host_path_correct_params_https_returns_correcturl() {
ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder builder = new ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder(getLufthansaTokenAndUrl());
builder.setProtocol("https");
builder.setPort(-1);
URL result = buildUrlWith(builder.build());
assertThat(result.getProtocol()).isEqualToIgnoringCase(builder.getProtocol());
assertThat(result.getHost()).isEqualToIgnoringCase(builder.getHost());
assertThat(result.getPort()).isEqualTo(builder.getPort());
assertThat(result.getPath()).isEqualToIgnoringCase(builder.getPath());
}
@Test
void test_buildUrlWith_wrong_protocol_host_path_throws_MalformedURLException() {
ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder builder = new ApiTokenAndUrlInformation.ApiTokenAndUrlInformationBuilder(getLufthansaTokenAndUrl());
builder.setProtocol("wrong");
builder.setPort(-1);
org.junit.jupiter.api.Assertions.assertThrows(UncheckedIOException.class, () -> buildUrlWith(builder.build()));
}
@Test
void test_setFormatToJsonFor_with_basic_Httpheader_returns_json_Httpheader() {
HttpHeaders testData = new HttpHeaders();
setFormatToJsonFor(testData);
assertThat(Objects.requireNonNull(testData.get(HttpHeaders.ACCEPT)).get(0)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
}
@Test
void test_setFormatToXmlFor_with_basic_Httpheader_returns_xml_Httpheader() {
HttpHeaders testData = new HttpHeaders();
setFormatToXmlFor(testData);
assertThat(Objects.requireNonNull(testData.get(HttpHeaders.ACCEPT)).get(0)).isEqualTo(MediaType.APPLICATION_XML_VALUE);
}
}
|
Shell | UTF-8 | 832 | 3.046875 | 3 | [] | no_license | #!/bin/sh
SCRIPT_ROOT=$(dirname "$(realpath -s $0)")
NODE_HOME="$SCRIPT_ROOT/volumes/livenet"
BITCORE_HOME="$(dirname "$SCRIPT_ROOT")/sibcore/volumes/bitcore"
NODE_CONTAINER_HOME="/home/sibcore/node"
BITCORE_CONTAINER_HOME="/home/sibcore/.nvm/versions/node/v4.8.4/lib/node_modules/bitcore"
if [ ! -d ${NODE_HOME}/node_modules/insight-api ]
then
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
nvm use v4.8.4
cd ${NODE_HOME} && npm install
fi
# Step
# BWS inside -p 3232:3232 -p 3231:3231 -p 3380:3380 --link bwsdb:bwsdb \
# Sibcore inside
docker run --rm -it -p 1945:1945 -p 1944:1944 -p 3001:3001 \
-v ${NODE_HOME}:${NODE_CONTAINER_HOME} \
-v ${BITCORE_HOME}:${BITCORE_CONTAINER_HOME} \
livenet:1
|
Markdown | UTF-8 | 1,255 | 3.28125 | 3 | [] | no_license | https://sleeptracker123.netlify.com/login
Sleep Tracker
"Pitch:
Not everyone needs 8 hours of sleep, but how do you know if you’re someone lucky enough to need only 6? Or an unlucky one that needs 10?! Enter Sleep Tracker.
MVP:
Onboarding process for a user.
Homepage view shows a graph of your nightly hours of sleep over time .
Ability to create a night’s sleep entry. For each date set (1/1/19-1/2/19), user can scroll through a digital clock image (like when you set your alarm on your phone, or just type in) to enter what time they got in bed and what time they woke up. From this data, app will calculate their total time in bed.
Ability to edit or delete a sleep entry.
Ability to click one of four emoji buttons to rate how they felt right when they woke up, how they felt during the day, and how tired they felt when they went to bed. Behind the scenes, a score 1-4 is given for each emoji. The app will calculate an average mood score for 1/2/19, and compare it to the time spent in bed. The app will then recommend after using for >1 month how much sleep you need. “Your mood score tends to be highest when you sleep 7.5 hours”
Stretch: Connect the app to a movement tracking device to automatically track when user is asleep.
" |
Java | UTF-8 | 3,644 | 2.46875 | 2 | [
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.bluewind.boot.common.utils;
import com.bluewind.boot.module.sys.sysbasedict.mapper.SysBaseDictMapper;
import com.bluewind.boot.common.utils.spring.SpringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author liuxingyu01
* @date 2020-05-30-0:28
* @description 获取枚举值 公共方法类 - 使用SpringUtil工具类获取bean
**/
public class BaseDictUtils {
final static Logger logger = LoggerFactory.getLogger(BaseDictUtils.class);
private static SysBaseDictMapper sysBaseDictMapper;
private static SysBaseDictMapper getBaseDictService() {
if (sysBaseDictMapper == null) {
Object bean = SpringUtil.getBean("sysBaseDictMapper");
if (bean == null) {
logger.error("baseDictMapper bean is null!");
}
sysBaseDictMapper = (SysBaseDictMapper) bean;
}
return sysBaseDictMapper;
}
/**
* 根据字典id和key获取对应的值
* @param dictId
* @param key
* @return
*/
public static String getDictValue(String dictId, String key) {
if (StringUtils.isBlank(dictId)) {
return "字典id不能为空";
}
if (StringUtils.isBlank(key)) {
return "字典key不能为空";
}
String dictValue = "";
List<Map<String, String>> dictList = getBaseDictService().getBaseDictByDictId(dictId);
if (CollectionUtils.isNotEmpty(dictList)) {
for (Map tempMap : dictList) {
if (!MapUtils.isEmpty(tempMap)) {
if (key.equals((String) tempMap.get("code"))) {
dictValue = (String) tempMap.get("name");
break;
}
}
}
}
return dictValue;
}
/**
* 获取指定的枚举列表
*
* @param dictId
* @return
*/
public static List<Map<String, String>> getDictList(String dictId) {
if (StringUtils.isBlank(dictId)) {
return null;
}
List<Map<String, String>> dictList = getBaseDictService().getBaseDictByDictId(dictId);
if (!CollectionUtils.isEmpty(dictList)) {
return dictList;
} else {
return null;
}
}
/**
* 获取指定的枚举Map
* @param dictId
* @return
*/
public static Map<String, String> getDictMap(String dictId) {
if (StringUtils.isBlank(dictId)) {
return null;
}
Map<String, String> result = new HashMap<>();
List<Map<String, String>> dictList = getBaseDictService().getBaseDictByDictId(dictId);
if (!CollectionUtils.isEmpty(dictList)) {
for (int i = 0; i < dictList.size(); i++) {
Map<String, String> tempMap = dictList.get(i);
String K = tempMap.get("code");
String V = tempMap.get("name");
result.put(K, V);
}
}
return result;
}
/**
* 获取指定的枚举JSON
* @param dictId
* @return
*/
public static String getDictJson(String dictId) {
List<Map<String, String>> list = getDictList(dictId);
if (!CollectionUtils.isEmpty(list)) {
return JsonTool.listToJsonString(list);
} else {
return "获取字典列表为空";
}
}
}
|
Markdown | UTF-8 | 1,292 | 2.546875 | 3 | [] | no_license | ---
template: article.jade
title: Ubuntu 8.04 Hardy Heron vs Firefox 2 & 3
date: '2008-05-13T19:59:00.000Z'
author: Olivier
aliases: ['/post/2008/05/13/ubuntu-8-04-hardy-heron-vs-firefox-2-3/', '/post/2008/05/13/ubuntu-804-hardy-heron-vs-firefox-2-3/']
categories: [Uncategorized]
tags: [Ubuntu,firefox]
---
<p>Tout le monde l'a remarqué lors de l'installation de Hardy, Firefox 3 a été installé.</p> <p>Toutes les extensions ne sont pas compatibles entre FF 2 et FF3; par exemple : <a href="https://addons.mozilla.org/fr/firefox/addon/3829">Live HTTP Headers</a>, <a href="https://addons.mozilla.org/fr/firefox/addon/1843">Firebug</a>, <a href="https://addons.mozilla.org/fr/firefox/addon/518">Fetch Text URL</a> ,...</p> <p>Pour gérer cette cohabitation, il faut passer par les profiles.</p> <p>Création d'un profile "FF2" pour firefox 2:</p>
<pre class="prettyprint lang-bsh">
% firefox-2 --profilemanager
</pre>
<p>Lancer les firefox :</p>
<pre class="prettyprint lang-bsh">
% firefox-2 -P FF2 -no-remote
</pre>
<pre class="prettyprint lang-bsh">
% firefox -P default -no-remote
</pre>
<p>Il faut réinstaller un à un les extensions dans FF2 ainsi que la configuration générale (gestion du cache, historique, ...) puisque FF2 est avec un profile tout neuf.</p>
|
Java | UTF-8 | 596 | 2.140625 | 2 | [
"MIT"
] | permissive | package com.xjcy.easywx.post;
import com.xjcy.util.ObjectUtils;
/**
* 微信页面签名所用对象
* @author YYDF
* 2018-04-13
*/
public class JsapiTicket {
public JsapiTicket(String _appId, String nonce, long time, String signStr) {
this.appId = _appId;
this.nonceStr = nonce;
this.timestamp = time;
this.signature = ObjectUtils.SHA1(signStr);
}
/**
* 微信公众号唯一ID
*/
public String appId;
/**
* 时间戳
*/
public long timestamp;
/**
* 随机字符串
*/
public String nonceStr;
/**
* 加密后字符串
*/
public String signature;
}
|
C# | UTF-8 | 48,288 | 2.71875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PDP1
{
class Diagnostics
{
int goodTests;
int badTests;
Cpu cpu;
String results;
public Diagnostics()
{
cpu = new Cpu();
cpu.powerOn();
}
private void info(String msg)
{
results += "Info: " + msg + "\r\n";
}
private void good(String msg)
{
results += "Good: " + msg + "\r\n";
goodTests++;
}
private void bad(String msg)
{
results += "Bad: " + msg + "\r\n";
badTests++;
}
private void lacTests()
{
results += "lac tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0;
cpu.Memory[0x000] = 0x10100;
cpu.Memory[0x100] = 0x12345;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after lac");
else bad("PC not incremented by 1 after lac");
if (cpu.Ac == 0x12345) good("AC had correct value after lac");
else bad("AC did not have correct value after lac");
}
private void dacTests()
{
results += "\r\ndac tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x29327;
cpu.Memory[0x000] = 0x14105;
cpu.Memory[0x105] = 0x12345;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after dac");
else bad("PC not incremented by 1 after dac");
if (cpu.Ac == 0x29327) good("AC was not modified by dac");
else bad("AC was modified by dac");
if (cpu.Memory[0x105] == 0x29327) good("Memory had correct value after dac");
else bad("Memory did not have correct value after dac");
}
private void dapTests()
{
results += "\r\ndap tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x49285;
cpu.Memory[0x000] = 0x16106;
cpu.Memory[0x106] = 0x12456;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after dap");
else bad("PC not incremented by 1 after dap");
if (cpu.Ac == 0x49285) good("AC was not modified by dap");
else bad("AC was modified by dap");
if (cpu.Memory[0x106] == 0x12285) good("Memory had correct value after dap");
else bad("Memory did not have correct value after dap");
}
private void dipTests()
{
results += "\r\ndip tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x32103;
cpu.Memory[0x000] = 0x18107;
cpu.Memory[0x107] = 0x12456;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after dip");
else bad("PC not incremented by 1 after dip");
if (cpu.Ac == 0x32103) good("AC was not modified by dip");
else bad("AC was modified by dip");
if (cpu.Memory[0x107] == 0x32456) good("Memory had correct value after dip");
else bad("Memory did not have correct value after dip");
}
private void lioTests()
{
results += "\r\nlio tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x54321;
cpu.Io = 0;
cpu.Memory[0x000] = 0x12108;
cpu.Memory[0x108] = 0x24680;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after lio");
else bad("PC not incremented by 1 after lio");
if (cpu.Ac == 0x54321) good("AC was not modified by lio");
else bad("AC was modified by lio");
if (cpu.Io == 0x24680) good("IO was correctly modified by lio");
else bad("IO was not correctly modified by lio");
if (cpu.Memory[0x108] == 0x24680) good("Memory was not modified by lio");
else bad("Memory was modified by lio");
}
private void dioTests()
{
results += "\r\ndio tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x54321;
cpu.Io = 0x16420;
cpu.Memory[0x000] = 0x1a109;
cpu.Memory[0x109] = 0x24680;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after dio");
else bad("PC not incremented by 1 after dio");
if (cpu.Ac == 0x54321) good("AC was not modified by dio");
else bad("AC was modified by dio");
if (cpu.Io == 0x16420) good("IO was not modified by dio");
else bad("IO was modified by dio");
if (cpu.Memory[0x109] == 0x16420) good("Memory was correctly modified by dio");
else bad("Memory was not correctly modified by dio");
}
private void dzmTests()
{
results += "\r\ndzm tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x54329;
cpu.Io = 0x98642;
cpu.Memory[0x000] = 0x1c10a;
cpu.Memory[0x10a] = 0x24680;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after dzm");
else bad("PC not incremented by 1 after dzm");
if (cpu.Ac == 0x54329) good("AC was not modified by dzm");
else bad("AC was modified by dzm");
if (cpu.Memory[0x10a] == 0x00000) good("Memory was set to 0 by dzm");
else bad("Memory was not set to 0 by dzm");
}
private void jmpTests()
{
results += "\r\njmp tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x54329;
cpu.Io = 0x98642;
cpu.Memory[0x000] = 0x3010b;
cpu.Memory[0x10a] = 0x24680;
cpu.cycle();
if (cpu.Pc == 0x10b) good("PC was correctly set by jmp");
else bad("PC was not correctly set by jmp");
if (cpu.Ac == 0x54329) good("AC was not modified by jmp");
else bad("AC was modified by jmp");
}
private void jspTests()
{
results += "\r\njsp tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x54329;
cpu.Pc = 0x123;
cpu.Memory[0x123] = 0x3210c;
cpu.cycle();
if (cpu.Pc == 0x10c) good("PC was correctly set by jsp");
else bad("PC was not correctly set by jsp");
if (cpu.Ac == 0x00124) good("AC address was properly set by jsp");
else bad("AC address was not properly set by jsp");
cpu.Memory[0x10c] = 0x32200;
cpu.Overflow = true;
cpu.cycle();
if (cpu.Ac == 0x2010d) good("AC overflow was properly set by jsp");
else bad("AC overflow was not properly set by jsp");
cpu.Memory[0x200] = 0x32400;
cpu.Overflow = false;
cpu.Extend = true;
cpu.cycle();
if (cpu.Ac == 0x10201) good("AC extend was properly set by jsp");
else bad("AC extend was not properly set by jsp");
cpu.Memory[0xa400] = 0x32150;
cpu.Overflow = false;
cpu.Extend = false;
cpu.Epc = 0xa << 12;
cpu.cycle();
if (cpu.Ac == 0x0a401) good("AC extended PC was properly set by jsp");
else bad("AC extended PC was not properly set by jsp");
}
private void calTests()
{
results += "\r\ncal tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x54329;
cpu.Pc = 0x123;
cpu.Memory[0x123] = 0x0e10c;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 0x41) good("PC was correctly set by cal");
else bad("PC was not correctly set by cal");
if (cpu.Ac == 0x00124) good("AC address was properly set by cal");
else bad("AC address was not properly set by cal");
cpu.Pc = 0x10c;
cpu.Memory[0x10c] = 0x0e200;
cpu.Overflow = true;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x2010d) good("AC overflow was properly set by cal");
else bad("AC overflow was not properly set by cal");
cpu.Pc = 0x200;
cpu.Memory[0x200] = 0x0e400;
cpu.Overflow = false;
cpu.Extend = true;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x10201) good("AC extend was properly set by cal");
else bad("AC extend was not properly set by cal");
cpu.Pc = 0x400;
cpu.Memory[0xa400] = 0x0e150;
cpu.Overflow = false;
cpu.Extend = false;
cpu.Epc = 0xa << 12;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x0a401) good("AC extended PC was properly set by cal");
else bad("AC extended PC was not properly set by cal");
}
private void jdaTests()
{
results += "\r\njda tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x14329;
cpu.Pc = 0x123;
cpu.Memory[0x123] = 0x0f10c;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 0x10d) good("PC was correctly set by jda");
else bad("PC was not correctly set by jda");
if (cpu.Ac == 0x00124) good("AC address was properly set by jda");
else bad("AC address was not properly set by jda");
if (cpu.Memory[0x10c] == 0x14329) good("Memory was properly set by jda");
else bad("Memory was not properly set by jda");
cpu.Memory[0x10d] = 0x0f200;
cpu.Overflow = true;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x2010e) good("AC overflow was properly set by jda");
else bad("AC overflow was not properly set by jda");
cpu.Memory[0x201] = 0x0f400;
cpu.Overflow = false;
cpu.Extend = true;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x10202) good("AC extend was properly set by jda");
else bad("AC extend was not properly set by jda");
cpu.Memory[0xa401] = 0x0f150;
cpu.Overflow = false;
cpu.Extend = false;
cpu.Epc = 0xa << 12;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x0a402) good("AC extended PC was properly set by jda");
else bad("AC extended PC was not properly set by jda");
}
private void sadTests()
{
results += "\r\nsad tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x0f10d;
cpu.Pc = 0;
cpu.Memory[0] = 0x28123;
cpu.Memory[0x123] = 0x0f10c;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 2) good("PC correctly incremented when values differ for sad");
else bad("PC not correctly incremented when values differ for sad");
if (cpu.Ac == 0x0f10d) good("AC was not touched by sad");
else bad("AC was touched by sad");
if (cpu.Memory[0x123] == 0x0f10c) good("Memory was not affected by sad");
else bad("Memory was affected by sad");
cpu.Ac = 0x32198;
cpu.Pc = 0;
cpu.Memory[0] = 0x28124;
cpu.Memory[0x124] = 0x32198;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC not incremented when values equal for sad");
else bad("PC was incremented when values equal for sad");
if (cpu.Ac == 0x32198) good("AC was not touched by sad");
else bad("AC was touched by sad");
if (cpu.Memory[0x124] == 0x32198) good("Memory was not affected by sad");
else bad("Memory was affected by sad");
}
private void sasTests()
{
results += "\r\nsas tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x0f10d;
cpu.Pc = 0;
cpu.Memory[0] = 0x2a123;
cpu.Memory[0x123] = 0x0f10c;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC not incremented when values differ for sas");
else bad("PC was incremented when values differ for sas");
if (cpu.Ac == 0x0f10d) good("AC was not touched by sas");
else bad("AC was touched by sas");
if (cpu.Memory[0x123] == 0x0f10c) good("Memory was not affected by sas");
else bad("Memory was affected by sas");
cpu.Ac = 0x32198;
cpu.Pc = 0;
cpu.Memory[0] = 0x2a124;
cpu.Memory[0x124] = 0x32198;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 2) good("PC was incremented when values equal for sas");
else bad("PC was not incremented when values equal for sas");
if (cpu.Ac == 0x32198) good("AC was not touched by sas");
else bad("AC was touched by sas");
if (cpu.Memory[0x124] == 0x32198) good("Memory was not affected by sas");
else bad("Memory was affected by sas");
}
private void excTests()
{
results += "\r\nexc tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x0;
cpu.Pc = 0;
cpu.Memory[0] = 0x08115;
cpu.Memory[0x115] = 0x10125;
cpu.Memory[0x125] = 0x13579;
cpu.cycle();
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented correctly by exc");
else bad("PC was not incremented correctly by exc");
if (cpu.Ac == 0x13579) good("lac properly executed by exc");
else bad("lac not properly executed by exc");
cpu.Pc = 0;
cpu.Memory[0] = 0x08113;
cpu.Memory[0x113] = 0x08213;
cpu.Memory[0x213] = 0x08313;
cpu.Memory[0x313] = 0x08413;
cpu.Memory[0x413] = 0x10125;
cpu.Memory[0x125] = 0x35791;
cpu.cycle();
cpu.cycle();
cpu.cycle();
cpu.cycle();
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented correctly by 4 nested excs");
else bad("PC was not incremented correctly by 4 nested excs");
if (cpu.Ac == 0x35791) good("lac properly executed by 4 nested excs");
else bad("lac not properly executed by 4 nested excs");
}
private void iorTests()
{
results += "\r\nior tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0xc;
cpu.Pc = 0;
cpu.Memory[0] = 0x04234;
cpu.Memory[0x234] = 0xa;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented correctly by ior");
else bad("PC was not incremented correctly by ior");
if (cpu.Ac == 0xe) good("ior worked correctly");
else bad("ior did not work correctly");
if (cpu.Memory[0x234] == 0xa) good("Memory was not modified by ior");
else bad("Memory was modified by ior");
}
private void xorTests()
{
results += "\r\nxor tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0xa;
cpu.Pc = 0;
cpu.Memory[0] = 0x06237;
cpu.Memory[0x237] = 0xc;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented correctly by xor");
else bad("PC was not incremented correctly by xor");
if (cpu.Ac == 0x6) good("xor worked correctly");
else bad("xor did not work correctly");
if (cpu.Memory[0x237] == 0xc) good("Memory was not modified by xor");
else bad("Memory was modified by xor");
}
private void andTests()
{
results += "\r\nand tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0xa;
cpu.Pc = 0;
cpu.Memory[0] = 0x02239;
cpu.Memory[0x239] = 0xc;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented correctly by and");
else bad("PC was not incremented correctly by and");
if (cpu.Ac == 0x8) good("and worked correctly");
else bad("and did not work correctly");
if (cpu.Memory[0x239] == 0xc) good("Memory was not modified by and");
else bad("Memory was modified by and");
}
private void ispTests()
{
results += "\r\nisp tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0;
cpu.Pc = 0;
cpu.Memory[0] = 0x26165;
cpu.Memory[0x165] = 0x3fffd;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("Skip did not occur on negative value after isp");
else bad("Skip occurred on negative value after isp");
if (cpu.Ac == 0x3fffe) good("isp correctly incremented -2");
else bad("isp did not correctly increment -2");
if (cpu.Memory[0x165] == 0x3fffe) good("Memory was updated by isp");
else bad("Memory was not updated by isp");
cpu.Memory[1] = 0x26166;
cpu.Memory[0x166] = 0x3fffe;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 3) good("Skip occurred incrementing -1 on isp");
else bad("Skip did not occur incrementing -1 on isp");
if (cpu.Ac == 0x00000) good("isp correctly incremented -1 to +0");
else bad("isp did not correctly increment -1 to +0");
if (cpu.Memory[0x166] == 0x00000) good("Memory was updated by isp");
else bad("Memory was not updated by isp");
cpu.Memory[3] = 0x26167;
cpu.Memory[0x167] = 123;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 5) good("Skip occurred incrementing +123 on isp");
else bad("Skip did not occur incrementing +123 on isp");
if (cpu.Ac == 124) good("isp correctly incremented +123");
else bad("isp did not correctly increment +123");
if (cpu.Memory[0x167] == 124) good("Memory was updated by isp");
else bad("Memory was not updated by isp");
}
private void idxTests()
{
results += "\r\nidx tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0;
cpu.Pc = 0;
cpu.Memory[0] = 0x24165;
cpu.Memory[0x165] = 0x3fffd;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented correctly on idx");
else bad("PC not incremented correctly on idx");
if (cpu.Ac == 0x3fffe) good("idx correctly incremented -2");
else bad("idx did not correctly increment -2");
if (cpu.Memory[0x165] == 0x3fffe) good("Memory was updated by idx");
else bad("Memory was not updated by idx");
cpu.Memory[1] = 0x24166;
cpu.Memory[0x166] = 0x3fffe;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 2) good("PC incremented correctly on idx");
else bad("PC not incremented correctly on idx");
if (cpu.Ac == 0x00000) good("idx correctly incremented -1 to +0");
else bad("idx did not correctly increment -1 to +0");
if (cpu.Memory[0x166] == 0x00000) good("Memory was updated by idx");
else bad("Memory was not updated by idx");
cpu.Memory[2] = 0x24167;
cpu.Memory[0x167] = 123;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 3) good("PC incremented correctly on idx");
else bad("PC not incremented correctly on idx");
if (cpu.Ac == 124) good("idx correctly incremented +123");
else bad("idx did not correctly increment +123");
if (cpu.Memory[0x167] == 124) good("Memory was updated by idx");
else bad("Memory was not updated by idx");
}
private void addTests()
{
results += "\r\nadd tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00004;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x00008;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after add");
else bad("PC not incremented by 1 after add");
if (cpu.Ac == 0x0000c) good("add +4 and +8 produced +12");
else bad("add +4 and +8 did not produce +12");
if (cpu.Overflow == false) good("add +4 and +8 did not produce overflow");
else bad("add +4 and +8 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00008;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x3fffb;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x00004) good("add +8 and -4 produced +4");
else bad("add +8 and -4 did not produce +4");
if (cpu.Overflow == false) good("add +8 and -4 did not produce overflow");
else bad("add +8 and -4 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00004;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x3fff7;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3fffb) good("add +4 and -8 produced -4");
else bad("add +4 and -8 did not produce -4");
if (cpu.Overflow == false) good("add +4 and -8 did not produce overflow");
else bad("add +r and -8 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fffb;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x00008;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x00004) good("add -4 and +8 produced +4");
else bad("add -4 and +8 did not produce +4");
if (cpu.Overflow == false) good("add -4 and +8 did not produce overflow");
else bad("add -4 and +8 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fff7;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x00004;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3fffb) good("add -8 and +4 produced -4");
else bad("add -8 and +4 did not produce -4");
if (cpu.Overflow == false) good("add -8 and +4 did not produce overflow");
else bad("add -8 and +4 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fff7;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x3fffb;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3fff3) good("add -8 and -4 produced -12");
else bad("add -8 and -4 did not produce -12");
if (cpu.Overflow == false) good("add -8 and -4 did not produce overflow");
else bad("add -8 and -4 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fffb;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x3fff7;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3fff3) good("add -4 and -8 produced -12");
else bad("add -4 and -8 did not produce -12");
if (cpu.Overflow == false) good("add -4 and -8 did not produce overflow");
else bad("add -4 and -8 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fffb;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x00004;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x00000) good("add -4 and +4 produced +0");
else bad("add -4 and +4 did not produce +0");
if (cpu.Overflow == false) good("add -4 and +4 did not produce overflow");
else bad("add -4 and +4 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x1ffff;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x00001;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x20000) good("add +131071 and +1 produced -131071");
else bad("add +131071 and +1 did not produce -131071");
if (cpu.Overflow == true) good("add +131071 and +1 produced overflow");
else bad("add +131071 and +1 did not produce overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x20000;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x3fffe;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x1ffff) good("add -131071 and -1 produced +131071");
else bad("add -131071 and -1 did not produce +131071");
if (cpu.Overflow == true) good("add -131071 and -1 produced overflow");
else bad("add -131071 and -1 did not produce overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00000;
cpu.Memory[0x000] = 0x2010a;
cpu.Memory[0x10a] = 0x3ffff;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x00000) good("add +0 and -0 produced +0");
else bad("add +0 and -0 did not produce +0");
if (cpu.Overflow == false) good("add +0 and -0 did not produce overflow");
else bad("add +0 and -0 produced overflow");
}
private void subTests()
{
results += "\r\nsub tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00004;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x00008;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after sub");
else bad("PC not incremented by 1 after sub");
if (cpu.Ac == 0x3fffb) good("sub +4 and +8 produced -4");
else bad("sub +4 and +8 did not produce -4");
if (cpu.Overflow == false) good("sub +4 and +8 did not produce overflow");
else bad("sub +4 and +8 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00008;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x3fffb;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x0000c) good("sub +8 and -4 produced +12");
else bad("sub +8 and -4 did not produce +12");
if (cpu.Overflow == false) good("sub +8 and -4 did not produce overflow");
else bad("sub +8 and -4 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00004;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x3fff7;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x0000c) good("sub +4 and -8 produced +12");
else bad("sub +4 and -8 did not produce +12");
if (cpu.Overflow == false) good("sub +4 and -8 did not produce overflow");
else bad("sub +r and -8 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fffb;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x00008;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3fff3) good("sub -4 and +8 produced -12");
else bad("sub -4 and +8 did not produce -12");
if (cpu.Overflow == false) good("sub -4 and +8 did not produce overflow");
else bad("sub -4 and +8 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fff7;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x00004;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3fff3) good("sub -8 and +4 produced -12");
else bad("sub -8 and +4 did not produce -12");
if (cpu.Overflow == false) good("sub -8 and +4 did not produce overflow");
else bad("sub -8 and +4 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fff7;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x3fffb;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3fffb) good("sub -8 and -4 produced -4");
else bad("sub -8 and -4 did not produce -4");
if (cpu.Overflow == false) good("sub -8 and -4 did not produce overflow");
else bad("sub -8 and -4 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fffb;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x3fff7;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x00004) good("sub -4 and -8 produced +4");
else bad("sub -4 and -8 did not produce +4");
if (cpu.Overflow == false) good("sub -4 and -8 did not produce overflow");
else bad("sub -4 and -8 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x3fffb;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x3fffb;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x00000) good("sub -4 and -4 produced +0");
else bad("sub -4 and -4 did not produce +0");
if (cpu.Overflow == false) good("sub -4 and -4 did not produce overflow");
else bad("sub -4 and -4 produced overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x1ffff;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x3fffe;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x20000) good("sub +131071 and -1 produced -131071");
else bad("sub +131071 and -1 did not produce -131071");
if (cpu.Overflow == true) good("sub +131071 and -1 produced overflow");
else bad("sub +131071 and -1 did not produce overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x20000;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x00001;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x1ffff) good("sub -131071 and +1 produced +131071");
else bad("sub -131071 and +1 did not produce +131071");
if (cpu.Overflow == true) good("sub -131071 and +1 produced overflow");
else bad("sub -131071 and +1 did not produce overflow");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00000;
cpu.Memory[0x000] = 0x2210a;
cpu.Memory[0x10a] = 0x3ffff;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3ffff) good("sub +0 and -0 produced -0");
else bad("sub +0 and -0 did not produce -0");
if (cpu.Overflow == false) good("sub +0 and -0 did not produce overflow");
else bad("sub +0 and -0 produced overflow");
}
private void mulTests()
{
results += "\r\nmul tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x10000;
cpu.Memory[0x000] = 0x2c10a;
cpu.Memory[0x10a] = 0x10000;
cpu.cycle();
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after mul");
else bad("PC not incremented by 1 after mul");
if (cpu.Ac == 0x08000) good("mul +.5 and +.5 produced +.25");
else bad("mul +.5 and +.5 did not produce +.25");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x10000;
cpu.Memory[0x000] = 0x2c10a;
cpu.Memory[0x10a] = 0x08000;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x04000) good("mul +.5 and +.25 produced +.125");
else bad("mul +.5 and +.25 did not produce +.125");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x10000;
cpu.Memory[0x000] = 0x2c10a;
cpu.Memory[0x10a] = 0x2ffff;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x37fff) good("mul +.5 and -.5 produced -.25");
else bad("mul +.5 and -.5 did not produce -.25");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x2ffff;
cpu.Memory[0x000] = 0x2c10a;
cpu.Memory[0x10a] = 0x10000;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x37fff) good("mul -.5 and +.5 produced -.25");
else bad("mul -.5 and +.5 did not produce -.25");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x2ffff;
cpu.Memory[0x000] = 0x2c10a;
cpu.Memory[0x10a] = 0x2ffff;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x08000) good("mul -.5 and -.5 produced +.25");
else bad("mul -.5 and -.5 did not produce +.25");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00004;
cpu.Memory[0x000] = 0x2c10a;
cpu.Memory[0x10a] = 0x00003;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x00000) good("integer mul +3 and +4 produced +0 in AC");
else bad("integer mul +3 and +4 did not produce +0 in AC");
if (cpu.Io == 0x00018) good("integer mul +3 and +4 produced +12 in IO");
else bad("integer mul +3 and +4 did not produce +12 in IO");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00004;
cpu.Memory[0x000] = 0x2c10a;
cpu.Memory[0x10a] = 0x3fffc;
cpu.cycle();
cpu.cycle();
if (cpu.Ac == 0x3ffff) good("integer mul +4 and -3 produced -0 in AC");
else bad("integer mul +4 and -3 did not produce +0 in AC");
if (cpu.Io == 0x3ffe7) good("integer mul +4 and -3 produced -12 in IO");
else bad("integer mul +4 and -3 did not produce -12 in IO");
}
private void lawTests()
{
results += "\r\nlaw tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x10000;
cpu.Memory[0x000] = 0x3810a;
cpu.Memory[0x10a] = 0x00000;
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after law");
else bad("PC not incremented by 1 after law");
if (cpu.Ac == 0x0010a) good("AC had 0x0010a after law 10a");
else bad("AC did not have 0x0010a after law 10a");
cpu.Memory[0x001] = 0x39456;
cpu.cycle();
if (cpu.Ac == 0x3fba9) good("AC had -0x456 after law -10a");
else bad("AC did not have -0x456 after law -10a");
}
private void shiftGroupTests()
{
results += "\r\nshift group tests\r\n";
info("rar");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x34567;
cpu.Memory[0x000] = 0x3720f;
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after rar");
else bad("PC not incremented by 1 after rar");
if (cpu.Ac == 0x1f456) good("AC had correct value after shifting 4 places with rar");
else bad("AC did not have correct value after shifting 4 places with rar");
info("ral");
cpu.Ac = 0x34567;
cpu.Memory[0x001] = 0x3620f;
cpu.cycle();
if (cpu.Pc == 2) good("PC incremented by 1 after ral");
else bad("PC not incremented by 1 after ral");
if (cpu.Ac == 0x0567d) good("AC had correct value after shifting 4 places with ral");
else bad("AC did not have correct value after shifting 4 places with ral");
info("sar");
cpu.Ac = 0x34567;
cpu.Memory[0x002] = 0x37a0f;
cpu.cycle();
if (cpu.Pc == 3) good("PC incremented by 1 after sar");
else bad("PC not incremented by 1 after sar");
if (cpu.Ac == 0x3f456) good("AC had correct value after shifting 4 places with sar");
else bad("AC did not have correct value after shifting 4 places with sar");
info("sal");
cpu.Ac = 0x34567;
cpu.Memory[0x003] = 0x36a0f;
cpu.cycle();
if (cpu.Pc == 4) good("PC incremented by 1 after sal");
else bad("PC not incremented by 1 after sal");
if (cpu.Ac == 0x2567f) good("AC had correct value after shifting 4 places with sal");
else bad("AC did not have correct value after shifting 4 places with sal");
info("rir");
cpu.reset();
cpu.Stopped = false;
cpu.Io = 0x34567;
cpu.Memory[0x000] = 0x3740f;
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after rir");
else bad("PC not incremented by 1 after rir");
if (cpu.Io == 0x1f456) good("IO had correct value after shifting 4 places with rir");
else bad("IO did not have correct value after shifting 4 places with rir");
info("ril");
cpu.Io = 0x34567;
cpu.Memory[0x001] = 0x3640f;
cpu.cycle();
if (cpu.Pc == 2) good("PC incremented by 1 after ril");
else bad("PC not incremented by 1 after ril");
if (cpu.Io == 0x0567d) good("IO had correct value after shifting 4 places with ril");
else bad("IO did not have correct value after shifting 4 places with ril");
info("sir");
cpu.Io = 0x34567;
cpu.Memory[0x002] = 0x37c0f;
cpu.cycle();
if (cpu.Pc == 3) good("PC incremented by 1 after sir");
else bad("PC not incremented by 1 after sir");
if (cpu.Io == 0x3f456) good("IO had correct value after shifting 4 places with sir");
else bad("IO did not have correct value after shifting 4 places with sir");
info("sil");
cpu.Io = 0x34567;
cpu.Memory[0x003] = 0x36c0f;
cpu.cycle();
if (cpu.Pc == 4) good("PC incremented by 1 after sil");
else bad("PC not incremented by 1 after sil");
if (cpu.Io == 0x2567f) good("IO had correct value after shifting 4 places with sil");
else bad("IO did not have correct value after shifting 4 places with sil");
info("rcr");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x34567;
cpu.Io = 0x29012;
cpu.Memory[0x000] = 0x3760f;
cpu.cycle();
if (cpu.Pc == 1) good("PC incremented by 1 after rcr");
else bad("PC not incremented by 1 after rcr");
if (cpu.Ac == 0x0b456) good("AC had correct value after shifting 4 places with rcr");
else bad("AC did not have correct value after shifting 4 places with rcr");
if (cpu.Io == 0x1e901) good("IO had correct value after shifting 4 places with rcr");
else bad("IO did not have correct value after shifting 4 places with rcr");
info("rcl");
cpu.Ac = 0x34567;
cpu.Io = 0x29012;
cpu.Memory[0x001] = 0x3660f;
cpu.cycle();
if (cpu.Pc == 2) good("PC incremented by 1 after rcl");
else bad("PC not incremented by 1 after rcl");
if (cpu.Ac == 0x0567a) good("AC had correct value after shifting 4 places with rcl");
else bad("AC did not have correct value after shifting 4 places with rcl");
if (cpu.Io == 0x1012d) good("IO had correct value after shifting 4 places with rcl");
else bad("IO did not have correct value after shifting 4 places with rcl");
info("scr");
cpu.Ac = 0x34567;
cpu.Io = 0x29012;
cpu.Memory[0x002] = 0x37e0f;
cpu.cycle();
if (cpu.Pc == 3) good("PC incremented by 1 after scr");
else bad("PC not incremented by 1 after scr");
if (cpu.Ac == 0x3f456) good("AC had correct value after shifting 4 places with scr");
else bad("AC did not have correct value after shifting 4 places with scr");
if (cpu.Io == 0x1e901) good("IO had correct value after shifting 4 places with scr");
else bad("IO did not have correct value after shifting 4 places with scr");
info("scl");
cpu.Ac = 0x34567;
cpu.Io = 0x29012;
cpu.Memory[0x003] = 0x36e0f;
cpu.cycle();
if (cpu.Pc == 4) good("PC incremented by 1 after scl");
else bad("PC not incremented by 1 after scl");
if (cpu.Ac == 0x2567a) good("AC had correct value after shifting 4 places with scl");
else bad("AC did not have correct value after shifting 4 places with scl");
if (cpu.Io == 0x1012f) good("IO had correct value after shifting 4 places with scl");
else bad("IO did not have correct value after shifting 4 places with scl");
}
private void skipGroupTests()
{
results += "\r\nskip group tests\r\n";
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00000;
cpu.Memory[0x000] = 0x34040;
cpu.cycle();
if (cpu.Pc == 2) good("PC correctly skipped when ac was zero on sza");
else bad("PC did not correctly skip when ac was zero on sza");
cpu.Ac = 0x00002;
cpu.Memory[0x002] = 0x34040;
cpu.cycle();
if (cpu.Pc == 3) good("PC did not skip on nonzero ac on sza");
else bad("PC skipped on nonzero ac on sza");
cpu.Ac = 0x00002;
cpu.Memory[0x003] = 0x34080;
cpu.cycle();
if (cpu.Pc == 5) good("PC skipped on positive number in ac on spa");
else bad("PC did not skip on positive number in ac on spa");
cpu.Ac = 0x00000;
cpu.Memory[0x005] = 0x34080;
cpu.cycle();
if (cpu.Pc == 7) good("PC skipped on positive zero in ac on spa");
else bad("PC did not skip on positive zero in ac on spa");
cpu.Ac = 0x3ffff;
cpu.Memory[0x007] = 0x34080;
cpu.cycle();
if (cpu.Pc == 8) good("PC did not skip on negative zero in ac on spa");
else bad("PC skipped on negative zero in ac on spa");
cpu.Ac = 0x3fffe;
cpu.Memory[0x008] = 0x34080;
cpu.cycle();
if (cpu.Pc == 9) good("PC did not skip on negative number in ac on spa");
else bad("PC skipped on negative number in ac on spa");
cpu.Ac = 0x00002;
cpu.Memory[0x009] = 0x34100;
cpu.cycle();
if (cpu.Pc == 0x00a) good("PC did not skip on positive number in ac on sma");
else bad("PC skipped on positive number in ac on sma");
cpu.Ac = 0x00000;
cpu.Memory[0x00a] = 0x34100;
cpu.cycle();
if (cpu.Pc == 0x00b) good("PC did not skip on positive zero in ac on sma");
else bad("PC skipped on positive zero in ac on sma");
cpu.Ac = 0x3ffff;
cpu.Memory[0x00b] = 0x34100;
cpu.cycle();
if (cpu.Pc == 0x00d) good("PC skipped on negative zero in ac on sma");
else bad("PC did not skipp on negative zero in ac on sma");
cpu.Ac = 0x3fffe;
cpu.Memory[0x00d] = 0x34100;
cpu.cycle();
if (cpu.Pc == 0x00f) good("PC skipped on negative number in ac on sma");
else bad("PC did not skipp on negative number in ac on sma");
cpu.reset();
cpu.Stopped = false;
cpu.Ac = 0x00000;
cpu.Overflow = false;
cpu.Memory[0x000] = 0x34200;
cpu.cycle();
if (cpu.Pc == 2) good("PC skipped when no overflow on szo");
else bad("PC did not skip when no overflow on szo");
cpu.Overflow = true;
cpu.Memory[0x002] = 0x34200;
cpu.cycle();
if (cpu.Pc == 3) good("PC did not skip when overflow on szo");
else bad("PC skipped when overflow on szo");
cpu.Overflow = false;
cpu.Memory[0x003] = 0x35200;
cpu.cycle();
if (cpu.Pc == 0x004) good("PC did not skipped no overflow on inverse szo");
else bad("PC skipped when no overflow on inverse szo");
cpu.Overflow = true;
cpu.Memory[0x004] = 0x35200;
cpu.cycle();
if (cpu.Pc == 0x006) good("PC skipped when overflow on inverse szo");
else bad("PC did not skip when overflow on inverse szo");
cpu.reset();
cpu.Stopped = false;
cpu.Pc = 0x003;
cpu.Ac = 0x3ffff;
cpu.Memory[0x003] = 0x34400;
cpu.cycle();
if (cpu.Pc == 5) good("PC skipped on positive number in io on spi");
else bad("PC did not skip on positive number in io on spi");
cpu.Io = 0x00000;
cpu.Memory[0x005] = 0x34400;
cpu.cycle();
if (cpu.Pc == 7) good("PC skipped on positive zero in io on spi");
else bad("PC did not skip on positive zero in io on spi");
cpu.Io = 0x3ffff;
cpu.Ac = 0x00000;
cpu.Memory[0x007] = 0x34400;
cpu.cycle();
if (cpu.Pc == 8) good("PC did not skip on negative zero in io on spi");
else bad("PC skipped on negative zero in io on spi");
cpu.Io = 0x3fffe;
cpu.Memory[0x008] = 0x34400;
cpu.cycle();
if (cpu.Pc == 9) good("PC did not skip on negative number in io on spi");
else bad("PC skipped on negative number in io on spi");
}
public String run()
{
goodTests = 0;
badTests = 0;
results = "";
lacTests();
dacTests();
dapTests();
dipTests();
lioTests();
dioTests();
dzmTests();
jmpTests();
jspTests();
calTests();
jdaTests();
sadTests();
sasTests();
excTests();
iorTests();
xorTests();
andTests();
ispTests();
idxTests();
addTests();
subTests();
mulTests();
lawTests();
shiftGroupTests();
skipGroupTests();
results += "\r\n";
results += "Good tests: " + goodTests.ToString() + "\r\n";
results += "Bad tests : " + badTests.ToString() + "\r\n";
return results;
}
}
}
|
Java | UTF-8 | 1,631 | 2.71875 | 3 | [] | no_license | package monopoly;
import model.Board;
import model.Dice;
import monopoly.Monopoly;
import monopoly.MonopolyProperties;
import org.junit.Before;
import org.junit.Test;
import transaction.Bank;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
public class MonopolyTest {
Monopoly monopoly;
Board board;
Dice dice;
Bank bank;
MonopolyProperties monopolyProperties;
@Before
public void setUp() {
board = mock(Board.class);
dice = mock(Dice.class);
bank = mock(Bank.class);
monopolyProperties = mock(MonopolyProperties.class);
when(monopolyProperties.getProperty("player.worth")).thenReturn("1000");
monopoly = new Monopoly(board, dice, bank, monopolyProperties);
}
@Test
public void testShouldTakeInputsAndDelegateInitialization() throws IOException {
String cellPositionsAndTypes = "";
String diceOutput = "";
String numberOfPlayers = "2";
monopoly.init(numberOfPlayers, cellPositionsAndTypes, diceOutput);
verify(board, times(1)).init(cellPositionsAndTypes, monopolyProperties);
verify(dice, times(1)).init(diceOutput);
}
@Test
public void testShouldInitPlayers() throws IOException {
String numberOfPlayers = "2";
String diceOutput = "";
String cellPositionAndTypes = "";
monopoly.init(numberOfPlayers, cellPositionAndTypes, diceOutput);
assertEquals("Player-1", monopoly.getPlayer(0).getName());
assertEquals("Player-2", monopoly.getPlayer(1).getName());
}
}
|
Markdown | UTF-8 | 1,032 | 3.140625 | 3 | [] | no_license | Exercício 4
Para explorar os conceitos vistos na Aula 04, iremos utilizar a stack React + Redux para uma aplicação que possua uma listagem de filmes favoritos. A ideia é que, utilizando o projeto da aula 04, possamos escolher quais os nossos filmes favoritos a partir da listagem e mostrá-los em uma tela, tudo utilizando a store do Redux. Para isso, siga os seguintes passos: Passo 1 Utilizando o exercício da aula 03 para listagem de filmes, instale no projeto os seguintes pacotes:
● npm i -S redux;
● npm i -S react-redux.
Passo 2 Utilizando o exemplo do Code sandbox visto na Aula 04, crie a estrutura para utilização do Redux. Ao invés de utilizar o conceito de “contador”, iremos utilizar o conceito de “favorites”.
● Crie uma action que receba o objeto do filme a ser “favoritado”;
● Crie um reducer para modificar o estado global;
Passo 3 Crie uma rota “/favorites” utilizando o react router conforme visto na aula 02. Em seguida, exiba os filmes marcados como favoritos na listagem. |
Java | UTF-8 | 434 | 2.734375 | 3 | [] | no_license |
package log4jpackage;
import org.apache.log4j.Logger;
public class log4jclass {
static Logger log = Logger.getLogger(log4jclass.class);
public static void main(String[] args) {
log.debug("HERE IS AN DEBUG WARNING");
log.info("THERE IS A INFO MESSAGE");
log.warn("OOPS! THIS IS AN WARN MESSAGE");
log.error("DANGEROUS! ERROR!");
log.fatal("SO DANGEROUS! FATAL ERROR!");
}
}
|
C++ | UTF-8 | 822 | 3.0625 | 3 | [] | no_license | #include "EntityManager.h"
EntityManager::EntityManager() {
}
EntityManager::~EntityManager() {
}
Entity* EntityManager::createEntity()
{
uint entityId = 0;
//check if there is a re-usable id
if (m_availableIds.empty()) {
entityId = ++m_entityId;
}
else {
entityId = m_availableIds.top();
m_availableIds.pop();
}
Entity* entity = new Entity(entityId);
m_entityMap.emplace(entityId, entity);
return entity;
}
void EntityManager::deleteEntity(Entity*& e) {
//set the entity's components to false so they don't get processed
for (auto component : e->getComponents())
{
component.second->setActive(false);
}
//add the entities id to the stack of available ids
m_availableIds.push(e->getId());
//remove the entity from the map and delete it
m_entityMap.erase(e->getId());
delete e;
}
|
Python | UTF-8 | 703 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | import re
from glob import glob
from configparser import ConfigParser
for path in glob('**/.git/config', recursive=True):
config = ConfigParser()
config.read(path)
for section in config.sections():
if not section.startswith('remote '):
continue
match = re.match(r'https://github.com/(.+?)/(.+)', config[section]['url'])
if not match:
continue
repo = match[2]
if not repo.endswith('.git'):
repo += '.git'
config[section]['url'] = f'git@github.com:{match[1]}/{repo}'
with open(path + '.bk', 'w') as fbk, open(path, 'r') as f:
fbk.write(f.read())
with open(path, 'w') as f:
config.write(f)
|
Java | UTF-8 | 684 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | import com.example.broaddemo.NetworkStatus;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int status=NetworkStatus.getNetworkInfo(context);
switch(status)
{
case 1:Toast.makeText(context, "MOB INTERNET", Toast.LENGTH_LONG).show();
break;
case 2:Toast.makeText(context, "WI-FI", Toast.LENGTH_LONG).show();
break;
default:Toast.makeText(context, "NO CONNECTIVITY", Toast.LENGTH_LONG).show();
}
}
}
|
Rust | UTF-8 | 2,382 | 3.515625 | 4 | [
"Apache-2.0"
] | permissive | //! the module includes everything related to resource metadata
use chrono::{DateTime, Utc};
/// The metadata information for the current resource
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Metadata {
version: u8,
created: DateTime<Utc>,
last_modified: Option<DateTime<Utc>>,
}
impl Metadata {
/// Creates a new metadata value
pub fn new(version: u8, created: DateTime<Utc>, last_modified: Option<DateTime<Utc>>) -> Self {
Metadata {
version,
created,
last_modified,
}
}
/// Creates metadata for a newly created resource
pub fn created_at(created: DateTime<Utc>) -> Self {
Metadata {
version: 1u8,
created,
last_modified: None,
}
}
/// Updates this metadata after an update
pub fn updated_at(self, last_modified: DateTime<Utc>) -> Self {
Metadata {
version: self.version + 1,
created: self.created,
last_modified: Some(last_modified),
}
}
/// The resource version
pub fn version(&self) -> u8 {
self.version
}
/// The resource creation timestamp
pub fn created(&self) -> &DateTime<Utc> {
&self.created
}
/// The resource last update timestamp
pub fn last_modified(&self) -> Option<&DateTime<Utc>> {
self.last_modified.as_ref()
}
}
impl Default for Metadata {
fn default() -> Self {
let now: DateTime<Utc> = Utc::now();
Metadata::created_at(now)
}
}
#[cfg(test)]
mod tests {
use super::*;
mod metadata {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn it_should_create_metadata() {
let now: DateTime<Utc> = Utc::now();
let metadata = Metadata::created_at(now);
assert_eq!(1, metadata.version());
assert_eq!(&now, metadata.created());
assert_eq!(None, metadata.last_modified());
}
#[test]
fn it_should_update_metadata() {
let now: DateTime<Utc> = Utc::now();
let metadata = Metadata::created_at(now).updated_at(now);
assert_eq!(2, metadata.version());
assert_eq!(&now, metadata.created());
assert_eq!(Some(&now), metadata.last_modified());
}
}
}
|
Markdown | UTF-8 | 3,537 | 3.25 | 3 | [] | no_license | # ReversiAI
### 1. Alpha Beta Pruning
The implementation of Alpha Beta Pruning that was devised for this project is more time efficient than the base MiniMax agent without losing out on the effect on gameplay. When both agents are setup to only search down to the same depth, the agent with Alpha Beta Pruning always completes it's moves quicker. This allows it to look down at further depths of the decision tree and preform better than the base minimax agent.
With the search depth set at 4 I found that the Alpha Beta Agent made its decisions for each move more than twice as fast as the base agent with an average decision time of 0.2 seconds while the base agent had an average of 0.56 seconds.
### 2. Beam Search
We implemented a Beam Search algorithm to try and increase speed of search. This allows us to increase depth or to use more intensive algorithms without sacrificing speed because we are trimming improbable routes. With just beam search, on every turn decision cycle, we found our algorithm to be significantly faster than it's counter part without beam search. However, with just beam search and none of our other enhancements we tend to lose more games. This is expected as beam search cuts branches by guessing and doesn't play perfectly.
Given two agents running the same depth here is the speed difference we see:
{'X': 17, 'O': 3, 'TIE': 0}
{'X': 143.83176200000003, 'O': 21.853547}
Note that we expect O to lose more because both agents search the same depth
### 3. Improved Hueristics
To implement a better heuristic than a simple greedy one, I looked into the most important aspects of any Reversi move. There are four aspects to think of for any given move that one should consider:
Coin Parity: This is the difference in the number of pieces that you and your opponent have on the board (basically the previously mentioned greedy heuristic).
Mobility: This prioritizes giving you a high number of moves, while limiting the numebr of moves your opponent has.
Corners: Self explanatory; this heuristic prioritizes getting control of the corners, as corner pieces are extremely valuable in a Reversi game.
Stability: The stability of a piece means how likely it is to be overturned in the next turn. It can be stable, semi-stable, or unstable.
I was able to get 3 of the 4 working within good time, as I was not able to find of a way to implement a stability check while keeping the agent fast. However, this does not matter too much as the combination of the other 3 factors make the overall MiniMax agent significantly more efficient. While it did not make the agent more time efficient, each heuristic seemed to help win more games.
From Most to Least impactful:
Corner Heuristic - On an average of 20 games, this beats the mobility heuristic and the coin parity heuristic 15-18 games
Mobility Heuristic - This flips back and forth with the coin parity heuristic, either winning by 3-4 or losing by 3-4, but it seems to be winning a small margin more
Coin Parity - The greedy heuristic means the least, as a highly greedy board state does not mean a stable one. This one loses most often to the Mobility Heuristic usually by 3-4, and the corner one usually 17-18 times out of 20.
A combination of the 3 wins against every other heuristic which is no surprise, as it just combines all previous ones. it wins 18-19 games against the mobility and coin parity heuristics, and wins 14-15 times versus the corner herustic, which just further enforces how important corners are in Reversi.
|
Java | UTF-8 | 1,610 | 2.875 | 3 | [] | no_license | package com.rohim.enumeration;
/**
* Created by Nurochim on 19/10/2016.
*/
public enum EnumInputService {
SpinnerInput("SI") {
@Override
public String toString() {
return ("Spinner");
}
},
TextShort("TS") {
@Override
public String toString() {
return ("Text Short");
}
},
TextLong("TL") {
@Override
public String toString() {
return ("TextLong");
}
},
Map("MP") {
@Override
public String toString() {
return ("Map");
}
},
TextAutomatic("TA") {
@Override
public String toString() {
return ("TextAutomatic");
}
};
private String val;
EnumInputService(String val) {
this.val = val;
}
public static EnumInputService valOf(String val) {
if (val.equals(EnumInputService.SpinnerInput)) {
return EnumInputService.SpinnerInput;
}else if (val.equals(EnumInputService.TextShort)) {
return EnumInputService.TextShort;
}else if (val.equals(EnumInputService.TextLong)) {
return EnumInputService.TextLong;
}else if (val.equals(EnumInputService.Map)) {
return EnumInputService.TextAutomatic;
}else if (val.equals(EnumInputService.TextAutomatic)) {
return EnumInputService.TextAutomatic;
}else {
return null;
}
}
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
}
|
JavaScript | UTF-8 | 1,088 | 4.03125 | 4 | [] | no_license | var todos = ["keep study"];
var input = prompt("What would you like to do?");
while (input !== "quit") {
if (input === "list") {
listToDo();
} else if (input === "new") {
newToDo();
} else if (input === "delete") {
deleteToDo();
} else {
console.log("Invalid input");
}
input = prompt("What would you like to do?");
}
console.log("You have quit the app.");
function listToDo() {
// forEach 有三个参数,element,index,array本身
todos.forEach(function(todo, i){
console.log(i + ": " + todo);
})
console.log("---");
}
function newToDo() {
input = prompt("Enter new a todo");
todos.push(input)
console.log("Added a new todo");
}
function deleteToDo() {
// ask for the index of todo to be deleted
input = prompt("Enter the index of todo needs to be deleted");
// delete the specific todo by splice()
// splice(index, numer) 有两个参数,index开始删除的位置,number要删除几个
todos.splice(input, 1);
console.log("Item " + input + " deleted");
} |
Java | UTF-8 | 10,606 | 1.96875 | 2 | [] | no_license | package com.spring.springcloudlibraryproduct.Controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spring.springcloudlibraryproduct.Service.EmpService;
import com.spring.springcloudlibraryproduct.Service.WebSocketSerivceImpl;
import com.spring.springcloudlibraryproduct.Service.noticeService;
import com.spring.springcloudlibraryproduct.Service.recService;
import com.spring.springcloudlibraryproduct.pojo.employee;
import com.spring.springcloudlibraryproduct.pojo.face;
import com.spring.springcloudlibraryproduct.pojo.notice;
import com.spring.springcloudlibraryproduct.pojo.records;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import javax.sound.midi.Soundbank;
import javax.websocket.OnClose;
import java.security.Principal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Controller
@RequestMapping("/websocket")
public class WebSocketController {
@Autowired
private com.spring.springcloudlibraryproduct.Service.recService recService;
@Autowired
private EmpService empService;
@Autowired //配置Spring Boot 自动配置消息模板对象
private SimpMessagingTemplate simpMessagingTemplate;
// concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketSerivceImpl对象
private static CopyOnWriteArraySet<Principal> principalSet = new CopyOnWriteArraySet<>();
@Autowired
private SimpUserRegistry simpUserRegistry;
private static ConcurrentHashMap<String,Object> sessionsSet = new ConcurrentHashMap<>();
private static String sessionid = null;
private static int onlineCount = 0;
public static ConcurrentHashMap<String, Object> getSessionsSet() {
return sessionsSet;
}
public static void setSessionsSet(ConcurrentHashMap<String, Object> sessionsSet) {
WebSocketController.sessionsSet = sessionsSet;
}
@Autowired
private noticeService noticeService;
public static String getSessionid() {
return sessionid;
}
public static synchronized void setSessionid(String sessionid) {
WebSocketController.sessionid = sessionid;
}
private static List<Object> userList = new ArrayList<>();
//发送页面
@GetMapping("/send")
public String send(){
return "html/send";
}
@GetMapping("/receive")
public String receive(){
return "html/receive";
}
@GetMapping("/sendUser")
public String sendUser(){
return "html/send-user";
}
@GetMapping("/receiveUser")
public String receiveUser(){
return "html/receive-user";
}
@GetMapping("/liaotian")
public String liaotian(){
return "html/liaotian";
}
// 定义消息请求路径
@MessageMapping("/send")
// 定义结果发送到特定路径
@SendTo("/sub/chat")
public synchronized Object sendMsg(Principal principal,String value){
JSONObject jsonObject = JSON.parseObject(value);
employee employeea = empService.getEmpByname(jsonObject.getString("userName"));
recService.addrecords(jsonObject.getString("userName"), jsonObject.getString("message"));
Map<String, Object> sendMap = new HashMap<>();
sendMap.put("emp", employeea);
/*String srcUser = principal.getName();*/
String message = /*jsonObject.getString("userName") + "曰: " + */jsonObject.getString("message");
sendMap.put("message", message);
return sendMap;
}
// 将消息发送给特定用户
@MessageMapping("/sendUser")
public synchronized void sendToUser(Principal principal, String body){
String srcUser = principal.getName();
String [] args = body.split(",");
String desUser = args[0];
System.out.println("desUser:"+desUser);
String message = "【" + srcUser + "】给你发来消息:" + args[1];
System.out.println(message);
// 发送到用户和监听地址
simpMessagingTemplate.convertAndSendToUser(desUser, "/queue/customer",message);
}
@MessageMapping("/connectToUser")
public synchronized void ConnectToUser(String value){
Map<String, Object> messageMap = new HashMap<>();
messageMap.put("sessionid", this.getSessionid());
String messageStr = JSON.toJSONString(messageMap);
System.out.println(messageStr);
simpMessagingTemplate.convertAndSendToUser(value,"/queue/cona",messageStr);
// END
}
/**
* 聊天记录
* @param value
* @return
*/
@MessageMapping("/sendjilu")
@SendTo("/sub/jilu")
public synchronized Object sendjilu(String value){
System.out.println("进入sendjilu");
JSONObject jsonObject = JSON.parseObject(value);
List<records> recordsList = recService.getrecordsAll();
List<face> faceList = recService.getFace();
for(records records: recordsList){
/*for (face face: faces) {*/
if(records.getContent()==null){
records.setContent(" ");
continue;
}
if((records.getContent().replaceAll("/s","")).equals("")){
continue;
}
Pattern pattern = Pattern.compile("\\[.*?\\]");
Matcher matcher = pattern.matcher(records.getContent());
while (matcher.find()) {
//System.out.println(matcher.group());
for (face face: faceList) {
String ma = matcher.group();
ma = ma.replace("[","");
ma = ma.replace("]","");
if (face.getFaceName().equals(ma)||face.getFaceName()==ma) {
/*<img class=\"plimga\" src=\"../images/face/"+ImgIputHandler.facePath[i].facePath+"\" height=\"24\" width=\"24\">*/
String com_content = (records.getContent()).replace(matcher.group(),"<img class=\"plimga\" src=\"../images/face/"
+face.getFacePath()+"\" height=\"24\" width=\"24\">");
records.setContent(com_content);
}
}
}
/*}*/
}
Map<String, Object> records = new HashMap<>();
records.put("recordsList", recordsList);
records.put("userList", userList);
records.put("username",jsonObject.getString("username"));
return records;
}
@MessageMapping("/connect")
@SendTo("/sub/conaa")
public synchronized Object Connect(Principal principal,String value){
/*String userName = (String)sessionsSet.get(value);*/
Map<String, Object> messageMap = new HashMap<>();
for(int i = 0; i<userList.size(); i++) {
if (value.equals(((employee)userList.get(i)).getEmp_username())) {
userList.remove(i);
}
}
// END
System.out.println("当前用户:"+value);
employee employeea = empService.getEmpByname(value);
String message = value + "加入群聊!";
userList.add(employeea);
addOnlineCount();
messageMap.put("isuser","0");
messageMap.put("numbera", getOnlineCount());
messageMap.put("srcUser", value);
messageMap.put("state","0");
messageMap.put("employeea",employeea);
System.out.println(value + "加入群聊!当前在线人数:"+getOnlineCount());
for (SimpUser simpUser:simpUserRegistry.getUsers()) {
System.out.println("用户:"+simpUser.getSessions());
}
return messageMap;
}
@MessageMapping("/disConnect")
@SendTo("/sub/conaa")
public synchronized Object disConnect(Principal principal, String value){
// 从sessionsSet中删除当前连接
/*String userName = (String)sessionsSet.get(value);
sessionsSet.remove(value);*/
// END
Map<String, Object> messageMap = new HashMap<>();
System.out.println("当前用户:"+value);
subOnlineCount();
String message = value + "退出群聊!当前在线人数:"+getOnlineCount();
for(int i = 0; i< userList.size(); i++){
if(((employee)userList.get(i)).getEmp_username().equals(value)){
userList.remove(i);
}
}
for (SimpUser simpUser:simpUserRegistry.getUsers()) {
System.out.println("用户:"+simpUser.getSessions());
}
messageMap.put("numbera", getOnlineCount());
messageMap.put("srcUser", value);
messageMap.put("state","1");
System.out.println(message);
return messageMap;
}
@MessageMapping("/notice")
@SendTo("/sub/notice")
public synchronized Object notice(String value){
JSONObject jsonObject = JSON.parseObject(value);
notice notice = new notice();
notice.setEmpname(jsonObject.getString("username"));
notice.setContent(jsonObject.getString("content"));
notice.setTitle(jsonObject.getString("title"));
notice.setIssue_userid(jsonObject.getIntValue("issue_userid"));
noticeService.addnotice(notice);
System.out.println("发布人:"+jsonObject.getString("username")+",内容:"+jsonObject.getString("content"));
return value;
}
@GetMapping("/index")
public String websocket(){
return "html/WebSocketTest";
}
// 返回在线数量
private static synchronized int getOnlineCount(){
return onlineCount;
}
// 当在线人数增加时
private static synchronized void addOnlineCount(){
WebSocketController.onlineCount++;
}
// 当在线人数减少时
private static synchronized void subOnlineCount(){
WebSocketController.onlineCount--;
}
}
|
C# | UTF-8 | 3,100 | 3.046875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
namespace Ejercicio_58_Serializacion
{
[Serializable]
public class PuntoDat : Archivo, IArchivos<PuntoDat>
{
private string contenido;
public string Contenido
{
get
{
return this.contenido;
}
set
{
this.contenido = value;
}
}
bool IArchivos<PuntoDat>.Guardar(string ruta, PuntoDat objeto)
{
bool existe=true;
Stream fs;
BinaryFormatter ser;
if(objeto.ValidarArchivo(ruta, existe))
{
fs = new FileStream(ruta, FileMode.Create);
ser = new BinaryFormatter();
ser.Serialize(fs, (PuntoDat)objeto);
fs.Close();
}
return existe;
}
bool IArchivos<PuntoDat>.GuardarComo(string ruta, PuntoDat objeto)
{
StreamWriter nr;
if (ValidarArchivo(ruta, false))
{
nr = new StreamWriter(ruta);
nr.Write(objeto.contenido);
nr.Close();
((IArchivos<PuntoDat>)this).Guardar(ruta, objeto);
}
else
{
((IArchivos<PuntoDat>)this).Guardar(ruta, objeto);
}
return true;
}
public PuntoDat Leer(string ruta)
{
PuntoDat aux = new PuntoDat();
FileStream fs; // Objeto que leerá en binario.
BinaryFormatter ser; // Objeto que Deserializará.
if (ValidarArchivo(ruta, true))
{
//Se indica ubicación del archivo binario y el modo.
fs = new FileStream(ruta, FileMode.Open);
//Se crea el objeto deserializador.
ser = new BinaryFormatter();
//Deserializa el archivo contenido en fs, lo guarda en aux.
aux = (PuntoDat)ser.Deserialize(fs);
fs.Close();
}
return aux;
}
protected override bool ValidarArchivo(string ruta, bool validaExistencia)
{
//validaExistencia = false;
try
{
if (base.ValidarArchivo(ruta, validaExistencia))
{
if (Path.GetExtension(ruta) == ".dat")
{
validaExistencia = true;
}
else
{
throw new ArchivoIncorrectoException("El archivo no es un dat.");
}
}
}
catch (FileNotFoundException e)
{
throw new ArchivoIncorrectoException("Archivo no Encontrado",e);
}
return validaExistencia;
}
}
}
|
PHP | UTF-8 | 1,292 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace WpPhpRequestGo;
use GuzzleHttp\Client;
use Throwable;
class PhpRequestGo
{
/**
* GO 访问域名
* @var string
*/
private static string $endpoint = 'http://127.0.0.1:9501';
public function connectGo(string $api, array $params, string $method)
{
try {
$method = strtoupper($method);
// 发送数据
$client = new Client([
// Base URI is used with relative requests
'base_uri' => self::$endpoint,
// You can set any number of default request options.
'timeout' => 5.0,
]);
$res = $client->request($method, $api, [
'body' => self::arrayToJson($params),
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
],
]);
return json_decode($res->getBody()->getContents(), true);
} catch (Throwable $e) {
return ['code' => 1, 'msg' => $e->getMessage(), 'status' => false, 'data' => []];
}
}
private static function arrayToJson(array $res)
{
return json_encode($res, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
}
}
|
Python | UTF-8 | 11,089 | 2.609375 | 3 | [
"MIT"
] | permissive | """Tests the add plugin."""
import argparse
import copy
import shutil
from pathlib import Path
from unittest.mock import MagicMock, Mock, call, patch
import pytest
from sqlalchemy.orm.session import Session
import moe
from moe.core.config import Config
from moe.core.library.album import Album
from moe.core.library.session import session_scope
from moe.core.library.track import Track
from moe.plugins import add
class ImportPlugin:
"""Test plugin that implements the ``import_metadata`` hook for testing."""
@staticmethod
@moe.hookimpl
def import_album(config: Config, session: Session, album: Album) -> Album:
"""Changes the album title."""
album.title = "pre-add plugin"
return album
class TestParseArgs:
"""Test general functionality of the argument parser."""
def test_multiple_item_exit_error(self, real_track, tmp_session):
"""Don't exit after the first failed item if more to be added.
Still exit with non-zero code if any failures occured.
"""
args = argparse.Namespace(paths=["bad file", str(real_track.path)])
with patch("moe.plugins.add.add._add_item") as add_item_mock:
add_item_mock.side_effect = [add.AddError, tmp_session.add(real_track)]
with pytest.raises(SystemExit) as error:
add.add._parse_args(Mock(), tmp_session, args)
assert error.value.code != 0
assert tmp_session.query(Track).one()
def test_multiple_paths(self, real_track_factory, tmp_session):
"""Add all paths given."""
mock_config = Mock()
mock_session = Mock()
track_path1 = real_track_factory().path
track_path2 = real_track_factory().path
args = argparse.Namespace(paths=[str(track_path1), str(track_path2)])
with patch("moe.plugins.add.add._add_item") as add_item_mock:
add.add._parse_args(mock_config, mock_session, args)
calls = [
call(mock_config, mock_session, track_path1),
call(mock_config, mock_session, track_path2),
]
add_item_mock.assert_has_calls(calls)
assert add_item_mock.call_count == 2
class TestAddItemFromDir:
"""Test a directory given to ``_add_item()`` to add as an album."""
def test_dir_album(self, real_album, tmp_session):
"""If a directory given, add to library as an album."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
add.add._add_item(mock_config, tmp_session, real_album.path)
assert tmp_session.query(Album).filter_by(path=real_album.path).one()
def test_extras(self, real_album, tmp_session):
"""Add any extras that are within the album directory."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
assert real_album.extras
add.add._add_item(mock_config, tmp_session, real_album.path)
db_album = tmp_session.query(Album).one()
for extra in real_album.extras:
assert extra in db_album.extras
def test_no_valid_tracks(self, tmp_session, tmp_path):
"""Error if given directory does not contain any valid tracks."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
album_path = tmp_path / "empty"
album_path.mkdir()
with pytest.raises(add.AddError):
add.add._add_item(mock_config, tmp_session, album_path)
assert not tmp_session.query(Album).scalar()
def test_different_tracks(self, real_track_factory, tmp_path, tmp_session):
"""Error if tracks have different album attributes.
All tracks in a given directory should belong to the same album.
"""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
tmp_album_path = tmp_path / "tmp_album"
tmp_album_path.mkdir()
shutil.copy(real_track_factory(year=1).path, tmp_album_path)
shutil.copy(real_track_factory(year=2).path, tmp_album_path)
with pytest.raises(add.AddError):
add.add._add_item(mock_config, tmp_session, tmp_album_path)
assert not tmp_session.query(Album).scalar()
def test_duplicate_tracks(self, real_album, tmp_session):
"""Don't fail album add if a track (by tags) already exists in the library."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
tmp_session.merge(real_album.tracks[0])
add.add._add_item(mock_config, tmp_session, real_album.path)
assert tmp_session.query(Album).filter_by(path=real_album.path).one()
def test_duplicate_album(self, real_album, tmp_session):
"""We merge an existing album by it's path."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
dup_album = copy.deepcopy(real_album)
dup_album.title = "diff"
tmp_session.merge(dup_album)
add.add._add_item(mock_config, tmp_session, real_album.path)
assert tmp_session.query(Album).filter_by(path=real_album.path).one()
def test_merge_existing(self, real_album_factory, tmp_session):
"""Merge the album to be added with an existing album in the library.
The album info should be kept (likely to be more accurate), however, any tracks
or extras should be overwritten.
"""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
new_album = real_album_factory()
existing_album = real_album_factory()
new_album.date = existing_album.date
new_album.path = existing_album.path
existing_album.mb_album_id = "1234"
assert not new_album.is_unique(existing_album)
for track in new_album.tracks:
track.title = "new_album"
for extra_num, extra in enumerate(new_album.extras):
extra.path = Path(f"{extra_num}.txt")
assert new_album.mb_album_id != existing_album.mb_album_id
assert new_album.tracks != existing_album.tracks
assert new_album.extras != existing_album.extras
tmp_session.merge(existing_album)
with patch("moe.plugins.add.add._add_album", return_value=new_album):
add.add._add_item(mock_config, tmp_session, new_album.path)
db_album = tmp_session.query(Album).one()
assert db_album.mb_album_id == existing_album.mb_album_id
assert sorted(db_album.tracks) == sorted(new_album.tracks)
assert sorted(db_album.extras) == sorted(new_album.extras)
def test_add_multi_disc(self, real_album, tmp_session):
"""We can add a multi-disc album."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
track1 = real_album.tracks[0]
track2 = real_album.tracks[1]
track1.disc = 1
track2.disc = 2
real_album.disc_total = 2
track1_path = Path(real_album.path / "disc 01" / track1.path.name)
track2_path = Path(real_album.path / "disc 02" / track2.path.name)
track1_path.parent.mkdir()
track2_path.parent.mkdir()
track1.path.rename(track1_path)
track2.path.rename(track2_path)
track1.path = track1_path
track2.path = track2_path
add.add._add_item(mock_config, tmp_session, real_album.path)
album = tmp_session.query(Album).filter_by(path=real_album.path).one()
assert track1 in album.tracks
assert track2 in album.tracks
class TestAddItemFromFile:
"""Test a file argument given to add as a track."""
def test_path_not_found(self):
"""Raise SystemExit if the path to add does not exist."""
with pytest.raises(add.AddError):
add.add._add_item(Mock(), Mock(), Path("does not exist"))
def test_file_track(self, real_track, tmp_session):
"""If a file given, add to library as a Track."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
add.add._add_item(mock_config, tmp_session, real_track.path)
assert tmp_session.query(Track.path).filter_by(path=real_track.path).one()
def test_min_reqd_tags(self, tmp_session):
"""We can add a track with only a track_num, album, albumartist, and year."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
reqd_track_path = Path("tests/resources/reqd.mp3")
add.add._add_item(mock_config, tmp_session, reqd_track_path)
assert tmp_session.query(Track.path).filter_by(path=reqd_track_path).one()
def test_non_track_file(self):
"""Error if the file given is not a valid track."""
with pytest.raises(add.AddError):
add.add._add_item(Mock(), Mock(), Path("tests/resources/log.txt"))
def test_track_missing_reqd_tags(self):
"""Error if the track doesn't have all the required tags."""
with pytest.raises(add.AddError):
add.add._add_item(Mock(), Mock(), Path("tests/resources/empty.mp3"))
def test_duplicate_track(self, real_track, tmp_session, tmp_path):
"""Overwrite old track path with the new track if a duplicate is found."""
mock_config = MagicMock()
mock_config.plugin_manager.hook.import_album.return_value = []
new_track_path = tmp_path / "full2"
shutil.copyfile(real_track.path, new_track_path)
tmp_session.add(real_track)
add.add._add_item(mock_config, tmp_session, new_track_path)
assert tmp_session.query(Track.path).filter_by(path=new_track_path).one()
@pytest.mark.integration
class TestImportAlbum:
"""Test integration with the ``import_album`` hook and thus the add prompt."""
def test_album(self, real_album, tmp_config):
"""Prompt is run with a plugin implementing the ``import_album`` hook."""
cli_args = ["add", str(real_album.path)]
config = tmp_config(settings='default_plugins = ["add"]')
config.plugin_manager.register(ImportPlugin)
mock_q = Mock()
mock_q.ask.return_value = add.prompt._apply_changes
with patch("moe.plugins.add.prompt.questionary.rawselect", return_value=mock_q):
moe.cli.main(cli_args, config)
with session_scope() as session:
album = session.query(Album).one()
assert album.title == "pre-add plugin"
@pytest.mark.integration
class TestCommand:
"""Test cli integration with the add command."""
def test_file(self, real_track, tmp_config):
"""Tracks are added to the library when a file is passed to `add`."""
cli_args = ["add", str(real_track.path)]
config = tmp_config(settings='default_plugins = ["add"]')
moe.cli.main(cli_args, config)
with session_scope() as session:
assert session.query(Track).one()
|
Java | UTF-8 | 7,432 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | package us.ihmc.simulationConstructionSetTools.util.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import us.ihmc.commons.PrintTools;
import us.ihmc.tools.gui.GUIMessagePanel;
public class GUIMessageFrame
{
private static final boolean SHOW_GUI_MESSAGE_FRAME = false;
private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("M/d/uu h:mm a: ");
private final JFrame messageWindow;
private final JTabbedPane jTabbedPane;
private final JCheckBox lockBox;
private final int errorMessagePanelIndex, outMessagePanelIndex, parameterMessagePanelIndex;
private boolean locked = false;
private int lastMessagePanel = 0;
private ArrayList<Integer> listOfPanels = new ArrayList<Integer>();
private static GUIMessageFrame elvis;
public GUIMessageFrame(String messageWindowName)
{
if (SHOW_GUI_MESSAGE_FRAME)
{
messageWindow = new JFrame(messageWindowName);
jTabbedPane = new JTabbedPane();
lockBox = new JCheckBox("Lock Focus");
messageWindow.getContentPane().setLayout(new BorderLayout());
messageWindow.getContentPane().add(jTabbedPane); // ,BorderLayout.CENTER);
messageWindow.getContentPane().add(lockBox, BorderLayout.SOUTH);
// jTabbedPane.setSize(100, 100);
lockBox.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (locked)
{
locked = false;
jTabbedPane.setSelectedIndex(lastMessagePanel);
}
else
{
locked = true;
}
}
});
GUIMessagePanel messagePanel;
String outStatusString = "Out";
messagePanel = new GUIMessagePanel(outStatusString);
jTabbedPane.add(outStatusString, messagePanel);
outMessagePanelIndex = jTabbedPane.indexOfTab(outStatusString);
listOfPanels.add(outMessagePanelIndex);
String errorStatusString = "Error";
messagePanel = new GUIMessagePanel(errorStatusString);
jTabbedPane.add(errorStatusString, messagePanel);
errorMessagePanelIndex = jTabbedPane.indexOfTab(errorStatusString);
listOfPanels.add(errorMessagePanelIndex);
String parameterStatusString = "Parameter";
messagePanel = new GUIMessagePanel(parameterStatusString);
jTabbedPane.add(parameterStatusString, messagePanel);
parameterMessagePanelIndex = jTabbedPane.indexOfTab(parameterStatusString);
listOfPanels.add(parameterMessagePanelIndex);
messageWindow.setSize(new Dimension(900, 800));
messageWindow.setLocation(250, 0);
if (SHOW_GUI_MESSAGE_FRAME)
messageWindow.setVisible(true);
}
else
{
this.parameterMessagePanelIndex = 0;
this.outMessagePanelIndex = 0;
this.errorMessagePanelIndex = 0;
this.messageWindow = null;
this.jTabbedPane = null;
this.lockBox = null;
}
}
public static GUIMessageFrame getInstance()
{
if (elvis == null)
{
elvis = new GUIMessageFrame("GUI Message Frame");
}
return elvis;
}
public void appendOutMessage(String outMessage)
{
appendMessageToPanel(outMessagePanelIndex, outMessage);
}
public void appendErrorMessage(String error)
{
appendMessageToPanel(errorMessagePanelIndex, error);
}
public void appendParameterMessage(String message)
{
appendMessageToPanel(parameterMessagePanelIndex, message);
}
public void popupErrorMessage(String error)
{
JOptionPane.showMessageDialog(messageWindow, error, "Error", JOptionPane.ERROR_MESSAGE);
}
public void popupWarningMessage(String warning)
{
JOptionPane.showMessageDialog(messageWindow, warning, "Warning", JOptionPane.WARNING_MESSAGE);
}
public void popupInformationMessage(String message)
{
JOptionPane.showMessageDialog(messageWindow, message, "Message", JOptionPane.INFORMATION_MESSAGE);
}
public void appendMessageToPanel(int panelIndex, String message)
{
appendMessageToPanel(panelIndex, message, Color.BLACK);
}
private String prependTimeToMessage(String message)
{
String time = computeTime();
message = time + message;
return message;
}
public String computeTime()
{
return LocalDateTime.now().format(dateTimeFormatter);
}
public void appendMessageToPanel(int panelIndex, String message, Color color)
{
if (SHOW_GUI_MESSAGE_FRAME)
{
message = prependTimeToMessage(message);
GUIMessagePanel gUIMessagePanel = (GUIMessagePanel) jTabbedPane.getComponentAt(panelIndex);
gUIMessagePanel.appendMessage(message, color);
if (!locked)
jTabbedPane.setSelectedIndex(panelIndex);
lastMessagePanel = panelIndex;
}
}
public int createGUIMessagePanel(String name)
{
if (SHOW_GUI_MESSAGE_FRAME)
{
GUIMessagePanel ret = new GUIMessagePanel(name);
int checkIndex = jTabbedPane.indexOfTab(name);
if (checkIndex != -1)
{
throw new RuntimeException("This name is already taken: " + name);
}
else
jTabbedPane.addTab(name, ret);
int integerValueToReturn = jTabbedPane.indexOfTab(name);
listOfPanels.add(integerValueToReturn);
return integerValueToReturn;
}
else
{
return 0;
}
}
public void reset()
{
for (Integer panelIndexValue : listOfPanels)
{
GUIMessagePanel gUIMessagePanel = null;
gUIMessagePanel = (GUIMessagePanel) jTabbedPane.getComponentAt(panelIndexValue);
gUIMessagePanel.clear();
}
}
public void save(String filename)
{
File file = new File(filename);
save(file);
}
public void save(File file)
{
PrintWriter printWriter;
try
{
printWriter = new PrintWriter(file);
}
catch (FileNotFoundException fileNotFoundException)
{
PrintTools.error(fileNotFoundException.getMessage() + "\n" + file);
return;
}
// printWriter.println(listOfPanels.size());
for (int panelIndex = 0; panelIndex < listOfPanels.size(); panelIndex++)
{
GUIMessagePanel guiMessagePanel = (GUIMessagePanel) jTabbedPane.getComponentAt(panelIndex);
PrintTools.debug(guiMessagePanel.toString());
String name = guiMessagePanel.getName();
printWriter.println(name);
printWriter.println("{\\StartGUIMessagePanelText}");
String text = guiMessagePanel.getText();
printWriter.write(text);
printWriter.println("{\\EndGUIMessagePanelText}");
}
printWriter.flush();
printWriter.close();
}
}
|
Markdown | UTF-8 | 3,343 | 3.140625 | 3 | [] | no_license | # Read Me Before You Start! :book:
In the current directory, you'll see two sub-directories. Each one has code for our super-awesome services.
Right now you have only 2 services. So you might not mind starting each one individually.
But you never know how many we might end up making! So it's good to future-proof, and save ourselves from panic attacks when we'll have 10 such services! :yum:
## What do you have to do?
Before telling you what to do, we'll tell you something about docker-compose. (Quoting directly from the [official documentation](https://docs.docker.com/compose/overview/):)
> Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services. Then, with a single command, you create and start all the services from your configuration.
**Now let us tell you what you need to do.** Use Docker Compose, and just with this single incantation (you can swing your wands too! :sunglasses:), spawn our 2 services:
```
docker-compose up
```
Pretty simple, right? :bowtie:
Well... If you were awake in the first Docker Session, then it's pretty simple. :relaxed:
But... :point_up: if you were sleeping :sleeping: (and we know you were!), and therefore not sure how to go about doing this, we would suggest you go through these docs to get to know Docker Compose:
- [Meet Docker Compose](https://docs.docker.com/compose/overview/) :whale:
- [Install Docker Compose](https://docs.docker.com/compose/install/) :arrow_down: :whale:
- [And get your hands dirty!](https://docs.docker.com/compose/gettingstarted/) :open_hands: :whale: *(Hint: This page has solutions to all your problems!* :wink:*)*
## A Word On The Services
You have 2 services right now:
- Product API Service
- WebPro Panel FrontEnd
Product API Service has been implemented in Python, and the WebPro Panel has been written in PHP.
However, **to complete this challenge you don't need to know either Python or PHP.**
And to relieve you even more, we have gone ahead and dockerized Product API Service for you already! :innocent:
And for the WebPro Panel Service, we can tell you that you need to:
- Use an image named [```php:5.6.36-apache```](https://hub.docker.com/_/php/).
- And, copy the php file in the ```/var/www/html``` directory of your container.
**Then you just need to fill the ```docker-compose.yml``` file**, and say that magic incantation:
```
docker-compose up
```
That's it!
## Bonus Points
You would not want to keep restarting your services when you make some changes to your code.
To avoid that, use **docker volumes** so that your containers have direct access to the changed code.
## How To Verify If It Worked?
You should be able to call your services (from your browser) on whatever ports you started them on. *(Hint: Ports will go in the ```docker-compose.yml``` file.)*
Right now, the 2 services are not communicating with each other. But what fun will the next session be if you were to do all the hard work!?! :sweat_smile:
## What If I Still Can't Do It?
No problem! You can talk to any one of us: Birju.s, Rajeev.s, Supriya.m, Sudheer.m, Prasad.p, Arnav.c, or Abhinav.ve.
And if you are too shy to do even that, we'll anyway show you how to do this (and much more! :sunglasses:) in our next Docker Session. So stay tuned! :smiley: |
Markdown | UTF-8 | 8,780 | 2.609375 | 3 | [] | no_license | # Cisco IOU L2 L3 lab với GNS3
# Mục lục
<h3><a href="#concept">1. Các phần mềm yêu cầu cho bài lab</a></h3>
<h3><a href="#iouvm_vir">2. Cài đặt GNS3 IOU VM trên Virtual Box</a></h3>
<h3><a href="#cfg_iou_server">3. Cấu hình IOU Server trên GNS3</a></h3>
<h3><a href="#integ">4. Tích hợp GNS3 với Cisco IOU</a></h3>
<h3><a href="#setup">5. Cấu hình network bonding với GNS3 và IOU switch</a></h3>
<ul>
<li><a href="#topology">5.1. Mô hình lab</a></li>
<li><a href="#cfg_sw">5.2. Cấu hình các switch</a></li>
</ul>
<h3><a href="#ref">6. Tham khảo</a></h3>
---
<h2><a name="concept">1. Các phần mềm yêu cầu cho bài lab</a></h2>
<div>
<ul>
<li>Cài đặt GNS3 (bài lab sử dụng bản 1.3.3). <a href="https://github.com/GNS3/gns3-gui/releases/tag/v1.3.3">Tải GNS3 1.3.3.</a></li>
<li>Virtual Box, tải <a href="https://www.virtualbox.org/">tại đây.</a></li>
<li>IOU Images: sử dụng để tạo switch trên GNS3. Tải IOU Images sử dụng <a href="http://www.bittorrent.com/bittorrent-free">bittorent</a>. File torrent một số IOU Images mẫu có thể tải <a href="https://www.dropbox.com/s/es46wrxfajvrnbk/55EAD4B54E75A459176E0605F8BE32C9706E2CBA.torrent?dl=0">tại đây</a>.</li>
<li>GNS3 IOU VM: đây là server để chạy các Switch VM. Tải image GNS3 IOU VM: <a href="http://sourceforge.net/projects/gns-3/files/IOU%20VMs/">http://sourceforge.net/projects/gns-3/files/IOU%20VMs/</a>. Chú ý chọn file *.ova phiên bản phù hợp với phiên bản GNS3, ở đây chọn file <a href="https://sourceforge.net/projects/gns-3/files/IOU%20VMs/GNS3%20IOU%20VM_1.3.3.ova/download">GNS3 IOU VM_1.3.3.ova</a></li>
<li>IOURC: là file Cisco license cho các IOU Images. <a href="https://www.dropbox.com/s/8r64q7ttnigymrj/iourc.txt?dl=0">Tải IOURC.</a></li>
</ul>
</div>
<h2><a name="iouvm_vir">2. Cài đặt GNS3 IOU VM trên Virtual Box</a></h2>
<div>
<ul>
<li>Mở VirtualBox, import file *.ova đã tải về để tạo server.
<br><br>
<img src="http://i.imgur.com/l3Xm6pi.png">
<br><br>
</li>
<li>Duyệt tới file *.ova, sau đó click Next
<br><br>
<img src="http://i.imgur.com/DiMQLkK.png">
<br><br>
</li>
<li>Ở cửa sổ tiếp theo, click Import
<br><br>
<img src="http://i.imgur.com/ympa8bb.png">
<br><br>
</li>
<li>Sau khi import xong ta có một máy ảo làm server. Tiến hành chỉnh sửa lại chế độ card mạng chọn lại card mạng cho server này hoạt động ở chế độ <b>Host Only</b>
<br><br>
<img src="http://i.imgur.com/Wph5zZb.png">
<br><br>
</li>
<li>Mở server lên, kiểm tra địa chỉ IP của server.(User: root, mật khẩu: cisco). Ví dụ địa chỉ server ở đây là: 10.10.100.128
<br><br>
<img src="http://i.imgur.com/IdYU537.png">
<br><br>
</li>
<li>Truy cập vào server trên trình duyệt để upload image của các switch lên server. Truy cập địa chỉ: <code>http://<ip_server>:8000/upload</code>. Ví dụ: http://10.10.100.128:8000/upload.</li>
<br><br>
<img src="http://i.imgur.com/oXi3a4n.png">
<br><br>
<li>Sau khi tải file nén các image mẫu của các IOU switch về (sử dụng bittorent), giải nén ra ta sẽ có một số image mẫu như hình:
<br><br>
<img src="http://i.imgur.com/1V9YMJv.png">
<br><br>
</li>
<li>Tiến hành upload một số image mẫu lên như hình.
<br><br>
<img src="http://i.imgur.com/Txws3qQ.png">
<br><br>
Sau khi upload thành công, chú ý note lại đường dẫn lưu image trên server của image tải lên.(đường dẫn này dùng trong cấu hình switch bên dưới)
</li>
</ul>
</div>
<h2><a name="cfg_iou_server">3. Cấu hình IOU Server trên GNS3</a></h2>
<div>Mở GNS3 lên và chuyển sang tab: <code>Edit->Preferences</code> hoặc sử dụng phím tắt <code>Ctrl+Shift+P</code> để mở cửa sổ cấu hình. Trên cửa sổ cấu hình chuyển sang tab <code>Server->Remote servers</code>. Sau đó cấu hình như hình minh họa bên dưới.
<br><br>
<img src="http://i.imgur.com/jxrjmDX.png">
<br><br>
</div>
<h2><a name="integ">4. Tích hợp GNS3 với Cisco IOU</a></h2>
<div>
Trước hết ta cần import cisco license để sử dụng các IOU images. Vẫn trong cửa sổ cấu hình như mục 3, chuyển sang tab <code>IOS on UNIX->General</code>. Nhấn "Browse" duyệt tới file license đã tải rồi lick Apply->OK để áp dụng cấu hình.
<br><br>
<img src="http://i.imgur.com/Zi2xtxp.png">
<br><br>
Bây giờ ta sẽ tiến hành tạo switch layer 2 sử dụng file image đã tải lên server. Vẫn trong cửa sổ cấu hình của GNS3, chuyển sang tab <code>IOS on UNIX->IOU devices</code>. Click New tạo switch mới.
<br><br>
<img src="http://i.imgur.com/2NwOWgQ.png">
<br><br>
Click Next, nếu có thông báo hiện ra thì click OK. Sau đó đặt trên cho switch và paste đường dẫn của image trên server đã note lại ở bước 2, rồi click Finish tạo switch.
<br><br>
<img src="http://i.imgur.com/tU2GHQh.png">
<br><br>
<img src="http://i.imgur.com/Bxf5lYN.png">
<br><br>
Cuối cùng Click Apply->OK để xác nhận tạo switch mới.
<br><br>
<img src="http://i.imgur.com/8kMC7qi.png">
<br><br>
</div>
<h2><a name="setup">5. Cấu hình network bonding với GNS3 và IOU switch</a></h2>
<ul>
<li><h3><a name="topology">5.1. Mô hình lab</a></h3>
Mô hình lab sử dụng 2 switch đã tạo ở bước trên, tạo 2 đường kết nối giữa 2 switch và tiến hành cấu hình bonding trên 2 switch này.
<br><br>
<img src="http://i.imgur.com/0iuWafd.png">
<br><br>
</li>
<li><h3><a name="cfg_sw">5.2. Cấu hình các switch</a></h3>
Chú ý sử dụng switch đã tạo, ví dụ như hình bên dưới.
<br><br>
<img src="http://i.imgur.com/SFBUmNN.png">
<br><br>
</li>
Bật các switch lên, sau đó click chuột phải vào mỗi switch, chọn <code>Console</code> để mở cửa sổ cấu hình.
<br>
Cấu hình trên switch 2 trước, lần lượt thực hiện các lệnh sau:
<pre>
<code>
conf t
int range e0/0 -1
sw t en d
sw m t
sw non
channel-group 20 mode ?
channel-group 20 mode passive
end
</code>
</pre>
Cấu hình trên switch 1, gõ từng lệnh cấu hình sau:
<pre>
<code>
conf t
int range e0/0 -1
sw t en d
sw m t
sw non
channel-group 10 mode ?
channel-group 10 mode active
end
wr
</code>
</pre>
Trên switch 1, sau khi cấu hình xong, gõ lệnh kiểm tra <code>show etherchannel summary</code>. Kết quả thành công sẽ tương tự như sau:
<pre>
<code>
SW1#show etherchannel summary
Flags: D - down P - bundled in port-channel
I - stand-alone s - suspended
H - Hot-standby (LACP only)
R - Layer3 S - Layer2
U - in use f - failed to allocate aggregator
M - not in use, minimum links not met
u - unsuitable for bundling
w - waiting to be aggregated
d - default port
Number of channel-groups in use: 1
Number of aggregators: 1
Group Port-channel Protocol Ports
------+-------------+-----------+-----------------------------------------------
10 Po10(SU) LACP Et0/0(P) Et0/1(P)
</code>
</pre>
Chú ý bảng cuối cùng thấy ở cột <b>Protocol</b> giá trị là <b>LACP</b>, và cột <b>Port</b> thấy kí hiệu P (ý nghĩa là hai đường kết nối đã được "bó" lại trên 1 kênh logic) thì cấu hình đã chính xác.
</ul>
<h2><a name="ref">6. Tham khảo</a></h2>
<div>
[1] - <a href="http://letusexplain.blogspot.com/2015/07/cisco-iou-l2-l3-lab-with-gns3-switching.html">http://letusexplain.blogspot.com/2015/07/cisco-iou-l2-l3-lab-with-gns3-switching.html</a>
<br>
[2] - <a href="https://www.youtube.com/watch?v=vAitTGfsuJE">https://www.youtube.com/watch?v=vAitTGfsuJE</a>
<br>
[3] - <a href="https://www.youtube.com/watch?v=akGp2NX_0zI">https://www.youtube.com/watch?v=akGp2NX_0zI</a>
</div>
|
SQL | UTF-8 | 555 | 3.484375 | 3 | [] | no_license |
CREATE VIEW dbo.TEMPLATE_LOCATIONS_2_V
AS
SELECT dbo.TEMPLATE_LOCATIONS.LOCATION, TEMPLATES_1.TEMPLATE_NAME, TEMPLATES1.TEMPLATE_NAME AS TAB_NAME
FROM dbo.TABS INNER JOIN
dbo.TEMPLATES TEMPLATES1 ON dbo.TABS.TEMPLATE_ID = TEMPLATES1.TEMPLATE_ID INNER JOIN
dbo.TEMPLATES TEMPLATES_1 INNER JOIN
dbo.TEMPLATE_LOCATIONS ON TEMPLATES_1.TEMPLATE_ID = dbo.TEMPLATE_LOCATIONS.LEVEL_2_TEMPLATE ON
dbo.TABS.TAB_ID = dbo.TEMPLATE_LOCATIONS.LEVEL_2_TAB
|
Java | UTF-8 | 3,926 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package org.appenders.log4j2.elasticsearch.hc;
/*-
* #%L
* log4j2-elasticsearch
* %%
* Copyright (C) 2019 Rafal Foltynski
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
* #L%
*/
import java.util.List;
import java.util.Optional;
public class BatchResult implements Response {
private static final int ERROR_MAX_STACK_DEPTH = Integer.parseInt(System.getProperty("appenders.BatchResult.error.depth", "1"));
static final String UNABLE_TO_GET_MORE_INFO = "Unable to extract error info from failed items";
static final String ONE_OR_MORE_ITEMS_FAILED = "One or more items failed";
static final String FIRST_FAILED_ITEM_PREFIX = "First failed item: ";
static final String ROOT_ERROR_PREFIX = "Root error: ";
private static final String SEPARATOR = ". ";
private final int took;
private final boolean errors;
private final Error error;
private final int statusCode;
private final List<BatchItemResult> items;
private String errorMessage;
private int responseCode;
public BatchResult(int took, boolean errors, Error error, int statusCode, List<BatchItemResult> items) {
this.took = took;
this.errors = errors;
this.error = error;
this.statusCode = statusCode;
this.items = items;
}
public int getTook() {
return took;
}
/**
* @return true if {@link #errors} is false and {@link #error is null}, false otherwise
*/
public boolean isSucceeded() {
return !this.errors && error == null;
}
public Error getError() {
return error;
}
public int getStatusCode() {
return statusCode;
}
public List<BatchItemResult> getItems() {
return items;
}
@Override
public int getResponseCode() {
return responseCode;
}
@Override
public String getErrorMessage() {
return errorMessage;
}
public BatchResult withResponseCode(int responseCode) {
this.responseCode = responseCode;
return this;
}
private StringBuilder appendFailedItemErrorMessageIfAvailable(final StringBuilder sb) {
if (getItems() == null) {
return sb.append(UNABLE_TO_GET_MORE_INFO);
}
final Optional<BatchItemResult> firstFailedItem = getItems().stream().filter(item -> item.getError() != null).findFirst();
if (!firstFailedItem.isPresent()) {
return sb.append(UNABLE_TO_GET_MORE_INFO);
}
sb.append(FIRST_FAILED_ITEM_PREFIX);
return firstFailedItem.get().getError().appendErrorMessage(sb, ERROR_MAX_STACK_DEPTH);
}
public BatchResult withErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
if (isSucceeded()) {
return this;
}
final StringBuilder sb = new StringBuilder(256);
sb.append(errorMessage);
if (errors) {
sb.append(SEPARATOR).append(ONE_OR_MORE_ITEMS_FAILED);
appendFailedItemErrorMessageIfAvailable(sb.append(SEPARATOR));
}
if (statusCode > 0) {
sb.append(SEPARATOR).append("status: ").append(statusCode);
}
if (getError() != null) {
sb.append(SEPARATOR).append(ROOT_ERROR_PREFIX);
getError().appendErrorMessage(sb, ERROR_MAX_STACK_DEPTH);
}
this.errorMessage = sb.toString();
return this;
}
}
|
Python | UTF-8 | 1,201 | 3.859375 | 4 | [] | no_license |
# 문제
# N개의 정수 A[1], A[2], …, A[N]이 주어져 있을 때,
# 이 안에 X라는 정수가 존재하는지 알아내는 프로그램을 작성하시오.
#
# 입력
# 첫째 줄에 자연수 N(1≤N≤100,000)이 주어진다.
# 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다.
# 다음 줄에는 M(1≤M≤100,000)이 주어진다.
# 다음 줄에는 M개의 수들이 주어지는데, 이 수들이 A안에 존재하는지 알아내면 된다.
# 모든 정수들의 범위는 int 로 한다.
#
# 출력
# M개의 줄에 답을 출력한다. 존재하면 1을, 존재하지 않으면 0을 출력한다.
import sys
def binary_search(target, data):
start = 0
end = len(data) - 1
while start <= end:
mid = (start + end) // 2
if data[mid] == target:
return True
elif data[mid] < target:
start = mid + 1
else:
end = mid -1
return False
N = int(sys.stdin.readline())
A = list(map(int, sys.stdin.readline().split()))
M = int(sys.stdin.readline())
B = list(map(int, sys.stdin.readline().split()))
A.sort()
for i in range(M):
print(1) if binary_search(B[i], A) else print(0)
|
TypeScript | UTF-8 | 935 | 3.375 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=236 lang=typescript
*
* [236] 二叉树的最近公共祖先
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
if (root == null || root == p || root == q) return root;
// 后序遍历
let left = lowestCommonAncestor(root.left, p, q);
let right = lowestCommonAncestor(root.right, p, q);
if (left == null) return right;
if (right == null) return left;
return root;
};
// @lc code=end
|
Java | UTF-8 | 1,651 | 2.71875 | 3 | [] | no_license | package model;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
*
* @author kadirayk
*
*/
public class State implements Serializable {
/**
*
*/
private static final long serialVersionUID = -849218511658141465L;
private String name;
private Map<String, String> transition;
private List<Question> questions;
public Question getQuestionById(String id) {
Question question = null;
if (ListUtil.isNotEmpty(questions)) {
for (Question q : questions) {
if (id.equals(q.getId())) {
return q;
}
}
}
return question;
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getTransition() {
return transition;
}
public void setTransition(Map<String, String> transition) {
this.transition = transition;
}
/**
* Generates concrete HTML element from the UI Elements of the questions to
* make up the form
*
* @return
*/
public String toHTML() {
StringBuilder htmlElement = new StringBuilder();
if (ListUtil.isNotEmpty(questions)) {
for (Question q : questions) {
String formQuestion = q.getContent();
if (formQuestion != null) {
htmlElement.append("<br>").append(formQuestion).append("<br>");
}
UIElement formUiElement = q.getUiElement();
if (formUiElement != null) {
htmlElement.append(formUiElement.toHTML()).append("<br>").append("\n");
}
}
}
return htmlElement.toString();
}
}
|
Java | UTF-8 | 7,554 | 2.421875 | 2 | [] | no_license | package authorize.testsuite;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import authorize.login.LoginPage;
import authorize.universal.method.ScreenShot;
import authorize.universal.method.globalValue;
import authorize.universal.method.highlight;
import authorize.universal.method.openBrowser;
import authorize.universal.method.sleep;
import authorize.user.management.ObjectUserManagement;
/*
* 文件名:deluser.java
* 包名:authorize.testsuite
* 目的:执行测试用例3. 删除用户
* 输入参数:test_name
* 返回结果:
* 注意事项:使用admin_name账号测试
* 作者:曾昱皓
* 日期:May 6, 2014 2:30:20 PM
*/
public class deluser
{
public deluser(WebDriver driver)
{
// Check that we're on the right page.
if (!globalValue.title.equals(driver.getTitle()))
{
// Alternatively, we could navigate to the login page, perhaps
// logging out first
throw new IllegalStateException("This is not the login page");
}
}
public deluser() throws FileNotFoundException, IOException, InterruptedException
{
Properties prop = new Properties();
prop.load(new FileInputStream("config.properties"));
String root_name = prop.getProperty("root_name");
String root_password = prop.getProperty("root_password");
String login_name = prop.getProperty("admin_name");
String login_passwd = prop.getProperty("password");
int count = Integer.parseInt(prop.getProperty("count"));
int time = Integer.parseInt(prop.getProperty("time"));
String admin_name = prop.getProperty("admin_name");
String guest_name = prop.getProperty("guest_name");
String modify_name = prop.getProperty("modify_name");
for (int i = 1; i <= count; i++)
{
//删除guest用户
WebDriver wdriver = new openBrowser().run();
LoginPage LoginPage_guest = new LoginPage(wdriver);
sleep.wait(time);
wdriver.manage().window().maximize();
sleep.wait(time);
highlight.Element(wdriver, LoginPage_guest.getusernameLocator());
sleep.wait(time);
LoginPage_guest.typeUsername(login_name);
sleep.wait(time);
highlight.Element(wdriver, LoginPage_guest.getpasswordLocator());
sleep.wait(time);
LoginPage_guest.typePassword(login_passwd);
sleep.wait(time);
highlight.Element(wdriver, LoginPage_guest.getloginButtonLocator());
sleep.wait(time);
LoginPage_guest.clickLogin();
sleep.wait(time);
LoginPage_guest.clickusermanagementPage();
sleep.wait(time);
ScreenShot.takeScreenShot("deluser_guest_usermanagementPage", wdriver);
ObjectUserManagement ObjectUserManagement_guest = new ObjectUserManagement(wdriver);
for (int j = 1; j <= 10; j++)
{
ObjectUserManagement_guest.clickSelectxlineLocator(String.valueOf(j), guest_name);
}
sleep.wait(time);
highlight.Element(wdriver, ObjectUserManagement_guest.getdelButtonLocator());
sleep.wait(time);
ObjectUserManagement_guest.clickDelButtonLocator(ObjectUserManagement_guest.getdelButtonLocator());
sleep.wait(time);
ObjectUserManagement_guest.clickSaveButtonLocator("/html/body/div[2]/div/div/div[2]/button[2]");
sleep.wait(time*5);
LoginPage_guest.clickoperationPage();
sleep.wait(time*3);
ScreenShot.takeScreenShot("del_guest_operationPage", wdriver);
sleep.wait(time);
wdriver.quit();
//删除test用户
WebDriver wd = new openBrowser().run();
LoginPage LoginPage_test = new LoginPage(wd);
sleep.wait(time);
wd.manage().window().maximize();
sleep.wait(time);
highlight.Element(wd, LoginPage_test.getusernameLocator());
sleep.wait(time);
LoginPage_test.typeUsername(login_name);
sleep.wait(time);
highlight.Element(wd, LoginPage_test.getpasswordLocator());
sleep.wait(time);
LoginPage_test.typePassword(login_passwd);
sleep.wait(time);
highlight.Element(wd, LoginPage_test.getloginButtonLocator());
sleep.wait(time);
LoginPage_test.clickLogin();
sleep.wait(time);
LoginPage_test.clickusermanagementPage();
sleep.wait(time);
ScreenShot.takeScreenShot("deluser_test_usermanagementPage", wd);
ObjectUserManagement ObjectUserManagement_test = new ObjectUserManagement(wd);
for (int j = 1; j <= 10; j++)
{
ObjectUserManagement_test.clickSelectxlineLocator(String.valueOf(j), modify_name);
}
sleep.wait(time);
highlight.Element(wd, ObjectUserManagement_test.getdelButtonLocator());
sleep.wait(time);
ObjectUserManagement_test.clickDelButtonLocator(ObjectUserManagement_test.getdelButtonLocator());
sleep.wait(time);
ObjectUserManagement_test.clickSaveButtonLocator("/html/body/div[2]/div/div/div[2]/button[2]");
sleep.wait(time*5);
LoginPage_test.clickoperationPage();
sleep.wait(time*3);
ScreenShot.takeScreenShot("del_test_operationPage", wd);
sleep.wait(time);
wd.quit();
//删除admin用户
WebDriver odriver = new openBrowser().run();
LoginPage LoginPage = new LoginPage(odriver);
sleep.wait(time);
odriver.manage().window().maximize();
sleep.wait(time);
highlight.Element(odriver, LoginPage.getusernameLocator());
sleep.wait(time);
LoginPage.typeUsername(root_name);
sleep.wait(time);
highlight.Element(odriver, LoginPage.getpasswordLocator());
sleep.wait(time);
LoginPage.typePassword(root_password);
sleep.wait(time);
highlight.Element(odriver, LoginPage.getloginButtonLocator());
sleep.wait(time);
LoginPage.clickLogin();
sleep.wait(time);
LoginPage.clickusermanagementPage();
sleep.wait(time);
ScreenShot.takeScreenShot("deluser_admin_usermanagementPage", odriver);
ObjectUserManagement ObjectUserManagement = new ObjectUserManagement(odriver);
for (int j = 1; j <= 10; j++)
{
ObjectUserManagement.clickSelectxlineLocator(String.valueOf(j), admin_name);
}
sleep.wait(time);
highlight.Element(odriver, ObjectUserManagement.getdelButtonLocator());
sleep.wait(time);
ObjectUserManagement.clickDelButtonLocator(ObjectUserManagement.getdelButtonLocator());
sleep.wait(time);
ObjectUserManagement.clickSaveButtonLocator("/html/body/div[2]/div/div/div[2]/button[2]");
sleep.wait(time*5);
LoginPage.clickoperationPage();
sleep.wait(time*3);
ScreenShot.takeScreenShot("del_admin_operationPage", odriver);
sleep.wait(time);
odriver.quit();
}
}
} |
Markdown | UTF-8 | 1,319 | 3.484375 | 3 | [] | no_license | # Singleton Design Pattern
Singleton Design Pattern is a creational design pattern and also one of the most commonly used design pattern. This pattern is used when only a single instance of the struct should exist. This single instance is called a singleton object. Some of the cases where the singleton object is applicable:
1. DB instance – we only want to create only one instance of DB object and that instance will be used throughout the application.
2. Logger instance – again only one instance of the logger should be created and it should be used throughout the application.
The singleton instance is created when the struct is first initialized. Usually, there is getInstance() method defined on the struct for which only one instance needs to be created. Once created then the same singleton instance is returned every time by the GetInstance().
## Singleton Design Pattern using sync.Mutex
We need to be very careful and check if the singleton is created both before and after using the Lock.
## Singleton Design Pattern using init function
When the singleton can be created at the start of the program, then
we can use the init-function for the creation.
## Singleton Design Pattern using sync.Once
When we want to delay the creation to when the singleton is first used, then we can use sync.Once. |
Markdown | UTF-8 | 1,814 | 3.21875 | 3 | [] | no_license | # Schema Editing
As noted, initially the Writer schema in a workspace is a mirror image of the source. However, in many cases the user requires the output to have a different data structure.
Schema Editing is the process of altering the destination schema to customize the structure of the output data. One good example is renaming an attribute field in the output. After editing, the source schema still represents ‘what we have’, but the destination schema now truly does represent 'what we want.'
## Editable Components
There are a number of edits that can be performed, including, but not limited to the following.
### Attribute Renaming
Attributes on the destination schema can be renamed, such as renaming POSTALCODE to PSTLCODE.
To rename an attribute open the Feature Type Properties dialog and click the User Attributes tab. Click the attribute to be renamed and enter the new name.
### Attribute Type Changes
Any attribute on the writer schema can have a change of type; for example, changing STATUS from a character field to a number field.
To change an attribute type open the Feature Type Properties dialog and click the User Attributes tab. Use the Data Type field to change the type of an attribute.
### Feature Type Renaming
To rename a destination feature type (for example, rename PostalAddress to Addresses) open the Feature Type Properties dialog. Click the General tab. Click in the Feature Type Name field and edit the name as required.
### Geometry Type Changes
To change the permitted geometry for a feature type, (for example, change the permitted geometries from lines to points) open the Feature Type Properties dialog. Click the General tab. Choose from the list of permitted geometries.
This field is only available where the format requires a decision on geometry type.
|
Markdown | UTF-8 | 2,699 | 2.859375 | 3 | [
"MIT"
] | permissive | # 获取指定签到表的签到情况
## 接口信息
**API Path**
/record/:id
**请求协议**
HTTP
**请求方法**
GET
**相关人员**
负责人:RoseAT
创建人:RoseAT
最后编辑人:RoseAT
**REST参数**:
| 参数名 | 说明 | 必填 | 类型 | 值可能性 | 限制 | 示例 |
| :------------ | :------------ | :------------ | :------------ | :------------ | :------------ | :------------ |
|id|签到表的signid|是|[string]| || |
**响应内容**:
**返回结果**
Json
Object
| 参数名 | 说明 | 必填 | 类型 | 值可能性 | 限制 | 示例 |
| :------------ | :------------ | :------------ | :------------ | :------------ | :------------ | :------------ |
|code|状态码|是|[number]|0:成功|| |
|msg|状态信息|是|[string]| || |
|data|响应数据|是|[object]| || |
|data>>records|所有签到记录|是|[array]| || |
|data>>records>>recordId|记录的唯一标识|是|[string]| || |
|data>>records>>siginId|签到表|是|[string]| || |
|data>>records>>peopleId|关联活动成员id|是|[string]| || |
|data>>records>>activityId|所属活动id|是|[string]| || |
|data>>records>>userId|所属用户的唯一id|是|[string]| || |
|data>>records>>name|签到用户的名字|是|[string]| || |
|data>>records>>lastTime|最后签到时间|是|[string]| || |
|data>>records>>location|位置信息|是|[string]| || |
|data>>records>>method|签到方式|是|[number]| || |
|data>>records>>photo|拍照方式的图片|是|[string]| || |
|data>>records>>status|签到情况|是|[string]| || |
|data>>records>>tips|批注信息教师填入|否|[string]| || |
|data>>records>>rank|签到排名|是|[number]| || |
**数据结构**:
defaultResponse
| 参数名 | 说明 | 必填 | 类型 | 值可能性 | 示例 |
| :------------ | :------------ | :------------ | :------------ | :------------ | :------------ |
|code|状态码|是|[number]|0:成功||
|msg|状态信息|是|[string]|||
|data|响应数据|是|[object]|||
record
| 参数名 | 说明 | 必填 | 类型 | 值可能性 | 示例 |
| :------------ | :------------ | :------------ | :------------ | :------------ | :------------ |
|recordId|记录的唯一标识|是|[string]|||
|siginId|签到表|是|[string]|||
|peopleId|关联活动成员id|是|[string]|||
|activityId|所属活动id|是|[string]|||
|userId|所属用户的唯一id|是|[string]|||
|name|签到用户的名字|是|[string]|||
|lastTime|最后签到时间|是|[string]|||
|location|位置信息|是|[string]|||
|method|签到方式|是|[number]|||
|photo|拍照方式的图片|是|[string]|||
|status|签到情况|是|[string]|||
|tips|批注信息教师填入|否|[string]|||
|rank|签到排名|是|[number]|||
|
C++ | UTF-8 | 1,067 | 3.078125 | 3 | [] | no_license | /*
===================================================================================
* File Name: 24 - Swap Nodes in Pairs.cpp
* Description: https://leetcode.com/problems/swap-nodes-in-pairs/
* Author: Stoney
* Category: 链表
* Note:
*
* Version: 1.0
* Submit Time: 2016/02/14
* Run Time: 4ms, beats 1.74%
* Solutions:
===================================================================================
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode ans(0);
ans.next = head;
ListNode* pre = &ans, *cur = head;
while(cur!=NULL && cur->next!=NULL){
pre->next = cur->next;
cur->next = cur->next->next;
pre->next->next = cur;
cur = pre->next->next->next;
pre = pre->next->next;
}
return ans.next;
}
};
|
PHP | UTF-8 | 213 | 2.625 | 3 | [] | no_license | <?php // Check if the nick is unique
$sql = "SELECT * FROM users WHERE nick='$nick'";
if ($result = $db->query($sql)) {
$usersNum = $result->num_rows;
if ($usersNum > 0) {
$output = "not-unique-error";
}
}
?> |
Python | UTF-8 | 1,906 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | import pandas as pd
import numpy as np
from sklearn.neighbors import KDTree
#import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import seaborn as sns
import random
data = pd.read_csv("1.txt", sep = ",", header = None)
del data[0]
del data[1]
test = pd.read_excel("2.xlsx", header = None)
del test[0]
del test [1]
train_price = data[20]
train_price=train_price
del data[20]
test_price = test[20]
test_price=test_price.values
del test[20]
train_scaled=(data-data.min())/(data.max()-data.min())
train_scaled=train_scaled.values
test_scaled=(test-test.min())/(test.max()-test.min())
test_scaled=test.values
tree = KDTree(train_scaled)
nearest_dist, nearest_ind = tree.query(test_scaled[13].reshape(1, -1), k = 3)
def haha1(niubi, num = 1.0, niubi1 = 0.1):
return num / (niubi + niubi1)
def wk_nnc(kdtree, test_point, target, k = 25,
weight_fun = haha1):
nearest_dist, nearest_ind = kdtree.query(test_point, k = k)
avg = 0.0
totalniubi = 0.0
for i in range(k):
niubi = nearest_dist[0][i]
idx = nearest_ind[0][i]
niubi1 = weight_fun(niubi)
avg += niubi1 * target[idx]
totalniubi += niubi1
avg = round(avg / totalniubi)
return avg
def testalgorithm(algo, kdtree, testset, target, test_target):
error = 0.0
for row in range(len(testset)):
guess = algo(kdtree, testset[row].reshape(1, -1), target)
error += (test_target[row] - guess) ** 2
return round(np.sqrt(error / len(testset)))
random.seed(1191)
ex = random.sample(range(len(test_price)), 5)
print("predicted",";", "actual", " ;", "error")
for i in ex:
res = wk_nnc(tree, test_scaled[i].reshape(1, -1), train_price)
print(res,
" ;",
test_price[i],
" ;",
abs(test_price[i] - res))
print(testalgorithm(wk_nnc, tree, test_scaled, train_price, test_price))
|
Java | UTF-8 | 2,186 | 2.546875 | 3 | [
"MIT"
] | permissive | package cz.muni.fi.pa165.entity;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
/**
* User entity
*
* @author Petr Valenta
*/
@Entity
@Table(name="Users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@NotNull
@Email
@Column(nullable = false, unique = true)
private String email;
@NotNull
private String firstName;
@NotNull
private String surname;
@NotNull
private boolean administrator;
@NotNull
private String passwordHash;
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public boolean isAdministrator() {
return administrator;
}
public void setAdministrator(boolean admin) {
this.administrator = admin;
}
public String getPasswordHash() {
return passwordHash;
}
public void setPasswordHash(String passwordHash) {
this.passwordHash = passwordHash;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !(o instanceof User)) {
return false;
}
final User user = (User) o;
if (!user.getEmail().equals(getEmail())) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash(email);
}
}
|
C++ | UTF-8 | 862 | 3.203125 | 3 | [
"MIT"
] | permissive | #include <cassert>
#include <string>
#include <binary_median_heap.hpp>
//função dara os testes
void test_median_heap(){
BinaryMedianHeap<std::string> heap {};
heap.insert(11,"glória ao príncipe da paz");
heap.insert(10,"Jesus");
heap.insert(12,"vida longa");
heap.insert(13,"vida");
heap.insert(13,"victor");
auto test = heap.median_element();
if(test){
auto [prio,elem] = *test;
//std::cout<<"Priority: "<<prio<<"-Element: "<<elem<<std::endl;
assert(prio == 12);
assert(elem == "vida longa");
}
heap.median_extract();
auto test2 = heap.median_element();
if(test2){
auto [prio,elem] = *test2;
//std::cout<<"Priority: "<<prio<<"-Element: "<<elem<<std::endl;
assert(prio == 11);
assert(elem == "glória ao príncipe da paz");
}
}
int main(){
test_median_heap();
} |
Java | UTF-8 | 1,118 | 3.328125 | 3 | [] | no_license | /*Dylan Keeton Sonal Jain
* DK23765 SJ23277
* Section: 16165
* EE 422C- Assignment 3
*/
package Assignment3;
public class Grocery extends Item {
private boolean perishable;
//=====================================================================================
public Grocery(String n, double p, int q, int w, boolean b) {
super(n, p, q, w);
perishable = b;
}
public boolean isPerishable() {
return perishable;
}
public void setPerishable(boolean perishable) {
this.perishable = perishable;
}
float calculatePrice ()
{
float final_price = 0;
final_price += quantity * price;
final_price += 20*weight*quantity;
if(perishable)
final_price += (20*weight*quantity)*.2;
return final_price;
}
void printItemAttributes ()
{
if(perishable)
System.out.printf("Name: %s Price: $%.02f Quantity: %d Weight: %d lb(s) PERISHABLE\nTotal Charge: $%.02f\n", name, price, quantity, weight, calculatePrice());
else
System.out.printf("Name: %s Price: $%.02f Quantity: %d Weight: %d lb(s) NOTPERISHABLE\nTotal Charge: $%.02f\n", name, price, quantity, weight, calculatePrice());
}
}
|
C | UTF-8 | 532 | 2.90625 | 3 | [] | no_license | #include<stdio.h>
int main(){
int idNum[18] = {0};
int seed[17] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
char result[11] = {'1','0','X','9','8','7','6','5','4','3','2'};
int sum = 0;
int index = 0;
long long id = 0;
scanf("%lld", &id);
printf("%lld\n",id);
for(int i = 17; i >= 0; i--){
idNum[i] = id % 10;
id /= 10;
}
for(int i = 0; i < 17; i++){
sum = sum + idNum[i] * seed[i];
}
index = sum % 11;
printf("%c\n", result[index]);
}
|
Ruby | UTF-8 | 936 | 2.84375 | 3 | [] | no_license | RESULT_1 = {
:length => 1,
:location => 1,
:prime => 2,
:position => 0
}
RESULT_2 = {
:length => 2,
:location => 3,
:prime => 23,
:position => 16
}
describe EulerPrimeJob do
describe "#execute" do
it "is only valid with integers" do
job = EulerPrimeJob.new("a string", 1)
expect(job).to_not be_valid
job2 = EulerPrimeJob.new(1, 1)
expect(job2).to be_valid
end
it "finds the first prime" do
job = EulerPrimeJob.new(RESULT_1[:location], RESULT_1[:length])
job.execute
expect(job.result[:prime]).to eq(RESULT_1[:prime])
expect(job.result[:position]).to eq(RESULT_1[:position])
end
it "finds a later, longer prime" do
job = EulerPrimeJob.new(RESULT_2[:location], RESULT_2[:length])
job.execute
expect(job.result[:prime]).to eq(RESULT_2[:prime])
expect(job.result[:position]).to eq(RESULT_2[:position])
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.