language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 1,223 | 2.953125 | 3 | [] | no_license | import gym
from typing import TypeVar
import random
Action = TypeVar('Action')
class RandomActionWrapper(gym.ActionWrapper):
def __init__(self, env, epsilon = 0.1):
super(RandomActionWrapper, self).__init__(env)
self.epsilon = epsilon
def action(self, action: Action) -> Action:
if random.random() < self.epsilon:
print('Random!')
return self.env.action_space.sample()
return action
def print_env_info(env):
print(obs)
print(env.action_space)
print(env.observation_space)
print(env.action_space.sample())
print(env.observation_space.sample())
if __name__ == '__main__':
env = RandomActionWrapper(gym.make('CartPole-v0'))
env = gym.wrappers.Monitor(env, 'recording', force=True)
for i_episode in range(30):
obs = env.reset()
total_reward, total_steps = 0.0, 0
while True:
env.render()
action = env.action_space.sample()
obs, reward, done, _ = env.step(action)
total_reward += reward
total_steps += 1
#if done:
# break
print('episode steps: %d total reward: %.2f' % (total_steps, total_reward)) |
Markdown | UTF-8 | 4,269 | 3.46875 | 3 | [] | no_license | # CLASS 11 READING NOTES
- [Home](https://seidomo.github.io/201-reading-notes/home)
## IMAGES
Controlling the size and alignment of
your images using CSS keeps rules that
affect the presentation of your page in
the CSS and out of the HTML markup.
You can also achieve several interesting effects using
background images. In this chapter you will learn how to:
- Specify the size and alignment of an image using
- Add background images to boxes
- Create image rollovers in CSS
You can control the size of an
image using the width and
height properties in CSS, just
like you can for any other box.
Specifying image sizes helps
pages to load more smoothly
because the HTML and CSS
code will often load before the
images, and telling the browser
how much space to leave for an
image allows it to render the rest
of the page without waiting for
the image to download.
You might think that your site
is likely to have images of all
different sizes, but a lot of sites
use the same sized image across
many of their pages.
For example, an e-commerce site
tends to show product photos
at the same size. Or, if your site
is designed on a grid, then you
might have a selection of image
sizes that are commonly used on
all pages, such as:
- Small portrait: 220 x 360
- Small landscape: 330 x 210
- Feature photo: 620 x 400
Whenever you use consistently
sized images across a site,
you can use CSS to control
the dimensions of the
images, instead of putting the
dimensions in the HTML.
First you need to determine the
sizes of images that will be used
commonly throughout the site,
then give each size a name.
For example:
- small
- medium
- large
Where the <img> elements
appear in the HTML, rather
than using width and height
attributes you can use these
names as values for the class
attribute.
In the CSS, you add selectors for
each of the class names, then
use the CSS width and height
properties to control the image
dimensions.
## REAPINTING IMAGES
- repeat
The background image is
repeated both horizontally and
vertically (the default way it
is shown if the backgroundrepeat property isn't used).
- repeat-x
The image is repeated
horizontally only (as shown in
the first example on the left).
- repeat-y
The image is repeated vertically
only.
- no-repeat
The image is only shown once.
The background-attachment
property specifies whether a
background image should stay in
one position or move as the user
scrolls up and down the page. It
can have one of two values:
- fixed
The background image stays in
the same position on the page.
- scroll
The background image moves
up and down as the user scrolls
up and down the page.
## Designing Navigation
Site navigation not only helps people find where they want to go, but also
helps them understand what your site is about and how it is organized.
Good navigation tends to follow these principles...
- Concise
Ideally, the navigation should
be quick and easy to read. It is
a good idea to try to limit the
number of options in a menu to
no more than eight links. These
can link to section homepages
which in turn link to other pages.
- Clear
Users should be able to predict
the kind of information that
they will find on the page
before clicking on the link.
Where possible, choose single
descriptive words for each link
rather than phrases.
- Selective
The primary navigation should
only reflect the sections or
content of the site. Functions
like logins and search, and legal
information like terms and
conditions and so on are best
placed elsewhere on the page.
- Context
Good navigation provides
context. It lets the user know
where they are in the website at
that moment. Using a different
color or some kind of visual
marker to indicate the current
page is a good way to do this.
- Interactive
Each link should be big enough
to click on and the appearance
of the link should change when
the user hovers over each item
or clicks on it. It should also
be visually distinct from other
content on the page.
- Consistent
The more pages a site contains,
the larger the number of
navigation items there will be.
Although secondary navigation
will change from page to page,
it is best to keep the primary
navigation exactly the same.
- [Previous](https://seidomo.github.io/201-reading-notes/class10)
|
Python | UTF-8 | 1,812 | 2.984375 | 3 | [] | no_license | import numpy as np
from motor import Motor
from tkinter import *
import tkinter.font
######################################################################################
# L298N Module 1
# front motor right En1 = Gpio 22, In1 = Gpio 27, In2 = Gpio 17 Speed sensor = 5 +
# back motor right En2 = Gpio 2, In1 = Gpio 3, In2 = Gpio 4 Speed sensor = 10 +
######################################################################################
######################################################################################
# L298N Module 2
# front motor left En1 = Gpio 14, In1 = Gpio 15, In2 = Gpio 18 Speed sensor = 11
# back motor left En2 = Gpio 25, In1 = Gpio 24, In2 = Gpio 23 Speed sensor = 9
######################################################################################
front_right = Motor(22, 27, 17)
back_right = Motor(2, 3, 4)
front_left = Motor(25, 24, 23)
back_left = Motor(14, 15, 18)
win = Tk()
win.title("Motor control")
myFont = tkinter.font.Font(family = "Hevvetica", size = 12, weight = "bold")
#
code = Entry(win, font = myFont, width = 10)
code.grid(row = 2, column = 1)
def motorEnable():
setSpeed = int(code.get())
front_right.moveF(setSpeed)
def motorDisable():
front_right.stop()
def close_win():
front_right.stop()
win.destroy()
def main():
print("main function")
EnableMotorBtn = Button(win, text = "Motor On", font = myFont, command = motorEnable, bg = 'bisque2', height = 1, width = 24)
EnableMotorBtn.grid(row = 0, column = 1)
DisableMotorBtn = Button(win, text = "Motor Off", font = myFont, command = motorDisable, bg = 'bisque2', height = 1, width = 24)
DisableMotorBtn.grid(row = 1, column = 1)
win.protocol("WM_DELETE_WINDOW", close_win)
win.mainloop()
if __name__ == "__main__":
main() |
Java | UTF-8 | 3,022 | 2.21875 | 2 | [] | no_license | package com.example.ecommerce;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
public static final String TAG="TAG+++";
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference users = database.getReference("ecommerce-2345b");
Toolbar toolbar;
EditText username;
EditText password;
// Context ctx=getApplicationContext();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void login(View view){
username= (EditText)findViewById(R.id.editTextUsername);
password= (EditText)findViewById(R.id.editTextPassword);
signin(username.getText().toString() , password.getText().toString());
{
// Toast toast = Toast.makeText(this,"Logged In Successfully",Toast.LENGTH_SHORT);
// toast.show();
// Intent intent= new Intent(this,Register.class);
// startActivity(intent);
}
}
public void registerpage(View view){
Intent i = new Intent(MainActivity.this,Register.class);
startActivity(i);
}
private void signin(final String username, final String password) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(username).exists()){
if(!username.isEmpty()){
User login=dataSnapshot.child(username).getValue(User.class);
Log.d(TAG, String.valueOf(login));
if(login.getPassword().equals(password)){
Toast t=Toast.makeText(MainActivity.this,"SuccessLogin...,",Toast.LENGTH_LONG);
t.show();
}
else{
Toast.makeText(MainActivity.this,"Failed....",Toast.LENGTH_LONG).show();
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
|
Java | UTF-8 | 1,072 | 1.9375 | 2 | [] | no_license | package p004bo.app;
import com.appboy.models.ResponseError;
import com.appboy.support.AppboyLogger;
import org.json.JSONException;
import org.json.JSONObject;
/* renamed from: bo.app.bv */
public final class C0393bv {
/* renamed from: a */
private static final String f214a = AppboyLogger.getAppboyLogTag(C0393bv.class);
/* renamed from: b */
private final ResponseError f215b;
public C0393bv(JSONObject jSONObject) {
ResponseError responseError;
JSONObject optJSONObject = jSONObject.optJSONObject("error");
if (optJSONObject != null) {
try {
responseError = new ResponseError(optJSONObject);
} catch (JSONException e) {
AppboyLogger.m1740w(f214a, "Encountered exception processing ResponseError: " + optJSONObject.toString(), e);
}
this.f215b = responseError;
}
responseError = null;
this.f215b = responseError;
}
/* renamed from: a */
public ResponseError mo6856a() {
return this.f215b;
}
}
|
Shell | UTF-8 | 1,289 | 3.671875 | 4 | [] | no_license | #!/usr/bin/env bash
#=========================================================================================
# Variables
#=========================================================================================
CERT_DIR="/etc/letsencrypt/live/${DOMAIN}"
SSL_CERT="${CERT_DIR}/fullchain.pem"
SSL_KEY="${CERT_DIR}/privkey.pem"
DO_CREDS="/etc/letsencrypt/digitalocean.ini"
PROPAGATION="60"
#=========================================================================================
# Functions
#=========================================================================================
log() {
echo -e "$(date "+%b %d %T")" "$(basename "$0")" - "$@"
}
create_certs() {
log "Creating Certificate for [${DOMAIN}]"
certbot certonly --dns-digitalocean \
--dns-digitalocean-credentials "${DO_CREDS}" \
--dns-digitalocean-propagation-seconds "${PROPAGATION}" \
--domain "${DOMAIN}" --domain "*.${DOMAIN}" -m "${EMAIL}" \
--agree-tos --non-interactive
}
renew_certs() {
while true
do
certbot renew
sleep 86400
done
}
##########################################################################################
if [[ ! -f ${SSL_CERT} ]] || [[ ! -f ${SSL_KEY} ]]; then
log "SSL Certificates do NOT exist"
create_certs
fi
renew_certs
|
Python | UTF-8 | 3,084 | 2.984375 | 3 | [] | no_license | from pprint import pprint
import matplotlib.pyplot as plt
import numpy as np
import math
import time
def gauss(A):
n = len(A)
for i in range(0, n):
maxEl = abs(A[i][i])
maxRow = i
for k in range(i + 1, n):
if abs(A[k][i]) > maxEl:
maxEl = abs(A[k][i])
maxRow = k
for k in range(i, n + 1):
tmp = A[maxRow][k]
A[maxRow][k] = A[i][k]
A[i][k] = tmp
for k in range(i + 1, n):
c = -A[k][i] / A[i][i]
for j in range(i, n + 1):
if i == j:
A[k][j] = 0
else:
A[k][j] += c * A[i][j]
x = [0 for i in range(n)]
for i in range(n - 1, -1, -1):
x[i] = A[i][n] / A[i][i]
for k in range(i - 1, -1, -1):
A[k][n] -= A[k][i] * x[i]
return x
x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [5.95, 20.95, 51.9, 105, 186, 301, 456.1, 657.1]
def ls_approx(x, y, degree_of_polynom):
x_degrees = []
for i in range(0, len(x)):
x_degrees.append([x[i]])
for key, value in enumerate(x):
for i in range(1, (degree_of_polynom * 2)):
x_degrees[key].append(x_degrees[key][i - 1] * value)
#pprint(x_degrees)
x_degrees_sum = []
for degree in range(0, (degree_of_polynom * 2)):
# for el in x_degrees:
# degree_sum += el[degree - 1]
pprint(degree)
x_degrees_sum.append(sum([i[degree] for i in x_degrees]))
pprint(len(x_degrees_sum))
x_degrees_sum.insert(0, float(len(x)))
lin_eq = [[0 for i in range(degree_of_polynom + 1)] for j in range(degree_of_polynom + 1)]
for i in range(degree_of_polynom + 1):
for j in range(degree_of_polynom + 1):
lin_eq[i][j] = x_degrees_sum[i + j]
#pprint(lin_eq)
B = [sum(y)]
for i in range(0, degree_of_polynom):
b = 0
for j in range(0, len(x)):
b += y[j] * x_degrees[j][i]
B.append(b)
# for i in range(degree_of_polynom + 1):
# lin_eq[i].append(B[i])
return np.linalg.solve(lin_eq, B)
if __name__ == "__main__":
# pprint(gauss(lin_eq))
# x1 = [-2.0]
# y1 = []
#
# x2 = [-3.2, -2.1, 0.4, 0.7, 2, 2.5, 2.777]
# y2 = [10, -2, 0, -7, 7, 0, 0]
#
x1 = [-2.0]
y1 = []
summ = -2.0
for i in range(0, 8):
summ += 0.5
x1.append(summ)
for x in x1:
y1.append(math.sin(5 * x) * 2.71828183 ** x)
x1 = [0.0, 1.0, 4.0]
y1 = [3, 1.0, -2.0]
# x1 = [-3.2, -2.1, 0.4, 0.7, 2, 2.5, 2.777]
# y1 = [10, -2, 0, -7, 7, 0, 0]
# pprint(x1)
# pprint(y1)
start_time = time.time()
coeffs = ls_approx(x1, y1, 2)
pprint(coeffs)
# pprint("Execution time:" + str(time.time() - start_time))
#
# pprint(coeffs)
xs = np.linspace(-4, 4, 100)
ys = np.polynomial.polynomial.polyval(xs, coeffs)
plt.scatter(x1, y1, edgecolors='blue')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(xs, ys, color='red')
plt.show()
|
JavaScript | UTF-8 | 585 | 2.53125 | 3 | [] | no_license | export const validateColor = (weather) => {
switch (weather) {
case 'Clouds':
return require('../../assets/background/clouds.jpg');
case 'Haze':
return require('../../assets/background/haze.jpg')
case 'Rain':
return require('../../assets/background/rain.jpg')
case 'Fog':
return require('../../assets/background/haze.jpg')
case 'Clear':
return require('../../assets/background/clear.jpg')
default:
return require('../../assets/background/clouds.jpg')
}
}
|
JavaScript | UTF-8 | 1,629 | 2.71875 | 3 | [
"MIT"
] | permissive | function solve() {
return function (selector) {
var select = $(selector),
options = select.find('option');
select.hide();
var dropdown = $('<div />')
.addClass('dropdown-list');
var current = $('<div />')
.addClass('current')
.attr('data-value','')
.html(options.eq(0).html());
var optionsContainer = $('<div />')
.addClass('options-container')
.css('position','absolute')
.css('display','none');
for(var i=0;i<options.length;i++){
var newOption = $('<div />')
.addClass('dropdown-item')
.attr('data-value',options.eq(i).attr('value'))
.attr('data-index',i)
.html(options.eq(i).html());
optionsContainer.append(newOption);
}
addEvents();
dropdown.append(select.clone());
dropdown.append(current);
dropdown.append(optionsContainer);
select.replaceWith(dropdown);
function addEvents(){
dropdown.on('click','.current',function(){
optionsContainer.css('display','');
});
dropdown.on('click','.dropdown-item',function(ev){
var dropdownItem = $(ev.target);
current.attr('data-value',dropdownItem.attr('data-value'));
current.html(dropdownItem.html());
optionsContainer.css('display','none');
$(selector).val(dropdownItem.attr('data-value'));
});
}
};
}
module.exports = solve; |
Python | UTF-8 | 1,749 | 2.6875 | 3 | [] | no_license | __author__ = 'jsh0x'
__version__ = '1.0.0'
from sys import maxsize
from secrets import randbelow
from string import digits, ascii_letters, punctuation
import numpy as np
def generate_char_map(key_length=6):
retval = {}
chars = digits+ascii_letters+punctuation
val = set()
while len(val) < 94:
val.add(int(str(randbelow(maxsize))[:key_length]))
for k,v in zip(val, chars):
retval[k] = v
return retval
def generate_key():
retval = 0
while len(str(retval)) < 8:
retval = randbelow(maxsize)
return retval
def encrypt(char_map:dict, key:int, value:str):
#TODO: Similarity return for NaCl
if type(char_map) is not dict: raise TypeError
if type(key) is not int: raise TypeError
if type(value) is not str: raise TypeError
if len(char_map) != 94: raise IndexError
for k,v in char_map.items():
if type(k) is not int: raise TypeError
if type(v) is not str: raise TypeError
if k >= maxsize: raise KeyError
if len(v) > 2: raise ValueError
retval = ""
for char in value:
for k, v in char_map.items():
if v == char:
k = np.int64(k)
key = np.int64(key)
retval += np.binary_repr(np.add(k, key))
return int(retval, 2)
def decrypt(char_map:dict, key:int, value:str):
if type(char_map) is not dict: raise TypeError
if type(key) is not int: raise TypeError
if type(value) is not str: raise TypeError
if len(char_map) != 94: raise IndexError
for k,v in char_map.items():
if type(k) is not int: raise TypeError
if type(v) is not str: raise TypeError
if k >= maxsize: raise KeyError
if len(v) > 2: raise ValueError
step = 19
value = np.binary_repr(np.int(value))
retval = ""
for i in range(0, len(value)-step, step):
retval += char_map[np.subtract(int(value[i:i+step], base=2), key)]
return retval |
C++ | UTF-8 | 473 | 3.546875 | 4 | [] | no_license | // C11Q08.cpp
/* Create a function that takes a char& argument and modifies that argument. In main( ), print out a char
variable, call your function for that variable, and print it out again to prove to yourself that it has
been changed. How does this affect program readability? */
#include <iostream>
using namespace std;
void foo(char& c1) {
c1 = 'x';
}
int main() {
char c2 = 'j';
cout << c2 << endl;
foo(c2);
cout << c2 << endl;
}
|
C++ | UTF-8 | 837 | 2.71875 | 3 | [] | no_license | #include "interval.h"
#include <cgv/base/register.h>
#include <libs/cgv_gl/gl/gl.h>
interval::interval(float a, float b)
{
if (a < b) {
min = a;
max = b;
invalid = false;
}
else {
a = 0;
b = 0;
invalid = true;
}
}
interval interval::intersectIntervals(interval other)
{
if (this->isInvalid() || other.isInvalid())
{
interval a = interval(float(1.0), float(0.0));
return a;
}
if (cgv::math::maximum(min, other.get_min()) > cgv::math::minimum(max,other.get_max()))
{
interval a = interval(float(1.0),float(0.0));
return a;
}
else {
return interval(cgv::math::maximum(min, other.get_min()), cgv::math::minimum(max, other.get_max()));
}
}
float interval::get_min()
{
return min;
}
float interval::get_max()
{
return max;
}
bool interval::isInvalid()
{
return invalid;
}
interval::~interval()
{
}
|
Python | UTF-8 | 8,001 | 2.765625 | 3 | [] | no_license | import numpy as np
import pandas as pd
import random
from .PreProcessing import get_HistoricalData_FX
###############################################################################
# COMPUTE LOG RETURNS #
###############################################################################
def calculate_LogReturns_FX( df_HistoricalMarketData_Exchange,
ccy_FOR ,
ccy_DOM ):
df_historical = get_HistoricalData_FX( df_HistoricalMarketData_Exchange = df_HistoricalMarketData_Exchange,
ccy_FOR = ccy_FOR,
ccy_DOM = ccy_DOM)
if df_historical.empty:
return np.array([])
df_historical_sorted = df_historical.copy() # make a deepcopy, needed for sorting
df_historical_sorted['date'] = pd.to_datetime(df_historical_sorted['date'], format='%Y/%m/%d')
df_historical_sorted = df_historical_sorted.sort_values(by='date')
df_historical_sorted['log_return'] = np.log(df_historical_sorted['rate']) - \
np.log(df_historical_sorted['rate'].shift(1))
# remove first row, because the log_return is NaN
df_historical_sorted = df_historical_sorted.drop(df_historical_sorted.index[0])
df_historical_sorted = df_historical_sorted.reset_index(drop=True)
return df_historical_sorted['log_return'].values
###############################################################################
# READ RANDOM INDICES #
###############################################################################
def read_RandomIndices( df_RandomIndices,
n_indices ,
rowSelection ,
n_logReturns ):
"""
get RandomIndices from DataFrame that was created based on csv file.
There's two choices for the RandomIndex file:
[1] Read Integers (Return Picks)
[2] Read Uniform distribution in [0,1] that needs to be converted to [1]
This function converts [2] to [1] if necessary, namely if index is 0 < idx < 1
The index_array that is returned is in range [0 , n_logReturns-1]
"""
if n_indices > df_RandomIndices.shape[0]:
print('[ERROR]. Not enough RandomIndices provided to select n_indices')
print(' nRows(df_RandomIndices) = ' + str(df_RandomIndices.shape[0]))
print(' n_indices = ' + str(n_indices))
print(' Skipping FX_rate')
return(np.array([]))
first_RandomValue = df_RandomIndices[rowSelection].values[0]
last_RandomValue = df_RandomIndices[rowSelection].values[-1]
#----------------#
# float values #
#----------------#
if first_RandomValue > 0.0 and first_RandomValue < 1.0 and \
last_RandomValue > 0.0 and last_RandomValue < 1.0:
idx_selected = df_RandomIndices[rowSelection].values
idx_selected = (np.floor(idx_selected*n_logReturns)).astype(int)
#----------------#
# integer values #
#----------------#
else:
idx_selected = df_RandomIndices[rowSelection].values-1
# every value that is larger than max_value will be replaced, so that range = [0 , n_logReturns-1]
idx_selected[idx_selected >= n_logReturns] = n_logReturns-1
return idx_selected
###############################################################################
# COMPUTE RANDOM INDICES #
###############################################################################
def select_RandomIndices( n_indices,
n_LogReturns):
idx_selected = [ random.randint(0, n_LogReturns-1) for x in range(0, n_indices) ]
return idx_selected
###############################################################################
# COMPUTE Ito TERM #
###############################################################################
def calculate_ItoTerm( arr_logReturns, n):
std = np.std(arr_logReturns) # computes population std by default
arr_ito_term = -0.5 * std**2 * np.arange(1, n+1)
return arr_ito_term
###############################################################################
# COMPUTE Shift TERM #
###############################################################################
def calculate_ShiftTerm( arr_logReturnsRescaled,
stressed_vol ,
n ):
mean_rescaled = np.mean(arr_logReturnsRescaled)
arr_shift = (-0.5 * stressed_vol**2 * np.arange(1, n+1)) - \
(mean_rescaled*np.arange(1, n+1))
return arr_shift
###############################################################################
# COMPUTE 1 PRIIPS PATH (Fav, Mod, Unfav) #
###############################################################################
def calculate_PRIIPsPath_FMU( arr_randomIndices,
arr_logReturns ,
arr_ItoTerm ,
spot_rate ):
arr_returns = arr_logReturns[arr_randomIndices]
arr_returns_cumsum = np.cumsum(arr_returns)
arr_underlying = spot_rate*np.exp(arr_returns_cumsum + arr_ItoTerm)
return arr_underlying
###############################################################################
# COMPUTE 1 PRIIPS PATH (Stressed) #
###############################################################################
def calculate_PRIIPsPath_Stressed( arr_randomIndices ,
arr_logReturnsRescaled,
arr_shiftTerm ,
spot_rate ):
arr_returns = arr_logReturnsRescaled[arr_randomIndices]
arr_returns_cumsum = np.cumsum(arr_returns)
arr_underlying = spot_rate*np.exp(arr_returns_cumsum + arr_shiftTerm)
return arr_underlying
###############################################################################
# COMPUTE THE STRESSED VOLATILITY #
###############################################################################
def calculate_stressed_vol(arr_returns, window_length):
arr_rolling_returns = (rolling_window(arr_returns, window_length+1))
arr_rolling_vol = np.array([])
for arr_ret_window in arr_rolling_returns:
arr_rolling_vol = np.append(arr_rolling_vol, np.std(arr_ret_window))
stressed_vol = None
# the percentile used for rolling vol depends on window length
if (window_length == 12) or \
(window_length == 16) or \
(window_length == 63):
stressed_vol = np.percentile(arr_rolling_vol, 90)
if (window_length == 6) or \
(window_length == 8) or \
(window_length == 21):
stressed_vol = np.percentile(arr_rolling_vol, 99)
return stressed_vol
###############################################################################
# COMPUTE A ROLLING WINDOW OF ARRAY #
###############################################################################
def rolling_window(arr, window):
idx_windowStart = 0
idx_windowEnd = window
arr_window = np.array([])
list_window = []
while True:
if len(arr) < (idx_windowStart+idx_windowEnd):
break
else:
new_window = arr[idx_windowStart : (idx_windowStart+idx_windowEnd)]
list_window.append(new_window)
idx_windowStart += 1
return np.array(list_window)
|
C++ | UTF-8 | 4,322 | 2.53125 | 3 | [] | no_license | // Copyright (C) 2014 Caleb Lo
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// LogisticRegression class functions implement modules that are then passed
// to an unconstrained minimization algorithm.
#include "logistic_regression.h"
// This function is applied to vectors.
arma::vec LogisticRegression::ComputeSigmoid(const arma::vec sigmoid_arg) {
const arma::vec kSigmoid = 1/(1+arma::exp(-sigmoid_arg));
return kSigmoid;
}
// Arguments "theta" and "grad" are updated by nlopt.
// "theta" corresponds to the optimization parameters.
// "grad" corresponds to the gradient.
double LogisticRegression::ComputeCost(const std::vector<double> &theta,
std::vector<double> &grad,const Data &data) {
const int kNumTrainEx = data.num_train_ex();
assert(kNumTrainEx >= 1);
const int kNumFeatures = data.num_features();
assert(kNumFeatures >= 1);
arma::vec nlopt_theta = arma::randu<arma::vec>(kNumFeatures+1,1);
// Uses current value of "theta" from nlopt.
for(int feature_index=0; feature_index<(kNumFeatures+1); feature_index++)
{
nlopt_theta(feature_index) = theta[feature_index];
}
set_theta(nlopt_theta);
const arma::mat kTrainingFeatures = data.training_features();
const arma::vec kTrainingLabels = data.training_labels();
const arma::vec kSigmoidArg = kTrainingFeatures*theta_;
const arma::vec kSigmoidVal = ComputeSigmoid(kSigmoidArg);
const arma::vec kCostFuncVal = (-1)*(kTrainingLabels%arma::log(kSigmoidVal)+\
(1-kTrainingLabels)%arma::log(1-kSigmoidVal));
const double kJTheta = sum(kCostFuncVal)/kNumTrainEx;
// Updates "grad" for nlopt.
const int kReturnCode = this->ComputeGradient(data);
for(int feature_index=0; feature_index<(kNumFeatures+1); feature_index++)
{
grad[feature_index] = gradient_(feature_index);
}
return kJTheta;
}
// The number of training examples should always be a positive integer.
int LogisticRegression::ComputeGradient(const Data &data) {
const int kNumTrainEx = data.num_train_ex();
assert(kNumTrainEx >= 1);
const int kNumFeatures = data.num_features();
assert(kNumFeatures >= 1);
const arma::mat kTrainingFeatures = data.training_features();
const arma::vec kTrainingLabels = data.training_labels();
const arma::vec kSigmoidArg = kTrainingFeatures*theta_;
const arma::vec kSigmoidVal = ComputeSigmoid(kSigmoidArg);
arma::vec gradient_array = arma::zeros<arma::vec>(kNumFeatures+1);
for(int feature_index=0; feature_index<(kNumFeatures+1); feature_index++)
{
const arma::vec gradient_term = \
(kSigmoidVal-kTrainingLabels) % kTrainingFeatures.col(feature_index);
gradient_array(feature_index) = sum(gradient_term)/kNumTrainEx;
}
set_gradient(gradient_array);
return 0;
}
// The number of training examples should always be a positive integer.
int LogisticRegression::LabelPrediction(const Data &data) {
const int kNumTrainEx = data.num_train_ex();
assert(kNumTrainEx >= 1);
const arma::mat kTrainingFeatures = data.training_features();
const arma::vec kSigmoidArg = kTrainingFeatures*theta_;
const arma::vec kSigmoidVal = ComputeSigmoid(kSigmoidArg);
for(int example_index=0; example_index<kNumTrainEx; example_index++)
{
predictions_(example_index) = (kSigmoidVal(example_index) >= 0.5) ? 1 : 0;
}
return 0;
}
// Unpacks WrapperStruct to obtain instances of LogisticRegression and Data.
double ComputeCostWrapper(const std::vector<double> &theta,
std::vector<double> &grad,void *void_data) {
WrapperStruct *wrap_struct = static_cast<WrapperStruct *>(void_data);
LogisticRegression *log_res = wrap_struct->log_res;
Data *data = wrap_struct->data;
return log_res->ComputeCost(theta,grad,*data);
}
|
Python | UTF-8 | 5,622 | 2.53125 | 3 | [] | no_license | import requests as R
import json
import bs4
import js2py
import os
import html
import time
S = R.session()
def get_headers():
cookies_str = """
:authority: www.toutiao.com
:method: GET
:path: /i6608430039597842948/
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding: gzip, deflate, br
accept-language: zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7
cache-control: no-cache
dnt: 1
pragma: no-cache
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
"""
cs = cookies_str.split("\n")
cookies = {}
for i in range(len(cs)):
pair = cs[i].split(": ")
if pair.__len__() < 2:
continue
name = pair[0].strip(" ")
value = pair[1].strip(" ")
if name.startswith(":"):
name = name[1:]
cookies[f"{name}"] = value
return cookies
# 公用request
def reqeuestFun(url=None):
content = S.get(url, headers=get_headers()).text
return content
offset = 0
# 获取新闻列表
def getNewsList(keyword):
global offset
url = f'https://www.toutiao.com/search_content/?offset={offset}&format=json&keyword={keyword}&autoload=true&count=20&cur_tab=1&from=search_tab&pd=synthesis'
print(url)
res = reqeuestFun(url)
res = json.loads(res)
arr = []
for i in res['data']:
if i.__contains__('abstract') and i['abstract'] != '' and i.__contains__('id'):
print(i)
arr.append({
'abstract': i['abstract'],
'id': i['id']
})
else:
print('不存在')
# 检查是否存在并获取详情
validArr = checkRepeat(arr)
for j in validArr:
getNewsContent(j)
offset+=20
getNewsList(keyword)
# 获取新闻内容
def getNewsContent(idObj):
print('延迟20秒')
time.sleep(0)
url = f'https://www.toutiao.com/a{idObj["id"]}/'
res = reqeuestFun(url)
soup = bs4.BeautifulSoup(res, 'html.parser')
id1 = soup.find_all('script')
try:
pass
ad = js2py.eval_js(id1[6].get_text())
# print(ad)
# 整合数据
t = {}
info = ad["articleInfo"]
if info == None:
return
tags = info["tagInfo"]['tags']
# 集合的集合序列化是有问题的,必须重新整理下
new_tags = []
for x in tags:
new_tags.append(x["name"])
tags = new_tags
data = {
"content": info["content"],
"title": info["title"],
"first_line": idObj["abstract"],
"cover_img": info["coverImg"],
"post_time": info["subInfo"]["time"],
"index": idObj["id"],
"tags": tags,
"source": "",
"img_count": "",
"src_link": ""
}
saveNews(data)
except:
print('不是文章,换个ID重来')
return
# 保存新闻内容
def saveNews(data):
workPath = os.getcwd() + '/news/'
path = workPath + str(data["index"])
# 新建文件夹
isExists = os.path.exists(path)
if not isExists:
os.makedirs(path)
print('创建成功')
else:
print('文件夹已存在')
# 保存内容为HTML
content = html.unescape(data['content'])
f = open(path + '/index.html', 'w', encoding='utf-8')
f.write(content)
f.close()
downLoadImg(data, path)
# 下载图片
def downLoadImg(data, path):
print('开始下载图片')
res = open(path + '/index.html', 'r', encoding='utf-8')
soup = bs4.BeautifulSoup(res, 'html.parser')
allImg = soup.find_all('img')
# 图片保存到本地
for i in range(len(allImg)):
bytes = S.get(allImg[i].get('src')).content
with open(f'{path}/{i}.jpg', "wb") as f:
f.write(bytes)
f.close()
allImg[i]["src"] = f'{i}.jpg'
del allImg[i]["img_height"]
del allImg[i]["img_width"]
del allImg[i]["alt"]
del allImg[i]["inline"]
f = open(path + '/index.html', 'w', encoding='utf-8')
soup = str(soup)
f.write(soup)
f.close()
# 更新JSON信息
try:
updateJson(path,data)
except:
pass
# 更新JSON
def updateJson(path,data):
data.pop("content")
print('开始更新json')
# 保存封面图
bytes = S.get(data['cover_img']).content
with open(path+'/cover_img.jpg', "wb") as f:
f.write(bytes)
f.close()
data['cover_img'] = 'cover_img.jpg'
# 更新json
with open('News.json', mode='r+', encoding='utf-8') as f:
gData = json.loads(f.read())
gData.append(data)
f.seek(0)
f.write(json.dumps(gData))
updateExist(data['index'])
# 更新已下载文件信息
def updateExist(id):
with open('existNews.txt', mode='r+', encoding='utf-8') as f:
gData = json.loads(f.read())
gData.append(id)
f.seek(0)
f.write(json.dumps(gData))
# 检查是否重复
def checkRepeat(idArr):
idList = open('existNews.txt', 'r', encoding='utf-8').read()
idList = json.loads(idList)
arr = []
for i in idArr:
arr.append(i['id'])
# 排除已经下载的新闻
effArr = []
vaiArr = set(arr).difference(set(idList))
for j in vaiArr:
for t in idArr:
if (t['id'] == j):
effArr.append(t)
return effArr
# 输入关键字
keyword=input()
getNewsList(keyword)
|
Shell | UTF-8 | 1,008 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | #!/bin/bash
source "$(dirname "${BASH_SOURCE}")/../../hack/lib/init.sh"
function cleanup() {
os::test::junit::reconcile_output
os::cleanup::processes
}
trap "cleanup" EXIT
suite_dir="${OS_ROOT}/test/integration/cvp-trigger/"
workdir="${BASETMPDIR}/cvp-trigger"
mkdir -p "${workdir}"
os::test::junit::declare_suite_start "integration/cvp-trigger"
# This test validates the cvp-trigger tool
actual="${workdir}/output.yaml"
os::cmd::expect_success "cvp-trigger --bundle-image-ref=git@example.com/org/bundle.git --index-image-ref=git@example.com/org/index.git --prow-config-path=${suite_dir}/config.yaml --job-config-path=${suite_dir}/jobs.yaml --job-name=periodic-ipi-deprovision --ocp-version=4.5 --operator-package-name=package1 --channel=channel1 --target-namespaces=namespace1 --install-namespace=namespace2 --dry-run>${actual}"
os::integration::sanitize_prowjob_yaml ${actual}
os::integration::compare "${actual}" "${suite_dir}/periodic-ipi-deprovision.expected"
os::test::junit::declare_suite_end
|
SQL | UTF-8 | 1,551 | 2.96875 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Creato il: Gen 20, 2017 alle 21:14
-- Versione del server: 10.1.19-MariaDB
-- Versione PHP: 7.0.13
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `glam`
--
-- --------------------------------------------------------
--
-- Struttura della tabella `iscrizioni`
--
CREATE TABLE `iscrizioni` (
`id` int(11) NOT NULL,
`nome` varchar(20) NOT NULL,
`data_iscrizione` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dump dei dati per la tabella `iscrizioni`
--
INSERT INTO `iscrizioni` (`id`, `nome`, `data_iscrizione`) VALUES
(1, 'gianpaolo', '2017-01-20 19:52:15'),
(2, 'wassim', '2017-01-20 20:38:44'),
(3, 'negro', '2017-01-20 20:38:53');
--
-- Indici per le tabelle scaricate
--
--
-- Indici per le tabelle `iscrizioni`
--
ALTER TABLE `iscrizioni`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT per le tabelle scaricate
--
--
-- AUTO_INCREMENT per la tabella `iscrizioni`
--
ALTER TABLE `iscrizioni`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java | ISO-8859-1 | 6,051 | 2.046875 | 2 | [] | no_license | package com.socgen.bip.action;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.socgen.bip.commun.action.AutomateAction;
import com.socgen.bip.db.JdbcBip;
import com.socgen.bip.exception.BipException;
import com.socgen.bip.form.FavorisForm;
import com.socgen.bip.user.UserBip;
import com.socgen.cap.fwk.exception.BaseException;
/**
* @author JMA - 01/03/2006
*
* Action permettant d'ajouter un favori partir de d'une fentre Popup
*
*
*/
public class AddFavorisAction extends AutomateAction {
private static String PACK_INSERT = "favoris.add.proc";
/**
* Constructor for AddFavorisAction.
*/
public AddFavorisAction() {
super();
}
/**
* Action permettant le premier appel de la JSP
*
*/
protected ActionForward initialiser(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ActionErrors errors,
Hashtable hParams)
throws ServletException {
String signatureMethode =
this.getClass().getName() + " - initialiser(paramProc, mapping, form , request, response, errors )";
logBipUser.entry(signatureMethode);
FavorisForm favForm = (FavorisForm) form;
try {
UserBip userBip = (UserBip) (request.getSession(false)).getAttribute("UserBip");
favForm.setMenu(userBip.getCurrentMenu().getId());
favForm.setTypFav(request.getParameter("typFav"));
favForm.setLibelle(request.getParameter("libFav"));
StringBuffer sbLien = new StringBuffer();
sbLien.append(request.getParameter("lienFav"));
int nbParam = 0;
for (Enumeration vE = request.getParameterNames(); vE.hasMoreElements();) {
String paramName = (String) vE.nextElement();
if (paramName.startsWith("param")) {
String param = request.getParameter(paramName);
String valeur = request.getParameter("value" + paramName.substring(5));
if (nbParam == 0)
sbLien.append("?");
else
sbLien.append("&");
sbLien.append(param + "=" + valeur);
nbParam++;
}
}
favForm.setLienFav(URLEncoder.encode(sbLien.toString()));
request.setAttribute("favorisForm", favForm);
// rcupration userId
UserBip user = (UserBip) request.getSession().getAttribute("UserBip");
favForm.setUserid(user.getIdUser());
} catch (Exception ex) {
return mapping.findForward(processSsimpleException(this.getClass().getName(), "consulter", ex, favForm, request));
}
logBipUser.exit(signatureMethode);
return mapping.findForward("ecran");
}
/**
* Action qui permet de crer un favori
*/
protected ActionForward creer(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response,
ActionErrors errors,
Hashtable hParamProc)
throws ServletException {
JdbcBip jdbc = new JdbcBip();
Vector vParamOut = new Vector();
String message = "";
boolean msg = false;
String signatureMethode = this.getClass().getName() + " - creer( mapping, form , request, response, errors )";
logBipUser.entry(signatureMethode);
//excution de la procdure PL/SQL
try {
vParamOut = jdbc.getResult(hParamProc, configProc, PACK_INSERT);
try {
message = jdbc.recupererResult(vParamOut, "valider");
} catch (BaseException be) {
logBipUser.debug(this.getClass().getName() + "-creer() --> BaseException :" + be);
logBipUser.debug(this.getClass().getName() + "-creer() --> Exception :" + be.getInitialException().getMessage());
logService.debug(this.getClass().getName() + "-creer() --> BaseException :" + be);
logService.debug(this.getClass().getName() + "-creer() --> Exception :" + be.getInitialException().getMessage());
//Erreur de lecture du resultSet
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("11217"));
//this.saveErrors(request,errors);
jdbc.closeJDBC(); return mapping.findForward("error");
}
if (!message.equals("")) {
//Entit dj existante, on rcupre le message
((FavorisForm) form).setMsgErreur(message);
logBipUser.debug("message d'erreur:" + message);
logBipUser.exit(signatureMethode);
//on reste sur la mme page
jdbc.closeJDBC(); return mapping.findForward("initial");
}
} //try
catch (BaseException be) {
logBipUser.error(this.getClass().getName() + "-creer() --> BaseException :" + be);
logBipUser.error(this.getClass().getName() + "-creer() --> Exception :" + be.getInitialException().getMessage());
logService.error(this.getClass().getName() + "-creer() --> BaseException :" + be);
logService.error(this.getClass().getName() + "-creer() --> Exception :" + be.getInitialException().getMessage());
//Si exception sql alors extraire le message d'erreur du message global
if (be.getInitialException().getClass().getName().equals("java.sql.SQLException")) {
message = BipException.getMessageFocus(BipException.getMessageOracle(be.getInitialException().getMessage()), form);
((FavorisForm) form).setMsgErreur(message);
jdbc.closeJDBC(); return mapping.findForward("initial");
} else {
//Erreur d''excution de la procdure stocke
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("11201"));
request.setAttribute("messageErreur", be.getInitialException().getMessage());
//this.saveErrors(request,errors);
jdbc.closeJDBC(); return mapping.findForward("error");
}
}
logBipUser.exit(signatureMethode);
jdbc.closeJDBC(); return mapping.findForward("ecran");
} //creer
} |
SQL | UTF-8 | 1,042 | 3.671875 | 4 | [] | no_license | CREATE TABLE ejerciciosql.usuarios(
id INT AUTO_INCREMENT NOT NULL,
nombre VARCHAR(100) NOT NULL UNIQUE,
apellidos VARCHAR(100) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL UNIQUE,
fecha date NOT NULL UNIQUE,
CONSTRAINT pk_usuarios PRIMARY KEY(id)
);
CREATE TABLE ejerciciosql.categorias(
id INT AUTO_INCREMENT NOT NULL,
nombre VARCHAR(100) NOT NULL,
CONSTRAINT pk_categorias PRIMARY KEY (id)
);
CREATE TABLE ejerciciosql.entradas(
id INT AUTO_INCREMENT NOT NULL,
usuario_id INT NOT NULL,
categoria_id INT NOT NULL,
titulo VARCHAR(200) NOT NULL,
descripcion text,
fecha DATE NOT NULL,
CONSTRAINT pk_entradas PRIMARY KEY(id)
);
ALTER TABLE entradas ADD CONSTRAINT fk_entrada_usuario FOREIGN KEY(usuario_id) REFERENCES usuarios(id)
;
ALTER TABLE entradas ADD CONSTRAINT fk_entrada_categoria FOREIGN KEY(categoria_id) REFERENCES categorias(id)
; |
Markdown | UTF-8 | 8,279 | 3.046875 | 3 | [] | no_license | # Website Builders
Website builders aim to help users compose a website with the most ease by using pre-built components or widgets. Many offer drag and drop functionality as well as pre-designed templates from which to start. Many offer hosting and self-maintenance of the development, eliminating technical factors many users do not want to deal with. Some offer the ability to dive into the code if so pleased. Though some say website builders lack the robustness and flexibility for customization that popular CMS can provide, new and popular website builders have caught up to the needs of their users and have lots of integrations and services.
Website builders are less likely to handle complex platforms and heavier data, making it challenging to make larger-scale data complex sites. Additionally, another drawback is website builders generally have recurring costs that are either monthly or annual.
---
## Popular website builders
A surprising number of designers start their portfolio on one platform and end up switching to the other platform out of frustration. Some designers prefer the structured parameters and super easy setup of Squarespace and WordPress, while others prefer the freedom and complete flexibility; some are frustrated by Squarespace's template limitations, while others are frustrated by the need to tweak every element in Webflow.
### Squarespace
Difficulty Level: Easy
[Squarespace](https://www.squarespace.com/) is the most well-known website platform with many templates that offer a lot of variety for layout for all user types. It was originally designed for e-commerce, so most templates are better for heavily visual sites and can be shaky when juggling large amounts of text. Depending on the template, it can offer interesting opportunities for customization and be highly rigid in those terms. The paid version offers a bit more flexibility and so may be worth exploring.
Resources for Squarespace
- [Website visibility](https://support.squarespace.com/hc/en-us/articles/205814568)
- [SEO checklist](https://support.squarespace.com/hc/en-us/articles/360002090267-SEO-checklist)
- [Enhance your Squarespace site in a Google search](https://www.stylefactoryproductions.com/blog/squarespace-seo)
### Webflow
Difficulty Level: Slightly Hard
[Webflow](https://webflow.com/) is a platform that advertises complete freedom for the designer. It allows for limitless arrangement, but it usually requires a level of precision and review from the designer that they're not used to. If you're familiar with HTML and CSS but don't feel like hosting your portfolio, Webflow is a viable option.
If you're considering using Webflow, be sure you understand the following HTML terminology:
- float
- relative
- absolute
- and fixed positioning
- Webflow hosting
- Connect your domain
- Free SSL certificate
#### Resources for Webflow
- [Webflow essential guide](https://webflow.com/blog/seo-and-webflow-the-essential-guide)
- [Webflow title and meta data](https://university.webflow.com/article/seo-title-meta-description)
- [Webflow SEO course](https://university.webflow.com/courses/seo-fundamentals-course)
### Blocs
Difficulty Level: Easy
[Blocs](https://blocsapp.com/) rivals Webflow but "renowned for its simplicity" in that they lean on pre-made widgets and sections that are responsive. Drag and drop make it easy for customizations, and animation panels allow designers to add that layer to their sites. Available exclusively on the Mac for a single payment getting you the software on up to two Macs. [Students get a discount off the full software](https://help.blocsapp.com/knowledge-base/student-discount/) but the trial is entirely free indefinitely, but features are restricted in this mode.
- Animation: Add stunning animations and scroll effects with just a few clicks.
- Responsive: Create fully responsive websites that look great on any screen.
- Font Manager: Use local and Google web fonts to create beautiful typography.
- Bootstrap 4: Powered by the Bootstrap 4 web design framework.
- Pre-made Blocks: Build with a range of pre-made layouts or create and store your own.
- CMS Integration: Integrated support for a range of Content Management Systems.
- Page Comments: Enable visitors to leave comments with integrated Disqus support.
- Local PHP Rendering: Preview server-side PHP functionality on the desktop.
- Sitemap: Automatic sitemap generation, which helps to improve SEO.
- Unlimited Websites: Build as many websites as you like, with no restrictions.
- True WYSIWYG: See how your website looks as you design and build it.
- Works Offline: Free to build websites anytime, anyplace, anywhere.
### Wix
Difficulty Level: Easy
[Wix](https://www.wix.com/) has over 500 designer-made templates to begin with, while offers control of the designs of websites with the Wix Editor. With true drag-and-drop, video backgrounds, animation, and fonts galore, Wix touts, you can make a professional and customized website. Built-in responsiveness, search engine optimization, and conversion for mobile, Wix also provides several integrated marketing solutions and business-focused services like built-in domain name, hosting, and SSL certificates. Wix ADI is their Artificial Design Intelligence that will instantly design a stunning website based on answering a few questions.
### Strikingly
Difficulty Level: Easy
[Strikingly](https://www.strikingly.com/) has been voted one of the best website builders for creating one-page websites: a long single-page site after which clicking on the navigation, it scrolls visitors up and down the page versus going to separate pages. With lots of templates and even a category of 'portfolio' templates, you can easily find one suitable for design portfolios. Strikingly's interface is intuitive, and their "sections editor" is easy to learn and use. There is an ability to build multiple-page websites if you upgrade to the highest plan.
### Adobe Portfolio
Difficulty Level: Moderate
[Adobe Portfolio](https://portfolio.adobe.com/) comes free with your Creative Cloud license and was created specifically for designers. Hence, it has a lot of excellent drag-and-drop features and Adobe's intuitive control panels. If you know and like Illustrator, Photoshop, and other Adobe programs, it's easy to pick up. Additionally, a few notable features:
- Behance Integration: Portfolio lets you easily connect with Behance to import your projects
- Optimized for Any Device: Each of our themes is natively responsive, resizing your content and images to fit any device or screen width.
### Semplice
Difficulty Level: Moderate
[Semplice](https://www.semplice.com/) touts the first fully customizable portfolio system based on WordPress, made by designers, for designers. For a single payment (not a subscription), you get features geared towards a designers' needs. [See the complete list of Semplice features](https://www.semplice.com/features) or a shortlist:
- Content Editor
- Fully Responsive
- Custom Font sets
- Fully Brandable
- Video Support
- Fullscreen Cover
- Dribbble Module
- Code Module
- Private Projects
### Cargo and Persona
Difficulty Level: Easy
[Cargo](https://2.cargocollective.com/) Collective has a long history of designing sites for designers and artists and has developed some dynamic and sophisticated templates for use. Though the offerings are more unconventional than others out there, its templates can be limited in customization. All Cargo templates are free to try and build, but you must pay the subscription fee to make a site public.
A few notable templates:
- [Post Dust](https://cargo.site/Templates/medium#postdust)
- [Pro Vital](https://cargo.site/Templates#provital)
- [Natalie Sarraute](https://cargo.site/Templates#nathaliesarraute)
- [Bürohaus](https://burohaus.cargo.site/)
[Persona](https://persona.co/) was created for artists and designers as an extension of Cargo Collective and offers features that may not be featured on other platforms. It has a simple back-end interface that supports heavy CSS customization. It doesn't provide much in the way of customer support compared to other platforms.
___ |
C# | UTF-8 | 724 | 2.515625 | 3 | [
"MIT"
] | permissive | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item {
public int ID { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public int BuyPrice { get; private set; }
public int SellPrice { get; private set; }
public string Icon { get; private set; }
public string ItemType { get; protected set; }
public Item(int id, string name, string description, int buyPrice, int sellPrice, string Icon) {
this.ID = id;
this.Name = name;
this.Description = description;
this.BuyPrice = buyPrice;
this.SellPrice = sellPrice;
this.Icon = Icon;
}
}
|
C# | UTF-8 | 680 | 2.59375 | 3 | [
"MIT"
] | permissive | using System.ComponentModel;
namespace LinqAn.Google.Metrics
{
/// <summary>
/// The name of the requested custom metric, where 109 refers the number/index of the custom metric. Note that the data type of ga:metric109 can be INTEGER, CURRENCY or TIME.
/// </summary>
[Description("The name of the requested custom metric, where 109 refers the number/index of the custom metric. Note that the data type of ga:metric109 can be INTEGER, CURRENCY or TIME.")]
public class Metric109: Metric<float>
{
/// <summary>
/// Instantiates a <seealso cref="Metric109" />.
/// </summary>
public Metric109(): base("Custom Metric 109 Value",true,"ga:metric109")
{
}
}
}
|
C# | UTF-8 | 578 | 3.140625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shape_Naive
{
enum ShapeType { Circle, Square };
class Program
{
static void Main(string[] args)
{
List<Shape> allShapes;
DrawingApp drawingApp = new DrawingApp();
allShapes = new List<Shape>();
allShapes.Add(new Circle(2.3));
allShapes.Add(new Square(2));
drawingApp.drawAllShapes(allShapes);
Console.ReadLine();
}
}
}
|
PHP | UTF-8 | 1,021 | 2.546875 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\api;
use App\Comment;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function register(Request $request){
$user_id = $request->user_id;
$thread_id = $request->thread_id;
$reply_content = $request->reply_content;
if(!$user_id || !$thread_id || !$reply_content)
return json_encode(array('error'=>'missing form data'));
$comment = new Comment;
$comment->user_id = $user_id;
$comment->thread_id = $thread_id;
$comment->reply_content = $reply_content;
if($comment->save())
return json_encode("success");
else
return json_encode(array('error'=>'insert error'));
}
public function getAllComment(){
return Comment::all();
}
public function getAllCommentByThreadId(Request $request){
return Comment::where('thread_id',$request->thread_id)->get();
}
}
|
C++ | UTF-8 | 4,222 | 2.75 | 3 | [
"BSL-1.0",
"GPL-1.0-or-later",
"MIT"
] | permissive | /*=============================================================================
Copyright (c) 2017 Paul Fultz II
reveal.cpp
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include "test.hpp"
#include <boost/hof/reveal.hpp>
#include <boost/hof/first_of.hpp>
#include <boost/hof/static.hpp>
#include <boost/hof/lambda.hpp>
#include <boost/hof/fix.hpp>
namespace reveal_test {
#define CONDITIONAL_FUNCTION(n) \
struct t ## n {}; \
struct f ## n \
{ \
constexpr int operator()(t ## n) const \
{ \
return n; \
} \
};
CONDITIONAL_FUNCTION(1)
CONDITIONAL_FUNCTION(2)
CONDITIONAL_FUNCTION(3)
typedef boost::hof::first_of_adaptor<f1, f2, f3> f_type;
static constexpr boost::hof::static_<f_type> f = {};
BOOST_HOF_TEST_CASE()
{
BOOST_HOF_TEST_CHECK(boost::hof::reveal(f)(t1()) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::reveal(f)(t2()) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::reveal(f)(t3()) == 3);
static_assert(boost::hof::is_invocable<boost::hof::reveal_adaptor<f_type>, t1>::value, "Invocable");
static_assert(boost::hof::is_invocable<boost::hof::reveal_adaptor<f_type>, t2>::value, "Invocable");
static_assert(boost::hof::is_invocable<boost::hof::reveal_adaptor<f_type>, t3>::value, "Invocable");
static_assert(!boost::hof::is_invocable<boost::hof::reveal_adaptor<f_type>, int>::value, "Invocable");
// boost::hof::reveal(f)(1);
}
#ifndef _MSC_VER
static constexpr auto lam = boost::hof::first_of(
BOOST_HOF_STATIC_LAMBDA(t1)
{
return 1;
},
BOOST_HOF_STATIC_LAMBDA(t2)
{
return 2;
},
BOOST_HOF_STATIC_LAMBDA(t3)
{
return 3;
}
);
BOOST_HOF_TEST_CASE()
{
STATIC_ASSERT_EMPTY(lam);
STATIC_ASSERT_EMPTY(boost::hof::reveal(lam));
BOOST_HOF_TEST_CHECK(boost::hof::reveal(lam)(t1()) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::reveal(lam)(t2()) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::reveal(lam)(t3()) == 3);
// boost::hof::reveal(lam)(1);
// lam(1);
}
#endif
BOOST_HOF_STATIC_LAMBDA_FUNCTION(static_fun) = boost::hof::first_of(
[](t1)
{
return 1;
},
[](t2)
{
return 2;
},
[](t3)
{
return 3;
}
);
BOOST_HOF_TEST_CASE()
{
#ifndef _MSC_VER
STATIC_ASSERT_EMPTY(static_fun);
// STATIC_ASSERT_EMPTY(boost::hof::reveal(static_fun));
#endif
BOOST_HOF_TEST_CHECK(boost::hof::reveal(static_fun)(t1()) == 1);
BOOST_HOF_TEST_CHECK(boost::hof::reveal(static_fun)(t2()) == 2);
BOOST_HOF_TEST_CHECK(boost::hof::reveal(static_fun)(t3()) == 3);
BOOST_HOF_TEST_CHECK(static_fun(t1()) == 1);
BOOST_HOF_TEST_CHECK(static_fun(t2()) == 2);
BOOST_HOF_TEST_CHECK(static_fun(t3()) == 3);
// boost::hof::reveal(static_fun)(1);
}
struct integral_type
{
template<class T>
BOOST_HOF_USING_TYPENAME(failure_alias, std::enable_if<std::is_integral<T>::value>::type);
struct failure
: boost::hof::as_failure<failure_alias>
{};
template<class T, class=typename std::enable_if<std::is_integral<T>::value>::type>
constexpr T operator()(T x) const
{
return x;
}
};
struct foo {};
struct dont_catch {};
struct catch_all
{
template<class T>
BOOST_HOF_USING_TYPENAME(failure_alias, std::enable_if<!std::is_same<T, dont_catch>::value>::type);
struct failure
: boost::hof::as_failure<failure_alias>
{};
template<class T, class=typename std::enable_if<!std::is_same<T, dont_catch>::value>::type>
constexpr int operator()(T) const
{
return -1;
}
};
static constexpr boost::hof::reveal_adaptor<boost::hof::first_of_adaptor<integral_type, catch_all>> check_failure = {};
BOOST_HOF_TEST_CASE()
{
BOOST_HOF_TEST_CHECK(check_failure(5) == 5);
BOOST_HOF_TEST_CHECK(check_failure(foo()) == -1);
static_assert(!boost::hof::is_invocable<decltype(check_failure), dont_catch>::value, "Invocable");
static_assert(!boost::hof::is_invocable<decltype(check_failure), int, int>::value, "Invocable");
// check_failure(dont_catch());
}
}
|
C++ | UTF-8 | 1,460 | 3.125 | 3 | [] | no_license | #include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
void process(string line) {
vector<char> chars;
size_t delim = 999;
auto sl = stoi(line, &delim);
// cout << "strings length: " << sl << endl;
// cout << "charset source: " << line.substr(delim+1) << endl;
for(char c : line.substr(delim+1)) {
if(chars.end() == std::find(chars.begin(), chars.end(), c)) {
chars.push_back(c);
}
}
std::sort(chars.begin(), chars.end());
// cout << "charset: length = " << chars.size() << ", chars: ";
// for(auto iter = chars.begin(), end = chars.end(); end != iter; ++iter) {
// if(chars.begin() != iter) {
// cout << ", ";
// }
// cout << *iter;
// }
// cout << endl;
long tc = 1;
for(int n = sl; n > 0; --n) {
tc *= chars.size();
}
// cout << "total results: " << tc << endl;
int base = static_cast<int>(chars.size());
string s;
for(int i = 0 ; i < tc; ++i) {
if(i) {
cout << ',';
}
s.clear();
for(int j = 0, v = i; j < sl; ++j) {
s += chars[v%base];
v /= base;
}
std::reverse(s.begin(), s.end());
cout << s;
}
cout << endl;
}
void test() {
process("1,aa");
cout << "a" << endl;
process("2,ab");
cout << "aa,ab,ba,bb" << endl;
process("3,pop");
cout << "ooo,oop,opo,opp,poo,pop,ppo,ppp" << endl;
}
int main(int _a, char ** _v) {
// test();
ifstream stream(_v[1]);
string s;
while(std::getline(stream,s)) {
process(s);
}
}
|
C | UTF-8 | 361 | 3.84375 | 4 | [] | no_license | //wap to identify if the number is perfect number or not
#include <stdio.h>
void main()
{
int a,b,c;
c=0;
printf("\n enter a number");
scanf("%d",&b);
for(a=1;a<b;a++)
{
if(b%a==0)
{
c+=a; //c=c+a
}
}
if(c==b)
printf("\n %d is a perfect number",b);
else
printf("\n %d is not a perfect number",b);
}
|
Java | UTF-8 | 88 | 1.695313 | 2 | [] | no_license | package abstractfactory;
public class SmeltedCoalProduct implements SmeltedProduct {
}
|
JavaScript | UTF-8 | 167 | 3.21875 | 3 | [] | no_license | /*
* Complete the 'find_integer' function below.
*
* The function accepts a long array as parameter.
*/
function find_integer(arr) {
// Write your code here
}
|
C# | UTF-8 | 7,697 | 3.375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp25_go_fish_game
{
class Game
{
private List<Player> players; //lista graczy
private Dictionary<Values, Player> books; //slownik kolekcji
private Deck stock;//karty na stole
private TextBox textBoxOnForm;//element form
public Game(string playerName, IEnumerable<string> opponentNames, TextBox textBoxOnForm)
{
Random random = new Random();
this.textBoxOnForm = textBoxOnForm;
players = new List<Player>();
players.Add(new Player(playerName, random, textBoxOnForm));//dodanie gracza JA
foreach (string player in opponentNames)//dodanie przeciwnikow
players.Add(new Player(player, random, textBoxOnForm));
books = new Dictionary<Values, Player>();//stworzenie slownika kolekcji 4x
stock = new Deck();//domyslnie tworzy 52 karty a-z
Deal();//losowanie wszystkich kart,rozdanie kart- po 5 kazdy
players[0].SortHand();
}
// This is where the game starts—this method's only called at the beginning
// of the game. Shuffle the stock, deal five cards to each player, then use a
// foreach loop to call each player's PullOutBooks() method.
private void Deal()
{
stock.Shuffle();
for (int i = 0; i < 5; i++)// 5 razy- 5 kart
foreach (Player player in players)//dla kazdego gracza
player.TakeCard(stock.Deal());//daj jedną kartę
foreach (Player player in players)//dla kazdego gracza
PullOutBooks(player);
}
public bool PlayOneRound(int selectedPlayerCard)
{
Values cardToAskFor = players[0].Peek(selectedPlayerCard).Value; //karta do sprawdzenia to zaznaczona karta
for (int i = 0; i < players.Count; i++)//dla kazdego gracza
{
if (i == 0)//jeśli gracz JA
{
players[0].AskForACard(players, 0, stock, cardToAskFor);//sprawdza gracza JA czy mają tą wybraną kartę
}
else
{
players[i].AskForACard(players, i, stock);//jeśli gracz PC- sprawdza wszystkich pozostalych graczy czy mają jego losową
}
if (PullOutBooks(players[i]))//jesli gracz juz nie ma kart- podlicza jego booki
{
textBoxOnForm.Text += players[i].Name + " drew a new hand" + Environment.NewLine;//informuje
int card = 1;
while (card <= 5 && stock.Count > 0)//(jeśli gracz już nie ma kart), musi zabrać 5- jeśli są na stosie
{
players[i].TakeCard(stock.Deal());
card++;
}
}
players[0].SortHand();//sortuje karty gracza JA
if (stock.Count == 0)//jeśli stock pusty
{
textBoxOnForm.Text = "The stock is out of cards. Game over!" + Environment.NewLine;
return true;
}
}
return false;//jesli stock nie jest pusty- gra trwa dalej
}
// Pull out a player's books. Return true if the player ran out of cards, otherwise
// return false. Each book is added to the Books dictionary. A player runs out of
// cards when he’'s used all of his cards to make books—and he wins the game.
public bool PullOutBooks(Player player)
{
IEnumerable<Values> booksPulled = player.PullOutBooks();
foreach (Values value in booksPulled)//dodaje do listy books jego booki
books.Add(value, player);
if (player.CardCount == 0)//jeśli już nie ma kart
return true;
return false;
}
// Return a long string that describes everyone's books by looking at the Books dictionary
//"Joe has a book of sixes. (line break) Ed has a book of Aces."
public string DescribeBooks()
{
string whoHasWhichBooks = "";
foreach (Values value in books.Keys)
whoHasWhichBooks += books[value].Name + " has a book of " + Card.Plural(value) + Environment.NewLine;
return whoHasWhichBooks;
}
public IEnumerable<string> GetPlayerCardNames()//funkcja zwraca liste kart gracza
{
return players[0].GetCardNames();
}
//Game(textName.Text, new List<string> { "Joe", "Bob" }, textProgress);
public string DescribePlayerHands()//zwraca stringa opisujacego stan gry- kart graczy i stos
{
string description = "";
for (int i = 0; i < players.Count; i++)//dla kazdego gracza
{
description += players[i].Name + " has " + players[i].CardCount;//opisuje jakie ma karty
if (players[i].CardCount == 1)//jeśli ma tylko jedną
description += " card." + Environment.NewLine;//bez s
else
description += " cards." + Environment.NewLine;//z s
}
description += "The stock has " + stock.Count + " cards left.";//ile kart zostało na stosie
return description;
}
// This method is called at the end of the game. It uses its own dictionary
// (Dictionary<string, int> winners) to keep track of how many books each player
// ended up with in the books dictionary. First it uses a foreach loop
// on books.Keys—foreach (Values value in books.Keys)—to populate
// its winners dictionary with the number of books each player ended up with.
// Then it loops through that dictionary to find the largest number of books
// any winner has. And finally it makes one last pass through winners to come
// up with a list of winners in a string ("Joe and Ed"). If there's one winner,
// it returns a string like this: "Ed with 3 books". Otherwise, it returns a
// string like this: "A tie between Joe and Bob with 2 books."
public string GetWinnerName()
{
Dictionary<string, int> winners = new Dictionary<string, int>(); //utworzenie nowego dictionary
foreach (Values value in books.Keys)//dla kazdego booka gracza
{
string name = books[value].Name;//zwraca nazwę booka
if (winners.ContainsKey(name))
winners[name]++;
else
winners.Add(name, 1);
}
int mostBooks = 0;
foreach (string name in winners.Keys)
if (winners[name] > mostBooks)
mostBooks = winners[name];
bool tie = false;
string winnerList = "";
foreach (string name in winners.Keys)
if (winners[name] == mostBooks)
{
if (!String.IsNullOrEmpty(winnerList))
{
winnerList += " and ";
tie = true;
}
winnerList += name;
}
winnerList += " with " + mostBooks + " books";
if (tie)
return "A tie between " + winnerList;
else
return winnerList;
}
}
}
|
Java | UTF-8 | 16,663 | 2.546875 | 3 | [] | no_license | package game;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import org.apache.log4j.Logger;
public abstract class Wezen implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1;
protected int HP, maxHP, goud,strength,dexterity,intellect,charisma;
protected double level;
protected String naam,stance = "defensive";
protected boolean dood, knockedDown;
protected double movement = 3.5;
protected LinkedHashMap<Item,Integer> inventory;
protected ArrayList<Spell> spreuken = new ArrayList<Spell>();
protected double[] statIncrease = new double[4];
protected int[] resistance = new int[4];
protected int initWeight = 15;
protected int[] defense = new int[3];
protected Equipment boog;
protected Equipment wapen;
protected Equipment schild;
protected Equipment helm,harnas,handschoenen,broek,schoenen;
protected Equipment nothing = new Equipment(-1,"Nothing",0,0,0,0,0.0);
protected Clothing mantle,shirt,pants;
protected Clothing noClothing = new Clothing(-1,"Nothing","",0.0,0,null,0);
protected Munition arrow = new Munition(-1,"Arrow","A simple wooden arrow.",0.08,1,3);
protected double dimMov = 0;
protected HashMap<Ability,Integer> abilities = new HashMap<Ability,Integer>();
protected ArrayList<Buff> buffs = new ArrayList<Buff>();
private static final Logger logger = Logger.getLogger(Wezen.class);
public Wezen(double lvl, String name, int hp, int gold,int strength,int dexterity,int intellect,int charisma){
level = lvl;
HP = hp;
goud = gold;
naam = name;
maxHP = hp;
this.strength = strength;
this.dexterity = dexterity;
this.intellect = intellect;
this.charisma = charisma;
dood = false;
knockedDown = false;
inventory = new LinkedHashMap<Item,Integer>();
}
public Wezen(){
}
public abstract void updateHPBar();
public HashMap<Ability,Integer> getAbilities(){
return abilities;
}
/*
*
* SPELL METHODS
*
*/
public boolean addSpreuk(Spell spreuk){
for(int j=0;j<spreuken.size();j++){
if(spreuken.get(j) == spreuk){
RPGMain.printText(true,"You have already learned this spell.");
return false;
}
if(spreuken.get(j) == null){
spreuken.add(spreuk);
return true;
}
}
return false;
}
public int getAantalSpreuken(){
int aantal = 0;
for(int j = 0;j<spreuken.size();j++){
if(spreuken.get(j) != null) aantal++;
}
return aantal;
}
public Spell getSpreuk(int index){
return spreuken.get(index);
}
public Spell getSpreuk(String naam){
for(int j = 0;j<spreuken.size();j++){
if(spreuken.get(j).getName().equalsIgnoreCase(naam)){
return spreuken.get(j);
}
}
return null;
}
/*
*
* INVENTORY METHODS
*
*/
public Item getInventoryItem(int index){
int j=0;
for(Item i:inventory.keySet()){
if(j == index){
return i;
}
j++;
}
return null;
}
public Item getInventoryItem(String name){
for(Item i:inventory.keySet()){
if(i.getName().equalsIgnoreCase(name)){
return i;
}
}
return null;
}
public int getInventoryItemIndex(String name){
int j=0;
for(Item i:inventory.keySet()){
if(i.getName().equalsIgnoreCase(name)){
return j;
}
j++;
}
return -1;
}
public int getItemNumber(String name){
for(Item i:inventory.keySet()){
if(i.getName().equalsIgnoreCase(name)){
return inventory.get(i);
}
}
return 0;
}
public int getItemNumber(Item i){
return inventory.get(i);
}
public boolean hasItem(String name){
if(getInventoryItemIndex(name) == -1){
return false;
}
return true;
}
public int getInventorySize(){
return inventory.size();
}
public void addInventoryItem(Item item, int number){
for(int i=0;i<number;i++){
addInventoryItem(item);
}
}
public void addInventoryItem(Item item){
if(getInventorySpace() >= item.getWeight()){
//TODO
if(item instanceof Equipment){
Equipment e = new Equipment((Equipment)item);
inventory.put(e, 1);
}
else if(item instanceof Consumable){
Consumable c = new Consumable((Consumable)item);
inventory.put(c, 1);
}
else if(item instanceof Herb){
Herb h = new Herb((Herb)item);
//TODO add required item
if(hasItem("")){
h.setQuality((int)Math.round(2+Math.random()));
}
else{
h.setQuality((int)Math.round(0.4+Math.random()));
}
inventory.put(h, 1);
}
else{
if(hasItem(item.getName())){
//Since item is different instance of what is already in there, if you would just add the item, you'd have the original with the original amount,
//PLUS the new item with 1+original amount, thereby duplicating items
inventory.put(this.getInventoryItem(item.getName()), getItemNumber(item.getName())+1);
}
else{
inventory.put(item,1);
}
}
try{
Logbook.addContent(item.getLogbookPath(), 1, item.getLogbookSummary());
} catch(Exception e){
e.printStackTrace();
logger.error(e);
}
try{
GameFrameCanvas.updatePlayerInfoTable();
}catch(Exception e){
}
if(RPGMain.speler != null){
for(Quest q: RPGMain.speler.getQuestLog()){
try{
q.checkProgress(item.getClass().getName().split("\\.")[1],item.getID());
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
continue;
} catch(Exception e){
e.printStackTrace();
logger.error(e);
}
}
}
}
else{
RPGMain.printText(true, "You are too heavily loaded.");
}
}
public void delInventoryItem(Item i){
inventory.put(i, inventory.get(i)-1);
if(inventory.get(i) <= 0){
inventory.remove(i);
}
}
public void delInventoryItem(String s, int number){
delInventoryItem(getInventoryItem(s),number);
}
public void delInventoryItem(Item item, int number){
for(int i=0;i<number;i++){
delInventoryItem(item);
}
}
public void delInventoryItem(int index){
Item i = getInventoryItem(index);
inventory.put(i, inventory.get(i)-1);
if(inventory.get(i) <= 0){
inventory.remove(i);
}
}
public void delInventoryItem(int index, int number){
delInventoryItem(getInventoryItem(index),number);
}
public double getInventorySpace(){
double g = getMaxWeight();
for(Item e: inventory.keySet()){
g-=(e.getWeight()*inventory.get(e));
}
return g;
}
/* GETTERS/SETTERS */
public Equipment getEquipped(int type){
switch(type){
case 1: return wapen;
case 2: return wapen;
case 3: return schild;
case 4: return boog;
case 5: return helm;
case 6: return harnas;
case 7: return handschoenen;
case 8: return broek;
case 9: return schoenen;
default: return null;
}
}
public double getMaxWeight(){
return initWeight + strength/2.0;
}
public void setAbilityCooldown(Ability a, int cd){
abilities.put(a, cd);
}
public void decrAllAbilitiesCooldown(){
for(Ability a: abilities.keySet()){
abilities.put(a,Math.max(abilities.get(a)-1,0));
}
}
public void setKnockedDown(boolean b){
knockedDown = b;
}
public boolean getKnockedDown(){
return knockedDown;
}
public Clothing getMantle(){
return mantle;
}
public Clothing getShirt(){
return shirt;
}
public Clothing getPants(){
return pants;
}
public void setMantle(Clothing c){
if(c.getArea().equalsIgnoreCase("mantle")){
mantle = c;
}
}
public void setShirt(Clothing c){
if(c.getArea().equalsIgnoreCase("shirt")){
shirt = c;
}
}
public void setPants(Clothing c){
if(c.getArea().equalsIgnoreCase("pants")){
pants = c;
}
}
public String getStance(){
return stance;
}
public void setStance(String s){
stance = s;
}
public double getStanceAttackModifier(){
if(stance.equalsIgnoreCase("offensive")){
return 1.3;
}
return 1.0;
}
public double getStanceDefenseModifier(){
if(stance.equalsIgnoreCase("offensive")){
return 0.8;
}
return 1.0;
}
protected Equipment initGear(int index){
if(Data.equipment.get(index) != null){
return Data.equipment.get(index);
}
else
return nothing;
}
public void checkTreats(){
statIncrease = new double[4];
checkTreats(wapen);
checkTreats(helm);
checkTreats(harnas);
checkTreats(handschoenen);
checkTreats(broek);
checkTreats(schoenen);
checkTreats(schild);
checkTreats(boog);
}
public double getEquippedWeight(){
double weight = 0;
for(int j=1;j<10;j++){
try{
weight+=getEquipped(j).getWeight();
}catch(NullPointerException exc){
continue;
}
}
return weight;
}
public int getArrows(){
int j = 0;
for(Item i:inventory.keySet()){
if(i.getClass().equals(Munition.class)){
j+=inventory.get(i).intValue();
}
}
return j;
}
public void addArrows(int x){
while(x > 0){
addInventoryItem(arrow);
x--;
}
if(x < 0){
for(int j=x;j<0;j++){
delInventoryItem(arrow);
}
}
}
public void checkTreats(Equipment item){
if(item != null){
String treat = item.getTreat();
if(treat != null){
if(treat.substring(0,treat.lastIndexOf(" ")).equalsIgnoreCase("strength")){
statIncrease[0] += Integer.parseInt(treat.substring(treat.lastIndexOf(" ")+1));
}
else if(treat.substring(0,treat.lastIndexOf(" ")).equalsIgnoreCase("dexterity")){
statIncrease[1] += Integer.parseInt(treat.substring(treat.lastIndexOf(" ")+1));
}
else if(treat.substring(0,treat.lastIndexOf(" ")).equalsIgnoreCase("intellect")){
statIncrease[2] += Integer.parseInt(treat.substring(treat.lastIndexOf(" ")+1));
}
else if(treat.substring(0,treat.lastIndexOf(" ")).equalsIgnoreCase("charisma")){
statIncrease[3] += Integer.parseInt(treat.substring(treat.lastIndexOf(" ")+1));
}
}
}
}
public int getMeleeWeaponSkill(){
return 1;
}
public int getArchery(){
return 1;
}
public int getDefense(int index){
if(defense[0] > 0){
return defense[index];
}
else{
if(index == 0){
return Math.max((int)level,helm.getStrength());
}
else if(index == 1){
return Math.max((int)level,harnas.getStrength());
}
else if(index == 2){
return Math.max((int)level,(int)(broek.getStrength()));
}
return 0;
}
}
public Equipment getWapen(){
return wapen;
}
public Equipment getHarnas(){
return harnas;
}
public Equipment getSchild(){
return schild;
}
public Equipment getBoog(){
return boog;
}
public int getLevel(){
return (int)level;
}
public double getFullLevel(){
return level;
}
public int getHP(){
if(HP <0) HP=0;
return HP;
}
public int getMaxHP(){
return maxHP;
}
public int getGoud(){
return goud;
}
public String getName(){
return naam;
}
public double getMovement(){
double extraWeight = getEquippedWeight();
// the more extra weight you have, the less you can walk, however the stronger you are, the more you can bear the weight
double dummyMovement = movement*(1-extraWeight/50.0+0.01*strength) - dimMov;
return dummyMovement;
}
public void setLevel(int x){
level=x;
}
public void addHP(int x){
HP+=x;
if(HP > maxHP){
HP = maxHP;
}
if(HP < 0){
HP = 0;
}
updateHPBar();
}
public void setHP(int x){
HP = x;
updateHPBar();
}
public void setMaxHP(int x){
maxHP = x;
}
public void addGoud(int x){
goud+=x;
if(goud < 0) goud = 0;
GameFrameCanvas.updatePlayerInfoTable();
}
public void setStrength(int x){
strength = x;
}
public int getStrength(){
return strength+(int)statIncrease[0];
}
public void setDexterity(int x){
dexterity = x;
}
public int getDexterity(){
return dexterity+(int)statIncrease[1];
}
public void setIntellect(int x){
intellect = x;
}
public int getIntellect(){
return intellect+(int)statIncrease[2];
}
public void setCharisma(int x){
charisma = x;
}
public void dimMovement(double x){
dimMov+=x*movement;
// maximally at 33% of initial movement, and no extra movement
dimMov = (int)Math.max(0,Math.min(dimMov, 2.0*movement/3.0));
if(this.getClass().equals(Avatar.class)){
GameFrameCanvas.updatePlayerInfoTable();
}
}
public boolean hasStun(){
//TODO
return false;
}
public boolean hasSpell(String name){
for(Spell s:spreuken){
try{
if(s.getName().equalsIgnoreCase(name))
return true;
}catch(NullPointerException exc){
}
}
return false;
}
public void wearOut(int damage, int aimFor){
switch(aimFor){
case 0: helm.addKwaliteit(-(int)(damage/(helm.getStrength()+0.01))); break;
case 1: harnas.addKwaliteit(-(int)(damage/(harnas.getStrength()+0.01)));
handschoenen.addKwaliteit(-(int)(damage/(handschoenen.getStrength()+0.01))); break;
case 2: broek.addKwaliteit(-(int)(damage/(broek.getStrength()+0.01)));
schoenen.addKwaliteit(-(int)(damage/(schoenen.getStrength()+0.01)));break;
default: break;
}
}
public int getCharisma(){
return charisma+(int)statIncrease[3];
}
public boolean checkDood(){
if(HP<=0){
HP = 0;
dood = true;
}
else{
dood = false;
}
return dood;
}
public void increaseStat(int index,double amount){
statIncrease[index]+=amount;
}
public void removeEquippedItem(Equipment item){
switch(item.getType()){
case 1: wapen = nothing; break;
case 2: wapen = nothing; break;
case 3: schild = nothing; break;
case 4: boog = nothing; break;
case 5: helm = nothing; break;
case 6: harnas = nothing; break;
case 7: handschoenen = nothing; break;
case 8: broek = nothing; break;
case 9: schoenen = nothing; break;
default: break;
}
}
public void addBuff(String name, String type, int amount, int duration, int intervalTime, String description){
buffs.add(new Buff(name,type,amount,duration,intervalTime,description, false));
}
public void tickBuffs(){
for(Buff b: buffs){
b.activate();
}
}
public void autoRunBuffs(){
for(Buff b: buffs){
b.start();
}
}
class Buff extends Thread implements Serializable{
private String name,description,type;
private int amount,duration,currentPhase;
private int intervalTime;
private boolean isPlayer;
public Buff(String name, String type, int amount, int duration, int intervalTime, String description, boolean isPlayer){
this.name = name;
this.type = type;
this.amount = amount;
this.duration = duration;
this.intervalTime = intervalTime;
this.description = description;
this.isPlayer = isPlayer;
currentPhase = 0;
}
public void run(){
while(amount != 0 && currentPhase < duration && !checkDood()){
try{
activate();
sleep(intervalTime);
} catch(InterruptedException e){
e.printStackTrace();
logger.error(e);
}
}
}
public void activate(){
if(!checkDood() && currentPhase >= 0 && currentPhase < duration){
if(amount < 0){
if(isPlayer){
RPGMain.printText(true, new String[]{naam," suffers from ", name, ", and recieves ", amount + " damage."}, new String[]{"greenbold","regular","bold","regular","redbold"});
}
else{
RPGMain.printText(true, new String[]{naam," suffers from ", name, ", and recieves ", amount + " damage."}, new String[]{"redbold","regular","bold","regular","redbold"});
}
}
else{
if(isPlayer){
RPGMain.printText(true, new String[]{naam, " enjoys the effect of ", name, " and recieves ", amount + " HP."}, new String[]{"greenbold","regular","bold","regular","greenbold"});
}
else{
RPGMain.printText(true, new String[]{naam, " enjoys the effect of ", name, " and recieves ", amount + " HP."}, new String[]{"redbold","regular","bold","regular","greenbold"});
}
}
if(description != null && !description.equalsIgnoreCase("")){
RPGMain.printText(true, description);
}
addHP(amount);
currentPhase++;
}
else{
buffs.remove(this);
}
}
public String getType(){
return type;
}
public String getBuffName(){
return name;
}
public String getDescription(){
return description;
}
public int getAmount(){
return amount;
}
public int getDuration(){
return duration;
}
public int getCurrentPhase(){
return currentPhase;
}
}
}
|
C++ | UTF-8 | 615 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef THREAD_POOL
#define THREAD_POOL
#include "task.h"
#include <pthread.h>
#include <iostream>
#include <vector>
#include <queue>
class ThreadPool {
public:
static ThreadPool* create_pool(int num = 10); // 默认参数不能同时在函数定义和函数声明
void add_task(Task* t);
Task* get_task();
bool alive();
private:
ThreadPool(int num);
static void* ThreadFunc(void*);
bool is_running; // 此时线程池正在运行
std::vector<pthread_t> threads;
std::queue<Task*> task_queue;
pthread_mutex_t lock; // 互斥锁保护条件量
pthread_cond_t cond; // 条件变量
};
#endif |
Java | UTF-8 | 436 | 2.5625 | 3 | [] | no_license | package QspiderTest;
import java.util.Arrays;
public class Demo3 {
public static void main(String[] args) {
String s="failure is the pillar of success";
System.out.println("Before reversing.....");
System.out.println(s);
StringBuffer sb=new StringBuffer(s);
StringBuffer sb1=sb.reverse();
String s1=sb1.toString();
System.out.println("After reversing.....");
System.out.println(s1);
}
}
|
JavaScript | UTF-8 | 982 | 3.515625 | 4 | [] | no_license | var price = 44, age = 23, temperature = 32; //numaric variable
var name = "Rashidul Habib"; //string variable. Use single quation or double
var pass = true; //boolian variable
var dab_chor = false; //this is also boolian variable
// do not use reserved word as variable name
// var false =10;
// var delete = 'delete';
// variable name should be one word
// var nayok name = 'chapik khan';
// do not use cotation in variable name
// var 'nayka' = "shabnur";
// can use under score (_) with variable name
// rearly used in js
var school_name = 'Zilla school';
// use capital letter to write big variable name
// brodly used in js
// camale case is very popular in js var naming
var mySchoolName = 'Zilla School';
// All Capital latter is used when declearing a defined value
// rearly used
var PI = 3.1416;
// can't start name with number
// but can used number after a word
// var 99price = 654; wrong
var price99 = 543;
// use a meaningful name. It is recomanded |
Python | UTF-8 | 2,259 | 2.640625 | 3 | [] | no_license | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import seaborn as sns
import pickle
from sklearn.metrics import classification_report, confusion_matrix
df = pd.read_csv("Adult_train.tab", delimiter="\t")
df.drop(index=0, inplace=True)
df.drop(index=1, inplace=True)
for col in df.head(0):
df[col] = df[col].astype('category')
for col in df.head(0):
df[col] = df[col].cat.codes
corr_matrix = df.corr().abs()
upper = corr_matrix.where(np.triu(np.ones_like(corr_matrix), k=1).astype(np.bool))
to_drop = [column for column in upper.columns if any(upper[column] > 0.7)]
df = df.drop(df[to_drop], axis=1)
### Split database ###
y = df['y']
X = df.drop('y', axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, shuffle=True)
dane = {}
for k in range(25, 75):
clf = RandomForestClassifier(n_estimators=100,
random_state=k,
max_features='auto',
n_jobs=-1, verbose=0)
clf.fit(X_train, y_train)
trainig_score = clf.score(X_train, y_train)
test_score = clf.score(X_test,y_test)
dane[k] = [trainig_score, test_score]
if test_score >= 0.85:
with open("RFadultModel.pickle", "wb") as f:
pickle.dump(clf, f)
for keys, values in dane.items():
print(keys, " : ", values)
"""n_nodes = []
max_depths = []
# Stats about the trees in random forest
for ind_tree in clf.estimators_:
n_nodes.append(ind_tree.tree_.node_count)
max_depths.append(ind_tree.tree_.max_depth)
print(f'Average number of nodes {int(np.mean(n_nodes))}')
print(f'Average maximum depth {int(np.mean(max_depths))}')
# Training predictions (to demonstrate overfitting)
train_rf_predictions = clf.predict(X_train)
train_rf_probs = clf.predict_proba(X_train)[:, 1]
# Testing predictions (to determine performance)
rf_predictions = clf.predict(X_test)
rf_probs = clf.predict_proba(X_test)[:, 1]
from sklearn.metrics import precision_score, recall_score, roc_auc_score, roc_curve, plot_confusion_matrix
import matplotlib.pyplot as plt"""
|
C# | UTF-8 | 2,849 | 2.90625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MGRpgLibrary.TileEngine
{
public class TileMap
{
#region Field Region
List<Tileset> tilesets;
List<ILayer> mapLayers;
CollisionLayer collisionLayer;
static int mapWidth;
static int mapHeight;
#endregion
#region Property Region
public CollisionLayer CollisionLayer
{
get { return collisionLayer; }
}
public static int WidthInPixels
{
get { return mapWidth * Engine.TileWidth; }
}
public static int HeightInPixels
{
get { return mapHeight * Engine.TileHeight; }
}
#endregion
#region Constructor Region
public TileMap(List<Tileset> tilesets, MapLayer baseLayer, MapLayer buildingLayer, MapLayer
splatterLayer, CollisionLayer collisionLayer)
{
this.tilesets = tilesets;
this.mapLayers = new List<ILayer>();
this.collisionLayer = collisionLayer;
mapLayers.Add(baseLayer);
AddLayer(buildingLayer);
AddLayer(splatterLayer);
mapWidth = baseLayer.Width;
mapHeight = baseLayer.Height;
}
public TileMap(Tileset tileset, MapLayer baseLayer)
{
tilesets = new List<Tileset>
{
tileset
};
collisionLayer = new CollisionLayer();
mapLayers = new List<ILayer>
{
baseLayer
};
mapWidth = baseLayer.Width;
mapHeight = baseLayer.Height;
}
#endregion
#region Method Region
public void AddLayer(ILayer layer)
{
if (layer is MapLayer)
{
if (!(((MapLayer)layer).Width == mapWidth && ((MapLayer)layer).Height ==
mapHeight))
{
throw new Exception("Map layer size exception");
}
}
mapLayers.Add(layer);
}
public void AddTileset(Tileset tileset)
{
tilesets.Add(tileset);
}
public void Update(GameTime gameTime)
{
foreach (ILayer layer in mapLayers)
{
layer.Update(gameTime);
}
}
public void Draw(SpriteBatch spriteBatch, Camera camera)
{
foreach (MapLayer layer in mapLayers)
{
layer.Draw(spriteBatch, camera, tilesets);
}
}
#endregion
}
}
|
Java | UTF-8 | 531 | 1.921875 | 2 | [] | no_license | package com.challenge.challenge.service;
import com.challenge.challenge.feign.SpotifyFallback;
import com.challenge.challenge.feign.SpotifyFeign;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
public class HystrixFeignServiceImplTest {
private HystrixFeignService hystrixFeignService = new HystrixFeignServiceImpl();
@Test
public void testGetApi() {
SpotifyFeign api = hystrixFeignService.getApi(SpotifyFeign.class, "test", new SpotifyFallback());
assertNotNull(api);
}
}
|
C# | UTF-8 | 903 | 3.1875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace EAPAccess.Common.Classes
{
public class RandomPassword
{
public static string RandomGeneratePassword()
{
string allowedChars = "";
allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";
char[] sep = { ',' };
string[] arr = allowedChars.Split(sep);
string passwordString = "";
string temp = "";
Random rand = new Random();
for (int i = 0; i < 8; i++)
{
temp = arr[rand.Next(0, arr.Length)];
passwordString += temp;
}
return passwordString;
}
}
}
|
C++ | UTF-8 | 1,723 | 2.9375 | 3 | [] | no_license | // 23.merge-k-sorted-lists.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <random>
#include <bitset>
#include "..\Common\Common.h"
//#include "..\Common\GraphNode.h"
//#include "..\Common\TreeNode.h"
#include "..\Common\ListNode.h"
using namespace std;
ListNode* mergeKLists(vector<ListNode*>& lists)
{
ListNode *pHead = new ListNode(0);
ListNode *pNode = pHead;
int len = lists.size();
int nullCount = 0;
while (nullCount < len)
{
nullCount = 0;
pair<int, int> minVal = { -1, INT_MAX };
for (int i = 0; i < lists.size(); i++)
{
if (lists[i] == nullptr)
{
nullCount++;
continue;
}
if (lists[i]->val < minVal.second)
{
minVal.first = i;
minVal.second = lists[i]->val;
}
}
if (minVal.first == -1) continue;
pNode->next = lists[minVal.first];
pNode = pNode->next;
lists[minVal.first] = lists[minVal.first]->next;
}
pNode->next = nullptr;
pNode = pHead->next;
delete pHead;
return pNode;
}
int main()
{
vector<ListNode *> lists;
ListNode *pHead = nullptr;
pHead = StringToListNode("[1,5,5]");
lists.push_back(pHead);
pHead = nullptr;
pHead = StringToListNode("[1,3,4]");
lists.push_back(pHead);
pHead = nullptr;
pHead = StringToListNode("[2,6]");
lists.push_back(pHead);
pHead = nullptr;
pHead = StringToListNode("[1]");
lists.push_back(pHead);
pHead = nullptr;
for (auto p : lists)
{
cout << p << endl;
}
pHead = mergeKLists(lists);
cout << pHead << endl;
cout << endl;
} |
Ruby | UTF-8 | 3,252 | 2.828125 | 3 | [
"MIT"
] | permissive | require 'rubygems'
require 'net/ssh'
require 'net/ssh/gateway'
require 'activesupport'
require 'simple_gate/server_definition'
class SimpleGate
# Initialize a new SimpleGate
# @param [Hash] options Hash with options to configure SimpleGate. Defaults to set :verbose to false.
def initialize(options={})
@options = {
:verbose => false
}.merge(options)
end
# Is the verbose option turned on?
def verbose?
@options[:verbose]
end
# Connect through a list of gateways to a target server.
# Treats the last 'gateway' as the target server and the others as gateways.
#
# @param [Array] *gateways A list of gateway server names that can be found using ServerDefinition.find(). Should have at least one server name.
# @yieldparam [Net::SSH::Connection::Session] session SSH Session to the target server.
# @raise [ArgumentError] When no gateways are chosen.
def through_to(*gateways)
gateways = gateways.flatten
raise ArgumentError.new("No target chosen") if gateways.size == 0
target = ServerDefinition.find(gateways.pop)
if gateways.size == 0
target.connection_info do |host, user, options|
Net::SSH.start(host,user,options) do |session|
yield(session)
end
end
return
end
through(gateways) do |gate|
target.connection_info do |host, user, options|
gate.ssh(host, user, options) do |session|
yield(session)
end
end
end
nil
end
# Establish a series of gateways and yields the last one created.
# Will automatically shut down gateway connections when the block closes.
#
# Most of the code was taken from Capistrano and then changed to work
# outside of Capistrano.
#
# @param [Array] *gateways A list of gateway server names that can be found using ServerDefinition.find(). Should have at least one server name.
# @yieldparam [Net::SSH::Gateway] gateway Gateway object of the last tunnel endpoint.
# @raise [ArgumentError] When no gateways are chosen.
def through(*gateways)
Thread.abort_on_exception = true
open_connections = []
gateways = gateways.flatten.collect { |g| ServerDefinition.find(g) }
raise ArgumentError.new("No target chosen") if gateways.size == 0
tunnel = gateways[0].connection_info do |host, user, connect_options|
STDERR.puts "Setting up tunnel #{gateways[0]}" if verbose?
gw = Net::SSH::Gateway.new(host, user, connect_options)
open_connections << gw
gw
end
gateway = (gateways[1..-1]).inject(tunnel) do |tunnel, destination|
STDERR.puts "Connecting to #{destination}" if verbose?
tunnel_port = tunnel.open(destination.host, (destination.port || 22))
localhost_options = {:user => destination.user, :port => tunnel_port, :password => destination.password}
local_host = ServerDefinition.new("127.0.0.1", localhost_options)
local_host.connection_info do |host, user, connect_options|
STDERR.puts "Connecting using local info #{local_host}" if verbose?
gw = Net::SSH::Gateway.new(host, user, connect_options)
open_connections << gw
gw
end
end
yield(gateway)
ensure
while g = open_connections.pop
g.shutdown!
end
end
end
|
Swift | UTF-8 | 2,546 | 3.109375 | 3 | [] | no_license | //
// GroupedSortedComicsSpecs.swift
// BDDComicsListMacOSTests
//
// Created by William Hass on 2019-09-19.
// Copyright © 2019 William. All rights reserved.
//
import Foundation
import Quick
import Nimble
class GroupedSortedComicsSpecs: QuickSpec {
var groupedSortedComics: GroupedSortedComics!
override func spec() {
let comics = [
Comic(id: 4, title: "Comic"),
Comic(id: 1, title: "Aaa comic"),
Comic(id: 2, title: "Abb comic"),
Comic(id: 5, title: "Crook"),
Comic(id: 3, title: "Big comic"),
Comic(id: 5, title: "cool comic"),
]
self.groupedSortedComics = GroupedSortedComics(comics: comics)
describe("GroupedSortedComics") {
context("When grouping and sorting a list of comics") {
it("Should categorize comics in a dictionary grouped by their first letter") {
let groupedComics = self.groupedSortedComics.groupedComics
expect(groupedComics.keys.count).to(equal(3))
expect(groupedComics["a"]).toNot(beNil())
expect(groupedComics["a"]?.count).to(equal(2))
expect(groupedComics["b"]).toNot(beNil())
expect(groupedComics["b"]?.count).to(equal(1))
expect(groupedComics["c"]).toNot(beNil())
expect(groupedComics["c"]?.count).to(equal(3))
}
it("Should sort categories ascending") {
let orderedSections = self.groupedSortedComics.sortedKeys
expect(orderedSections[0]).to(equal("a"))
expect(orderedSections[1]).to(equal("b"))
expect(orderedSections[2]).to(equal("c"))
}
it("Should sort comics by the first title letter ascending") {
let letterASection = self.groupedSortedComics.groupedComics["a"]!
expect(letterASection[0].title).to(equal("Aaa comic"))
expect(letterASection[1].title).to(equal("Abb comic"))
let letterCSection = self.groupedSortedComics.groupedComics["c"]!
expect(letterCSection[0].title).to(equal("Comic"))
expect(letterCSection[1].title).to(equal("cool comic"))
expect(letterCSection[2].title).to(equal("Crook"))
}
}
}
}
}
|
Java | UTF-8 | 930 | 3.578125 | 4 | [] | no_license | import java.util.ArrayList;
public class p46 {
public static void main(String[]args) {
int n = 10000 , odd = 1 , p = 1;
ArrayList<Integer> a = new ArrayList<Integer>();
for(int i = 2; i < n; i++) {
if(isPrime(i)) a.add(i);
}
boolean f = true;
while(f) {
odd += 2;
int i = 1;
f = false;
while(odd >= a.get(i)) {
if(twiceSquare(odd-a.get(i))) {
f = true;
break;
}
else p = odd; //storing the smallest conjecture that couldn't fit the rule
i++;
}
}
System.out.println("The smallest odd composite that cannot be written as the sum of a prime and twice a square: " + p);
}
public static boolean twiceSquare(long x) {
double sq = Math.sqrt(x/2);
return sq == ((int)sq);
}
public static boolean isPrime(int x) {
for(int i = 2; i <= Math.sqrt(x); i++) {
if(x%i == 0) return false;
}
return true;
}
} |
C# | UTF-8 | 4,532 | 2.703125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SampleMongoCrud.Services;
using SampleMongoCrud.Models;
namespace SampleMongoCrud.Controllers
{
[Produces("application/json")]
[Consumes("application/json")]
[Route("[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
private readonly BookService _bookService;
public BooksController(bool test = false)
{
if (test)
{
_bookService = new BookServiceMock();
}
else
{
_bookService = new BookService();
}
}
/// <summary>Return books in pages of 10.</summary>
/// <param name="pageNumber">Starts in page 1</param>
/// <response code="200">Success</response>
[HttpGet]
[ProducesResponseType(typeof(List<Book>), StatusCodes.Status200OK)]
public IActionResult AllBooks(int? pageNumber = 1)
{
try
{
int? toSkip = (pageNumber - 1) * 10;
IEnumerable<Book> response = _bookService.Get(toSkip);
if (response.Count() == 0)
return NotFound();
return Ok(response);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
/// <summary>Search a book for a given id.</summary>
/// <param name="id">id</param>
/// <response code="200">Success</response>
[HttpGet("{id:length(24)}")]
[ProducesResponseType(typeof(Book), StatusCodes.Status200OK)]
public IActionResult BookById(string id)
{
try
{
Book found = _bookService.Get(id);
if (found == null)
return NotFound();
return Ok(found);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
/// <summary>Post a new book.</summary>
/// <param name="book">New book object</param>
/// <response code="201">Success</response>
[HttpPost]
[ProducesResponseType(typeof(Book), StatusCodes.Status201Created)]
public IActionResult CreateBook([FromBody] BookInfo book)
{
try
{
Book toCreate = JsonCasting.ChangeType<BookInfo, Book>(book);
return Created("CreateBook", _bookService.Create(toCreate));
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
/// <summary>Updates a book.</summary>
/// <param name="update">Update book object</param>
/// <param name="id">Id of the book to be updated</param>
/// <response code="200">Success</response>
[HttpPut("{id:length(24)}")]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult UpdateBook(string id, [FromBody] BookInfo update)
{
try
{
Book toUpdate = _bookService.Get(id);
if (toUpdate == null)
return NotFound();
Book theUpdate = JsonCasting.ChangeType<BookInfo, Book>(update);
theUpdate.Id = toUpdate.Id;
_bookService.Update(id, theUpdate);
return Ok();
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
/// <summary>Deletes a book.</summary>
/// <param name="id">Id of the book to be deleted</param>
/// <response code="200">Success</response>
[HttpDelete("{id:length(24)}")]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult Remove(string id)
{
try
{
Book toRemove = _bookService.Get(id);
if (toRemove == null)
return NotFound();
_bookService.Remove(toRemove.Id);
return Ok();
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
}
} |
C# | UTF-8 | 467 | 3.25 | 3 | [] | no_license | using System.Linq;
namespace CodeWars.Kata_550498447451fbbd7600041c
{
public class Kata
{
public static bool comp(int[] a, int[] b)
{
if ((a == null) || (b == null)) return false;
if (a.Length != b.Length) return false;
int[] aInOrder = a.OrderBy(x => x).ToArray();
int[] bInOrder = b.OrderBy(x => x).ToArray();
for (int i = 0; i < a.Length; i++)
{
if (aInOrder[i] * aInOrder[i] != bInOrder[i]) return false;
}
return true;
}
}
} |
Go | UTF-8 | 8,631 | 2.53125 | 3 | [
"MIT"
] | permissive | package login
import (
"errors"
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
"github.com/profclems/glab/commands/auth/authutils"
"github.com/profclems/glab/pkg/iostreams"
"github.com/AlecAivazis/survey/v2"
"github.com/MakeNowJust/heredoc"
"github.com/profclems/glab/api"
"github.com/profclems/glab/commands/cmdutils"
"github.com/profclems/glab/internal/config"
"github.com/profclems/glab/pkg/glinstance"
"github.com/spf13/cobra"
)
type LoginOptions struct {
IO *iostreams.IOStreams
Config func() (config.Config, error)
Interactive bool
Hostname string
Token string
}
var opts *LoginOptions
func NewCmdLogin(f *cmdutils.Factory) *cobra.Command {
opts = &LoginOptions{
IO: f.IO,
Config: f.Config,
}
var tokenStdin bool
cmd := &cobra.Command{
Use: "login",
Args: cobra.ExactArgs(0),
Short: "Authenticate with a GitLab instance",
Long: heredoc.Docf(`
Authenticate with a GitLab instance.
You can pass in a token on standard input by using %[1]s--stdin%[1]s.
The minimum required scopes for the token are: "api", "write_repository".
`, "`"),
Example: heredoc.Doc(`
# start interactive setup
$ glab auth login
# authenticate against gitlab.com by reading the token from a file
$ glab auth login --stdin < myaccesstoken.txt
# authenticate with a self-hosted GitLab instance
$ glab auth login --hostname salsa.debian.org
`),
RunE: func(cmd *cobra.Command, args []string) error {
if !opts.IO.PromptEnabled() && !tokenStdin && opts.Token == "" {
return &cmdutils.FlagError{Err: errors.New("--stdin or --token required when not running interactively")}
}
if opts.Token != "" && tokenStdin {
return &cmdutils.FlagError{Err: errors.New("specify one of --token or --stdin. You cannot use both flags at the same time")}
}
if tokenStdin {
defer opts.IO.In.Close()
token, err := ioutil.ReadAll(opts.IO.In)
if err != nil {
return fmt.Errorf("failed to read token from STDIN: %w", err)
}
opts.Token = strings.TrimSpace(string(token))
}
if opts.IO.PromptEnabled() && opts.Token == "" && opts.IO.IsaTTY {
opts.Interactive = true
}
if cmd.Flags().Changed("hostname") {
if err := hostnameValidator(opts.Hostname); err != nil {
return &cmdutils.FlagError{Err: fmt.Errorf("error parsing --hostname: %w", err)}
}
}
if !opts.Interactive {
if opts.Hostname == "" {
opts.Hostname = glinstance.Default()
}
}
return loginRun()
},
}
cmd.Flags().StringVarP(&opts.Hostname, "hostname", "h", "", "The hostname of the GitLab instance to authenticate with")
cmd.Flags().StringVarP(&opts.Token, "token", "t", "", "Your GitLab access token")
cmd.Flags().BoolVar(&tokenStdin, "stdin", false, "Read token from standard input")
return cmd
}
func loginRun() error {
c := opts.IO.Color()
cfg, err := opts.Config()
if err != nil {
return err
}
if opts.Token != "" {
if opts.Hostname == "" {
return errors.New("empty hostname would leak oauth_token")
}
err := cfg.Set(opts.Hostname, "token", opts.Token)
if err != nil {
return err
}
return cfg.Write()
}
hostname := opts.Hostname
apiHostname := opts.Hostname
defaultHostname := glinstance.OverridableDefault()
isSelfHosted := false
if hostname == "" {
var hostType int
err := survey.AskOne(&survey.Select{
Message: "What GitLab instance do you want to log into?",
Options: []string{
defaultHostname,
"GitLab Self-hosted Instance",
},
}, &hostType)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
isSelfHosted = hostType == 1
hostname = defaultHostname
apiHostname = hostname
if isSelfHosted {
err := survey.AskOne(&survey.Input{
Message: "GitLab hostname:",
}, &hostname, survey.WithValidator(hostnameValidator))
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
err = survey.AskOne(&survey.Input{
Message: "API hostname:",
Help: "For instances with different hostname for the API endpoint",
Default: hostname,
}, &apiHostname, survey.WithValidator(hostnameValidator))
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
}
}
fmt.Fprintf(opts.IO.StdErr, "- Logging into %s\n", hostname)
if token := config.GetFromEnv("token"); token != "" {
fmt.Fprintf(opts.IO.StdErr, "%s you have GITLAB_TOKEN or OAUTH_TOKEN environment variable set. Unset if you don't want to use it for glab\n", c.Yellow("!WARNING:"))
}
existingToken, _, _ := cfg.GetWithSource(hostname, "token", false)
if existingToken != "" && opts.Interactive {
apiClient, err := cmdutils.LabClientFunc(hostname, cfg, false)
if err != nil {
return err
}
user, err := api.CurrentUser(apiClient)
if err == nil {
username := user.Username
var keepGoing bool
err = survey.AskOne(&survey.Confirm{
Message: fmt.Sprintf(
"You're already logged into %s as %s. Do you want to re-authenticate?",
hostname,
username),
Default: false,
}, &keepGoing)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
if !keepGoing {
return nil
}
}
}
fmt.Fprintln(opts.IO.StdErr)
fmt.Fprintln(opts.IO.StdErr, heredoc.Doc(getAccessTokenTip(hostname)))
var token string
err = survey.AskOne(&survey.Password{
Message: "Paste your authentication token:",
}, &token, survey.WithValidator(survey.Required))
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
if hostname == "" {
return errors.New("empty hostname would leak token")
}
err = cfg.Set(hostname, "token", token)
if err != nil {
return err
}
err = cfg.Set(hostname, "api_host", apiHostname)
if err != nil {
return err
}
gitProtocol := "https"
apiProtocol := "https"
glabExecutable := "glab"
if exe, err := os.Executable(); err == nil {
glabExecutable = exe
}
credentialFlow := &authutils.GitCredentialFlow{Executable: glabExecutable}
if opts.Interactive {
err = survey.AskOne(&survey.Select{
Message: "Choose default git protocol",
Options: []string{
"SSH",
"HTTPS",
"HTTP",
},
Default: "HTTPS",
}, &gitProtocol)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
gitProtocol = strings.ToLower(gitProtocol)
if opts.Interactive && gitProtocol != "ssh" {
if err := credentialFlow.Prompt(hostname, gitProtocol); err != nil {
return err
}
}
if isSelfHosted {
err = survey.AskOne(&survey.Select{
Message: "Choose host API protocol",
Options: []string{
"HTTPS",
"HTTP",
},
Default: "HTTPS",
}, &apiProtocol)
if err != nil {
return fmt.Errorf("could not prompt: %w", err)
}
apiProtocol = strings.ToLower(apiProtocol)
}
fmt.Fprintf(opts.IO.StdErr, "- glab config set -h %s git_protocol %s\n", hostname, gitProtocol)
err = cfg.Set(hostname, "git_protocol", gitProtocol)
if err != nil {
return err
}
fmt.Fprintf(opts.IO.StdErr, "%s Configured git protocol\n", c.GreenCheck())
fmt.Fprintf(opts.IO.StdErr, "- glab config set -h %s api_protocol %s\n", hostname, apiProtocol)
err = cfg.Set(hostname, "api_protocol", apiProtocol)
if err != nil {
return err
}
fmt.Fprintf(opts.IO.StdErr, "%s Configured API protocol\n", c.GreenCheck())
}
apiClient, err := cmdutils.LabClientFunc(hostname, cfg, false)
if err != nil {
return err
}
user, err := api.CurrentUser(apiClient)
if err != nil {
return fmt.Errorf("error using api: %w", err)
}
username := user.Username
err = cfg.Set(hostname, "user", username)
if err != nil {
return err
}
err = cfg.Write()
if err != nil {
return err
}
if credentialFlow.ShouldSetup() {
err := credentialFlow.Setup(hostname, gitProtocol, username, token)
if err != nil {
return err
}
}
fmt.Fprintf(opts.IO.StdErr, "%s Logged in as %s\n", c.GreenCheck(), c.Bold(username))
return nil
}
func hostnameValidator(v interface{}) error {
val := fmt.Sprint(v)
if len(strings.TrimSpace(val)) < 1 {
return errors.New("a value is required")
}
re := regexp.MustCompile(`^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])(:[0-9]+)?(/[a-z0-9]*)*$`)
if !re.MatchString(val) {
return fmt.Errorf("invalid hostname %q", val)
}
return nil
}
func getAccessTokenTip(hostname string) string {
glHostname := hostname
if glHostname == "" {
glHostname = glinstance.OverridableDefault()
}
return fmt.Sprintf(`
Tip: you can generate a Personal Access Token here https://%s/-/profile/personal_access_tokens
The minimum required scopes are 'api' and 'write_repository'.`, glHostname)
}
|
SQL | UTF-8 | 2,590 | 3 | 3 | [] | no_license | -- phpMyAdmin SQL Dump
-- version 5.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 29, 2020 at 12:56 AM
-- Server version: 10.4.11-MariaDB
-- PHP Version: 7.4.1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `pw_193040046`
--
-- --------------------------------------------------------
--
-- Table structure for table `mahasiswa`
--
CREATE TABLE `mahasiswa` (
`id` int(11) NOT NULL,
`nrp` char(9) DEFAULT NULL,
`nama` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`jurusan` varchar(50) NOT NULL,
`gambar` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `mahasiswa`
--
INSERT INTO `mahasiswa` (`id`, `nrp`, `nama`, `email`, `jurusan`, `gambar`) VALUES
(1, '193040046', 'Aji Nuansa Sengarie', 'ansengarie@gmail.com', 'Teknik Informatika', '193040046.jpg'),
(2, '193040056', 'Sahid Jafar', 'sahidjafar@gmail.com', 'Teknik Informatika', '193040056.jpg'),
(3, '193040043', 'Herlan Nurachman', 'herlannur@gmail.com', 'Teknik Informatika', '193040043.jpg'),
(4, '193040071', 'Tresna Eka Widiana', 'tresnaeka@gmail.com', 'Teknik Informatika', '193040071.jpg'),
(5, '193040052', 'Adinda Fadhil Patria', 'didapatria@gmail.com', 'Teknik Informatika', '193040052.jpg'),
(6, '193040053', ' Fauzan Nursalma Mawardi', 'fauzannur@gmail.com', 'Teknik Informatika', '193040053.jpg'),
(7, '193040070', 'Muhammad Angga Saputra', 'manggasaputra@gmail.com', 'Teknik Informatika', '193040070.jpg'),
(8, '193040069', 'Agam Febriansyah', 'agamfeb@gmail.com', 'Teknik Informatika', '193040069.jpg'),
(9, '193040058', 'Bayu Cucan Herdian', 'bayucucan@gmail.com', 'Teknik Informatika', '193040058.jpg'),
(10, '193040042', 'Suhendani', 'suhendaniaja@gmail.com', 'Teknik Informatika', '193040042.jpg'),
(11, '193040055', 'Devi Ayu Lestari', '193040055@mail.unpas.ac.id', 'Teknik Informatika', '193040055.jpg'),
(13, '193040050', 'Salsabila Nada Adzani', '193040050@mail.unpas.ac.id', 'Teknik Informatika', '193040050.jpg'),
(21, '193040054', 'Aldi Ageng', 'aldiageng@gmail.com', 'Teknik Informatika', '193040054.jpg');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `mahasiswa`
--
ALTER TABLE `mahasiswa`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `mahasiswa`
--
ALTER TABLE `mahasiswa`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java | UTF-8 | 611 | 2.3125 | 2 | [] | no_license | package com.perennial.patientapp.vo;
import javax.persistence.*;
@Entity
@Table(name = "DISEASE")
public class DiseaseVO implements IGenericVO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private long id;
@Column(name = "DISEASE_NAME")
private String diseaseName;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDiseaseName() {
return diseaseName;
}
public void setDiseaseName(String diseaseName) {
this.diseaseName = diseaseName;
}
}
|
C# | UTF-8 | 1,942 | 2.640625 | 3 | [] | no_license | using AutoMapper;
using EgitimPortal.Business.Abstract;
using EgitimPortal.DataAccess.Abstract;
using EgitimPortal.Entities.Concrete;
using System.Collections.Generic;
namespace EgitimPortal.Business.Concrete.Managers
{
public class CourseCategoriesManager : ICourseCategoriesService
{
private ICourseCategoriesDal _coursecategoriesDal;
private readonly IMapper _mapper;
public CourseCategoriesManager(ICourseCategoriesDal coursecategoriesDal, IMapper mapper)
{
_coursecategoriesDal = coursecategoriesDal;
_mapper = mapper;
}
public List<CourseCategories> GetAll()
{
var model = _mapper.Map<List<CourseCategories>>(_coursecategoriesDal.GetList());
return model;
}
public CourseCategories GetById(int id)
{
var model = _coursecategoriesDal.Get(p => p.Id == id);
return model;
}
public CourseCategories Add(CourseCategories coursecategories)
{
return _coursecategoriesDal.Add(coursecategories);
}
public CourseCategories Update(CourseCategories coursecategories)
{
return _coursecategoriesDal.Update(coursecategories);
}
public void Delete(CourseCategories coursecategories)
{
_coursecategoriesDal.Delete(coursecategories);
}
///Courses Tablosu ile olan Foreign Key Column CourseId
public List<CourseCategories> GetListByCoursesId(int courseid)
{
var model = _coursecategoriesDal.GetList(p => p.CourseId == courseid);
return model;
}
///Categories Tablosu ile olan Foreign Key Column FlagId
public List<CourseCategories> GetListByCategoriesId(int flagid)
{
var model = _coursecategoriesDal.GetList(p => p.FlagId == flagid);
return model;
}
}
} |
Python | UTF-8 | 2,892 | 3.40625 | 3 | [] | no_license | import numpy as np
import re
import os
def load_data_and_labels(data_files):
"""
1. 加载所有数据和标签
2. 可以进行多分类,每个类别的数据单独放在一个文件中
3. 保存处理后的数据
"""
data_files = data_files.split(',')
num_data_file = len(data_files)
assert num_data_file > 1
x_text = []
y = []
for i, data_file in enumerate(data_files):
# 将数据放在一起
data = read_and_clean_zh_file(data_file, True)
x_text += data
# 形成数据对应的标签
label = [0] * num_data_file
label[i] = 1
labels = [label for _ in data]
y += labels
return [x_text, np.array(y)]
def read_and_clean_zh_file(input_file, output_cleaned_file=False):
"""
1. 读取中文文件并清洗句子
2. 可以将清洗后的结果保存到文件
3. 如果已经存在经过清洗的数据文件则直接加载
"""
data_file_path, file_name = os.path.split(input_file)
output_file = os.path.join(data_file_path, 'cleaned_' + file_name)
if os.path.exists(output_file):
lines = list(open(output_file, 'r').readlines())
lines = [line.strip() for line in lines]
else:
lines = list(open(input_file, 'r').readlines())
lines = [clean_str(seperate_line(line)) for line in lines]
if output_cleaned_file:
with open(output_file, 'w') as f:
for line in lines:
f.write(line + '\n')
return lines
def clean_str(string):
"""
1. 将除汉字外的字符转为一个空格
2. 将连续的多个空格转为一个空格
3. 除去句子前后的空格字符
"""
string = re.sub(r'[^\u4e00-\u9fff]', ' ', string)
string = re.sub(r'\s{2,}', ' ', string)
return string.strip()
def seperate_line(line):
"""
将句子中的每个字用空格分隔开
"""
return ''.join([word + ' ' for word in line])
def batch_iter(data, batch_size, num_epochs, shuffle=True):
'''
生成一个batch迭代器
'''
data = np.array(data)
data_size = len(data)
num_batches_per_epoch = int((data_size - 1) / batch_size) + 1
for epoch in range(num_epochs):
if shuffle:
shuffle_indices = np.random.permutation(np.arange(data_size))
shuffled_data = data[shuffle_indices]
else:
shuffled_data = data
for batch_num in range(num_batches_per_epoch):
start_idx = batch_num * batch_size
end_idx = min((batch_num + 1) * batch_size, data_size)
yield shuffled_data[start_idx:end_idx]
# yield 能把该函数变成一个迭代对象
if __name__ == '__main__':
data_files = './data/maildata/spam_5000.utf8,./data/maildata/ham_5000.utf8'
x_text, y = load_data_and_labels(data_files)
print(len(y))
|
PHP | UTF-8 | 2,229 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Piloco;
use Illuminate\Support\Facades\Auth;
class PilocoCrudController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$user = Auth::user();
$pilocos = Piloco::orderBy('created_at', 'desc')->get();
return $pilocos;
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$piloco = new Piloco([
'mode' => $request->input('mode'),
'name' => $request->input('name'),
'verre' => $request->input('verre')
]);
$piloco->save();
return response()->json('Product created!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$piloco = Piloco::find($id);
return response()->json($piloco);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$piloco = Piloco::find($id);
$piloco->update($request->all());
return response()->json('piloco updated!');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$piloco = Piloco::find($id);
$piloco->delete();
return response()->json('piloco deleted!');
}
}
|
Swift | UTF-8 | 534 | 2.734375 | 3 | [] | no_license | class Solution {
// 注意:上一次提交的代码有误
//DP
// [-2,1,-3,4,-1,2,1,-5,4]
func maxSubArray(_ nums: [Int]) -> Int {
if nums.isEmpty { return 0 }
// 递推公式:dp(i) = max(0, dp[i-1]) + nums[i]
var dpArray = [Int](repeating: 0, count: nums.count)
dpArray[0] = nums[0]
for i in 1..<nums.count {
dpArray[i] = max(0, dpArray[i-1]) + nums[i]
}
return dpArray.max()!
}
} |
Markdown | UTF-8 | 1,063 | 2.859375 | 3 | [] | no_license | # Article 2
Les végétaux, produits végétaux et autres objets mentionnés à l'annexe V, partie A, chapitre Ier, sont soumis à un contrôle sanitaire à la production afin de vérifier :
a) Qu'ils ne sont pas contaminés par les organismes nuisibles énumérés à l'annexe I, partie A, chapitre II ;
b) Que ces végétaux, produits végétaux et autres objets mentionnés également à l'annexe II, partie A, chapitre II, ne sont pas contaminés par les organismes nuisibles les concernant, énumérés dans cette partie d'annexe ;
c) Que ces végétaux, produits végétaux et autres objets mentionnés également à l'annexe IV, partie A, chapitre II, répondent aux exigences particulières les concernant, figurant dans cette partie d'annexe.
Sans préjudice des dispositions de l'article R251-6 du code rural, si au cours de ce contrôle il apparaît que les exigences mentionnées ci-dessus ne sont pas respectées, le passeport phytosanitaire n'est pas délivré et ne peut être apposé sur ces végétaux, produits végétaux ou autres objets.
|
C# | UTF-8 | 534 | 2.625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace BookInventory
{
class BookInventory
{
// notice the private set on the id
public int Id { get; private set; }
public String BookName { get; set; }
public String AuthorName { get; set; }
public BookInventory(String bookname, String authorname)
{
this.BookName = bookname;
this.AuthorName = authorname;
}
}
}
|
JavaScript | UTF-8 | 1,021 | 2.625 | 3 | [] | no_license | import types from "../actions/_types";
const INITIAL_STATE = { allCategories: [], category: {}, isLoading: false };
export default (state = INITIAL_STATE, action) => {
const { type, payload } = action;
switch (type) {
case types.LOADING_CATEGORIES:
return { ...state, isLoading: true };
case types.FETCH_ALL_CATEGORIES_SUCCESS:
return { ...state, allCategories: payload, isLoading: false };
case types.ADD_CATEGORY_SUCCESS:
return {
...state,
allCategories: [...state.allCategories, payload.data]
};
case types.UPDATE_CATEGORY_SUCCESS:
return {
...state,
allCategories: state.allCategories.map(category =>
category._id === payload._id ? { ...payload } : category
)
};
case types.DELETE_CATEGORY_SUCCESS:
return {
...state,
allCategories: state.allCategories.filter(category =>
{ return category._id !== payload._id }
)
};
default:
return state;
}
};
|
JavaScript | UTF-8 | 704 | 3.546875 | 4 | [] | no_license | var list = [ "vinoj, arjun", "dixy", "amala, ken"];
function removeComma(list){
for( var i= 0; i<list.length; i++) {
if (list[i].search(',')> -1){
let a = list[i]
// console.log(list[i].search(','),
// a.slice(0, a.search(',')),
// a.slice(a.search(',')+2, a.length) );
list.splice(i,1);
// console.log(list)
list.splice(i, 0, a.slice(0, a.search(',')), a.slice(a.search(',')+2, a.length));
}
}
console.log(list)
}
removeComma(list);
var array = [ [{name: "vinoj"}, {name: "dixy"}], {name: "amala"}, {name: "arjun"}];
console.log(array.flat(Infinity)) // elegent way. |
JavaScript | UTF-8 | 1,392 | 2.609375 | 3 | [] | no_license | var Promise = require('bluebird');
exports.EventEmitterPromisifier = function (originalMethod) {
// return a function
return function promisified() {
var args = [].slice.call(arguments);
// Needed so that the original method can be called with the correct receiver
var self = this;
// which returns a promise
return new Promise(function (resolve, reject) {
// We call the originalMethod here because if it throws,
// it will reject the returned promise with the thrown error
var emitter = originalMethod.apply(self, args);
emitter
.on("success", function (data, response) {
resolve([data, response]);
})
.on("fail", function (data, response) {
// Erroneous response like 400
resolve([data, response]);
})
.on("error", function (err) {
reject(err);
})
.on("abort", function () {
reject(new Promise.CancellationError());
})
.on("timeout", function () {
reject(new Promise.TimeoutError());
});
});
};
};
exports.methodNamesToPromisify = "get post put del head patch json postJson putJson".split(" ");
|
Java | UTF-8 | 1,196 | 2.296875 | 2 | [] | no_license | package com.zjl.mouse.utils.trace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author zhujinglei
*/
public class TraceRecord {
private final String error = "ERROR";
private static Logger logger = LoggerFactory.getLogger(TraceRecord.class);
private final String format = "[TraceLog]-[{}]-[请求={}.{}]-[服务类型={}]-[服务名={}]-[traceID={}]-[spanID={}]-[耗时={}]-[referenceId={}]\n {}";
public TraceRecord() {
}
public void record(TraceRecordDTO dto) {
this.record(dto.getLevel(), "[TraceLog]-[{}]-[请求={}.{}]-[服务类型={}]-[服务名={}]-[traceID={}]-[spanID={}]-[耗时={}]-[referenceId={}]\n {}", new Object[]{dto.getRecordType(), dto.getClientGroup(), dto.getClientIp(), dto.getProtocol(), dto.getServerName(), dto.getRecordId(), dto.getSpanId(), dto.getCost(), dto.getReferenceId(), dto.getRecordInfo()});
}
protected Logger getLogger() {
return logger;
}
protected void record(String level, String format, Object[] obj) {
if (error.equals(level)) {
this.getLogger().error(format, obj);
} else {
this.getLogger().info(format, obj);
}
}
}
|
Java | UTF-8 | 194 | 2.734375 | 3 | [] | no_license | package homework1;
interface SimpleMath {
public int sum(int a , int b);
public int subtraction(int a ,int b);
public int multiplication(int a ,int b);
public int division(int a, int b);
}
|
Python | UTF-8 | 270 | 3.171875 | 3 | [] | no_license | class Text:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
def to_dict(self):
return {"name": str(self.__name)}
|
Java | UTF-8 | 2,268 | 2.171875 | 2 | [] | no_license | package com.javaex.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.javaex.service.ShareReplyService;
import com.javaex.vo.ShareReplyVo;
@Controller
public class ShareReplyController {
@Autowired
private ShareReplyService shareReplyService;
//------------------------------------------------------------------------------------- 댓글 ajax
@RequestMapping("/replyAdd")
public String replyAdd() {
System.out.println("ajax로 add처리!~!~!~!~!");
return "main/share_petagram_detail";
}
//------------------------------------------------------------------------------------- 댓글 리스트
// //댓글 리스트
// @ResponseBody
// @RequestMapping("/detailList/{shareNo}")
// public List<ShareReplyVo> detailList(@PathVariable("shareNo") int shareNo) {
// System.out.println("detailList@#@#@#@#@");
//
// List<ShareReplyVo> drList = shareReplyService.getList(shareNo);
//
// System.out.println(drList.toString());
//
// return drList;
// }
//------------------------------------------------------------------------------------- 댓글 추가
//댓글 작성
@ResponseBody
@RequestMapping("/write/{shareNo}")
public ShareReplyVo write(@RequestBody ShareReplyVo shareReplyVo, @PathVariable("shareNo") int shareNo) {
System.out.println("shareReplyController전-----@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
System.out.println(shareReplyVo.toString());
ShareReplyVo replyAdd = shareReplyService.addReply(shareReplyVo, shareNo);
int count = shareReplyService.replyCount(shareNo);
System.out.println("count 댓글 갯수 시발아"+count);
// int count = 0;
// count++;
// replyNo = count;
// insert (shareReplyVo);
return replyAdd;
}
//------------------------------------------------------------------------------------- 댓글 삭제
}
|
C++ | UTF-8 | 5,015 | 3.375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <fstream>
using namespace std;
class Reader
{
private:
int curPos;
char curChar;
string source;
string filepath;
public:
Reader()
{
source = " ";
curPos = -1;
nextChar();
}
Reader(string filepath)
{
this->filepath = filepath;
if (filepath == "" || filepath == " " || filepath == "\n")
{
this->filepath += "codes/";
cout << "Enter brainfuck code (or filename adding ~ before it):\n";
cin >> source;
if (source[0] == '~')
{
this->filepath += source.substr(1, source.length());
readFile();
}
}
else
{
readFile();
}
curPos = -1;
nextChar();
}
void readFile()
{
ifstream sourceFile;
sourceFile.open(filepath);
if (sourceFile)
{
getline(sourceFile, source, '\0');
}
else
{
cout << "~ ! No such file (" + filepath + ") in codes directory. Please add one first! \n";
cout << "~ ! Exiting now !\n";
exit(EXIT_FAILURE);
}
sourceFile.close();
source += '\n';
}
char getChar()
{
return curChar;
}
void nextChar()
{
curChar = source[++curPos];
}
void previousChar()
{
curChar = source[--curPos];
}
int getCurPos()
{
return curPos;
}
// $D=Decimal, $A=ASCII, Default: D
char getOutputMode()
{
while (getChar() != '$' && getChar() != '>' && getChar() != '<' && getChar() != '+' && getChar() != '-' && getChar() != '.' && getChar() != ',' && getChar() != '[' && getChar() != ']')
{
nextChar();
}
if (getChar() == '$')
{
nextChar();
return getChar();
}
else
{
return 'D';
}
}
};
// This is the Brainfuck interpreter which runs Brainfuck codes from files or manual input.
class Interpreter
{
private:
char mem[3000] = {0};
int memSize;
char *ptr;
char outputMode; // $A = ASCII or $D = DECIMAL
int loopDepth; // 0 [ 1 [ 2 [ 3 ] 2 ] 1 ] 0
Reader reader;
public:
Interpreter(Reader reader)
{
this->reader = reader;;
ptr = mem;
memSize = 3000;
outputMode = reader.getOutputMode();
interpret();
}
void interpret()
{
while (reader.getChar() != '\0')
{
if (reader.getChar() == '<')
{
--ptr;
if (ptr < mem)
{
ptr = &mem[memSize];
}
}
else if (reader.getChar() == '>')
{
++ptr;
if (ptr > &mem[3000])
{
ptr = mem;
}
}
else if (reader.getChar() == '+')
{
++*ptr;
}
else if (reader.getChar() == '-')
{
--*ptr;
}
else if (reader.getChar() == '.')
{
// $D means decimal output, $A means ASCII output
if (outputMode == 'D')
{
cout << "MEM[" << ptr - mem << "] = " << to_string((int)*ptr) << '\n';
}
else if (outputMode == 'A')
{
cout << *ptr;
}
}
else if (reader.getChar() == ',')
{
cout << "Input : ";
cin >> *ptr;
}
// If memory currently pointing at is zero goto next same depths ']'
else if (reader.getChar() == '[')
{
if ((int)*ptr == 0)
{
loopDepth = 1;
reader.nextChar();
while (loopDepth != 0)
{
if(reader.getChar() == '[')
++loopDepth;
else if(reader.getChar() == ']')
--loopDepth;
reader.nextChar();
if(!reader.getChar() == '\0') // If EOF
{
cout << "Error no matching closing ']' braces!";
exit(EXIT_SUCCESS);
}
}
}
}
// If memory currently pointing at is non-zero then goto goto next same depths preceding '['
else if (reader.getChar() == ']')
{
if ((int)*ptr != 0)
{
loopDepth = 1;
reader.previousChar();
while (loopDepth != 0)
{
if(reader.getChar() == ']')
++loopDepth;
else if(reader.getChar() == '[')
--loopDepth;
reader.previousChar();
if(reader.getChar() == '\0') // If EOF
{
cout << "Error no matching opening '[' braces!";
exit(EXIT_FAILURE);
}
}
}
}
// Just skip comments starting with # (Not a brainfuck directive)
else if (reader.getChar() == '#')
{
while (reader.getChar() != '\n')
reader.nextChar();
}
reader.nextChar();
}
}
};
void printHelp()
{
cout << "=========================\n";
cout << "= BRAINFUCK INTERPRETER =\n";
cout << "=========================\n";
cout << "# This interpreter can directly run codes from your input or filename given.\n";
cout << "# This interpreter searches for brainfuck files (*.bf) in codes directory.\n";
cout << "# If inputting filenames it must be followed by a ~ sign.\n";
cout << "# For inputting code just type it directly.\n";
cout << "# $ is output mode controller.\n";
cout << "# Write $ASCII or $A at the start of line for ASCII output.\n";
cout << "# Write $DECIMAl or $D at the start of line forDECIMAL output.\n";
cout << "\n";
}
int main(int argc, char *argv[])
{
string filepath = "codes/";
if (argc >= 2)
filepath += argv[1];
else
{
printHelp();
filepath = "";
}
Reader reader(filepath);
Interpreter interpreter(reader);
cout << '\n';
return 0;
}
|
Python | UTF-8 | 11,799 | 2.984375 | 3 | [] | no_license | import agent, copy, evaluation, game, math, random, itertools, argparse
NUM_DECKS = 1
NUM_CARDS = 5 # Must be <= 13 and non-zero
def run_game(g, agents, verbose=1):
# Welcome message
if verbose != 0:
print "\nWelcome to the card game BS! You are player 0, " + \
"and there are {} other players.".format(len(g.players)-1)
print "==============================================================================="
print "===============================================================================\n"
# Initialize array of model based reflex agents
modelReflexAgents = [a.playerNum for a in agents if isinstance(a, agent.ModelReflexAgent)]
# Run game
over = False
currPlayer = 0
while not over:
# Print turn information
if verbose != 0:
g.printTurn()
# Get actions for current player and select one to take
currAgent = agents[currPlayer]
moves = g.getActions(currPlayer)
action = currAgent.getAction(moves, g)
currPlayer = g.currPlayer
g.takeAction(action, currPlayer, verbose)
currCaller = g.currPlayer
while(True):
# Take the first call after the player who just played
call = agents[currCaller].getCall(g, verbose)
# Use call to update oppCallProbs for all model based reflex agents
for a in modelReflexAgents:
agents[a].updateCallProb(currCaller, call)
if call:
isLying = g.takeCall(currCaller, verbose)
for a in modelReflexAgents:
agents[a].updateLieProb(currPlayer, isLying)
break
currCaller = (currCaller + 1) % g.numPlayers
# If we wrap around to the player who just played, break
if currCaller == currPlayer:
break
currPlayer = g.currPlayer
over = g.isOver()
if verbose != 0:
print "\n=========================" + \
"======================================================\n"
winner = g.winner()
return winner
def extractFeatures(state):
game, playerNum = state
features = []
# Num cards in own hand
features.append(sum(game.players[playerNum].hand))
# Num cards in opponents hands
for i in range(len(game.players)):
if i != playerNum:
features.append(sum(game.players[i].hand))
# Size of discard pile
features.append(sum(game.discard))
# Number of i of a kind you have in your hand
for i in range(0, 5):
features.append(game.players[playerNum].hand.count(i))
# Number of next two required cards you have
if game.currPlayer == playerNum:
nextCard = (game.currCard + game.numPlayers) % NUM_CARDS
else:
nextCard = (game.currCard + (playerNum - game.currPlayer) % game.numPlayers) % NUM_CARDS
nextNextCard = (nextCard + game.numPlayers) % NUM_CARDS
features.append(game.players[playerNum].hand[nextCard])
features.append(game.players[playerNum].hand[nextNextCard])
features+=game.players[playerNum].hand
return features
def logLinearEvaluation(state, w):
"""
Evaluate the current state using the log-linear evaluation
function.
@param state : Tuple of (game, playerNum), the game is
a game object (see game.py for details, and playerNum
is the number of the player for whose utility the state is
being evaluated.
@param w : List of feature weights.
@returns V : Evaluation of current game state.
"""
features = extractFeatures(state)
dotProduct = sum([features[i] * w[i] for i in range(len(features))])
V = float(1)/(1 + math.exp(-dotProduct))
return V
def TDUpdate(state, nextState, reward, w, eta):
"""
Given two sequential game states, updates the weights
with a step size of eta, using the Temporal Difference learning
algorithm.
@param state : Tuple of game state (game object, player).
@param nextState : Tuple of game state (game object, player),
note if the game is over this will be None. In this case,
the next value for the TD update will be 0.
@param reward : The reward is 1 if the game is over and your
player won, 0 otherwise.
@param w : List of feature weights.
@param eta : Step size for learning.
@returns w : Updated weights.
"""
if nextState:
residual = reward + logLinearEvaluation(nextState, w) - logLinearEvaluation(state, w)
else:
residual = reward - logLinearEvaluation(state, w)
phi = extractFeatures(state)
expTerm = math.exp(-sum([phi[i] * w[i] for i in range(len(phi))]))
gradCoeff = expTerm / math.pow((1 + expTerm), 2)
for i in range(len(w)):
gradient = phi[i] * gradCoeff
w[i] += (eta * residual * gradient)
return w
"""
Plays a training tournament between the reflex or model agents and picks
the one that won its round to advance. At the end, return the weight
vector of the overall winner.
"""
def tournament(numPlayers=3, numIters=50, numContenders = 27, isModel=False):
tournamentArr = []
for i in range(numContenders):
tournamentArr.append(train(numPlayers, numIters))
while(len(tournamentArr) != 1):
newArr = []
iterable = iter(tournamentArr)
for i in iterable:
weights = [i, iterable.next(), iterable.next()]
w = train(numPlayers, numIters, isModel, weights)
newArr.append(w)
tournamentArr = newArr
return tournamentArr[0]
"""
Trains reflex or model agents using TD learning. Returns the resulting
weight vector.
"""
def train(numAgents=3, numGames=50, isModel=False, weights = None):
print "Training on {} players for {} iterations...".format(numAgents, numGames)
alpha = 1e-1
numFeats = 8 + numAgents + NUM_CARDS
weightVector = []
for i in range(numAgents):
weight = [random.gauss(-1e-1, 1e-2) for _ in range(numFeats)]
weightVector.append(weight)
if not weights:
if isModel:
agents = [agent.ModelReflexAgent(i, numAgents, logLinearEvaluation, weightVector[i]) for i in range(numAgents)]
else:
agents = [agent.ReflexAgent(i, logLinearEvaluation, weightVector[i]) for i in range(numAgents)]
else:
agents = []
for i in range(len(weights)):
if isModel:
agents.append(agent.ModelReflexAgent(i, numAgents, logLinearEvaluation, weights[i]))
else:
agents.append(agent.ReflexAgent(i, logLinearEvaluation, weights[i]))
# Initialize array of model based reflex agents
modelReflexAgents = [a.playerNum for a in agents if isinstance(a, agent.ModelReflexAgent)]
i = 0
winners = [0 for j in range(numAgents)]
numGames = int(numGames)
while i < numGames:
g = game.Game(len(agents), NUM_DECKS)
# Run game
over = False
currPlayer = 0
cycle = False
turnCounter = 0
threshold = 100
oldW = list(weightVector[currPlayer])
oldAgents = copy.deepcopy(agents)
while not over:
if turnCounter > threshold:
cycle = True
break
turnCounter += 1
states = [(g.clone(), currPlayer)]
# Get actions for current player and select one to take
currAgent = agents[currPlayer]
moves = g.getActions(currPlayer)
action = currAgent.getAction(moves, g)
currPlayer = g.currPlayer
g.takeAction(action, currPlayer, verbose=0)
currCaller = g.currPlayer
while(True):
# Take the first call after the player who just played
call = agents[currCaller].getCall(g, verbose=0)
for a in modelReflexAgents:
agents[a].updateCallProb(currCaller, call)
if call:
isLying = g.takeCall(currCaller, verbose=0)
for a in modelReflexAgents:
agents[a].updateLieProb(currPlayer, isLying)
break
currCaller = (currCaller + 1) % g.numPlayers
# If we wrap around to the player who just played, break
if currCaller == currPlayer:
break
for state in states:
nextState = (g, state[1])
weightVector[currPlayer] = TDUpdate(state,nextState,0, weightVector[currPlayer],alpha)
agents[currPlayer].setWeights(weightVector[currPlayer])
currPlayer = g.currPlayer
over = g.isOver()
if not cycle:
winner = g.winner()
weightVector[winner] = TDUpdate((g, winner),None, 1.0, weightVector[winner] ,alpha)
i += 1
winners[winner] += 1
else:
i += 1
w = oldW
agents = oldAgents
#Get weight vector that won the most
index = winners.index(max(winners))
return weightVector[index]
def test(agents, numGames=100, verbose=0):
playerWin = [0 for i in range(len(agents))] #Our agent won, other agent won
for i in range(numGames):
g = game.Game(len(agents), NUM_DECKS)
winner = run_game(g, agents, verbose)
playerWin[winner] += 1
for j in range(len(agents)):
if j == 0:
winRate = float(playerWin[j]) / sum(playerWin)
print "Player {} win rate: {}".format(j, winRate)
return winRate
def main(args=None):
# Parse command line arguments
argNames = ['-trainGames', '-run', '-p', '-test', '-agent', '-opp', '-tournament', '-human', '-verbose']
parser = argparse.ArgumentParser(description='Process input parameters.')
for arg in argNames:
parser.add_argument(arg)
namespace = parser.parse_args()
numPlayers = int(getattr(namespace, 'p')) if getattr(namespace, 'p') else 3
numTrainGames = int(getattr(namespace, 'trainGames')) if getattr(namespace, 'trainGames') else 50
numTestGames = int(getattr(namespace, 'test')) if getattr(namespace, 'test') else 100
numRuns = int(getattr(namespace, 'run')) if getattr(namespace, 'run') else 10
agentType = getattr(namespace, 'agent') if getattr(namespace, 'agent') else 'model'
oppType = getattr(namespace, 'opp') if getattr(namespace, 'opp') else 'simple'
isTournament = (getattr(namespace, 'tournament') == 'y')
isHuman = (getattr(namespace, 'human') == 'y')
verbose = (getattr(namespace, 'verbose') == 'y')
winRates = []
for i in range(numRuns):
# Play a game with human agent
if isHuman:
agents = [agent.HumanAgent(0)]
for j in range(1, numPlayers):
if oppType == 'random':
agents.append(agent.RandomAgent(j))
elif oppType == 'simple':
agents.append(agent.ReflexAgent(j, evaluation.simpleEvaluation))
elif oppType == 'honest':
agents.append(agent.HonestAgent(j))
elif oppType == 'dishonest':
agents.append(agent.DishonestAgent(j))
elif oppType == 'bs':
agents.append(agent.AlwaysCallBSAgent(j))
g = game.Game(numPlayers, NUM_DECKS)
run_game(g, agents)
# Play a game with computer agent
else:
agents = []
if agentType == 'random':
agents.append(agent.RandomAgent(0))
elif agentType == 'simple':
agents.append(agent.ReflexAgent(0, evaluation.simpleEvaluation))
elif agentType == 'honest':
agents.append(agent.HonestAgent(0))
elif agentType == 'dishonest':
agents.append(agent.DishonestAgent(0))
elif agentType == 'bs':
agents.append(agent.AlwaysCallBSAgent(0))
elif agentType == 'reflex':
if isTournament:
w = tournament(numPlayers, numTrainGames)
a = agent.ReflexAgent(0, logLinearEvaluation, w)
agents.append(a)
else:
w = train(numPlayers, numTrainGames)
a = agent.ReflexAgent(0, logLinearEvaluation, w)
agents.append(a)
elif agentType == 'model':
if isTournament:
w = tournament(numPlayers, numTrainGames, isModel=True)
a = agent.ModelReflexAgent(0, numPlayers, logLinearEvaluation, w)
agents.append(a)
else:
w = train(numPlayers, numTrainGames, isModel=True)
a = agent.ModelReflexAgent(0, numPlayers, logLinearEvaluation, w)
agents.append(a)
for j in range(1, numPlayers):
if oppType == 'random':
agents.append(agent.RandomAgent(j))
elif oppType == 'simple':
agents.append(agent.ReflexAgent(j, evaluation.simpleEvaluation))
elif oppType == 'honest':
agents.append(agent.HonestAgent(j))
elif oppType == 'dishonest':
agents.append(agent.DishonestAgent(j))
elif oppType == 'bs':
agents.append(agent.AlwaysCallBSAgent(j))
winRates.append(test(agents, numTestGames, verbose))
if winRates:
avgWinRate = sum(winRates) / numRuns
print "Average win rate of agent is: {}".format(avgWinRate)
if __name__=="__main__":
main()
|
TypeScript | UTF-8 | 1,070 | 2.765625 | 3 | [] | no_license | import { Reducer } from "redux";
import * as userTypes from "../types/userTypes";
import { userActions } from "../actions/user.action";
import { InferActionsTypes } from "./index";
const initialState = {
user: {
firstName: "Gleb",
secondName: "Kasyak",
email: "sonyck94@gmail.com",
password: "12345",
},
isAuth: false
};
type StateType = typeof initialState;
type ActionTypes = InferActionsTypes<typeof userActions>;
const reducer :Reducer<StateType, ActionTypes> = (state = initialState, action): StateType => {
switch (action.type) {
case userTypes.SIGN_IN_USER:
case userTypes.SIGN_UP_USER:
return {
...state,
user: action.payload,
isAuth: true
};
case userTypes.LOGOUT_USER:
return initialState;
case userTypes.AUTHORIZED_USER_SUCCESS:
return {
...state,
isAuth: true
};
default:
return state;
}
};
export default reducer;
|
Java | UTF-8 | 1,476 | 2.15625 | 2 | [] | no_license | package com.spms.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.spms.dao.SuppliersDAO;
import com.spms.entity.TSuppliersinfo;
import com.spms.service.SuppliersService;
import com.spms.util.PageBean;
@Transactional
@Service
public class SuppliersServiceImpl implements SuppliersService {
@Resource
private SuppliersDAO suppliersDAO;
@Override
public TSuppliersinfo save(TSuppliersinfo supplier) {
return this.suppliersDAO.save(supplier);
}
@Override
public TSuppliersinfo findById(Integer rowId) {
return this.suppliersDAO.findById(rowId);
}
@Override
public int getCount(TSuppliersinfo supplier) {
return this.suppliersDAO.getCount(supplier);
}
@Override
public void delete(TSuppliersinfo supplier) {
this.suppliersDAO.delete(supplier);
}
@Override
public List<TSuppliersinfo> findAll(TSuppliersinfo supplier) {
return this.suppliersDAO.findAll(supplier);
}
@Override
public PageBean findPage(TSuppliersinfo supplier, int currentPage,
int pageSize) {
return this.suppliersDAO.findPage(supplier, currentPage, pageSize);
}
@Override
public PageBean findPageWithCriteria(TSuppliersinfo supplier,
int currentPage, int pageSize) {
return this.suppliersDAO.findPageWithCriteria(supplier, currentPage, pageSize);
}
}
|
Java | UTF-8 | 4,051 | 3.09375 | 3 | [] | no_license | package cz.mxmx.memoryanalyzer.memorywaste;
import com.google.common.collect.Lists;
import cz.mxmx.memoryanalyzer.model.ClassDump;
import cz.mxmx.memoryanalyzer.model.InstanceDump;
import cz.mxmx.memoryanalyzer.model.InstanceFieldDump;
import cz.mxmx.memoryanalyzer.model.MemoryDump;
import cz.mxmx.memoryanalyzer.model.memorywaste.DuplicateInstanceWaste;
import cz.mxmx.memoryanalyzer.model.memorywaste.Waste;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Analyzer to find duplicate instances of objects.
*/
public class DuplicateInstanceWasteAnalyzer implements WasteAnalyzer {
@Override
public List<Waste> findMemoryWaste(MemoryDump memoryDump) {
List<Waste> wasteList = new ArrayList<>();
Set<InstanceDump> processedInstances = Collections.synchronizedSet(new HashSet<>());
Map<Long, InstanceDump> userInstances = memoryDump.getUserInstances();
userInstances.keySet().forEach(id -> {
InstanceDump instance = userInstances.get(id);
processedInstances.add(instance);
memoryDump.getUserInstances().keySet().forEach(id2 -> {
InstanceDump instance2 = memoryDump.getUserInstances().get(id2);
if (id.equals(id2) || processedInstances.contains(instance2)) {
return;
}
if (this.instancesAreSame(instance, instance2)) {
this.mergeWasteList(wasteList, instance, instance2);
}
});
});
System.out.println();
return wasteList;
}
/**
* Checks if the given instances are the same
* @param instance Instance 1
* @param instance2 Instance 2
* @return True if the instances are the same, otherwise false.
*/
private boolean instancesAreSame(InstanceDump instance, InstanceDump instance2) {
if(!this.instancesOfSameClass(instance, instance2)
|| instance.getInstanceFieldValues().size() != instance2.getInstanceFieldValues().size()) {
return false;
}
ClassDump classDump = instance.getClassDump();
for (InstanceFieldDump field : classDump.getInstanceFields()) {
Object value = instance.getInstanceFieldValues().get(field);
Object value2 = instance2.getInstanceFieldValues().get(field);
if (!value.equals(value2)) {
return false;
}
}
return classDump.getInstanceFields().size() > 0;
}
/**
* Checks if the instances are of the same class.
* @param instance Instance 1
* @param instance2 Instance 2
* @return True if t he instances are of the same class, otherwise false
*/
private boolean instancesOfSameClass(InstanceDump instance, InstanceDump instance2) {
ClassDump parent = instance.getClassDump();
do {
if (parent.equals(instance2.getClassDump())) {
return true;
}
parent = parent.getSuperClassDump();
} while (parent != null && parent.getName() != null && !parent.getName().equals(Object.class.getName()));
parent = instance2.getClassDump();
do {
if (parent.equals(instance.getClassDump())) {
return true;
}
parent = parent.getSuperClassDump();
} while (parent != null && parent.getName() != null && !parent.getName().equals(Object.class.getName()));
return false;
}
/**
* Merges the results into the given list, if similar exist, otherwise creates a new entry.
* @param wasteList List with current results
* @param instance New instance 1
* @param instance2 New instance 2
*/
private void mergeWasteList(List<Waste> wasteList, InstanceDump instance, InstanceDump instance2) {
Optional<Waste> optWaste = wasteList
.stream()
.filter(waste -> this.instancesAreSame(waste.getAffectedInstances().get(0), instance)).findFirst();
if (optWaste.isPresent()) {
if (!optWaste.get().getAffectedInstances().contains(instance)) {
optWaste.get().addAffectedInstance(instance);
}
if (!optWaste.get().getAffectedInstances().contains(instance2)) {
optWaste.get().addAffectedInstance(instance2);
}
} else {
wasteList.add(new DuplicateInstanceWaste(this, Lists.newArrayList(instance, instance2)));
}
}
}
|
Markdown | UTF-8 | 1,535 | 3.296875 | 3 | [
"MIT"
] | permissive | ## Comparison to scala-ts
[scala-ts](https://github.com/miloszpp/scala-ts) is another tool to generate typescript interfaces from your scala domain code.
When we evaluated it for use, we found it unsuitable for use in our projects because of the following limitations:
##### scala-ts is limited to the types the authors have provided and case classes.
For example, the current version (0.4.0) cannot handle `BigDecimal`.
If your domain contains a `case class Foo(num: BigDecimal)` you are out of luck with scala-ts.
For built-in java and scala you could theoretically expand this, but the tool will never work with library or your own types which aren't case classes.
##### scala-ts only has a single way to generate case classes
Sometimes, you want to modify your JSON (de)serialization slightly.
With scala-ts, you are out of luck, but with scala-tsi this is not a problem.
Say you want to remove the `password` property of your `User` class in serialization:
```
case class User(name: String, password: String)
// Example play json writer
implicit val userSerializer = Json.writes[User].transform(jsobj => jsobj - "password")
```
This is not possible with scala-ts, but not a problem with scala-tsi:
```
import nl.codestar.scala.ts.interface.dsl._
implicit val userTsType = TSType.fromCaseClass[User] - "password"
```
##### However, the flexibility of scala-tsi comes at increased complexity
scala-ts is *much* simpler to use.
If your project can work within the limitations of scala-ts, we recommend you use scala-ts.
|
PHP | UTF-8 | 2,727 | 3.046875 | 3 | [] | no_license | <?php
namespace Dev\Action;
use Dev\Model;
use Exception;
class LookAction {
private $model;
public function __construct() {
$this->model = new Model\ModelLook();
}
public function returnData($num) {
if ($num != false) {
$data = $this->model->findResult($num);
$higIndex = count($data)-1;
$data = $this->binary_search($data, $num, 0, $higIndex, 0);
// $data = $this->model->look($num);
if(empty($data)) {
throw new Exception("Can't find reference (but file exist)");
}
return $data;
}
throw new Exception("Non valid argument");
}
//fonction récursive qui prend en paramètre le tableau sur le quel rechercher, le nombre rechercher, l'index de la première ligne, l'index de la dernière ligne
function binary_search($data, $num, $lowIndex, $higIndex, $iteration) {
$tmpLowIndex = $lowIndex;
$tmpHigIndex = $higIndex;
$lenNum = strlen($num);
$midIndex = intdiv(($lowIndex + $higIndex), 2);
$midVal = preg_replace('/0?(\.|,)/','', $data[$midIndex]);
$midVal = substr($midVal, 0, $lenNum);
if ($midVal == $num) {
$lowVal = preg_replace('/0?(\.|,)/','', $data[$lowIndex]);
$lowVal = substr($lowVal, 0, $lenNum);
$higVal = preg_replace('/0?(\.|,)/','', $data[$higIndex]);
$higVal = substr($higVal, 0, $lenNum);
//permet de tonquer les valeurs non intéressantes du sous-tableau obtenus
while ($lowVal != $num) {
$lowIndex++;
$lowVal = preg_replace('/0?(\.|,)/','', $data[$lowIndex]);
$lowVal = substr($lowVal, 0, $lenNum);
}
//permet de tronquer les valeurs non intéressantes du sous-tableau obtenus
while ($higVal != $num) {
$higIndex--;
$higVal = preg_replace('/0?(\.|,)/','', $data[$higIndex]);
$higVal = substr($higVal, 0, $lenNum);
}
$higIndex = $higIndex-$lowIndex;
$data = array_slice($data, $lowIndex, $higIndex+1);
return $data;
} else {
if ($num > $midVal) {
$lowIndex = $midIndex;
} else {
$higIndex = $midIndex;
}
if ($tmpHigIndex == $higIndex && $tmpLowIndex == $lowIndex) {
$iteration++;
if ($iteration > 3) {
throw new Exception('too mutch iterations');
}
}
return $this->binary_search($data, $num, $lowIndex, $higIndex, $iteration);
}
}
} |
Java | UTF-8 | 7,617 | 2.875 | 3 | [] | no_license | package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import databases.*;
import models.*;
import view.*;
public class Controller implements ActionListener{
private static View frame;
private static Rooms rooms=Rooms.getRooms();
private static Player player=new Player();
/**
* tell the stats object to call its observer's (StatsPanel) update() method
* called when the stats tab is clicked (TabPanel)
*/
public static final ActionListener statUpdate=new ActionListener(){public void actionPerformed(ActionEvent arg0) {Stats.updateObservers();}};
/**
* tell the inventory object to call its observer's (InvPanel) update() method
* called when the inventory tab is clicked (TabPanel)
*/
public static final ActionListener invUpdate=new ActionListener(){public void actionPerformed(ActionEvent arg0) {Inventory.updateObservers();}};
/**
* create a new profile object and save it.
*/
public static final ActionListener createProfile=new ActionListener(){public void actionPerformed(ActionEvent arg0) {}};
/**
* try to get a profile from the string in the username textField
* check if the profile's password matches the String in the password text field
* Load the save datas for that profile
*/
public static final ActionListener login=new ActionListener(){public void actionPerformed(ActionEvent arg0) {}};
/**
*
*/
public static final ActionListener logoutAction=new ActionListener(){public void actionPerformed(ActionEvent arg0) {}};
/**
* create a new Player object with the default values
* launch the game gui
*
*/
public static final ActionListener startNew=new ActionListener(){public void actionPerformed(ActionEvent arg0) {}};
/**
*
*/
public static final ActionListener loadSave=new ActionListener(){public void actionPerformed(ActionEvent arg0) {}};
/**
* get the next room ID from the button that was pressed
* -when the nav0 button in the ConsolePanel is pressed, it calls changeRoom[0]
*
*/
public static final ActionListener changeRoom[]={
/*
new ActionListener(){public void actionPerformed(ActionEvent arg0) {nav(0);}},
new ActionListener(){public void actionPerformed(ActionEvent arg0) {nav(1);}},
new ActionListener(){public void actionPerformed(ActionEvent arg0) {nav(2);}},
new ActionListener(){public void actionPerformed(ActionEvent arg0) {nav(3);}},
new ActionListener(){public void actionPerformed(ActionEvent arg0) {nav(4);}}
*/
};
public static ActionListener getCRAL(int i){
return changeRoom[i];
}
private void nav(int id){
byte room = player.getCurrentRoom();
byte[] exits = rooms.getExits(room);
byte newRoom=exits[id];
changeRoom(room, newRoom);
}
/**
* if there is a monster in the room, call escapeBattle().
* -if it returns true, then proceed with changing room and save the monster's remaining health in playerstats
* -false, then
* check if the door is locked
* -
* -
* set new room id to player's currentRoom
* reset the console's item display
* check for monsters
*
* get the room's description and tell the consolePanel to display it
* get the room's list of exits and update the nav buttons
* -only show two of the five buttons if the room only has two exits
* -change the text on the button to show the name of the room
* make sure the scan button is visible
* @param inRoom
* @param toRoom
*/
private void changeRoom(byte inRoom, byte toRoom){
player.setRoom(toRoom);
//if(Rooms.getPuzzle(toRoom)==null)
frame.getConsole().setRoomText(rooms.getDescription(toRoom), rooms.getDescription(toRoom));
frame.getConsole().showRoomText();
//else ConsolePanel.setRoomText(Rooms.getDescription(toRoom), Rooms.getPuzzle(toRoom).getText());
String[] exits= new String[]{"","","","",""};
byte[] exit=rooms.getExits(toRoom);
int n=0;
while(exit.length>n){
exits[n]=rooms.getName(exit[n]);
n++;
}
frame.getConsole().updateNav(exits);
}
/**
* Hide option for scan room
* show option for
* get combat Object for the Monster
* Evaluate if monster attacks first
*
*/
private static final void activateBattle(byte monsterID){
}
/**
* mark the monster as defeated
* add item to itemdrop
* unhide scan button
*/
private static final void winBattle(byte monsterID){
}
/**
* evaluate if you escape from the monster or not
* @return
*/
private static final boolean escapeBattle(byte monsterID){
if(Math.random()>=Monsters.getEscapeChance(monsterID))return true;
return false;
};
/**Called when Examine Room button is clicked
*
* change the text to display the room's description
*
*/
public static final ActionListener getRoomDesc=new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
};
/**Called when Scan Room Button is clicked
* activate a puzzle if there is one in the current room
* for each artifact in the room's item drop, make a pickupItem button
* -call ConsolePanel.newButton(), which makes a button and adds a pickupItem[] actionListener to it
* then tell the console to display the buttons
*/
public static final ActionListener getItemDrop=new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
};
public static final ActionListener atkAction=new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
};
/**
* remove the artifact from the item drop and add it to the inventory
*/
public static final ActionListener pickupItem[]={new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}};
/**
*
*/
public static final ActionListener useItem=new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
};
/**
* get the selected item from the view List
* get the items description variable, then send it to the consonle text display
*/
public static final ActionListener examineItem=new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
};
/**
* get selected usable from the list (returns index of the inventory slot)
* get the value of the item index in that slot of the inventory
* -add an item to the current room's itemdrop using that item index
* set the value of that slot to zero in the inventory
*
*/
public static final ActionListener dropItem=new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
};
//Puzzle Actions
public Controller(View frame){
this.frame=frame;
player.setRoom((byte) 0);
changeRoom((byte)0,(byte)0);
}
private void createGUI(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void start(){
frame = new View();
createGUI();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==frame.getConsole().getNavButton(0))nav(0);
if(e.getSource()==frame.getConsole().getNavButton(1))nav(1);
if(e.getSource()==frame.getConsole().getNavButton(2))nav(2);
if(e.getSource()==frame.getConsole().getNavButton(3))nav(3);
if(e.getSource()==frame.getConsole().getNavButton(4))nav(4);
}
}
|
Java | UTF-8 | 3,728 | 1.851563 | 2 | [] | no_license | package com.neusoft.edu.cn.dingzhenling.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.neusoft.edu.cn.dingzhenling.R;
import com.neusoft.edu.cn.dingzhenling.adapter.CollectAdapter;
import com.neusoft.edu.cn.dingzhenling.adapter.IssueAdapter;
import com.neusoft.edu.cn.dingzhenling.adapter.LikeAdapter;
import com.neusoft.edu.cn.dingzhenling.bean.Issue;
import com.neusoft.edu.cn.dingzhenling.bean.Like;
import com.neusoft.edu.cn.dingzhenling.bean.MyUser;
import java.util.ArrayList;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
/**
* Created by Administrator on 2017/3/12 0012.
*/
public class CollectionActivity extends AppCompatActivity {
private static final String TAG = "CollectionActivity";
public Context context;
//显示对应问题列表
private RecyclerView mRecyclerView;
public CollectAdapter collectAdapter;
private List<Issue> mDatas;
@Override
protected void onCreate(Bundle savedInstanceState) {
context = this.getApplication();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collect);
mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getApplication()));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
initData();
}
private void initData() {
MyUser user= BmobUser.getCurrentUser(MyUser.class);
BmobQuery<Issue> query=new BmobQuery<>();
query.include("user");
query.addWhereEqualTo("collect",new BmobPointer(user));
query.findObjects(new FindListener<Issue>() {
@Override
public void done(List<Issue> list, BmobException e) {
if(e==null){
mDatas = list;
collectAdapter=new CollectAdapter(CollectionActivity.this,mDatas);
CollectAdapter.setOnItemClickListener(new CollectAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
Intent intent=new Intent(CollectionActivity.this,IssuedetaiActivity.class);
intent.putExtra("issue_id",mDatas.get(position).getObjectId());
startActivity(intent);
}
@Override
public void onItemLongClick(View view, int position) {
}
});
// collectAdapter.OnItemClickListener(new CollectAdapter.OnRecyclerViewItemClickListener(){
// @Override
// public void onItemClick(View view, String data) {
// Intent intent=new Intent(CollectionActivity.this,IssuedetaiActivity.class);
// intent.putExtra("issue_id",data);
// startActivity(intent);
// }
// });
mRecyclerView.setAdapter(collectAdapter);
initData();
}
}
});
}
public void clickBack(View v) {
finish();
}
}
|
Markdown | UTF-8 | 6,373 | 3.5625 | 4 | [] | no_license | ##行为模式
行为型设计模式侧重于类或对象的行为。
###1.模板方法模式
- 定义:一个操作中的算法的框架,而将一些步骤的执行延迟到子类中,使得子类可以在不改变算法的结构的前提下即可重新定义该算法的某些特定步骤。
通常
- 例子:饮料的制作
- 步骤一:准备热水
- 步骤二:加入主成分
- 步骤三:加入辅助成分
- 伪代码:
```
抽象类:
HotDrink:热饮
方法:
1.制作过程(包含:加水、加主成分、加辅助成分)
2.加主成分
3.加辅助成分
子类
HotDrinkTea : 热茶
HotDrinkLatte : 热拿铁
HotDrinkAmericano: 热美式
```
###2。策略模式
- 定义:定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。
- 例子:模拟一个两个整数可以随意替换加减乘除算法的场景。
- 伪代码:
```
抽象策略类:
TwoIntOperation
方法:
1.操作参数1和参数2
具体策略类
TwoIntOperationAdd : 加法
TwoIntOperationSub : 减法
环境类
Context:
方法:
1.传入具体策略类
2.操作参数1和参数2
```
###3.责任链模式
- 定义:为请求创建了一个接收者对象的链,每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。总结是A作为B的输入,B作为C的输入。
- 例子:模拟一个 ATM 取现金的场景:ATM机器有50,20,10面值的纸币,根据用户需要提取的现金金额来输出纸币张数最少的等价金额的纸币。
比如用户需要取130元,则ATM需要输出2张50面额的纸币,1张20面额的纸币,1张10面额的纸币;而不是6张20面额的纸币加1张10面额的纸币。
- 伪代码:
```
抽象类:
DispenseChainNode
方法:
1.设置下一个处理面值
2.分发
子类
DispenseChainNodeFor50Yuan : 50元
DispenseChainNodeFor20Yuan : 20元
DispenseChainNodeFor10Yuan : 10元
具体处理类:
ATMDispenseChain :ATM
使用:
ATMDispenseChain *atm = [[ATMDispenseChain alloc] init];
[atm dispense:230];
[atm dispense:70];
[atm dispense:40];
[atm dispense:10];
[atm dispense:8];
```
###4.状态模式
- 定义:允许一个对象在其内部状态改变时,改变它的行为。
- 例子:模拟一个程序员一天的生活,他有四个状态:
- 醒着
- 睡觉中
- 写代码中
- 吃饭中
- 伪代码:
```
状态类:
State
方法:
传入程序员
行动协议:
ActionProtocol
方法:
醒着
睡觉中
写代码
吃饭中
具体状态子类
StateAwake:醒着
StateSleeping:睡觉中
StateEating:吃
StateCoding:写代码
程序员:
Coder
属性:
醒着状态
睡觉中状态
吃状态
写代码状态
具体调用:
Coder *coder = [[Coder alloc] init];
//change to awake.. failed
[coder wakeUp];//Already awake, can not change state to awake again
//change to coding
[coder startCoding];//Change state from awake to coding
//change to sleep
[coder fallAsleep];//Too tired, change state from coding to sleeping
//change to eat...failed
[coder startEating];//Already sleeping, can change state to eating
```
###5.命令模式
- 定义:命令(或请求)被封装成对象。客户端将命令(或请求)对象先传递给调用对象。调用对象再把该命令(或请求)对象传给合适的,可处理该命令(或请求)的对象来做处理。
- 例子:模拟一个使用遥控器开灯和关灯的例子。
- 伪代码:
```
灯类:
Light
方法:
开灯
关灯
抽象命令类:
Command
方法:
执行
具体命令类:(需要传入灯)
CommandLightOn:开灯
CommandLightOff:关灯
遥控器类:
RemoteControl
方法:
命令
执行
具体调用:
//================== client ==================
//init Light and Command instance
//inject light instance into command instance
Light *light = [[Light alloc] init];
CommandLightOn *co = [[CommandLightOn alloc] initWithLight:light];
//set command on instance into remote control instance
RemoteControl *rm = [[RemoteControl alloc] init];
[rm setCommand:co];
//excute command(light on command)
[rm pressButton];
//inject light instance into command off instance
CommandLightOff *cf = [[CommandLightOff alloc] initWithLight:light];
//change to off command
[rm setCommand:cf];
//excute command(light close command)
[rm pressButton];
```
###6.观察者模式
- 定义:定义对象间的一种一对多的依赖关系,使得每当一个对象状态发生改变时,其相关依赖对象都可以到通知并做相应针对性的处理。
- 例子:客户(投资者)订阅理财顾问的建议购买不同价格的股票。当价格信息变化时,所有客户会收到通知(可以使短信,邮件等等),随后客户查看最新数据并进行操作。
- 伪代码:
```
观察者
Observer
具体观察者类
Investor
具体目标类
FinancialAdviser
目标类
Subject
具体调用:
FinancialAdviser *fa = [[FinancialAdviser alloc] init];
Investor *iv1 = [[Investor alloc] initWithSubject:fa];
NSLog(@"====== first advice ========");
[fa setBuyingPrice:1.3];
Investor *iv2 = [[Investor alloc] initWithSubject:fa];
Investor *iv3 = [[Investor alloc] initWithSubject:fa];
NSLog(@"====== second advice ========");
[fa setBuyingPrice:2.6];
```
###7.中介者模式
- 定义:用一个中介对象来封装一系列的对象交互,中介者使各对象之间不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
- 例子:模拟一个多人对话的场景:当一个人发出消息后,另外的那些人可以收到该消息。
- 伪代码:
```
用户类
User
方法:
初始化名字
发送消息
接收消息
中介者类:
ChatMediator
方法:
增加用户
发送消息
具体调用:
ChatMediator *cm = [[ChatMediator alloc] init];
User *user1 = [[User alloc] initWithName:@"Jack" mediator:cm];
User *user2 = [[User alloc] initWithName:@"Bruce" mediator:cm];
User *user3 = [[User alloc] initWithName:@"Lucy" mediator:cm];
[cm addUser:user1];
[cm addUser:user2];
[cm addUser:user3];
[user1 sendMessage:@"happy"];
[user2 sendMessage:@"new"];
[user3 sendMessage:@"year"];
``` |
Python | UTF-8 | 232 | 3.125 | 3 | [] | no_license | str1 = "Test string global"
def f1():
str2 = "Test string local"
print(str1)
print(str2)
# print (locals())
# f1()
# print (globals())
# print(str1)
def foo(x):
print(locals())
foo(1)
print(foo.__class__)
|
JavaScript | UTF-8 | 612 | 3.9375 | 4 | [] | no_license | // If life was easy, we could just do things the easy way:
// var getElementsByClassName = function (className) {
// return document.getElementsByClassName(className);
// };
// But instead we're going to implement it from scratch:
var getElementsByClassName = function(className, currentNode = document.body) {
var result = [];
var classList = currentNode.classList;
if (classList && classList.contains(className)) {
result.push(currentNode);
}
currentNode.childNodes.forEach(function(child) {
result = result.concat(getElementsByClassName(className, child));
});
return result;
};
|
Java | UTF-8 | 376 | 1.914063 | 2 | [] | no_license | package com.kanasansoft.WSBroadcaster;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;
public class MyWebSocketServlet extends WebSocketServlet {
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new MyWebSocket();
}
}
|
Java | UTF-8 | 694 | 2.375 | 2 | [] | no_license | package com.library.book.model;
import java.sql.Date;
public class AddBookRequest implements IRequest{
private String name;
private String author;
private Date entryDate;
private String takenBy;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setAuthor(String author)
{
this.author = author;
}
public String getAuthor()
{
return author;
}
public void setEntryDate(Date entryDate)
{
this.entryDate = entryDate;
}
public Date getEntryDate()
{
return entryDate;
}
public void setTakenBy(String takenBy)
{
this.takenBy = takenBy;
}
public String getTakenBy()
{
return takenBy;
}
}
|
SQL | UTF-8 | 1,670 | 3.109375 | 3 | [] | no_license | /*
SQLyog Ultimate v11.11 (64 bit)
MySQL - 5.5.5-10.1.30-MariaDB : Database - user
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`user` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `user`;
/*Table structure for table `data_user` */
DROP TABLE IF EXISTS `data_user`;
CREATE TABLE `data_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`fullname` varchar(170) DEFAULT NULL,
`pass` varchar(50) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`telp` varchar(13) DEFAULT NULL,
`baned` enum('Y','N') NOT NULL DEFAULT 'Y',
`logintime` datetime DEFAULT NULL,
`akses` int(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `usernameunique` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*Data for the table `data_user` */
insert into `data_user`(`id`,`username`,`fullname`,`pass`,`email`,`telp`,`baned`,`logintime`,`akses`) values (1,'jaka','Jaka Oktorio','*4ACFE3202A5FF5CF467898FC58AAB1D615029441','jakaoktorio22@gmail.com','081250462104','Y','2018-03-12 11:34:45',1);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
|
Python | UTF-8 | 672 | 3.015625 | 3 | [
"MIT"
] | permissive | c = ('\033[m',
'\033[0;30;41m',
'\033[0;30;42m',
'\033[0;30;43m',
'\033[0;30;44m',
'\033[0;30;45m',
'\033[7;30m');
def ajuda(com):
linha(f'Acessando o manual do comando \'{op}\'', 4)
print(c[6], end='')
help(com)
print(c[0], end='')
def linha(txt, cor=0):
tam = len(txt) + 4
print(c[cor], end='')
print('~' * tam)
print(f'{txt}')
print('~' * tam)
print(c[0], end='')
while True:
linha('SISTEMA DE AJUDA PyHELP', 2)
op = str(input('Função ou Biblioteca > ')).strip()
if op.upper() == 'FIM':
break
else:
ajuda(op)
linha('Acessando o manual do comando')
help(op)
linha('Volte Sempre', 1) |
Go | UTF-8 | 2,093 | 3.1875 | 3 | [
"MIT"
] | permissive | package os_test
import (
// "fmt"
"os"
"testing"
// "path/filepath"
// "sort"
oshelper "jac0p/helper/os"
log "github.com/sirupsen/logrus"
)
func TestCreateTG(t *testing.T) {
// path, _ := filepath.Abs("./data")
// tg := path + "/aggregated.log"
tg := "/tmp/testfile.log"
os.Remove(tg) // remove existing file before testing
oshelper.CreateTG(tg) // create new file
if _, err := os.Stat(tg); os.IsNotExist(err) {
t.Errorf("CreateTG() didn't create: %s", tg)
}
}
func TestCheckIfFile(t *testing.T) {
var tests = []struct {
input string
want bool
}{
{"./cases/afile", true},
{"./cases/bfile", true},
{"./cases/adir", false},
}
for _, test := range tests {
if oshelper.CheckIfFile(test.input) != test.want {
t.Errorf("CheckIfFile(%s) != %s", test.input, test.want)
}
}
}
func TestWalkDir(t *testing.T) {
input := "./cases/walkme/"
want := []string{"./cases/walkme/afile", "./cases/walkme/bfile", "./cases/walkme/adir/cfile", "./cases/walkme/adir/bdir/dfile"}
fl := oshelper.WalkDir(input)
// sort.Strings(fl)
// this test doesn't really tell the whole story
if len(fl) != len(want) {
t.Errorf("WalkDir(%q) = %v", input, fl)
}
}
func TestDeleteDir(t *testing.T) {
target := "/tmp/deleteme/"
log.Debug("creating directory: %s", target)
err := os.MkdirAll(target, 0666)
if err != nil {
t.Errorf("cannot create %s", target)
}
oshelper.DeleteDir("/tmp/deleteme/")
if oshelper.CheckIfDir(target) {
t.Errorf("directory wasn't deleted..")
}
}
func TestListDir(t *testing.T) {
source := "/tmp/listme/"
children := []string{"/dirone/", "/dirtwo/", "/dirthree/"}
for _, child := range children {
os.MkdirAll(source + child, 0666)
}
contents := oshelper.ListDir(source)
// this test doesn't really tell the whole story
if len(contents) != len(children) {
t.Errorf("ListDir(%q) = %v", children, contents)
}
}
|
Markdown | UTF-8 | 5,096 | 2.953125 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: Jekyll个人博客添加返回顶部按钮
subtitle: 让博客使用更方便
tags: [Jekyll]
categories: Jekyll
---
不知道大家阅读一篇博客,读完了,想返回到博客的顶部,是滑动鼠标滚能还是拖动滚动条呢?为了提供方便性,尤其是对于阅读较长的博文的时候,这个返回顶部的按钮也就显得很方便了。
对于我这样爱折腾,以及对于任何事情力求完整的人来说,这个返回顶部的按钮也就必须要添加到我自己的博客里面的。那么,接下来就来看看我是如何实现这个功能的吧!
<!-- TOC -->
- [1. 寻找添加的位置](#1-%e5%af%bb%e6%89%be%e6%b7%bb%e5%8a%a0%e7%9a%84%e4%bd%8d%e7%bd%ae)
- [2. 添加代码](#2-%e6%b7%bb%e5%8a%a0%e4%bb%a3%e7%a0%81)
- [3. 创建back_top_button.html文件](#3-%e5%88%9b%e5%bb%babacktopbuttonhtml%e6%96%87%e4%bb%b6)
- [4. 添加样式](#4-%e6%b7%bb%e5%8a%a0%e6%a0%b7%e5%bc%8f)
- [5. 展示效果](#5-%e5%b1%95%e7%a4%ba%e6%95%88%e6%9e%9c)
<!-- /TOC -->
# 1. 寻找添加的位置
首先大家想一想这个返回顶部按钮该添加到什么地方呢?不仅仅要在主要展示上添加,并且还要在每篇博文上的页面也要进行添加,那么肯定就要找到他们共同的布局文件了。在Jekyll上写过博文的都知道,在写博文的时候头部需要给这篇博文添加一些参数,比如,`layout`就是指定当前布局的格式是post还是page、`title`就是指定是标题等等参数。就像下面的格式一样。
```html
{% raw %}
---
layout: post
title: Jekyll个人博客添加返回顶部按钮
subtitle: 让博客使用更方便
tags: [Jekyll]
categories: Jekyll
---
{% endraw %}
```
因此,可以知道当前博客布局要么就是**post**格式的,要么就是**page**格式的,所以打开`_layout/`目录下的`post.html`和`page.html`文件,从这两个文件的首部可以看到,它们都是基于`base.html`来完成的,如下图所示。那么刚好在`_layout/`目录下正好有个`base.html`文件,打开查看,发现这个正式我们要添加返回顶部按钮的文件。

# 2. 添加代码
在`base.html`文件,添加`{% raw %}{% include back_top_button.html %}{% endraw %}`到该文件的末尾,最后添加后的`base.html`文件完整代码如下:
```html
{% raw %}
---
common-css:
- "/css/bootstrap.min.css"
- "/css/bootstrap-social.css"
- "/css/main.css"
common-ext-css:
- "//maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css"
common-googlefonts:
- "Lora:400,700,400italic,700italic"
- "Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800"
common-js:
- "/js/jquery-1.11.2.min.js"
- "/js/bootstrap.min.js"
- "/js/main.js"
---
<!DOCTYPE html>
<html lang="en">
<!-- Beautiful Jekyll | MIT license | Copyright Dean Attali 2016 -->
{% include head.html %}
<body>
{% include gtm_body.html %}
{% include nav.html %}
{{ content }}
{% include footer.html %}
{% include footer-scripts.html %}
{% include back_top_button.html %}
</body>
</html>
{% endraw %}
```
# 3. 创建back_top_button.html文件
接下来要在`_include/`目录下创建`back_top_button.html`这个文件了,然后添加如下代码到这个文件之中:
```html
{% raw %}
<div id="back-top">
<a href="#top" title="回到顶部">
<i class="icon-2x icon-arrow-up"></i>
</a>
</div>
<script type="text/javascript">
$("#back-top").hide();
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#back-top').fadeIn();
} else {
$('#back-top').fadeOut();
}
});
$('#back-top a').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
});
</script>
{% endraw %}
```
# 4. 添加样式
接下来就是在`css/main.css`文件的末尾添加一些样式,在该文件的末尾添加即可,需要添加的代码如下:
```css
/* Back Top Button */
#back-top {
position: fixed;
bottom: 30px;
right: 0%;
margin-right: 40px;
background-color: #aaa;
-webkit-border-radius: 7px;
-moz-border-radius: 7px;
border-radius: 7px;
-webkit-transition: 0.7s;
-moz-transition: 0.7s;
transition: 0.7s;
/*behavior: url(/css/PIE.htc);*/
}
#back-top:hover {
background-color: #777;
}
#back-top a {
background: #ddd url(/img/bg_up_arrow.png) no-repeat center center;
color: #fff;
text-decoration: none;
padding: 12px 14px;
display: inline-block;
}
```
> 注意别忘记把向上的箭头的图片放在`img/`目录下了,名字可以自己去修改。
# 5. 展示效果
到此也就完成了返回顶部按钮的功能,下面来看看具体实现的效果吧。
* 在主页的效果:

* 在博文的效果:

|
TypeScript | UTF-8 | 1,664 | 2.5625 | 3 | [] | no_license | import { Component, OnInit } from '@angular/core';
import {Observable, Subject} from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'app';
ngOnInit(){
//this is an observable
// let observerStream$ = new Observable(observer => {
// console.log('observable execution');
// observer.next(1);
// observer.next(2);
// setTimeout(()=>{
// observer.next("balalablala");
// }, 3000);
// // observer.error(new Error('no more movies'));
// observer.next(3);
// observer.complete();
// });
//
// let observer1 = observerStream$.subscribe(
// value => console.log(value),
// error => console.error(error),
// () => console.log(`done`));
//
// setTimeout(() => {
// observer1.unsubscribe();
// }, 2000);
// let subject = new Subject();
// subject.subscribe((v) => {
// console.log('Observer A:'+ v);
// })
//
// subject.next(1)
//
// subject.subscribe((v) => {
// console.log('Observer B' + v);
// })
// const numbers = [1,2,3,4,5]
// const numbers$ = Observable.from(numbers);
// let observer1 = numbers$.subscribe(
// value => console.log(value),
// error => console.error(error),
// () => console.log(`done`));
const btn = document.querySelector('#btn');
const btn$ = Observable.fromEvent(btn, 'click');
let sub = btn$.subscribe(
value => console.log(value.target.innerHTML),
error => console.error(error),
() => console.log(`done`));
}
}
|
Java | UTF-8 | 292 | 1.734375 | 2 | [] | no_license | package com.wepindia.pos.views.Billing.Listeners;
import com.wep.common.app.models.PaymentDetails;
/**
* Created by Administrator on 22-01-2018.
*/
public interface OnProceedToPayCompleteListener {
void onProceedToPayComplete(PaymentDetails obj);
void onDismiss();
}
|
Python | UTF-8 | 1,891 | 4.625 | 5 | [] | no_license | # print('')
# print('------------------Functions---------------------')
# print('')
# def greeting(name, age):
# print(f'Hello {name}, you are {age} years old')
# greeting('John', 30)
# print('')
# print('------------------Functions Exercise---------------------')
# print('')
# 1. Add new print statement - on a new line
# which says 'We hear you like the color xxx! xxx is a string with color
# 2. extend the function with another input parameter 'color', that defaults to 'red'
# 3. Capture the color via an input box as variable:color
# 4. Change the 'You are xx!' text to say 'you will be xx+1 years old next birthday
# adding 1 to the age
# 5. Capitalize first letter of the 'name', and rest are small caps
# 6. Favorite color should be in lowercase
# def greeting(name, age=28, color='red'):
# #Greets user with 'name' from 'input box' and 'age', if available, default age is used
# print('Hello ' + name.title() + ', you will be ' + str(age+1) +' next birthday!')
# print(f'Hello {name.title()}, you will be {age+1} next birthday!')
# print(f'We hear you like the color {color.lower()}!')
# color = input('Enter your color: ')
# name = input('Enter your name: ')
# age = input('Enter your age: ')
# greeting(name, int(age), color)
# print('')
# print('------------------Functions Named Notation---------------------')
# print('')
# just placing notating what each parameter in the function call greeting(name='mark', int(age)=5, color='blue')
print('')
print('------------------Functions Return Statements---------------------')
print('')
def vat(amount):
tax =amount * 0.25
total_amount = amount * 1.25
return [tax, amount, total_amount] #depending on what we put here will be the type that is returned, it could have been a list or a tuple.
price= vat(100)
print(price, type(price))#type(price) not necessary just to see what type it is. |
Java | UTF-8 | 4,246 | 3.46875 | 3 | [] | no_license | package Exam2020;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
//Scanner scan = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int[] firstInput = Arrays.stream(reader.readLine().split(", ")).mapToInt(Integer::parseInt).toArray();
int[] secondInput = Arrays.stream(reader.readLine().split(", ")).mapToInt(Integer::parseInt).toArray();
// this is stack
ArrayDeque<Integer> bombEffect = new ArrayDeque<>();
//this is queueu
ArrayDeque<Integer> bombCasing = new ArrayDeque<>();
Map<String, Integer> bombs = new TreeMap<>();
bombs.put("Datura Bombs", 0);
bombs.put("Cherry Bombs", 0);
bombs.put("Smoke Decoy Bombs", 0);
boolean firstFlag = false;
boolean secondFlag = false;
boolean thirdFlag = false;
boolean pouchIsFilled = false;
for (int element : firstInput) {
bombEffect.offer(element);
}
for (int element : secondInput) {
bombCasing.push(element);
}
//--------------------------------
while (!bombEffect.isEmpty() && !bombCasing.isEmpty() && !pouchIsFilled ) {
int firstElement = bombEffect.peek();
int secondElement = bombCasing.peek();
int sum = firstElement + secondElement;
if (sum == 40) {
bombEffect.poll();
bombCasing.pop();
bombs.put("Datura Bombs", bombs.get("Datura Bombs") + 1);
if (bombs.get("Datura Bombs") == 3) {
firstFlag =true;
}
} else if (sum == 60) {
bombEffect.poll();
bombCasing.pop();
bombs.put("Cherry Bombs", bombs.get("Cherry Bombs") + 1);
if (bombs.get("Cherry Bombs") == 3) {
secondFlag =true;
}
} else if (sum == 120) {
bombEffect.poll();
bombCasing.pop();
bombs.put("Smoke Decoy Bombs", bombs.get("Smoke Decoy Bombs") + 1);
if (bombs.get("Smoke Decoy Bombs") == 3) {
thirdFlag =true;
}
} else {
bombCasing.push(bombCasing.pop() - 5);
}
pouchIsFilled = checkIfPouchIsFilled(bombs);
}
if (pouchIsFilled) {
System.out.println("Bene! You have successfully filled the bomb pouch!");
} else {
System.out.println("You don't have enough materials to fill the bomb pouch.");
}
if (bombEffect.isEmpty()) {
System.out.println("Bomb Effects: empty");
} else {
System.out.print("Bomb Effects: ");
List<Integer> printArray = new ArrayList<>();
printArray.addAll(bombEffect);
for (int i = 0; i < printArray.size() - 1; i++) {
System.out.print(printArray.get(i) +", ");
}
System.out.println(printArray.get(printArray.size()-1));
}
if (bombCasing.isEmpty()) {
System.out.println("Bomb Casings: empty");
} else {
System.out.print("Bomb Casings: ");
List<Integer> printArray = new ArrayList<>();
printArray.addAll(bombCasing);
for (int i = 0; i < printArray.size() - 1; i++) {
System.out.print(printArray.get(i) +", ");
}
System.out.println(printArray.get(printArray.size()-1));
}
for (Map.Entry<String, Integer> e : bombs.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
}
private static boolean checkIfPouchIsFilled(Map<String, Integer> bombs) {
int count = 0;
for (Map.Entry<String, Integer> entry : bombs.entrySet()) {
if (entry.getValue() >= 3) {
count++;
}
if (count == 3) {
return true;
}
}
return false;
}
}
|
Python | UTF-8 | 2,806 | 2.78125 | 3 | [] | no_license | import json
from flask import Flask, render_template, abort, request
from mock_data import mock_data
from flask_cors import CORS
from config import db
app = Flask(__name__)
CORS(app)
# put dict here
me = {
"name": "Kenny",
"last": "Cruz",
"email": "kennyc@gmail.com",
"age": 25,
"hobbies": [],
"address": {
"street": "sesame",
"number": 123
}
}
@app.route("/")
@app.route("/home")
def index():
return render_template("index.html")
@app.route("/about")
def about():
return f"{me['name']} {me['last']} {'Age: '} {me['age']}"
@app.route("/about/email")
def email():
return f"{me['email']}"
@app.route("/about/address")
def address():
address = me["address"]
print(type(address))
return f"{address['number']} {address['street']}"
@app.route("/api/catalog", methods=["GET"])
def get_catalog():
cursor = db.products.find({})
catalog = []
for prod in cursor:
catalog.append(prod)
return json.dumps(catalog)
@app.route("/api/catalog", methods=["POST"])
def save_product():
product = request.get_json()
if not "price" in product or product["price"] <= 0:
abort(400, "Price is required and should be greater than 0")
if not "title" in product or len(product["title"]) < 5:
abort(400, "Title is required and must be at least 5 characters long")
mock_data.append(product)
product["_id"] = len(product["title"])
return json.dumps(mock_data)
@app.route("/api/catalog/<cat>")
def get_category(cat):
found = False
categories = []
for prod in mock_data:
if prod["category"].lower() == cat.lower():
found = True
categories.append(prod)
if found:
return json.dumps(categories)
elif not found:
abort(404)
@app.route("/api/categories")
def get_categories():
categories = []
for product in mock_data:
category = product["category"]
if category not in categories:
categories.append(category)
return json.dumps(categories)
@app.route("/api/product/<id>")
def get_id(id):
found = False
for prod in mock_data:
if prod["_id"] == id:
found = True
return json.dumps(prod)
if not found:
abort(404)
@app.route("/api/product/cheapest")
def get_cheapest():
cheap = mock_data[0]
for prod in mock_data:
if prod["price"] < cheap["price"]:
cheap = prod
return json.dumps(cheap)
@app.route("/api/test/loaddata")
def load_data():
return "Data Already Loaded"
for prod in mock_data:
db.products.insert_one(prod)
return "Data Loaded"
app.run(debug=True)
|
C++ | UTF-8 | 9,291 | 3.328125 | 3 | [] | no_license | //
// Created by Dawson Heide on 11/14/19.
//
#ifndef TODOS_DATABASE_H
#define TODOS_DATABASE_H
#include <iostream>
#include <string>
#include <sqlite3.h>
#include <vector>
using namespace std;
/**
* UserData
* used for turning sql data into User objects
*/
struct UserData {
int id;
string name;
string email;
string password;
};
/**
* TaskData
* used for turning sql query data into Task objects
*/
struct TaskData {
int id;
string title;
string description;
int user_id;
int completed;
string created_at;
int priority;
};
class Database {
private:
//// sqlite database object
sqlite3 *db;
/**
* Creates a user table in the database if not created
*/
void createUserTable() {
char *messageError;
int exit;
string qry = "CREATE TABLE User("
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
"name TEXT NOT NULL, "
"email TEXT NOT NULL, "
"password TEXT NOT NULL); ";
exit = sqlite3_exec(db, qry.c_str(), nullptr, nullptr, &messageError);
if (exit != SQLITE_OK) {
std::cerr << messageError << std::endl;
sqlite3_free(messageError);
}
}
/**
* Creates a task table in the database if not created
*/
void createTaskTable() {
char *messageError;
int exit;
string qry = "CREATE TABLE Task("
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
"title TEXT NOT NULL, "
"description TEXT NOT NULL, "
"user_id INT NOT NULL,"
"created_at TEXT NOT NULL,"
"completed INT NOT NULL DEFAULT 0,"
"priority INT DEFAULT 0);";
exit = sqlite3_exec(db, qry.c_str(), nullptr, 0, &messageError);
if (exit != SQLITE_OK) {
std::cerr << messageError << std::endl;
sqlite3_free(messageError);
}
}
public:
/**
* Constructor for a Database object
* creates and opens the database file if not already created
*/
Database() {
char *messageError;
int exit = sqlite3_open("todos.db", &db);
if (exit) std::cerr << "Error open DB " << sqlite3_errmsg(db) << std::endl;
else std::cout << "Opened Database Successfully!" << std::endl;
this->createUserTable();
this->createTaskTable();
}
/**
* Gets all users from the database
* @param qry - a custom qry for the database
* @return a vector of UserData objects
*/
vector<UserData *> getUserData(string qry = "") {
if (qry == "") qry = "SELECT * FROM User";
cout << qry << endl;
vector<UserData *> users;
char *messageError;
sqlite3_stmt *stmt;
int exit = sqlite3_prepare_v2(db, qry.c_str(), -1, &stmt, NULL);
if (exit != SQLITE_OK) {
cerr << "SELECT failed: " << sqlite3_errmsg(db) << endl;
}
while ((exit = sqlite3_step(stmt)) == SQLITE_ROW) {
UserData *user = new UserData();
user->id = sqlite3_column_int(stmt, 0);
user->name = reinterpret_cast<const char *>(sqlite3_column_text(stmt, 1));
user->email = reinterpret_cast<const char *>(sqlite3_column_text(stmt, 2));
user->password = reinterpret_cast<const char *>(sqlite3_column_text(stmt, 3));
// let's assume number can be NULL:
users.push_back(user);
}
if (exit != SQLITE_DONE) {
cerr << "SELECT failed: " << sqlite3_errmsg(db) << endl;
}
sqlite3_finalize(stmt);
return users;
}
/**
* Gets all the tasks in the database
* @return a vector of TaskData objects
*/
vector<TaskData *> getTaskData() {
string qry = "SELECT * FROM Task";
vector<TaskData *> tasks;
char *messageError;
sqlite3_stmt *stmt;
int exit = sqlite3_prepare_v2(db, qry.c_str(), -1, &stmt, NULL);
if (exit != SQLITE_OK) {
cerr << "SELECT failed: " << sqlite3_errmsg(db) << endl;
}
while ((exit = sqlite3_step(stmt)) == SQLITE_ROW) {
TaskData *task = new TaskData();
task->id = sqlite3_column_int(stmt, 0);
task->title = reinterpret_cast<const char *>(sqlite3_column_text(stmt, 1));
task->description = reinterpret_cast<const char *>(sqlite3_column_text(stmt, 2));
task->user_id = atoi(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 3)));
task->created_at = atoi(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 4)));
task->completed = atoi(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 5)));
task->priority = atoi(reinterpret_cast<const char *>(sqlite3_column_text(stmt, 6)));
// let's assume number can be NULL:
tasks.push_back(task);
}
if (exit != SQLITE_DONE) {
cerr << "SELECT failed: " << sqlite3_errmsg(db) << endl;
}
sqlite3_finalize(stmt);
return tasks;
}
/**
* Takes user information and creates a user in the database
*
* @param name
* @param email
* @param password
* @return
*/
int createUser(string &name, string &email, string &password) {
string qry = "INSERT INTO User (name, email, password)"
" VALUES(\"" + name + "\",\"" + email + "\",\"" + password + "\");";
char *messageError;
int exit = sqlite3_exec(this->db, qry.c_str(), nullptr, nullptr, &messageError);
if (exit != SQLITE_OK) {
std::cerr << messageError << std::endl;
sqlite3_free(messageError);
return 0;
}
int last_id = sqlite3_last_insert_rowid(this->db);
return last_id;
}
/**
* Takes task information and creates a task in the database
*
* @param title
* @param description
* @param user_id
* @param created_at
* @param priority
* @return The new Task id
*/
int createTask(string &title, string &description, int user_id, string created_at, int priority = 0) {
string qry;
if (priority != 0) {
qry = "INSERT INTO Task (title, description, user_id, created_at, priority)"
" VALUES(\"" + title + "\",\""
+ description + "\",\""
+ to_string(user_id) + "\",\""
+ created_at + "\",\""
+ to_string(priority) + "\");";
} else {
qry = "INSERT INTO Task (title, description, created_at, user_id)"
" VALUES(\"" + title + "\",\""
+ description + "\",\""
+ created_at + "\",\""
+ to_string(user_id) + "\");";
}
char *messageError;
int exit = sqlite3_exec(this->db, qry.c_str(), nullptr, nullptr, &messageError);
if (exit != SQLITE_OK) {
std::cerr << messageError << std::endl;
sqlite3_free(messageError);
return 0;
}
int last_id = sqlite3_last_insert_rowid(this->db);
return last_id;
}
/**
* Updates a task in the database using a sql query
*
* @param id of a task
* @param title of a task
* @param description
* @param completed
* @param priority
*/
void updateTask(int id, string &title, string &description, int completed, int priority = 0) {
cout << "update task" << endl;
string qry;
if (priority != 0) {
qry = "UPDATE Task SET title=\"" + title + "\","
+ "description=\"" + description + "\","
+ "completed=" + to_string(completed) + ","
+ "priority=" + to_string(priority) + " "
+ "WHERE id=" + to_string(id) + ";";
} else {
qry = "UPDATE Task SET title=\"" + title + "\","
+ "description=\"" + description + "\","
+ "completed=" + to_string(completed) + " "
+ "WHERE id=" + to_string(id) + ";";
}
cout << "qry: " << qry << endl;
char *messageError;
int exit = sqlite3_exec(this->db, qry.c_str(), nullptr, nullptr, &messageError);
if (exit != SQLITE_OK) {
std::cerr << messageError << std::endl;
sqlite3_free(messageError);
}
}
/**
*
* Deletes a task from the database using an sql query
* @param id of a task
*/
void deleteTask(int id) {
cout << "delete task" << endl;
string qry;
qry = "DELETE FROM Task WHERE id=" + to_string(id) + ";";
cout << "qry: " << qry << endl;
char *messageError;
int exit = sqlite3_exec(this->db, qry.c_str(), nullptr, nullptr, &messageError);
if (exit != SQLITE_OK) {
std::cerr << messageError << std::endl;
sqlite3_free(messageError);
}
}
};
#endif //TODOS_DATABASE_H
|
Swift | UTF-8 | 1,241 | 3.453125 | 3 | [] | no_license | //
// AnimateTextSize.swift
// NewSwift
//
// Created by Massa Antonio on 30/06/21.
//
import SwiftUI
struct AnimatableSystemFontModifier: AnimatableModifier {
var size: CGFloat
var weight: Font.Weight
var design: Font.Design
var animatableData: CGFloat {
get { size }
set { size = newValue }
}
func body(content: Content) -> some View {
content
.font(.system(size: size, weight: weight, design: design))
}
}
extension View {
func animatableSystemFont(size: CGFloat, weight: Font.Weight = .regular, design: Font.Design = .default) -> some View {
self.modifier(AnimatableSystemFontModifier(size: size, weight: weight, design: design))
}
}
struct AnimateTextSize: View {
@State private var fontSize: CGFloat = 32
var body: some View {
Text("Hello, World!")
.animatableSystemFont(size: fontSize)
.onTapGesture {
withAnimation(.spring(response: 0.5, dampingFraction: 0.5, blendDuration: 1).repeatForever()) {
fontSize = 72
}
}
}
}
struct AnimateTextSize_Previews: PreviewProvider {
static var previews: some View {
AnimateTextSize()
}
}
|
Python | UTF-8 | 1,457 | 2.609375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from wtforms import Form, IntegerField, StringField, PasswordField
from wtforms.validators import ValidationError, DataRequired, Length, NumberRange, Email, EqualTo
from app.models.user import User
class Emailform(Form):
email = StringField(validators=[DataRequired(), Length(8, 64),
Email(message='电子邮件不符合规范')])
class LoginForm(Emailform):
password = PasswordField(validators=[
DataRequired(message='密码不可以为空,请输入你的密码'), Length(6, 32)])
class RegisterForm(LoginForm):
nickname = StringField(validators=[DataRequired(),
Length(2, 10, message='昵称至少需要两个字符,最多10个字符')])
def validate_email(self, field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('电子邮件已被注册')
def validate_nickname(self, field):
if User.query.filter_by(nickname=field.data).first():
raise ValidationError('昵称已存在')
class ResetPasswordForm(Form):
password1 = PasswordField(
validators=[DataRequired(),
Length(6, 32, message='密码长度至少需要6到32个字符之间'),
EqualTo('password2', message='两次输入的密码不相同')])
password2 = PasswordField(validators=[DataRequired(), Length(6, 32)])
|
Java | UTF-8 | 1,692 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package com.hengyi.mvp.ui.jiandan;
import com.hengyi.mvp.bean.FreshNewsBean;
import com.hengyi.mvp.net.BaseObserver;
import com.hengyi.mvp.net.JanDanApi;
import com.hengyi.mvp.net.RxSchedulers;
import com.hengyi.mvp.ui.base.BasePresenter;
import javax.inject.Inject;
/**
* Created by honghengqiang on 2018/2/21.
*/
public class JanDanPresenter extends BasePresenter<JandanContract.View> implements JandanContract.Presenter{
private static final String TAG = "JanDanPresenter";
JanDanApi mJanDanApi;
@Inject
public JanDanPresenter(JanDanApi janDanApi){
this.mJanDanApi = janDanApi;
}
@Override
public void getData(String type, int page) {
if(type.equals(JanDanApi.TYPE_FRESH)) {
getFreshNews(page);
}else {
getDetailData(type,page);
}
}
@Override
public void getFreshNews(final int page) {
mJanDanApi.getFreshNews(page)
.compose(RxSchedulers.<FreshNewsBean>applySchedulers())
.compose(mView.<FreshNewsBean>bindToLife())
.subscribe(new BaseObserver<FreshNewsBean>() {
@Override
public void onSucess(FreshNewsBean freshNewsBean) {
if(page>1) {
mView.loadMoreFreshNews(freshNewsBean);
}else {
mView.loadFreshNews(freshNewsBean);
}
}
@Override
public void onFail(Throwable e) {
}
});
}
@Override
public void getDetailData(String type, int page) {
}
}
|
Markdown | UTF-8 | 1,126 | 2.65625 | 3 | [] | no_license | <div itemscope itemtype="http://developers.google.com/ReferenceObject">
<meta itemprop="name" content="tf.contrib.quantize.create_eval_graph" />
</div>
# tf.contrib.quantize.create_eval_graph
``` python
create_eval_graph(
input_graph,
elements=None
)
```
Defined in [`tensorflow/contrib/quantize/python/quantize_graph.py`](https://www.tensorflow.org/code/tensorflow/contrib/quantize/python/quantize_graph.py).
Returns a transformed eval input_graph for simulated quantization.
The forward pass has fake quantization ops inserted to simulate the error
introduced by quantization.
#### Args:
* <b>`input_graph`</b>: The tf.Graph to be transformed.
* <b>`elements`</b>: (Optional) List of Tensors and Operations in input_graph whose
corresponding elements in the new graph will be returned.
#### Returns:
Returns a tuple(g, l) where:
g is new tf.Graph that is rewritten for simulated quantization.
l is a list of Tensors/Operations in g corresponding to the provided input
elements.
#### Raises:
* <b>`ValueError`</b>: If elements contains an element that isn't a tf.Tensor or
tf.Operation. |
TypeScript | UTF-8 | 1,669 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | import * as fromActions from '../actions/tasks.actions';
import { SearchTaskHistoryResult } from '../models/search-task-history-result.model';
import { SearchTasksResult } from "../models/search-tasks-result.model";
import { Task } from '../models/task.model';
export interface TaskLstState {
isLoading: boolean;
isErrorLoadOccured: boolean;
content: SearchTasksResult;
}
export interface TaskState {
isLoading: boolean;
isErrorLoadOccured: boolean;
rendering: any;
description: string;
searchTaskHistory: SearchTaskHistoryResult;
task: Task;
}
export const initialTaskLstState: TaskLstState = {
content: null,
isLoading: true,
isErrorLoadOccured: false
};
export const initialTaskState: TaskState = {
rendering: {},
description: null,
task: null,
searchTaskHistory: null,
isLoading: true,
isErrorLoadOccured: false
};
export function taskLstReducer(state = initialTaskLstState, action: fromActions.ActionsUnion) {
switch (action.type) {
case fromActions.ActionTypes.COMPLETE_SEARCH_TASKS:
state.content = action.content;
return { ...state };
default:
return state;
}
}
export function taskReducer(state = initialTaskState, action: fromActions.ActionsUnion) {
switch (action.type) {
case fromActions.ActionTypes.COMPLETE_GET_TASK:
state.rendering = action.rendering;
state.task = action.task;
state.description = action.description;
state.searchTaskHistory = action.searchTaskHistory;
return { ...state };
default:
return state;
}
} |
Markdown | UTF-8 | 3,203 | 3.125 | 3 | [] | no_license | # 科学网—人眼在黑暗中能看见东西吗? - 徐明昆的博文
# 人眼在黑暗中能看见东西吗?
已有 12384 次阅读2014-3-9 11:30|个人分类:[科学哲学](http://blog.sciencenet.cn/home.php?mod=space&uid=537101&do=blog&classid=153025&view=me)|系统分类:[科研笔记](http://blog.sciencenet.cn/home.php?mod=space&do=blog&view=all&uid=537101&catid=1)
首先说明,在绝对没有光线的黑屋里,并且不考虑红外紫外的边值情况,任何生物应该是看不见东西的。
本文说的黑暗,是日常生活中只有星星的夜晚,室内外光线非常微弱的环境。
人眼通常在黑暗中是看不见东西的,但是也有例外,主要有四类:
**一 白化病人**
白化病人,指的是缺乏色素,通常全身缺乏色素,也有身体颜色看上去正常,仅仅眼睛缺乏色素的。
因为缺乏色素,所以眼睛难以承受光线的刺激,白天不自觉地眯着眼睛躲避光线,晚上视力倒正常。[1]
**二 高度近视者**
高度近视者,正常距离下,晚上也是看不到东西的。
但是,高度近视者擅长看很近的东西,书报。因为距离眼睛很近,进入眼睛的光线
相对较强,所以夜晚看书报的能力强一些。
BTW,正常人如果经常在昏暗光线下看东西,为了弥补光线不足,就会凑得更近,很容易得近视眼。
**三 杆状细胞增多者**
人眼睛的视网膜中,有锥体细胞和杆状细胞两种不同的感光细胞。锥体细胞和杆状细胞在处理可见光时是有分工的,锥体感光细胞集中于黄斑区的中心凹处,专门处理较强的光,而较暗的光则由黄斑区以外的视网膜中杆状细胞处理。[2] 正常人的杆状细胞少,如果杆状细胞数目异常多,夜视能力就会比较强。
杆状细胞感光能力极强,但是感觉不到色彩,所以需要夜行的动物们,比如猫,狼,猫头鹰等等,还有大多数哺乳动物,锥体细胞相对较少,应该色盲或者色弱。据试验,猫狗马看到的世界和动物,并不是人所看到的五彩的世界和动物,而是单色的,这个结论和人的直觉是不同的。
**四 受过专门训练者**
普通人经过专门训练,夜视能力可能会有提高,不细述。
[1][http://v.ifeng.com/documentary/discovery/2014002/031ec5b3-0244-4a9d-844c-f2d904a5dbc3.shtml#_v_www6](http://v.ifeng.com/documentary/discovery/2014002/031ec5b3-0244-4a9d-844c-f2d904a5dbc3.shtml#_v_www6)
[2]视觉[http://baike.baidu.com/link?url=fvnlD33tw90OqPEdtTY6Vtom7QORRpRta6MdzZf5RB7uUGnN12F-bc_tvC6bZDuZ](http://baike.baidu.com/link?url=fvnlD33tw90OqPEdtTY6Vtom7QORRpRta6MdzZf5RB7uUGnN12F-bc_tvC6bZDuZ)
转载本文请联系原作者获取授权,同时请注明本文来自徐明昆科学网博客。
链接地址:[http://blog.sciencenet.cn/blog-537101-774384.html](http://blog.sciencenet.cn/blog-537101-774384.html)
上一篇:[妨碍中国科技进步的是科技体制而非中国文化](blog-537101-773213.html)
下一篇:[量子力学:对波粒二象性的质疑](blog-537101-774889.html)
|
Java | UTF-8 | 715 | 2.1875 | 2 | [] | no_license | package org.jasig.cas.authentication.handler;
/**
* @author SxL
* Created on 9/25/2018 2:15 PM.
*/
public final class UnsupportedCredentialsException extends AuthenticationException {
public static final UnsupportedCredentialsException ERROR = new UnsupportedCredentialsException();
private static final long serialVersionUID = 3977861752513837361L;
private static final String CODE = "error.authentication.credentials.unsupported";
public UnsupportedCredentialsException() {
super("error.authentication.credentials.unsupported");
}
public UnsupportedCredentialsException(Throwable throwable) {
super("error.authentication.credentials.unsupported", throwable);
}
}
|
Java | UTF-8 | 1,311 | 2.078125 | 2 | [] | no_license | package com.yyt.blue.bluetooth;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import me.wangyuwei.particleview.ParticleView;
public class SplashActivit extends AppCompatActivity implements ParticleView.ParticleAnimListener {
private ParticleView mParticleView;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mParticleView = (ParticleView) findViewById(R.id.picview);
mParticleView.setOnParticleAnimListener(this);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mParticleView.startAnim();
}
}, 1000);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onAnimationEnd() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashActivit.this, MainActivity.class);
startActivity(intent);
}
}, 2000);
}
}
|
Shell | UTF-8 | 3,422 | 4.5625 | 5 | [] | no_license | #!/bin/bash
SAVEIFS=$IFS
commentPattern="((#|\/\/))"
function set_IFS_no_spaces {
IFS=$(echo -en "\n\b")
}
function reset_IFS {
IFS=$SAVEIFS
}
function writeToFile {
echo "Writing to file: ${tempFileName}"
echo "$*" >> "${tempFileName}"
}
if [ "$1" == "-debug" ]; then
debug="-debug"
echo "Debug turned on for setIniVariable.sh!"
shift
fi
function decho {
if [ "${debug}" ]; then
echo "$@"
fi
}
if [ "$2" ]; then
fileName="$1"
shift
variable="$1"
shift
valueToSet="$*"
set_IFS_no_spaces
tempFileName="${fileName}.$(date +%s%N)"
while [ -f "${tempFileName}" ]; do
tempFileName="${fileName}.$(date +%s%N)"
done
decho "tempFileName: ${tempFileName}"
if [ -f "${fileName}" ]; then
results=$(cat "${fileName}")
# Check all results to see if a match for the variable exists already.
for b in ${results}; do
# valueTest checks for the variable and gets the value of it if it exists
valueTest="$(echo $b | sed -E "s/[[:blank:]]*${commentPattern}.*//g" | sed -E "s/${commentPattern}.*//g" | grep -P "^((${variable}|${variable}[[:blank:]]))=")"
if ! [ "$valueTest" ]; then
# If it is not a match, just write this line to the temporary file
writeToFile "$b"
else
# This is so that it does not get added to the end of the line, since it was found
valueSet="true"
# This preserves any comments that were on the line.
comments="$(echo "$b" | grep -Po "[[:blank:]]*${commentPattern}.*")"
# Instead of writing the line, add the desired value instead, preserving any comments.
writeToFile "${variable}=${valueToSet}${comments}"
# This is just here to give assurance to the person using the command that it worked correctly and in case they actually need that old value.
oldValue="$(echo "$valueTest" | sed -E 's/.*=[[:blank:]]*//g' | sed 's/.*=//g')"
if [ "$oldValue" ]; then
echo "Value existed for variable, '${variable}'. Changing '${oldValue}' to '${valueToSet}'"
unset oldValue
else
echo "${variable} existed, but had no value. Set variable to '${valueToSet}'"
fi
unset comments
fi
done
else
valueSet="true"
echo "File did not exist! Creating it and adding the following line: ${variable}=${valueToSet}"
writeToFile "${variable}=${valueToSet}"
fi
# None of the lines contained the variable, so let's add it to the end of the file.
if ! [ "$valueSet" ]; then
echo "File found and variable did not already exist. Adding the following line to the end of file, '${fileName}': ${variable}=${valueToSet}"
writeToFile "${variable}=${valueToSet}"
fi
# Replace the original file with the temporary file, if it exists - the check to see if the temporary file exists is to avoid circumstances where the temporary file may not have been writeable
if [ -f "${tempFileName}" ]; then
echo "Replacing file with temporary file"
mv "${tempFileName}" "${fileName}"
else
echo "ERROR: Could not write to a temporary file! Aborting! Please make sure you run this script from a directory you have write permissions in!"
fi
else
echo "This script will set an individual value to an ini file for you."
echo "Usage: setIniValue.sh [FileName] [variable] [value]"
echo "Note: This command will preserve comments if some already existed and can be used to add a comment when changing or adding the value."
echo "Example: setIniValue.sh myIni.ini onetwo \"buckle my shoe, three four # close the door\""
fi
|
SQL | UTF-8 | 6,459 | 3.390625 | 3 | [] | no_license | /*
MySQL Data Transfer
Source Host: localhost
Source Database: lgdb
Target Host: localhost
Target Database: lgdb
Date: 2014/3/2 22:28:37
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for ligong_application_form
-- ----------------------------
DROP TABLE IF EXISTS `ligong_application_form`;
CREATE TABLE `ligong_application_form` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`extension` varchar(32) NOT NULL,
`key_word` varchar(255) NOT NULL,
`file_path` varchar(255) NOT NULL,
`add_time` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_class
-- ----------------------------
DROP TABLE IF EXISTS `ligong_class`;
CREATE TABLE `ligong_class` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`session_id` int(11) NOT NULL,
`speciality_id` int(11) NOT NULL,
`name` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_curriculum
-- ----------------------------
DROP TABLE IF EXISTS `ligong_curriculum`;
CREATE TABLE `ligong_curriculum` (
`id` int(11) NOT NULL AUTO_INCREMENT,
` session_id` int(11) NOT NULL,
`speciality_id` int(11) NOT NULL,
`year` varchar(32) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_online_classes
-- ----------------------------
DROP TABLE IF EXISTS `ligong_online_classes`;
CREATE TABLE `ligong_online_classes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`add_time` date NOT NULL,
`introduction` text,
`key_word` varchar(255) DEFAULT NULL,
`poster_name` varchar(255) DEFAULT NULL,
`poster_path` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_online_classes_content
-- ----------------------------
DROP TABLE IF EXISTS `ligong_online_classes_content`;
CREATE TABLE `ligong_online_classes_content` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`online_classes_id` int(11) NOT NULL,
`file_path` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`extension` varchar(32) NOT NULL,
`add_time` datetime NOT NULL,
`sort` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_reservation
-- ----------------------------
DROP TABLE IF EXISTS `ligong_reservation`;
CREATE TABLE `ligong_reservation` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` varchar(16) NOT NULL,
`reservation_curriculum_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_reservation_curriculum
-- ----------------------------
DROP TABLE IF EXISTS `ligong_reservation_curriculum`;
CREATE TABLE `ligong_reservation_curriculum` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`year` varchar(32) NOT NULL,
`class_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`status` int(11) NOT NULL DEFAULT '0',
`deadline` date DEFAULT NULL,
`total_hours` int(11) NOT NULL,
`credit` double NOT NULL,
`max_num` int(11) NOT NULL,
`current_num` int(11) NOT NULL,
`from_week` int(11) NOT NULL,
`end_week` int(11) NOT NULL,
`weekday` int(11) NOT NULL,
`from_lesson` int(11) NOT NULL,
`end_lesson` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_session
-- ----------------------------
DROP TABLE IF EXISTS `ligong_session`;
CREATE TABLE `ligong_session` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(16) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_speciality
-- ----------------------------
DROP TABLE IF EXISTS `ligong_speciality`;
CREATE TABLE `ligong_speciality` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`session_id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_student_work
-- ----------------------------
DROP TABLE IF EXISTS `ligong_student_work`;
CREATE TABLE `ligong_student_work` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`session_id` int(11) NOT NULL,
`speciality_id` int(11) NOT NULL,
`class _id` int(11) NOT NULL,
`curriculum_id` int(11) NOT NULL,
`student_id` varchar(16) NOT NULL,
`year` varchar(32) NOT NULL,
`title` varchar(255) NOT NULL,
`add_time` datetime NOT NULL,
`introduction` tinyint(4) DEFAULT NULL,
`recommended` int(11) NOT NULL DEFAULT '0',
`comments` text,
`type` varchar(32) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_student_work_content
-- ----------------------------
DROP TABLE IF EXISTS `ligong_student_work_content`;
CREATE TABLE `ligong_student_work_content` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_work_id` int(11) NOT NULL,
`file_path` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`extension` varchar(32) NOT NULL,
`add_time` datetime NOT NULL,
`sort` int(11) DEFAULT NULL,
`cover` int(11) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_students
-- ----------------------------
DROP TABLE IF EXISTS `ligong_students`;
CREATE TABLE `ligong_students` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`session_id` int(11) NOT NULL,
`speciality_id` int(11) NOT NULL,
`class _id` int(11) NOT NULL,
`student_id` varchar(16) NOT NULL,
`name` varchar(64) NOT NULL,
`password` varchar(32) NOT NULL,
`avatar` varchar(255) DEFAULT NULL,
`introduction` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for ligong_teachers
-- ----------------------------
DROP TABLE IF EXISTS `ligong_teachers`;
CREATE TABLE `ligong_teachers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records
-- ----------------------------
|
Java | UTF-8 | 509 | 2.1875 | 2 | [] | no_license | package sk.baric.animalshop.rest.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
/**
* Throw this exception, when no product ids are defined by the user during submiting an order.
*
* @author Juraj Baric
*
*/
@SuppressWarnings("serial")
public class NoProductOrderedException extends HttpClientErrorException {
public NoProductOrderedException() {
super(HttpStatus.UNPROCESSABLE_ENTITY, "You didn't define any product id");
}
}
|
Java | UTF-8 | 4,769 | 2.4375 | 2 | [
"MIT"
] | permissive | package com.lothrazar.cyclic.block.endershelf;
import com.lothrazar.cyclic.registry.BlockRegistry;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.minecraft.block.BlockState;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.CapabilityItemHandler;
public class EnderShelfHelper {
public static final int MAX_ITERATIONS = 24; // TODO config entry
public static BlockPos findConnectedController(World world, BlockPos shelfPos) {
return recursivelyFindConnectedController(world, shelfPos, new HashMap<BlockPos, Integer>(), 0);
}
private static BlockPos recursivelyFindConnectedController(World world, BlockPos pos, Map<BlockPos, Integer> visitedLocations, int iterations) {
BlockState state = world.getBlockState(pos);
if (iterations > MAX_ITERATIONS) {
return null; //We tried for too long, stop now before there's an infinite loop
}
if (!(state.getBlock() instanceof BlockEnderShelf)) {
return null; //We left the group of connected shelves, stop here.
}
if (visitedLocations.containsKey(pos)) {
return null; //We've already traveled here and didn't find anything, stop here.
}
if (state.getBlock() == BlockRegistry.ender_controller) {
return pos; //We found the Controller!
}
visitedLocations.put(pos, iterations);
BlockPos[] possibleControllers = new BlockPos[Direction.values().length];
BlockPos returnController = null;
int index = 0;
iterations++;
for (Direction direction : Direction.values()) {
if (state.get(BlockStateProperties.HORIZONTAL_FACING) != direction) {
possibleControllers[index] = recursivelyFindConnectedController(world, pos.offset(direction), visitedLocations, iterations);
}
if (possibleControllers[index] != null) {
returnController = possibleControllers[index];
}
}
return returnController;
}
public static Set<BlockPos> findConnectedShelves(World world, BlockPos controllerPos) {
return recursivelyFindConnectedShelves(world, controllerPos, new HashSet<>(), new HashSet<>(), 0);
}
public static Set<BlockPos> recursivelyFindConnectedShelves(World world, BlockPos pos, Set<BlockPos> visitedLocations, Set<BlockPos> shelves, int iterations) {
BlockState state = world.getBlockState(pos);
if (visitedLocations.contains(pos)) {
return shelves; //We've already traveled here and didn't find anything, stop here.
}
visitedLocations.add(pos);
if (iterations > MAX_ITERATIONS) {
return shelves; //We tried for too long, stop now before there's an infinite loop
}
if (iterations > 0 && !isShelf(state)) {
return shelves; //We left the group of connected shelves, stop here.
}
//If we made it this far, we found a valid shelf.
if (iterations > 0) {
shelves.add(pos); //add the shelf, but not on the first iteration because that's the controller
}
iterations++;
for (Direction direction : Direction.values()) {
if (state.get(BlockStateProperties.HORIZONTAL_FACING) != direction) {
shelves.addAll(recursivelyFindConnectedShelves(world, pos.offset(direction), visitedLocations, shelves, iterations));
}
}
return shelves;
}
public static EnderShelfItemHandler getShelfHandler(TileEntity te) {
if (te != null &&
te.getBlockState().getBlock() == BlockRegistry.ender_shelf &&
te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).isPresent() &&
te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).resolve().get() instanceof EnderShelfItemHandler) {
return (EnderShelfItemHandler) te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).resolve().get();
}
return null;
}
public static EnderControllerItemHandler getControllerHandler(TileEntity te) {
if (te != null &&
te.getBlockState().getBlock() == BlockRegistry.ender_controller &&
te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).isPresent() &&
te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).resolve().get() instanceof EnderControllerItemHandler) {
return (EnderControllerItemHandler) te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY).resolve().get();
}
return null;
}
public static boolean isController(BlockState state) {
return state.getBlock() == BlockRegistry.ender_controller;
}
public static boolean isShelf(BlockState state) {
return state.getBlock() == BlockRegistry.ender_shelf;
}
}
|
Markdown | UTF-8 | 3,468 | 3.140625 | 3 | [
"ISC"
] | permissive | # Gymtrack
[](http://shields.io/)
[](https://opensource.org/licenses/ISC)
## Description
*Gymtrack* is an application that provides gym owners with a system to manage data related to instructors, members, classes, and reviews left by members.
There are two types of application users: *instructors* and *members*. Instructors are able to log in and add/edit/delete classes. Members are able to log in and book classes as well as leave reviews about classes and/or class instructors.
## Table of Contents
- [Motivations](#Motivations)
- [Technologies Used](#Technologies-Used)
- [Testing](#Testing)
- [Links](#Links)
- [Screenshots](#Screenshots)
- [Contributors](#Contributors)
- [License](#License)
## Motivations
We wanted to design a useful application that would facilitate the basic process of creating and booking classes at gyms, and to provide gym members with a platform on which to provide feedback.
As budding web developers, we also approached this project with the objective to build on our understanding of application architectures, in particular, through the implementation of the Model-View-Controller design pattern.
## Technologies Used
- Node.js
- Express / Express sessions
- MySQL / Sequelize
- Passport.js
- bcrypt
- Handlebars
- CSS / Bootstrap
- Google Fonts
- Font Awesome
## Testing
You can test various application functionalities by logging in through one of the seed accounts provided in the source code:
1. Navigate to the the db/seeds.js file and use any one of the provided email and password credentials.
*Note: There is a db/seeds.js file and a db/seeds.sql file. You will need to refer to the JavaScript file, not the SQL file.*
2. To log in as an instructor, use the email and password of one of the three instructor accounts listed under the "Instructor seeds" comment.
3. To log in as a member, use the email and password of any one of the four member accounts listed under the "Member seeds" comment.
4. Anyone who signs up for an account through the signup page is a member. In the meantime, instructor accounts must be created through the backend.
## Links
- GitHub repository: [github.com/jkaho/gymtrack](https://github.com/jkaho/gymtrack)
- Deployed application: [gymtrack-app.herokuapp.com](https://gymtrack-app.herokuapp.com/)
- Presentation slides: [Google Slides](https://docs.google.com/presentation/d/1Fq8ysZkSJzhZkVIfUYoRk6_kMDduu-L-Hf_VRpZTnmg/edit?usp=sharing)
## Screenshots
### Homepage

### Classes

### Reviews

### Profile page
#### Member

#### Instructor

## Contributers
- [Kevin Lin](https://github.com/klin4994)
- [Jessica Hong](https://github.com/jkaho)
- [Tomomi Inoue](https://github.com/Chib1co)
- [Joshua Steward](https://github.com/JoshSteward)
## License
This application is covered under the ISC license.
For more information, [click here](https://opensource.org/licenses/ISC).
|
C++ | UTF-8 | 10,366 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | #include <iostream>
#define DEBUG 1
#include <ring_buffer.h>
#include <stack.h>
#include <array.h>
#include <gtest/gtest.h>
using namespace Mcucpp;
using namespace Containers;
TEST(Containers, RingBuffer1)
{
RingBufferPO2<16, int> buf1;
const RingBufferPO2<16, int> &cref = buf1;
EXPECT_TRUE(buf1.empty());
EXPECT_TRUE(buf1.push_back(100));
EXPECT_FALSE(buf1.empty());
EXPECT_EQ(buf1.front(), 100);
EXPECT_TRUE(buf1.pop_front());
EXPECT_TRUE(buf1.empty());
EXPECT_FALSE(buf1.pop_front());
EXPECT_TRUE(buf1.push_back(200));
EXPECT_TRUE(buf1.push_back(300));
EXPECT_EQ(buf1.front(), 200);
EXPECT_EQ(buf1.back(), 300);
EXPECT_EQ(buf1.size(), 2);
EXPECT_EQ(cref.front(), 200);
EXPECT_EQ(cref.back(), 300);
EXPECT_EQ(cref.size(), 2);
buf1.clear();
EXPECT_EQ(buf1.size(), 0);
EXPECT_TRUE(buf1.empty());
for(unsigned i=0; i < buf1.capacity(); i++)
EXPECT_TRUE(buf1.push_back(i));
EXPECT_FALSE(buf1.push_back(-1));
EXPECT_TRUE(buf1.full());
EXPECT_TRUE(cref.full());
for(unsigned i=0; i < buf1.capacity(); i++)
{
EXPECT_EQ(buf1[i], int(i));
EXPECT_EQ(cref[i], int(i));
}
for(unsigned i=0; i < buf1.capacity(); i++)
{
EXPECT_EQ(buf1.front(), int(i));
EXPECT_EQ(cref.front(), int(i));
EXPECT_TRUE(buf1.pop_front());
}
}
TEST(Containers, RingBufferPO2FullCondition)
{
RingBufferPO2<16, int> buf1;
for(unsigned i=0; i < buf1.capacity(); i++)
EXPECT_TRUE(buf1.push_back(i));
ASSERT_EQ(16, buf1.size());
EXPECT_TRUE(buf1.full());
for(unsigned i=0; i < 0xffff; i++)
{
ASSERT_TRUE(buf1.pop_front());
ASSERT_TRUE(buf1.push_back(i));
ASSERT_EQ(16, buf1.size());
}
}
TEST(Containers, RingBufferFullCondition)
{
RingBuffer<16, int> buf1;
for(unsigned i=0; i < buf1.capacity(); i++)
EXPECT_TRUE(buf1.push_back(i));
ASSERT_EQ(16, buf1.size());
EXPECT_TRUE(buf1.full());
for(unsigned i=0; i < 0xffff; i++)
{
ASSERT_TRUE(buf1.pop_front());
ASSERT_TRUE(buf1.push_back(i));
ASSERT_EQ(16, buf1.size());
}
}
size_t RoundToWordBoundary(size_t size)
{
return (size + sizeof(unsigned) - 1) & ~(sizeof(unsigned) - 1);
}
TEST(Containers, RingBufferPO2StorageSize)
{
EXPECT_EQ(sizeof(uint_fast8_t), sizeof(RingBufferPO2<16, uint8_t>::size_type));
EXPECT_EQ(RoundToWordBoundary(16 + 2 * sizeof(uint_fast8_t)), sizeof(RingBufferPO2<16, uint8_t>));
EXPECT_EQ(sizeof(uint_fast16_t), sizeof(RingBufferPO2<256, uint8_t>::size_type));
EXPECT_EQ(RoundToWordBoundary(256 + 2 * sizeof(uint_fast16_t)), sizeof(RingBufferPO2<256, uint8_t>));
EXPECT_EQ(sizeof(uint_fast8_t), sizeof(RingBufferPO2<16, uint16_t>::size_type));
EXPECT_EQ(RoundToWordBoundary(16 * 2 + 2 * sizeof(uint_fast8_t)), sizeof(RingBufferPO2<16, uint16_t>));
EXPECT_EQ(sizeof(uint_fast16_t), sizeof(RingBufferPO2<256, uint16_t>::size_type));
EXPECT_EQ(RoundToWordBoundary(256 * 2 + 2 * sizeof(uint_fast16_t)), sizeof(RingBufferPO2<256, uint16_t>));
EXPECT_EQ(sizeof(uint_fast8_t), sizeof(RingBufferPO2<16, uint16_t>::size_type));
EXPECT_EQ(RoundToWordBoundary(16 * 4 + 2 * sizeof(uint_fast8_t)), sizeof(RingBufferPO2<16, uint32_t>));
EXPECT_EQ(sizeof(uint_fast16_t), sizeof(RingBufferPO2<256, uint32_t>::size_type));
EXPECT_EQ(RoundToWordBoundary(256 * 4 + 2 * sizeof(uint_fast16_t)), sizeof(RingBufferPO2<256, uint32_t>));
}
TEST(Containers, RingBuffer2)
{
RingBuffer<20, int> buf1;
const RingBuffer<20, int> &cref = buf1;
EXPECT_TRUE(buf1.empty());
EXPECT_TRUE(buf1.push_back(100));
EXPECT_FALSE(buf1.empty());
EXPECT_EQ(buf1.front(), 100);
EXPECT_TRUE(buf1.push_back());
EXPECT_EQ(buf1.back(), 0);
EXPECT_TRUE(buf1.pop_front());
EXPECT_TRUE(buf1.pop_front());
EXPECT_TRUE(buf1.empty());
EXPECT_FALSE(buf1.pop_front());
EXPECT_TRUE(buf1.push_back(200));
EXPECT_TRUE(buf1.push_back(300));
EXPECT_EQ(buf1.front(), 200);
EXPECT_EQ(buf1.back(), 300);
EXPECT_EQ(buf1.size(), 2);
EXPECT_EQ(cref.front(), 200);
EXPECT_EQ(cref.back(), 300);
EXPECT_EQ(cref.size(), 2);
buf1.clear();
EXPECT_EQ(buf1.size(), 0);
EXPECT_TRUE(buf1.empty());
for(unsigned i=0; i< buf1.capacity(); i++)
EXPECT_TRUE(buf1.push_back(i));
EXPECT_FALSE(buf1.push_back(-1));
EXPECT_TRUE(buf1.full());
EXPECT_TRUE(cref.full());
for(unsigned i=0; i < buf1.capacity(); i++)
{
EXPECT_EQ(buf1[i], int(i));
EXPECT_EQ(cref[i], int(i));
}
for(unsigned i=0; i < buf1.capacity(); i++)
{
EXPECT_EQ(buf1.front(), int(i));
EXPECT_EQ(cref.front(), int(i));
EXPECT_TRUE(buf1.pop_front());
}
}
TEST(Containers, Stack)
{
FixedStack<20, int> stack;
FixedStack<20, int> &cref = stack;
EXPECT_TRUE(stack.empty());
EXPECT_TRUE(cref.empty());
EXPECT_EQ(stack.size(), 0);
EXPECT_EQ(cref.size(), 0);
EXPECT_TRUE(stack.push_front(100));
EXPECT_FALSE(stack.empty());
EXPECT_FALSE(cref.empty());
EXPECT_EQ(stack.front(), 100);
EXPECT_EQ(cref.front(), 100);
EXPECT_TRUE(stack.pop_front());
EXPECT_FALSE(stack.pop_front());
EXPECT_TRUE(stack.empty());
EXPECT_TRUE(cref.empty());
EXPECT_TRUE(stack.push_front(200));
EXPECT_TRUE(stack.push_front(300));
EXPECT_EQ(stack.front(), 300);
EXPECT_EQ(cref.front(), 300);
EXPECT_EQ(stack.back(), 200);
EXPECT_EQ(cref.back(), 200);
EXPECT_EQ(stack.size(), 2);
EXPECT_EQ(cref.size(), 2);
stack.clear();
EXPECT_EQ(stack.size(), 0);
EXPECT_TRUE(stack.empty());
for(unsigned i=0; i< stack.capacity(); i++)
EXPECT_TRUE(stack.push_front(i));
EXPECT_FALSE(stack.push_front(-1));
for(unsigned i=0; i < stack.capacity(); i++)
{
EXPECT_EQ(stack[i], int(stack.capacity() - 1 - i));
EXPECT_EQ(cref[i], int(cref.capacity() - 1 - i));
}
for(unsigned i=0; i < stack.capacity(); i++)
{
EXPECT_EQ(stack.front(), int(stack.capacity() - 1 - i));
EXPECT_EQ(cref.front(), int(cref.capacity() - 1 - i));
EXPECT_TRUE(stack.pop_front());
}
}
TEST(Containers, Array)
{
FixedArray<20, int> array;
FixedArray<20, int> &cref = array;
EXPECT_TRUE(array.empty());
EXPECT_TRUE(cref.empty());
EXPECT_EQ(array.size(), 0);
EXPECT_EQ(cref.size(), 0);
EXPECT_TRUE(array.push_back(100));
EXPECT_FALSE(array.empty());
EXPECT_FALSE(cref.empty());
EXPECT_EQ(array.front(), 100);
EXPECT_EQ(cref.front(), 100);
EXPECT_TRUE(array.pop_back());
EXPECT_FALSE(array.pop_back());
EXPECT_TRUE(array.empty());
EXPECT_TRUE(cref.empty());
EXPECT_TRUE(array.push_back(200));
EXPECT_TRUE(array.push_back(300));
EXPECT_EQ(array.front(), 200);
EXPECT_EQ(cref.front(), 200);
EXPECT_EQ(array.back(), 300);
EXPECT_EQ(cref.back(), 300);
EXPECT_EQ(array.size(), 2);
EXPECT_EQ(cref.size(), 2);
array.clear();
EXPECT_EQ(array.size(), 0);
EXPECT_TRUE(array.empty());
for(unsigned i=0; i< array.capacity(); i++)
EXPECT_TRUE(array.push_back(i));
EXPECT_FALSE(array.push_back(-1));
for(unsigned i=0; i < array.capacity(); i++)
{
EXPECT_EQ(array[i], int(i));
EXPECT_EQ(cref[i], int(i));
}
for(unsigned i=0; i < array.capacity(); i++)
{
EXPECT_EQ(array.back(), int(array.capacity() - 1 - i));
EXPECT_EQ(cref.back(), int(cref.capacity() - 1 - i));
EXPECT_TRUE(array.pop_back());
}
}
TEST(Containers, ArrayBool)
{
FixedArray<20, bool> array;
FixedArray<20, bool> &cref = array;
EXPECT_TRUE(array.empty());
EXPECT_TRUE(cref.empty());
EXPECT_EQ(array.size(), 0);
EXPECT_EQ(cref.size(), 0);
EXPECT_TRUE(array.push_back(true));
EXPECT_FALSE(array.empty());
EXPECT_FALSE(cref.empty());
EXPECT_EQ(array.front(), true);
EXPECT_EQ(cref.front(), true);
EXPECT_TRUE(array.pop_back());
EXPECT_FALSE(array.pop_back());
EXPECT_TRUE(array.empty());
EXPECT_TRUE(cref.empty());
EXPECT_TRUE(array.push_back(false));
EXPECT_TRUE(array.push_back(true));
EXPECT_EQ(array.front(), false);
EXPECT_EQ(cref.front(), false);
EXPECT_EQ(array.back(), true);
EXPECT_EQ(cref.back(), true);
EXPECT_EQ(array.size(), 2);
EXPECT_EQ(cref.size(), 2);
array.clear();
EXPECT_EQ(array.size(), 0);
EXPECT_TRUE(array.empty());
for(unsigned i=0; i< array.capacity(); i++)
EXPECT_TRUE(array.push_back(bool(i & 1)));
EXPECT_FALSE(array.push_back(false)!=0);
for(unsigned i=0; i < array.capacity(); i++)
{
EXPECT_EQ(array[i], bool(i & 1));
EXPECT_EQ(cref[i], bool(i & 1));
}
for(unsigned i=0; i < array.capacity(); i++)
{
EXPECT_EQ(array.back(), bool(int(array.capacity() - 1 - i) & 1) );
EXPECT_EQ(cref.back(), bool(int(cref.capacity() - 1 - i) & 1) );
EXPECT_TRUE(array.pop_back());
}
}
class ArrayBoolInitClass
{
public:
FixedArray<20, bool> array;
ArrayBoolInitClass();
};
ArrayBoolInitClass::ArrayBoolInitClass()
:array()
{
array.push_back(false);
}
TEST(Containers, ArrayBoolInit)
{
ArrayBoolInitClass foo;
EXPECT_EQ(foo.array.size(), 1);
ArrayBoolInitClass *pfoo = new ArrayBoolInitClass();
EXPECT_EQ(pfoo->array.size(), 1);
delete pfoo;
}
class ConstructionTest
{
static int _count;
int _data;
public:
ConstructionTest()
:_data(_count)
{
_count ++;
}
static void Reset()
{
_count = 0;
}
static int Count()
{
return _count;
}
};
int ConstructionTest::_count = 0;
TEST(Array, ConstructionTest)
{
ConstructionTest::Reset();
FixedArray<20, ConstructionTest> array;
EXPECT_EQ(0, ConstructionTest::Count());
for(int i = 0; i<10; i++)
{
array.push_back( );
EXPECT_EQ(i+1, ConstructionTest::Count());
}
}
TEST(RingBufferPO2, ConstructionTest)
{
ConstructionTest::Reset();
RingBufferPO2<16, ConstructionTest> array;
EXPECT_EQ(0, ConstructionTest::Count());
for(int i = 0; i<10; i++)
{
array.push_back( );
EXPECT_EQ(i+1, ConstructionTest::Count());
}
}
TEST(RingBuffer, ConstructionTest)
{
ConstructionTest::Reset();
RingBuffer<22, ConstructionTest> array;
EXPECT_EQ(0, ConstructionTest::Count());
for(int i = 0; i<10; i++)
{
array.push_back( );
EXPECT_EQ(i+1, ConstructionTest::Count());
}
}
TEST(FixedStack, ConstructionTest)
{
ConstructionTest::Reset();
FixedStack<22, ConstructionTest> array;
EXPECT_EQ(0, ConstructionTest::Count());
for(int i = 0; i<10; i++)
{
array.push_front(ConstructionTest() );
EXPECT_EQ(i+1, ConstructionTest::Count());
}
} |
Markdown | UTF-8 | 2,066 | 3.15625 | 3 | [] | no_license |
# 汇编实验1:环境搭建与Debug使用 - 迂者-贺利坚的专栏 - CSDN博客
2017年03月08日 22:52:17[迂者-贺利坚](https://me.csdn.net/sxhelijian)阅读数:1567
### 1 实验目的
学会搭建汇编语言程序设计的软件平台
学会Debug实用程序的基本功能
对汇编指令、寄存器、内存空间产生直观的认识
### 2 实验内容
**任务0-搭建汇编语言实验环境**
参考视频“0105 汇编语言实践环境搭建”,搭建汇编语言实验环境,以便于下面的工作。
如果使用的winXP,可以不安装DOSBOX模拟器,而是用XP的MS-DOS方式运行masm文件夹中的命令。
参考文章:[搭建x86汇编语言学习环境(内含软件下载链接)](http://blog.csdn.net/sxhelijian/article/details/54845039)
**任务1-Debug程序的使用**
参考视频“0205 Debug的使用”和教材P35页对应的讲解,自行演练相关的Debug命令。
用R命令查看、改变CPU寄存器的内容
用D命令查看内存中的内容
用E命令改变内存中的内容
用U命令将内存中的机器指令翻译成汇编指令
用A命令以汇编指令的格式在内存中写入机器指令
用T命令执行机器指令
实验报告中,每条命令至少要截一个图展示。
**任务2-使用Debug运行程序**
使用Debug,将右面的程序段写入内存(用a命令)后单步执行(用t命令),观察每条指令执行后CPU中相关寄存器中内容的变化。
**任务3-查看内存中的内容**
在内存FFF00H~FFFFF间浏览(用d命令),找到一段记录日期值的内存,截屏并说明日期值。
注:这个日期代表主板的生产日期,参考第1章1.15节
**任务4-在屏幕上显示多彩符号**
向内存B8100H开始的空间中写入如下数据“01 01 02 02 03 03 04 04”(用e命令),观察并记录产生的现象,再修改写入的数据,如改写为“4C 17 6F 92 76 a3 65 84”,以及你想玩的其他数值,再观察和记录。
注:对实验结果的解释,见第1章1.15节和教材187页实验9。
|
TypeScript | UTF-8 | 349 | 2.59375 | 3 | [] | no_license | export interface UserName {
title: string;
first: string;
last: string;
}
export interface UserId {
name: string;
value: string;
}
export interface UserPicture {
large: string;
medium: string;
thumbnail: string;
}
export interface User {
id: UserId;
name: UserName;
email: string;
phone: string;
picture: UserPicture;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.