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
| 697
| 3.953125
| 4
|
[
"MIT"
] |
permissive
|
'''
subsets and subarrays
subarrays:
a = [10,20,30]
=> [
[10], [20], [30]
[10,20], [10,20,30], [20,30],
]
subsets:
a = [10,20,30]
=> [
[], [10,20,30]
[10], [20], [30], [10, 20], [10, 30], [20, 30]
]
'''
def print_subsets(a):
limit = 2 ** len(a)
for i in range(limit):
for j in range(len(a)):
if(i & (1 << j) > 0):
print(a[j], end=" ")
print()
def print_subarray(a):
for i in range(len(a)):
for j in range(i, len(a)):
for k in range(i, j+1):
print(a[k], end=" ")
print()
print_subsets([10,20,30])
print_subarray([10,20,30])
|
Ruby
|
UTF-8
| 177
| 3.796875
| 4
|
[] |
no_license
|
print "Please enter a number: "
number_1 = gets.to_i
def always_three(number)
(((((number + 5) * 2) - 4) / 2) - number)
end
puts "Always " + always_three(number_1).to_s + "."
|
Shell
|
UTF-8
| 6,676
| 3.671875
| 4
|
[] |
no_license
|
#!/bin/bash
. /workspace/ENV
ENVIRONMENT="dev"
BASEHTML="/var/www/html"
DOCROOT="/var/www/html/web"
DRUSH="/.composer/vendor/drush/drush/drush -y"
GRPID=$(stat -c "%g" /var/lib/mysql/)
LOCAL_IP=$(hostname -I| awk '{print $1}')
HOSTIP=$(/sbin/ip route | awk '/default/ { print $3 }')
DEV_MODULES_ENABLED=("${DEV_MODULES_ENABLED[*]}" $(ls /workspace/modules))
DEV_MODULES_ENABLED=("${DEV_MODULES_ENABLED[*]}" $(ls /workspace/.base/modules))
DEV_MODULES_ENABLED=("${DEV_MODULES_ENABLED[*]}" $(ls /workspace/features))
DEV_MODULES_ENABLED=("${DEV_MODULES_ENABLED[*]}" $(ls /workspace/.base/features))
DEV_THEMES_ENABLED=("${DEV_THEMES_ENABLED[*]}" $(ls /workspace/themes))
DEV_THEMES_ENABLED=("${DEV_THEMES_ENABLED[*]}" $(ls /workspace/.base/themes))
function logrun(){
LABEL=$1; shift
LOGFILE=$1; shift
COMMAND=$1; shift
declare -a ARGS=(${@@Q})
echo ${COMMAND} ${ARGS[*]} >> "/tmp/${LOGFILE}"
echo | tee "/tmp/${LOGFILE}"
echo "++++ ${LABEL}" | tee "/tmp/${LOGFILE}"
echo " Started $(date)" | tee "/tmp/${LOGFILE}"
eval ${COMMAND} ${ARGS[*]} >> "/tmp/${LOGFILE}" 2>&1
if [[ $? -ne 0 ]]; then
echo " Error running command. Output follows:"
cat "/tmp/${LOGFILE}"
echo
exit -1
fi
echo " Completed $(date)"
}
echo
echo "----------------------------------------------------------------------------------"
echo " ${SITE_NAME} installation started"
echo " $(date)"
echo "----------------------------------------------------------------------------------"
# Setup hosts file.
echo "${HOSTIP} dockerhost" >> /etc/hosts
# Start supervisord
supervisord -c /etc/supervisor/conf.d/supervisord.conf -l /tmp/supervisord.log
# Composer and Drush commands run from here.
cd ${BASEHTML}
# Run composer create-project
if ! logrun "Running \`composer create-project\`. This takes a while." \
"composer-create-project.log" \
composer create-project --no-interaction; then
exit $?
fi
# Fetch adminer.
if ! logrun "Fetch adminer." \
"wget-fetch-adminer.log" \
wget "http://www.adminer.org/latest.php" -O ${DOCROOT}/adminer.php; then
exit $?
fi
chmod a+w ${DOCROOT}/sites/default;
chown -R www-data:${GRPID} ${DOCROOT}
chmod -R ug+w ${DOCROOT}
# Generate random passwords
DRUPAL_DB="drupal"
DEBPASS=$(grep password /etc/mysql/debian.cnf |head -n1|awk '{print $3}')
ROOT_PASSWORD=`pwgen -c -n -1 12`
MYSQL_PASSWORD=`pwgen -c -n -1 12`
echo ${ROOT_PASSWORD} > /var/lib/mysql/mysql/mysql-root-pw.txt
echo ${MYSQL_PASSWORD} > /var/lib/mysql/mysql/drupal-db-pw.txt
# Wait for mysql
if ! mysqladmin status >/dev/null 2>&1; then
echo -n "Waiting for mysql ." ; sleep 1;
while ! mysqladmin status >/dev/null 2>&1; do
echo -n .
sleep 1
done
echo
fi
# Create and change MySQL creds
mysqladmin -u root password ${ROOT_PASSWORD} 2>/dev/null
mysql -uroot -p${ROOT_PASSWORD} -e \
"GRANT ALL PRIVILEGES ON *.* TO 'debian-sys-maint'@'localhost' IDENTIFIED BY '$DEBPASS';" 2>/dev/null
mysql -uroot -p${ROOT_PASSWORD} -e \
"CREATE DATABASE drupal; GRANT ALL PRIVILEGES ON drupal.* TO 'drupal'@'%' IDENTIFIED BY '$MYSQL_PASSWORD'; FLUSH PRIVILEGES;" 2>/dev/null
cd ${DOCROOT}
cp sites/default/default.settings.php sites/default/settings.php
# Drush crashes w segfault if xdebug is on. Disable for cli.
rm -f /etc/php/7.2/cli/conf.d/20-xdebug.ini
# Site install.
if ! logrun "Running \`drush site-install\`." \
"drush-site-install.log" \
${DRUSH} site-install standard \
--account-name="${DEV_DRUPAL_ADMIN_USER}" \
--account-pass="${DEV_DRUPAL_ADMIN_PASSWORD}" \
--db-url="mysql://drupal:${MYSQL_PASSWORD}@localhost:3306/drupal" \
--site-name="${SITE_NAME}"; then
exit $?
fi
# Change root password
echo "root:${ROOT_PASSWORD}" | chpasswd
# Enabled themes
if [[ ! -z "${DEV_THEMES_ENABLED[*]}" ]]; then
for theme in ${DEV_THEMES_ENABLED[*]}; do
if ! logrun "Enable theme: ${theme}." \
"drush-theme-enable.log" ${DRUSH} theme-enable ${theme}; then
exit $?
fi
done
fi
# Set the site theme
if [[ ! -z ${DEV_PUBLIC_THEME} ]]; then
if ! logrun "Set primary site theme: ${DEV_PUBLIC_THEME[*]}." \
"drush-config-set-system-theme-default.log" \
${DRUSH} config-set system.theme default "${DEV_PUBLIC_THEME}"; then
exit $?
fi
fi
# Set the admin theme
if [[ ! -z ${DEV_ADMIN_THEME} ]]; then
if ! logrun "Set administration theme: ${DEV_ADMIN_THEME[*]}." \
"drush-config-set-system-theme-admin.log" \
${DRUSH} config-set system.theme admin "${DEV_ADMIN_THEME}"; then
exit $?
fi
fi
# Disabled themes
if [[ ! -z "${DEV_THEMES_DISABLED[*]}" ]]; then
for theme in ${DEV_THEMES_DISABLED[*]}; do
if ! logrun "Disable theme: ${theme}." \
"drush-theme-uninstall.log" ${DRUSH} theme-uninstall ${theme}; then
exit $?
fi
done
fi
# Enabled modules
if [[ ! -z "${DEV_MODULES_ENABLED[*]}" ]]; then
if ! logrun "Enable modules: ${DEV_MODULES_ENABLED[*]}." \
"drush-pm-enable.log" ${DRUSH} pm-enable ${DEV_MODULES_ENABLED[*]}; then
exit $?
fi
fi
# Disabled modules
if [[ ! -z "${DEV_MODULES_DISABLED[*]}" ]]; then
if ! logrun "Disable modules: ${DEV_MODULES_DISABLED[*]}." \
"drush-pm-uninstall.log" ${DRUSH} pm-uninstall ${DEV_MODULES_DISABLED[*]}; then
exit $?
fi
fi
# Import features configuration.
if ! logrun "Applying Features configuration." \
"drush-features-import-all.log" \
${DRUSH} features-import-all; then
exit $?
fi
# Reset files perms
chown -R www-data:${GRPID} ${DOCROOT}/sites/default/
chmod -R ug+w ${DOCROOT}/sites/default/
chown -R mysql:${GRPID} /var/lib/mysql/
chmod -R ug+w /var/lib/mysql/
# User post installation script.
[[ -f "/workspace/postinstall.sh" ]] && . /workspace/postinstall.sh "${ENVIRONMENT}"
# Wait a few then rebuild cache
sleep 3
if ! logrun "Cache rebuild." \
"drush-pm-config-set-system-theme-admin.log" \
${DRUSH} --root=${DOCROOT} cache-rebuild; then
exit $?
fi
# Credentials report
echo
echo "----------------------------------------------------------------------------------"
echo
echo " ${SITE_NAME} installation complete $(date)"
echo
echo " DRUPAL: http://localhost with user/pass: ${DEV_DRUPAL_ADMIN_USER}/${DEV_DRUPAL_ADMIN_PASSWORD}"
echo
echo " MYSQL : http://localhost/adminer.php database: drupal"
echo " user: drupal/${MYSQL_PASSWORD}"
echo
echo " SSH : ssh root@localhost user: root/${ROOT_PASSWORD}"
echo
echo " Please report any issues to https://github.com/dfletcher/drupal-devcontainer"
echo
echo "----------------------------------------------------------------------------------"
echo
|
Java
|
UTF-8
| 990
| 3.1875
| 3
|
[] |
no_license
|
package org.hardy.alegole;
/**
* 提供两个字符串的差距
* @author songshangkun
*
*/
public class DisdenceEdite {
//有问题的程序
public static int getLevenshteinDistance(String strA, String strB) {
int lenA = (int)strA.length();
int lenB = (int)strB.length();
int[][] c = new int[lenA+1][lenB+1];
// Record the distance of all begin points of each string
//初始化方式与背包问题有点不同
for(int i = 0; i < lenA; i++) c[i][lenB] = lenA - i;
for(int j = 0; j < lenB; j++) c[lenA][j] = lenB - j;
c[lenA][lenB] = 0;
for(int i = lenA-1; i >= 0; i--)
for(int j = lenB-1; j >= 0; j--)
{
char[] cB = strB.toCharArray();
char[] cA = strA.toCharArray();
if(cB[j] == cA[i])
c[i][j] = c[i+1][j+1];
else{
int temp = Math.min(c[i][j+1], c[i+1][j]);
c[i][j] = Math.min(temp, c[i+1][j+1])+1;
}
}
return c[0][0];
}
}
|
Go
|
UTF-8
| 477
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
package gpsutil
import (
"testing"
"math"
)
func TestToRad(t *testing.T) {
expected := math.Pi/2
result := toRad(90)
if result != expected {
t.Errorf("Expected '%v' but got '%v'", expected, result)
}
expected = math.Pi/4
result = toRad(45)
if result != expected {
t.Errorf("Expected '%v' but got '%v'", expected, result)
}
expected = math.Pi * 2
result = toRad(360)
if result != expected {
t.Errorf("Expected '%v' but got '%v'", expected, result)
}
}
|
Python
|
UTF-8
| 792
| 2.71875
| 3
|
[] |
no_license
|
# coding: utf-8
# In[64]:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import classification_report,confusion_matrix
# In[65]:
image = pd.read_csv('final.csv')
X=image.drop(image.columns[[0,314]], axis=1)
y=image[image.columns[314]]
# In[66]:
X_train, X_test, y_train, y_test = train_test_split(X, y)
# In[67]:
scaler = StandardScaler()
scaler.fit(X)
# In[68]:
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# In[93]:
mlp = MLPClassifier(hidden_layer_sizes=(13),max_iter=5000)
# In[94]:
mlp.fit(X_train,y_train)
# In[95]:
predictions = mlp.predict(X_test)
print(mlp.score(X_test,y_test));
|
Python
|
UTF-8
| 7,737
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python
from __future__ import division
import numpy
import os
from sklearn.cluster import DBSCAN, AgglomerativeClustering
def RMSD(traj, ref, idx):
'''
Returns RMSD between trajectory frames in mdtraj traj and reference frame in mdtraj ref object.
RMSD is computed for atom indices specified in idx.
'''
return numpy.sqrt(numpy.sum(numpy.square(traj.xyz[:,idx,:] - ref.xyz[:,idx,:]),axis=(1, 2))/len(idx))
def Cluster_Traj(distance_mat=None, eps=None, min_samples=None, metric= 'precomputed', use_algo='DBSCAN',
n_clusters=2, linkage='average' ):
'''
Clustering of input Distance matrix, for ex., RMSD_Matrix
'''
if use_algo.lower() == 'dbscan':
try:
assert eps != None and min_samples != None
except AssertionError:
raise ValueError('DBSCAN parameters eps and min_samples cannot be None.')
cluster_estimator = DBSCAN(eps=eps, min_samples=min_samples, metric=metric).fit(distance_mat)
elif use_algo.lower() == 'hierarchical':
cluster_estimator = AgglomerativeClustering(n_clusters=n_clusters, linkage=linkage, affinity=metric).fit(distance_mat)
cluster_labels = cluster_estimator.labels_
return cluster_labels
def Process_Clusters(traj, cluster_labels, align_index=None, rmsd_index=None, save_nFrames=100, beta=1.0, rmsd_unit_factor=10,save_format='xtc',save_path=''):
'''
Characterizes each cluster and saves sav_nFrames number of frames as separate traj file.
Input: traj-> mdtraj traj object
cluster_labels -> corresponding to each trajectory frame
dist_mat -> Distance matrix used in clustering
save_nFrames -> Number of trajectory frames o save for each cluster
'''
try:
assert align_index != None
except AssertionError:
raise ValueError('align_index cannot be None')
#If rmsd_index not defined, assign align_index to rmsd_index
if rmsd_index == None:
rmsd_index = align_index
print '-'*110
print('Total frames: %d\t Total Noise: %d\t Total Classified: %d\t # of Clusters: %d\n'
% (len(cluster_labels), len(cluster_labels[cluster_labels == -1]), len(cluster_labels)-len(cluster_labels[cluster_labels == -1]),
len(set(cluster_labels)) - (1 if -1 in cluster_labels else 0)))
print "Cluster_Label\tCluster_Size\tMax_RMSD_from_Centroid\tCluster_Spread (Avg. RMSD) Centroid_Frame_Id"
print '-'*110
for c_label in set(cluster_labels):
if c_label != -1: #Ignore noise
frame_indices = numpy.where(cluster_labels == c_label)[0]
#All Frames corresponding to this cluster from original trajectory
traj_cluster_frames = traj[frame_indices]
#Compute All pairwise RMSD required for cluster medoid calculation
rmsd_mat = numpy.empty((traj_cluster_frames.n_frames, traj_cluster_frames.n_frames))
for f_index in range(traj_cluster_frames.n_frames):
traj_cluster_frames.superpose(traj_cluster_frames[f_index], atom_indices = align_index)
rmsd_mat[f_index]= RMSD(traj_cluster_frames, traj_cluster_frames[f_index], rmsd_index)*rmsd_unit_factor
#Compute Similarity Score and return max(Similarity score) as medoid
medoid_index = numpy.exp(-beta*rmsd_mat / rmsd_mat.std()).sum(axis=1).argmax()
#medoid_index = 0
c_medoid = traj_cluster_frames[medoid_index]
c_spread = numpy.mean(rmsd_mat[medoid_index])
max_rmsd = numpy.max(rmsd_mat[medoid_index])
#Save Cluster centroid pdb
c_medoid.save(os.path.join(save_path, 'Cluster_'+str(c_label)+'_Centroid.pdb'))
print '%d\t\t%d\t\t%f\t\t%f\t\t\t%d' % (c_label, len(frame_indices), max_rmsd,c_spread, frame_indices[medoid_index])
#Superpose savenFrames cluster frames on centroid and save savenFrames cluster frames
if save_nFrames < len(frame_indices):
frame_indices = numpy.random.choice(frame_indices, size=save_nFrames, replace = False)
#Superpose cluster frames on Cluster centroid; Save Cluster centroid and cluster frames
save_cluster_frames = traj[frame_indices]
save_cluster_frames.superpose(c_medoid, atom_indices = align_index)
save_cluster_frames.save(os.path.join(save_path, 'Cluster_'+str(c_label)+'.'+save_format))
def cmdscale(distance_matrix):
'''
Classical multidimensional scaling (MDS)
Input-> distance_matrix : (N, N) array
Output-> Y : (N, P) array
Configuration matrix. Each column represents a dimension. Only the
p dimensions corresponding to positive eigenvalues of B are returned.
Note that each dimension is only determined up to an overall sign,
corresponding to a reflection.
e : (n,) array
Eigenvalues of B.
'''
# Number of points
n = len(distance_matrix)
# Centering matrix
H = numpy.eye(n) - numpy.ones((n, n))/n
# YY^T
B = -H.dot(distance_matrix**2).dot(H)/2
# Diagonalize
evals, evecs = numpy.linalg.eigh(B)
# Sort by eigenvalue in descending order
idx = numpy.argsort(evals)[::-1]
evals = evals[idx]
evecs = evecs[:,idx]
# Compute the coordinates using positive-eigenvalued components only
w, = numpy.where(evals > 0)
L = numpy.diag(numpy.sqrt(evals[w]))
V = evecs[:,w]
Y = V.dot(L)
return Y, evals
def tanimoto_dissimilarity(fingerprint_matrix, relative=None):
'''
Borrowed from Davide's HREX analysis code, modified a bit to cover the case
of all 0 fingerprints (commented out). Tanimoto distance between two fingerprints with all 0 bits
is set to 0.
'''
featuresum= numpy.sum(fingerprint_matrix, axis=1) # Number of on bits in each frame
'''
#Don't remember the logic behind this step but adding one doesn't seem right, so commenting it out
#Check if any of the fingerprint is all zeros, and set varibales accordingly
if not numpy.count_nonzero(featuresum) == featuresum.shape[0]: #Evaluates to True if there is a fingerprint with all 0 bits
eps_regularize = 0
add_one = 1
else:
eps_regularize = 1e-5
add_one = 0
'''
add_one = 0
eps_regularize= 1e-5
ab= numpy.dot(fingerprint_matrix, fingerprint_matrix.T)
a=numpy.repeat([featuresum],len(featuresum),axis=0)
b=a.T
r=1-(ab+add_one)/(a+b+add_one-ab+eps_regularize)
if relative:
s=r/(1-r+relative)
else:
s=r
if eps_regularize:
numpy.fill_diagonal(s, 0.0)
return s
|
PHP
|
UTF-8
| 3,701
| 2.5625
| 3
|
[] |
no_license
|
<?php
include('conection.php');
if(isset($_POST['submit'])){
try{
if(empty($_POST['username'])){
throw new Exception("User name field cannot be empty");
}
if(empty($_POST['password'])){
throw new Exception("Password field cannot be empty");
}
$result= mysqli_query($connection,"select * from tbl_student_l3t1 where id='$_POST[username]' and password='$_POST[password]'" );
$num= mysqli_num_rows($result);
if($num>0)
{
session_start();
$row=mysqli_fetch_assoc($result);
$_SESSION['name']="rafid";
$_SESSION['std_name']=$row['name'];
$_SESSION['id']=$row['id'];
$_SESSION['dept']=$row['dept'];
$_SESSION['level']=$row['level'];
$_SESSION['term']=$row['term'];
$_SESSION['gender']=$row['gender'];
$_SESSION['phone']=$row['phone'];
$_SESSION['password']=$row['password'];
$_SESSION['password']=$row['password'];
$_SESSION['cse_210']=$row['cse_301'];
$_SESSION['cse_211']=$row['cse_302'];
$_SESSION['cse_212']=$row['cse_303'];
$_SESSION['cse_213']=$row['cse_304'];
$_SESSION['cse_215']=$row['cse_305'];
$_SESSION['cse_216']=$row['cse_306'];
$_SESSION['cse_217']=$row['cse_307'];
$_SESSION['cse_220']=$row['cse_308'];
$_SESSION['math_247']=$row['cse_309'];
$_SESSION['cgpa']=$row['cgpa'];
header('location: student_profile.php');
}
else{
throw new Exception("Incorrect username or password");
}
}
catch(Exception $e){
$error=$e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<div>
<div class="header">
<div class="logo">
<img src="img/logo.gif">
</div>
<div class="name">
<h1>Bangladesh Army International University of Science & Technology</h1>
<p>Comilla Cantonment, Comilla.</p>
</div>
</div>
<div class="nav">
<ul>
<li><a href="student_login.php">Student Login</a></li>
<li><a href="admin_panel.php">Admin Panel</a></li>
</ul>
</div>
<div class="std">
<h1>Student login</h1>
</div>
<hr>
<?php
if(isset($error)){
echo $error;
}
?>
<div class="loginBox">
<br/>
<form action="" method="post">
<table>
<tr>
<td>Enter Username(id): </td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Enter Password: </td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="login"></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
|
Java
|
UTF-8
| 5,929
| 2.453125
| 2
|
[] |
no_license
|
package hacks.coachs_timer;
import android.app.Activity;
import android.content.Context;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* Created by Sam on 2/28/2016.
*/
public class TimerAdapter extends ArrayAdapter {
Context context;
int layoutResourceId;
Timer data[] = null;
public TimerAdapter(Context context, int layoutResourceId, Timer[] data) {
super(context, layoutResourceId, data);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
TimerHolder holder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new TimerHolder();
holder.name = (TextView)row.findViewById(R.id.name);
holder.splitNum = (TextView)row.findViewById(R.id.textView3);
holder.totalTime = (TextView)row.findViewById(R.id.totalTime);
holder.runningSplit = (TextView)row.findViewById(R.id.runningSplit);
holder.lastSplit = (TextView)row.findViewById(R.id.lastSplit);
holder.reset = (ImageButton)row.findViewById(R.id.resetButton);
holder.delete = (ImageButton)row.findViewById(R.id.deleteButton);
//TODO: Add button listeners
row.setTag(holder);
row.setOnTouchListener(new OnSwipeTouchListener(context) {
@Override
public void onSwipeRight() {
if(view != null) {
ListView lV = (ListView) view.getParent();
int position = lV.getPositionForView(view);
if(data[position].isRunning())
data[position].stop();
else
data[position].start(SystemClock.uptimeMillis());
}
System.out.println("Swipe right;): ");
}
@Override
public void onSwipeLeft() {
if(view != null) {
ListView lV = (ListView) view.getParent();
int position = lV.getPositionForView(view);
if (data[position].isRunning())
data[position].splitAction();
}
System.out.println("Swipe left)");
}
@Override
public void doubleTap() {
ImageButton resetButton = (ImageButton) view.findViewById(R.id.resetButton);
ImageButton deleteButton = (ImageButton) view.findViewById(R.id.deleteButton);
resetButton.setVisibility(View.VISIBLE);
deleteButton.setVisibility(View.VISIBLE);
resetButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout) v.getParent();
ListView lv = (ListView) ll.getParent();
int position = lv.getPositionForView(ll);
data[position].reset();
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LinearLayout ll = (LinearLayout) v.getParent();
ListView lv = (ListView) ll.getParent();
int position = lv.getPositionForView(ll);
data[position].setDelete();
}
});
System.out.println("Double Tap");
}
@Override
public void singleTap() {
ImageButton resetButton = (ImageButton) view.findViewById(R.id.resetButton);
ImageButton deleteButton = (ImageButton) view.findViewById(R.id.deleteButton);
resetButton.setVisibility(View.INVISIBLE);
deleteButton.setVisibility(View.INVISIBLE);
resetButton.setOnClickListener(null);
deleteButton.setOnClickListener(null);
System.out.println("Single Tap");
}
@Override
public void longPress() {
if(view != null) {
ListView lV = (ListView) view.getParent();
int position = lV.getPositionForView(view);
data[position].setExpand(true);
}
System.out.println("Long Press");
}
});
}
else {
holder = (TimerHolder)row.getTag();
}
Timer timer = data[position];
holder.name.setText(timer.getName());
holder.splitNum.setText(timer.getSplitNumber());
holder.totalTime.setText(timer.getTotalTime());
holder.runningSplit.setText(timer.getRunningSplit());
holder.lastSplit.setText(timer.getLastSplit());
return row;
}
public Timer[] getData(){
return data;
}
static class TimerHolder {
TextView name,splitNum,totalTime,runningSplit,lastSplit;
ImageButton reset,delete;
}
}
|
Markdown
|
UTF-8
| 1,748
| 2.65625
| 3
|
[] |
no_license
|
---
ID: 235
post_title: The .uk TLD has arrived
author: Andrew Coates
post_date: 2014-06-23 11:25:43
post_excerpt: ""
layout: post
permalink: >
https://dev.mikamai.com/2014/06/23/the-uk-tld-has-arrived/
published: true
tumblr_mikamayhem_permalink:
- >
http://dev.mikamai.com/post/89647283094/the-uk-tld-has-arrived
tumblr_mikamayhem_id:
- "89647283094"
---
<p>At 8:00am on June 10th, registrars began to allow the registration of the .uk TLD for all. Previously, .co.uk and .org.uk were the most common used, and .uk was reserved mostly for government usage, such as <a href="http://police.uk">police.uk</a> or <a href="http://gov.uk">gov.uk</a>.
<br /><br />
In order to prevent domain-squatting, <a href="http://www.nominet.org.uk">Nominet</a>, the registry behind the .uk domain reserved all .uk domains that had an existing .co.uk counterpart until 2019. However, this still means that you need to pay for a new .uk domain if you own an existing .co.uk site.
<br /><br />
The release of the domain has not been met with great enthusiasm. Low demand, increased consumer confusion, the devaluation of the .co.uk domain, and the fact that businesses are being pressured to move from the .co.uk domain through an increase of costs, create the perception that this move by Nominet is simply a 5-year-late money grab.
<br /><br />
To purchase a .uk domain, I recommend using a third party registrar rather than Nominet such as <a href="http://namecheap.com">namecheap</a> or <a href="http://www.gandi.net">Gandi</a> as these are both cheaper and faster.
<br /><br />
With the exclusion of “.co”, comes the opportunity for more creative domains, check out <a href="http://dumb.domains">http://dumb.domains</a> for some inspiration.</p>
|
TypeScript
|
UTF-8
| 2,109
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
import { CoreQuadOperation } from "../../tree/core/CoreQuadOperation";
import { CoreContext } from "../../tree/core/CoreContext";
import { ElementCore } from "../../tree/core/ElementCore";
import { RenderTextureInfo } from "../../tree/core/RenderTextureInfo";
import { WebGLCoreRenderExecutor } from "./WebGLCoreRenderExecutor";
import { WebGLShader } from "./WebGLShader";
import { WebGLCoreQuadList } from "./WebGLCoreQuadList";
import { WebGLRenderTexture } from "./WebGLRenderTexture";
export class WebGLCoreQuadOperation extends CoreQuadOperation {
extraAttribsDataByteOffset: number;
constructor(
context: CoreContext,
shader: WebGLShader,
shaderOwner: ElementCore,
renderTextureInfo: RenderTextureInfo,
scissor: number[] | undefined,
index: number,
) {
super(context, shader, shaderOwner, renderTextureInfo, scissor, index);
this.extraAttribsDataByteOffset = 0;
}
get quadList(): WebGLCoreQuadList {
return super.quadList as WebGLCoreQuadList;
}
getWebGLShader(): WebGLShader {
return this.shader as WebGLShader;
}
getAttribsDataByteOffset(index: number) {
// Where this quad can be found in the attribs buffer.
return (this.quadList as WebGLCoreQuadList).getAttribsDataByteOffset(this.index + index);
}
// Returns the relative pixel coordinates in the shader owner to gl position coordinates in the render texture.
getNormalRenderTextureCoords(x: number, y: number) {
const coords = this.shaderOwner.getRenderTextureCoords(x, y);
coords[0] /= this.getRenderWidth();
coords[1] /= this.getRenderHeight();
coords[0] = coords[0] * 2 - 1;
coords[1] = 1 - coords[1] * 2;
return coords;
}
getProjection() {
if (this.renderTextureInfo && this.renderTextureInfo.renderTexture) {
return (this.renderTextureInfo.renderTexture as WebGLRenderTexture).projection;
} else {
return (this.context.renderExecutor as WebGLCoreRenderExecutor).projection;
}
}
}
|
Java
|
UTF-8
| 5,214
| 2.109375
| 2
|
[] |
no_license
|
package com.binroot.gpa;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import misc.Constants;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
public class HomeworkActivity extends Activity {
String period = null;
GridView g;
GridAdapter ga;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homework);
Bundle extras = this.getIntent().getExtras();
if(extras!=null) {
period = extras.getString("period");
}
// TODO: storage init
g = (GridView) findViewById(R.id.grid_hw);
storageInit();
} // end onCreate
public void storageInit() {
FileInputStream fis = null;
try {
fis = openFileInput(Constants.File_TranscriptList);
} catch (FileNotFoundException e) {
Log.d(getString(R.string.app_name), "Could not find file "+Constants.File_TranscriptList);
}
if(fis == null) { // File doesn't exist. Must be a new user.
// TODO: Error message
}
else {
StringBuilder total = null;
try {
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
//fis.read(buf);
//bis.read(buf);
} catch (IOException e) {
Log.d(getString(R.string.app_name), "Could not read buffer "+Constants.File_TranscriptList);
}
String transcriptJSONStr = total.toString();
Log.d(getString(R.string.app_name), "json from file: "+transcriptJSONStr);
JSONObject jMain = null;
try {
jMain = new JSONObject(transcriptJSONStr);
} catch (JSONException e) {
Log.d(getString(R.string.app_name), "not proper JSON: "+transcriptJSONStr);
}
ArrayList<String> classes = new ArrayList<String>();
try {
JSONArray jClasses = jMain.getJSONArray(period);
for(int i=0; i<jClasses.length(); i++) {
String title = jClasses.getJSONObject(i).getString("title");
classes.add(title);
}
} catch (JSONException e) {
e.printStackTrace();
}
ga = new GridAdapter(classes);
g.setAdapter(ga);
g.setOnItemClickListener(ga);
}
}
public void optionClicked(View v) {
int classSize = ga.getCount();
final int randomItem = (int)(Math.random()*classSize);
Toast.makeText(HomeworkActivity.this, "Randomly choosing class", Toast.LENGTH_SHORT).show();
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
public void run() {
String title = ga.getItem(randomItem);
Intent i = new Intent(HomeworkActivity.this, TodoActivity.class);
i.putExtra("title", title);
i.putExtra("period", period);
startActivity(i);
}
}, 500);
}
public class GridAdapter extends BaseAdapter implements OnItemClickListener{
ArrayList<String> classes;
public GridAdapter(ArrayList<String> classes) {
this.classes = classes;
}
public int getCount() {
return classes.size();
}
public String getItem(int position) {
return classes.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v==null) {
v = getLayoutInflater().inflate(R.layout.class_grid_item, null);
}
String title = classes.get(position);
((TextView) v.findViewById(R.id.text_hw_grid_class)).setText(title);
RelativeLayout rl = (RelativeLayout)v.findViewById(R.id.relative_grid_class);
int randCol = getHashColor(title);
//int col = -1*Integer.parseInt(color, 16);
Log.d(getString(R.string.app_name),"color: ");
rl.setBackgroundColor(randCol);
return v;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
String title = getItem(pos);
Intent i = new Intent(HomeworkActivity.this, TodoActivity.class);
i.putExtra("title", title);
i.putExtra("period", period);
startActivity(i);
}
}
public int getHashColor(String str) {
String hashStr = str.hashCode()+"";
hashStr += hashStr + hashStr + hashStr + hashStr + hashStr;
String red = hashStr.substring(1, 3);
String green = hashStr.substring(2, 4);
String blue = hashStr.substring(4, 6);
String blueStr = "ff"+red+green+blue;
long n = Long.parseLong(blueStr, 16);
int nn = (int) n;
return nn;
}
public void logoClicked(View v) {
HomeworkActivity.this.finish();
}
}
|
Java
|
UTF-8
| 772
| 2.140625
| 2
|
[] |
no_license
|
package be.sansoft.axondemo.accounts.view.projection.details;
import be.sansoft.axondemo.accounts.view.projection.json.JpaAccountDetailsJsonConverter;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
/**
* @author kristofennekens
*/
@Entity
@Table(name = "account_details")
public class AccountDetailsEntity {
@Id
private String id;
@Getter
@Setter
@Column(name = "data", columnDefinition = "text")
@Convert(converter = JpaAccountDetailsJsonConverter.class)
private AccountDetails data;
public static AccountDetailsEntity of(String id, AccountDetails data) {
AccountDetailsEntity entity = new AccountDetailsEntity();
entity.id = id;
entity.data = data;
return entity;
}
}
|
Rust
|
UTF-8
| 766
| 3.46875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum DayOfWeek {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
impl fmt::Debug for DayOfWeek {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Self::Sunday => "Sunday",
Self::Monday => "Monday",
Self::Tuesday => "Tuesday",
Self::Wednesday => "Wednesday",
Self::Thursday => "Thursday",
Self::Friday => "Friday",
Self::Saturday => "Saturday",
};
write!(f, "{}", s)
}
}
impl fmt::Display for DayOfWeek {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
|
PHP
|
UTF-8
| 438
| 2.90625
| 3
|
[] |
no_license
|
<?php
namespace Sepbin\System\Util\Data;
class GUID
{
public static function create() {
$charid = strtolower(md5(uniqid(mt_rand(), true)));
$hyphen = chr(45);// "-"
$uuid = substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12);
return $uuid;
}
}
|
Java
|
UTF-8
| 152
| 2.484375
| 2
|
[] |
no_license
|
public class ToItemException extends Exception {
@Override
public String getMessage() {
return "To-Do item is illegal";
}
}
|
Markdown
|
UTF-8
| 1,649
| 2.921875
| 3
|
[] |
no_license
|
# Cloud Maturity Assessment Survey Tool
An Office Excel based tool that can used by
- Organizations adopting a Cloud Platform, or
- by ISV Vendors that provide Cloud based Solutions to their Customers
to assess how they are utilising the Cloud Platform today and the state that they aspire to be in, in the future.
## How to use the Tool
Download the tool from this Repo.
The Excel file has a 'Readme' sheet that explains how it needs to be used. See the image below
<img src="./images/Readme.PNG" alt="drawing" height="500px"/>
Respond to the Survey questions by selecting the options that represents the 'current' state and a Target 'To-be' State
* :boom: The Maturity Assessment rating and the Survey questions are not based on any industry Standard or benchmark. It is meant to be used as a self-assessment tool.
## Viewing the 'Assessment' Sheet
Once the Survey is responded to, the 'Assessment' Sheet gets populated with a Spider Chart that graphically represents the current and Target State, across different areas. It gives a bird's eye view of where the gaps are, and identify actions that can lead to filling those gaps. In the 'Comments' section in the sheet, a stakeholder could capture comments and details on the corrective actions required to address the gaps.
<img src="./images/Assessment.PNG" alt="drawing" height="500px"/>
## Viewing the 'FollowupActions' Sheet
Based on the Survey response, and the values selected for the 'As-is' and 'To-be' state, certain recommended actions are automatically populated that can help fill the gaps.
<img src="./images/FollowupActions.PNG" alt="drawing" height="500px"/>
|
C++
|
UTF-8
| 1,395
| 2.8125
| 3
|
[] |
no_license
|
/** A wrapper class for dealing with ESCs.
* Comes with calibration function.
*/
#ifndef H_DRONE_ESC
#define H_DRONE_ESC
#define SERVO_OUTPUT_MAX 1000
#define SERVO_OUTPUT_MIN 2000
#define INTENSITY_MAX 1.0
#define INTENSITY_MIN 0.0
#define CALI_MAX_DURATION 2000
#define CALI_MIN_DURATION 2000
#define CALI_GRAD_DURATION 2000
#include <Servo.h>
#include "common.h"
class DroneESC {
private:
static const int16_t ESC_NW = 0;
static const int16_t ESC_NE = 1;
static const int16_t ESC_SE = 2;
static const int16_t ESC_SW = 3;
Servo escs[4];
int16_t pins[4];
double intensities[4];
static int intensity_to_servo(double intensity);
void apply_intensities();
void apply_intensity(int16_t direction);
public:
DroneESC(int16_t pin_nw, int16_t pin_ne, int16_t pin_se, int16_t pin_sw);
void set_intensities(double intensity);
void set_intensity(int16_t direction, double intensity);
void set_max_intensities();
void set_min_intensities();
void set_max_intensity(int16_t direction);
void set_min_intensities(int16_t direction);
void change_intensity(int16_t direction, double pcn);
void change_intensities(double pcn);
void set_intensity_linear(int16_t direction, double intensity_before, double intensity_after, int duration);
void set_intensities_linear(double intensity_before, double intensity_after, int duration);
void initialize();
void calibrate();
};
#endif
|
Python
|
UTF-8
| 1,228
| 3.578125
| 4
|
[] |
no_license
|
class NumArray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.nums = nums
self.len = len(nums)
if self.len >0:
self.partsum =[nums[0]]
for i in range(1,self.len):
self.partsum.append(self.partsum[i-1]+nums[i])
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
if self.len== 0:
return 0
if i > j :
return 0
if i == j and i > -1 and i < self.len:
return self.nums[i]
newI = i
if i >= self.len:
return 0
if i < 0:
newI = 0
newJ = j
if j > self.len-1:
newJ = self.len-1
if newI == 0:
return self.partsum[newJ]
return self.partsum[newJ] - self.partsum[newI-1]
# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
# numArray.sumRange(0, 1)
# numArray.sumRange(1, 2)
if __name__ == '__main__':
so = NumArray([1,2,3,4,5,6,7])
print(so.sumRange(1,-21))
|
Java
|
UTF-8
| 2,914
| 2.3125
| 2
|
[] |
no_license
|
package com.example.xeus_labmacbook.growup.model;
import com.google.gson.annotations.SerializedName;
public class DataItem{
@SerializedName("temp_stat")
private String tempStat;
@SerializedName("airhumid_value")
private String airhumidValue;
@SerializedName("waterlvl_value")
private String waterlvlValue;
@SerializedName("pot_id")
private String potId;
@SerializedName("user_id")
private String userId;
@SerializedName("values_timestamp")
private String valuesTimestamp;
@SerializedName("airhumid_stat")
private String airhumidStat;
@SerializedName("temp_value")
private String tempValue;
@SerializedName("soil_value")
private String soilValue;
@SerializedName("soil_stat")
private String soilStat;
@SerializedName("waterlvl_stat")
private String waterlvlStat;
public void setTempStat(String tempStat){
this.tempStat = tempStat;
}
public String getTempStat(){
return tempStat;
}
public void setAirhumidValue(String airhumidValue){
this.airhumidValue = airhumidValue;
}
public String getAirhumidValue(){
return airhumidValue;
}
public void setWaterlvlValue(String waterlvlValue){
this.waterlvlValue = waterlvlValue;
}
public String getWaterlvlValue(){
return waterlvlValue;
}
public void setPotId(String potId){
this.potId = potId;
}
public String getPotId(){
return potId;
}
public void setUserId(String userId){
this.userId = userId;
}
public String getUserId(){
return userId;
}
public void setValuesTimestamp(String valuesTimestamp){
this.valuesTimestamp = valuesTimestamp;
}
public String getValuesTimestamp(){
return valuesTimestamp;
}
public void setAirhumidStat(String airhumidStat){
this.airhumidStat = airhumidStat;
}
public String getAirhumidStat(){
return airhumidStat;
}
public void setTempValue(String tempValue){
this.tempValue = tempValue;
}
public String getTempValue(){
return tempValue;
}
public void setSoilValue(String soilValue){
this.soilValue = soilValue;
}
public String getSoilValue(){
return soilValue;
}
public void setSoilStat(String soilStat){
this.soilStat = soilStat;
}
public String getSoilStat(){
return soilStat;
}
public void setWaterlvlStat(String waterlvlStat){
this.waterlvlStat = waterlvlStat;
}
public String getWaterlvlStat(){
return waterlvlStat;
}
@Override
public String toString(){
return
"DataItem{" +
"temp_stat = '" + tempStat + '\'' +
",airhumid_value = '" + airhumidValue + '\'' +
",waterlvl_value = '" + waterlvlValue + '\'' +
",pot_id = '" + potId + '\'' +
",user_id = '" + userId + '\'' +
",values_timestamp = '" + valuesTimestamp + '\'' +
",airhumid_stat = '" + airhumidStat + '\'' +
",temp_value = '" + tempValue + '\'' +
",soil_value = '" + soilValue + '\'' +
",soil_stat = '" + soilStat + '\'' +
",waterlvl_stat = '" + waterlvlStat + '\'' +
"}";
}
}
|
C++
|
UTF-8
| 643
| 3.546875
| 4
|
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
bool isPossible(vector<int> &piles, int h, int k) {
int total = 0;
for (auto pile: piles) {
total += ceil(pile * 1.0 / k);
}
return total <= h;
}
int minEatingSpeed(vector<int> piles, int h)
{
int lo = 1, hi = *max_element(piles.begin(), piles.end());
while (lo < hi) {
int k = lo + (hi - lo) / 2;
if (!isPossible(piles, h, k))
lo = k + 1;
else
hi = k;
}
return lo;
}
int main()
{
cout << minEatingSpeed({3,6,7,11}, 8) << "\n";
cout << minEatingSpeed({30,11,23,4,20}, 6) << "\n";
return 0;
}
|
Java
|
UTF-8
| 285
| 2.59375
| 3
|
[] |
no_license
|
package wzorzec_dekorator.example_1.składniki;
import wzorzec_dekorator.example_1.Pizza;
public class FungiPizza implements Pizza {
@Override
public String getName() {
return "Fungi";
}
@Override
public float getCost() {
return 20.50f;
}
}
|
Java
|
UTF-8
| 966
| 3.140625
| 3
|
[] |
no_license
|
package ConsoleBars;
import java.util.*;
import java.io.*;
class ConsoleBar implements Observer {
static enum Opcode {
INC, DEC, BELL
}
static class Command {
Opcode op;
Command(Opcode op) {
this.op = op;
}
}
int cmax;
ValueBar model;
static final char BLOCK = 0x2588; // ASCII Character
ConsoleBar(ValueBar value) {
model = value;
// get max columns
cmax = Toolkit.TerminalWidth.getColumns();
model.setMax(cmax);
}
int getMax() {
return cmax;
}
public void update(Observable o, Object arg) {
Command comm = (Command) arg;
switch (comm.op) {
case INC:
System.out.print(BLOCK);
break;
case DEC:
// delete char to the left
System.out.print(Const.BACKWARD);
System.out.print(Const.DELETECHAR);
break;
case BELL:
System.out.print('\007');
break;
}
}
}
|
C++
|
WINDOWS-1250
| 932
| 2.5625
| 3
|
[] |
no_license
|
//Este proyecto utiliza una clase llamada Img creada por Manuel Jess Zavala Nez
//Esta clase engloba a la clase de OpenCV Mat para hacer ms sencilla la implementacin de sus funciones
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "Img.h"
#include <iostream>
#include <stdlib.h>
Mat imagethreeshold;
Mat imagethreeshold2;
Img img;
int main(int argc, char** argv) {
Mat image;
image = imread("images/Fig0940(a)(rice_image_with_intensity_gradient).tif", CV_LOAD_IMAGE_GRAYSCALE);
img.setMat(image);
img.Show("a) Original");
img.setMat(img.thresHold());
img.Show("b)thresholded image");
img.setMat(image);
img.setMat(img.MorphologicFcn(2, 30));
img.Show("c)image opened");
img.setMat(image);
img.setMat(img.MorphologicFcn(5, 20));
img.Show("d) top hat transformation");
img.setMat(img.thresHold());
img.Show("e) top hat threshold");
waitKey(0);
return 0;
}
|
TypeScript
|
UTF-8
| 454
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
import { BotEvent } from "../types/types";
const event: BotEvent = {
name: 'Ready',
description: 'Evento chamado quando o Bot inicia',
caller: 'ready',
enable: true,
run: (Bot) => {
Bot.startTime = Date.now(); // Salvar timestamp do horario que o bot iniciou
console.log(`Bot iniciado com ${Bot.users.cache.size} usuários, ${Bot.channels.cache.size} canais e ${Bot.guilds.cache.size} servidores!`);
},
};
export default event;
|
C#
|
UTF-8
| 2,872
| 2.9375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WeatherGroup2.Models;
namespace WeatherGroup2.Controllers
{
public class WeatherHTTPClientController : Controller
{
public string apiKey = "fc4dbbf2a03c3f80f8366cbb3c15c421";
public HttpClient client;
public WeatherHTTPClientController()
{
client = new HttpClient() { BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/") };
}
public WeatherDetails2 GetByCityToday(string cityId)
{
var serializer = new DataContractJsonSerializer(typeof(WeatherDetails2));
// var response = client.GetAsync($"weather?q={cityName}&appid={apiKey}").Result;
var response = client.GetAsync($"weather?id={cityId}&appid={apiKey}").Result;
var responseStream = response.Content.ReadAsStreamAsync().Result;
var weatherResult = (WeatherDetails2)serializer.ReadObject(responseStream);
return weatherResult;
}
public WeatherData GetByCityForecast(string cityId)
{
var serializer = new DataContractJsonSerializer(typeof(WeatherData));
var response = client.GetAsync($"forecast?id={cityId}&appid={apiKey}").Result;
var responseStream = response.Content.ReadAsStreamAsync().Result;
var weatherResult = (WeatherData)serializer.ReadObject(responseStream);
var testSplitDays = weatherResult.DetailedInformation.Select(x => x.Date.Day).Distinct().ToList();
var returnListOfFirstResultOfDay = new List<WeatherDetails2>();
foreach (var testSplitDay in testSplitDays)
{
var testGetSplitDays = weatherResult.DetailedInformation.FirstOrDefault(x => x.Date.Day == testSplitDay);
returnListOfFirstResultOfDay.Add(testGetSplitDays);
}
return weatherResult;
}
public WeatherSearch GetSearchResultsGetByQuery(string query)
{
var serializer = new DataContractJsonSerializer(typeof(WeatherSearch));
var response = client.GetAsync($"find?q={query}&type=like&appid={apiKey}").Result;
var responseStream = response.Content.ReadAsStreamAsync().Result;
var searchResult = (WeatherSearch)serializer.ReadObject(responseStream);
//Istället för att bara få platsnamn och land så får man tillbaka ikoner/väder just nu... tog med det för tillfället
//eftersom det är så lätt att göra resultaten lite snyggare
return searchResult;
//Får lista av de olika matchningar, vi vill ha Platsnamn/Id till platser som vi sedan kan skicka in i GetByCity() metoden.
}
}
}
|
Python
|
UTF-8
| 1,984
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
# ***************************************************************************************
# ***************************************************************************************
#
# Name : makedictionary.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 8th November 2018
# Purpose : Create initial dictionary from kernel.lst
#
# ***************************************************************************************
# ***************************************************************************************
import re
from imagelib import *
image = MZImage()
#
# Read in all the __mzdefine(*) labels
#
labels = {}
for l in [x.lower().strip() for x in open("boot.img.vice").readlines() if x.find("__MZDEFINE") > 0]:
m = re.match("^al\s*c\:\s*([0-9a-f]+) ___mzdefine_([0-9a-fnd_]+)$",l)
assert m is not None,l+" syntax"
assert m.group(2) not in labels,l+" duplicate"
labels[m.group(2)] = int(m.group(1),16)
#
# Sort them by address
#
keys = [x for x in labels.keys()]
keys.sort(key = lambda x:labels[x])
#
# For each key (that's not a macro end)
#
for l in keys:
if l[-4:] != "_end":
#
# Analyse it
#
word = "".join([chr(int(x,16)) for x in l.split("_")])
isProtected = False
if word[-1] == "p":
isProtected = True
word = word[:-1]
wType = word[-1]
assert wType == "m" or wType == "w"
wName = word[:-3]
#print(wType,wName,labels[l])
#
# Add to the physical dictionary in the image
#
image.addDictionary(wName,image.currentCodePage(),labels[l])
#
# Special case. Initially only 'compile' and 'execute' are immediate words.
#
if wName == "compile" or wName == "execute":
image.xorLastTypeByte(15)
#
# Set the type byte for macros to the macro length
#
if wType == "m":
size = labels[l+"_end"]-labels[l]
assert size <= 6,"Macro size for "+wName+ "??"
image.xorLastTypeByte(size)
#
# Set protected flag if wanted
#
if isProtected:
image.xorLastTypeByte(0x40)
#
# Write the image out.
#
image.save()
|
Markdown
|
UTF-8
| 941
| 2.84375
| 3
|
[] |
no_license
|
# Article 58
Les établissements fournissent au minimum les informations suivantes au sujet des espèces présentées :
- nom scientifique ;
- nom vernaculaire ;
- éléments permettant d'appréhender la position de l'espèce dans la classification zoologique ;
- répartition géographique ;
- éléments remarquables de la biologie et écologie de l'espèce dans son milieu naturel ;
ainsi que, le cas échéant :
- statut de protection de l'espèce ;
- menaces pesant sur la conservation de l'espèce ;
- actions entreprises en vue de la conservation de l'espèce.
Dans le cas des présentations de nombreuses espèces illustrant un même biotope ou dédiées au développement d'un thème biologique spécifique, la totalité des informations peut n'être fournie que pour les espèces les plus représentatives, les informations concernant les autres espèces pouvant être limitées aux noms scientifiques et vernaculaires.
|
Java
|
UTF-8
| 1,167
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* <p>Copyright (R) 2014 我是大牛软件股份有限公司。<p>
*/
package com.woshidaniu.drdcsj.drsj.handler.impl;
import java.util.List;
import com.woshidaniu.drdcsj.drsj.comm.ImportConfig;
import com.woshidaniu.drdcsj.drsj.dao.entities.DrlpzModel;
import com.woshidaniu.drdcsj.drsj.handler.AbstractHandler;
import com.woshidaniu.drdcsj.drsj.handler.HandlerContext;
import com.woshidaniu.drdcsj.drsj.handler.excel.ExcelCell;
import com.woshidaniu.drdcsj.drsj.handler.excel.ExcelRow;
/**
* @author 康康(1571)
* 主键收集验证器,先收集主键列,然后开始验证主键
* 这个应该放到 验证主键 的验证器前面
*/
/**public**/ final class PrimaryKeyExcelCollectorHandler extends AbstractHandler{
@Override
protected boolean accept(final HandlerContext context,final ExcelRow currentRow,final List<ExcelRow> allRows) {
List<ExcelCell> cells = currentRow.getCells();
for(ExcelCell cell : cells) {
DrlpzModel drlpz = cell.getDrlpzModel();
String sfzj = drlpz.getSfzj();
if(ImportConfig._SFZJ_YES.equals(sfzj)) {
currentRow.getPrimaryKeys().add(cell);
}
}
//始终返回true
return true;
}
}
|
C++
|
GB18030
| 4,975
| 2.859375
| 3
|
[] |
no_license
|
#include "cutPhoto.h"
cuttingPhotos* cuttingPhotos::create(const char* photo,unsigned int rows,unsigned int columns)
{
cuttingPhotos *cp=new cuttingPhotos();
if (cp && cp->initWithPhoto(photo,rows,columns)) {
cp->autorelease();
return cp;
}
CC_SAFE_DELETE(cp);
return nullptr;
}
bool cuttingPhotos::initWithPhoto(const char* photo,unsigned int rows,unsigned int columns)
{
bool result;//ʼǷɹ
if (Layer::init()) {
_rows=rows;
_columns=columns;
if (initSlice(photo)) {
initTouchEventlistener();
restart();
result=true;
}else{
result=false;
}
}else{
result =false;
}
return result;
}
bool cuttingPhotos::initSlice(const char* photo)
{
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(photo);
if (texture==nullptr) {
return false;
}
//ʼ洢еб
for (int w=0; w<_rows; ++w) {
std::vector<Sprite*> row;
for (int h=0; h<_columns; ++h) {
row.push_back(nullptr);
}
_slices.push_back(row);
}
//ͼƬÿеĿ
auto size=texture->getContentSize();
_sliceWidth=size.width/_rows;
_sliceHeight=size.height/_columns;
this->setContentSize(size);//LayerС
//һ
auto endSlice=Sprite::createWithTexture(texture,Rect(_sliceWidth*(_rows-1),_sliceHeight*(_columns-1),_sliceWidth,_sliceHeight));
endSlice->setAnchorPoint(Vec2(0,0));
endSlice->setPosition((_rows-1)*_sliceWidth,0);
endSlice->setOpacity(100);//
this->addChild(endSlice);
//Ϊգʾ
_slices[_rows-1][_columns-1] = nullptr;
//Ƭ
for(int w = 0; w < _rows;w++){
for(int h = 0; h < _columns; h++){
if(w == _rows - 1 && h == _columns - 1){
break;
}
Sprite* slice = Sprite::createWithTexture(texture,Rect(_sliceWidth*w,_sliceHeight*h,_sliceWidth,_sliceHeight));
slice->setAnchorPoint(Vec2(0,0));
slice->setPosition(w*_sliceWidth,size.height-(h+1)*_sliceHeight);
this->addChild(slice);
_slices[w][h] = slice;
}
}
return true;
}
void cuttingPhotos::initTouchEventlistener()
{
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [&](Touch *touch,Event *event){
Point locationInNode = this->convertToNodeSpace(touch->getLocation());
Size s = this->getContentSize();
Rect rect = Rect(0,0,s.width,s.height);
if(rect.containsPoint(locationInNode)){
return true;
}else{ return false;}
};
listener->onTouchEnded = [&](Touch *touch,Event *event){
Point locationInNode = this->convertToNodeSpace(touch->getLocation());
//ĸͼ
int x = static_cast<int>(floor(locationInNode.x/this->_sliceWidth));
int y = static_cast<int>(floor(locationInNode.y/this->_sliceHeight));
this->move(x,y);
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);
}
void cuttingPhotos::move(int x , int y)
{
y = _columns - y - 1;
auto slice = _slices[x][y];
if(slice == nullptr){
return;
}
//ΧǷпհ
bool isFind = false;
Point targetPos;
if(y < _columns - 1 && _slices[x][y+1] == nullptr){
targetPos.x = x;
targetPos.y = y+1;
isFind = true;
}else if (y>0 && _slices[x][y-1]==nullptr) {
targetPos.x=x;
targetPos.y=y-1;
isFind=true;
}else if (x<_rows-1 && _slices[x+1][y]==nullptr) {
targetPos.x=x+1;
targetPos.y=y;
isFind=true;
}else if (x>0 && _slices[x-1][y]==nullptr) {
targetPos.x=x-1;
targetPos.y=y;
isFind=true;
}
if (isFind==false) {
return;
}
slice->runAction(MoveTo::create(0.25, Vec2(targetPos.x*_sliceWidth,_sliceHeight*_columns-(targetPos.y+1)*_sliceHeight)));
_slices[targetPos.x][targetPos.y]=slice;
_slices[x][y]=nullptr;
}
void cuttingPhotos::restart()
{
Vector<Sprite*> list;
//ȡƬ
for(int w = 0; w < _rows; w++){
for (int h=0; h<_columns; ++h) {
auto slice = _slices[w][h];
if(slice!=nullptr){
list.pushBack(slice);
}
}
}
//õÿһλ
for (int w=0; w<_rows; ++w) {
for (int h=0; h<_columns; ++h) {
if (w==_rows-1 && h==_columns-1) {
//һ鲻Ҫ
_slices[w][h]=nullptr;
break;
}
auto length= list.size();
auto value= static_cast<int>(CCRANDOM_0_1()*length);
auto slice=list.at(value);
list.eraseObject(slice);
_slices[w][h]=slice;
slice->setPosition(w*_sliceWidth,_sliceHeight*_columns-(h+1)*_sliceHeight);
}
}
}
|
Markdown
|
UTF-8
| 1,850
| 2.640625
| 3
|
[] |
no_license
|
#### 仿京东地址选择器
##### 用法
Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
```javascript
allprojects {
repositories{
maven { url 'https://jitpack.io' }
}
}
```
Step 2. Add the dependency
```
dependencies {
implementation 'com.github.paomian2:AddressPicker:v1.0.0'
}
```
Step 3.Use in code
```
AddressPickerSimpleActivity.launch(this@MainActivity)
```
eg:
```
class MainActivity : AppCompatActivity() {
private var tvAddress: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tvAddress=findViewById(R.id.tvAddress)
findViewById<Button>(R.id.btnAddress).setOnClickListener {
AddressPickerSimpleActivity.launch(this@MainActivity)
}
}
@SuppressLint("SetTextI18n")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode==AddressPickerSimpleActivity.REQUEST_CODE && resultCode== Activity.RESULT_OK){
val province=data?.getSerializableExtra("province") as AddressListBean?
val city= data?.getSerializableExtra("city") as AddressListBean?
val country= data?.getSerializableExtra("country") as AddressListBean?
val street= data?.getSerializableExtra("street") as AddressListBean?
Toast.makeText(this@MainActivity,province?.name+city?.name+country?.name+street?.name,Toast.LENGTH_SHORT).show()
tvAddress?.text = province?.name+city?.name+country?.name+street?.name
}
}
}
```
效果图

|
C++
|
UTF-8
| 496
| 2.84375
| 3
|
[] |
no_license
|
#include"BasicData.h"
float cPOINTF::GetDistance(cPOINTF & s)
{
return sqrt((x - s.x)*(x - s.x) + (y - s.y)*(y - s.y));
}
float cPOINTF::GetAngle(cPOINTF & d)
{
if (fabs(d.x - x)<1e-6)
{
if (d.y<y)
{
return 270;
}
else
{
return 90;
}
}
float a = atan((d.y - y) / (d.x - x)) / 3.1415926 * 180;
if (d.x<x)
{
a += 180;
}
return a;
}
BOOL RestrictInBoundary(RECT r)
{
RECT ir;
RECT boundary = {0,0,CLIENTWIDTH,CLIENTHEIGHT};
return IntersectRect(&ir,&boundary,&r);
}
|
Java
|
UTF-8
| 1,386
| 2.234375
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
package org.apereo.cas.support.inwebo.authentication;
import org.apereo.cas.authentication.AuthenticationBuilder;
import org.apereo.cas.authentication.AuthenticationTransaction;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.metadata.BaseAuthenticationMetaDataPopulator;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.val;
/**
* The Inwebo metadata populator which adds the authentication device as an authentication attribute.
*
* @author Jerome LELEU
* @since 6.4.0
*/
@ToString(callSuper = true)
@RequiredArgsConstructor
public class InweboAuthenticationDeviceMetadataPopulator extends BaseAuthenticationMetaDataPopulator {
/**
* Authentication attribute to capture device name.
*/
public static final String ATTRIBUTE_NAME_INWEBO_AUTHENTICATION_DEVICE = "inweboAuthenticationDevice";
@Override
public void populateAttributes(final AuthenticationBuilder builder, final AuthenticationTransaction transaction) {
val inweboCredential = (InweboCredential) transaction.getCredentials().iterator().next();
builder.addAttribute(ATTRIBUTE_NAME_INWEBO_AUTHENTICATION_DEVICE, inweboCredential.getDeviceName());
}
@Override
public boolean supports(final Credential credential) {
return InweboCredential.class.isAssignableFrom(credential.getClass());
}
}
|
TypeScript
|
UTF-8
| 829
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
// @TODO:
/**
* The Chat Bubble Class
* This application displays a temporary message sent from a particular Token in the active Scene.
* The message is displayed on the HUD layer just above the Token.
*/
declare class ChatBubbles {
/**
* Track active Chat Bubbles
*/
bubbles: object;
constructor();
/**
* A reference to the chat bubbles HTML container in which rendered bubbles should live
*/
get container(): JQuery;
/**
* Speak a message as a particular Token, displaying it as a chat bubble
* @param token The speaking Token
* @param message The spoken message text
* @param emote Whether to style the speech bubble as an emote
* @return A Promise which resolves once the chat bubble has been created
*/
say(token: Token, message: string, { emote }: { emote: boolean }): Promise<void>
}
|
Java
|
UTF-8
| 5,043
| 1.953125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.zaproxy.zap.db.repository;
import java.util.List;
import java.util.Optional;
import javax.persistence.QueryHint;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.query.Param;
import org.zaproxy.zap.db.model.HistoryModel;
import org.zaproxy.zap.db.repository.base.CacheableCrudRepository;
/**
* https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query-methods.query-creation
*/
public interface HistoryModelRepository extends CacheableCrudRepository<HistoryModel, Long> {
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT id FROM #{#entityName} WHERE sessionId = :sessionId ORDER BY id")
List<Long> findIdsBySessionId(@Param("sessionId") Long sessionId);
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT id FROM #{#entityName} WHERE sessionId = :sessionId AND id >= :startAtHistoryId ORDER BY id")
List<Long> findIdsBySessionIdStartingAt(@Param("sessionId") Long sessionId,
@Param("startAtHistoryId") Long startAtHistoryId);
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT id FROM #{#entityName} WHERE sessionId = :sessionId AND type IN (:histTypes) ORDER BY id")
List<Long> findIdsBySessionIdAndType(@Param("sessionId") Long sessionId, @Param("histTypes") int... histTypes);
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT id FROM #{#entityName} WHERE sessionId = :sessionId AND id >= :startAtHistoryId AND type IN (:histTypes) ORDER BY id")
List<Long> findIdsBySessionIdAndTypeStartingAt(@Param("sessionId") Long sessionId,
@Param("startAtHistoryId") Long startAtHistoryId, @Param("histTypes") int... histTypes);
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT id FROM #{#entityName} WHERE sessionId = :sessionId AND type NOT IN (:histTypes) ORDER BY id")
List<Long> findIdsBySessionIdAndNotType(@Param("sessionId") Long sessionId, @Param("histTypes") int... histTypes);
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT id FROM #{#entityName} WHERE sessionId = :sessionId AND id >= :startAtHistoryId AND type NOT IN (:histTypes) ORDER BY id")
List<Long> findIdsBySessionIdAndNotTypeStartingAt(@Param("sessionId") Long sessionId,
@Param("startAtHistoryId") Long startAtHistoryId, @Param("histTypes") int... histTypes);
List<HistoryModel> findBySessionIdAndTypeOrderByIdAsc(Long sessionId, int histType);
@Modifying
@Query("DELETE FROM #{#entityName} WHERE sessionId = :sessionId")
void deleteBySessionId(@Param("sessionId") Long sessionId);
@Modifying
@Query("DELETE FROM #{#entityName} WHERE sessionId = :sessionId AND type IN (:histTypes)")
void deleteBySessionIdAndType(@Param("sessionId") Long sessionId, @Param("histTypes") int... histType);
@Modifying
@Query("DELETE FROM #{#entityName} WHERE type IN (:histTypes)")
void deleteAllByType(@Param("histTypes") Iterable<Integer> types);
Optional<HistoryModel> findFirstByUriAndMethodAndRequestBodyAndSessionIdAndType(String uri, String method,
String requestBody, Long sessionId, int type);
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT h FROM #{#entityName} h WHERE uri = :uri AND method = :method AND requestBody = :requestBody AND sessionId = :sessionId AND statusCode != #{T(org.parosproxy.paros.network.HttpStatusCode).NOT_MODIFIED} AND id >= :id AND id <= (:id + 200)")
List<HistoryModel> findAllHistoryCache(@Param("id") Long id, @Param("uri") String uri,
@Param("method") String method, @Param("requestBody") String requestBody,
@Param("sessionId") Long sessionId, Pageable page);
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT h FROM #{#entityName} h WHERE uri = :uri AND method = :method AND requestBody = :requestBody AND sessionId = :sessionId AND statusCode != #{T(org.parosproxy.paros.network.HttpStatusCode).NOT_MODIFIED} ")
List<HistoryModel> findAllHistoryCacheBefore(@Param("uri") String uri, @Param("method") String method,
@Param("requestBody") String requestBody, @Param("sessionId") Long sessionId, Pageable page);
@QueryHints(value = { @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true") })
@Query("SELECT MAX(id) FROM #{#entityName}")
Optional<Long> findMaxId();
}
|
TypeScript
|
UTF-8
| 1,949
| 3.453125
| 3
|
[] |
no_license
|
export class Descriptive {
static mean(data: number[]): number {
return Descriptive.sum(data) / data.length;
}
static median(data: number[]): number {
const sortedDataset = data.sort((left, right) => left - right);
const middleIndex = sortedDataset.length / 2;
if (!this.isEven(data.length)) {
const index = Math.floor(middleIndex);
return sortedDataset[index];
}
const lowerIndex = middleIndex - 1;
return (sortedDataset[lowerIndex] + sortedDataset[middleIndex]) / 2;
}
static max(data: number[]): number {
return data.reduce((left, right) => left > right ? left : right, -Infinity);
}
static mode(data: number[]): number[] {
const table = Descriptive.table(data);
const maximum = Descriptive.max(data);
const isMax = key => table[key] === maximum;
const toNum = key => Number(key);
return Object
.keys(table)
.filter(isMax)
.map(toNum);
}
static variance(data: number[]): number {
const dataMean = Descriptive.mean(data);
const squared = val => Math.pow(val, 2);
const calcVariance = val => squared(val - dataMean);
const variances = data.map(calcVariance);
return this.sum(variances) / data.length;
}
static stdDev(data: number[]): number {
const populationVariance = Descriptive.variance(data);
return Math.sqrt(populationVariance);
}
static sum(data: number[]) {
return data.reduce((left, right) => left + right, 0);
}
static isEven(value: number): boolean {
return value % 2 === 0;
}
static table(data: number[]): Dataset {
const addFreq = (freqs, val) => { freqs[val] = (freqs[val] || 0) + 1; return freqs; }
return data.reduce(addFreq, {});
}
}
export interface Dataset {
[index: string]: number;
}
|
Java
|
UTF-8
| 3,035
| 2.40625
| 2
|
[] |
no_license
|
package me.ele.homedemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import me.ele.omniknight.OKActivity;
public class MainActivity extends OKActivity {
private ViewPager viewPager;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(4);
final MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
String title = null;
switch (position) {
case 0:
title = "4条数据";
break;
case 1:
title = "7条数据";
break;
case 2:
title = "20条数据";
break;
case 3:
title = "页面" + position;
break;
}
getSupportActionBar().setTitle(title);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
}
private class MyAdapter extends FragmentStatePagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = FirstFragment.newInstance(4);
break;
case 1:
fragment = FirstFragment.newInstance(7);
break;
case 2:
fragment = FirstFragment.newInstance(20);
break;
case 3:
fragment = SecondFragment.newInstance(position);
break;
}
return fragment;
}
@Override
public int getCount() {
return 4;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
|
Java
|
UTF-8
| 7,184
| 2.265625
| 2
|
[] |
no_license
|
package com.zenithgames.shadowrunner.utils;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
/**
* Created by iker on 12/7/15.
*/
public class AssetsLoader {
public static TextureRegion background1,white,black,greyground,blackground,whiteground,left1,left2,right1,right2,whiteb,blackb,up1,up2,whiteOrb,blackOrb,greyOrb;
public static FileHandle particleEffectWhiteConstant,particleEffectBlackConstant,particleEffectWhiteExplosion,particleEffectBlackExplosion, particleEffect2;
public static void init(){
switch(Gdx.app.getType()) {
case Android:
particleEffectWhiteConstant = Gdx.files.internal("whiteConstant.p");
particleEffectBlackConstant = Gdx.files.internal("blackConstant.p");
particleEffectWhiteExplosion = Gdx.files.internal("whiteExplosion.p");
particleEffectBlackExplosion = Gdx.files.internal("blackExplosion.p");
particleEffect2 = Gdx.files.internal("");
blackOrb = new TextureRegion(new Texture(Gdx.files.internal("blackOrb.png")));
whiteOrb = new TextureRegion(new Texture(Gdx.files.internal("whiteOrb.png")));
greyOrb = new TextureRegion(new Texture(Gdx.files.internal("greyOrb.png")));
background1 = new TextureRegion(new Texture(Gdx.files.internal("background.png")));
white = new TextureRegion(new Texture(Gdx.files.internal("runnerwhite.png")));
black = new TextureRegion(new Texture(Gdx.files.internal("runnerblack.png")));
greyground = new TextureRegion(new Texture(Gdx.files.internal("greyground.png")));
whiteground =new TextureRegion(new Texture(Gdx.files.internal("whiteground.png")));
blackground = new TextureRegion(new Texture(Gdx.files.internal("blackground.png")));
left1 = new TextureRegion(new Texture(Gdx.files.internal("leftbutton.png")));
left2 = new TextureRegion(new Texture(Gdx.files.internal("leftbutton2.png")));
right1 = new TextureRegion(new Texture(Gdx.files.internal("rightbutton.png")));
right2 = new TextureRegion(new Texture(Gdx.files.internal("rightbutton2.png")));
whiteb = new TextureRegion(new Texture(Gdx.files.internal("buttonwhite.png")));
blackb = new TextureRegion(new Texture(Gdx.files.internal("buttonblack.png")));
up1 = new TextureRegion(new Texture(Gdx.files.internal("upbutton.png")));
up2 = new TextureRegion(new Texture(Gdx.files.internal("upbutton2.png")));
break;
case Desktop:
particleEffectWhiteConstant = Gdx.files.internal("android/assets/whiteConstant.p");
particleEffectBlackConstant = Gdx.files.internal("android/assets/blackConstant.p");
particleEffectWhiteExplosion = Gdx.files.internal("android/assets/whiteExplosion.p");
particleEffectBlackExplosion = Gdx.files.internal("android/assets/blackExplosion.p");
particleEffect2 = Gdx.files.internal("android/assets");
blackOrb = new TextureRegion(new Texture(Gdx.files.internal("android/assets/blackOrb.png")));
whiteOrb = new TextureRegion(new Texture(Gdx.files.internal("android/assets/whiteOrb.png")));
greyOrb = new TextureRegion(new Texture(Gdx.files.internal("android/assets/greyOrb.png")));
background1 = new TextureRegion(new Texture(Gdx.files.internal("android/assets/background.png")));
white = new TextureRegion(new Texture(Gdx.files.internal("android/assets/runnerwhite.png")));
black = new TextureRegion(new Texture(Gdx.files.internal("android/assets/runnerblack.png")));
greyground = new TextureRegion(new Texture(Gdx.files.internal("android/assets/greyground.png")));
whiteground =new TextureRegion(new Texture(Gdx.files.internal("android/assets/whiteground.png")));
blackground = new TextureRegion(new Texture(Gdx.files.internal("android/assets/blackground.png")));
left1 = new TextureRegion(new Texture(Gdx.files.internal("android/assets/leftbutton.png")));
left2 = new TextureRegion(new Texture(Gdx.files.internal("android/assets/leftbutton2.png")));
right1 = new TextureRegion(new Texture(Gdx.files.internal("android/assets/rightbutton.png")));
right2 = new TextureRegion(new Texture(Gdx.files.internal("android/assets/rightbutton2.png")));
whiteb = new TextureRegion(new Texture(Gdx.files.internal("android/assets/buttonwhite.png")));
blackb = new TextureRegion(new Texture(Gdx.files.internal("android/assets/buttonblack.png")));
up1 = new TextureRegion(new Texture(Gdx.files.internal("android/assets/upbutton.png")));
up2 = new TextureRegion(new Texture(Gdx.files.internal("android/assets/upbutton2.png")));
break;
}
blackOrb.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
whiteOrb.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
greyOrb.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
background1.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
white.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
black.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
greyground.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
whiteground.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
blackground.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
left1.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
left2.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
right1.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
right2.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
whiteb.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
blackb.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
up1.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
up2.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
}
public static TextureRegion getBackground(String s){
switch (s){
case "1":
return background1;
default:
return background1;
}
}
}
|
C++
|
UTF-8
| 513
| 3.046875
| 3
|
[] |
no_license
|
#pragma once
#include <vector>
#include "Vector2.h"
class Edge;
class Node
{
public:
Vector2 position;
std::vector<Edge> edges;
void AddEdge(Edge e);
};
class Edge
{
public:
Node* connectedTo;
float weight;
Edge(Node* node, float w = 1);
};
class Graph
{
std::vector<Node> nodes;
public:
Graph();
~Graph();
void AddNode(Node node);
std::vector<Node*> GetAdjacentNodes(Node* node);
std::vector<Node>& GetAllNodes();
Node* GetNode(Vector2 position);
float GetDistance(Node* n1, Node* n2);
};
|
C#
|
UTF-8
| 3,082
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FontWorx
{
public partial class ByteGenerator : Form
{
Main MainWindow;
List<Character> Chars = new List<Character>();
public ByteGenerator(Main sender, List<Character> CharInfo)
{
Chars.Clear();
Chars.AddRange(CharInfo);
MainWindow = sender;
InitializeComponent();
}
private void ByteGenerator_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
if (singleArrayRadio.Checked)
{
string output = "";
output += "uint8_t " + variableName.Text + "[" + (8 * Chars.Count).ToString() + "] = {\r\n";
for(int C = 0; C < Chars.Count; ++C) // (Character C in Chars)
{
for (int i = 0; i < 8; ++i)
{
output += "0x" + Chars[C].glyfData[i].ToString("X2");
if (i < 7) output += ", ";
else
{
if (C < Chars.Count - 1) output += ",";
}
}
output += "\r\n";
}
output += "};";
if (copyToClipboardRadio.Checked)
{
Clipboard.SetText(output);
this.Close();
}
else
{
MessageBox.Show("Write to file not implemented yet");
}
}
else
{//Double array
string output = "";
output += "uint8_t " + variableName.Text + "[" + Chars.Count.ToString() + "][8] = {\r\n";
for(int C = 0; C < Chars.Count; ++C)
{
output += "\t{/*ASCII: " + ((char)(C+32)) +" */";
output += "\r\n\t\t";
for(int i = 0; i < 8; ++i)
{
output += "0x" + Chars[C].glyfData[i].ToString("X2");
if (i < 7) output += ",";
}
output += "\r\n\t}";
if (C < Chars.Count - 1) output += "\r\n\t,\r\n";
}
output += "\r\n};";
if (copyToClipboardRadio.Checked)
{
Clipboard.SetText(output);
this.Close();
}
else
{
MessageBox.Show("Write to file not implemented yet");
}
}
}
}
}
|
Python
|
UTF-8
| 4,047
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
"""DEPRECATED
Provides the struct used to store instructions within binary files.
"""
# TODO: Add automatic detection and creation of format string based on
# int.bitlength
from __future__ import print_function
import bitstruct
import sys
class Struct(object):
"""Conveniece wrapper around struct.Struct class to only need to apply
the byteorder.
"""
def __init__(self, byteorder, frmt):
self._byteorder = None
self._frmt = frmt
self._init_byteorder(byteorder)
def _init_byteorder(self, byteorder):
"""Initialize the byte order."""
self._byteorder = check_byteorder(byteorder)
@property
def frmt(self):
"""Property defining the format of the struct using frmt strings from
the struct pkg."""
return ENDIAN_CHARMAP[self._byteorder] + self._frmt
@frmt.setter
def set(self):
"""Disable setting for frmt outside of init."""
raise Exception("Can't set frmt.")
def pack(self, *args):
"""Pack the arguments into a bytearray"""
return bitstruct.pack(self.frmt, *args)
# TODO: Implement this at some point.. maybe.
# @staticmethod
# def quickpack(*args, byteorder=None):
# """Quickly and intelligently pack the arguments without have to create
# a Struct Object.
# """
# frmt = Struct.gen_frmt(args, byteorder=byteorder)
# return bitstruct.pack(frmt, *args)
# @staticmethod
# def gen_frmt(*args, byteorder=None):
# """Generate a bitstruct frmt string based on the arguments."""
# frmt = ENDIAN_CHARMAP[byteorder]
# if type(args) is tuple:
# args = args[0]
# print('broken' + str(args))
# for arg in args:
# print(str(arg))
# frmt += str(len(arg)) + 'u'
# print('frmt:',frmt)
# return frmt
class BadByteorderException(Exception):
pass
ENDIAN_CHARMAP = {'little': '<',
'big': '>'
}
DEFAULT_BYTEORDER = sys.byteorder
ENDIAN_CHARMAP[None] = ENDIAN_CHARMAP[DEFAULT_BYTEORDER]
def check_byteorder(byteorder):
"""Return whether the byteorder string is valid or not."""
if not byteorder:
print('WARN: byteorder not given, using system byteorder.',
file=sys.stderr)
return None
elif byteorder in ENDIAN_CHARMAP.keys():
return byteorder
else:
raise BadByteorderException('%s not a valid byteorder.\
Try little or big.' % byteorder)
# TODO: Make this into a group that can just run all or a single self test.
def test():
print('Starting self test.')
try:
Struct(byteorder='hello', frmt='u1u2u3')
except BadByteorderException:
pass
else:
assert False, 'Expected to fail with a BadByteorderException'
test_struct = Struct(byteorder='little', frmt='u1u2u3')
assert test_struct._byteorder == 'little', test_struct._byteorder
test_struct = Struct(byteorder='big', frmt='u1u2u3')
assert test_struct._byteorder == 'big', test_struct._byteorder
# Test that when we put in None as byteorder we create a default
# byteorder Struct and that a warning is output to stderr.
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
stderr = sys.stderr
stderr_redir = sys.stderr = StringIO()
test_struct = Struct(None, frmt='u1u2u3')
sys.stderr = stderr
assert test_struct._byteorder is None, test_struct._byteorder
assert test_struct.frmt == '<u1u2u3', test_struct.frmt
assert stderr_redir.getvalue().rstrip() == \
"WARN: byteorder not given, using system byteorder.",\
stderr_redir.getvalue().rstrip()
# Try packing some args.
test_struct = Struct('big', frmt='u1u3u4')
assert test_struct.pack(0, 1, 3) == b'\x13', test_struct.pack(0, 1, 3)
print('---------- PASSED SELF TEST -----------')
# Self test
if __name__ == '__main__':
test()
|
C++
|
UTF-8
| 2,856
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2018 Delft University of Technology
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <sstream>
#include <string>
#include "./srec.h"
namespace fletchgen {
namespace srec {
Record::Record(const uint8_t *data, size_t length, uint32_t address)
: length_(length), address_(address) {
data_ = (uint8_t *) calloc(1, length_);
memcpy(data_, data, length);
byte_count_ = 4 + length_ + 1; // 4 for addr, 1 for checksum
checksum_ = checksum();
}
Record::~Record() {
free(data_);
}
uint8_t Record::checksum() {
auto ret = static_cast<uint8_t>(byte_count_);
// Address
ret += (uint8_t) ((address_ & 0xFFu << 24u) >> 24u);
ret += (uint8_t) ((address_ & 0xFFu << 16u) >> 16u);
ret += (uint8_t) ((address_ & 0xFFu << 8u) >> 8u);
ret += (uint8_t) (address_ & 0xFFu);
// Data
for (unsigned int i = 0; i < length_; i++)
ret += (uint8_t) data_[i];
// 1's complement the final result
ret = ~ret;
return ret;
}
std::string Record::toString() {
// Formatting was taken from:
// https://github.com/vsergeev/libGIS
// Buffer to throw snprintf output in
char buf[64] = {0};
// String stream to build output
std::stringstream output;
// Byte count
snprintf(buf, sizeof(buf), "%s%2.2X", "S3", (unsigned int) byte_count_);
output << std::string(buf);
// Address
snprintf(buf, sizeof(buf), "%2.8X", address_);
output << std::string(buf);
// Data
for (unsigned int i = 0; i < length_; i++) {
snprintf(buf, sizeof(buf), "%2.2X", data_[i]);
output << std::string(buf);
}
// Checksum
snprintf(buf, sizeof(buf), "%2.2X\r\n", checksum_);
output << std::string(buf);
return output.str();
}
File::File(const uint8_t *data, size_t length, uint32_t address) {
// Chop the data up into MAX_DATA_BYTES Records
size_t pos = 0;
while (pos < length) {
size_t recsize;
if ((length - pos) / Record::MAX_DATA_BYTES > 0) {
recsize = Record::MAX_DATA_BYTES;
} else {
recsize = (length - pos) % Record::MAX_DATA_BYTES;
}
auto record = std::make_shared<Record>(&data[pos], recsize, static_cast<uint32_t>(address + pos));
lines_.push_back(record);
pos = pos + recsize;
}
}
void File::write(std::ostream &output) {
for (auto &r : lines_) {
output << r->toString();
}
}
}; // namespace srec
}; // namespace fletchgen
|
PHP
|
UTF-8
| 9,345
| 2.765625
| 3
|
[] |
no_license
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>form_upload</title>
</head>
<body>
<div class="well">
<div class="content">
<form action="form_upload.php" method="post" enctype="multipart/form-data">
<fieldset>
<table width="350" border="0" align="center">
<legend> Data Entry
<tr><td><label>Image Name <span class="required">*</span></label></td>
<td align="center"><input type="text" name="iname" placeholder="Image Name"></br>
</td>
</tr>
<tr><td><label for="file">Upload Picture: </label></td>
<td align="right"><input type="file" name="file" id="file"></br>
</td>
</tr>
<tr><td> </td></tr>
<tr><td><label for="table">Choose Table: </label></td>
<td align="right">
<input type="radio" name="table" value="carousel" id="table" checked>Carousel</br>
<input type="radio" name="table" value="product" id="table">Products</br>
<input type="radio" name="table" value="arrivals" id="table">New Arrivals <br/>
</td>
</tr>
<tr><td colspan="2" align="center"><button type="submit" name="submit">Submit</button></br></br><a href="adminhome.php?">View Data</a></td></tr>
<tr><td colspan="2"> </td></tr>
<tr><td colspan="2" align="center">
<?php
if(isset($_REQUEST['submit']) && ($_POST['table'] == 'carousel'))
{
$con=mysqli_connect("localhost", "JonathanAdmin","0311*Dog", "data_from_the_base");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_error();
}
$iname=$_POST['iname'];
$file=$_FILES["file"]["name"];
$size=$_FILES["file"]["size"];
if( empty($iname) || empty($file))
{
echo "<label class='err'>All fields required</label>";
}
//chech file size
elseif($size > 500000)
{
echo "<label class='err'> Image size max is 500kb </label>";
}
/* -- Few preparations for Checking the File Type (extension) -- */
$allowedExts = array("gif", "jpeg", "jpg", "png");
//Store the allowed extensions in an array
/* using explode() function, seperate the 'File Name'
and its 'Extension' into individual elements of an array: $temp */
$temp = explode(".", $_FILES["file"]["name"]);
/* The end() function returns the last element of an array.
As per array $temp, First element: File Name
Last element: Extension */
$extension = end($temp);
/* -- Checking the File Type (extension) -- */
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/txt")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] <= 5000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
//Checks if the specific file already exists in the directory.
elseif (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . "Image upload already exists. ";
}
else
{
/* The move_uploaded_file() function moves an
uploaded file to a new location. */
move_uploaded_file ( $_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"] );
//Insert the 'Image name' and 'File Name' to the database
mysqli_query($con,"INSERT INTO carousel (imageName, filename)
VALUES ('$iname', '$file')");
echo "Data Entered Successfully Saved!";
}
}
mysqli_close($con); //Close the Database Connection
}
elseif(isset($_REQUEST['submit']) && ($_POST['table'] == 'product'))
{
$con=mysqli_connect("localhost", "root", "", "data_from_the_base");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_error();
}
$iname=$_POST['iname'];
$file=$_FILES["file"]["name"];
$size=$_FILES["file"]["size"];
if( empty($iname) || empty($file))
{
echo "<label class='err'>All fields required</label>";
}
//chech file size
elseif($size > 500000)
{
echo "<label class='err'> Image size max is 500kb </label>";
}
/* -- Few preparations for Checking the File Type (extension) -- */
$allowedExts = array("gif", "jpeg", "jpg", "png");
//Store the allowed extensions in an array
/* using explode() function, seperate the 'File Name'
and its 'Extension' into individual elements of an array: $temp */
$temp = explode(".", $_FILES["file"]["name"]);
/* The end() function returns the last element of an array.
As per array $temp, First element: File Name
Last element: Extension */
$extension = end($temp);
/* -- Checking the File Type (extension) -- */
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/txt")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] <= 5000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
//Checks if the specific file already exists in the directory.
elseif (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . "Image upload already exists. ";
}
else
{
/* The move_uploaded_file() function moves an
uploaded file to a new location. */
move_uploaded_file ( $_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"] );
//Insert the 'Image name' and 'File Name' to the database
mysqli_query($con,"INSERT INTO product (productName, fileName)
VALUES ('$iname', '$file')");
echo "Data Entered Successfully Saved!";
}
}
mysqli_close($con); //Close the Database Connection
}
elseif(isset($_REQUEST['submit']) && ($_POST['table'] == 'arrivals'))
{
$con=mysqli_connect("localhost", "root", "", "data_from_the_base");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_error();
}
$iname=$_POST['iname'];
$file=$_FILES["file"]["name"];
$size=$_FILES["file"]["size"];
if( empty($iname) || empty($file))
{
echo "<label class='err'>All fields required</label>";
}
//chech file size
elseif($size > 500000)
{
echo "<label class='err'> Image size max is 500kb </label>";
}
/* -- Few preparations for Checking the File Type (extension) -- */
$allowedExts = array("gif", "jpeg", "jpg", "png");
//Store the allowed extensions in an array
/* using explode() function, seperate the 'File Name'
and its 'Extension' into individual elements of an array: $temp */
$temp = explode(".", $_FILES["file"]["name"]);
/* The end() function returns the last element of an array.
As per array $temp, First element: File Name
Last element: Extension */
$extension = end($temp);
/* -- Checking the File Type (extension) -- */
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/txt")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] <= 5000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
//Checks if the specific file already exists in the directory.
elseif (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . "Image upload already exists. ";
}
else
{
/* The move_uploaded_file() function moves an
uploaded file to a new location. */
move_uploaded_file ( $_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"] );
//Insert the 'Image name' and 'File Name' to the database
mysqli_query($con,"INSERT INTO arrivals (description, fileName)
VALUES ('$iname', '$file')");
echo "Data Entered Successfully Saved!";
}
}
mysqli_close($con); //Close the Database Connection
}
?>
</td></tr>
</legend>
</table>
</fieldset>
</form>
</div>
</div>
</body>
</html>
|
Java
|
UTF-8
| 7,635
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
package name.valery1707.kazPersonId;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;
public final class PersonIdUtils {
protected PersonIdUtils() {
throw new IllegalStateException("Utils can not be created");
}
private static final int ID_LENGTH = 12;
/**
* <a href="http://egov.kz/wps/portal/Content?contentPath=/egovcontent/passport_id_card/article/iin_info&lang=ru">Private person ID/ИИН</a>
*/
public static final String PRIVATE_ID_REGEXP =
"^" +
"\\d{2}" + //Year: any
"(0[1-9]|1[0-2])" + //Month: 01-12
"(0[1-9]|[1-2][0-9]|3[0-1])" + //Day: 01-31
"[1-6]" + //Sex and Century bit mask
// 1 - 19 Century, Male
// 2 - 19 Century, Female
// 3 - 20 Century, Male
// 4 - 20 Century, Female
// 5 - 21 Century, Male
// 6 - 21 Century, Female
"\\d{4}" + //Registration number
"\\d" + //CRC
"$";
public static final Pattern PRIVATE_ID_PATTERN = Pattern.compile(PRIVATE_ID_REGEXP);
/**
* <a href="http://egov.kz/wps/portal/Content?contentPath=/egovcontent/bus_business/for_businessmen/article/business_identification_number&lang=ru">Juridical person ID/БИН</a>
*/
public static final String JURIDICAL_ID_REGEXP =
"^" +
"\\d{2}" + //Year: any
"(0[1-9]|1[0-2])" + //Month: 01-12
"[4-6]" + //Juridical person type or Individual entrepreneur:
// 4 - Juridical person resident // Юридическое лицо резидент
// 5 - Juridical person non-resident // Юридическое лице не резидент
// 6 - Individual entrepreneur // ИП
"[0-3]" + //Additional attribute:
// 0 - Head unit of Juridical person or Individual entrepreneur // Головное подразделение юридического лица или ИП(С)
// 1 - Affiliated branch of Juridical person or Individual entrepreneur // Филиал юридического лица или ИП(С)
// 2 - Representation office of Juridical person or Individual entrepreneur // Представительство юридического лица или ИП(С)
// 3 - Farming // Крестьянское (фермерское) хозяйство, осуществляющее деятельность на основе совместного предпринимательства
"\\d{5}" + //Registration number
"\\d" + //CRC
"$";
public static final Pattern JURIDICAL_ID_PATTERN = Pattern.compile(JURIDICAL_ID_REGEXP);
protected static boolean isDigits(String s) {
for (char c : s.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
private static final int[][] CRC_WEIGHTS = new int[][]{
new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11},
new int[]{3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 2},
};
private static final int CRC_MODE = 11;
private static final int CRC_INCORRECT = 10;
public static int calculateCRC(String id) {
if (id == null || id.length() < CRC_WEIGHTS[0].length || !isDigits(id)) {
return -1;
}
int crc = CRC_INCORRECT;
int weightPos = 0;
while (crc == CRC_INCORRECT && weightPos < CRC_WEIGHTS.length) {
crc = 0;
for (int i = 0; i < ID_LENGTH - 1; i++) {
crc += charAsDigit(id.charAt(i)) * CRC_WEIGHTS[weightPos][i];
}
crc = crc % CRC_MODE;
weightPos++;
}
return crc;
}
public static boolean isValidCRC(String id) {
if (id == null || id.length() != ID_LENGTH || !isDigits(id)) {
return false;
}
int testCrc = charAsDigit(id.charAt(ID_LENGTH - 1));
int crc = calculateCRC(id);
return crc == testCrc;
}
private static int charAsDigit(char c) {
return Character.digit(c, 10);
}
private static final int SEX_AND_CENTURY_POS = 6;
public static Sex detectSex(String id) {
if (id == null || id.length() <= SEX_AND_CENTURY_POS) {
return null;
}
char sex = id.charAt(SEX_AND_CENTURY_POS);
switch (sex) {
case '1':
case '3':
case '5':
return Sex.MALE;
case '2':
case '4':
case '6':
return Sex.FEMALE;
}
//Unknown Sex code
return null;
}
public static final Pattern DATE_PATTERN = Pattern.compile(
"^" +
"\\d{2}" + //Year: any
"(0[1-9]|1[0-2])" + //Month: 01-12
"(0[1-9]|[1-2][0-9]|3[0-1])" + //Day: 01-31
"$"
);
private static boolean isDate(String s) {
return DATE_PATTERN.matcher(s).matches();
}
private static final String BIRTH_DATE_FORMAT = "yyMMdd";
private static final Calendar[] YEAR_PREFIXES = new Calendar[]{
//Unassigned: 0
null,
//18xx: 1, 2
new GregorianCalendar(1800, Calendar.JANUARY, 1),
new GregorianCalendar(1800, Calendar.JANUARY, 1),
//19xx: 3, 4
new GregorianCalendar(1900, Calendar.JANUARY, 1),
new GregorianCalendar(1900, Calendar.JANUARY, 1),
//20xx: 5, 6
new GregorianCalendar(2000, Calendar.JANUARY, 1),
new GregorianCalendar(2000, Calendar.JANUARY, 1),
//Unassigned: 7, 8, 9
null,
null,
null,
};
public static Date detectBirthDate(String id) {
if (id == null || id.length() <= SEX_AND_CENTURY_POS) {
return null;
}
String date = id.substring(0, SEX_AND_CENTURY_POS);
if (!isDigits(date) || !isDate(date)) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(BIRTH_DATE_FORMAT);
dateFormat.setLenient(false);
int yearPrefixIndex = charAsDigit(id.charAt(SEX_AND_CENTURY_POS));
Calendar yearPrefix = YEAR_PREFIXES[(yearPrefixIndex)];
if (yearPrefix != null) {
dateFormat.set2DigitYearStart(yearPrefix.getTime());
}
try {
return new Date(dateFormat.parse(date).getTime());
} catch (ParseException e) {
//todo Throw exception?
return null;
}
}
private static final String REGISTRATION_DATE_FORMAT = "yyMM";
private static final int REGISTRATION_DATE_LENGTH = REGISTRATION_DATE_FORMAT.length();
public static Date detectRegistrationDate(String id) {
if (id == null || id.length() < REGISTRATION_DATE_LENGTH || !PersonIdUtils.isDigits(id.substring(0, REGISTRATION_DATE_LENGTH))) {
return null;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(REGISTRATION_DATE_FORMAT);
dateFormat.setLenient(false);
try {
return new Date(dateFormat.parse(id.substring(0, REGISTRATION_DATE_LENGTH)).getTime());
} catch (ParseException e) {
//todo Throw exception?
return null;
}
}
private static final int TYPE_POS = REGISTRATION_DATE_LENGTH;
public static JuridicalPersonType detectJuridicalPersonType(String id) {
if (id == null || id.length() <= TYPE_POS) {
return null;
}
switch (id.charAt(TYPE_POS)) {
case '4':
return JuridicalPersonType.RESIDENT;
case '5':
return JuridicalPersonType.NON_RESIDENT;
case '6':
return JuridicalPersonType.INDIVIDUAL;
}
return null;
}
private static final int ATTRIBUTE_POS = TYPE_POS + 1;
public static JuridicalPersonAttribute detectJuridicalPersonAttribute(String id) {
if (id == null || id.length() <= ATTRIBUTE_POS) {
return null;
}
switch (id.charAt(ATTRIBUTE_POS)) {
case '0':
return JuridicalPersonAttribute.HEAD_UNIT;
case '1':
return JuridicalPersonAttribute.AFFILIATED_BRANCH;
case '2':
return JuridicalPersonAttribute.REPRESENTATION_OFFICE;
case '3':
return JuridicalPersonAttribute.FARMING;
}
return null;
}
}
|
C++
|
UTF-8
| 1,204
| 2.796875
| 3
|
[] |
no_license
|
#ifndef STRING
#define STRING
#include<string>
#endif
#ifndef IOSTREAM
#define IOSTREAM
#include<iostream>
#endif
#ifndef USER
#define USER
#include "user.h"
#endif
#ifndef DATABASE
#define DATABASE
#include "database.h"
#endif
#ifndef MISC
#define MISC
#include "misc.h"
#endif
#ifndef AIRPORT_CONTROLLER_MODIFY_AIRPORT
#define AIRPORT_CONTROLLER_MODIFY_AIRPORT
#include "airport_controller_modify_airport.h"
#endif
#ifndef AIRPORT_CONTROLLER_VIEW_AIRPORT
#define AIRPORT_CONTROLLER_VIEW_AIRPORT
#include "airport_controller_view_airport.h"
#endif
using namespace std;
void modify_airport_details();
void view_airport_details();
void load_airport_controller_page(User *user){
int select=-1;
while(true){
cout<<"\n\n\t\tEnter your choice:\n\t\t1. Modify airport details\n\t\t2. View airport details\n\t\t3. Log Out\n\t\t>";
cin.clear();
cin>>select;
switch(select){
case 1: modify_airport_details();
break;
case 2: view_airport_details();
break;
case 3:
cout<<"\n\n\t\tLogging out of Airport Controller page...";
return;
default: cout<<"\n\n\t\tERROR: invalid option entered. Please try again";
break;
}
select=-1;
}
}
|
Java
|
UTF-8
| 4,665
| 2.34375
| 2
|
[] |
no_license
|
package com.senzecit.iitiimshaadi.customdialog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.senzecit.iitiimshaadi.R;
import java.util.ArrayList;
import java.util.Vector;
public class MainActivity extends Activity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
textView= (TextView) findViewById(R.id.text);
((Button)findViewById(R.id.btn_normal)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(100,50);
}
});
((Button)findViewById(R.id.btn_cal)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
public Vector<Dialog> dialogs = new Vector<Dialog>();
private void showDialog(int d_width,int d_height){
final ArrayList<Model>models=new ArrayList<Model>();
for(int i=0;i<20;i++){
Model model=new Model();
model.setName("Faiyaz "+i);
models.add(model);
}
final Dialog dialog = new Dialog(this, R.style.CustomDialog);//,R.style.CustomDialog
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().getAttributes().windowAnimations = R.style.animation;
View view = getLayoutInflater().inflate(R.layout.toast_layout, null);
final LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.custom_list);
// final RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
((Button)view.findViewById(R.id.button_done)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
final CustomListAdapterDialog clad1 = new CustomListAdapterDialog(MainActivity.this, models);
recyclerView.setAdapter(clad1);
dialog.setContentView(view);
dialog.setCanceledOnTouchOutside(true);
dialogs.add(dialog);
dialog.show();
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Window window = dialog.getWindow();
window.setGravity(Gravity.RIGHT);
window.setLayout(width-d_width, height-d_height);
clad1.setOnItemClickListener(new CustomListAdapterDialog.OnItemClickListener() {
@Override
public void onItemClick(View view, int position, String id) {
int positionInList = position % models.size();
textView.setText(models.get(positionInList).getName());
dialog.dismiss();
// showDialog(130,50);
}
});
/*final TextView mCenterIndicator = (TextView) view.findViewById(R.id.centerIndicator);
final int itemWidth =240;// (int) getResources().getDimension(R.dimen.flexible_space_image_height) ;
mCenterIndicator.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int center = ( mCenterIndicator.getTop()+ mCenterIndicator.getBottom() ) / 2 ;
int padding = center - itemWidth / 2; //Assuming both left and right padding needed are the same
// recyclerView.setPadding(padding,0,padding,0);
recyclerView.setOnScrollListener(new CenterLockListener(center));
}
});
recyclerView.getLayoutManager().scrollToPosition(Integer.MAX_VALUE / 2);
new Thread(new Runnable() {
@Override
public void run() {
int firstPos = mLayoutManager.findFirstVisibleItemPosition();
int lastPos = mLayoutManager.findLastVisibleItemPosition();
int middle = Math.abs(lastPos - firstPos) / 2 + firstPos;
int selectedPos = -1;
for (int i = 0; i < clad1.getItemCount(); i++) {
if (i == middle) {
selectedPos = i;
} else {
}
}
System.out.println("Middle Pos "+selectedPos);
}
}).start();
*/
// clad1.notifyDataSetChanged();
}
}
|
Shell
|
UTF-8
| 2,357
| 3.765625
| 4
|
[] |
no_license
|
#!/bin/bash
# chkconfig: 2345 20 80
# description: hubot start/stop script
# processname: hubot
### BEGIN INIT INFO
# Provides: hubot
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: hubot - chatops
### END INIT INFO
# REFERENCE: http://werxltd.com/wp/2012/01/05/simple-init-d-script-template/
# This script assumes you have a user called "hubot" on your system and that hubot is installed in /opt/hubot
# Save Environement Variables in /opt/hubot/hubot.env
# e.g
# export HUBOT_GTALK_USERNAME='hubot@example.com'
# export HUBOT_GTALK_PASSWORD='abc123''
# export HUBOT_GTALK_WHITELIST_DOMAINS='example.com'
source /var/lib/hubot/hubot.env
DAEMON="${HUBOT_DIR}/bin/hubot"
DAEMONOPTS=""
if [ ! -z "${HUBOT_NAME}" ]; then
DAEMONOPTS="${DAEMONOPTS} --name ${HUBOT_NAME}"
fi
if [ ! -z "${HUBOT_ADAPTER}" ]; then
DAEMONOPTS="${DAEMONOPTS} --adapter ${HUBOT_ADAPTER}"
fi
NAME=ccbot
USER=root
DESC="hubot"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
case "$1" in
start)
cd $HUBOT_DIR
printf "%-50s" "Starting $DESC..."
PID=`su - $USER -c "source $HUBOT_DIR/hubot.env && cd $HUBOT_DIR && $DAEMON $DAEMONOPTS" >> /var/log/hubot 2>&1 & echo $!`
#echo "Saving PID" $PID " to " $PIDFILE
if [ -z $PID ]; then
printf "%s\n" "Fail"
else
echo $PID > $PIDFILE
printf "%s\n" "Ok"
fi
;;
status)
printf "%-50s" "Checking $DESC..."
if [ -f $PIDFILE ]; then
PID=`cat $PIDFILE`
if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then
printf "%s\n" "Process dead but pidfile exists"
else
echo "Running"
fi
else
printf "%s\n" "Service not running"
fi
;;
stop)
printf "%-50s" "Stopping $DESC"
PID=`cat $PIDFILE`
if [ -f $PIDFILE ]; then
kill $PID
printf "%s\n" "Ok"
rm -f $PIDFILE
# Ensure node also gets killed
sleep 2
nodeps=`ps ax | grep node | grep hubot | awk '{print $1}'`
if [ ! -z $nodeps ]; then
kill $nodeps
fi
else
printf "%s\n" "pidfile not found"
fi
;;
restart)
$0 stop
$0 start
;;
*)
echo "Usage: $0 {status|start|stop|restart}"
exit 1
esac
|
Java
|
UTF-8
| 2,573
| 2.3125
| 2
|
[] |
no_license
|
package com.example.akhil.workforce.worker;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.akhil.workforce.R;
public class WorkerHome extends Fragment{
View view;
Button accept, reject;
TextView jobAlert;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.worker_home,container,false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
jobAlert=(TextView)view.findViewById(R.id.job_alert);
accept=(Button)view.findViewById(R.id.accept);
reject=(Button)view.findViewById(R.id.reject);
accept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Alert for confirmation
AlertDialog.Builder dialog=new AlertDialog.Builder(getActivity());
dialog.setTitle("CONFIRM ACTION");
dialog.setCancelable(true);
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
jobAlert.setText("You have curently dont have active jobs");
Toast.makeText(getContext(),"You have assigned a new job..!",Toast.LENGTH_LONG).show();
}
});
dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(),"no",Toast.LENGTH_SHORT).show();
}
});
dialog.setNeutralButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
});
}
}
|
C#
|
UTF-8
| 3,136
| 2.765625
| 3
|
[] |
no_license
|
using Sales.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sales.Components.PriceComponent
{
class PriceImpl : IPrice
{
private SalesDBEntities context;
public void addPriceCustomer(int customerId, decimal price, DateTime fromDate, DateTime toDate = default(DateTime), int qty = 0)
{
PriceTable pt = new PriceTable
{
CustomerId = customerId,
Price = price,
FromDate = fromDate,
ToDate = toDate,
MinQty = qty
};
using (context = new SalesDBEntities())
{
context.PriceTable.Add(pt);
context.SaveChanges();
}
}
public void addPriceItem(int customerId, int itemId, decimal price, DateTime fromDate, DateTime toDate = default(DateTime), int qty = 0)
{
PriceTable pt = new PriceTable
{
CustomerId = customerId,
Price = price,
FromDate = fromDate,
ToDate = toDate,
MinQty = qty
};
using (context = new SalesDBEntities())
{
context.PriceTable.Add(pt);
context.SaveChanges();
}
}
public void addPriceItemGroup(int customerId, int itemGroupId, decimal price, DateTime fromDate, DateTime toDate = default(DateTime), int qty = 0)
{
PriceTable pt = new PriceTable
{
CustomerId = customerId,
Price = price,
FromDate = fromDate,
ToDate = toDate,
MinQty = qty
};
using (context = new SalesDBEntities())
{
context.PriceTable.Add(pt);
context.SaveChanges();
}
}
public IEnumerable<PriceTable> getAllPrices()
{
IEnumerable<PriceTable> records;
using (context = new SalesDBEntities())
{
records = from pt in context.PriceTable
select pt;
}
return records;
}
public IEnumerable<PriceTable> getCustomerPrices(int customerId)
{
IEnumerable<PriceTable> records;
using (context = new SalesDBEntities())
{
records = from pt in context.PriceTable
where pt.CustomerId == customerId
select pt;
}
return records;
}
public IEnumerable<PriceTable> getItemGroupPrices(int itemGroupId)
{
throw new NotImplementedException();
}
public IEnumerable<PriceTable> getItemPrices(int itemId)
{
throw new NotImplementedException();
}
public PriceTable getPrice(int customerId, int itemId)
{
throw new NotImplementedException();
}
}
}
|
Swift
|
UTF-8
| 1,902
| 2.6875
| 3
|
[] |
no_license
|
//
// ToolbarView.swift
// APITest
//
// Created by Mathew Polzin on 4/12/20.
// Copyright © 2020 Mathew Polzin. All rights reserved.
//
import Foundation
import SwiftUI
import APIModels
struct ToolbarView: View {
let buildingAndRunningTestCount: Int
let finishedTodayTestCount: Int
let settingsTrayOpen: Bool
let newTestButtonDisabled: Bool
let settingsButtonDisabled: Bool
var body: some View {
HStack {
StandardButton(
action: {
store.dispatch(API.GetAllProperties.request)
store.dispatch(NewTest.open)
},
label: "New Test"
).disabled(newTestButtonDisabled)
Spacer()
Text("\(buildingAndRunningTestCount) building/running")
Self.divider
Text("\(finishedTodayTestCount) finished today")
Spacer().frame(maxWidth: .infinity)
Image("Settings")
.renderingMode(.template)
.resizable()
.rotationEffect(.degrees(settingsTrayOpen ? -90.0 : 0.0)).animation(.easeInOut(duration: 0.25))
.foregroundColor(settingsButtonDisabled ? .gray : .accentColor)
.padding(8).frame(width: 46, height: 46)
.onTapGesture {
store.dispatch(Settings.toggleOpen)
}
.disabled(settingsButtonDisabled)
Spacer()
Button(action: { store.dispatch(Help.open) }, label: { Image("Help").resizable() })
.padding(8)
.frame(width: 46, height: 46)
}
}
static var divider: some View {
Rectangle().fill(LinearGradient(gradient: Gradient(colors: [Color.clear, Color.secondary.opacity(0.5), Color.clear]), startPoint: .top, endPoint: .bottom))
.frame(idealWidth: 2, idealHeight: 44).fixedSize()
}
}
|
PHP
|
UTF-8
| 676
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateItemPricesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('item_prices', function(Blueprint $table)
{
$table->integer('id')->unsigned()->primary();
$table->integer('product_id')->unsigned();
$table->integer('price_list_id')->unsigned();
$table->float('rate', 10, 0);
$table->string('currency', 191)->default('EGP');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('item_prices');
}
}
|
Python
|
UTF-8
| 5,501
| 2.53125
| 3
|
[] |
no_license
|
import base64
import tornado.web
import tornado.template
import os.path
import json
import GameBoard
import utils
from config import STATIC_CONTENT_PATH
class MapEditorHandler(tornado.web.RequestHandler):
actions = utils.Enum(["MODULE_SELECTOR", "PAGE", "LIST_IMAGES", "MODULE", "CREATE", "MODULE_INFO"])
def initialize(self, action, config, html_path=""):
self.HTML_PATH = html_path
self.action = action
self.config = config
def get(self, **params):
loader = tornado.template.Loader(self.HTML_PATH)
if self.action == self.actions.MODULE_SELECTOR:
# moduleNames = os.listdir(self.config.ABS_MODS_PATH)
moduleNames = ["napoleon"]
self.write(loader.load("moduleSelector.html").generate(moduleNames=moduleNames))
elif self.action == self.actions.PAGE:
moduleName = params["moduleName"]
self.write(loader.load("mapEditor.html").generate(moduleName=moduleName))
elif self.action == self.actions.MODULE_INFO:
moduleName = params["moduleName"]
moduleInfo = {
"moduleName": moduleName
}
with open(GameBoard.Util.filePath(moduleName, "info.json")) as file:
moduleInfo["metadata"] = json.load(file)
if "stencilImage" in moduleInfo["metadata"]:
stencilData = moduleInfo["metadata"]["stencilImage"]
filePath = GameBoard.Util.filePath(moduleName, stencilData.pop("fileName"))
with open(filePath, "rb") as imageFile:
stencilData["encoded"] = base64.b64encode(imageFile.read()).decode("utf-8")
with open(GameBoard.Util.countryFileName(moduleName)) as countryInfo:
moduleInfo["countries"] = countryInfo.read()
with open(GameBoard.Util.unitFileName(moduleName)) as unitInfo:
moduleInfo["unitCatalogue"] = unitInfo.read()
with open(GameBoard.Util.territoryFileName(moduleName)) as territoryInfo:
moduleInfo["territories"] = territoryInfo.read()
with open(GameBoard.Util.connectionFileName(moduleName)) as connections:
moduleInfo["connections"] = connections.read()
with open(GameBoard.Util.filePath(moduleName, "unitSetup.json")) as connections:
moduleInfo["unitSetup"] = connections.read()
self.write(json.dumps(moduleInfo))
elif self.action == self.actions.LIST_IMAGES:
"""
If no directory provided, looks in top level images directory
Returns an object containing the file names of the images in the given directory
And the names of subdirectories
Throws an error if directory does not exist
"""
requestedDirectory = self.get_argument("directory", "")
if requestedDirectory.__contains__(".."):
self.send_error(500)
return
directory = os.path.join(STATIC_CONTENT_PATH, "images", requestedDirectory)
images = []
directories = []
if os.path.isdir(directory):
for f in os.listdir(directory):
absolutePath = os.path.join(directory, f)
if os.path.isfile(absolutePath):
images.append(f)
elif os.path.isdir(os.path.join(directory, f)):
directories.append(f)
self.write(json.dumps({
"images": images,
"directories": directories
}))
else:
self.send_error(500)
def post(self, **params):
if self.action == self.actions.MODULE:
moduleName = params["moduleName"]
moduleInfo = json.loads(self.request.body.decode("utf-8"))
if os.path.exists(os.path.join(self.config.ABS_MODS_PATH, moduleName)):
def writeFile(key, fileName):
if key in moduleInfo:
with open(fileName, "w") as f:
f.write(json.dumps(moduleInfo[key], indent=4, sort_keys=True))
writeFile("countries", GameBoard.Util.countryFileName(moduleName))
writeFile("units", GameBoard.Util.unitFileName(moduleName))
writeFile("territories", GameBoard.Util.territoryFileName(moduleName))
writeFile("connections", GameBoard.Util.connectionFileName(moduleName))
writeFile("unitSetup", GameBoard.Util.filePath(moduleName, "unitSetup.json"))
elif self.action == self.actions.CREATE:
moduleName = self.get_argument("moduleName")
if not os.path.exists(os.path.join(self.config.ABS_MODS_PATH, moduleName)):
os.makedirs(os.path.join(self.config.ABS_MODS_PATH, moduleName))
with open(GameBoard.Util.countryFileName(moduleName), 'w') as f:
f.write("[]")
with open(GameBoard.Util.unitFileName(moduleName), 'w') as f:
f.write("{}")
with open(GameBoard.Util.territoryFileName(moduleName), 'w') as f:
f.write("[]")
with open(GameBoard.Util.connectionFileName(moduleName), 'w') as f:
f.write("[]")
with open(GameBoard.Util.filePath(moduleName, "unitSetup.json"), 'w') as f:
f.write("{}")
|
Python
|
UTF-8
| 2,756
| 3.84375
| 4
|
[] |
no_license
|
"""
## 牛客网Python刷题stdin问题
牛客网上面大部分题都不是像leetcode那样将解答写在Solution类的实例方法上
而是 从stdin读取测试用例,再通过stdout输出返回值
## 牛客网的Python版本不完全支持typehint
牛客网的python3版本是3.5,刚开始支持typehint,但仅在函数入参和返回值中支持typehint
不支持Python 3.6的typehint/variable annotations
[variable annotations](https://docs.python.org/3/whatsnew/3.6.html)
```
PEP 526: Syntax for variable annotations
PEP 484 introduced the standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:
primes: List[int] = []
captain: str # Note: no initial value!
class Starship:
stats: Dict[str, int] = {}
```
"""
import sys
def int_array_split_whitespace():
"""
[2019 PayPal实习生招聘编程卷 - [编程题]飞机最低可俯冲高度](https://nowcoder.com/test/16723511/summary)
输入样例:
1 1000
"""
# split()方法默认会以空格作为分隔符
nums = [int(num) for num in input().split()]
print(nums)
def int_array_split_newline_1():
"""
[牛客网-在线编程-连续子数组最大和](https://nowcoder.com/practice/03d341fb6c9d42debcdd38d82a0a545c)
提示: 在IDEA的运行窗口,要通过cmd+D发送EOF,因为Ctrl+D是Debug的快捷键。在Terminal上Ctrl+D就能发送EOF了
输入样例:
1
2
"""
import fileinput
nums = [int(line) for line in fileinput.input()]
print(nums)
def int_array_split_newline_2():
"""
input()和sys.stdin.readline()一样只能从stdin读一行,遇到'\n'就结束,不能处理多行输入的测试用例
输入样例:
1
2
"""
nums = [int(line) for line in sys.stdin.readlines()]
print(nums)
def multi_lines_multi_value():
"""
[牛客网-在线编程-连续子数组最大和](https://nowcoder.com/practice/03d341fb6c9d42debcdd38d82a0a545c)
输入样例:
2.0
5
3.0 5.0
6.0 13.0
2.0 6.0
7.0 12.0
0.0 2.0
输出样例:
[[0, 2], [1, 3], [4]]
"""
distance = float(sys.stdin.readline().rstrip('\n'))
n = float(sys.stdin.readline().rstrip('\n'))
coordinates = []
for line in sys.stdin.readlines():
values = line.rstrip('\n').split()
coordinates.append((float(values[0]), float(values[1])))
print(distance, n)
print(coordinates)
output = [[0, 2], [1, 3], [4]]
print(output)
if __name__ == '__main__':
# int_array_split_whitespace()
# int_array_split_newline_1()
# int_array_split_newline_2()
multi_lines_multi_value()
|
Java
|
UTF-8
| 1,365
| 1.804688
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* <p>IJPay 让支付触手可及,封装了微信支付、支付宝支付、银联支付常用的支付方式以及各种常用的接口。</p>
*
* <p>不依赖任何第三方 mvc 框架,仅仅作为工具使用简单快速完成支付模块的开发,可轻松嵌入到任何系统里。 </p>
*
* <p>IJPay 交流群: 723992875、864988890</p>
*
* <p>Node.js 版: <a href="https://gitee.com/javen205/TNWX">https://gitee.com/javen205/TNWX</a></p>
*
* <p>企业微信-发放企业红包</p>
*
* @author Javen
*/
package com.ijpay.wxpay.model;
import com.ijpay.core.model.BaseModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SendWorkWxRedPackModel extends BaseModel {
private String nonce_str;
private String sign;
private String mch_billno;
private String mch_id;
private String wxappid;
private String sender_name;
private String agentid;
private String sender_header_media_id;
private String re_openid;
private String total_amount;
private String wishing;
private String act_name;
private String remark;
private String scene_id;
private String workwx_sign;
}
|
JavaScript
|
UTF-8
| 6,319
| 3.421875
| 3
|
[] |
no_license
|
const classicGallery = document.querySelector("#section-classic");
const veganGallery = document.querySelector("#section-vegan");
const spicyGallery = document.querySelector("#section-spicy");
const courseToAdd = [
{
section: "classic",
name: "falafels",
picture: {src:"ressources/desktop/classic-entree.jpg", alt:"falafels"},
info: "fresh - gluten free - nut free - lactose free"
},
{
section: "classic",
name: "Burger Angus frites",
picture: {src:"ressources/desktop/classic-main.jpg", alt:"Burger Angus frites"},
info: "fresh - not so healthy but yummy"
},
{
section: "classic",
name: "cheesecake",
picture: {src:"ressources/desktop/classic-dessert.jpg", alt:"cheesecake"},
info: "fresh - homemade"
},
{
section: "vegan",
name: "salade de tofu",
picture: {src:"ressources/desktop/vegan-entree.jpg", alt:"salade de tofu"},
info: "fresh - low carb - lactose free"
},
{
section: "vegan",
name: "vegan burger",
picture: {src:"ressources/desktop/vegan-main.jpg", alt:"vegan burger"},
info: "fresh - nut free - lactose free"
},
{
section: "vegan",
name: "crème coco tapioca",
picture: {src:"ressources/desktop/vegan-dessert.jpg", alt:"crème coco tapioca"},
info: "fresh - lactose free"
},
{
section: "spicy",
name: "Gambas harissa",
picture: {src:"ressources/desktop/spicy-entree.jpg", alt:"Gambas harissa"},
info: "fresh - nut free - spicy"
},
{
section: "spicy",
name: "spicy Burger",
picture: {src:"ressources/desktop/spicy-main.jpg", alt:"spicy Burger"},
info: "fresh - nut free - spicy"
},
{
section: "spicy",
name: "glace choco piment",
picture: {src:"ressources/desktop/spicy-dessert.jpg", alt:"glace choco piment"},
info: "spicy - yummy"
},
]
const priceClasssicMenu = document.createElement('h5');
priceClasssicMenu.innerHTML = "Menu HTML";
classicGallery.appendChild(priceClasssicMenu);
const priceVeganMenu = document.createElement('h5');
priceVeganMenu.innerHTML = "Menu CSS";
veganGallery.appendChild(priceVeganMenu);
const priceSpicyMenu = document.createElement('h5');
priceSpicyMenu.innerHTML = "Menu JS";
spicyGallery.appendChild(priceSpicyMenu);
function createCard(courseToAdd) {
const courseContainer = document.createElement('div'); // cree une div dans const courseContainer
courseContainer.classList.add('course-container'); // ajoute une class a la div
if (courseToAdd.section === "classic") {
classicGallery.appendChild(courseContainer); // ajoute div.course-container a classicGallery
} else if (courseToAdd.section === "vegan") {
veganGallery.appendChild(courseContainer);
} else {
spicyGallery.appendChild(courseContainer);
}
const cardImg = document.createElement('img');
cardImg.src = courseToAdd.picture.src;
cardImg.alt = courseToAdd.picture.alt;
cardImg.classList.add("gallery-picture");
cardImg.classList.add("show-on-scroll");
courseContainer.appendChild(cardImg);
const titleCard = document.createElement('h2');
//titleCard.classList.add() mais pas de class particuliere
titleCard.innerHTML = courseToAdd.name;
courseContainer.appendChild(titleCard);
const infoCard = document.createElement('h3');
infoCard.innerHTML = courseToAdd.info;
courseContainer.appendChild(infoCard);
}
for (let i = 0 ; i < courseToAdd.length ; i++)
createCard(courseToAdd[i]);
// STICKY HEADER //
// When the user scrolls the page, execute myFunction
window.onscroll = function() {stickyMenu()};
// Get the nav
const navGallery = document.getElementById("nav-gallery");
// Get the offset position of the navbar
const sticky = navGallery.offsetTop;
// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
function stickyMenu() {
if (window.pageYOffset > sticky) {
navGallery.classList.add("sticky");
} else {
navGallery.classList.remove("sticky");
}
}
// CLASS BUTTON PAGE ACTIVE //
//Get the container element
const buttonContainer = document.querySelector("#nav-gallery ul");
// Get all buttons with class="btn" inside the container
const btns = buttonContainer.getElementsByClassName("btn");
// Loop through the buttons and add the active class to the current/clicked button
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function(){
const current = document.getElementsByClassName("active");
// If there's no active class
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", '');
}
// Add the active class to the current/clicked button
this.className += " active";
});
}
// ANIMATION ON SCROLL //
// scroll should be the window.requestAnimationFrame method
const scroll = window.requestAnimationFrame ||
function(callback){ window.setTimeout(callback, 1000/60)};
// grab the elements on the page we want to look out for.
const elementsToShow = document.querySelectorAll('.show-on-scroll');
// Let’s set up that looping function.
function loop() {
elementsToShow.forEach(function (element) {
// if it’s in the viewport > visible else invisible
if (isElementInViewport(element)) {
element.classList.add('is-visible');
} else {
element.classList.remove('is-visible');
}
});
scroll(loop);
}
// Call the loop for the first time
loop();
// Helper function from: http://stackoverflow.com/a/7557433/274826
function isElementInViewport(el) {
// special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
(rect.top <= 0
&& rect.bottom >= 0)
||
(rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight))
||
(rect.top >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
);
}
|
Java
|
UTF-8
| 811
| 2.515625
| 3
|
[] |
no_license
|
package br.edu.up.Control.service;
import br.edu.up.Control.DAO.Dao;
import br.edu.up.Control.DAO.FactoryDao;
import br.edu.up.Control.entidade.Produto;
public class ProdutoService {
public void salvar(Produto c) throws ServiceException {
if (c.getNome() == null || c.getNome().equals("")) {
throw new
ServiceException("ERR01 - O nome precisa ser preenchido.");
}
Dao<Produto> ProdutoDao = FactoryDao.createProdutoDao();
ProdutoDao.salvar(c);
}
public void alterar (Produto c) throws ServiceException {
Dao<Produto> ProdutoDao = FactoryDao.createProdutoDao();
ProdutoDao.alterar(c);
}
public void excluir (Produto c) throws ServiceException {
Dao<Produto> ProdutoDao = FactoryDao.createProdutoDao();
ProdutoDao.excluir(c);
}
}
|
C#
|
UTF-8
| 2,348
| 2.671875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
string path = "";
protected void Page_Load(object sender, EventArgs e)
{
path = AppDomain.CurrentDomain.BaseDirectory;
}
protected void Button_number_Click(object sender, EventArgs e)
{
Random rand = new Random();
int n = rand.Next(50) + 1; // creates a number between 1 and 50
this.Label_number.Text = n.ToString();
double width = 100.0 / n;
StreamWriter file = new StreamWriter(path + "ex4.html");
file.WriteLine("<html>");
file.WriteLine("<head>");
file.WriteLine("<title>EX-4</title>");
file.WriteLine("<meta charset = \"utf-8\" />");
file.WriteLine("<style>");
file.WriteLine("body {");
file.WriteLine("margin: 0;");
file.WriteLine("}");
file.WriteLine(".size {");
file.WriteLine("width: " + width + "%;");
file.WriteLine("height: 100%;");
file.WriteLine("float: left;");
file.WriteLine("}");
file.WriteLine(".column1 {");
file.WriteLine("background-color: blue;");
file.WriteLine("}");
file.WriteLine(".column2 {");
file.WriteLine("background-color: red;");
file.WriteLine("}");
file.WriteLine(".column3 {");
file.WriteLine("background-color: green;");
file.WriteLine("}");
file.WriteLine("</style>");
file.WriteLine("</head>");
file.WriteLine("<body>");
file.WriteLine("<div>");
for (int i = 0; i < n; i++)
{
if (i % 3 == 0)
file.WriteLine("<div class=\"size column1\" ;></div>");
else if (i % 3 == 1)
file.WriteLine("<div class=\"size column2\" ;></div>");
else
file.WriteLine("<div class=\"size column3\" ;></div>");
}
file.WriteLine("</div>");
file.WriteLine("</body>");
file.WriteLine("</html>");
file.Close();
System.Diagnostics.Process.Start(path + "ex4.html");
}
}
|
Rust
|
UTF-8
| 2,587
| 3.140625
| 3
|
[] |
no_license
|
use crate::state::State;
use crate::world::World;
#[derive(Debug, Clone, Copy)]
pub struct StateIndexer {
num_taxi_states: usize,
num_passenger_states: usize,
num_destination_states: usize,
}
impl StateIndexer {
pub fn new(world: &World) -> StateIndexer {
let num_taxi_states = (world.width * world.height) as usize;
let num_destination_states = world.num_fixed_positions();
let num_passenger_states = num_destination_states + 1;
StateIndexer {
num_taxi_states,
num_passenger_states,
num_destination_states,
}
}
pub fn num_states(&self) -> usize {
self.num_taxi_states * self.num_passenger_states * self.num_destination_states
}
pub fn get_index(&self, world: &World, state: &State) -> Option<usize> {
if let Some(destination_index) = world.get_fixed_index(state.get_destination()) {
let mut result = destination_index;
if let Some(passenger_index) = match state.get_passenger() {
Some(passenger_id) => world.get_fixed_index(passenger_id),
None => Some(self.num_passenger_states - 1),
} {
result *= self.num_passenger_states;
result += passenger_index;
let taxi_pos = state.get_taxi();
let taxi_index = (world.width * taxi_pos.y + taxi_pos.x) as usize;
result *= self.num_taxi_states;
result += taxi_index;
return Some(result);
}
}
None
}
pub fn get_state(&self, world: &World, mut state_index: usize) -> Option<State> {
let taxi_index = state_index % self.num_taxi_states;
state_index /= self.num_taxi_states;
let passenger_index = state_index % self.num_passenger_states;
state_index /= self.num_passenger_states;
let destination_index = state_index;
let taxi_x = taxi_index % (world.width as usize);
let taxi_y = taxi_index / (world.width as usize);
if let Some(destination) = world.get_fixed_id_from_index(destination_index) {
let passenger = if passenger_index < world.num_fixed_positions() {
world.get_fixed_id_from_index(passenger_index)
} else {
None
};
State::build(
world,
(taxi_x as i32, taxi_y as i32),
passenger,
destination,
)
.ok()
} else {
None
}
}
}
|
Markdown
|
UTF-8
| 1,557
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
---
title: Karakter og fellesskap
date: 21/07/2022
---
En sang lyder: «Jeg er en stein, jeg er en øy.» Har du noen gang følt det slik – å ville stå alene? Du kan ha hørt folk si: «Vel, min vandring med Gud er en privatsak. Det er ikke noe jeg vil snakke om.»
`Les Ef 4,11–16. Hva er poenget i teksten? Hva er fellesskapets rolle?`
Når Paulus skriver til efeserne, skildrer han menigheten som en kropp. Jesus er hodet, og hans folk utgjør resten. Hvis du leser Ef 4,13, ser du hensikten med å leve i et slikt fellesskap? Det er å oppleve «hele Kristi fylde». Og til det trenger vi hverandre!
Det er mulig å være kristen helt alene. Mange mennesker som har blitt latterliggjort eller forfulgt, har måttet stå alene. Det er et sterkt vitnesbyrd om Guds kraft at menn og kvinner ikke bukker under for presset de utsettes for. Men likevel understreker Paulus en stor sannhet: vi opplever og åpenbarer Kristi fylde når vi arbeider sammen i fellesskap med hverandre.
`Les Ef 4,11–16. Hva må skje før Kristi fylde kan bli åpenbart i vårt fellesskap?`
`Hvordan er det vitnesbyrdet et fellesskap som åpenbarer Kristi fylde annerledes enn det den enkelte kan åpenbare av Kristi fylde? Hva har dette å si for den store konflikten? Se Ef 3,10.`
`Det er lett å være hyggelig når du er alene eller blant fremmede, men det er mye vanskeligere å være hyggelig mot folk du enten kjenner godt eller ikke liker. Når vi likevel viser disse menneskene godhet og vennlighet, er det et uimotståelig vitnesbyrd om sannheten om Gud.`
|
Go
|
UTF-8
| 1,069
| 2.59375
| 3
|
[] |
no_license
|
package nana
import (
"bytes"
"testing"
"time"
"github.com/DataDog/datadog-go/statsd"
"github.com/Sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
func TestNullMetricsClient(t *testing.T) {
assert := assert.New(t)
log := logrus.New()
log.Level = logrus.DebugLevel
log.Formatter = &logrus.TextFormatter{
DisableColors: true,
}
var output string
logBuffer := bytes.NewBufferString(output)
log.Out = logBuffer
metrics := &NullMetricsClient{log}
metrics.Gauge("gauge", float64(123), []string{"tag1", "tag2"}, 1)
assert.Contains(logBuffer.String(), "name=gauge rate=1 tags=\"[tag1 tag2]\" value=123")
metrics.Incr("incr", []string{"tag1", "tag2"}, 1)
assert.Contains(logBuffer.String(), "name=incr rate=1 tags=\"[tag1 tag2]\"")
metrics.ServiceCheck(&statsd.ServiceCheck{
Name: "sc",
Status: statsd.Critical,
})
assert.Contains(logBuffer.String(), "sc 2")
metrics.Timing("timing", time.Duration(45)*time.Millisecond, []string{"tag1", "tag2"}, 1)
assert.Contains(logBuffer.String(), "name=timing rate=1 tags=\"[tag1 tag2]\"")
}
|
C++
|
UTF-8
| 5,285
| 3.78125
| 4
|
[] |
no_license
|
#include "BSTree.h"
// default constructor
BSTree::BSTree()
{
root = nullptr;
}
// destructor, deallocate all memory in heap
BSTree::~BSTree()
{
empty(); // empties out tree
}
/*
* inserts a movie into the BST
* in sorted order.
*/
bool BSTree::insert(Movie *movie)
{
// check if object is null
if (movie == nullptr)
return false;
else if (isEmpty(root))
{ // tree is empty, place node at root
root = new Node;
root->data = movie;
root->left = nullptr;
root->right = nullptr;
}
else
{
Node *prev = new Node;
Node *tmp = root;
while (!isEmpty(tmp))
{ // traverse tree for insertion
prev = tmp;
if (*tmp->data < *movie)
tmp = tmp->right;
else if (*tmp->data > *movie)
tmp = tmp->left;
else
return false; // object is already in tree
}
tmp = new Node;
if (*prev->data < *movie)
{
prev->right = new Node;
prev->right = tmp;
}
else if (*prev->data > *movie)
{
prev->left = new Node;
prev->left = tmp;
}
tmp->data = movie; // add Movie to BST
tmp->left = nullptr;
tmp->right = nullptr;
}
return true;
}
// helper method to check if tree/subtree is empty
bool BSTree::isEmpty(Node *root) const
{
return root == nullptr;
}
/*
* displays each movie's information
* by calling their display().
*/
void BSTree::display() const
{
if (root == nullptr) // tree is empty
return;
// helper method to traverse tree in order
inOrderTraversal(root);
}
/*
* precondition: BSTree is not empty.
* postcondition: traverses the tree
* in order to output each movie's information.
*/
void BSTree::inOrderTraversal(Node *root) const
{
if (root->left != nullptr)
inOrderTraversal(root->left);
root->data->display();
if (root->right != nullptr)
inOrderTraversal(root->right);
}
// empties entire tree
void BSTree::empty()
{
while (!isTreeEmpty())
{
// remove node, one at a time
remove();
}
}
// removes smallest node from BSTree
void BSTree::remove()
{
//go as far left as possible
// check if node is leaf, delete if so
// else if child, copy child to node and delete child
Node *tmp = root;
while (tmp->left != nullptr) // find smallest node
tmp = tmp->left;
if (tmp->left == nullptr && tmp->right == nullptr)
{ // node is a leaf
delete tmp;
tmp = nullptr; // no dangling pointer
}
else
{ // node has right child
tmp->data = tmp->right->data;
delete tmp->right;
tmp->right = nullptr; // no dangling pointer
}
}
// checks if tree is empty
bool BSTree::isTreeEmpty() const
{
return root == nullptr;
}
/*
* searches for movie in BST and
* sets Movie* passed in parameter
* to the Node* pointing to the movie.
*/
bool BSTree::search(Movie *&movie) const {
Node* tmp = root;
while(tmp != nullptr) {
if(*tmp->data == *movie) {
movie = tmp->data;
return true;
}
else if(*tmp->data < *movie)
tmp = tmp->right;
else
tmp = tmp->left;
}
return false; // movie was not found in tree
}
/*
* helper method for checkAlternative() that returns a string that
* has the concatenation of all actor last names for alternative movies.
*/
string BSTree::getLastNames(const Node* root, const Classic *&film) const {
if(root != nullptr) {
const Classic& movie = static_cast<const Classic &>(*root->data);
if(film->isAlternative(movie)) // concatenate strings of alternative last names
return movie.getActorLastName() + " " + getLastNames(root->left, film) + " " +
getLastNames(root->right, film);
}
}
/*
* helper method for checkAlternative() that totals up
* stock of all alternative Classic movies.
*/
int BSTree::getTotalStock(const Node* root, const Classic* &film) const {
if(root != nullptr) {
const Classic& movie = static_cast<const Classic &>(*root->data);
if(film->isAlternative(movie))
return root->data->getStock() + getTotalStock(root->right, film) +
getTotalStock(root->left, film); // recursive call to get total of all alt films stocks
}
return 0; // don't add stock of movie that isn't an alternative
}
/*
* prints a message to the user letting them know if there
* are altrenatives of a movie and who the major actor is
* for each one.
*/
void BSTree::checkAlternative(const Classic* &film) const {
if(getTotalStock(root, film) == 0)
cout << "We are out of stock of " + film->getTitle() << endl;
else {
cout << "There are " + getTotalStock(root, film) << " available copies of " <<
film->getTitle() << "." << endl;
cout << "Here are the available alternatives." << getLastNames(root, film) << endl;
}
}
|
SQL
|
UTF-8
| 153
| 2.890625
| 3
|
[] |
no_license
|
CREATE PROCEDURE sunnyHolidays()
BEGIN
SELECT holiday_date AS ski_date
FROM holidays
INNER JOIN weather ON holiday_date = sunny_date;
END
|
Python
|
UTF-8
| 2,810
| 3.25
| 3
|
[] |
no_license
|
name = ["mohan", "raj", "harsh"]
# print(name)
# number=[23,45,29,59,34]
# print(number)
# mixed=["mohan","raj","harsh",23,45,29,59,34]
# print(mixed)
# mixed_int=[23,45,29,59,34]
# mixed_int.sort()
# print(mixed_int)
# name.append("sohan")
# print(name)
# name.insert(2,"ravi")
# print(name)
# name.extend([2,3,4,5,6,7,8])
# print(name)
# name.pop()
# print(name)
# name.remove("ravi")
# print(name)
# name.clear()
# print(name)
# name.sort()
# print(name)
# copy_name=name.copy()
# print(name)
# print(copy_name)
# copy_name[0]='sohan'
# print(copy_name)
# print(name)
# # # name.sort()
# # # print(name)
# # # print(copy_name)
# # #############################
# # ######################
# mylist=[1,1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,4]
# mylist=set([1,1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,4])
# print(mylist)
# # #######################
l = [3, 7, [1, 4, 'hello']]
l[2][2] = 'goodbye'
print(l)
# tupledict=dict(name="raju",age=23,role="baaa")
# print(tupledict)
# s={1,2,2,3,43,4,45,5,5,1,2,3}
# print(s)
# # ###############################33
number = [1, 2, 3, 4, 5]
square = [i ** 2 for i in number]
print(square)
# #
number = [1, 2, 3, 4, 5]
squre = [x ** 2 for x in number if x % 2 == 1]
print(squre)
# #
# # number_list = [ x**2 for x in range(20) if x % 2 == 0]
# # print(number_list)
# #
my_list = [('a', 232),
('b', 343),
('c', 543),
('d', 23)]
# # #output should be [('a', 'b', 'c', 'd'), (232, 343, 543, 23)]
# #
c = list(zip(*my_list))
print(c)
# #
# #
# mixed=["mohan","23","raj","34"]
# mixed.sort()
# print(mixed)
# #
#
# del name[3]
# print(name)
# #
# # #name.sort()
# # #print(name)
# # number.sort()
# # print(number)
# # mixed.sort()
# # print(mixed)
# # print(sorted(name))
# # print(name)
# #
# # name.reverse()
# # print(name)
# #
# # cpoy_1=name.copy()
# # print(cpoy_1)
# # name[1]="madhuri"
# # print(name)
tuple
# tup1 = ('Robert', 'Carlos','1965','Terminator 1995', 'Actor','Florida')
# tup2 = (1,2,3,4,5,6,7)
# print(tup1[0])
# print(tup2[1:4])
# #Packing and Unpacking
# x = ("webtrackker", 20, "Education") # tuple packing
# (company, emp, profile) = x # tuple unpacking
# print (company)
# print (emp)
# print (profile)
# print(x)
# #Comparing tuples
# case 1
a = (5, 6)
b = (1, 4)
if (a > b):
print("a is bigger")
else:
print("b is bigger")
#
# #case 2
a = (5, 6)
b = (5, 4)
if (a > b):
print("a is bigger")
else:
print("b is bigger")
# #case 3
a = (5, 6)
b = (6, 4)
if (a > b):
print("a is bigger")
else:
print("b is bigger")
# #Tuples and dictionary
dict = {'x': 100, 'y': 200}
b = dict.items()
print(b)
# #Slicing of Tuple
x = ("a", "b", "c", "d", "e")
print(x[2:4])
|
C++
|
UTF-8
| 3,774
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
#include "UI.h"
#include "Scene.h"
#include "LevelManager.h"
#include "Level.h"
#include "ShaderManager.h"
#include "PredefinedWordFactory.h"
#include "ButtonFactory.h"
#include "UIAdapter.h"
void UI::init() {
selectedButton = -1;
backgroundTexture.loadFromFile("images/UI/black_frame.png", TEXTURE_PIXEL_FORMAT_RGBA);
backgroundTexture.setMinFilter(GL_NEAREST);
backgroundTexture.setMagFilter(GL_NEAREST);
background = Sprite::createSprite(glm::vec2(UI_WIDTH, UI_HEIGHT), glm::vec2(1., 1.), &ShaderManager::getInstance().getShaderProgram(), &backgroundTexture);
jobName = PredefinedWordFactory::instance().createJobWord();
outWord = PredefinedWordFactory::instance().createInfoWord("OUT");
numberOutLemmings.init();
inWord = PredefinedWordFactory::instance().createInfoWord("IN");
numberInLemmings.init();
timeWord = PredefinedWordFactory::instance().createInfoWord("TIME");
time.init();
selectFrameTexture.loadFromFile("images/UI/white_frame.png", TEXTURE_PIXEL_FORMAT_RGBA);
selectFrameTexture.setMinFilter(GL_NEAREST);
selectFrameTexture.setMagFilter(GL_NEAREST);
selectFrame = Sprite::createSprite(glm::vec2(17, 25), glm::vec2(17./32, 25./32), &ShaderManager::getInstance().getShaderProgram(), &selectFrameTexture);
for (int i = 0; i < NUM_BUTTONS; ++i) {
buttons[i] = ButtonFactory::instance().createButton(i);
buttons[i].setNum(i);
}
setPosition(glm::vec2(0, 0));
}
void UI::render() {
background->render();
if (jobName != NULL) {
jobName->render();
}
outWord->render();
numberOutLemmings.render();
inWord->render();
numberInLemmings.render();
timeWord->render();
time.render();
for (int i = 0; i < NUM_BUTTONS; ++i) {
buttons[i].render();
}
if (selectedButton != -1) {
selectFrame->render();
}
}
void UI::update()
{
for (int i = 0; i < 8; ++i) {
int jobCount = LevelManager::getInstance().getJobCount(i);
buttons[i + 2].setNum(jobCount);
}
buttons[Button::ButtonNames::MINUS_BUTTON].setNum(LevelManager::getInstance().getMinReleaseRate());
buttons[Button::ButtonNames::PLUS_BUTTON].setNum(LevelManager::getInstance().getReleaseRate());
numberOutLemmings.displayNum(LevelManager::getInstance().getNumLemmingsAlive());
numberInLemmings.displayPercentage(LevelManager::getInstance().getPercentageSavedLemmings());
time.displayTime(LevelManager::getInstance().getRemainingTime());
}
void UI::setPosition(glm::vec2 position) {
this->position = position;
background->setPosition(position);
jobName->setPosition(position + glm::vec2(0, 1));
outWord->setPosition(position + glm::vec2(113, 1));
numberOutLemmings.setPosition(position + glm::vec2(140, 1));
inWord->setPosition(position + glm::vec2(180, 1));
numberInLemmings.setPosition(position + glm::vec2(200, 1));
timeWord->setPosition(position + glm::vec2(247, 1));
time.setPosition(position + glm::vec2(280, 1));
for (int i = 0; i < NUM_BUTTONS; ++i) {
buttons[i].setPosition(position + glm::vec2(16 * i + 1, 13));
}
}
int UI::getButtonIndexInPos(int posX, int posY)
{
for (int i = 0; i < NUM_BUTTONS; ++i) {
int leftPos = position.x + 16 * i + 1;
int rightPos = position.x + 16 * i + 17;
if (leftPos <= posX && posX < rightPos && posY >= position.y + 13) {
if (i != Button::PAUSE_BUTTON && Scene::getInstance().isPaused()) {
return -1;
}
else {
return i;
}
}
}
return -1;
}
void UI::changeSelectedButton(int selectedButton)
{
this->selectedButton = selectedButton;
selectFrame->setPosition(position + glm::vec2(16*selectedButton,12));
}
int UI::getSelectedButtonJobCount()
{
return Level::currentLevel().getLevelAttributes()->jobCount[selectedButton - 2];
}
void UI::changeDisplayedJob(string lemmingJobName)
{
UIAdapter::getInstance().changeJobName(jobName, lemmingJobName);
}
|
C++
|
UTF-8
| 2,382
| 3.375
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
int bin2dec()
{
int num,cal, dec = 0, i = 0;
printf("Enter binary number: ");
flag: fflush(stdin);
scanf("%d",&num);
fflush(stdin);
if(num == 0 || num%10 == 2 ||num%10 == 3 || num%10 == 4 || num%10 == 5 || num%10 == 6 || num%10 == 7 ||num%10 ==8 || num%10 == 9)
{
num = 0;
printf("\nWrong format!\n");
printf("Re-enter the binary: ");
goto flag;
}
while (num > 0)
{
dec = dec + (num % 10) * pow(2,i++);
num = num / 10 ;
}
printf("Decimal number is: %d\n",dec);
printf("Press any key to continue.\n");
}
int oct2dec()
{
long int oct, dec = 0;
int i = 0;
printf("Enter any octal number: ");
flag: fflush(stdin);
scanf("%d",&oct);
fflush(stdin);
if(oct == 0 || oct%10 == 9 || oct%10 == 8)
{
oct = 0;
printf("\nWrong format!\n");
printf("Re-enter the binary: ");
goto flag;
}
while (oct != 0)
{
dec = dec +(oct % 10)* pow(8, i++);
oct = oct / 10;
}
printf("Decimal number is: %d\n",dec);
printf("Press any key to continue.\n");
}
int hex2dec()
{
long int hex, dec = 0;
int i = 0;
printf("Enter any hexadecimal number: ");
flag: fflush(stdin);
scanf("%d",&hex);
fflush(stdin);
if(hex == 0 || hex%10 == 11 || hex%10 == 10 || hex%10 == 12 || hex%10 == 13 || hex%10 == 14 || hex%10 == 15)
{
hex = 0;
printf("\nWrong format!\n");
printf("Re-enter the binary: ");
goto flag;
}
while (hex != 0)
{
dec = dec +(hex % 10)* pow(16, i++);
hex = hex / 10;
}
printf("Decimal number is: %d\n\n",dec);
printf("Press any key to continue.\n");
}
int main()
{
int choice;
do
{
system("cls");
printf("1. Convert binary number to decimal number\n");
printf("2. Convert octal number to decimal number\n");
printf("3. Convert hexadecimal number to decimal number\n");
printf("4. Exit\n");
choice = getch();
switch(choice)
{
case '1' :
bin2dec();
break;
case '2' :
oct2dec();
break;
case '3' :
hex2dec();
break;
case '4': printf("Leaving\n");
break;
default: printf("\nWrong format\n");
break;
}
getch();
}
while(choice != '4');
}
|
Markdown
|
UTF-8
| 3,119
| 2.515625
| 3
|
[] |
no_license
|
Projet de PCD 2019.
Membres du groupe :
FAZOUANE Souhail
REHIOUI Walid
HMIZA Jaber
LATA Warren
Release Day 1:
* Mise en place de la vue principale
* Recherche d'un flux RSS et sur le parsing du XML correspondant
* Tester le lancement du 1er Media
* Conception du Podcast (Ajout des classes du Modèle)
* Ajout des classes des vues( Combination FXML/JavaFX)
Release Day 2:
* Réalisation d'une base de donnée en dur(format JSON) vu qu'on avait pas d'accès à l' API
* Liaison entre Vue et modèle (PodcastApp)
* Liaison base de donnée et modèle (iTunes data)
* Installation gradle
* Visualisation de l'interface (PodcastView et EpisodeView) => Update de l'interface EpisodeView selon le Podcast sélectionné
* Ajout lecture d'un Média se trouvant en local (Bouton Openfile)
* Ajout d'une version prototype des fonctionnalités correspondantes au MediaPlayer (Play/Pause/Speed ratio/Stop)
* récupération de la clé pour accéder à l'api partagée (ListenNotes)
Release Day 3:
* Ajout de la classe PodcastApiFetcher qui récupère les flux RSS à travers une requête de l'utilisateur
* Optimisation de l'interface Graphique (coloration)
* Ajout D'un bouton Download qui permet le téléchargement en local Des épisodes d'un podcast sans bloquer l'interface (Thread)
* Modification de la classe PodcastApiFetcher pour qu'elle donne des flux RSS correspondant à une requête de recherche selon un mot-clé ou un genre ou la langue
* Modification de la classe Podcast et PodcastFinder pour qu'elle puisse inclure aussi l'image d'un Podcast, son langage et sa description.
* Modification de la classe PodcastApp pour qu'elle sOIT compatible avec les fonctionnalités requises (mode préférence,mode accueil, mode recherche).
Release Day 4:
* Réussite des requêtes faites avec l'API : ( affichage des 5 podcasts populaires et récents au hasard, en mode actualité + chercher les flux rss correspondant
à des critères spécifiés par l'utilisateur. )
* Travail sur l'interface graphique : amélioration et liaison des fonctionalités du model à chaque vue) .
* Ajout de la fonctionalité 'ajouter' ou 'supprimer' des podcasts dans la liste de préférence.
* Ajout de la fonctionalité mediaplayer d'un épisode d'un podcast (barre d'avancement de la vidéo + slider pour controler le son. );
Release Final:
* Amélioration des interfaces pour une meilleur visualisation.
* Correction des derniers bugs de l'application (affichage inutile, réduction du tempsd'éxécution .
* Ajout d'un média player interactif pour la lecture des audios et videos
Lancement:
Notre application est munie d'un gradle. Pour la runner il suffit donc soit de faire un ./gradlew run dans le répertoire de notre application Fortify(cd Fortify).
Ou de faire un ./gradlew jar ( en étant toujours dans le répertoire Fortify) et lancer par la suite java -jar /build/libs/PodcastApp-Fortify.jar.
Ou de lancer ./gradlew run
Commentaire: Pour faire une recherche sur l'application il faut obligatoirement spécifier un mot-clé(qui peut s'apparenter à un thème,une personne, un sujet etc...)
|
JavaScript
|
UTF-8
| 3,180
| 3.546875
| 4
|
[] |
no_license
|
var Cards = require("./cards.js");
var inquirer = require("inquirer");
var dataFile = require("./data.txt");
var fs = require("fs");
var correctCounter = 0;
var wrongCounter = 0;
var x = 0;
function start() {
inquirer.prompt([{
type: "list",
name: "userChoice",
message: "Would like to go for the quiz",
choices: ["Yes I would like to take the quiz", "No, Thank I want to quit"]
}]).then(function(choice) {
if (choice.userChoice === "Yes I would like to take the quiz") {
quiz('data.txt', x);
} else {
inquirer.prompt([{
type: "list",
name: "confirm",
message: "Are you sure?",
choices: ["Yes", "No"]
}]).then(function(confirm) {
if (confirm.confirm === "Yes") {
console.log("Thank you, welcome back any time")
} else {
quiz("data.txt", x)
}
});
}
})
}
var quiz = function(dataFile, x) {
fs.readFile(dataFile, "utf8", function(error, data) {
var data = JSON.parse(data);
if (x < data.length) {
if (data[x].hasOwnProperty("front")) {
var gameCard = new Cards(data[x].front, data[x].back);
var gameQuestion = gameCard.front;
var gameAnswer = gameCard.back.toLowerCase();
}
inquirer.prompt([{
name: "question",
message: gameQuestion,
validate: function(value) {
if (value.length > 0) {
return true;
}
return 'Please choose an answer, or (ctr+c) to quit';
}
}]).then(function(answers) {
if (answers.question.toLowerCase() === gameAnswer) {
console.log('Correct!');
correctCounter++;
x++;
quiz(dataFile, x);
} else {
gameCard.printAnswer();
wrongCounter++;
x++;
quiz(dataFile, x);
}
})
} else if (wrongCounter < correctCounter) {
console.log('*******************************')
console.log(' Congratulation .. you WON ', "\n Your result: ");
console.log(' * Correct:', correctCounter, '\n * Wrong: ', wrongCounter);
console.log('Thank you for taking the quiz');
console.log('*******************************')
correctCounter = 0;
wrongCounter = 0;
} else {
console.log('*******************************')
console.log('Sorry .. you lost ', "\n Your result is: ");
console.log(' * Correct:', correctCounter, '\n * Wrong: ', wrongCounter);
console.log('Thank you for taking the quiz');
console.log('*******************************')
correctCounter = 0;
wrongCounter = 0;
}
});
};
start();
// quiz('data.txt', x);
|
JavaScript
|
UTF-8
| 4,008
| 2.640625
| 3
|
[] |
no_license
|
var usrId;
var btnPress;
var addDlg;
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
$(document).ready(function() {
addDlg = $("#dialog").dialog({
autoOpen: false,
top: 40,
height: "auto",
modal: true,
buttons: {
Ok: function() {
if(btnPress == "add")
add();
else if(btnPress == "update")
update();
},
Cancel: function() {
addDlg.dialog( "close" );
}
},
open: function() {
$("#code").focus();
},
close: function() {
$("#add-form")[0].reset()
}
});
$("#row tr").click(function() {
selectRow($(this).attr("id"));
});
$("#add-btn").click(function() {
btnPress = "add";
openDlg("add");
$("#code").focus();
});
$("#update-btn").click(function() {
btnPress = "update";
perpareUpdate();
});
$("#delete-btn").click(function() {
btnPress = "delete";
del();
});
});
function selectRow(id) {
if(usrId)
$("#" + usrId).removeClass("selected-row");
usrId = id;
$("#" + usrId).addClass("selected-row");
$("#update-btn").prop("disabled", false);
$("#delete-btn").prop("disabled", false);
}
function openDlg(type) {
if(type == "add") {
$(".ui-widget-header").css("background", "#9ECFDE");
addDlg.dialog("option", "title", "Add User Master");
addDlg.dialog("open");
}
else if(type == "update") {
$(".ui-widget-header").css("background", "#DDFA9D");
addDlg.dialog("option", "title", "Update User Master");
addDlg.dialog("open");
}
}
function add() {
var code = $("#code").val();
var name = $("#name").val();
var roId = $("#roId").val();
var roName = $("#roId option:selected").text();
var password = $("#password").val();
if(roId == 0) {
alert("Please select Role.");
return;
}
$.ajax({
type:"PUT",
url:"rest/usermasterWs",
data: {
"code": code,
"name": name,
"password": password,
"roId": roId
},
success:function(result) {
if(numberRegex.test(result)) {
$("#row").append("<tr id='" + result + "'><td>" + result + "</td><td>" + code + "</td><td>" + name + "</td><td>"
+password + "</td><td id='r" + roId + "'>" +
roName + "</td></tr>");
$("#" + result).click(function() {
selectRow(result);
});
$("#" + result).click();
addDlg.dialog("close");
}
else alert("Wrong format value!");
}
});
}
function perpareUpdate() {
var e = $("#" + usrId);
$("#usrId").val(usrId);
$("#code").val($(e).children().eq(1).html());
$("#name").val($(e).children().eq(2).html());
$("#password").val($(e).children().eq(3).html());
var roName = $(e).children().eq(4).html();
$("select option").filter(function() {
//may want to use $.trim in here
return $(this).text() == roName;
}).prop('selected', true);
openDlg("update");
}
function update() {
var usrId = $("#usrId").val();
var code = $("#code").val();
var name = $("#name").val();
var roName = $("#roId option:selected").text();
var password = $("#password").val();
var roId = $("#roId").val();
if(roId == 0) {
alert("Please select role.");
return;
}
$.ajax({
type:"POST",
url:"rest/usermasterWs",
data: {
"usrId": usrId,
"code": code,
"name": name,
"password": password,
"roId": roId
},
success:function(result) {
if(result == "true") {
var e = $("#" + usrId);
$(e).children().eq(1).html(code);
$(e).children().eq(2).html(name);
$(e).children().eq(3).html(password);
$(e).children().eq(4).html(roName);
addDlg.dialog("close");
}
else alert("Cannot update User Master Code. " + $("#code").val() + "!");
}
});
}
function del() {
var code = $("#" + usrId).children().eq(0).html();
if(confirm("Do you want to delete User Master Code. " + code + "?")) {
$.ajax({
type:"DELETE",
url:"rest/usermasterWs",
data: {
"usrId": usrId
},
success:function(result) {
if(result == "true") {
$("#" + usrId).remove();
addDlg.dialog("close");
}
else alert("Cannot remove User Master Code. " + code + "!");
}
});
}
}
|
JavaScript
|
UTF-8
| 1,175
| 2.640625
| 3
|
[] |
no_license
|
export default {
data() {
return {
// 所有的商品分类
catelist: [],
// 级联选择框的对应关系
cascaderProps: {
value: 'cat_id',
label: 'cat_name',
children: 'children'
},
// 选中的商品分类
selectedCate: [],
// 被选中的 tab 页签的名字
activeName: 'first'
}
},
created() {
this.getCateList()
},
methods: {
// 获取所有分类的数据
async getCateList() {
const { data: res } = await this.$http.get('categories?type=3')
if (res.meta.status !== 200) return this.$message.error('获取分类数据失败!')
this.catelist = res.data
},
// 每当分类选择框选择项发生变化,都会触发这个事件处理函数
handleCateChange() {
if (this.selectedCate.length !== 3) {
this.selectedCate = []
}
console.log(this.selectedCate)
},
// 每当点击了不同的页签,都会触发这个函数
handleTabClick() {
// 只要发生了 tab 栏的切换,就立即打印当前被选中的 tab 栏 页签的 名称
console.log(this.activeName)
}
}
}
|
Python
|
UTF-8
| 1,228
| 3.625
| 4
|
[
"MIT"
] |
permissive
|
"""
Utilities for use with pandas.DataFrame
"""
import pandas as pd
def summary(data=None, groups=None, column=None, *args):
"""
Create a table of descriptive statistics of the underlying data. Function will calculate
the percentiles in `args` in addition to the min, max, mean, std, and count. `summary` is
similar to `pandas.describe` but works with grouped data and populates the data in columns
rather than rows
:param data: DataFrame of data
:param groups: columns to group by
:param column: column to calculate
:param args: percentiles to apply
:return: DataFrame
"""
if data is None or column is None:
return data
df = data[groups].drop_duplicates()
df.set_index(groups, inplace=True)
df["count"] = data.groupby(groups)[column].count()
df["min"] = data.groupby(groups)[column].min()
df["mean"] = data.groupby(groups)[column].mean()
df["max"] = data.groupby(groups)[column].max()
df["std"] = data.groupby(groups)[column].std()
for p in args:
try:
p = float(p)
except ValueError:
next
col = "p" + str(p)
df[col] = data.groupby(groups)[column].quantile(p)
return df
|
Java
|
UTF-8
| 2,905
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
package io.github.oliviercailloux.j_voting.preferences;
import com.google.common.graph.MutableGraph;
import io.github.oliviercailloux.j_voting.Alternative;
/**
* <p>
* A mutable preference keeps two graphs: the one representing the information
* received directly from the voter, not necessarily transitive or reflexive,
* given by {@link #asMutableGraph()}; and the one we deduce, which is at all
* times transitively closed and reflexive, given by {@link #asGraph()}.
* </p>
*
* <p>
* To improve performance, avoid calling {@link #asGraph()} before modifying the
* preference, as this obliges this class to maintain the transitive closure.
* </p>
*
* <p>
* The transitive closure of the graph must be interpreted with caution while it
* is building, even when the graph is mutated only by adding edges (never by
* removing any). When the mutable graph has an edge from a to b but not from b
* to a, the transitive closure will seem to say that a is strictly preferred to
* b, which we can’t deduce: this is valid when the preferential information in
* input is complete (otherwise, perhaps b ≥ a in supplement to a ≥ b and they
* are tied).
* </p>
* <p>
* This interface does not promote any specific notion of equality. The
* alternative would have been, either, to define a specific notion of equality
* for a mutable preference (having the same mutable graph), or re-use the
* natural notion of equality for a general preference, that is, having the same
* transitive graph. The second one would have been surprising, as two mutable
* preferences with different mutable graphs could have ended up being equal.
* And, in any case, it is not generally considered a
* <a href="https://stackoverflow.com/q/9089335">good idea</a> to rely on
* equality of a mutable object.
* </p>
*/
public interface MutablePreference extends Preference {
/**
* This graph is not necessarily transitive and not necessarily reflexive.
*
*/
public MutableGraph<Alternative> asMutableGraph();
/**
* Adds an alternative to the Preference. This alternative is not preferred to
* any other of the preference, it is being added isolated.
*
* @param alternative to add to the preference.
*/
public void addAlternative(Alternative alternative);
/**
* Adds an edge from an alternative a1 to an alternative a2 and from a2 to a1.
* If one of them is not in the graph, they are added. a1 and a2 are ex-aequo.
*
* @param a1 first alternative
* @param a2 second alternative
*/
public void addEquivalence(Alternative a1, Alternative a2);
/**
* Adds an edge from an alternative a1 to an alternative a2, so that a1 is as
* least as good as a2 (a1 >= a2). Those that are not yet in the graph are
* added.
*
* @param a1 preferred alternative to a2
* @param a2 "lower" alternative
*/
public void setAsLeastAsGood(Alternative a1, Alternative a2);
}
|
C++
|
UTF-8
| 1,425
| 3.734375
| 4
|
[] |
no_license
|
#include <algorithm>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <cmath>
using namespace std;
template <uint32_t DIM>
class Queue {
public:
Queue() : array(), head(0), tail(0) {}
Queue(const Queue<DIM> & rhs) : head(rhs.head), tail(rhs.tail) {
for (uint32_t i = 0; i < DIM; i++)
array[i] = rhs[i];
}
Queue<DIM> & operator=(const Queue<DIM> & rhs) {
if (&rhs != this) {
Queue<DIM> tmp(rhs);
swap(rhs);
}
return *this;
}
const int operator[](uint32_t index) const { return array[index]; }
int operator[](uint32_t index) { return static_cast<const Queue<DIM>*>(this)->operator[](index); }
inline bool isEmpty() { return head == tail; }
inline bool isFull() { return tail + 1 == head || (head == 0 && tail == DIM); }
void enqueue(int val) {
if (isFull()) {
cout << "The queue is full.\n";
return;
}
array[tail++] = val;
tail = tail == DIM + 1 ? 0 : tail;
}
int dequeue() {
if (isEmpty()) {
cout << "The queue is empty.\n";
return -1;
}
int res = array[head++];
head = head == DIM + 1 ? 0 : head;
return res;
}
private:
void swap(Queue<DIM> & rhs) {
swap(array, rhs.array);
swap(head, rhs.head);
swap(tail, rhs.tail);
}
int array[DIM+1];
uint32_t head;
uint32_t tail;
};
int main() {
Queue<3> a;
for (int i = 0; i < 3; i++) {
a.enqueue(i);
}
for (int i = 0; i < 3; i++) {
cout << a.dequeue() << endl;
}
}
|
Java
|
UTF-8
| 3,661
| 2.125
| 2
|
[] |
no_license
|
package com.property.tax.controller;
import com.property.tax.TaxApplication;
import com.property.tax.model.SelfAssessmentForm;
import com.property.tax.model.ZonalReport;
import com.property.tax.service.PropertyTaxService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
@Controller
public class PropertyTaxController {
@Autowired
PropertyTaxService propertyTaxService;
private static final Logger logger = LogManager.getLogger(PropertyTaxController.class);
@RequestMapping("/")
public String getIndexPage() {
return "index";
}
@RequestMapping("/international")
public String getInternationalPage() {
return "index";
}
@RequestMapping("/selfAssessment")
public String selfAssessment(Model model){
logger.info("Inside selfAssessment method");
SelfAssessmentForm selfAssessmentForm = new SelfAssessmentForm();
model.addAttribute("selfAssessmentForm", selfAssessmentForm);
model.addAttribute("zones", propertyTaxService.getAllZones());
model.addAttribute("propertyTypes", propertyTaxService.getAllPropertyType());
model.addAttribute("statusTypes", propertyTaxService.getAllStatus());
return "selfAssessment";
}
@RequestMapping("/zonalReport")
public String zonalReport(Model model){
logger.info("Inside zonalReport method");
List<ZonalReport> zonalReportList = propertyTaxService.getZonalReport();
List<Integer> yearsList = zonalReportList.stream()
.map(ZonalReport::getYearOfAssessment)
.distinct()
.collect(Collectors.toList());
model.addAttribute("yearsList", yearsList);
model.addAttribute("zonalReportList", zonalReportList);
return "zonalReport";
}
@RequestMapping(value = "/calculateTax", method = RequestMethod.POST)
public ResponseEntity calculateTax(@RequestBody SelfAssessmentForm selfAssessmentForm){
logger.info("The value of zonal class -->"+selfAssessmentForm.getZonalClassification());
logger.info("The value property type -->"+selfAssessmentForm.getPropertyDescription());
logger.info("The value status -->"+selfAssessmentForm.getStatus());
logger.info("The value construction year -->"+selfAssessmentForm.getBuildingConstructionYear());
logger.info("The value buildup area -->"+selfAssessmentForm.getBuildUpArea());
double payableTax = propertyTaxService.calculatePayableTax(selfAssessmentForm);
return new ResponseEntity(payableTax, HttpStatus.OK);
}
@RequestMapping("/payTax")
public String payTax(@Valid SelfAssessmentForm selfAssessmentForm, BindingResult result, Model model){
if(result.hasErrors()){
model.addAttribute("zones", propertyTaxService.getAllZones());
model.addAttribute("propertyTypes", propertyTaxService.getAllPropertyType());
model.addAttribute("statusTypes", propertyTaxService.getAllStatus());
return "selfAssessment";
}
propertyTaxService.saveSelfAssessment(selfAssessmentForm);
return "index";
}
}
|
Java
|
UTF-8
| 329
| 2.28125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.nutz.walnut.ext.data.fake.impl;
import org.nutz.walnut.ext.data.fake.WnFaker;
public class WnStaticFaker implements WnFaker<Object> {
private Object value;
public WnStaticFaker(Object value) {
this.value = value;
}
@Override
public Object next() {
return this.value;
}
}
|
Java
|
UTF-8
| 276
| 2.171875
| 2
|
[] |
no_license
|
package org.nardogames.rattlesnake.common.keyboard;
public interface IListenToKeyEvents {
public boolean listensToKey(int key);
void notifyKeyPushed(int key);
void notifyKeyIsDown(int key, float deltaTime);
void notifyKeyReleased(int key, long timeDown);
}
|
Markdown
|
UTF-8
| 947
| 2.53125
| 3
|
[] |
no_license
|
## AWS Training Manual
Brought to you by we45

## Objective
This repository contains the list of exercises intended for the "Hacking and Defending your applications in AWS" workshop presented at the Information Security Symposium at the University of California (Davis), June 2019.
These hands-on labs should give a high level introduction to some of the popular AWS services used by developers and how to leverage security best practices and simulate vulnerabilities that could potentially compromise sensitive information within the apps.
### Contents
The following list of topics would be the key focus areas of this workshop.
1. AWS Cli
2. Terraform Intro
3. EC2
4. IAM
5. Vulnerability Assessment within AWS using Inspector
6. S3
7. Logging & Monitoring using Cloudwatch/Cloudtrail
#### Contact Us
[](https://twitter.com/we45)
[](https://github.com/we45)
|
C++
|
UTF-8
| 3,516
| 2.90625
| 3
|
[] |
no_license
|
/**
Check if a directed Graph is a Tree or not
Insights
========
1 . A tree has only 1 root
2 . A vertex can't be visited more than once
(If it is visited more than once , then there is 2 paths from the root .
But in a tree there is always only 1 path to a vertex)
One extra condition for Undirected Graph : only a parent can be visited twice .
3. After DFS from the root , all vertex will be explored .
Common Mistake
==============
1.
bool dfs(int u)
{
vis[u] = true;
for(int v:adj[u])
{
if(!vis[v]) return dfs(v);
else return false;
}
return true;
}
In DFS , Don't write
return dfs(v)
Then it will explore only 1 child and return it's value .
One way to mitigate is return , only when false . This way we are sure .
bool dfs(int u)
{
vis[u] = true;
for(int v:adj[u])
{
if(!vis[v])
{
if(dfs(v)==false)
return;
}
else return false;
}
return true;
}
Best is to explore all the vertexes
**/
/** Which of the favors of your Lord will you deny ? **/
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define PII pair<int,int>
#define PLL pair<LL,LL>
#define F first
#define S second
#define ALL(x) (x).begin(), (x).end()
#define READ freopen("alu.txt", "r", stdin)
#define WRITE freopen("vorta.txt", "w", stdout)
#ifndef ONLINE_JUDGE
#define DBG(x) cout << __LINE__ << " says: " << #x << " = " << (x) << endl
#else
#define DBG(x)
#endif
template<class T1, class T2>
ostream &operator <<(ostream &os, pair<T1,T2>&p);
template <class T>
ostream &operator <<(ostream &os, vector<T>&v);
template <class T>
ostream &operator <<(ostream &os, set<T>&v);
inline void optimizeIO()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
const int nmax = 1e6+7;
vector<int>adj[nmax];
vector<int>in(nmax);
vector<bool>vis(nmax,0);
map<int,int>m;
bool dfs(int u) /// is Tree
{
vis[u] = true;
bool ok = true;
for(int v:adj[u])
{
if(!vis[v])
ok &= dfs(v);
else
ok = false;
}
return ok;
}
int main()
{
optimizeIO();
bool tree = true;
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
adj[a].push_back(b);
}
int rt_cnt = 0;
int rt = 0;
for(int i=1; i<=n; i++)
{
if(in[i]==0)
{
rt_cnt++;
rt = i;
}
}
if(rt_cnt!=1) tree = false;
else
{
tree = dfs(rt);
for(int i=1; i<=n; i++)
if(!vis[i])
tree = false;
}
if(tree) cout<<"Tree"<<endl;
else cout<<"Not a tree"<<endl;
return 0;
}
/**
6 8 5 3 5 2 6 4
5 6 0 0
8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0
3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1
53 says: u = 5
54 says: v = 1
53 says: u = 1
54 says: v = 2
53 says: u = 5
54 says: v = 3
53 says: u = 3
54 says: v = 2
53 says: u = 3
54 says: v = 4
53 says: u = 5
54 says: v = 6
**/
template<class T1, class T2>
ostream &operator <<(ostream &os, pair<T1,T2>&p)
{
os<<"{"<<p.first<<", "<<p.second<<"} ";
return os;
}
template <class T>
ostream &operator <<(ostream &os, vector<T>&v)
{
os<<"[ ";
for(int i=0; i<v.size(); i++)
{
os<<v[i]<<" " ;
}
os<<" ]";
return os;
}
template <class T>
ostream &operator <<(ostream &os, set<T>&v)
{
os<<"[ ";
for(T i:v)
{
os<<i<<" ";
}
os<<" ]";
return os;
}
|
Java
|
UTF-8
| 516
| 1.835938
| 2
|
[] |
no_license
|
package com.bpmnengine.data;
import com.bpmnengine.model.Activity;
import com.bpmnengine.model.CatchEvent;
/**
* @author André Waloszek
*/
public interface DataContext {
void executeDataInputAssociations();
void executeDataOutputAssociations();
void setDataObject(String id, Object value);
Object getDataObject(String id);
DataContextAccess createDataContextAccess();
DataContext createDataContext(Activity activity);
CatchEventDataContext createDataContext(CatchEvent catchEvent);
}
|
Python
|
UTF-8
| 495
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
# pylint: disable=missing-docstring
import asyncio
async def bla1():
await asyncio.sleep(1)
async def bla2():
await asyncio.sleep(2)
async def combining_coroutine1():
await bla1()
await bla2()
async def combining_coroutine2():
future1 = bla1()
future2 = bla2()
await asyncio.gather(future1, future2)
def do_stuff():
loop = asyncio.get_event_loop()
loop.run_until_complete(combining_coroutine1())
loop.run_until_complete(combining_coroutine2())
|
C
|
UTF-8
| 543
| 2.640625
| 3
|
[] |
no_license
|
#ifndef TVM_MEMORY_H_
#define TVM_MEMORY_H_
#include <stdint.h>
#include <stddef.h>
#define MIN_MEMORY_SIZE (64 * 1024 * 1024) /* 64 MB */
typedef union
{
int32_t i32;
int32_t* i32_ptr;
union
{
int16_t h;
int16_t l;
} i16;
} tvm_register_t;
typedef struct
{
/*
Similar to x86 FLAGS register
0x1 EQUAL
0x2 GREATER
*/
int FLAGS;
int remainder;
void* mem_space;
int mem_space_size;
tvm_register_t* registers;
} tvm_memory_t;
tvm_memory_t* create_memory(size_t size);
void destroy_memory(tvm_memory_t* mem);
#endif
|
Swift
|
UTF-8
| 2,719
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
import Firebase
import ProgressHUD
protocol ForgotPasswordViewEvents: AnyObject {
func present(viewController: UIViewController)
func push(viewController: UIViewController)
}
class ForgotPasswordViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var backLoginButton: UIButton!
private var viewModel: ForgotPasswordViewModelProtocol?
override func viewDidLoad() {
super.viewDidLoad()
configNavigationItem()
setupButton(button: sendButton)
configureTextFieldDelegate()
self.viewModel = ForgotPasswordViewModel()
self.viewModel?.viewController = self
}
@IBAction func send(_ sender: Any) {
viewModel?.resetPassDidTapped()
self.resetPassword()
}
@IBAction func login(_ sender: Any) {
viewModel?.loginTapped()
}
func setupButton(button: UIButton){
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.backgroundColor = UIColor.white.withAlphaComponent(1.0)
button.tintColor = UIColor.black
button.layer.cornerRadius = 10
button.clipsToBounds = true
}
func resetPassword(){
guard let email = emailTextField.text, email != " " else {
ProgressHUD.showError(ERROR_EMPTY_EMAIL_RESET)
return
}
AuthUser.User.resetPassword(withEmail: email, onSucess: {
self.view.endEditing(true)
self.clearTextFields()
}) { (errorMessage) in
ProgressHUD.showError(errorMessage)
}
}
func clearTextFields(){
emailTextField.text = ""
}
func configureTextFieldDelegate(){
emailTextField.delegate = self
}
func configNavigationItem(){
let backButton = UIBarButtonItem()
backButton.title = "Voltar"
self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton
}
}
extension ForgotPasswordViewController: UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension ForgotPasswordViewController: ForgotPasswordViewEvents{
func push(viewController: UIViewController) {
navigationController?.pushViewController(viewController, animated: true)
}
func present(viewController: UIViewController) {
present(viewController, animated: true, completion: nil)
}
}
|
Shell
|
UTF-8
| 596
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/bash
input=$1
output=$2
if [ -z "$input" ] || [ -z "$output" ]; then
echo "Usage: subset <input> <output>"
exit 1
fi
ncks -v state_WVatm_avk,state_WVatm,atm_altitude,state_WVatm_a,atm_nol,lat,lon,fit_quality,iter,srf_flag,Time,Date $input $output
# for file in *.nc; do
# ncks --overwrite -v lat,lon,state/WV/avk/k,state/WV/n/k,state/WV/Tatmxavk/k,state/GHG/avk/k,state/GHG/n/k,state/GHG/Tatmxavk/k,state/HNO3/avk/k,state/HNO3/n/k,state/HNO3/Tatmxavk/k,state/Tatm/n/k,state/Tatm/avk/k \
# $file \
# ~/git/python/iasi-analysis/data/eigenvalues/$file
# done
|
C#
|
UTF-8
| 816
| 2.65625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace SimpleSurveyAPI.Controllers
{
public class SurveyController : ApiController
{
public HttpResponseMessage Get(int id)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
if (id == 1)
{
response.Content = new StringContent("First");
}
else if (id == 42)
{
response.Content = new StringContent("<span>Hitchickers</span>");
}
else
{
response.Content = new StringContent("<span>Unknown</span>");
}
return response;
}
}
}
|
Java
|
UTF-8
| 1,606
| 2.0625
| 2
|
[] |
no_license
|
package com.bridgelabz.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.bridgelabz.dao.UserDao;
import com.bridgelabz.listener.LoginListener;
import com.bridgelabz.model.User;
/**
* Servlet implementation class PreSuccess
*/
public class PreSuccess extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PreSuccess() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
UserDao userdao=new UserDao();
List<User> list=userdao.getAllRecords();
request.setAttribute("list",list);
RequestDispatcher rd= request.getRequestDispatcher("success");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
Python
|
UTF-8
| 955
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
import enum
class JointPath:
def __init__(self, joint_positions, cost):
self.joint_positions = joint_positions
self.cost = cost
class SolveMethod(enum.Enum):
""" Acrobotics.planning implements two types of algorithms. """
sampling_based = 0
optimization_based = 1
class CostFuntionType(enum.Enum):
l1_norm = 0
l2_norm = 1
sum_squared = 3
weighted_sum_squared = 4
class PlanningSetup:
def __init__(self, robot, path, scene):
self.robot = robot
self.path = path
self.scene = scene
class Solution:
def __init__(
self,
success: bool,
joint_positions=None,
path_cost: float = None,
run_time: float = None,
extra_info: dict = None,
):
self.success = success
self.joint_positions = joint_positions
self.path_cost = path_cost
self.run_time = run_time
self.extra_info = extra_info
|
PHP
|
UTF-8
| 1,230
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace NotificationChannels\OneSignal\Traits\Categories;
trait GroupingHelpers
{
/**
* Set the Android Grouping Parameters.
*
* @param string $group
* @param array $groupMessage
* @return $this
*/
public function setAndroidGroup(string $group, array $groupMessage)
{
return $this->setParameter('android_group', $group)
->setParameter('android_group_message', $groupMessage);
}
/**
* Set the Amazon (FireOS) Grouping Parameters.
*
* @param string $group
* @param array $groupMessage
* @return $this
*/
public function setAmazonGroup(string $group, array $groupMessage)
{
return $this->setParameter('adm_group', $group)
->setParameter('adm_group_message', $groupMessage);
}
/**
* Set the Grouping Parameters for all available Systems (currently Android and Amazon (FireOs)).
*
* @param string $group
* @param array $groupMessage
* @return $this
*/
public function setGroup(string $group, array $groupMessage)
{
return $this->setAndroidGroup($group, $groupMessage)
->setAmazonGroup($group, $groupMessage);
}
}
|
Java
|
UTF-8
| 1,232
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
package client;
import handlers.IWordOperations;
import java.net.URL;
import java.util.Scanner;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
import org.apache.xmlrpc.client.util.ClientFactory;
public class Client {
public static void main(String[] args) {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
try {
config.setServerURL(new URL("http://127.0.0.1:" + Integer.parseInt(args[0]) + "/"));
XmlRpcClient client = new XmlRpcClient();
client.setTransportFactory(new XmlRpcCommonsTransportFactory(client));
client.setConfig(config);
// Add this for dynamic proxy
ClientFactory clientFactory = new ClientFactory(client);
IWordOperations wordOperationsInterface= (IWordOperations) clientFactory.newInstance(IWordOperations.class);
// Find occurrence of a word.
Scanner scanner = new Scanner(System.in);
String keyword = scanner.nextLine();
System.out.println(wordOperationsInterface.findOccurrences(keyword));
scanner.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception: " + e.getMessage());
}
}
}
|
C++
|
UTF-8
| 643
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
#include <gtest/gtest.h>
using namespace std;
int strStr(string haystack, string needle)
{
int index = -1;
const int n = haystack.length();
const int m = needle.length();
if (n < m)
return -1;
for (int i=0; i<=n-m; ++i)
{
int j = 0;
for (; j<m; ++j)
{
if (haystack[i+j] != needle[j])
{
break;
}
}
if (j==m)
{
index = i;
break;
}
}
return index;
}
TEST(Pratices, tStrStr)
{
// 12345678 123 =>0
ASSERT_EQ(strStr("12345678","123"),0);
ASSERT_EQ(strStr("12345678","231"),-1);
ASSERT_EQ(strStr("123","123"),0);
ASSERT_EQ(strStr("123","1234"),-1);
ASSERT_EQ(strStr("11123412341234","1234"),2);
}
|
C++
|
BIG5
| 374
| 3.0625
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
int main ()
{ int a[9];
int answer=0;
printf("JAnƦr:\n");
for(int i=0;i<9;i++)
{
scanf("%d",&a[i]);
}
for(int i=0;i<9;i++)
{
printf("%d",a[i]);
}
answer=(a[0]*a[4]*a[8])+(a[3]*a[7]*a[2])+(a[6]*a[1]*a[5])
-(a[2]*a[4]*a[6])-(a[1]*a[3]*a[8])-(a[0]*a[5]*a[7]);
printf("\n%d",answer);
return 0;
}
|
C++
|
UTF-8
| 1,107
| 2.734375
| 3
|
[] |
no_license
|
#include <iostream>
#include "Matrix.h"
#include "Object.h"
#include "Painter.h"
#include "Render.h"
void renderObject(const Object& obj,Render *r){
for(int i=0;i<obj.length()-1;++i)
{
Vec3f a[3];
for(int j=0;j<3;++j){
a[j]=r->vert(obj.vert(i,j));
}
r->Line(a[0],a[1],Green);
r->Line(a[1],a[2],Green);
r->Line(a[2],a[0],Green);
}
}
int main(int argc,char**argv) {
Object object(argv[1]);
Render renderer;
RenderDevice device;
TCHAR *title=_T("test");
int result=device.initWindow(800,1000,title);
std::cout<<result<<std::endl;
renderer.initDevice(800,1000,device.frameBuffer());
while(!device.exit())
{
device.dispatchWindow();
renderer.clearDevice(0);
if(device.keyState(VK_UP))
renderer.Move_Up();
else if(device.keyState(VK_DOWN))
renderer.Move_Down();
else if(device.keyState(VK_SPACE))
renderer.Reset();
renderObject(object,&renderer);
device.updateWindow();
Sleep(1);
}
return 0;
}
|
Java
|
UTF-8
| 5,332
| 2.21875
| 2
|
[] |
no_license
|
package com.nisira.core.dao;
import com.nisira.core.entity.*;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import com.nisira.core.database.DataBaseClass;
import android.content.ContentValues;
import android.database.Cursor;
import com.nisira.core.util.ClaveMovil;
import java.util.ArrayList;
import java.util.LinkedList;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Concepto_cuentaDao extends BaseDao<Concepto_cuenta> {
public Concepto_cuentaDao() {
super(Concepto_cuenta.class);
}
public Concepto_cuentaDao(boolean usaCnBase) throws Exception {
super(Concepto_cuenta.class, usaCnBase);
}
public void mezclarLocal(Concepto_cuenta obj)throws Exception{
List<Concepto_cuenta> lst= listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? AND LTRIM(RTRIM(t0.IDCONCEPTO))=?",obj.getIdempresa().trim(),obj.getIdconcepto().trim());
if(lst.isEmpty())
insertar(obj);
else
actualizar(obj);
}
public List<Concepto_cuenta> ListarConsumidor(Dordenliquidaciongasto obj)throws Exception {
if (obj != null) {
List<Concepto_cuenta> lst = listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? ", obj.getIdempresa().trim());
if(lst.isEmpty()){
return null;
}else
return lst;
}
return null;
}
public Boolean insert(Concepto_cuenta concepto_cuenta) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues initialValues = new ContentValues();
initialValues.put("IDEMPRESA",concepto_cuenta.getIdempresa());
initialValues.put("IDCONCEPTO",concepto_cuenta.getIdconcepto());
initialValues.put("IDCUENTA",concepto_cuenta.getIdcuenta());
initialValues.put("DESCRIPCION",concepto_cuenta.getDescripcion());
initialValues.put("REGISTRAR_EN",concepto_cuenta.getRegistrar_en());
initialValues.put("ESTADO",concepto_cuenta.getEstado());
initialValues.put("SINCRONIZA",concepto_cuenta.getSincroniza());
initialValues.put("FECHACREACION",dateFormat.format(concepto_cuenta.getFechacreacion() ) );
resultado = mDb.insert("CONCEPTO_CUENTA",null,initialValues)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
public Boolean update(Concepto_cuenta concepto_cuenta,String where) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues initialValues = new ContentValues();
initialValues.put("IDEMPRESA",concepto_cuenta.getIdempresa()) ;
initialValues.put("IDCONCEPTO",concepto_cuenta.getIdconcepto()) ;
initialValues.put("IDCUENTA",concepto_cuenta.getIdcuenta()) ;
initialValues.put("DESCRIPCION",concepto_cuenta.getDescripcion()) ;
initialValues.put("REGISTRAR_EN",concepto_cuenta.getRegistrar_en()) ;
initialValues.put("ESTADO",concepto_cuenta.getEstado()) ;
initialValues.put("SINCRONIZA",concepto_cuenta.getSincroniza()) ;
initialValues.put("FECHACREACION",dateFormat.format(concepto_cuenta.getFechacreacion() ) ) ;
resultado = mDb.update("CONCEPTO_CUENTA",initialValues,where,null)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Boolean delete(String where) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
resultado = mDb.delete("CONCEPTO_CUENTA",where,null)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
public ArrayList<Concepto_cuenta> listar(String where,String order,Integer limit) {
if(limit == null){
limit =0;
}
ArrayList<Concepto_cuenta> lista = new ArrayList<Concepto_cuenta>();
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
Cursor cur = mDb.query("CONCEPTO_CUENTA",
new String[] {
"IDEMPRESA" ,
"IDCONCEPTO" ,
"IDCUENTA" ,
"DESCRIPCION" ,
"REGISTRAR_EN" ,
"ESTADO" ,
"SINCRONIZA" ,
"FECHACREACION"
},
where, null, null, null, order);
if (cur!=null){
cur.moveToFirst();
int i=0;
while (cur.isAfterLast() == false) {
int j=0;
Concepto_cuenta concepto_cuenta = new Concepto_cuenta() ;
concepto_cuenta.setIdempresa(cur.getString(j++));
concepto_cuenta.setIdconcepto(cur.getString(j++));
concepto_cuenta.setIdcuenta(cur.getString(j++));
concepto_cuenta.setDescripcion(cur.getString(j++));
concepto_cuenta.setRegistrar_en(cur.getString(j++));
concepto_cuenta.setEstado(cur.getDouble(j++));
concepto_cuenta.setSincroniza(cur.getString(j++));
concepto_cuenta.setFechacreacion(dateFormat.parse(cur.getString(j++)) );
lista.add(concepto_cuenta);
i++;
if(i == limit){
break;
}
cur.moveToNext();
}
cur.close();
}
} catch (Exception e) {
}finally {
mDb.close();
}
return lista;
}
}
|
Markdown
|
UTF-8
| 2,786
| 2.8125
| 3
|
[] |
no_license
|
# CSFX HW 1
```
Team #15
107062503 許博皓
10706XXXX 鄭家鈞
107062566 黃鈺程
```
## Introduction
我們準備了三張圖片:
[人臉](https://i.imgur.com/4S6XvLu.png)
[蘋果](https://i.imgur.com/VKd1dfg.png)
[橘子](https://i.imgur.com/vKQNUwr.jpg)
進行四個實驗:
1. 蘋果 轉換成 **橘子風格**
2. 人臉 轉換成 **橘子風格**
3. 橘子 轉換成 **蘋果風格**
5. 人臉 轉換成 **蘋果風格**
並使用四種 model 來實驗。
---
另外,我們有對程式碼進行一點小修改:

根據 tqdm 的文檔,當 `tqdm` 與 `enumerate` 相互使用了,應寫成 `enumerate(tqdm())` 而不是 `tqdm(enumerate())`,因為 `len` 無法作用在 `enumerate` 的結果上,造成 `tqdm` 抓不到總共有幾個 iteration。
## Exp: Cycle GAN (64x64) with our weight
訓練:

轉成橘子(結果在左,原圖在右):


轉成蘋果(結果在左,原圖在右):


## Exp: Cycle GAN (256x256) with our weight
訓練:

轉成橘子(結果在左,原圖在右):


轉成蘋果(結果在左,原圖在右):


## Exp: Cycle GAN with pretrained weight
轉成橘子(結果在左,原圖在右):


轉成蘋果(結果在左,原圖在右):


## Exp: Color Transfer
Source 為風格,Target 為要轉換的圖片,Transfer 為結果。




## Report
根據以上實驗,我們有三個結論:
1. Color Transfer 基本就是調色調而已,相對 Cycle GAN 效果並不好。但速度非常快。
2. size 為 64 的結果效果較差,顆粒感重。而 size 為 256 則效果較好,看起來自然許多,也沒有顆粒感,但就需要訓練比較久。
3. 和 pre-trained weights 相比,pre-trained 的效果較好,蘋果轉橘子的光澤較為自然。
## Misc.
我們還使用了其他 dataset 訓練。一些結果如下:
### horse2zebra
訓練:

轉成馬(結果在左,原圖在右):

轉成斑馬(結果在左,原圖在右):

|
Python
|
UTF-8
| 4,636
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
"""Peter Rasmussen, Lab 4, run.py
This module processes a reads a file or directory of files containing integers, executes five
recursive sorting algorithms, and an output CSV for each input file.
"""
# standard library imports
import csv
from copy import deepcopy
from pathlib import Path
from time import time_ns
# local imports
from lab4.datamaker.make_data import make_data
from lab4.file_io import FileIO, make_header
from lab4.sorts import HeapSort
from lab4.sorts import MergeSort
def run(
in_path: Path,
out_path: Path,
datamaker_out_path: Path,
file_header: str
):
"""
Symbolically combine polynomials and then evaluate for various evaluation sets.
:param in_path: Data input path or directory
:param out_path: Data output CSV path or directory where CSVs will be saved
:param datamaker_out_path: Datamaker output directory
:param file_header: Header to add to top of CSV
"""
program_start = time_ns()
if datamaker_out_path is not None:
make_data(datamaker_out_path)
else:
sorters = {"heap_sort": {"sort_class": HeapSort, "kwargs": {}},
"two_way_merge": {"sort_class": MergeSort, "kwargs": {"way": 2}},
"three_way_merge": {"sort_class": MergeSort, "kwargs": {"way": 3}},
"four_way_merge": {"sort_class": MergeSort, "kwargs": {"way": 4}},
"natural_merge": {"sort_class": MergeSort, "kwargs": {"way": "natural"}},
}
file_io = FileIO(in_path, out_path)
datasets = file_io.read_input()
if len(datasets) == 0:
raise ValueError("No files were read.")
# Iterate over each dataset
for dataset_name, dataset in datasets.items():
print(f"Dataset: {dataset_name}")
data_dict = {"unsorted": dataset}
# Iterate over each sorter (e.g., 2-way merge sort, natural merge, etc.)
for sort_name, sorter_di in sorters.items():
print(f"\tSort: {sort_name}")
# Extract dictionary arguments, instantiate sorter, and sort list
sorter_class, kwargs = sorter_di["sort_class"], sorter_di["kwargs"]
sorter = sorter_class(deepcopy(dataset), **kwargs)
sorter.sort()
# Build temp dictionary and add outputs
data_dict[sort_name] = {"sorted": sorter.sorted_li,
"n": sorter.n,
"n_comparisons": sorter.n_comparisons,
"n_exchanges": sorter.n_exchanges,
"n_partition_calls": sorter.n_partition_calls,
"elapsed_ns": sorter.elapsed}
# Make destination filepath
dst = file_io.create_out_filename(dataset_name)
# Make file headers
operation_message = "Unsorted and sorted lists and sorted list performance metrics."
in_file = in_path / f"{dst.stem}.dat"
file_header_ = make_header(file_header, in_file, dst, operation_message)
# Make column names
column_names: list = list(data_dict.keys())
# Create metrics table
csv_li: list = [["metric"] + column_names]
# Metrics table: Add number of comparisons, exchanges, and partition calls
for metric in ["n", "n_comparisons", "n_exchanges", "n_partition_calls", "elapsed_ns"]:
li = [di[metric] for k, di in data_dict.items() if k != "unsorted"]
if metric == "n":
metric_li = [metric, len(dataset)] + li
else:
metric_li = [metric, "N/A"] + li
csv_li.append(metric_li)
csv_li.append([""] + len(column_names) * [""]) # blank line to separate tables
# Create data table
csv_li.append(["ix"] + column_names)
counter = 0
for ix, value in enumerate(data_dict["unsorted"]):
li = [ix, value] + [sort_dict["sorted"][ix] for sort_name, sort_dict in
data_dict.items() if sort_name != "unsorted"]
csv_li.append(li)
counter += 1
# We don't need to write all the rows
if counter >= 50:
break
# Write outputs to CSV
with open(str(dst), "w") as f:
f.write(file_header_)
writer = csv.writer(f)
writer.writerows(csv_li)
|
Python
|
UTF-8
| 11,694
| 3.8125
| 4
|
[] |
no_license
|
# Jonathan Williams
# Jon
# Final Project
# Clicker Madness
# Version 0.8.5
# Version Patch Notes: Add rough elapsed time, difficulty selection.
# Clicker Game that displays targets the player must click for points.
##To do list for Final Project:
##FUTURE Improvements:
##Upgrade Graphics
##New kinds of targets.
##New random events.
##Music.
from graphics import *
import math
import time
from random import randrange
import pygame
pygame.init()
# Player Class. Saves Name and Final Score. (CLOD) My own class
class Player:
def __init__(self, name, highscore):
self.name = name
self.highscore = int(highscore)
def getName(self):
return self.name
def getHighScore(self):
return self.highscore
def display(self):
print("{:<15}".format(self.name), "{:>}".format(self.highscore))
# Target Class (CLOD) My own class.
class Target:
# Parameters for Target: Circle Center, amount of points its worth, color, x and y direction,
def __init__(self, center, points, color, dirx=-1, diry=-1):
self.circle = Circle(center, 1)
self.circle.setFill(color)
self.dirx = dirx
self.diry = diry
# Class method gets center of circles.
def getCenter(self):
return self.circle.getCenter()
# Class method for drawing circles.
def draw(self, win):
self.circle.draw(win)
# Class method for checking if the mouse is clicked inside a circle.
def checkClick(self, win, mouse):
if mouse == None:
mouse = 0
else:
dx = mouse.getX() - self.circle.getCenter().getX() # Get X Corrds
dy = mouse.getY() - self.circle.getCenter().getY() # Get Y Coords
dist = math.sqrt(dx * dx + dy * dy) ##Distance Formula
return dist <= self.circle.getRadius() ##Check if distance is less than radius.
# Move method. Moves circles randomly around the screen.
def move(self):
dx = self.circle.getCenter().getX() # return x coord of center
dy = self.circle.getCenter().getY() # return y coord of center
if dy >= 8:
self.diry = -1
elif dx >= 8:
self.dirx = -1
elif dx <= -8:
self.dirx = 1
elif dy <= -8:
self.diry = 1
elif dx >= 8 and dy >= 8:
self.dirx = -1
self.diry = -1
elif dx <= -8 and dy <= -8:
self.dirx = 1
self.dirx = 1
else:
self.dirx = randrange(-8, 8) # (RND) Random Elements.
self.diry = randrange(-8, 8) # (RND) Random Elements.
self.circle.move(self.dirx, self.diry)
# Creates the game board. (GW) Graph Window
def window():
win = GraphWin("Clicker Madness", 600, 600)
win.setBackground("black")
win.setCoords(-10, -10, 10, 10)
return win
# Function for difficulty selection.
def difSelec(win):
easy = Rectangle(Point(-6, -6), Point(-4, -3))
easy.setFill("green")
easy.draw(win)
med = Rectangle(Point(-2, -6), Point(0, -3))
med.setFill("yellow")
med.draw(win)
hard = Rectangle(Point(2, -6), Point(4, -3))
hard.setFill("red")
hard.draw(win)
diff = 0
while True:
##(IMS) Mouse click and location.
click = win.getMouse()
dx = click.getX()
dy = click.getY()
# Easy
if dx >= -6 and dx <= -4 and dy >= -6 and dy <= -3:
print("easy")
easy.undraw()
med.undraw()
hard.undraw()
diff = 0.8
return diff
# Medium
elif dx >= -2 and dx <= 0 and dy >= -6 and dy <= -3:
print("medium")
easy.undraw()
med.undraw()
hard.undraw()
diff = 0.65
return diff
# Hard
elif dx >= 2 and dx <= 4 and dy >= -6 and dy <= -3:
print("hard")
easy.undraw()
med.undraw()
hard.undraw()
diff = 0.4
return diff
# Function to create title screen and player inputs.
def title(win):
# (IEB)Entry box.
nameEntry = Entry(Point(0, 0), 8)
nameEntry.setText("")
nameEntry.getText()
nameEntry.setSize(28)
# (OTXT) Title text and instructions.
text = Text(Point(0, 3), "Clicker Madness!").draw(win)
text.setSize(28)
text.setFill("cyan")
text2 = Text(Point(0, 1.8), "Enter Player Name, then Click a color:").draw(win)
text2.setFill("cyan")
text3 = Text(Point(0, -1.3), "Press q at anytime to quit")
text3.draw(win)
text3.setFill("cyan")
text4 = Text(Point(0, -2), "Green=Easy, Yellow=Medium, Red=Hard")
text4.setFill("cyan")
text4.draw(win)
nameEntry.draw(win)
diff = difSelec(win)
name = nameEntry.getText()
if name == " " or name == "":
name = "NoName"
name = name[0:9]
player = Player(name, 0)
if name != " ":
nameEntry.undraw()
text.undraw()
text2.undraw()
text3.undraw()
text4.undraw()
# Displays current player name and word "score".
nameDisplay = Text(Point(-3, 9.5), name)
nameDisplay.setFill("cyan")
nameDisplay.draw(win)
scoreDisplay = Text(Point(0, 9.5), "Score: ")
scoreDisplay.setFill("cyan")
scoreDisplay.draw(win)
return player, diff # returns difficulty selection.
# Function that returns player score.
def useHighScore(player):
return player.getHighScore()
# (OFL) Saves Player data to outfile.
def save(player):
outfile = open("Saves.txt", "a")
outfile.write(player.getName() + "\t" + str(player.getHighScore()) + "\n")
outfile.close()
# Function to draw targets.
def drawCircle(win, circle_list):
for c in circle_list:
c.draw(win)
# Function to move the circles.
def moveCircle(win, circle_list):
for c in circle_list:
c.move()
# Main Game Play Function
def gamePlay(win, diff):
music=pygame.mixer.Sound("gnat.wav")
music.play()
# Create each target.
green = Target(Point(1, 1), 2, "green")
blue = Target(Point(2, 1), 5, "blue")
yellow = Target(Point(3, 1), 3, "yellow")
red = Target(Point(4, 1), 0, "red")
purple = Target(Point(5, 1), 10, "purple")
lime = Target(Point(6, 1), 0, "lime")
indigo = Target(Point(6, 1), -5, "indigo")
circle_list = [green, blue, yellow, red, purple, lime, indigo]
drawCircle(win, circle_list)
# Initialize score to 0
score = 0
# Set up to display live score after main game play loop.
dispScore = Text(Point(1.5, 9.5), score)
dispScore.setFill("cyan")
dispScore.draw(win)
# Sets up elapsed time text for screen.
time_text = Text(Point(9, 9.5), "--")
time_text.setFill("cyan")
time_text.draw(win)
# Start time to begin count for elapsed time.
start_time = time.time()
# Main game play loop.
while True:
if closeWin(win):
break
# Moves Targets.
moveCircle(win, circle_list)
time.sleep(diff) # Target move speed. Default 0.65
# Main loop to detect clicks and award points.
mouse = win.checkMouse()
if green.checkClick(win, mouse):
print("+2!")
score = score + 2
elif red.checkClick(win, mouse): # terminates game.
print("Game Over!")
highscore = score
score = 0
print(highscore)
music.stop()
return highscore
elif blue.checkClick(win, mouse):
print("+5!")
score = score + 5
elif yellow.checkClick(win, mouse):
print("+3!")
score = score + 3
elif purple.checkClick(win, mouse):
print("+10!")
score = score + 10
elif lime.checkClick(win, mouse): # Zeros out current score.
print("Zero'd Out!")
score = 0
elif indigo.checkClick(win, mouse): # Subtracts 5 points from score.
print("-5!")
score = score - 5
# Current Time
current_time = time.time()
elapsed = (current_time - start_time + 0.65) // 1
# Line displays live score.
dispScore.setText(score)
time_text.setText(elapsed)
print(score)
return score, music
# Function to close game at any time when the q key is pressed.
def closeWin(win):
key = win.checkKey()
if key == "q":
music.stop()
win.close()
return True
return False
# Function that displays the top 5 players based on highscore.
def display():
win = GraphWin("High Scores!", 600, 600) # Draws HS Screen.
win.setBackground("black")
win.setCoords(-10, -10, 10, 10)
hsText = Text(Point(0, 9.2), "High Scores")
hsText.setFill("cyan")
hsText.setStyle("bold italic")
hsText.setSize(28)
hsText.draw(win)
credit = Text(Point(0, -8.2), "Designed and Programmed by: Jon Williams.")
credit.setFill("cyan")
credit.setStyle("italic")
credit.draw(win)
credit2 = Text(Point(0, -9.2), "Special Thanks to Jason, Amin, and Magari")
credit2.setFill("cyan")
credit2.setStyle("italic")
credit2.draw(win)
textName = Text(Point(-2.9, 6), "Name")
textName.setFill("cyan")
textName.setStyle("bold")
textName.draw(win)
textScore = Text(Point(2.9, 6), "High Score")
textScore.setFill("cyan")
textScore.setStyle("bold")
textScore.draw(win)
sortFile = open("Saves.txt", "r").readlines() # (IFL) Reads data from the saved file.
playerList = [] # (LOOD)List of my own class objects.
for line in sortFile: # Sorts high score list by score (lowest to highest)
name = line.split("\t")[0] # Splits Player Name from string.
highscore = line.split("\t")[1] # Splits high score from string.
plyr = Player(name, int(highscore)) # Turns high score into an int.
playerList.append(plyr) # Appends player data to playerList.
playerList.sort(key=useHighScore) # sets the key for sorting and sorts the list.
playerList.reverse() # Reverses sorted HS list.
y = 5 # variable to display the top 5 scores.
for p in playerList[:5]: # (OTXT)
text1 = Text(Point(-3, y), p.getName())
text1.setFill("cyan")
text1.draw(win)
text2 = Text(Point(3, y), p.getHighScore())
text2.setFill('cyan')
text2.draw(win)
y -= 1
return win
# Function draws a button and lets player play again upon click.
def playAgain(win):
button = Rectangle(Point(1, -3), Point(7, -6))
button.setFill("green")
button.draw(win)
playAgain = Text(Point(4, -4.5), "Play Again.")
playAgain.setStyle("bold")
playAgain.draw(win)
while True:
click = win.getMouse()
dx = click.getX()
dy = click.getY()
if dx >= 1 and dx <= 7 and dy <= -3 and dy >= -6: # (IMS) Mouse location/Check.
win.close()
main()
# Image drawing function.
def image(win):
kraken = Image(Point(-4.5, -4.5), "kraken.png")
kraken.draw(win)
# (FNC) Calling functions of my own design.
def main():
win = window()
player, diff = title(win)
score = gamePlay(win, diff)
player.highscore = int(score)
save(player)
win.close()
win2 = display()
image(win2)
playAgain(win2)
main()
|
Java
|
UTF-8
| 229
| 2.265625
| 2
|
[] |
no_license
|
public class NormalDistribution extends ProbabilityDistribution {
public NormalDistribution(double mean, double stddev) {
super(mean, stddev);
}
public NormalDistribution() {
super(0.0, 1.0);
}
}
|
Python
|
UTF-8
| 4,565
| 3.65625
| 4
|
[] |
no_license
|
"""
A3, Q2
Solving van der Pol oscillator using both Runge-Kutta and odeint,
taking odeint's result to be the true value
"""
import scipy.integrate as sp_int
import numpy as np
import matplotlib.pyplot as plt
from run_kut4 import *
# define constant
epsilon = 10.0
# inital conditions
x0 = 0.5
y0 = 0.0
ics = [x0,y0] #vector of initial conditions
# define the function as it demands
def f(x,y):
f = np.zeros(2)
f[0] = y[1] #f0 == dx, y[0] = x, y[1] = y
f[1] = (-y[0])-((epsilon*((y[0]**2)-1))*y[1]) #f1 == dy
return f
# integration parameters. These won't change
x_start = 0.0
x_stop = (10.0*np.pi)
# integration itself
X_002,Y_002 = integrate(f,x_start,ics,x_stop,0.02)
# plot
plt.figure(1)
plt.plot(X_002,Y_002[:,0],label=r'$h$ = 0.02',color='b')
plt.xlabel(r'time, $t$')
plt.ylabel(r'position, $x$')
plt.title(r'Position vs. time for step-size $h$ = 0.02')
plt.legend(loc=0)
plt.xlim(0,(10*np.pi))
plt.show()
# again for h=0.05
X_005,Y_005 = integrate(f,x_start,ics,x_stop,0.05)
plt.figure(2)
plt.plot(X_005,Y_005[:,0],label=r'$h$ = 0.05',color='g')
plt.xlabel(r'time, $t$')
plt.ylabel(r'position, $x$')
plt.title(r'Position vs. time for step-size $h$ = 0.05')
plt.xlim(0,(10*np.pi))
plt.legend(loc=0)
plt.show()
# again for h=0.1
X_01,Y_01 = integrate(f,x_start,ics,x_stop,0.1)
plt.figure(3)
plt.plot(X_01,Y_01[:,0],label=r'$h$ = 0.1', color='r')
plt.xlabel(r'time, $t$')
plt.ylabel(r'position, $x$')
plt.title(r'Position vs. time for step-size $h$ = 0.1')
plt.legend(loc=0)
#plt.ylim(-2.1,2.1)
plt.xlim(0,(10*np.pi))
plt.show()
# define equations for odeint
def odeint_f(q,t):
xi = q[0]
yi = q[1]
f0 = yi
f1 = (-xi)-((epsilon*((xi**2)-1))*yi)
return [f0,f1]
# range to solve for
t = np.linspace(0,(10*np.pi), 100000) #make this huge to get pretty curves
# integrate using odeint
odeint_sol_10 = sp_int.odeint(odeint_f,ics,t)
x_ois_10 = odeint_sol_10[:,0]
y_ois_10 = odeint_sol_10[:,1]
# plot this solution
plt.figure(4)
plt.plot(t,x_ois_10, label='odeint', color='k')
plt.xlabel(r'time, $t$')
plt.ylabel(r'position, $x$')
plt.title(r'Position vs. time, using odeint')
plt.xlim(0,(10*np.pi))
plt.show()
# plot all four
plt.figure(5)
plt.plot(X_01,Y_01[:,0], label=r'RK: $h$ = 0.1', color='r') ##this blows up
plt.plot(X_005,Y_005[:,0], label=r'RK: $h$ = 0.05', color='g')
plt.plot(X_002,Y_002[:,0], label=r'RK: $h$ = 0.02', color='b')
plt.plot(t,x_ois_10, label='odeint', color='k')
plt.xlabel(r'time, $t$')
plt.ylabel(r'position, $x$')
plt.title('Position vs. time')
plt.legend(loc=0)
plt.xlim(0,(10*np.pi))
plt.ylim(-2.1,2.1)
plt.show()
# Errors.
# Both arrays need to be of equal size.
# Generate new true value arrays to match the size of the rk arrays
def trange(x):
z = np.linspace(0,10*np.pi,len(x[:,0]))
return z
truev_002 = sp_int.odeint(odeint_f,ics,trange(Y_002))
truev_005 = sp_int.odeint(odeint_f,ics,trange(Y_005))
truev_01 = sp_int.odeint(odeint_f,ics,trange(Y_01))
er_rk_002 = np.abs((truev_002[:,0]) - (Y_002[:,0]))
er_rk_005 = np.abs((truev_005[:,0]) - (Y_005[:,0]))
er_rk_01 = np.abs((truev_01[:,0]) - (Y_01[:,0]))
plt.figure(6)
plt.semilogy(trange(Y_002),er_rk_002, label=r'Error for RK sol with $h$ = 0.02')
plt.semilogy(trange(Y_005),er_rk_005, label=r'Error for RK sol with $h$ = 0.05')
plt.semilogy(trange(Y_01),er_rk_01, label=r'Error for RK sol with $h$ = 0.1')
plt.xlim(0,10*np.pi)
plt.title(r'Graph of log of absolute errors vs. $t$')
plt.xlabel(r'$t$, time')
plt.ylabel(r'semilog($\sigma$), absolute error')
plt.legend(loc=0)
plt.show()
plt.figure(7)
plt.semilogy(trange(Y_002),er_rk_002, label=r'Error for RK sol with $h$ = 0.02')
plt.semilogy(trange(Y_005),er_rk_005, label=r'Error for RK sol with $h$ = 0.05')
plt.xlim(0,10*np.pi)
plt.title(r'Graph of log of absolute errors vs. $t$')
plt.xlabel(r'$t$, time')
plt.ylabel(r'semilog($\sigma$), absolute error')
plt.legend(loc=0)
plt.show()
# C
# get epsilon = 4 sol
epsilon = 4.0
odeint_sol_4 = sp_int.odeint(odeint_f,ics,t)
x_ois_4 = odeint_sol_4[:,0]
y_ois_4 = odeint_sol_4[:,1]
# do again for epsilon = 1
epsilon = 1.0
odeint_sol_1 = sp_int.odeint(odeint_f,ics,t)
x_ois_1 = odeint_sol_1[:,0]
y_ois_1 = odeint_sol_1[:,1]
plt.figure(8)
plt.plot(x_ois_1,y_ois_1, label=r'$\epsilon$ = 1', color='b')
plt.plot(x_ois_4,y_ois_4, label=r'$\epsilon$ = 4', color='g')
plt.plot(x_ois_10,y_ois_10, label=r'$\epsilon$ = 10', color='r')
plt.axis('equal')
plt.title(r'Phase-space plot, $\frac{dx}{dt}$ vs. $x$')
plt.xlabel(r'$x$, position')
plt.ylabel(r'$\frac{dx}{dt}$, velocity')
plt.legend(loc=0)
plt.show()
|
Python
|
UTF-8
| 1,109
| 3.09375
| 3
|
[] |
no_license
|
from functools import cmp_to_key
import re
def compare(stu1, stu2):
def getGrade(stu):
if stu[1] >= c and stu[2] >= c:
return 4
elif stu[1] >= c and stu[2] < c:
return 3
elif stu[1] < c and stu[2] < c and stu[1] >= stu[2]:
return 2
else:
return 1
gstu1 = getGrade(stu1)
gstu2 = getGrade(stu2)
ret = 0
if gstu1 == gstu2:
if (stu1[1] + stu1[2]) == (stu2[1] + stu2[2]):
if stu1[1] == stu2[1]:
ret = stu2[0] - stu1[0]
else:
ret = stu1[1] - stu2[1]
else:
ret = (stu1[1] + stu1[2]) - (stu2[1] + stu2[2])
else:
ret = gstu1 - gstu2
return ret
def inputInt():
return [int(i) for i in re.findall(r"[0-9]+",input())]
(a, b, c) = inputInt()
lst = []
for i in range(a):
stu = inputInt()
if stu[1] >= b and stu[2] >= b:
lst.append(stu)
lst.sort(key=cmp_to_key(compare), reverse=True)
print(len(lst))
for i in lst:
print(" ".join([str(j) for j in i]))
|
Java
|
UTF-8
| 1,535
| 2.203125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.pc.custadvisroyapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HomeActivity extends AppCompatActivity {
Button HeadAdvisor, Student, Advisor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Student = findViewById(R.id.buttonStudent);
HeadAdvisor = findViewById(R.id.buttonHeadAdvisor);
Advisor = findViewById(R.id.buttonAdvisor);
Student.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this,StudentLoginActivity.class);
startActivity(intent);
}
});
HeadAdvisor.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this,HeadAdvisorLoginActivity.class);
startActivity(intent);
}
});
Advisor.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this,AdvisorLoginActivity.class);
startActivity(intent);
}
});
}
}
|
Python
|
UTF-8
| 1,113
| 3.46875
| 3
|
[] |
no_license
|
import sys
def is_prime(num):
if num == 2 or num == 3: return True
if num < 2 or num % 2 == 0: return False
if num < 9: return True
if num % 3 == 0: return False
r = int(num ** 0.5)
f = 5
while f <= r:
if num % f == 0: return False
if num % (f + 2) == 0: return False
f += 6
return True
def get_p_range_rev(m):
return reversed(range(1, int(m ** 0.5) + 1))
def get_q_range_rev(m, a, b, p):
upper_bound_by_product = int(m / p)
upper_bound_by_ratio = int(b/a * p)
return reversed(range(p, min(upper_bound_by_product, upper_bound_by_ratio) + 1))
def get_most_suitable(m, a, b):
res = list()
for p in get_p_range_rev(m):
if is_prime(p):
for q in get_q_range_rev(m, a, b, p):
if is_prime(q):
res.append((p, q, p*q))
break
return max(res, key=lambda triplet: triplet[2])[:2]
def run():
res = list()
for line in sys.stdin:
line_split = line.split(' ')
m = int(line_split[0])
a = int(line_split[1])
b = int(line_split[2])
if m * a * b != 0:
p, q = get_most_suitable(m, a, b)
res.append(str(p) + ' ' + str(q))
return '\n'.join(res)
print(run())
|
Python
|
UTF-8
| 2,550
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
from read_data import *
from interaction_labelling import *
from feature_generation import *
from model import *
from sklearn.model_selection import StratifiedKFold
def main():
#import XML Data - From link source
drug_list, smiles_dict = read_from_file('../data/sample/full_database.xml')
#preprocessing
interactions = generate_interactions(drug_list, smiles_dict)
relation_list = generate_relations(interactions)
print("length of relation_list before preprocessing", len(relation_list))
#More preprocessing
relation_list, filter_count = remove_duplicates(relation_list)
relation_list, filter_count2 = filter_unknowns(relation_list)
relation_list, filter_count3 = filter_less_frequent_labels_v2(relation_list, 300)
print("filtered duplicates: ", filter_count)
print("filtered unknowns", filter_count2)
print("filtered labels with less than x count", filter_count3)
print("length of relation_list after removing duplicates", len(relation_list))
#Create the labels from the relation_list
label_map, label_lookup = generate_labels(relation_list)
#Feature generarion - from SMILEs to ECFP
smiles_feature_list, interaction_label_list, drug_pair_list \
= featurize_smiles_and_interactions(relation_list,smiles_to_ECFP,smiles_dict,label_map)
#Modelling
X = smiles_feature_list
y = interaction_label_list
X_arr = np.array(X)
y_arr = np.array(y)
X_arr_small = X_arr[0:5000]
y_arr_small = y_arr[0:5000]
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=None)
#Stratified train test split with k folds
for train_index, test_index in skf.split(X_arr_small, y_arr_small):
#print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X_arr_small[train_index], X_arr_small[test_index]
y_train, y_test = y_arr_small[train_index], y_arr_small[test_index]
#model_rf = rf_train(X_train, y_train)
#accuracy, precision, recall, f1 = generate_model_report(model_rf, X_test, y_test)
model = mlp_train(X_train, y_train)
accuracy, precision, recall, f1 = generate_model_report(model, X_test, y_test)
print(set(y_train))
print(y_arr_small.shape)
accuracy, precision, recall, f1 = generate_model_report_per_class(model, X_test, y_test, set(y_train))
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1] * 100))
print("Last Break Point")
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.