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
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 8,537
| 3.0625
| 3
|
[] |
no_license
|
### Introduction
This README file details the set of steps that i have taken inorder to execute the course project
for the Getting and Cleaning data course. In this markdown i will explain each step carried by the
R attached script.
### Assumptions
Before I begin, i would like to laydown certain assumptions
* The required set of data file (getdata-projectfiles-UCI HAR Dataset.rar) has been downloaded and unzipped in your working directory
* All the 3 training data sets (X_train, y_train, subject_train) is present in the folder .\UCI HAR Dataset\train inside your working directory
* All the 3 test data sets (X_test, y_test, subject_test) is present in the folder .\UCI HAR Dataset\test inside your working directory
### Set your working directory
At the very first line of the script you need to set your working directory, Please update the first line accordingly
`wd <- "D:\\selfLearning\\Coursera\\DataScienceSpecialization\\3_GettingAndCleaningData\\project"
setwd(wd)`
### Step 0 - Load all the files
Before I begin, I load all the 3 training files and the 3 test files into R.
`X_test <- read.table(file=".\\UCI HAR Dataset\\test\\X_test.txt",
colClasses="numeric", header=FALSE)`
`y_test <- read.table(file=".\\UCI HAR Dataset\\test\\y_test.txt", col.names=c("activity"),
colClasses="character", stringsAsFactors=FALSE, header=FALSE)`
`subject_test <- read.table(file=".\\UCI HAR Dataset\\test\\subject_test.txt",
col.names=c("subject"), colClasses="character",
stringsAsFactors=FALSE, header=FALSE)`
`X_train <- read.table(file=".\\UCI HAR Dataset\\train\\X_train.txt",
colClasses="numeric", header=FALSE)`
`y_train <- read.table(file=".\\UCI HAR Dataset\\train\\y_train.txt", col.names=c("activity"),
colClasses="character", stringsAsFactors=FALSE, header=FALSE)`
`subject_train <- read.table(file=".\\UCI HAR Dataset\\train\\subject_train.txt",
col.names=c("subject"), colClasses="character",
stringsAsFactors=FALSE, header=FALSE)`
### Step 1 - Merges the training and the test sets to create one data set.
Now that all the files have been loaded, I merge them. First I merge the 3 test set and 3 train sets individually using cbind
then I merge the two resultant sets using rbind
The X_train has 561 Variables, the subject_train and y_train has one variable each. All 3 of them have 7352 observations. So when
I cbind them I get 1 data set that has 7352 observations and 563 variables. I store this in a variable called all_train
`all_train <- cbind(X_train, y_train, subject_train)`
The X_test has 561 Variables, the subject_test and y_test has one variable each. All 3 of them have 2947 observations. So when
I cbind them I get 1 data set that has 2947 observations and 563 variables. I store this in a variable called all_test.
`all_test <- cbind(X_test, y_test, subject_test)`
I then append all_test to all_train. Each of them have 563 variables. all_test has 2947 observations and all_train has 7352
observations. I append them using rbind and store the result in variable called fulldata. this will have 10299 observations and
563 variables
`all_test <- fulldata <- rbind(all_train, all_test)`
### Step 2 - Extracts only the measurements on the mean and standard deviation for each measurement.
By referring to the features.txt, i have identified the column positions of variables that have mean and std, with these positions
i am forming a vector and will use the same to filter out only the required variables
I will then pull out only those variables from fulldata and discard the remainders
`reqdColumns <- c(1:6, 41:46, 81:86, 121:126, 161:166, 201:202, 214:215, 227:228, 240:241, 253:254, 266:271,
345:350, 424:429, 503:504, 516:517, 529:530, 542:543, 562, 563)`
`fulldata <- fulldata[,reqdColumns]`
### Step 3 - Uses descriptive activity names to name the activities in the data set.
I referred to the activity labels file to understand the activity labels of each code from 1 to 6. Using this I modify the activity variable
from the numeric code 1:6 to WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING respectively
`fulldata$activity <- ifelse(fulldata$activity == 1, "WALKING",
ifelse(fulldata$activity == 2, "WALKING_UPSTAIRS",
ifelse(fulldata$activity == 3, "WALKING_DOWNSTAIRS",
ifelse(fulldata$activity == 4, "SITTING",
ifelse(fulldata$activity == 5, "STANDING",
ifelse(fulldata$activity == 6, "LAYING",""))))))
`
### Step 4 - Appropriately labels the data set with descriptive variable names
Again I referred to the features.txt file to identify the labels of each of the variables that represents mean and std. With this i first
form a vector and then assign it to the names of the fulldata
`varLabels <- c("tBodyAcc-mean-X", "tBodyAcc-mean-Y", "tBodyAcc-mean-Z", "tBodyAcc-std-X",
"tBodyAcc-std-Y", "tBodyAcc-std-Z", "tGravityAcc-mean-X", "tGravityAcc-mean-Y",
"tGravityAcc-mean-Z", "tGravityAcc-std-X", "tGravityAcc-std-Y", "tGravityAcc-std-Z",
"tBodyAccJerk-mean-X", "tBodyAccJerk-mean-Y", "tBodyAccJerk-mean-Z", "tBodyAccJerk-std-X",
"tBodyAccJerk-std-Y", "tBodyAccJerk-std-Z", "tBodyGyro-mean-X", "tBodyGyro-mean-Y",
"tBodyGyro-mean-Z", "tBodyGyro-std-X", "tBodyGyro-std-Y", "tBodyGyro-std-Z",
"tBodyGyroJerk-mean-X", "tBodyGyroJerk-mean-Y", "tBodyGyroJerk-mean-Z", "tBodyGyroJerk-std-X",
"tBodyGyroJerk-std-Y", "tBodyGyroJerk-std-Z", "tBodyAccMag-mean", "tBodyAccMag-std",
"tGravityAccMag-mean", "tGravityAccMag-std", "tBodyAccJerkMag-mean", "tBodyAccJerkMag-std",
"tBodyGyroMag-mean", "tBodyGyroMag-std", "tBodyGyroJerkMag-mean", "tBodyGyroJerkMag-std",
"fBodyAcc-mean-X", "fBodyAcc-mean-Y", "fBodyAcc-mean-Z", "fBodyAcc-std-X",
"fBodyAcc-std-Y", "fBodyAcc-std-Z", "fBodyAccJerk-mean-X", "fBodyAccJerk-mean-Y",
"fBodyAccJerk-mean-Z", "fBodyAccJerk-std-X", "fBodyAccJerk-std-Y", "fBodyAccJerk-std-Z",
"fBodyGyro-mean-X", "fBodyGyro-mean-Y", "fBodyGyro-mean-Z", "fBodyGyro-std-X",
"fBodyGyro-std-Y", "fBodyGyro-std-Z", "fBodyAccMag-mean", "fBodyAccMag-std",
"fBodyBodyAccJerkMag-mean", "fBodyBodyAccJerkMag-std", "fBodyBodyGyroMag-mean", "fBodyBodyGyroMag-std",
"fBodyBodyGyroJerkMag-mean", "fBodyBodyGyroJerkMag-std")
`
As the last 2 variables are already appropriately named (subject and activity). I will use the varLabels vector to name
the first 66 variables
`names(fulldata)[1:66] <- varLabels`
### Step 5 - From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject
To do this I used the reshape2 package and used the function melt and dcast to arrive at the final data set
first I will install the package and import the library
`install.packages("reshape2")`
`library(reshape2)`
Now I will melt the data with dimensions being subject and activity and the remainder vars as measures
`datamelt <- melt(fulldata, id=c("subject", "activity"), measure.vars= varLabels)`
`finaldata <- dcast(datamelt, subject+activity~variable, mean)`
Now that the final data is arrived at, I will now write it back into the working directory
`write.table(finaldata, file="finaldata.txt", row.names=FALSE)`
My final tidy data has dimension 180*68. I would say this is wide form of tidy data. I contemplated for long weather i should go for a narrow tidy data by making the experiment too a variable but then i strongly feel that structuring the data depends on what our final analysis is. given that for this project we are not told for what purpose or analysis the data is going to be used for, it is hard to conclude weather a narrow or wide form of tidy data is applicable. I think the same has been discussed endlessly in the forums and both are applicable for this assignment.
Thank you and have a great day!!
|
Python
|
UTF-8
| 1,293
| 3.59375
| 4
|
[] |
no_license
|
__author__ = 'matisencale'
class DNA_Nucleotide:
'''
'''
def __init__(self, DNA_nucleotide_as_string):
self.symbol = str.upper(DNA_nucleotide_as_string)
self.description = self.get_description()
def get_description(self):
symbol_description = {'A':"adenine",'C':"cytosine",'G':"guanine",'T':"thymine"}
return symbol_description[self.symbol]
'''
dna_nucleotide_test_A = DNA_Nucleotide("A")
dna_nucleotide_test_C = DNA_Nucleotide("C")
dna_nucleotide_test_G = DNA_Nucleotide("G")
dna_nucleotide_test_T = DNA_Nucleotide("T")
print("test A")
print("A : " + str(dna_nucleotide_test_A))
print("A.symbol : " + str(dna_nucleotide_test_A.symbol))
print("A.description : " + str(dna_nucleotide_test_A.description))
print("test C")
print("C : " + str(dna_nucleotide_test_C))
print("C.symbol : " + str(dna_nucleotide_test_C.symbol))
print("C.description : " + str(dna_nucleotide_test_C.description))
print("test G")
print("G : " + str(dna_nucleotide_test_G))
print("G.symbol : " + str(dna_nucleotide_test_G.symbol))
print("G.description : " + str(dna_nucleotide_test_G.description))
print("test T")
print("T : " + str(dna_nucleotide_test_T))
print("T : " + str(dna_nucleotide_test_T.symbol))
print("T : " + str(dna_nucleotide_test_T.description))
'''
|
Markdown
|
UTF-8
| 1,269
| 3.609375
| 4
|
[
"MIT"
] |
permissive
|
# Feedster
## Description
Practice more animation methods using a click event, `.toggle()` notification bell menu, and `.toggleClass` +1 button.
## Objective
Feedster wants to add a notification menu and a +1 button to their news feed. [Here's what it looks like]("https://s3.amazonaws.com/codecademy-content/projects/2/feedster/index.html"). Click on the notification bell at the top right to see the dropdown menu, and click on each post's +1 button.
## Tasks
### 1.
Look at __index.html__. In the `<div class="notification">` section, there are two elements: an `<img>` element and a `<ul class="notification-menu">` element.
When the `<img>` is clicked, we want the `<ul class="notification-menu">` element to appear.
In each `<div class="post">` there is a `<class="btn">` element. When this button is clicked, we want it to turn red.
### 2.
In __app.js__, attach a click event handler to the notification bell image inside the `<div class="notification">` section so that it can respond to a click event.
### 3.
Inside the click event handler, toggle the `<ul class="notification-menu">` element.
### 4.
Attach another click event handler to the +1 button inside a `<div class="post">`.
### 5.
Inside the click event handler, toggle the class `btn-like`.
|
PHP
|
UTF-8
| 633
| 2.671875
| 3
|
[] |
no_license
|
<?php
//get variables from html form
$hash = $_GET['booking'];
//connect to db
$con = mysqli_connect('localhost','username','password','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"u214074043_glotq");
//get booking by hash
$sql1="SELECT * from bookings where hash = $hash ";
$result = mysqli_query($con,$sql1);
while($row = mysqli_fetch_array($result)) {
echo $row['id'] . ",";
echo $row['date'] . ",";
echo $row['time_section'] . ",";
echo $row['first_name'] . ",";
echo $row['last_name'] . ",";
echo $row['phone'] . ",";
echo $row['email'];
}
?>
|
Java
|
UTF-8
| 3,267
| 1.875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.syncope.core.persistence.relationships;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.syncope.core.persistence.beans.role.RAttr;
import org.syncope.core.persistence.beans.role.RAttrValue;
import org.syncope.core.persistence.beans.role.RSchema;
import org.syncope.core.persistence.dao.AttrDAO;
import org.syncope.core.persistence.dao.AttrValueDAO;
import org.syncope.core.persistence.dao.EntitlementDAO;
import org.syncope.core.persistence.dao.SchemaDAO;
import org.syncope.core.persistence.dao.RoleDAO;
import org.syncope.core.persistence.dao.UserDAO;
import org.syncope.core.AbstractTest;
import org.syncope.core.persistence.beans.PasswordPolicy;
import org.syncope.core.persistence.beans.role.SyncopeRole;
import org.syncope.core.persistence.dao.PolicyDAO;
@Transactional
public class RoleTest extends AbstractTest {
@Autowired
private UserDAO userDAO;
@Autowired
private RoleDAO roleDAO;
@Autowired
private SchemaDAO schemaDAO;
@Autowired
private AttrDAO attrDAO;
@Autowired
private AttrValueDAO attrValueDAO;
@Autowired
private EntitlementDAO entitlementDAO;
@Autowired
private PolicyDAO policyDAO;
public void createWithPasswordPolicy() {
final String ROLE_NAME = "roleWithPasswordPolicy";
PasswordPolicy policy = (PasswordPolicy) policyDAO.find(4L);
SyncopeRole role = new SyncopeRole();
role.setName(ROLE_NAME);
role.setPasswordPolicy(policy);
SyncopeRole actual = roleDAO.save(role);
assertNotNull(actual);
actual = roleDAO.find(actual.getId());
assertNotNull(actual);
assertNotNull(actual.getPasswordPolicy());
roleDAO.delete(actual.getId());
assertNull(roleDAO.find(actual.getId()));
assertNotNull(policyDAO.find(4L));
}
@Test
public void delete() {
roleDAO.delete(2L);
roleDAO.flush();
assertNull(roleDAO.find(2L));
assertEquals(1, roleDAO.findByEntitlement(
entitlementDAO.find("base")).size());
assertEquals(userDAO.find(2L).getRoles().size(), 2);
assertNull(attrDAO.find(700L, RAttr.class));
assertNull(attrValueDAO.find(41L, RAttrValue.class));
assertNotNull(schemaDAO.find("icon", RSchema.class));
}
}
|
C++
|
UTF-8
| 938
| 2.921875
| 3
|
[] |
no_license
|
#include "Functions.h"
#include "World.h"
// Возвращает освещённость точки
// Бросает много (RAYS_COUNT) лучей в направлении света с небольшим отклонением, усредняет
Color getLight(Vector3 const & pos, Vector3 const & normal) {
double globalLightIntensity = 0.0;
Vector3 dir = -world.globalLightDirection;
double d = dot(normal, dir);
if (d > 0.0)
globalLightIntensity = d;
return globalLightIntensity * world.globalLightDiffuse + world.globalLightAmbient;
}
// Расчитывает отражённый свет для блеска
Color getLightSpecular(Vector3 const & pos, Vector3 const & dir, double shininess) {
double lightIntensity = 0.0;
Vector3 lightDir = -world.globalLightDirection;
lightIntensity += pow(max(0.0, dot(dir, lightDir)), shininess);
return lightIntensity * world.globalLightDiffuse;
}
|
C#
|
UTF-8
| 236
| 2.625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args) {
List<string> list = new List<string>();
list.Add("Hello!");
Console.WriteLine(list[0].ToUpper());
}
}
|
C++
|
UTF-8
| 2,665
| 2.828125
| 3
|
[] |
no_license
|
/*
Quotek Strategies SDK 3.0
Copyright 2013-2016 Quotek SAS
*/
#ifndef LOGICALGRID_HPP
#define LOGICALGRID_HPP
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include "utils.hpp"
#define CELL_NAND 0x01
#define CELL_NOR 0x02
#define CELL_NXOR 0x03
#define CELL_AND 0x04
#define CELL_OR 0x05
#define CELL_XOR 0x06
namespace quotek {
namespace quant {
/**
* Logicalgrid is a research work meant to test if we can process
* financial time-series through an array of logical gates.
* Therefore logicalgrid is a sort of software reproduction of FPGAs (and incidentaly much slower).
* This is a meant to work along with genetics programming, to help determine
* what is the best circuit to process the time series.
* Notes for vectorization: One solution would be to express time series characteristics
* through boolean values. ex: (5min stddev >=20) ? 1: 0;
*
* GRID FILE FORMAT:
* FIRST LINE: <GRID_WIDTH> <GRID_HEIGHT>
* Each following lines is composed of the following:
* <CELL_NUM> <CELL_TYPE> <CONNECTED_TO_CELL_NUM>:<CONNECTED_CELL_INPUT_NUM>,<CONNECTED_TO_CELL_NUM>:<CONNECTED_CELL_INPUT_NUM>
*/
class logicalconn {
public:
logicalconn( void* peer , int input_num );
~logicalconn();
void* peer;
int input_num;
};
class logicalcell {
public:
logicalcell();
logicalcell(int inum);
~logicalcell();
unsigned int fct;
unsigned int output;
std::vector<unsigned int> inputs;
void run();
void bcast();
int connect( logicalcell* peer, int input_num );
std::vector<logicalconn> connections;
int inum;
};
class logicalgrid {
public:
logicalgrid(int grid_width, int grid_height );
~logicalgrid();
/** randomize creates a random grid given the initial construct parameters */
void randomize();
/** imports a previously saved grid */
static logicalgrid* import(std::string gridfile);
/** saves the current grid to file */
int save(std::string gridfile);
void connect(std::vector<int> c1,
std::vector<int> c2,
int input_num);
void connect(std::string connstring);
void run();
logicalcell& at(int x, int y);
/** 1D version of at(int,int) */
logicalcell& at(int x);
private:
std::vector<quotek::quant::logicalcell> grid;
int grid_width;
int grid_height;
int grid_size;
};
}
}
#endif
|
C++
|
UTF-8
| 691
| 3.03125
| 3
|
[] |
no_license
|
#include "Parser.h"
Parser::Parser(string fileName) {
file.open(fileName);
}
Parser::~Parser() {
file.close();
}
void Parser::readEdgesFromFile(int *maxSize) {
*maxSize = 0;
string line;
// Read first lines
getline(file, line);
getline(file, line);
// Get
int firstEdge = 0, secondEdge = 0;
int status;
while (getline(file, line)) {
status = sscanf(line.data(), "%d -> %d", &firstEdge, &secondEdge);
if(status == 2) {
edges.emplace_back(firstEdge, secondEdge);
*maxSize = max(*maxSize, max(firstEdge+1, secondEdge+1));
}
}
}
list<pair<int, int>> & Parser::getEdges() {
return edges;
}
|
Python
|
UTF-8
| 3,509
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
import sys
import Pbit.pbit_conversion_check
class Pbit_Conversion():
"""
変換系の関数を集めたモジュール
"""
def __init__(self):
self.pbit_check = Pbit.pbit_conversion_check.Pbit_Conversion_check()
def convert_decimal(self,value):
"""
This is a function to convert to decimal
Args:
value: Number to be converted
return:
ten_number: decimal
"""
Negative_counter = 0
value = str(value)
#Negative_number_check
if value[0] is "-":
value = value[1:]
Negative_counter = 1
head_type = self.pbit_check.type_decimal_number(value)
value = value[2:]
if head_type is 'two':
values = int(value,2)
ten_number = self.pbit_check.check_negative(Negative_counter,values)
return int(ten_number)
elif head_type is 'sixteen':
values = int(value,16)
ten_number = self.pbit_check.check_negative(Negative_counter,values)
return int(ten_number)
elif head_type is "ten":
sys.exit('This is value is not Binary number or Hexdecimal')
else:
sys.exit('Argument is not a numeric string ')
def convert_binary(self,value):
"""
This is a function to convert to Binary number
Args:
value: Number to be converted
return:
two_number: Binary number
"""
Negative_counter = 0
value = str(value)
#Negative_number_check
if value[0] is "-":
value = value[1:]
Negative_counter = 1
head_type = self.pbit_check.type_decimal_number(value)
if head_type is not "ten":
value = value[2:]
if head_type is 'ten':
values = bin(int(value))
two_number = self.pbit_check.check_negative(Negative_counter,values)
return two_number
elif head_type is 'sixteen':
values = bin(int(value,16))
two_number = self.pbit_check.check_negative(Negative_counter,values)
return two_number
elif head_type is 'two':
sys.exit('This is value is not Decimal number or Hexdecimal ')
else:
sys.exit("Argument is not a numeric string")
def convert_hex(self,value):
"""
This is a function to convert to Hexdecimal
Args:
value: Number to be converted
return:
hex_number: Hexdecimal
"""
Negative_counter = 0
value = str(value)
#Negative_number_check
if value[0] is "-":
value = value[1:]
Negative_counter = 1
head_type = self.pbit_check.type_decimal_number(value)
if head_type is not "ten":
value = value[2:]
if head_type is 'ten':
values = hex(int(value))
hex_number = self.pbit_check.check_negative(Negative_counter,values)
return hex_number
elif head_type is 'two':
values = hex(int(value,2))
hex_number = self.pbit_check.check_negative(Negative_counter,values)
return hex_number
elif head_type is 'sixteen':
sys.exit('This is value is not Decimal number or Binary number')
else:
sys.exit("Argument is not a numeric string")
|
C++
|
UTF-8
| 2,437
| 2.875
| 3
|
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
void __print(int x)
{
cerr << x;
}
void __print(long x) { cerr << x; }
// void __print(long long x) {cerr << x;}
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V> &x)
{
cerr << '{';
__print(x.first);
cerr << ',';
__print(x.second);
cerr << '}';
}
template <typename T>
void __print(const T &x)
{
int f = 0;
cerr << '{';
for (auto &i : x)
cerr << (f++ ? "," : ""), __print(i);
cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v)
{
__print(t);
if (sizeof...(v))
cerr << ", ";
_print(v...);
}
#ifndef ONLINE_JUDGE
#define debug(x...) \
cerr << "[" << #x << "] = ["; \
_print(x)
#else
#define debug(x...)
#endif
const int N = 2e5 + 4;
const int mod = 1e9 + 7;
/*
/https://www.interviewbit.com/problems/valid-binary-search-tree/
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
bool isBSTUtil(TreeNode *root, int minVal, int maxVal)
{
if (root == NULL)
return true;
if (root->val > minVal && root->val < maxVal &&
// node the minVal and root->val is used for left sub tree
// no elements here can be greater than root-val
isBSTUtil(root->left, minVal, root->val) && isBSTUtil(root->right, root->val, maxVal))
return true;
else
return false;
// we check if left subtree nodes value in range (minVal to root val)
// and right subtree nodes value in range (root val to maxVal) recursively
}
int Solution::isValidBST(TreeNode *A)
{
return isBSTUtil(A, INT_MIN, INT_MAX);
}
void solve()
{
}
int32_t main()
{
// ios_base::sync_with_stdio(false);cin.tie(NULL);
int tt;
tt = 1;
cin >> tt;
for (int t = 1; t <= tt; t++)
{
solve();
}
}
|
SQL
|
UTF-8
| 2,196
| 2.875
| 3
|
[] |
no_license
|
Insert into AccntTypes([Code], [NormalForm])
values ( 'DB','DB'), ('CR','CR');
insert into AccntTrxTypes([Code],[Remarks])
values ('GT','General Transaction'),('CR','Cash Receipt'),('CV','Cash Voucher'),('BK','Bank Transaction') ;
Insert into AccntCategories([Code],[Description],[OrderNo],[AccntTypeId])
values ( '1000','ASSETS',1,1),
( '2000','LIABILITIES',2,2),
( '3000','OWNERS EQUITY',3,2),
( '4000','REVENUES',4,2),
( '5000','EXPENSES',5,1),
( '6000','NON-OPERATING GAINS',6,2),
( '7000','NON-OPERATING LOSSES',7,1);
Insert into AccntMains([Code],[Name],[Remarks],[AccntTypeId],[AccntCategoryId])
values
( '10100','CASH','',1,1),
( '10200','BANK','',1,1),
( '10300','RECEIVABLES','',1,1),
( '10400','VEHICLES','',1,1),
( '10500','FIXED ASSETS','',1,1),
( '10600','INTANGIBLE ASSETS','',1,1),
( '20100','SHORT-TERM PAYABLES','',2,2),
( '20200','LONG-TERM PAYABLES','',2,2),
( '20300','WAGES','',2,2),
( '30100','OWNERS EQUITY','',2,3),
( '40100','SALES','',2,4),
( '40200','RENTAL','',2,4),
( '50100','SALARIES','',1,5),
( '50200','RENTAL','',1,5),
( '50300','UTILITIES','',1,5),
( '50400','ADVERTISING','',1,5),
( '50500','OTHERS','',1,5),
( '60100','NON-OPERATING GAINS','',2,6),
( '70100','NON-OPERATING LOSSES','',1,7);
Insert into AccntLedgers([Code],[Name],[AccntMainId],[Remarks])
values
( '1100','CASH',1,''), --10100
( '1200','BANK',2,''), --10200
( '1300','RECEIVABLES',3,''), --10300
( '1400','VEHICLES',4,''), --10400
( '1500','FIXED ASSETS',5,''), --10500
( '1600','INTANGIBLE ASSETS',6,''), --10600
( '2100','SHORT-TERM PAYABLES',7,''), --20100
( '2200','LONG-TERM PAYABLES',8,''), --20200
( '2300','WAGES',9,''), --20300
( '3100','OWNERS EQUITY',10,''), --30100
( '4100','SALES',11,''), --40100
( '4200','RENTAL',12,''), --40200
( '5100','SALARIES',13,''), --50100
( '5200','RENTAL',14,''), --50200
( '5300','UTILITIES',15,''), --50300
( '5400','ADVERTISING',16,''), --50400
( '5500','OTHERS',17,''), --50500
( '6100','NON-OPERATING GAINS',18,''), --60100
( '7100','NON-OPERATING LOSSES',19,''); --70100
-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------
|
PHP
|
UTF-8
| 2,327
| 2.78125
| 3
|
[] |
no_license
|
<?php
class model_kill extends model
{
public function __construct( $db )
{
$this->db = $db;
$this->define();
}
protected function define()
{
$t = $this;
$t->name = "kill";
$t->nice_name = "Kill";
$t->primary_table = "kills";
$t->primary_key = "kills.id";
$t->table( "kills", array(
"id" => $t->primary_key (),
"weapon" => $t->foreign_key ( "Weapon", "weapon", "select" ),
"description" => $t->text_field ( "Kill Description" ),
"assassin" => $t->foreign_key ( "Assassin", "player", "search" ),
"target" => $t->foreign_key ( "Target", "agent", "search" ),
"contested" => $t->boolean_field ( "Contested" ),
"contest" => $t->text_field ( "Contest Description" ),
"timestamp" => $t->datetime_field ( "Time of Death" ),
"game" => $t->foreign_key ( "Game", "game", "select" )
));
}
/**
* Registers kill of $assassin's target.
* Sets target as dead, makes a killboard stub.
*/
public function register_kill()
{
# 1. Initialise target
# 2. Set target dead
# 3. Initialise assassin
# 4. Increase kill count
# 5. Assign new target
# 6. E-mail killer new target?
}
public function default_form()
{
return array(
"Kill" => array(
"weapon",
"description",
"assassin",
"target",
"timestamp"
),
"Contest" => array(
"contested",
"contest"
)
);
}
public static function killboard_list()
{
$db = REGISTRY::get( "db" );
$sth = $db->prepare( "
SELECT kills.id as id,
kills.description as description,
kills.timestamp as timestamp,
assassins.name as assassin,
targets.name as target,
weapons.name as weapon,
kills.assassin as aid,
kills.target as tid
FROM kills
LEFT JOIN agents as assassins
ON kills.assassin = assassins.id
LEFT JOIN agents as targets
ON kills.target = targets.id
LEFT JOIN weapons
ON kills.weapon = weapons.id
WHERE kills.game = :curgame
ORDER BY kills.timestamp DESC
LIMIT 20
" );
$sth->bindParam( ":curgame", $gid );
$curgame = MODEL_GAME::current_games();
if( !is_array( $curgame ) )
{
return 0;
}
else
{
foreach( $curgame as $gid )
{
$sth->execute();
$res = $sth->fetchAll( PDO::FETCH_ASSOC );
$kills[ $gid ] = $res;
}
}
return $kills;
}
}
?>
|
Python
|
UTF-8
| 23,485
| 2.828125
| 3
|
[] |
no_license
|
# Created: 5/7/2019
# Purpose: To get growth rates from stack's zonal stats
# PROCESS:
# given an input csv, iterate through the unique PCA classes and filter data
# from remaining data, record and plot* growth rates:
# *record in a csv (based on class_heightMetric.csv) and plot median values + growth rate (from least squares min fit on median)
import os, sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import GLAS_zonalStats_to_database as zs # for csv to db function
from scipy import stats
batch = sys.argv[1] # i.e. Stacks_20190815
heightMetric = sys.argv[2]#'GLAS' # metric being used for height, which column(s) are used for height will depend on the metric. 1) GLAS; 2) DSM; 3) Combined
# FOR NOW, these are the column names to get the heights:
# GLAS: 'MedH' (for now)
# DSM: '2__median' (sr05_4m-sr05-min_1m-sr05-max_dz_eul_type_warp.tif median)
# Combined: '3__median' (DSM median) - 'elev_groun' (ground height from GLAS)
##def regression(X, Y, order=1): # doing linear
##
## coeffs = np.polyfit(X, Y, order) # returns [ m b ]
#### print coeffs
#### m,b = coeffs.tolist()
##
## # get r-squared and fit [function(x) that predicts y]
## fit = np.poly1d(coeffs)
#### #print fit
#### yhat = fit(X)
#### ybar = np.sum(Y)/float(len(Y))
####
#### ssreg = np.sum((yhat-ybar)**2) # same as np.sum([(yihat-ybar)**2 for yihat in yhat])
#### sstot = np.sum((Y-ybar)**2) # same as np.sum([(yi-ybar)**2 for yi in Y])
#### if sstot ==0:
#### print Y
#### print ybar
#### R2 = float(ssreg)/sstot
##
## #return m,b,R2,fit
## return fit
### try scipy, has the p-value already:
##def regression(X, Y):
# Set some variables
# The main zonal stats database/csv where all data is kept
databaseCsv = '/att/gpfsfs/briskfs01/ppl/mwooten3/3DSI/GLAS_zonal/{0}/{0}__zonalStats_15m.csv'.format(batch)
# Create variables for representative columns - this may change between runs
swapDir = '/att/gpfsfs/briskfs01/ppl/mwooten3/3DSI/GLAS_zonal/spaceForTimeSwap'
##batchDir = os.path.join(swapDir, batch)
##os.system('mkdir -p {}'.format(batchDir))
# PAY ATTENTION!!!
tccCol = '6__median' # median of LS7_CC_type_warp.tif; aka Tree Canopy Cover
inClassCol = '11__majority' # input class val from new PCA class tiff
# class layer is now accepted as is. create new col for this value anyways to write to output
classCol = 'class' # output class row (same as input now, 8/29/19)
distYrCol = '7__majority' # disturbance year; majority of C2C_change_year_type_warp
timeSinceDistCol = 'timeSinceDist' # in years; aka. data date - disturbance date
# Filter thresholds, etc.
minHeightFilter = 0.1 # must grow 0.1 meters + per year
maxHeightFilter = 1 # cannot grow > 1 m + per year
minTccFilter = 10 # blanket filter ... TCC must be 10% or more at all times
maxTccFilter = 30 # TCC must be less than 30%
minN = 30 # minumum number of samples per year needed to be included in trend
order = 1 # messing around
# Read input database into Pandas dataframe
db_df = pd.read_csv(databaseCsv)
#import pdb; pdb.set_trace()
# filter based on TCC; slope (?), other blanket filters; disturbance year not none
db_df = db_df[(db_df[tccCol] >= minTccFilter) & (db_df[tccCol] <= maxTccFilter)] # 10% <= TCC <= 30%
db_df = db_df[db_df[distYrCol] != 'None'] # Has a disturbance year
# Create time since disturbance columm; this depends on which height metric we are using
# Also create an official representative height column called height
if heightMetric == 'GLAS':
dataDateCol = db_df['shotYear']
db_df['height'] = pd.to_numeric(db_df['MedH']) #* GLAS_only FOR NOW; probably change later; float type
else:
dataDateCol = db_df['stackName'].str.slice(start=5, stop=9) # get year from stack name i.e WV01_yyyymm_etc...
if heightMetric == 'DSM':
# there may be 'None' in the 2__median column. Filter those out first
# 2 = sr05_4m-sr05-min_1m-sr05-max_dz_eul_type_warp
db_df = db_df[db_df['2__median'] != 'None']
db_df['height'] = pd.to_numeric(db_df['2__median'])
elif heightMetric == 'Combined':
# there may be 'None' in the 3__median column. Filter those out first
# 3 = out-DEM_1m_align_glas_type_warp
db_df = db_df[db_df['3__median'] != 'None']
db_df['height'] = pd.to_numeric(db_df['3__median']) - pd.to_numeric(db_df['elev_groun'])
# time since disturbance = dataDate - distDate
db_df[timeSinceDistCol] = pd.to_numeric(dataDateCol, downcast='integer') - (pd.to_numeric(db_df[distYrCol], downcast='integer')+1900)
db_df = db_df[db_df[timeSinceDistCol] > 0] # only want rows with time since disturbance > 0
# Lastly, filter using the min and max height filters
#db_df = db_df[(db_df['height']/db_df['timeSinceDist'] >= minHeightFilter) & (db_df['height']/db_df['timeSinceDist'] <= maxHeightFilter)]
# After speakinhg with Chris, this may not be the way to do it. Try this:
db_df = db_df[(db_df['height'] >= (1.37 + minHeightFilter*db_df['timeSinceDist'])) & (db_df['height'] <= (2.0 + maxHeightFilter*db_df['timeSinceDist']))]
# Get the unique PCA classes to iterate through; add extra columm to simplify
# 8/29/19: NOW PCA is as is in boreal_clust_30_30_warp layer. no longer need to do math like below
#db_df[classCol] = (db_df[inClassCol]/100000000).astype('float32').round().astype('int8')
db_df[classCol] = (db_df[inClassCol]).astype('uint16') # now just get majority val --> int. uint16 in case range of eco values is > 255 at any point
uClasses = db_df[classCol].unique()
# temporary, create csv of overview --> class, year, nSamples, median Height
##tempSummaryCsv = os.path.join(swapDir, 'classYearSummary__{}.csv'.format(heightMetric))
##with open(tempSummaryCsv, 'w') as oc:
## oc.write('Class,TimeSinceDist,nSamples,medianHeight\n')
# At this point, we have filtered down the points and we want to visualize this spatially
# So write the filtered points to csv, then use csv to make a shp
# original purpose was never used iirc. now paul wants his own csv of points that have been filtered
filteredCsv = '/att/gpfsfs/briskfs01/ppl/mwooten3/3DSI/GLAS_zonal/filteredPointCsvs/{}_{}__filteredPoints.csv'.format(batch, heightMetric)
db_df.to_csv(filteredCsv, index=False) # write filtered data frame to csv **
# csv for all heights and time since disturbance. One per height metric
valueCsv = os.path.join(swapDir, 'valueCsvs', '{}_{}__heights.csv'.format(batch, heightMetric))
with open(valueCsv, 'w') as vc:
vc.write('Ecoregion,Age,Height\n')
# last csv, we will be joining to the PCA shp
rateCsv = os.path.join(swapDir, '{}_{}__growthRates.csv'.format(batch, heightMetric))
with open(rateCsv, 'w') as rc:
rc.write('Ecoregion,slope,intercept,p-val\n')
# iterate through classes
for eco in uClasses:
class_df = db_df[db_df[classCol]==eco]
uYears = class_df['timeSinceDist'].unique() # unique time steps for class
#import pdb; pdb.set_trace()
# for all points
X_all = []#[1] # X = time since disturbance
Y_all = []#[1.37] # Y = height in meters
medDict = {} # for median values
valDict = {} # for all values
for yr in uYears:
year_df = class_df[class_df['timeSinceDist']==yr] # dataframe for eco class/year
## if int(eco) == 20 and int(yr) == 14.0:
## import pdb; pdb.set_trace()
# get the number of rows from year_df
nSamples = len(year_df)
if nSamples < minN:
#X.append(int(yr))
# else:
print "Class {}, year {} has only {} samples\n".format(eco, yr, nSamples)
continue # move on
year_heights = year_df['height']
# get all values: -- this won't work, it will replace the key every time. try lists
for i in year_heights:
X_all.append(int(yr))
Y_all.append(float(i))
# get median value of heights from year_df
medHeight = year_heights.median()
#Y.append(float(medHeight))
valDict[int(yr)] = float(medHeight)
print yr, medHeight
X = np.asarray(valDict.keys())
Y = np.asarray(valDict.values())
## m,b,R2,fit = regression(X, Y)
if len(X) < 2: # no year/only one year for class passed the minN threshold
print "Not enough years with samples for class {}".format(eco)
continue
# write all the heights to a csv if pass sample threshold
for i, x in enumerate(X_all):
y = Y_all[i]
with open(valueCsv, 'a') as vc:
vc.write('{},{},{}\n'.format(eco, x, y))
# and build X_violin and Y_violin for violin plots
X_violin = []
Y_violin = []
for uX in list(set(X_all)): # for each unique X
X_violin.append(uX) # set the x in the array
Y_arr = [] # empty list to store y's from corresponding x
for aXi, aX in enumerate(X_all): # for all x's (and by ext, y's)
if uX == aX: # if current x matches unique x we are interested in
Y_arr.append(float(Y_all[aXi])) # add corresponding Y to it
Y_violin.append(np.asarray(Y_arr)) # convert Y_arr to np, add to list
# now X_violin should be list of unique (len X) values and
# Y_violin should be list of len X with each item the corresponding Y vals
# scipy's least square linregress
m, b, r_value, p_value, std_err = stats.linregress(X, Y)
## print "{}*x + {}".format(m, b), value
title = 'Ecoregion {} | y = {:1.2f}*x + {:1.2f} | p-value = {:1.2f}'.format(eco, round(m,2), round(b, 2), round(p_value, 2))
outFig = os.path.join(swapDir, 'plot_{}_class{}.png'.format(heightMetric, eco))
fig = plt.figure(figsize=(12,8.27))
ax = fig.add_subplot(111)
ax.scatter(X_all, Y_all, color='black', alpha = 0.60, s=9) # all points
ax.plot(X, m*X + b, color = 'blue') # trendline
ax.violinplot(Y_violin, X_violin, widths=.75, points=500)#, bw_method='silverman')
ax.scatter(X, Y, color='green') # median points
ax.set_title(title, fontsize=16, fontweight='bold')#, fontdict=fonts)
ax.set_xlabel('Years Since Disturbance', fontsize=14, fontweight='bold')
ax.set_ylabel('Forest Vertical Structure (m)', fontsize=14, fontweight='bold')
ax.set_xlim(0, 35)
ax.set_ylim(0, 25)
plt.subplots_adjust(top=0.88)
fig.savefig(outFig)
## print len(X)
print "Wrote to {}\n".format(outFig)
# lastly, write stuff to csv:
with open(rateCsv, 'a') as rc:
rc.write('{:d},{:f},{:f},{:f}\n'.format(int(eco), m, b, p_value))
# create df to be written to CSV --> some attributes, height, timeSinceDist, other/all attributes temp for verification
# figure out how to send to least squares for growth rates
# write to big CSV??? heightMetric, Class, growth rate, p-value
#sys.exit()
# iterate through points: filter based on height per year, write to CSV
# then what?
# with remaining data, iterate over the years (time since dist.) and:
# get the median height and if N >= 100, record in dict/list, to be plotted --> if N < 100, I think we just do NoData
# use median heights to get
# repeat for next PCA class
# run again for different height metric
"""
start = time.time()
runN = '8'
# set data path variables
ddir = 'D:\\Maggie\\GEOG660_lidar'
figdir = os.path.join(ddir, 'Graphs', 'run_{}'.format(runN))
tbldir = os.path.join(ddir, 'Tables', 'run_{}'.format(runN))
database = os.path.join(ddir, 'GLAS_layers_zonalStats.csv')
for d in [figdir, tbldir]:
if not os.path.exists(d): os.makedirs(d)
# set thresholds and parameters
slopeThresh = 10 # No slope larger than threshold counts
lowConfidenceChange = True # turn off if we want to exclude LC change
upperGrowthThresh = 1.0 # if a stand has grown more than 1.5m each year, throw it out
lowerGrowthThresh = 0.2 # stand must grow at least 0.2 m a year or else it's trash
summaryTable = os.path.join(ddir, 'Summaries', 'regression_summary_run{}.csv'.format(runN))
with open(summaryTable, 'w') as st: # write the header:
st.write('Input .csv ={}, Slope threshold = {},LowConfidence = {},upperGrowthThresh={},lowerGrowthThresh={}\n'.format(database, slopeThresh,lowConfidenceChange,upperGrowthThresh,lowerGrowthThresh))
st.write('Name,ecoCode,permaCode,beforeFilter,afterFilter,m,b,Fit,R2\n')
# function to do regression for X and Y, and get R2
def regression(X, Y, order=1): # doing linear
coeffs = np.polyfit(X, Y, order) # returns [ m b ]
print coeffs
m,b = coeffs.tolist()
# get r-squared and fit [function(x) that predicts y]
fit = np.poly1d(coeffs)
#print fit
yhat = fit(X)
ybar = np.sum(Y)/float(len(Y))
ssreg = np.sum((yhat-ybar)**2) # same as np.sum([(yihat-ybar)**2 for yihat in yhat])
sstot = np.sum((Y-ybar)**2) # same as np.sum([(yi-ybar)**2 for yi in Y])
if sstot ==0:
print Y
print ybar
R2 = float(ssreg)/sstot
return m,b,R2,fit
ECOREGIONS_DICT = {
# ecoID: ecoName
1:'Alaska-St. Elias Range tundra',
2:'Alberta-British Columbia foothills forests',
3:'Alberta Mountain forests',
4:'British Columbia mainland coastal forests',
5:'Canadian Aspen forests and parklands',
6:'Cascade Mountains leeward forests',
7:'Central British Columbia Mountain forest',
8:'Central Pacific coastal forests',
9:'Fraser Plateau and Basin complex',
10:'Muskwa-Slave Lake forests',
11:'North Central Rockies forests',
12:'Northern Cordillera forests',
13:'Northern Pacific coastal forests',
14:'Northern transitional alpine forests',
15:'Okanagan dry forests',
16:'Pacific Coastal Mountain icefields and tundra',
17:'Palouse grasslands',
18:'Puget lowland forests',
19:'Queen Charlotte Islands',
20:'Rock and Ice',
21:'Yukon Interior dry forests',
99:'All Ecoregions'}
PERMAFROST_DICT = {
# new dict: 'permabatch': [permaNumCodeList] ... permaCode = permaName[0]
'Discontinuous': [3],
'Isolated': [2, 5],
'Sporadic': [1, 4, 9],
'Land': [8],
'Ocean/Inland Seas': [7],
'Glaciers': [6],
'All': [1,2,3,4,5,6,7,8,9]}
##PERMAFROST_DICT = {
## # new dict: 'permaName': [permaNumCodeList] ... permaCode = permaName[0]
## 'Discontinuous': [3],
## }
##
# read header and database into lists. header is a list of field names, allLines is a list of strings representing rows
with open(database, 'r') as od:
header = [f.strip() for f in od.readline().split(',')]
allLines =[f.strip() for f in od.readlines()] # read rest
print header
# first iterate through landscape options (ecoregion/permafrost combo) and read rows
e=0
for ecoCode, ecoName in ECOREGIONS_DICT.iteritems():
## print type(ecoCode), ecoName
## if int(ecoCode) != 11:
## continue
# if we want to just do permafrost type, (I, S, D, L)
# need to loop through and accept permafrost type where permaExtDesc == 'S' or etc
for permaName, permaNumCodeList in PERMAFROST_DICT.iteritems():
## print '---------------------------------'
## print permaName, permaNumCodeList
## if not permaName == 'Land':
## continue
## e+=1
## if e == 2:
## sys.exit()
permaCode = permaName[0] # D is permaCode, Discontinuous is permaName
if permaCode == 'O' or permaCode == 'G':
continue # skip water and glaciers
print "Ecoregion: {} ({})".format(ecoCode, ecoName)
print "Permafrost: {} ({})\n".format(permaCode, permaName)
# set up landscapeCombo-specific vars and outputs
landscapeCode = 'eco-{}_perma-{}'.format(ecoCode, permaCode) # i.e. eco-11_perma-D for example -- used to name files etc.
plotTitle = 'Ecoregion: {}\nPermafrost: {}'.format(ecoName, permaName) # the title of the graph -- full descriptions
outFig = os.path.join(figdir, '{}__plot.png'.format(landscapeCode))
outTbl = os.path.join(tbldir, '{}__table.csv'.format(landscapeCode))
comboCntBefore = 0 # to count the number of lines for the land combo before filter
comboCnt = 0 # to count the number of lines for the land combo after filter
X = [] # to store X values (time since dist)
Y = [] # to store Y values (height)
for lineStr in allLines:
line = lineStr.split(",")
## print (int(line[header.index("perm_med")]) in permaNumCodeList)
## print int(line[header.index("perm_med")])
## print permaNumCodeList
## if not int(line[header.index("ecoR_med")]) == int(ecoCode) or not (int(line[header.index("perm_med")]) in permaNumCodeList):
##
#### print int(line[header.index("ecoR_med")]), ecoCode
#### print int(line[header.index("perm_med")]), permaNumCodeList
#### print permaNumCodeList
#### sys.exit()
## continue
## else:
## comboCntBefore += 1
## print line
##
if int(line[header.index("ecoR_med")]) != int(ecoCode):
## print "Eco code not right"
# print int(line[header.index("ecoR_med")]), ecoCode
if ecoCode != 99:
continue
if not (int(line[header.index("perm_med")]) in permaNumCodeList):
## print "perma not right"
##
#### print int(line[header.index("ecoR_med")]), ecoCode
## print int(line[header.index("perm_med")]), permaNumCodeList
## sys.exit()
continue
else:
comboCntBefore += 1
#print line
# 1 first check: be sure there is not a wide mixture of disturbance years
distYrMin = int(line[header.index("distYr_mn")])
distYrMax = int(line[header.index("distYr_mx")])
distYrMed = int(line[header.index("distYr_med")])
if distYrMed == -9999:
continue
if distYrMax - distYrMin > 1:
print "Can't use point. Disturbance year range too large (more than a year apart). Skipping\n"
continue # skip
# now take the median to represent year. Add 1990 to convert disturbance layer year to actual year
distYear = distYrMed + 1900
print distYear
# 2 next check slope:
slope = float(line[header.index("slope_ave")])
if slope > slopeThresh:
print "Cannot use point. Slope too large ({})Skipping\n".format(slope)
continue # skip
# 3 check to be sure disturbance occured before GLAS shot
GLASyear = int(line[header.index("GLAS_year")])
timeSinceDist = GLASyear - distYear # years since disturbance has to be GTE 1
if timeSinceDist <= 0:
print "GLAS shot occurred before or same year as disturbance. Skipping\n"
print GLASyear, distYear
continue
# 4 if lowConfidenceChange is turned off, remove those whose median change type is low confidence (6)
distType = int(line[header.index("distTp_med")]) # for this there are only 2 types, so we can get the median and consider it the dominating change type
if not lowConfidenceChange:
if distType == 6:
print "Cannot use point. Low confidence change type. Skipping\n"
continue
# 5 lastly, make sure height is within growth threshold
height = float(line[header.index("rh100")])
if height < timeSinceDist * lowerGrowthThresh:
print "Height of {}m is too short for {} years".format(height, timeSinceDist)
continue
if height > timeSinceDist * upperGrowthThresh:
print "Height of {}m is too tall for {} years".format(height, timeSinceDist)
continue
# if we've made it here, we want to and add info to X (time since Dist) and Y (height)
comboCnt += 1
print timeSinceDist
print height
X.append(timeSinceDist)
Y.append(height)
print "Data points for {} before filtering: {} and after: {}".format(landscapeCode, comboCntBefore, comboCnt)
if comboCnt == 0:
print " Cannot do regression with no points\n"
with open(summaryTable, 'a') as st:
st.write("{},{},{},{},{},'--,'--,'--,'--\n".format(landscapeCode,ecoCode,permaCode,comboCntBefore,comboCnt))
continue
X = np.asarray(X) # convert python list to numpy
Y = np.asarray(Y)
# now get slope (m) and intercept (b) and R2
m,b,R2,fit = regression(X, Y, order=1)
#print m,b,R2,fit # fit prints {m} x + {b} -- represents f(x)
with open(summaryTable, 'a') as st:
st.write("{},{},{},{},{},{},{},{},{}\n".format(landscapeCode,ecoCode,permaCode,comboCntBefore,comboCnt,m,b,str(fit).strip(),R2))
#plotTitle = 'North Atlanta Dunes National Forest \nDiscontinuous Permafrost with thick overburden and blah blah ice\n '
print "Drawing plot {}".format(outFig)
fig = plt.figure(figsize=(12,8.27))
#fig = Figure(figsize=(12,8.27))
ax = fig.add_subplot(111)
ax.plot(X, m*X + b, color = 'blue')
ax.scatter(X, Y, color='green')
ax.set_title(plotTitle, fontsize=17, fontweight='bold')#, fontdict=fonts)
ax.set_xlim(min(X)-1, max(X)+1)
ax.set_ylim(-5, 35)
ax.set_xlabel('Time Since Disturbance (years)', fontsize=14, fontweight='bold')
ax.set_ylabel('Stand Height (m)', fontsize=14, fontweight='bold')
plt.subplots_adjust(top=0.88)
fig.savefig(outFig)
# write to table csv:
with open(outTbl, 'w') as ot:
for i in range(0, len(X)):
ot.write('{},{}\n'.format(X[i], Y[i]))
print '----------------------------------------\n'
print '\nFinished run{} in {} minutes'.format(runN,(time.time()-start)/60)
# TO DO:
# 1) write X and Y to csv ecorR_permaM__table.csv
# 2) add the following to summaryList
# as we are looping through different landsiteTypes/combos, we should be building csv of:
# landscapeName, ecoR, perma, n points, m, b, regression Equation, R2
# for each landscape combo, a small csv will be written with points and a plot with best fit line will be saved to image:
## tables/landscapeName_table.csv, plots/landscapeName_plots.csv
# 3) after going thru all combos, write summaryList to csv
# 4) try to also do just ecoregion and just permafrost. so straitfy by just ecor and perma. can prob do this in for loop
## #works but try another way
## #now we try to plot and save to fig:
##fig, ax = plt.subplots()
####fig.title('Title') doest work
###fig.suptitle('Growth after Disturbance\n', fontsize=30, ha='center')
####plt.tight_layout()
##ax.plot(X, m*X + b, color = 'red')
##ax.scatter(X, Y)
##ax.set_title('Growth after \nDisturbance', fontsize=30) # cuts off at top
##ax.set_xlabel('Time Since Disturbance', fontsize=20)
##ax.set_ylabel('Stand Height (m)')
##ax.xaxis.label.set_size(20)
##fig.savefig(figure)
### also works
##fig = plt.figure()
###plt.title('Title', y=1.0)
##plt.suptitle('Growth after \nDisturbance\n', fontsize=30, ha='center')
##plt.plot(X, m*X + b, color = 'red')
##plt.scatter(X, Y)
##plt.xlabel('Time Since Disturbance (years)')
##plt.ylabel('Stand Height (m)')
##fig.savefig(figure)
"""
|
Java
|
UTF-8
| 629
| 2.3125
| 2
|
[] |
no_license
|
package com.lambdatest.api;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
final class SimpleAuthenticator
extends Authenticator
{
private String username;
private String password;
SimpleAuthenticator(String username, String password)
{
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthtication()
{
return new PasswordAuthentication(username, password.toCharArray());
}
}
/* Location:
* Qualified Name: com.lambdatest.api.SimpleAuthenticator
* Java Class Version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
|
Java
|
UTF-8
| 6,917
| 2.25
| 2
|
[] |
no_license
|
package fr.ecp.IS1220.project.MyFoodora.core.tests;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import fr.ecp.IS1220.project.MyFoodora.core.Courier;
import fr.ecp.IS1220.project.MyFoodora.core.Customer;
import fr.ecp.IS1220.project.MyFoodora.core.Manager;
import fr.ecp.IS1220.project.MyFoodora.core.MyFoodora;
import fr.ecp.IS1220.project.MyFoodora.core.Order;
import fr.ecp.IS1220.project.MyFoodora.core.Restaurant;
import fr.ecp.IS1220.project.MyFoodora.core.menu.Dessert;
import fr.ecp.IS1220.project.MyFoodora.core.menu.FullMeal;
import fr.ecp.IS1220.project.MyFoodora.core.menu.HalfMeal;
import fr.ecp.IS1220.project.MyFoodora.core.menu.MainDish;
import fr.ecp.IS1220.project.MyFoodora.core.menu.Starter;
public class MyFoodoraTest {
static MyFoodora foodora = new MyFoodora(0.1, 0.1, 0.1);
static Manager Johna = new Manager("John", "jo", "john");
static Manager CEO = new Manager("Mary", "mary", "boss47");
static Manager Deputy = new Manager("John", "john", "jojojo");
static Courier Fred = new Courier("Fred", "fredo", "fred", 0, 10, "Fred@laposte.net", "0612345678");
static Courier Fredi = new Courier("Fred", "fredo", "fred", 0, 10, "Fred@laposte.net", "0612345678");
static Courier Carole = new Courier("Carole", "Coco", "~Xxcaroledu58xX~", 0, 10, "Carole@laposte.net",
"0612345678");
static Customer A1 = new Customer("A", "A", "a", 22, -24, "0654312456", "A@laposte.net");
static Customer A = new Customer("A", "A", "a", 22, -24, "0654312456", "A@laposte.net");
static Customer B = new Customer("B", "B", "b", 42, 14, "0654617456", "B@laposte.net");
static Customer C = new Customer("C", "C", "c", 52, -14, "0654312456", "C@laposte.net");
static Customer D = new Customer("D", "D", "d", -22, 42, "0658318456", "D@laposte.net");
static Customer E = new Customer("E", "E", "e", -12, 64, "0654312956", "E@laposte.net");
static Customer F = new Customer("F", "F", "f", -2, -4, "0614372456", "F@laposte.net");
static Customer G = new Customer("G", "G", "g", 0, 47, "0654312456", "G@laposte.net");
static Restaurant Bio = new Restaurant("BioFast", "biofast", -40, -10);
static Restaurant Sushi = new Restaurant("SushiWorld", "sushi", 5, -50);
static Restaurant Macdo = new Restaurant("MacDonald", "macdonald", 15, -20);
static Restaurant Quick = new Restaurant("Quick", "quick", 105, 74);
static Restaurant KFC = new Restaurant("KFC", "kfc", 40, 10);
static MainDish Drink = new MainDish("Drink", 0.5, true, true);
static MainDish BigMac = new MainDish("BigMac", 5, false, false);
static Starter Salad = new Starter("Salad", 1, true, true);
static Dessert MacFlurry = new Dessert("McFlurry", 2, true, false);
static FullMeal F1 = new FullMeal("F1", Salad, BigMac, MacFlurry);
static HalfMeal F2 = new HalfMeal("F2", Salad, Drink);
static FullMeal F9 = new FullMeal("F9", new Starter("SaucissonBio", 4, false, true),
new MainDish("ChickenBio", 4, false, true), new Dessert("IceCreamBio", 2, true, false));
static HalfMeal F10 = new HalfMeal("F10", new MainDish("Chicken2Bio", 4, false, true),
new Dessert("BetterIceCreamBio", 2, true, false));
static FullMeal F7 = new FullMeal("F7", new Starter("Saucisson", 4, false, true),
new MainDish("Chicken", 4, false, true), new Dessert("IceCream", 2, true, false));
static HalfMeal F8 = new HalfMeal("F8", new MainDish("Chicken2", 4, false, true),
new Dessert("BetterIceCream", 2, true, false));
static FullMeal F5 = new FullMeal("F5", new Starter("Sushi2", 4, false, true),
new MainDish("Sushi1", 4, false, true), new Dessert("Dessert", 2, true, false));
static HalfMeal F6 = new HalfMeal("F6", new MainDish("Sushi3", 4, false, true),
new Dessert("Dessert2", 2, true, false));
static FullMeal F3 = new FullMeal("F3", new Starter("Salad", 1, true, true),
new MainDish("Nuggets", 4, false, true), new Dessert("Donut", 2, true, false));
static HalfMeal F4 = new HalfMeal("F4", new MainDish("Nuggets", 4, false, true),
new Dessert("Donut", 2, true, false));
@Before
public void testMyFoodora() {
foodora.addUser(Johna);
foodora.addUser(CEO);
foodora.addUser(Deputy);
foodora.addUser(Macdo);
Macdo.addMeal(F1);
Macdo.addMeal(F2);
foodora.addUser(Quick);
Quick.addMeal(F3);
Quick.addMeal(F4);
foodora.addUser(Sushi);
Sushi.addMeal(F5);
Sushi.addMeal(F6);
foodora.addUser(KFC);
KFC.addMeal(F7);
KFC.addMeal(F8);
foodora.addUser(Bio);
Bio.addMeal(F9);
Bio.addMeal(F10);
foodora.addUser(Fred);
foodora.addUser(Fredi);
foodora.addUser(A1);
foodora.addUser(Carole);
foodora.addUser(A);
foodora.addUser(B);
foodora.addUser(C);
foodora.addUser(D);
foodora.addUser(E);
foodora.addUser(F);
foodora.addUser(G);
}
@Test
public void testGive() {
Order order = new Order(A, Macdo, Fred, 0.1, 0.1, 0.1);
foodora.give(order);
assertTrue(foodora.getCurrentOrder_List().contains(order));
}
@Test
public void testRegisterObserver() {
foodora.registerObserver(A);
assertTrue(foodora.getObservers().contains(A));
}
@Test
public void testUnregisterObserver() {
foodora.registerObserver(A);
assertTrue(foodora.getObservers().contains(A));
foodora.unregisterObserver(A);
assertTrue(!foodora.getObservers().contains(A));
}
@Test
public void testNotifyObservers() {
foodora.registerObserver(A);
assertTrue(foodora.getObservers().contains(A));
foodora.notifyObservers("This is a test");
}
@Test
public void testAddUser() {
foodora.removeUser(A);
assertTrue(!foodora.getUserList().values().contains(A));
foodora.addUser(A);
assertTrue(foodora.getUserList().values().contains(A));
}
@Test
public void testRemoveUser() {
foodora.addUser(A);
assertTrue(foodora.getUserList().values().contains(A));
foodora.removeUser(A);
assertTrue(!foodora.getUserList().values().contains(A));
}
@Test
public void testActivateUser() {
foodora.disactivateUser(A);
assertTrue(!A.isActivated());
foodora.activateUser(A);
assertTrue(A.isActivated());
}
@Test
public void testDisactivateUser() {
foodora.activateUser(A);
assertTrue(A.isActivated());
foodora.disactivateUser(A);
assertTrue(!A.isActivated());
}
@Test
public void testAddCourier() {
foodora.addCourier(Fred);
assertTrue(foodora.getUserList().values().contains(Fred));
foodora.removeCourier(Fred);
assertTrue(!foodora.getUserList().values().contains(Fred));
}
@Test
public void testRemoveCourier() {
foodora.removeCourier(Fred);
assertTrue(!foodora.getUserList().values().contains(Fred));
foodora.addCourier(Fred);
assertTrue(foodora.getUserList().values().contains(Fred));
}
@Test
public void testServiceFee() {
foodora.setServiceFee(15);
assertTrue(foodora.getServiceFee()==15);
}
@Test
public void testMarkupPourcentage() {
foodora.setMarkupPourcentage(15);
assertTrue(foodora.getMarkupPourcentage()==15);
}
@Test
public void testDeliveryCost() {
foodora.setDeliveryCost(15);
assertTrue(foodora.getDeliveryCost()==15);
}
}
|
Go
|
UTF-8
| 1,081
| 2.953125
| 3
|
[] |
no_license
|
package animations
import (
sfutils "github.com/GargouillePao/gosfml2ex/utils"
"time"
)
var Vector = sfutils.Utils.Vector
var Slice = sfutils.Utils.Slice
type Animation struct {
clip AnimationClip
clipHead AnimationClip
start bool
delay float64
}
type AnimateCurveFunc func(float32) float32
type OnAnimateFunc func([]float32)
type AnimateEndFunc func()
func NewAnimation(delay float64) *Animation {
return &Animation{start: false, delay: delay}
}
func (a *Animation) AddClip(clip AnimationClip) {
if a.clip == nil {
a.clip = clip
a.clipHead = clip
} else {
for {
if a.clip.GetNext() == nil {
a.clip.SetNext(clip)
a.clip = a.clipHead
return
} else {
a.clip = a.clip.GetNext()
}
}
}
}
func (a *Animation) GetFirstClip() AnimationClip {
return a.clip
}
func (a *Animation) Animate() {
if a.start {
if a.clip != nil {
a.clip.Animate()
}
}
}
func (a *Animation) Play() {
time.AfterFunc(time.Duration(a.delay*time.Duration.Seconds(1)), func() {
a.start = true
})
}
func (a *Animation) Stop() {
a.start = false
}
|
Java
|
UTF-8
| 1,044
| 2.671875
| 3
|
[] |
no_license
|
package sample;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.scene.image.ImageView;
import javafx.util.Duration;
public class Pea {
private int damage = 20;
private ImageView imageView;
private ImageView imageView2;
TranslateTransition peaTrans;
public Pea(ImageView imageView, ImageView imageView2){
this.imageView = imageView;
this.imageView2 = imageView2;
peaTrans = new TranslateTransition(Duration.seconds(2),imageView);
}
public ImageView getImageView(){
return imageView;
}
public ImageView getImageView2(){
return imageView2;
}
public void peaAnimation(ImageView plantImage)
{
peaTrans.setFromX((plantImage.getLayoutX()));
peaTrans.setToX(500);
peaTrans.setCycleCount(Timeline.INDEFINITE);
peaTrans.play();
}
public TranslateTransition getTranslateTransition(){
return peaTrans;
}
public int getDamage(){
return damage;
}
}
|
Java
|
UTF-8
| 12,224
| 1.945313
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.
*/
package org.jboss.arquillian.drone.configuration;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jboss.arquillian.drone.spi.DroneConfiguration;
import org.jboss.arquillian.impl.configuration.api.ArquillianDescriptor;
import org.jboss.arquillian.impl.configuration.api.ExtensionDef;
/**
* Utility which maps Arquillian Descriptor and System Properties to a
* configuration.
*
* @author <a href="kpiwko@redhat.com>Karel Piwko</a>
* @see DroneConfiguration
*/
public class ConfigurationMapper
{
private static final Logger log = Logger.getLogger(ConfigurationMapper.class.getName());
private Map<String, String> nameValuePairs;
private ConfigurationMapper()
{
this(Collections.<String, String> emptyMap());
}
private ConfigurationMapper(Map<String, String> nameValuePairs)
{
this.nameValuePairs = nameValuePairs;
}
/**
* Maps a configuration using Arquillian Descriptor file
*
* @param <T> Type of the configuration
* @param descriptor Arquillian Descriptor
* @param configuration Configuration object
* @param qualifier Qualifier annotation
* @return Configured configuration
*/
public static <T extends DroneConfiguration<T>> T fromArquillianDescriptor(ArquillianDescriptor descriptor, T configuration, Class<? extends Annotation> qualifier)
{
String descriptorQualifier = configuration.getConfigurationName();
String qualifierName = qualifier.getSimpleName().toLowerCase();
ConfigurationMapper mapper = new ConfigurationMapper();
mapper.setNameValuePairs(descriptor, descriptorQualifier, qualifierName);
return mapper.mapFromArquillianDescriptor(configuration);
}
/**
* Maps a configuration using System Properties
*
* @param <T> Type of the configuration
* @param configuration Configuration object
* @param qualifier Qualifier annotation
* @return Configured configuration
*/
public static <T extends DroneConfiguration<T>> T fromSystemConfiguration(T configuration, Class<? extends Annotation> qualifier)
{
String descriptorQualifier = configuration.getConfigurationName();
String qualifierName = qualifier.getSimpleName().toLowerCase();
ConfigurationMapper mapper = new ConfigurationMapper();
return mapper.mapFromSystemProperties(configuration, descriptorQualifier, qualifierName);
}
/**
* Maps configuration values from Arquillian Descriptor
*
* @param <T> A type of configuration
* @param configuration Configuration object
* @return Configured configuration of given type
*/
private <T extends DroneConfiguration<T>> T mapFromArquillianDescriptor(T configuration)
{
List<Field> fields = SecurityActions.getAccessableFields(configuration.getClass());
for (Field f : fields)
{
if (nameValuePairs.containsKey(f.getName()))
{
try
{
f.set(configuration, convert(box(f.getType()), nameValuePairs.get(f.getName())));
}
catch (Exception e)
{
throw new RuntimeException("Could not map Drone configuration(" + configuration.getConfigurationName() + ") for " + configuration.getClass().getName() + " from Arquillan Descriptor", e);
}
}
}
return configuration;
}
/**
* Maps configuration values from System properties
*
* @param <T> A type of configuration
* @param configuration Configuration object
* @param descriptorQualifier A qualifier used for extension configuration in
* the descriptor
* @param qualifierName Name of the qualifier passed
* @return Configured configuration of given type
*/
private <T extends DroneConfiguration<T>> T mapFromSystemProperties(T configuration, String descriptorQualifier, String qualifierName)
{
List<Field> fields = SecurityActions.getAccessableFields(configuration.getClass());
String fullQualifiedPrefix = new StringBuilder("arquillian.").append(descriptorQualifier).append("-").append(qualifierName).append(".").toString();
// get fields with qualifier included
Map<Field, String> fieldValuePairs = getFieldValuePairs(fields, fullQualifiedPrefix);
// get fields without qualifier included
if (fieldValuePairs.isEmpty())
{
String prefix = new StringBuilder("arquillian.").append(descriptorQualifier).append(".").toString();
fieldValuePairs = getFieldValuePairs(fields, prefix);
}
for (Map.Entry<Field, String> entry : fieldValuePairs.entrySet())
{
try
{
entry.getKey().set(configuration, convert(box(entry.getKey().getType()), entry.getValue()));
}
catch (Exception e)
{
throw new RuntimeException("Could not map Drone configuration(" + configuration.getConfigurationName() + ") for " + configuration.getClass().getName() + " from System properties", e);
}
}
return configuration;
}
/**
* Maps fields to values using System configuration properties
*
* @param fields Fields to be mapped
* @param prefix System property prefix
* @return Mapped values
*/
private Map<Field, String> getFieldValuePairs(Collection<Field> fields, String prefix)
{
Map<Field, String> fieldValuePairs = new HashMap<Field, String>();
for (Field f : fields)
{
String fieldName = keyTransform(new StringBuilder(prefix).append(f.getName()));
String value = SecurityActions.getProperty(fieldName);
if (value != null)
{
fieldValuePairs.put(f, value);
}
}
return fieldValuePairs;
}
/**
* Parses Arquillian Descriptor into property name - value pairs
*
* @param descriptor An Arquillian Descriptor
* @param descriptorQualifier A qualifier used for extension configuration in
* the descriptor
* @param qualifierName Name of the qualifier passed
*/
private void setNameValuePairs(ArquillianDescriptor descriptor, String descriptorQualifier, String qualifierName)
{
String fullDescriptorQualifier = new StringBuilder(descriptorQualifier).append("-").append(qualifierName).toString();
ExtensionDef match = null;
for (ExtensionDef extension : descriptor.getExtensions())
{
if (fullDescriptorQualifier.equals(extension.getExtensionName()))
{
this.nameValuePairs = extension.getExtensionProperties();
if (log.isLoggable(Level.FINE))
{
log.fine("Using <extension qualifier=\"" + extension.getExtensionName() + "\"> for Drone Configuration");
}
return;
}
else if (descriptorQualifier.equals(extension.getExtensionName()))
{
match = extension;
}
}
// found generic only
if (match != null)
{
this.nameValuePairs = match.getExtensionProperties();
if (log.isLoggable(Level.FINE))
{
log.fine("Using <extension qualifier=\"" + match.getExtensionName() + "\"> for Drone Configuration");
}
return;
}
}
/**
* Maps a field name to a property.
*
* Replaces camel case with a dot ('.') and lower case character, replaces
* other non digit and non letter characters with a dot (').
*
* @param fieldName The name of field
* @return Corresponding property name
*/
private String keyTransform(String fieldName)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fieldName.length(); i++)
{
char c = fieldName.charAt(i);
if (Character.isUpperCase(c))
{
sb.append('.').append(Character.toLowerCase(c));
}
else if (!Character.isLetterOrDigit(c))
{
sb.append('.');
}
else
{
sb.append(c);
}
}
return sb.toString();
}
private String keyTransform(StringBuilder fieldName)
{
return keyTransform(fieldName.toString());
}
/**
* A helper boxing method. Returns boxed class for a primitive class
*
* @param primitive A primitive class
* @return Boxed class if class was primitive, unchanged class in other cases
*/
private Class<?> box(Class<?> primitive)
{
if (!primitive.isPrimitive())
{
return primitive;
}
if (int.class.equals(primitive))
{
return Integer.class;
}
else if (long.class.equals(primitive))
{
return Long.class;
}
else if (float.class.equals(primitive))
{
return Float.class;
}
else if (double.class.equals(primitive))
{
return Double.class;
}
else if (short.class.equals(primitive))
{
return Short.class;
}
else if (boolean.class.equals(primitive))
{
return Boolean.class;
}
else if (char.class.equals(primitive))
{
return Character.class;
}
else if (byte.class.equals(primitive))
{
return Byte.class;
}
throw new IllegalArgumentException("Unknown primitive type " + primitive);
}
/**
* A helper converting method.
*
* Converts string to a class of given type
*
* @param <T> Type of returned value
* @param clazz Type of desired value
* @param value String value to be converted
* @return Value converted to a appropriate type
*/
private <T> T convert(Class<T> clazz, String value)
{
if (String.class.equals(clazz))
{
return clazz.cast(value);
}
else if (Integer.class.equals(clazz))
{
return clazz.cast(Integer.valueOf(value));
}
else if (Double.class.equals(clazz))
{
return clazz.cast(Double.valueOf(value));
}
else if (Long.class.equals(clazz))
{
return clazz.cast(Long.valueOf(value));
}
else if (Boolean.class.equals(clazz))
{
return clazz.cast(Boolean.valueOf(value));
}
else if (URL.class.equals(clazz))
{
try
{
return clazz.cast(new URI(value).toURL());
}
catch (MalformedURLException e)
{
throw new IllegalArgumentException("Unable to convert value " + value + " to URL", e);
}
catch (URISyntaxException e)
{
throw new IllegalArgumentException("Unable to convert value " + value + " to URL", e);
}
}
else if (URI.class.equals(clazz))
{
try
{
return clazz.cast(new URI(value));
}
catch (URISyntaxException e)
{
throw new IllegalArgumentException("Unable to convert value " + value + " to URL", e);
}
}
throw new IllegalArgumentException("Unable to convert value " + value + "to a class: " + clazz.getName());
}
}
|
C#
|
UTF-8
| 3,506
| 2.53125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RichardSzalay.MockHttp;
using Xunit;
namespace Sendy.Client.Tests
{
public class SendyClientSubscribeTests
{
private readonly MockHttpMessageHandler _httpMessageHandlerMock;
private readonly SendyClient _target;
public SendyClientSubscribeTests()
{
var baseUri = new Uri("http://foo");
var apiKey = "123ABC";
_httpMessageHandlerMock = new MockHttpMessageHandler();
var httpClient = _httpMessageHandlerMock.ToHttpClient();
httpClient.BaseAddress = baseUri;
_target = new SendyClient(baseUri, apiKey, null, httpClient);
}
[Fact]
public async Task Subscribe_WithValidData_ReturnsOk()
{
//arrange
var emailAddress = "foo@poo.nl";
var name = "Jeroen";
var listId = "xyz123";
var expectedPostData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("email", emailAddress),
new KeyValuePair<string, string>("name", name),
new KeyValuePair<string, string>("list", listId)
};
_httpMessageHandlerMock.Expect("/subscribe")
.WithFormData(expectedPostData)
.Respond("text/plain", "1");
//act
var result = await _target.SubscribeAsync(emailAddress, name, listId);
//assert
_httpMessageHandlerMock.VerifyNoOutstandingExpectation();
Assert.True(result.IsSuccess);
}
[Fact]
public async Task Subscribe_WithInValidList_ReturnsError()
{
//arrange
var emailAddress = "foo@poo.nl";
var name = "Jeroen";
var listId = "invalidId";
var expectedError = "Invalid list ID.";
var expectedPostData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("email", emailAddress),
new KeyValuePair<string, string>("name", name),
new KeyValuePair<string, string>("list", listId)
};
_httpMessageHandlerMock.Expect("/subscribe")
.WithFormData(expectedPostData)
.Respond("text/plain", expectedError);
//act
var result = await _target.SubscribeAsync(emailAddress, name, listId);
//assert
_httpMessageHandlerMock.VerifyNoOutstandingExpectation();
Assert.False(result.IsSuccess);
Assert.Equal("Invalid list ID.", result.ErrorMessage);
}
[Fact]
public async Task Subscribe_WithCustomFields_ReturnsOk()
{
//arrange
var emailAddress = "foo@poo.nl";
var name = "Jeroen";
var listId = "xyz123";
var customFields = new Dictionary<string, string> {{"customField1", "foo"}, {"customField2", "poo"}};
var expectedPostData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("email", emailAddress),
new KeyValuePair<string, string>("name", name),
new KeyValuePair<string, string>("list", listId),
new KeyValuePair<string, string>("customField1", "foo"),
new KeyValuePair<string, string>("customField2", "poo")
};
_httpMessageHandlerMock.Expect("/subscribe")
.WithFormData(expectedPostData)
.Respond("text/plain", "1");
//act
var result = await _target.SubscribeAsync(emailAddress, name, listId, customFields);
//assert
//this one validates that custom fields are send to the api
_httpMessageHandlerMock.VerifyNoOutstandingExpectation();
Assert.True(result.IsSuccess);
}
}
}
|
Python
|
UTF-8
| 3,770
| 2.859375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
"""
import pickle
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectPercentile
from sklearn.feature_selection import chi2
import config
class CharTfidfFeatureGenerator(object):
def __init__(self, name='charTfidfFeatureGenerator'):
self.name = name
def process(self, df):
print('process:', self.name)
# 1). create strings based on text
train = df[df['type'] == 'train']
print(train.head())
test = df[df['type'] == 'test']
print(test.head())
print('train.shape:', train.shape)
n_train = train.shape[0]
print('n_train:', n_train)
n_test = test.shape[0]
print('n_test:', n_test)
# 2). fit a TfidfVectorizer on text
vec_text = TfidfVectorizer(analyzer='char', ngram_range=(1, 2),
max_df=0.8, min_df=2, sublinear_tf=True)
text_tfidf = vec_text.fit_transform(df['text'].tolist())
print('text Tfidf.shape:', text_tfidf.shape)
vocabulary = vec_text.vocabulary_
print('vocabulary size:%d' % len(vocabulary))
print('vocabulary list:')
count = 0
for k, v in vocabulary.items():
if count < 10:
print("%s\t%s" % (k, v))
count += 1
print("feature set nums: ", len(vocabulary))
feature_names = vec_text.get_feature_names()
ch2_precent = SelectPercentile(chi2, percentile=5)
ch2 = ch2_precent.fit(text_tfidf[:n_train], df.iloc[:n_train]['label'])
text_tfidf = ch2_precent.transform(text_tfidf)
features = [feature_names[i] for i in ch2.get_support(indices=True)]
feature_scores = [ch2.scores_[i] for i in ch2.get_support(indices=True)]
sorted_feature = sorted(zip(features, feature_scores), key=lambda x: x[1], reverse=True)
feature_output_file = config.output_dir + 'char_tfidf_feature.txt'
with open(feature_output_file, "w", encoding="utf-8") as f:
for id, item in enumerate(sorted_feature):
f.write("\t".join([str(id + 1), item[0], str(item[1])]) + "\n")
print("feature select done, new feature set num: ", len(feature_scores))
# save train and test into separate files
tfidf_train = text_tfidf[:n_train, :]
tfidf_train_feature_path = config.output_dir + "train.text.char.tfidf.pkl"
with open(tfidf_train_feature_path, "wb") as f:
pickle.dump(tfidf_train, f)
print('text tfidf features of training set saved in %s' % tfidf_train_feature_path)
tfidf_test = None
if n_test > 0:
# test set is available
tfidf_test = text_tfidf[n_train:, :]
tfidf_test_feature_path = config.output_dir + "test.text.char.tfidf.pkl"
with open(tfidf_test_feature_path, "wb") as f:
pickle.dump(tfidf_test, f)
print('text tfidf features of test set saved in %s' % tfidf_test_feature_path)
return tfidf_train.toarray(), tfidf_test.toarray(), train['label'].values
def read(self, header='train'):
text_feature_path = config.output_dir + "%s.text.char.tfidf.pkl" % header
with open(text_feature_path, "rb") as f:
text_tfidf = pickle.load(f)
print('text_char_tfidf.shape:', text_tfidf.shape)
return [text_tfidf]
def read_chartfidf_feature_label():
data = pd.read_pickle(config.ngram_feature_path)
return CharTfidfFeatureGenerator().process(data)
if __name__ == '__main__':
data = pd.read_pickle(config.ngram_feature_path)
CharTfidfFeatureGenerator().process(data)
|
Swift
|
UTF-8
| 3,235
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// CardImageTableViewCell.swift
// Decktracker
//
// Created by Jovit Royeca on 16/07/2016.
// Copyright © 2016 Jovit Royeca. All rights reserved.
//
import UIKit
import CoreData
import SDWebImage
class CardImageTableViewCell: UITableViewCell {
// MARK: Variables
private var _cardOID: NSManagedObjectID?
var cardOID : NSManagedObjectID? {
get {
return _cardOID
}
set (newValue) {
if (_cardOID != newValue) {
_cardOID = newValue
displayCard()
}
}
}
// var backgroundImage:UIImage?
var cardBackImage:UIImage?
// MARK: Outlets
@IBOutlet weak var cardImage: UIImageView!
// MARK: Overrides
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// backgroundImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/Gray_Patterned_BG.jpg")
cardBackImage = UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/cardback.hq.jpg")
// cardImage.backgroundColor = UIColor(patternImage: backgroundImage!)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: Custom methods
func displayCard() {
if let _cardOID = _cardOID {
let card = CoreDataManager.sharedInstance.mainObjectContext.objectWithID(_cardOID) as! Card
if let urlPath = card.urlPath,
let imageCacheKey = card.imageCacheKey {
if let cachedImage = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(imageCacheKey) {
cardImage.image = cachedImage
} else {
cardImage.image = cardBackImage
let completedBlock = { (image: UIImage?, data: NSData?, error: NSError?, finished: Bool) -> Void in
if let image = image {
SDImageCache.sharedImageCache().storeImage(image, forKey: imageCacheKey)
performUIUpdatesOnMain {
UIView.transitionWithView(self.cardImage, duration: 1.0, options: .TransitionFlipFromRight, animations: {
self.cardImage.image = image
}, completion: nil)
}
} else {
performUIUpdatesOnMain {
self.cardImage.image = self.cardBackImage
}
}
}
let downloader = SDWebImageDownloader.sharedDownloader()
downloader.downloadImageWithURL(urlPath, options: .UseNSURLCache, progress: nil, completed: completedBlock)
}
} else {
cardImage.image = cardBackImage
}
} else {
cardImage.image = cardBackImage
}
}
}
|
Java
|
UTF-8
| 2,080
| 2.5625
| 3
|
[] |
no_license
|
/*
* Copyright (C) 2003-2011 eXo Platform SAS.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.exoplatform.social.xmlprocessor;
import java.util.Iterator;
import java.util.LinkedList;
/**
* The Processor is an Object which contain many Filter clustered as a queue
* each input should run though many filter using Processor.
*
* @author Ly Minh Phuong - http://phuonglm.net
*
*/
public class Processor {
LinkedList<Filter> filters;
/**
* Add Filter to Processor
*
* @param filter
*/
public void addFilter(Filter filter) {
filters.add(filter);
}
/**
* Remove a filter which instant of Class from queue.
*
* @param className
*/
public void removeFilter(Class className) {
LinkedList<Filter> filtersClone = (LinkedList<Filter>) filters.clone();
for (Iterator<Filter> filterIterator = filtersClone.iterator(); filterIterator.hasNext();) {
Filter filter = filterIterator.next();
if (filter.getClass().equals(className)) {
filters.remove(filter);
}
}
}
Processor() {
filters = new LinkedList<Filter>();
}
/**
* Process an Object though Filter chain.
*
* @param input
* @return
*/
public Object process(Object input) {
for (Iterator<Filter> filterIterator = filters.iterator(); filterIterator
.hasNext();) {
Filter filter = filterIterator.next();
input = filter.doFilter(input);
}
return input;
}
}
|
JavaScript
|
UTF-8
| 250
| 3.265625
| 3
|
[] |
no_license
|
function some(arr, callback) {
index= -1;
var result = [];
var resultIndex = 0;
for(var i=0; i < arr.length; i++){
if(callback(arr[i]) === true){
return true;
}
}
return false;
}
|
Java
|
UTF-8
| 20,243
| 2.296875
| 2
|
[] |
no_license
|
import java.awt.CardLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import tools.DBConnect;
public class Indox extends JPanel {
private JLabel lblUser;
private JTextField fromField;
private JTextField vsubjectField;
private JTextField toField;
private JTextField subjectField;
private JComboBox comboBox;
private Connection connection;
private JTable table;
private JTextArea vmessageArea;
private JTextArea messageArea;
private CardLayout clayout;
private JButton btnSave;
private JButton btnSend;
private JButton btnDeleteMessage;
private static int card =1,lastmessageloaded;
/**
* Create the panel.
*/
public Indox() {
connection = DBConnect.dbconnect();
JScrollPane scrollPane = new JScrollPane();
comboBox = new JComboBox();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String loadlist;
PreparedStatement pst;
try{
if(comboBox.getSelectedIndex()==0){
loadlist = "select id,title from messages where messagefor = ? and messagefrom <> ? order by time desc";
pst = connection.prepareStatement(loadlist);
pst.setString(1, Mainlogin.usrname);
pst.setString(2, Mainlogin.usrname);
}
else if(comboBox.getSelectedIndex()==1){
loadlist = "select id,title from messages where messagefrom = ? and status = ? order by time desc";
pst = connection.prepareStatement(loadlist);
pst.setString(1, Mainlogin.usrname);
pst.setString(2, "sent");
}
else if(comboBox.getSelectedIndex()==2){
loadlist = "select id,title from messages where messagefor = ? and status = ? order by time desc";
pst = connection.prepareStatement(loadlist);
pst.setString(1, Mainlogin.usrname);
pst.setString(2, "saved");
}
else{
loadlist = "SELECT id,title FROM messages where messagefrom = ? or messagefor = ?";
pst = connection.prepareStatement(loadlist);
pst.setString(1, Mainlogin.usrname);
pst.setString(2, Mainlogin.usrname);
}
ResultSet rst = pst.executeQuery();
table.setModel(Rs2TableModel.resultSetToTableModel(rst,false));
table.getColumnModel().getColumn(0).setPreferredWidth(25);
table.getColumnModel().getColumn(0).setHeaderValue("ID");
table.getColumnModel().getColumn(1).setHeaderValue("Message");
pst.close();
rst.close();
} catch(Exception e){
e.printStackTrace();
}
}
});
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Indox", "Sent", "Saved", "All Messages"}));
JPanel panel = new JPanel();
panel.setBorder(UIManager.getBorder("PopupMenu.border"));
JButton btnNewMessage = new JButton("New Message");
btnNewMessage.setIcon(new ImageIcon(this.getClass().getResource("/NewMessage.png")));
btnNewMessage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
clayout.show(panel, "newpanel");
card=2;
btnSave.setText("Save");
btnSave.setEnabled(true);
btnSend.setEnabled(true);
}
});
btnNewMessage.setFont(new Font("Tahoma", Font.PLAIN, 11));
JButton btnClose = new JButton("Close");
btnClose.setIcon(new ImageIcon(this.getClass().getResource("/Close.png")));
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Mainbody.tabbedPane.remove(Mainbody.tabbedPane.getSelectedComponent());
}
});
btnClose.setFont(new Font("Tahoma", Font.PLAIN, 11));
btnSend = new JButton("Send");
btnSend.setIcon(new ImageIcon(this.getClass().getResource("/Send.png")));
btnSend.setEnabled(false);
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if(Mainlogin.isfieldsempty(toField,subjectField)){
}
else if(checkuser(toField.getText())){
String query = "INSERT INTO messages (messagefrom, messagefor, title, body, status) VALUES(?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, Mainlogin.usrname);
pst.setString(2, toField.getText());
pst.setString(3, subjectField.getText());
pst.setString(4, messageArea.getText());
pst.setString(5, "sent");
pst.execute();
pst.close();
btnSend.setEnabled(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnSend.setFont(new Font("Tahoma", Font.PLAIN, 11));
btnDeleteMessage = new JButton("Delete Message");
btnDeleteMessage.setIcon(new ImageIcon(this.getClass().getResource("/Delete.png")));
btnDeleteMessage.setEnabled(false);
btnDeleteMessage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(table.getSelectedRow()>-1){
try {
int choice = JOptionPane.showConfirmDialog(null, "You REALLY Want to Delete Selected Message?","Confirmation",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
switch(choice){
case JOptionPane.YES_OPTION:
String query = "DELETE FROM messages WHERE id = ?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setInt(1, (int) table.getValueAt(table.getSelectedRow(),0));
pst.execute();
pst.close();
btnDeleteMessage.setEnabled(false);
break;
default:
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
btnDeleteMessage.setFont(new Font("Tahoma", Font.PLAIN, 11));
btnSave = new JButton("Save");
btnSave.setIcon(new ImageIcon(this.getClass().getResource("/Save.png")));
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(card==1){
if(Mainlogin.isfieldsempty(fromField,vsubjectField)){
}
else{
try {
String query = "INSERT INTO messages (messagefrom, messagefor, title, body, status) VALUES(?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, fromField.getText());
pst.setString(2, Mainlogin.usrname);
pst.setString(3, vsubjectField.getText());
pst.setString(4, vmessageArea.getText());
pst.setString(5, "saved");
pst.execute();
pst.close();
btnSave.setText("Saved");
btnSave.setEnabled(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
else{
if(Mainlogin.isfieldsempty(subjectField,toField)){
}
else{
try {
String query = "INSERT INTO messages (messagefrom, messagefor, title, body, status) VALUES(?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, Mainlogin.usrname);
pst.setString(2, Mainlogin.usrname);
pst.setString(3, subjectField.getText());
pst.setString(4, messageArea.getText());
pst.setString(5, "saved");
pst.execute();
pst.close();
btnSave.setText("Saved");
btnSave.setEnabled(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
});
btnSave.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblUser = new JLabel("");
lblUser.setHorizontalAlignment(SwingConstants.CENTER);
lblUser.setFont(new Font("Tahoma", Font.PLAIN, 16));
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(10)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(comboBox, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE))
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(10)
.addComponent(btnNewMessage)
.addGap(18)
.addComponent(lblUser, GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE)
.addGap(18)
.addComponent(btnDeleteMessage)))
.addPreferredGap(ComponentPlacement.RELATED))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(btnSave)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnSend)
.addGap(10)
.addComponent(btnClose)))
.addGap(10))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(11)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
.addComponent(btnNewMessage)
.addComponent(btnDeleteMessage)
.addComponent(lblUser, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
.addGap(8)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnClose, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnSave)
.addComponent(btnSend, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
table = new JTable();
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt){
if(evt.getClickCount()>=2){
if(table.getSelectedRow()>-1){
loadmessage((int) table.getValueAt(table.getSelectedRow(),0));
clayout.show(panel, "viewpanel");
card=1;
btnSend.setEnabled(false);
}
}
}
});
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
clayout = new CardLayout(0, 0);
panel.setLayout(clayout);
JPanel ViewMessages = new JPanel();
ViewMessages.setName("viewpanel");
panel.add(ViewMessages,"viewpanel");
JLabel lblFrom = new JLabel("From:- ");
fromField = new JTextField();
fromField.setName("From");
fromField.setEditable(false);
fromField.setColumns(10);
JLabel lblSubject = new JLabel("Subject:- ");
vsubjectField = new JTextField();
vsubjectField.setName("Subject");
vsubjectField.setEditable(false);
vsubjectField.setColumns(10);
JLabel lblvMessage = new JLabel("Message:- ");
JScrollPane scrollPane_1 = new JScrollPane();
vmessageArea = new JTextArea();
vmessageArea.setName("Message Body");
vmessageArea.setWrapStyleWord(true);
vmessageArea.setLineWrap(true);
vmessageArea.setOpaque(false);
vmessageArea.setEditable(false);
scrollPane_1.setViewportView(vmessageArea);
JButton btnForward = new JButton("Forward");
btnForward.setIcon(new ImageIcon(this.getClass().getResource("/Forward.png")));
btnForward.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
toField.setText("");
subjectField.setText(vsubjectField.getText());
messageArea.setText(vmessageArea.getText());
clayout.show(panel, "newpanel");
card=2;
btnSave.setText("Save");
btnSave.setEnabled(true);
btnSend.setEnabled(true);
}
});
btnForward.setFont(new Font("Tahoma", Font.PLAIN, 11));
GroupLayout gl_ViewMessages = new GroupLayout(ViewMessages);
gl_ViewMessages.setHorizontalGroup(
gl_ViewMessages.createParallelGroup(Alignment.LEADING)
.addGroup(gl_ViewMessages.createSequentialGroup()
.addGap(10)
.addGroup(gl_ViewMessages.createParallelGroup(Alignment.LEADING)
.addGroup(gl_ViewMessages.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(lblvMessage))
.addGroup(gl_ViewMessages.createParallelGroup(Alignment.TRAILING)
.addComponent(lblFrom)
.addComponent(lblSubject)))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_ViewMessages.createParallelGroup(Alignment.TRAILING)
.addComponent(vsubjectField, GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE)
.addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(gl_ViewMessages.createSequentialGroup()
.addComponent(fromField, GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addGap(166)))
.addGap(37)
.addComponent(btnForward)
.addContainerGap())
);
gl_ViewMessages.setVerticalGroup(
gl_ViewMessages.createParallelGroup(Alignment.LEADING)
.addGroup(gl_ViewMessages.createSequentialGroup()
.addGroup(gl_ViewMessages.createParallelGroup(Alignment.LEADING)
.addGroup(gl_ViewMessages.createSequentialGroup()
.addGap(14)
.addGroup(gl_ViewMessages.createParallelGroup(Alignment.BASELINE)
.addComponent(fromField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblFrom))
.addGroup(gl_ViewMessages.createParallelGroup(Alignment.LEADING)
.addGroup(gl_ViewMessages.createSequentialGroup()
.addGap(17)
.addComponent(lblSubject))
.addGroup(gl_ViewMessages.createSequentialGroup()
.addGap(14)
.addComponent(vsubjectField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addGap(11)
.addGroup(gl_ViewMessages.createParallelGroup(Alignment.BASELINE)
.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
.addComponent(lblvMessage)))
.addGroup(Alignment.TRAILING, gl_ViewMessages.createSequentialGroup()
.addContainerGap(163, Short.MAX_VALUE)
.addComponent(btnForward)))
.addContainerGap())
);
ViewMessages.setLayout(gl_ViewMessages);
JPanel NewMessage = new JPanel();
NewMessage.setName("newpanel");
panel.add(NewMessage,"newpanel");
JLabel lblTo = new JLabel("To:- ");
toField = new JTextField();
toField.setName("To Field");
toField.setColumns(10);
JLabel lblSubject_1 = new JLabel("Subject:- ");
subjectField = new JTextField();
subjectField.setName("Subject");
subjectField.setColumns(10);
JLabel lblMessage = new JLabel("Message:-");
JScrollPane scrollPane_2 = new JScrollPane();
messageArea = new JTextArea();
messageArea.setName("Message Body");
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
scrollPane_2.setViewportView(messageArea);
JButton btnCancel = new JButton("Cancel");
btnCancel.setIcon(new ImageIcon(this.getClass().getResource("/Close.png")));
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
loadmessage(lastmessageloaded);
clayout.show(panel, "viewpanel");
card=1;
btnSend.setEnabled(false);
}
});
btnCancel.setFont(new Font("Tahoma", Font.PLAIN, 11));
JButton btnReset = new JButton("Reset");
btnReset.setIcon(new ImageIcon(this.getClass().getResource("/Reset.png")));
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
toField.setText("");
messageArea.setText("");
subjectField.setText("");
}
});
btnReset.setFont(new Font("Tahoma", Font.PLAIN, 11));
GroupLayout gl_NewMessage = new GroupLayout(NewMessage);
gl_NewMessage.setHorizontalGroup(
gl_NewMessage.createParallelGroup(Alignment.LEADING)
.addGroup(gl_NewMessage.createSequentialGroup()
.addContainerGap()
.addGroup(gl_NewMessage.createParallelGroup(Alignment.TRAILING)
.addComponent(lblTo)
.addComponent(lblSubject_1)
.addComponent(lblMessage))
.addGap(10)
.addGroup(gl_NewMessage.createParallelGroup(Alignment.LEADING)
.addGroup(gl_NewMessage.createSequentialGroup()
.addComponent(toField, GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
.addGap(219))
.addGroup(Alignment.TRAILING, gl_NewMessage.createSequentialGroup()
.addGroup(gl_NewMessage.createParallelGroup(Alignment.TRAILING)
.addComponent(subjectField, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
.addComponent(scrollPane_2, GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_NewMessage.createParallelGroup(Alignment.TRAILING, false)
.addComponent(btnReset, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnCancel, GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE))))
.addContainerGap())
);
gl_NewMessage.setVerticalGroup(
gl_NewMessage.createParallelGroup(Alignment.LEADING)
.addGroup(gl_NewMessage.createSequentialGroup()
.addContainerGap()
.addGroup(gl_NewMessage.createParallelGroup(Alignment.BASELINE)
.addComponent(lblTo)
.addComponent(toField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_NewMessage.createParallelGroup(Alignment.BASELINE)
.addComponent(subjectField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblSubject_1))
.addGap(18)
.addGroup(gl_NewMessage.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_NewMessage.createParallelGroup(Alignment.BASELINE)
.addComponent(scrollPane_2, GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
.addComponent(lblMessage))
.addGroup(gl_NewMessage.createSequentialGroup()
.addComponent(btnReset)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(btnCancel)))
.addContainerGap())
);
NewMessage.setLayout(gl_NewMessage);
setLayout(groupLayout);
lblUser.setText("Indox for :- " + Mainlogin.usrname.toUpperCase());
}
void loadmessage(int mid){
try {
String query = "select * from messages where id = ?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setInt(1, mid);
ResultSet rst = pst.executeQuery();
if(rst.next()){
fromField.setText(rst.getString("messagefrom"));
vsubjectField.setText(rst.getString("title"));
vmessageArea.setText(rst.getString("body"));
if(rst.getString("status").equals("saved")){
btnSave.setText("Saved");
btnSave.setEnabled(false);
}
else{
btnSave.setText("Save");
btnSave.setEnabled(true);
}
btnDeleteMessage.setEnabled(true);
}
lastmessageloaded = mid;
pst.close();
rst.close();
lblUser.setText("Indox for :- " + Mainlogin.usrname.toUpperCase());
} catch (Exception e) {
e.printStackTrace();
}
}
boolean checkuser(String user){
try {
String query = "select * from accounts where username = ?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, user);
ResultSet rst = pst.executeQuery();
if(rst.next()){
return true;
}
else{
JOptionPane.showMessageDialog(null, "User NOT Found Please Check");
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
|
PHP
|
UTF-8
| 4,508
| 2.71875
| 3
|
[] |
no_license
|
<?php
namespace Service;
class GeovoileParser
{
private $x, $_report;
public function __construct($report)
{
$this->_report = $report;
}
public function setXml($f)
{
$tmp = glob($f);
if (1 !== count($f)) {
throw new \Exception($f . ' not found');
}
$this->x = simplexml_load_file($tmp[0]);
}
/*
<reports>
<report id="1" date="2013/02/06 12:50:25Z">
<v i="1" st="" d="37363" s="266" c="222" o="0" />
<v i="255" st="" d="-134" s="257" c="216" o="0" />
</report>
*/
public function getReports()
{
$ret = [];
foreach ($this->x->reports->report as $k => $report) {
$reportId = (int) $report->attributes()->id;
$date = (string) $report->attributes()->date; // 2013/02/06 13:18:00Z
$dt = \DateTime::createFromFormat('Y/m/d H:i:sZ', $date, new \DateTimeZone('UTC'));
$dt->setTimeZone(new \DateTimeZone('Europe/Paris'));
foreach ($report->v as $k => $boat) {
$boatId = (int) $boat->attributes()->i;
// if (1 !== $boatId) {
// continue;
// }
$tmp = [
'boatId' => $boatId,
'date' => $dt->format('Y-m-d'),
'time' => $dt->format('H:i'),
'dt' => $dt->format('Y-m-d H:i:s'),
'timestamp' => $dt->getTimestamp(),
'status' => (string) $boat->attributes()->st,
'speed' => (int) $boat->attributes()->s / 10,
'dtf' => (int) $boat->attributes()->d / 10,
'dtl_diff' => (int) $boat->attributes()->l / 10,
'heading' => (int) $boat->attributes()->c,
'offset' => (int) $boat->attributes()->o,
];
if ($boatId === 17) {
echo __METHOD__ . ' ' . $tmp['boatId'] . '-' . $tmp['timestamp'] . '-' . $tmp['dt'] . PHP_EOL;
}
$ret[$boatId][ $dt->getTimestamp() ] = $tmp;
}
}
return $ret;
}
public function getTracks()
{
$ret = [];
foreach ($this->x->tracks->track as $track) {
$boatId = (int) $track->attributes()->id;
// if (1 !== $boatId) {
// return false;
// }
$_points = explode(';', $track);
$lat = $lon = $ts = 0;
foreach ($_points as $_point) {
$tmp = explode(',', $_point);
$lat += (int) $tmp[0] / 100000;
$lon += (int) $tmp[1] / 100000;
$ts += (int) $tmp[2];
$dt = new \DateTime();
$dt->setTimestamp($ts);
$tmp = [
'boatId' => $boatId,
'date' => $dt->format('Y-m-d'),
'time' => $dt->format('H:i'),
'dt' => $dt->format('Y-m-d H:i:s'),
'timestamp' => $dt->getTimestamp(),
'lat_dec' => $lat,
'lon_dec' => $lon,
'lat_dms' => self::DECtoDMS($lat),
'lon_dms' => self::DECtoDMS($lon),
];
echo __METHOD__ . ' ' . $tmp['boatId'] . '-' . $tmp['timestamp'] . '-' . $tmp['dt'] . PHP_EOL;
$ret[$boatId][ $dt->getTimestamp() ] = $tmp;
}
return $ret;
}
return $ret;
}
public function merge($a, $b)
{
$ret = [];
$report = $this->_report->schema();
foreach ($a as $boatId => $_reports) {
foreach ($_reports as $ts => $_report) {
if (!isset($b[$boatId][$ts])) {
continue;
}
$tmp = $_report + $b[$boatId][$ts];
$ret[$boatId][$ts] = $tmp;
}
}
return $ret;
}
public static function DECtoDMS($dec)
{
if (!strpos($dec, '.')) {
$dec = $dec . '.0';
}
$vars = explode('.', $dec);
$deg = $vars[0];
$tempma = '0.' . $vars[1];
$tempma = $tempma * 3600;
$min = floor($tempma / 60);
$sec = $tempma - ($min * 60);
return $deg . '°' . $min . '.' . round($sec);
return [
'deg' => $deg,
'min' => $min,
'sec' => $sec,
];
}
}
|
TypeScript
|
UTF-8
| 2,433
| 2.546875
| 3
|
[] |
no_license
|
import { Request, Response } from "express";
import { classToClass } from "class-transformer";
import CreateCityService from "../../services/Cities/CreateCityService";
import UpdateCityService from "../../services/Cities/UpdateCityService";
import ListAllCitiesService from "../../services/Cities/ListAllCitiesService";
import DeleteCityService from "../../services/Cities/DeleteCityService";
export default class CitiesController {
public async index(request: Request, response: Response): Promise<Response> {
try {
const listAllCities = new ListAllCitiesService();
const user_id = request.user.id;
const cities = await listAllCities.run({
user_id,
});
return response.status(200).json(classToClass(cities));
} catch (err) {
return response.status(400).json({ error: err.message });
}
}
public async create(request: Request, response: Response): Promise<Response> {
try {
const createCities = new CreateCityService();
const user_id = request.user.id;
const image = request.file.filename;
const { name, description } = request.body;
const city = await createCities.run({
name,
image,
description,
user_id,
});
return response.status(200).json(classToClass(city));
} catch (err) {
return response.status(400).json({ error: err.message });
}
}
public async update(request: Request, response: Response): Promise<Response> {
try {
const updateCity = new UpdateCityService();
const user_id = request.user.id;
const { name, description } = request.body;
const { city_id } = request.params;
const city = await updateCity.run({
user_id,
city_id,
name,
description,
});
return response.status(200).json(classToClass(city));
} catch (err) {
return response.status(400).json({ error: err.message });
}
}
public async delete(request: Request, response: Response): Promise<Response> {
try {
const deleteCity = new DeleteCityService();
const user_id = request.user.id;
const { city_id } = request.params;
await deleteCity.run({
user_id,
city_id,
});
return response.status(200).json({ sucess: "Deleted city with success" });
} catch (err) {
return response.status(400).json({ error: err.message });
}
}
}
|
PHP
|
UTF-8
| 3,305
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
<?php
// Do something more than starting session, if needed
function tdlStartSession()
{
Ef_Session::start();
}
// Application model...
function appGetTitle()
{
$selectsqlreq = new F_SqlReq("
select ap_title from tdlapplication
",'tdlist');
return $selectsqlreq->getValue();
}
function appGetSubTitle()
{
$selectsqlreq = new F_SqlReq("
select ap_subtitle from tdlapplication
",'tdlist');
$appsubtitle = $selectsqlreq->getValue();
Ef_Log::log($appsubtitle, 'appsubtitle');
return $appsubtitle;
}
function appGetAdminType()
{
$selectsqlreq = new F_SqlReq("
select ap_admintype from tdlapplication
",'tdlist');
return $selectsqlreq->getValue();
}
// User model...
function tdlUserCheckPassword($login, $password)
{
$checkpassreq = new Ef_SqlReq("
select us_login from tdluser where us_login = '$login' and us_password = '$password'
",'tdlist');
// Ef_Log::log ($checkpasssql, ' checkpasssql in cmUserCheckPassword');
$checkpassvalue = $checkpassreq->getValue();
// Ef_Log::log ($checkpassvalue, ' checkpassvalue in cmUserCheckPassword');
if ($checkpassvalue == $login) {
return true;
} else {
return false;
}
}
function tdlUserSetConnected($login)
{
Ef_Session::setVal('login', $login);
}
function tdlUserDisconnect()
{
Ef_Session::delKey('login');
}
function tdlUserIsConnected()
{
if (Ef_Session::getVal('login')) {
return true;
} else {
return false;
}
}
function tdlUserGetWelcomeMessage()
{
if (Ef_Session::getVal('login')) {
$login = Ef_Session::getVal('login');
return Ef_Lang::get('Hi, %1 !', array($login));
} else {
return Ef_Lang::get('You are not connected');
}
}
function tdlGetUsers()
{
$sqlreq = new Ef_SqlReq("
select tdlus.usid, tdlus.us_login from tdluser tdlus
order by tdlus.usid
",'tdlist');
$rows = $sqlreq->getRows();
$userarray = array('');
foreach ($rows as $row) {
$code = $row['usid'];
$name = Ef_Lang::get($row['us_login']);
$userarray[$code] = $name;
}
// test : big number of users
// for ($i = 1; $i < 100; $i++) {
// $userarray['user'.$i] = 'name of user'.$i;
// }
return $userarray;
}
// Project model...
function tdlGetProjects()
{
$sqlreq = new Ef_SqlReq("
select tdlpr.prid, tdlpr.pr_title from tdlproject tdlpr
order by tdlpr.prid
",'tdlist');
$rows = $sqlreq->getRows();
$projectarray = array('');
foreach ($rows as $row) {
$code = $row['prid'];
$name = Ef_Lang::get($row['pr_title']);
$projectarray[$code] = $name;
}
return $projectarray;
}
// Status model...
function tdlGetStatus()
{
$sqlreq = new Ef_SqlReq("
select tdlst.stid, tdlst.st_title from tdlstatus tdlst
order by tdlst.stid
",'tdlist');
$rows = $sqlreq->getRows();
$statusarray = array('');
foreach ($rows as $row) {
$code = $row['stid'];
$name = Ef_Lang::get($row['st_title']);
$statusarray[$code] = $name;
}
return $statusarray;
}
?>
|
C++
|
UTF-8
| 812
| 3.671875
| 4
|
[] |
no_license
|
#include <iostream>
using namespace std;
int main()
{
float age, newAge;
cout << "Please enter your age: "; //Prompt and input for user age.
cin >> age;
if (age <= 0) { //Invalidate zero and negative inputs.
cout << "Invalid Input." << endl;
}
else if (age <= 2) {
newAge = 5.25 * age; //If first two years are 10.5 a year would be 5.25.
cout << "Your age in dog years is: " << newAge << endl;
}
else {
newAge = 10.5 + ((age-2) * 4); //Add 10.5 to account for the first 2 years and multiply the rest by 4
cout << "Your age in dog years is: " << newAge << endl;
}
system("pause > 0");
return 0;
}
|
PHP
|
UTF-8
| 929
| 3.1875
| 3
|
[] |
no_license
|
<?php
Class Pet
{
protected $id;
protected $petRace;
protected $petName;
protected $petSex;
protected $petAge;
public function getPetId()
{
return $this->id;
}
public function setPetId($id)
{
$this->id = $id;
}
public function getPetRace()
{
return $this->petRace;
}
public function setPetRace($petRace)
{
$this->petRace = $petRace;
}
public function getPetName()
{
return $this->petName;
}
public function setPetName($petName)
{
$this->petName = $petName;
}
public function getPetSex()
{
return $this->petSex;
}
public function setPetSex($petSex)
{
$this->petSex = $petSex;
}
public function getPetAge()
{
return $this->petAge;
}
public function setPetAge($petAge)
{
$this->petAge = $petAge;
}
}
|
Java
|
UTF-8
| 425
| 1.726563
| 2
|
[] |
no_license
|
package com.kelvin.ecbook.activity;
import android.app.Activity;
import android.os.Bundle;
import com.kelvin.ecbook.config.Config;
import cn.bmob.v3.Bmob;
/**
* Created by Kelvin on 2016/4/22.
*/
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bmob.initialize(this, Config.ApplicationId);
}
}
|
Java
|
UTF-8
| 758
| 1.71875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demonlp;
/**
*
* @author admin
*/
public class CommonDefine {
public static final String VERB = "verb";
public static final String ADJECTIVE = "adjective";
public static final String ADVERB = "adverb";
public static final String CONJUNCTION = "conjunction";
public static final String INTERJECTION = "interjection";
public static final String PREPOSITION = "prepositions";
public static final String PRONOUN = "pronoun";
public static final String NOUN = "noun";
}
|
Java
|
UTF-8
| 463
| 2.5625
| 3
|
[] |
no_license
|
package com.shir.androidfinalproject.Models;
import java.text.DateFormat;
import java.util.Date;
/**
* Created by shir on 29-Aug-17.
*/
public class EventDate extends Votes {
public Date date;
public EventDate (Date date){
this.date = date;
}
public String displayDate() {
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
String str = dateFormat.format(this.date);
return str;
}
}
|
Markdown
|
UTF-8
| 1,161
| 3.421875
| 3
|
[] |
no_license
|
---
id: operators-ex
title: Exercise
---
### Exercise
### What's the output of the following, write the output next to the code as comment
1. `5 * "5"` = ?
2. `6 + "7"` = ?
3. `1 + "JS"` = ?
4. `1 * "JS"` = ?
5. `5 + true` = ?
6. `6 - true` = ?
7. `7 - false` = ?
8. `8 + false` = ?
9. `true + true` = ?
10. `true + false` = ?
### Output of each line of code :
- `3 * '8'`
- `1 + '21' + 32`
- `"string" ? 4 : 1`
- `undefined ? 4 : 1`
- `4 * Number("")`
- `4 * 0`
- `4 / '2'`
- `4 + true`
- `3 * false`
- `3 * ""`
- `3 + ""`
### Output of the following line of code.
```js
"NaN" && "undefined" && 0; // output
"AT" && "" && false; // output
"AT" && " " && false; // output
"AT" || 5; // output
" " || "AT" || false; // output
!{}; //output
!""; //output
!"OK"; //output
!false; //output
!true; //output
```
### Double and Tripal equal
```js
var a = 5,
b = 10,
c = "5";
var x = a;
```
### What will be the output of the code below on the basis of above code.
```js
a == c; // output
a === c; // output
a == x; // output
a != b; // output
a > b; // output
a < b; // output
a >= b; // output
a <= b; // output
a >= c; // output
a <= c; // output
```
|
Go
|
UTF-8
| 2,563
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
package main
import (
"bufio"
"log"
"math"
"os/exec"
"time"
)
type IItem interface {
GetName() string
Aggregate(item IItem)
}
type ISample interface {
Append(item IItem)
Empty() bool
GetMap() map[string]IItem
}
type ISampleProcessor interface {
GetCmdName() string
GetCmdArgs() []string
AggregateSample(sample ISample)
NewSample() ISample
IsHeader(row string) bool
ParseRow(row string) (IItem, error)
}
type ISampleStats interface {
Append(value float64)
GetAverage() float64
}
type DynamicCollector struct {
processor ISampleProcessor
}
func NewDynamicCollector(processor ISampleProcessor) *DynamicCollector {
return &DynamicCollector{
processor: processor,
}
}
func (d *DynamicCollector) Run() {
pipe := make(chan string, 1000)
go d.executeCmd(d.processor.GetCmdName(), d.processor.GetCmdArgs(), pipe)
go d.processOutput(pipe)
}
func (d *DynamicCollector) processOutput(ch <-chan string) {
sample := d.processor.NewSample()
for row := range ch {
if d.processor.IsHeader(row) {
if sample != nil && !sample.Empty() {
d.processor.AggregateSample(sample)
}
sample = d.processor.NewSample()
continue
}
p, err := d.processor.ParseRow(row)
if err != nil {
continue
}
sample.Append(p)
}
}
func (d *DynamicCollector) executeCmd(name string, args []string, ch chan<- string) {
execute_cmd := func() {
cmd := exec.Command(name, args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err = cmd.Start(); err != nil {
log.Fatal(err)
}
defer cmd.Wait()
in := bufio.NewScanner(stdout)
for in.Scan() {
ch <- in.Text()
}
}
for true {
execute_cmd()
time.Sleep(time.Second)
}
}
type StatSample struct {
total float64
count float64
max float64
}
func NewStatSample(value float64) *StatSample {
return &StatSample{
total: value,
count: 1,
}
}
func (s *StatSample) Append(value float64) {
s.count += 1
s.total += value
s.max = math.Max(s.max, value)
}
func (s *StatSample) GetAverage() float64 {
return s.total / s.count
}
func (s *StatSample) GetMax() float64 {
return s.max
}
type Sample struct {
data map[string]IItem
}
func NewSample() *Sample {
return &Sample{
data: make(map[string]IItem, 10),
}
}
func (d *Sample) Append(item IItem) {
name := item.GetName()
if val, has := d.data[name]; has {
val.Aggregate(item)
} else {
d.data[name] = item
}
}
func (d *Sample) Empty() bool {
if len(d.data) > 0 {
return false
}
return true
}
func (d *Sample) GetMap() map[string]IItem {
return d.data
}
|
Python
|
UTF-8
| 3,911
| 2.78125
| 3
|
[] |
no_license
|
# coding: utf-8
# In[158]:
import numpy as np
import os
import math
from scipy import misc
from PIL import Image
import matplotlib.pyplot as plt
import sys
from sklearn.manifold import TSNE
train_N = 280
test_N = 120
C=40
input_path = sys.argv[1]
output_path = sys.argv[2]
def average(image_array):
average_f = np.mean(image_array, axis=0)
average = np.round(average_f).astype(np.uint8)
return average_f
def train_avg_class(training_set , NsubC_dim):
avgface_class = np.zeros( (40 , NsubC_dim) )
for i in range(40):
avgface_class[i] = average(training_set[i*7:(i+1)*7])#.reshape(56,46)
#plt.imshow(avgface_class[i], cmap='gray')
#plt.show()
return avgface_class
def PCA(data , average):
mu = data - average
U, S, VT = np.linalg.svd(mu ,full_matrices=False)
#output eigenfaces
#print(U.shape)
#print(S.shape)
#print(VT.shape)
V =VT.T
return V
def readfile():
training_set = np.zeros( (280 , 56,46) )
testing_set = np.zeros( (120 , 56,46) )
index_train = 0
index_test = 0
for i in range(1,41): #input filename example: 1_1.png 40_10.png
for j in range(1,11):
file_mame = input_path +'/'+str(i) + '_' + str(j) + '.png'
image= misc.imread(file_mame)
if j > 7:
testing_set[index_test] = image
index_test += 1
else:
training_set[index_train] = image
index_train += 1
training_set = training_set.reshape((280,56*46))
testing_set = testing_set.reshape((120,56*46))
return training_set , testing_set
if __name__ == "__main__":
print('main')
training_set , testing_set = readfile()
trainset_averageFACE = average(training_set)
test_averageFACE = average(testing_set)
X_train = training_set - trainset_averageFACE
train_EigenFace = PCA(training_set , trainset_averageFACE )
test_EigenFace = PCA(testing_set , test_averageFACE )
print('train_EigenFace :' , train_EigenFace.shape )
train_PCA_useful_eigen = train_EigenFace[:, 0:(train_N - C)]
print('PCA_useful_eigen :' , train_PCA_useful_eigen.shape)
train_projected_data = np.dot( training_set , train_PCA_useful_eigen)
print('PCA_projected_data :',train_projected_data.shape) #dim = 280*240
train_avgface_class = train_avg_class(train_projected_data , train_projected_data.shape[1])
print('avg_class: ',train_avgface_class.shape) #dim = 40*240
train_avgface_all = average(train_projected_data)
print('avg_glb : ',train_avgface_all.shape) #dim = 240
#test_avgface_all = average(testing_set)
SB = 7 * np.dot( (train_avgface_class - train_avgface_all).T , ((train_avgface_class - train_avgface_all)))
print('SB: ' , SB.shape)
SW = np.zeros((240,240))
for i in range(C):
X = train_projected_data - train_avgface_class[i]
SW += np.dot(X.T , X)
print('SW: ' , SW.shape)
e_vals, e_vecs = np.linalg.eig(np.linalg.inv(SW).dot(SB))
e_vecs = e_vecs.real
e_vecs = e_vecs[: , :C-1]
#print(e_vecs)
#print(e_vecs.shape)
#print('Eigenvectors \n%s' %e_vecs)
#print('\nEigenvalues \n%s' %e_vals)
fisherface = np.dot( train_PCA_useful_eigen , e_vecs )
fisherface = fisherface.T
output = fisherface[0].reshape(56,46)
misc.imsave(output_path ,output)
'''
#plt top five fisherfaces
fig = plt.figure(figsize=(9, 9))
for i in range(5):
img = fisherface[i].reshape(56,46)
ax = fig.add_subplot(1, 5, i+1)
plt.xlabel('fisherface: ' +str(i))
ax.imshow(img, cmap='gray')
plt.yticks(np.array([]))
plt.xticks(np.array([]))
#plt.tight_layout()
plt.show()
'''
print('over')
|
C
|
UTF-8
| 4,478
| 3.578125
| 4
|
[] |
no_license
|
/*
* General implementation of semaphores.
*
*--------------------------------------------------------------------
* Adapted from code for CS24 by Jason Hickey.
* Copyright (C) 2003-2010, Caltech. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
#include "sthread.h"
#include "semaphore.h"
/* This data structure is used exclusively with semaphores and allows us to
* to keep track of a linked list of threads that are blocked by a given
* semaphore.
*/
typedef struct _blocked_threads {
Thread * threadp;
struct _blocked_threads *next;
} BlockedThreads;
/*
* The semaphore data structure contains a value for the semaphore and two
* pointers to a linked list of blocked threads (from the head of the list and
* the tail of the list).
*/
struct _semaphore {
// Value of the semaphore
unsigned int value;
// Pointers to the linked list of threads
BlockedThreads * head;
BlockedThreads * tail;
};
/* This function takes in a semaphore and a thread and adds the thread to the
* linked list of threads that are blocked by the semaphore
*/
void add_thread(Semaphore *s, Thread *t) {
// We can't perform this operation if s or t are NULL
assert(s != NULL);
assert(t != NULL);
// Allocated memory for the linked list
BlockedThreads *b = (BlockedThreads *) malloc(sizeof(BlockedThreads));
if (b == NULL) {
fprintf(stderr, "Couldn't allocate enough memory for blocked thread linked list");
exit(2);
}
// Set values for the linked list
b->threadp = t;
b->next = NULL;
// The semaphore is not currently blocking any threads
if (s->head == NULL) {
// Set both head and tail to be the linked list containing this thread
assert(s->tail == NULL);
s->head = b;
s->tail = b;
}
// There are threads that are blocked by this semaphore
else {
assert(s->tail != NULL);
// Add this thread to the end of the list
s->tail->next = b;
s->tail = b;
}
}
/* This function gets a thread that is currently blocked by the semaphore given
* in the input.
*/
Thread * get_thread(Semaphore *s) {
// Temporary variable
Thread *threadp = NULL;
assert(s != NULL);
// Check if any threads are blocked by s, if so
if (s->head != NULL) {
// Get the first thread off the linked list
BlockedThreads *b = s->head;
// Rearrange the linked list to remove this thread
s->head = b->next;
if (s->head == NULL) {
s->tail = NULL;
}
// Store this thread to return it
threadp = b->threadp;
free(b);
}
return threadp;
}
/************************************************************************
* Top-level semaphore implementation.
*/
/*
* Allocate a new semaphore. The initial value of the semaphore is
* specified by the argument.
*/
Semaphore *new_semaphore(int init) {
Semaphore *semp = NULL;
assert(init >= 0);
// Allocate memory for the new semaphore
semp = (Semaphore *) malloc(sizeof(Semaphore));
if (semp == NULL) {
fprintf(stderr, "Couldn't allocate enough memory for a semaphore");
exit(2);
}
// Set values for the semaphore. Since this is new, there are no threads
// blocked by it currently.
semp->value = init;
semp->head = NULL;
semp->tail = NULL;
return semp;
}
/*
* Decrement the semaphore.
* This operation must be atomic, and it blocks iff the semaphore is zero.
*/
void semaphore_wait(Semaphore *semp) {
assert(semp != NULL);
// Avoid interruption from scheduler
__sthread_lock();
assert(semp->value >= 0);
// Do in a while loop for all threads trying the acquire the semaphore
while (semp->value == 0) {
// Block until semaphore is available
add_thread(semp, sthread_current());
sthread_block();
// Block removes the lock, so we have to relock
__sthread_lock();
}
assert(semp->value > 0);
semp->value = semp->value - 1;
__sthread_unlock();
}
/*
* Increment the semaphore.
* This operation must be atomic.
*/
void semaphore_signal(Semaphore *semp) {
Thread * t;
assert(semp != NULL);
__sthread_lock();
assert(semp->value >= 0);
semp->value = semp->value + 1;
t = get_thread(semp);
// If there are threads that are blocked by the semaphore, we remove the
// first thread from the linked list and unblock it
if (t != NULL) {
sthread_unblock(t);
}
else {
__sthread_unlock();
}
}
|
C#
|
UTF-8
| 1,630
| 3.859375
| 4
|
[] |
no_license
|
using System;
namespace Kalkulaator
{
class Program
{
static void Main(string[] args)
{
double firstnum;
double secondnum;
double answer;
string ops;
Console.WriteLine("\t\t\tConsole Calculator Tutorial in C#\r");
Console.WriteLine("\t\t\t---------------------------------\r");
Console.WriteLine("\t\t\tEnter first number\n");
firstnum = Double.Parse(Console.ReadLine());
Console.WriteLine("\t\t\tSelect an Operator: (+, -, *, /, %, ^)\n");
ops = Console.ReadLine();
Console.WriteLine("\t\t\tEnter second number\n");
secondnum = Double.Parse(Console.ReadLine());
if (ops == "+")
{
answer = firstnum + secondnum;
Console.WriteLine(answer);
}
if (ops == "-")
{
answer = firstnum - secondnum;
Console.WriteLine("\n" + answer);
}
if (ops == "*")
{
answer = firstnum * secondnum;
Console.WriteLine("\n" + answer);
}
if (ops == "/")
{
answer = firstnum / secondnum;
Console.WriteLine("\n" + answer);
}
if (ops == "%")
{
answer = firstnum % secondnum;
Console.WriteLine("\n" + answer);
}
Console.Write("\n" + "Press any key to exit...");
Console.ReadKey();
}
}
}
|
Python
|
UTF-8
| 875
| 3.015625
| 3
|
[] |
no_license
|
import cupy as cp
y_pred = [1, 2, 3, 4]
y_true = [2, 2, 3, 4]
y_true = cp.asarray(y_true)
y_pred = cp.asarray(y_pred)
def check_length(y_true, y_pred):
if len(y_true) == len(y_pred):
return True
else:
return False
def weight_sum(sample_score, sample_weight, normalize):
if normalize:
return cp.average(sample_score, weights=sample_weight)
elif sample_weight is not None:
return cp.dot(sample_score, sample_weight)
else:
return sample_score.sum()
def hamming_loss(y_true, y_pred, *, sample_weight=None):
if check_length(y_true, y_pred) is True:
try:
return float(weight_sum(y_true != y_pred,
sample_weight, normalize=True))
except ValueError:
raise ValueError("{0} is not supported".format(y_true))
hamming_loss(y_true, y_pred)
|
C#
|
UTF-8
| 1,593
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MineQuest
{
static class Noise
{
private const float brownianOffset = 32000f; // hack to prevent negative numbers from being fed into Perlin noise
public static float BrownianMotion(float x, float z, int octaves, float persistence)
{
float total = 0;
float frequency = 1;
float amplitude = 1;
float maxValue = 0;
for (int i = 0; i < octaves; i++)
{
total += Mathf.PerlinNoise((x + brownianOffset) * frequency, (z + brownianOffset) * frequency) * amplitude;
maxValue += amplitude;
amplitude *= persistence;
frequency *= 2;
}
return total / maxValue;
}
public static float BrownianMotion3d(float x, float y, float z, float smoothFactor, int octaves)
{
float xy = BrownianMotion(x * smoothFactor, y * smoothFactor, octaves, 0.5f);
float yz = BrownianMotion(y * smoothFactor, z * smoothFactor, octaves, 0.5f);
float xz = BrownianMotion(x * smoothFactor, z * smoothFactor, octaves, 0.5f);
float yx = BrownianMotion(y * smoothFactor, x * smoothFactor, octaves, 0.5f);
float zy = BrownianMotion(z * smoothFactor, y * smoothFactor, octaves, 0.5f);
float zx = BrownianMotion(z * smoothFactor, x * smoothFactor, octaves, 0.5f);
return (xy + yz + xz + yx + zy + zx) / 6.0f;
}
}
}
|
Python
|
UTF-8
| 1,904
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
class Validator(object):
def __init__(self, attrs={}, **kwargs):
self.errors = {}
if type(attrs) is dict:
for attr in attrs:
setattr(self, attr, attrs[attr])
for attr in kwargs:
setattr(self, attr, kwargs[attr])
def __getattr__(self, name):
def _missing(*args, **kwargs):
return None
return _missing()
def validate(self):
raise Exception("You must implement the validate() function in a subclass")
def is_valid(self):
self.errors = {}
self.validate()
return len(self.errors) == 0
def assert_present(self, attr, message = "not_present"):
try:
att = getattr(self, attr)
except AttributeError:
att = None
if att is None:
self._add_error(attr, message)
return False
return True
def assert_list(self, attr, message="not_valid"):
try:
lst = getattr(self, attr)
except AttributeError:
lst = None
if type(lst) is not list:
self._add_error(attr, message)
return False
return True
def assert_not_present(self, attr, message="not_allowed"):
try:
if getattr(self, attr) is not None:
self._add_error(attr, message)
return False
except AttributeError:
pass
return True
def assert_in(self, lst, attr, message = "{}_not_in_list"):
val = getattr(self, attr)
if type(lst) is not list:
self._add_error(lst, "not_valid")
return
if not val in lst:
self._add_error(attr, message.format(val))
def _add_error(self, attr, error):
if self.errors.get(attr) is None:
self.errors[attr] = []
self.errors[attr].append(error)
|
C++
|
UTF-8
| 989
| 2.546875
| 3
|
[] |
no_license
|
#include <iostream>
#include <cmath>
using namespace std;
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "sophus/so3.h"
#include "sophus/se3.h"
int main()
{
Eigen::Matrix3d R = Eigen::AngleAxisd(M_PI/2, Eigen::Vector3d(0,0,1)).toRotationMatrix();
Sophus::SO3 SO3_R(R);
Sophus::SO3 SO3_v(0,0,M_PI/2);
Eigen::Quaterniond q(R);
Sophus::SO3 SO3_q(q);
cout << "SO(3) from matrix: "<<SO3_R << endl;
cout << "SO(3) from vector: "<<SO3_v << endl;
cout << "SO(3) from quaternion: "<<SO3_q << endl;
cout << "=====================================================================================" << endl;
Eigen::Vector3d so3 = SO3_R.log();
cout<<"so3 = " <<so3.transpose()<<endl;
cout<<"so3 hat= "<<Sophus::SO3::hat(so3)<<endl;
cout<<"so3 hat vee = "<<Sophus::SO3::vee(Sophus::SO3::hat(so3)).transpose();
cout << "=====================================================================================" << endl;
return 0;
}
|
Python
|
UTF-8
| 581
| 3.265625
| 3
|
[] |
no_license
|
import numpy as np
def func1(x):
return (x**3) * (np.log(x))
def regra_trapezio_comp(x, y):
rtrap = []
n = len(x)
for i in range(n):
if i == 0 or i == n-1:
rtrap.append(y[i])
else:
rtrap.append(2*y[i])
I_1 = (h/2)*sum(rtrap)
return I_1
intervalo_ini = 1
intervalo_final = 3
sub_divisoes = 4
h = (intervalo_final - intervalo_ini) / sub_divisoes
x = [i for i in np.arange(intervalo_ini, intervalo_final+0.1, h)]
y = [round(func1(i), 4) for i in x]
print(x)
print(y)
I_1 = regra_trapezio_comp(x, y)
print(I_1)
|
C++
|
UTF-8
| 1,866
| 3.875
| 4
|
[] |
no_license
|
#include <string>
#include <vector>
#include <cctype>
#include <iostream>
#include <algorithm>
using namespace std;
/* -------------- Helper Methods -------------- */
// return true if c is one of ‘ ‘/’,’/’.’/’!’/’?’
bool is_punctuation_mark(char c){
return c == ' ' || c == ',' || c == '.' || c == '!' || c == '?';
}
void lower_each_string(vector<string>& data){
for (string& str: data){
for (char& c; str){
c = tolower(c);
}
}
}
void sort_each_string(vector<string>& data){
for (string& str: data){
sort(str.begin(), str.end());
}
}
/* -------------- Main Methods -------------- */
vector<string> split_to_words(string str){
vector<string> words;
string curr_str;
for (int i = 0; i<str.length() ; ++i){
char curr_char = str[i];
// Reaching a punctuation mark means an end of a word. Add the accumulated word to the vector.
if (is_punctuation_mark(curr_char) && !curr_str.empty()){
words.push_back(curr_str);
curr_str.clear();
}
// add character to the current word
else if (!is_punctuation_mark(curr_char)){
curr_str += curr_char;
}
}
// save the last word in the sentence, in case it ends with a word
if (!curr_str.empty()){
words.push_back(curr_str);
}
return words;
}
bool are_anagrams(string str1, string str2, bool case_sensitive = false){
vector<string> words1 = split_to_words(str1);
vector<string> words2 = split_to_words(str2);
// compare number of words in each vector
if (words1.size() != words2.size()){
return false;
}
// lower all characters if we are handling case insensitive.
if (!case_sensitive){
lower_each_string(words1);
lower_each_string(words2);
}
// sort each word in words1, words2 vectors
sort_each_string(words1);
sort_each_string(words2);
sort(words1.begin(), words1.end());
sort(words2.begin(), words2.end());
return words1 == words2;
}
|
Ruby
|
UTF-8
| 1,449
| 2.8125
| 3
|
[] |
no_license
|
# ACPI module for 'bd'
require 'libnotify'
@notifyWarning = false
@notifyCritical = false
@n = nil
def close_notify()
unless @n.nil?
@n.close
@n = nil
end
end
def notify(level, battery, time)
close_notify
@n = Libnotify.new(:summary => "Battery #{level}",
:body => "Battery level: #{battery}, Time: #{time}",
:urgency => level == 'Critical' ? :critical : :normal)
@n.update
end
def magic
charging = false
capacity = ''
time = ''
output = ""
IO.popen("acpitool -b") do |a| output += a.read end
output.split("\n").each do |line|
next unless line.include? ':'
parts = line.split(':', 2)
parts = parts[1].strip.split(',')
return if parts.length < 2
charging = parts[0].strip == 'Charging' || parts[0].strip == 'Full'
capacity = parts[1].strip
time = parts[2].strip if parts.length > 2
end
@bd.add_tooltip("Battery", "#{charging ? "Charging" : "Discharging" }, #{capacity}, #{time}")
if charging == true
@notifyWarning = @notifyCritical = false
close_notify
return
end
value = capacity.to_i
if value < 5
return if @notifyCritical == true
@notifyCritical = true
notify("Critical", capacity, time)
return
end
if value < 10
return if @notifyWarning == true
@notifyWarning = true
notify("Warning", capacity, time)
return
end
end
GLib::Timeout.add 5000 do
magic
true
end
magic
|
C++
|
UTF-8
| 1,035
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
#include <iostream>
#include <vector>
#include <string>
using LocPair = std::pair<int, std::string>;
using LocGrades = std::vector<LocPair>;
LocGrades init_loc_grades() {
LocGrades loc_grades;
// lower bound, name
loc_grades.push_back(LocPair(1, "few"));
loc_grades.push_back(LocPair(5, "several"));
loc_grades.push_back(LocPair(10, "pack"));
loc_grades.push_back(LocPair(20, "lots"));
loc_grades.push_back(LocPair(50, "horde"));
loc_grades.push_back(LocPair(100, "throng"));
loc_grades.push_back(LocPair(250, "swarm"));
loc_grades.push_back(LocPair(500, "zounds"));
loc_grades.push_back(LocPair(1000, "legion"));
return loc_grades;
}
int main() {
LocGrades loc_grades = init_loc_grades();
std::string name = loc_grades[0].second; //default result
int amount;
std::cin >> amount;
for(auto it = loc_grades.cbegin(); it != loc_grades.cend(); it++) {
if (amount >= it->first)
name = it->second;
}
std::cout << name << std::endl;
}
|
Markdown
|
UTF-8
| 3,308
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
# Team Reflection
Designed with R and Plotly, this app visualizes the global risk factors that contribute to human death and has well-designed features that provide answers to the research questions outlined in milestone 1 of this project. The app demonstrates the top risk factors that contribute to global death, the geographic distribution of top death-causing risk factors and visualizes the global death trends for these various risk factors. It does this from 1990 up to 2017 using interactive features such as dropdown menus, radio buttons, etc.
The app does so well in terms of user-friendliness, interactivity and ease of customization. It is robust and seamlessly integrates complex yet meaningful charts without compromising response time for displaying dashboard components.
All the suggestions and feedback received from TAs and peers have been incorporated into this milestone 4 R-project. These include further code cleaning and refactoring, code reformatting using Roxygen2 style and directory re-organization. We have also added more in-line comments and reduced the length of the app functionality description for the homepage of our app.
We also modified the titles of our interactive charts to fully reflect our research questions and normalized the trend plot by scaling it into a percentage for better comparison.
Unfortunately, while there are no limitations related to the development of our R project, we were unable to deploy it on Heroku. After our team exhausted all possibilities and consulted with the course instructor and TAs, it turned out that some of our `geom_sf` package that we used for the map is not currently supported by Heroku. Else, our dashboard app perfectly compiles and runs locally without any bugs or issues.
Furthermore, since the development team was limited on time, this app has several limitations which we consider as future improvements. First of all, adding a jumbotron button and testing for various dash fonts and colours could be further explored. Our overview bar chart is currently for 2017 only as indicated in our research question, but it's our future improvement to have a range slider that allows the user to pick a year of interest.
Secondly, another key future improvement is to incorporate our geo map with an additional feature that generates a summary graph after the user highlights a group of countries. This would allow comparison among countries of interest. Lastly, having an additional slider for choosing a particular year for the Trend chart would be great so that it could be used along with the radio buttons for risk factors that are currently implemented.
Overall, the feedback we received from TAs and peers on our milestone 1,2 &3 has been monumental and helped us greatly restructure our dashboard. The feedback was phenomenal and helped us better design our R app in a way that is more presentable to our users. All suggestions were considered where applicable and time permitted. Now, while Heroku failed to support the deployment of our app, it could be run locally to fully explore its highly interactive features. Deployment of the R version of the app to Heroku is considered as a future improvement and its deployment will be fulfilled as soon as `sf` package support becomes readily available on Heroku.
|
Markdown
|
UTF-8
| 5,124
| 2.765625
| 3
|
[] |
no_license
|
---
description: "How to Prepare Any-night-of-the-week Pancake Tower"
title: "How to Prepare Any-night-of-the-week Pancake Tower"
slug: 425-how-to-prepare-any-night-of-the-week-pancake-tower
date: 2021-07-04T07:02:44.113Z
image: https://img-global.cpcdn.com/recipes/1265f82658b7d473/680x482cq70/pancake-tower-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/1265f82658b7d473/680x482cq70/pancake-tower-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/1265f82658b7d473/680x482cq70/pancake-tower-recipe-main-photo.jpg
author: Mattie Mack
ratingvalue: 5
reviewcount: 15436
recipeingredient:
- " self raising flour"
- " caster sugar"
- " salt"
- " milk"
- " egg beaten"
- " butter"
- " bonne maman cherry compote"
recipeinstructions:
- "Put the Flour, Sugar and salt in a large mixing bowl, whisk in the milk and the beaten egg and set aside to rest."
- "Heat a large pan on a medium/high heat, I borrowed my mum's new American pancake pan, its quite cool with 5 slots to make these type of pancake, use the butter to melt in the pan."
- "When you can see the butter sizzling but not burning, add 2 large tablespoons of batter for each pancake, if your using a normal pan don't over crowd or you will have 1 huuge pancake."
- "Cook each for 2 mins on each side or depending on the heat until the batter get bubbly and thick, use a spatula to check the bottom so it doesn't burn, then flip to the other side, it should have a nice golden colour."
- "Serve to your loved one with whichever topping is chosen, my wife likes Cherry compote, I'm just happy pouring honey over the top, enjoy."
categories:
- Recipe
tags:
- pancake
- tower
katakunci: pancake tower
nutrition: 260 calories
recipecuisine: American
preptime: "PT38M"
cooktime: "PT60M"
recipeyield: "2"
recipecategory: Dessert
---

Hello everybody, it's Drew, welcome to our recipe site. Today, we're going to make a distinctive dish, pancake tower. One of my favorites food recipes. For mine, I'm gonna make it a bit tasty. This is gonna smell and look delicious.
Let's see how many pancakes you can pile up!! In this video we're playing Pancake Tower, a fun game for Android and iOS, where you can put these delicious pancakes in stack to make a tower of pancakes. Download Pancake Tower and enjoy it on your iPhone, iPad, and iPod touch. Let's see how many pancakes you can pile up!!
Pancake Tower is one of the most favored of recent trending meals in the world. It is easy, it is fast, it tastes delicious. It is appreciated by millions daily. They're fine and they look fantastic. Pancake Tower is something that I've loved my whole life.
To get started with this recipe, we must first prepare a few ingredients. You can have pancake tower using 7 ingredients and 5 steps. Here is how you can achieve it.
<!--inarticleads1-->
##### The ingredients needed to make Pancake Tower:
1. Make ready self raising flour
1. Make ready caster sugar
1. Make ready salt
1. Get milk
1. Make ready egg - beaten
1. Take butter
1. Make ready bonne maman cherry compote
POPULAR GAMES Casual Games Puzzle Games Action Games Kids Games « Back. Flip the pancake when it begins to form air bubbles around the edges, and proceed to cook the other side. Try Pancake Tower, a casual game where you can stack as many pancakes as you can. Who knew pancakes will also make for a great stacking game like this?
<!--inarticleads2-->
##### Steps to make Pancake Tower:
1. Put the Flour, Sugar and salt in a large mixing bowl, whisk in the milk and the beaten egg and set aside to rest.
1. Heat a large pan on a medium/high heat, I borrowed my mum's new American pancake pan, its quite cool with 5 slots to make these type of pancake, use the butter to melt in the pan.
1. When you can see the butter sizzling but not burning, add 2 large tablespoons of batter for each pancake, if your using a normal pan don't over crowd or you will have 1 huuge pancake.
1. Cook each for 2 mins on each side or depending on the heat until the batter get bubbly and thick, use a spatula to check the bottom so it doesn't burn, then flip to the other side, it should have a nice golden colour.
1. Serve to your loved one with whichever topping is chosen, my wife likes Cherry compote, I'm just happy pouring honey over the top, enjoy.
Try Pancake Tower, a casual game where you can stack as many pancakes as you can. Who knew pancakes will also make for a great stacking game like this? Enjoy all the fluffy goodness when you. Let's see how many pancakes you can pile up!! Download the latest version of Pancake Tower for Android.
So that is going to wrap this up for this exceptional food pancake tower recipe. Thanks so much for your time. I'm sure you can make this at home. There is gonna be more interesting food in home recipes coming up. Remember to bookmark this page on your browser, and share it to your loved ones, friends and colleague. Thank you for reading. Go on get cooking!
|
Java
|
UTF-8
| 2,396
| 2.125
| 2
|
[] |
no_license
|
package com.digiomega.hangrymatesrestaurants.Fragments;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.digiomega.hangrymatesrestaurants.AllConstant.Config;
import com.digiomega.hangrymatesrestaurants.AllConstant.PreferenceClass;
import com.digiomega.hangrymatesrestaurants.R;
/**
* Created by qboxus on 10/18/2019.
*/
public class EarningFragment extends Fragment {
WebView mWebview;
SharedPreferences sPre;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.earning_fragment, container, false);
sPre = getContext().getSharedPreferences(PreferenceClass.user, getContext().MODE_PRIVATE);
init(v);
return v;
}
public void init(View v){
callWebView(v);
}
public void callWebView(View v){
mWebview = v.findViewById(R.id.web_view);
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.getSettings().setLoadWithOverviewMode(true);
mWebview.getSettings().setUseWideViewPort(true);
mWebview.getSettings().setBuiltInZoomControls(true);
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Toast.makeText(getContext(), rerr.getDescription(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
}
@Override
public void onPageFinished(WebView view, String url) {
String webUrl = mWebview.getUrl();
}
});
mWebview.loadUrl(Config.earning_url);}
}
|
Markdown
|
UTF-8
| 3,616
| 4
| 4
|
[] |
no_license
|
# [235. Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
## Java
最小公共祖先(自己可以是自己的祖先)。这道题需要获取目标子叶的路径,所以明显得使用 **DFS**(Depth-first search,深度优先搜索)。借助递归之前必须清楚:
- 每步应该做什么
- 终止条件是什么
```java
public class Solution {
public boolean search(ArrayList<TreeNode> path, TreeNode root, TreeNode targetNode) {
// 终止条件
if (root == null || targetNode == null) return false;
// 终止条件
if (root.val == targetNode.val) {
path.add(root);
return true;
}
// 搜索左右子叶
if (search(path, root.left, targetNode) || search(path, root.right, targetNode)) {
// 如果子叶中有搜索到的话,说明经过当前节点
path.add(root);
return true;
}
return false;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// 首先使用深度搜索找到两个节点的路径
// 第一个目标子叶的路径
ArrayList<TreeNode> path1 = new ArrayList<>();
search(path1, root, p);
// 第二个目标子叶的路径
ArrayList<TreeNode> path2 = new ArrayList<>();
search(path2, root, q);
// 对比两个路径,找出最小公共祖先
TreeNode lowest = null;
HashMap<Integer, Boolean> map = new HashMap<>();
for (TreeNode node : path1) map.put(node.val, true);
for (TreeNode node : path2) {
if (map.containsKey(node.val)) {
if (lowest == null || lowest.val > node.val) {
lowest = node;
}
}
}
return lowest;
}
}
```
> **Status: Wrong Answer**
```
Input:[6,2,8,0,4,7,9,null,null,3,5]
node with value 3
node with value 5
Output:2
Expected:4
```
WTF!3 和 5 的共同祖先不包括 2 么?!懵逼了。
最后看清楚题目了,**Lowest** 是指最低的(最深的)共同祖先,而不是最小的!英语水平捉急啊= =。这样的话反而好做了,两条路径从根部寻起,遇到下一子叶不一致则说明当前节点为 Lowest。
```java
// 对比两个路径,找出最低共祖先
TreeNode lowest = null;
int minDepthLen = Math.min(path1.size(), path2.size());
// 注意路径是反向的
for (int i = minDepthLen - 1; i >= 0; i--) {
TreeNode node = path1.get(i);
if (node != path2.get(i)) break;
lowest = node;
}
```
> **Status: Wrong Answer**
又傻了,。这里因为路径列表是反的,两个列表的寻址位置应该是相对尾部的而不是固定的。**细心真的很重要!**
```java
// 对比两个路径,找出最低共祖先
TreeNode lowest = null;
int minDepthLen = Math.min(path1.size(), path2.size());
// 注意路径是反向的
for (int i = 0; i < minDepthLen; i++) {
TreeNode node = path1.get(path1.size() - i - 1);
if (node != path2.get(path2.size() - i - 1)) break;
lowest = node;
}
return lowest;
```
> **Accepted! Runtime: 11 ms**
想了下,其实还可以优化。和寻找最小值的解法不一样,寻找 Lowest Common Ancestor 其实就是寻找两个节点路径的分岔点。所以并不需要储存两个目标节点的路径,在递归里就能找到最低节点,终止条件为:**search(p.left) != search(q.left)**,也就是在当前节点产生分支,所以当前节点就是 Lowest Common Ancestor。
|
Python
|
UTF-8
| 977
| 3.03125
| 3
|
[] |
no_license
|
from biblioteca_grafo import Grafo
def kruskal(grafo):
arvore = []
s = [0]
for i in range(1, grafo.qtdVertices() + 1):
lista = [i]
s.append(lista)
pesos_ordenados = sorted(grafo.pesos.items(), key=lambda x: x[1])
arestas_ord = []
for elem in pesos_ordenados:
arestas_ord.append(elem[0])
for aresta in arestas_ord:
u = aresta[0]
v = aresta[1]
su = s[u]
sv = s[v]
if su != sv:
arvore.append(aresta)
x = []
x = su + sv
for y in x:
s[y] = x
custo = 0
for aresta in arvore:
custo += grafo.peso(aresta[0], aresta[1])
print(custo)
for i in range(len(arvore) - 1):
print(arvore[i][0],"-", sep='', end='')
print(arvore[i][1],", ", sep='', end='')
print(arvore[-1][0],"-", sep='', end='')
print(arvore[-1][1])
grafo_teste = Grafo("teste_kruskal.txt")
kruskal(grafo_teste)
|
Python
|
UTF-8
| 749
| 2.78125
| 3
|
[] |
no_license
|
import tensorflow_probability as tfp
%tensorflow_version 2.x
# PREPARE DATA
tfd = tfp.distributions
## 1. State [cold,hot]
initial_dist = tfd.Categorical(probs=[0.8, 0.2])
## 2. Transaction [cold,hot]
transaction_dist = tfd.Categorical(probs=[[0.7,0.3],[0.2,0.8]])
## 3. Observation (loc->mean;scale->SD)
observation_dist = tfd.Normal(loc=[0.,15.],scale=[5.,10.])
# CREATE MODEL
##num_steps = the amount of days you want to predict
HMmodel = tfd.HiddenMarkovModel(
initial_distribution=initial_dist,
transition_distribution=transaction_dist,
observation_distribution=observation_dist,
num_steps=7)
##how to see the values the model predict
mean = HMmodel.mean()
with tf.compat.v1.Session() as sess:
print(mean.numpy())
|
Python
|
UTF-8
| 1,607
| 2.671875
| 3
|
[] |
no_license
|
import xml.dom.minidom as xmldom
import re
import json
#generate the inverted list
def proximity_index(words,text,id):
r_words="[( ) ' ']+"
words_dic={}
for x in words:
words_dic[x]={}
#iterate the documents and find the position for every character
for j in range(0,text.length):
line=text[j].firstChild.data.strip()
line=line.split()
doc_id=id[j].firstChild.data.strip()
x=1
for i in range(0,len(line)):
if line[i] in words:
index={}
index=words_dic[line[i]]
if doc_id in index:
content=''
content=index[doc_id]
content=content+' '+str(i+1)
index[doc_id]=content
else:
index[doc_id]=str(i+1)
words_dic[line[i]]=index
#write into txt
with open('../index_file.txt','w',encoding='utf-8') as f:
for i in range(0,len(words_dic)):
f.write(words[i]+':')
f.write('\n')
index=words_dic[words[i]]
content=''
for item in index.items():
content=str(item)
content=re.sub(r_words,' ',content)
content=re.sub("[,]",':',content)
f.write(' ')
f.write(content)
f.write('\n')
#write into json
with open('../index_file.json','w',encoding='utf-8') as g:
json.dump(words_dic,g)
return words_dic
|
Python
|
UTF-8
| 472
| 3.3125
| 3
|
[] |
no_license
|
import random
output = ""
notes = ['Ab', 'A', 'A#',
'Bb', 'B',
'C', 'C#',
'Db', 'D', 'D#',
'Eb', 'E',
'F', 'F#',
'Gb', 'G', 'G#']
arpegg = ['Major 7th',
'Minor 7th',
'Dominant 7th',
'Suspended 4th',
'Major 6th',
'Minor 6th']
output += 'Play: ' + (random.choice(notes)) + ' ' + (random.choice(arpegg) +' Arpeggio (1 Octave, 2 Positions)')
print()
print(output)
print()
|
C++
|
UTF-8
| 716
| 2.609375
| 3
|
[] |
no_license
|
/*************************************************************************
> File Name: 119.cpp
> Author: Wqr_
> Mail: xueduanwei@126.com
> Created Time: Thu Sep 27 10:23:32 2018
************************************************************************/
#include <iostream>
using namespace std;
int main() {
int in;
while (cin >> in) {
int out[1000];
int i = 0;
int a;
bool flag = false;
if (in == 1 || in == 0) flag = true;
for (i;; i++) {
out[i] = in % 2;
in /= 2;
if (in == 1 || in == 0) {
a = in;
break;
}
}
if (!flag) cout << a;
for (int j = i; j >= 0; j--) {
cout << out[j];
}
cout << endl;
}
return 0;
}
|
Java
|
UTF-8
| 7,489
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019 The Android Open Source Project
*
* 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.
*/
package com.example.androidx.webkit;
import static java.nio.charset.StandardCharsets.UTF_8;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* Simple HTTP server that accepts requests.
* Can be used to test proxying or as a end destination server.
*/
public class HttpServer {
/**
* This interface offers a callback that is run when a request is served.
*/
public interface OnRequestCallback {
/**
* Called when this proxy serves a request.
*/
void onRequestServed();
}
/**
* Provider of request handlers.
*
* Typically just a static reference to either {@code HttpServer.EchoRequestHandler::new} or
* {@code HttpServer.ProxyRequestHandler::new}
*/
public interface RequestHandlerFactory {
/**
* Called to initialize a new RequestHandler
*/
@NonNull
RequestHandler create(@NonNull Socket socket);
}
private static final int TIMEOUT_MILLIS = 5000;
private boolean mRunning = false;
private OnRequestCallback mCallback;
private RequestHandlerFactory mHandlerFactory;
private ServerSocket mServerSocket;
private List<Thread> mThreadsList;
private int mRequestCount;
/**
* Create a server using provided port number.
*
* @param port port number
* @param handlerFactory Provider of request handler
* @param callback callback run when this a request is served
*/
@SuppressWarnings("CatchAndPrintStackTrace")
public HttpServer(int port,
@NonNull RequestHandlerFactory handlerFactory,
@Nullable OnRequestCallback callback) {
mRequestCount = 0;
mCallback = callback;
mHandlerFactory = handlerFactory;
mThreadsList = new ArrayList<>();
try {
mServerSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Get port number.
*/
public int getPort() {
return mServerSocket.getLocalPort();
}
/**
* Get the number of requests this server has served.
*/
public int getRequestCount() {
return mRequestCount;
}
/**
* Start listening for requests.
*/
public void start() {
if (mRunning) return;
mRunning = true;
new Thread(() -> {
while (mRunning) {
listen();
}
}).start();
}
@SuppressWarnings("CatchAndPrintStackTrace")
private void listen() {
try {
Socket socket = mServerSocket.accept();
mRequestCount++;
if (mCallback != null) {
mCallback.onRequestServed();
}
Thread thread = new Thread(mHandlerFactory.create(socket));
mThreadsList.add(thread);
thread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Shutdown.
*/
@SuppressWarnings("CatchAndPrintStackTrace")
public void shutdown() {
if (!mRunning) return;
mRunning = false;
for (Thread thread : mThreadsList) {
if (thread.isAlive()) {
try {
thread.join(TIMEOUT_MILLIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
mThreadsList.clear();
try {
mServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Request handler whose response can be controlled through the
* {@link #writeResponse(String, BufferedWriter)} method.
*/
abstract static class RequestHandler implements Runnable {
private Socket mSocket;
private BufferedReader mReader;
private BufferedWriter mWriter;
@SuppressWarnings("CatchAndPrintStackTrace")
RequestHandler(Socket socket) {
mSocket = socket;
try {
mSocket.setSoTimeout(TIMEOUT_MILLIS);
mReader = new BufferedReader(
new InputStreamReader(mSocket.getInputStream(), UTF_8));
mWriter = new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream(), UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
@SuppressWarnings("CatchAndPrintStackTrace")
public void run() {
try {
StringBuilder sb = new StringBuilder();
String s = mReader.readLine();
while (s != null && !s.trim().isEmpty()) {
sb.append(s);
sb.append("\n");
s = mReader.readLine();
}
String request = sb.toString();
writeResponse(request, mWriter);
} catch (IOException e) {
e.printStackTrace();
}
}
abstract void writeResponse(String request, BufferedWriter responseWriter)
throws IOException;
}
/**
* Request handler that responds with a HTML document containing the received request header.
*/
static class EchoRequestHandler extends RequestHandler {
EchoRequestHandler(Socket socket) {
super(socket);
}
@Override
void writeResponse(String request, BufferedWriter responseWriter) throws IOException {
responseWriter.write("HTTP/1.0 200 OK\nContent-Type: text/html\n\r\n");
responseWriter.write("<html><head><title>HttpServer</title></head>"
+ "<body>Server handled this request:<br><pre>"
+ request + "</pre></body></html>");
responseWriter.flush();
}
}
/**
* Respond with text that indicates that the request was handled by a proxy.
*/
static class ProxyRequestHandler extends RequestHandler {
ProxyRequestHandler(Socket socket) {
super(socket);
}
@Override
void writeResponse(String request, BufferedWriter responseWriter) throws IOException {
responseWriter.write("HTTP/1.0 200 OK\nUser-Agent: Proxy\n\r\n");
responseWriter.write("<html><head><title>Proxy</title></head>"
+ "<body>Proxy handled this request:<br><br>"
+ request + "</body></html>");
responseWriter.flush();
}
}
}
|
Python
|
UTF-8
| 521
| 3.171875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
x = 23.45
values = [5.9, 4.8, 3.6, 0, 5.1, 7.2, 'wombat']
for v in values:
try:
result = x / v
except ZeroDivisionError as err:
print(err)
except TypeError as err:
print(err)
except (KeyError, IndexError) as err:
print("Huh??")
except: # Exception as err:
#print("{}: {}".format(type(err).__name__, err))
result = float('Nan')
exit()
else: # no exceptions
pass
finally:
pass
print(result)
|
Java
|
UTF-8
| 2,372
| 2.09375
| 2
|
[] |
no_license
|
package com.amazonaws.services.dynamodb.model.transform;
import com.amazonaws.services.dynamodb.model.BatchWriteItemResult;
import com.amazonaws.transform.JsonUnmarshallerContext;
import com.amazonaws.transform.ListUnmarshaller;
import com.amazonaws.transform.MapUnmarshaller;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.StringJsonUnmarshaller;
import com.amazonaws.transform.Unmarshaller;
import org.codehaus.jackson.JsonToken;
public class BatchWriteItemResultJsonUnmarshaller implements Unmarshaller<BatchWriteItemResult, JsonUnmarshallerContext> {
private static BatchWriteItemResultJsonUnmarshaller instance;
public static BatchWriteItemResultJsonUnmarshaller getInstance() {
if (instance == null) {
instance = new BatchWriteItemResultJsonUnmarshaller();
}
return instance;
}
public BatchWriteItemResult unmarshall(JsonUnmarshallerContext jsonUnmarshallerContext) throws Exception {
BatchWriteItemResult batchWriteItemResult = new BatchWriteItemResult();
int currentDepth = jsonUnmarshallerContext.getCurrentDepth();
int i = currentDepth + 1;
JsonToken jsonToken = jsonUnmarshallerContext.currentToken;
if (jsonToken == null) {
jsonToken = jsonUnmarshallerContext.nextToken();
}
while (jsonToken != null) {
if (jsonToken != JsonToken.FIELD_NAME && jsonToken != JsonToken.START_OBJECT) {
if ((jsonToken == JsonToken.END_ARRAY || jsonToken == JsonToken.END_OBJECT) && jsonUnmarshallerContext.getCurrentDepth() <= currentDepth) {
break;
}
}
if (jsonUnmarshallerContext.testExpression("Responses", i)) {
batchWriteItemResult.setResponses(new MapUnmarshaller(StringJsonUnmarshaller.getInstance(), BatchWriteResponseJsonUnmarshaller.getInstance()).unmarshall(jsonUnmarshallerContext));
}
if (jsonUnmarshallerContext.testExpression("UnprocessedItems", i)) {
batchWriteItemResult.setUnprocessedItems(new MapUnmarshaller(StringJsonUnmarshaller.getInstance(), new ListUnmarshaller(WriteRequestJsonUnmarshaller.getInstance())).unmarshall(jsonUnmarshallerContext));
}
jsonToken = jsonUnmarshallerContext.nextToken();
}
return batchWriteItemResult;
}
}
|
Java
|
UTF-8
| 527
| 2.046875
| 2
|
[] |
no_license
|
package com.kakarot.plcenter.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* @author jinzj
* @since v4.0.0
*/
public class Client {
public static void main(String[] args) {
TestService testService = new TestServiceImpl();
InvocationHandler handler = new RealTest(testService);
TestService service = (TestService) Proxy.newProxyInstance(handler.getClass().getClassLoader(),testService.getClass().getInterfaces(),handler);
service.send();
}
}
|
JavaScript
|
UTF-8
| 5,288
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//scrollmagic controller for desktop and mobile
var controller = new ScrollMagic.Controller();
$(function () {
var desktopController = null;
//set initial values for page width and item height
var width = $(window).width()
function initScrollMagic(){
//scrollmagic functions for desktop
desktopController = new ScrollMagic.Controller();
//////////////
// Header //
//////////////
var sceneA = new ScrollMagic.Scene({
triggerElement: "#header",
offset: '-10%',
duration: '110%'
})
.on("enter", function (e) {
$(".portfolioBg").css("display", "none");
$(".contactBg").css("display", "none");
$(".headerBg").css("display", "block");
})
.setTween(".headerBg", {y: "-20%", ease: Linear.easeNone})
.addTo(desktopController);
//////////////////
// Portfolio //
//////////////////
var scene1 = new ScrollMagic.Scene({
triggerElement: "#portfolio",
triggerHook: 'onEnter',
offset: '-10%',
duration: '200%'
})
.on("enter", function (e) {
$(".portfolioBg").css("display", "block");
$(".contactBg").css("display", "none");
$(".headerBg").css("display", "none");
})
.on("leave", function (e) {
$direction = e.target.controller().info("scrollDirection");
if($direction == "REVERSE"){
$(".portfolioBg").css("display", "none");
$(".contactBg").css("display", "none");
$(".headerBg").css("display", "block");
}
})
.setTween(".portfolioBg", {y: "-20%", ease: Linear.easeNone})
.addTo(desktopController);
//////////////////
// Contact //
//////////////////
var contactScene = new ScrollMagic.Scene({
triggerElement: "#contact",
triggerHook: 'onEnter',
offset: '-10%',
duration: '110%'
})
.setTween(".contactBg", {y: "-20%", ease: Linear.easeNone})
.on("enter", function (e) {
$(".portfolioBg").css("display", "none");
$(".contactBg").css("display", "block");
$(".headerBg").css("display", "none");
})
.on("leave", function (e) {
$direction = e.target.controller().info("scrollDirection");
if($direction == "REVERSE"){
$(".portfolioBg").css("display", "block");
$(".contactBg").css("display", "none");
$(".headerBg").css("display", "none");
}
})
.addTo(desktopController);
}
//767 is my mobile breakpoint
if( width > 767) {
initScrollMagic()
}
$(window).resize(function(){
//reset values when page size changes
width = $(window).width()
if( width < 768 ) {
//you can just use 'controller' here as it will return true or false, you dont need all the conditionals
if (controller) {
controller = controller.destroy(true)
}
} else if ( width > 767 ) {
//same here
if ( !controller ) {
initScrollMagic()
}
}
});
//////////////////
// Navigation //
//////////////////
$('.solid').each(function(){
var solid = this;
var id = this.getAttribute('id');
var addShadow = new ScrollMagic.Scene({
triggerElement: solid,
triggerHook: 'onLeave',
offset: -70
})
.on("enter leave", function (e) {
$direction = e.target.controller().info("scrollDirection");
if($direction == "FORWARD"){
$(".navbar-custom").addClass("shadow");
}
else if( !(id.includes("team")) ){
$(".navbar-custom").removeClass("shadow");
}
})
.addTo(controller);
});
//////////////////
// Shadows //
//////////////////
$('.transparent').each(function(){
var transparent = this;
var removeShadow = new ScrollMagic.Scene({
triggerElement: transparent,
triggerHook: 'onLeave',
offset: -70
})
.on("enter leave", function (e) {
$direction = e.target.controller().info("scrollDirection");
if($direction == "FORWARD"){
$(".navbar-custom").removeClass("shadow");
}
else if($direction == "REVERSE"){
$(".navbar-custom").addClass("shadow");
}
})
.addTo(controller);
});
//////////////////
// Vita //
//////////////////
$('.timeline > li').each(function(){
var element = this;
var scene21 = new ScrollMagic.Scene({
triggerElement: element,
duration: 200
})
.on("enter", function (e) {
$direction = e.target.controller().info("scrollDirection");
$(element).addClass('increase');
})
.on("leave", function (e) {
$direction = e.target.controller().info("scrollDirection");
$(element).removeClass('increase');
})
.addTo(controller);
});
});
//because fuc*ing IE & Edge can't do background-attachment: fixed;
if(navigator.userAgent.match(/Trident\/7\./)) { // if IE
$('body').on("mousewheel", function () {
// remove default behavior
event.preventDefault();
//scroll without smoothing
var wheelDelta = event.wheelDelta;
var currentScrollPosition = window.pageYOffset;
window.scrollTo(0, currentScrollPosition - wheelDelta);
});
}
|
Java
|
UTF-8
| 2,509
| 2.203125
| 2
|
[] |
no_license
|
package d4tekkom.presensiuas.ui.login;
import com.orhanobut.logger.Logger;
import javax.inject.Inject;
import d4tekkom.presensiuas.data.DataRepository;
import d4tekkom.presensiuas.data.model.Petugas;
import d4tekkom.presensiuas.utility.rx.SchedulerProvider;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
/**
* Created by doy on 16/06/17.
*/
public class LoginPresenter implements LoginContract.Presenter {
private final LoginContract.View mView;
private final CompositeDisposable mCompositeDisposable;
private final DataRepository mDataRepository;
private final SchedulerProvider mScheduler;
@Inject
public LoginPresenter(LoginContract.View view,
CompositeDisposable compositeDisposable,
SchedulerProvider schedulerProvider,
DataRepository dataRepository) {
this.mView = view;
this.mCompositeDisposable = compositeDisposable;
this.mScheduler = schedulerProvider;
mDataRepository = dataRepository;
mView.setPresenter(this);
}
@Override
public void subscribe() {
mView.setupView();
if (mDataRepository.isPetugasLoggedIn()){
// TODO: 19/06/17 OPEN MAINACTIVITY
mView.startMainActivity();
}
}
@Override
public void unsubscribe() {
mCompositeDisposable.clear();
mView.dismissProgressDialog();
}
@Override
public void onLogin(String nip, String password) {
mView.showProgressDialog();
mCompositeDisposable.add(mDataRepository.loginPetugas(nip, password)
.subscribeOn(mScheduler.io())
.observeOn(mScheduler.ui())
.subscribe(new Consumer<Petugas>() {
@Override
public void accept(@NonNull Petugas petugas) throws Exception {
mDataRepository.createLoginSession(petugas);
mView.dismissProgressDialog();
mView.startMainActivity();
}
}, new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
Logger.e(throwable, throwable.getMessage());
mView.dismissProgressDialog();
}
})
);
}
}
|
Java
|
UTF-8
| 1,591
| 2.6875
| 3
|
[] |
no_license
|
package com.es.phoneshop.domain.cart.model;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.Objects;
public class MiniCart {
private int totalProductsQuantity;
private BigDecimal totalPriceValue;
private Currency currency;
public MiniCart(int totalProductsQuantity, BigDecimal totalPriceValue, Currency currency) {
this.totalProductsQuantity = totalProductsQuantity;
this.totalPriceValue = totalPriceValue;
this.currency = currency;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MiniCart miniCart = (MiniCart) o;
return totalProductsQuantity == miniCart.totalProductsQuantity && totalPriceValue.equals(miniCart.totalPriceValue) && currency.equals(miniCart.currency);
}
@Override
public int hashCode() {
return Objects.hash(totalProductsQuantity, totalPriceValue, currency);
}
public int getTotalProductsQuantity() {
return totalProductsQuantity;
}
public void setTotalProductsQuantity(int totalProductsQuantity) {
this.totalProductsQuantity = totalProductsQuantity;
}
public BigDecimal getTotalPriceValue() {
return totalPriceValue;
}
public void setTotalPriceValue(BigDecimal totalPriceValue) {
this.totalPriceValue = totalPriceValue;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
}
|
Java
|
UTF-8
| 422
| 2.234375
| 2
|
[] |
no_license
|
package com.dragon.persondata;
public class ContactsInfo {
public String userName=null;
public String userSign=null;
public int userImage=0;
public String groupInfo=null;
public ContactsInfo(String userName, String userSign, int userImage,
String groupInfo) {
super();
this.userName = userName;
this.userSign = userSign;
this.userImage = userImage;
this.groupInfo = groupInfo;
}
}
|
C#
|
UTF-8
| 1,535
| 2.578125
| 3
|
[] |
no_license
|
using Guru.ExtensionMethod;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Guru.DependencyInjection.Implementation.Configurable
{
internal class ConfigurableDependencyDescriptor : DefaultDependencyDescriptor
{
private List<PropertySetter> _PropertySetters = new List<PropertySetter>();
public List<PropertySetter> PropertySetters => _PropertySetters;
public ConfigurableDependencyDescriptor(Type implementationType, Lifetime lifetime, int priority)
: base(implementationType, lifetime, priority)
{
}
public void SetProperty(string name, string value)
{
var propertyInfo = ImplementationType.GetProperty(name);
if (propertyInfo == null)
{
return;
}
try
{
var propertyValue = value.ConvertTo(propertyInfo.PropertyType);
_PropertySetters.Add(new PropertySetter()
{
Name = name,
Value = value,
PropertyInfo = propertyInfo,
PropertyValue = propertyValue,
});
}
catch (Exception) { }
}
public class PropertySetter
{
public string Name { get; set; }
public string Value { get; set; }
public object PropertyValue { get; set; }
public PropertyInfo PropertyInfo { get; set; }
}
}
}
|
Java
|
UTF-8
| 584
| 2.671875
| 3
|
[] |
no_license
|
package com.in28minutes.springboot.basics.springbootin10steps;
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* RestController 가 어떻게 작동하는가?
* 1. @SpringBootApplication 에서 자동으로 @RestController 찾아서 빈등록하고 관리한다.
*/
@RestController
public class BooksController {
@GetMapping("/books")
public List<Book> getAllBooks() {
return Arrays.asList(new Book(1l,"Mastering Spirngsdf", "Gwangtae"));
}
}
|
C++
|
UTF-8
| 405
| 2.96875
| 3
|
[] |
no_license
|
// https://helloacm.com/how-to-sort-list-by-hamming-weight-in-c/
// https://binarysearch.com/problems/Sort-List-by-Hamming-Weight
// EASY, MATH
vector<int> solve(vector<int>& nums) {
sort(begin(nums), end(nums), [&](auto &a, auto &b) {
auto aa = __builtin_popcount(a);
auto bb = __builtin_popcount(b);
return (aa < bb) || (aa == bb) && (a < b);
});
return nums;
}
|
C
|
UTF-8
| 1,338
| 2.796875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
/**
* \file os_locate.c
* \brief Locates files along the standard built-in search paths.
* \author Copyright (c) 2014-2015 Jason Perkins and the Premake project
*/
#include <stdlib.h>
#include "premake.h"
int do_locate(lua_State* L, const char* filename, const char* path)
{
if (do_pathsearch(L, filename, path)) {
lua_pushstring(L, "/");
lua_pushstring(L, filename);
lua_concat(L, 3);
return 1;
}
return 0;
}
int os_locate(lua_State* L)
{
const char* path;
int i;
int nArgs = lua_gettop(L);
/* Fetch premake.path */
lua_getglobal(L, "premake");
lua_getfield(L, -1, "path");
path = lua_tostring(L, -1);
for (i = 1; i <= nArgs; ++i) {
const char* name = lua_tostring(L, i);
/* Direct path to an embedded file? */
if (name[0] == '$' && name[1] == '/' && premake_find_embedded_script(name + 2)) {
lua_pushvalue(L, i);
return 1;
}
/* Direct path to file? Return as absolute path */
if (do_isfile(L, name)) {
lua_pushcfunction(L, path_getabsolute);
lua_pushvalue(L, i);
lua_call(L, 1, 1);
return 1;
}
/* do_locate(arg[i], premake.path) */
if (do_locate(L, name, path)) {
return 1;
}
/* embedded in the executable? */
if (premake_find_embedded_script(name)) {
lua_pushstring(L, "$/");
lua_pushvalue(L, i);
lua_concat(L, 2);
return 1;
}
}
return 0;
}
|
PHP
|
UTF-8
| 3,480
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
<?php
session_start();
//session_destroy();
if ($_GET["logout"]==1 AND $_SESSION['id']){ session_destroy();
$message="Wylogowano !";
//echo $_SESSION['id'];
}
include("connection.php");
if ($_POST['submit']=="OK") {
if (!$_POST['email']) $error.="<br />Proszę podać poprawny email";
else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) $error.="<br />Proszę podać poprawny email";
if (!$_POST['password']) $error.="<br />Proszę podać hasło";
else {
if (strlen($_POST['password'])<8) $error.="<br />Wprowadź hasło zawierające conajmniej 8 znaków";
if (!preg_match('`[A-Z]`', $_POST['password'])) $error.="<br />Hasło musi zawierać minimum jedną wielką literę";
}
if ($error) $error = "Wprowadzone dane logowania są błędne:".$error;
else {
$query = "SELECT * FROM users WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'"; //The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.
$result = mysqli_query($link, $query); // The mysqli_query() function performs a query against the database.
$results = mysqli_num_rows($result); //The mysqli_num_rows() function returns the number of rows in a result set.
if ($results) $error = "Ten adres mailowy został już zarejestrowany. Czy chcesz się zalogować?";
else {
$query = "INSERT INTO `users` (`name`,`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['name'])."','".mysqli_real_escape_string($link, $_POST['email'])."','".md5(md5($_POST['email']).$_POST['password'])."')";
mysqli_query($link, $query);
echo "Zostałeś zarejestrowany w systemie !";
$_SESSION['id']=mysqli_insert_id($link);
// The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) used in the last query.
// print_r($_SESSION);
// header("Location:mainpage.php");
}
}
}
if ($_POST['submit']=="ZALOGUJ SIĘ") {
$query = "SELECT * FROM users WHERE email='".mysqli_real_escape_string($link, $_POST['loginemail'])."' AND password='" .md5(md5($_POST['loginemail']) .$_POST['loginpassword']). "' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
//The mysqli_fetch_array() function fetches a result row as an associative array, a numeric array, or both.
if ($row) {
$_SESSION['id']=$row['id'];
// getting an ID of the user just found in the database
//print_r($_SESSION);
//Redirect to logged in page
header("Location:mainpage.php");
} else {
$error = "Użytkownik o podanym adresie email nie istnieje w systemie. Spróbuj ponownie.";
}
}
?>
|
SQL
|
UTF-8
| 9,384
| 2.953125
| 3
|
[] |
no_license
|
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50635
Source Host : localhost:3306
Source Database : pms
Target Server Type : MYSQL
Target Server Version : 50635
File Encoding : 65001
Date: 2017-08-15 23:05:57
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_s_menu
-- ----------------------------
DROP TABLE IF EXISTS `t_s_menu`;
CREATE TABLE `t_s_menu` (
`id` varchar(64) NOT NULL COMMENT '菜单id',
`parent_id` varchar(64) DEFAULT NULL COMMENT '父级菜单ID',
`sys_id` varchar(64) DEFAULT NULL COMMENT '系统ID',
`name` varchar(255) DEFAULT NULL COMMENT '菜单名',
`leaf` int(11) DEFAULT NULL COMMENT '0 非叶子节点 1叶子节点',
`icon` varchar(255) DEFAULT NULL COMMENT '图标样式',
`path` varchar(255) DEFAULT NULL COMMENT '访问路径',
`level` int(11) DEFAULT NULL COMMENT '菜单级数',
`url` varchar(255) DEFAULT NULL COMMENT '跳转地址',
`target` varchar(255) DEFAULT NULL COMMENT '跳转方式',
`order_by` int(11) DEFAULT 0 COMMENT '排序',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`operator_id` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `t_s_menu` VALUES ('1', '-1', '1','菜单根目录', '0', null, '--', '0', '#', 0,null, '2012-12-15 18:08:07', '2012-12-23 19:46:45', '1');
INSERT INTO `t_s_menu` VALUES ('2', '1', '1','系统管理', '0', null, '1#2', '1', '#', 0,null, '2012-12-13 13:46:00', '2013-04-29 10:36:34', '1');
INSERT INTO `t_s_menu` VALUES ('3', '1', '1','业务管理', '0', null, '1#3', '1', '#', 0,null, '2012-12-13 13:53:10', '2013-04-26 20:15:27', '1');
INSERT INTO `t_s_menu` VALUES ('4', '2', '1','菜单管理', '0', null, '1#2#4', '2', '/system/menu/index', 0,null, '2012-12-13 16:00:02', '2013-04-26 20:15:36', '1');
INSERT INTO `t_s_menu` VALUES ('5', '2', '1','用户管理', '0', null, '1#2#5', '2', '/system/user/index', 0,null, '2012-12-13 16:00:02', '2013-04-26 20:15:47', '1');
INSERT INTO `t_s_menu` VALUES ('6', '2', '1','角色管理', '0', null, '1#2#6', '2', '/system/role/index', 0,null, '2012-12-13 16:00:02', '2013-04-26 20:15:50', '1');
INSERT INTO `t_s_menu` VALUES ('7', '4', '1','菜单添加', '1', null, '1#2#4#7', '3', '/system/menuAdd.jsp', 0,'centerFrame', '2012-12-15 18:33:28', '2013-04-26 20:16:31', '1');
INSERT INTO `t_s_menu` VALUES ('8', '2', '1','权限管理', '0', null, '1#2#8', '2', '/system/permission/index',0, null, '2012-12-16 13:59:33', '2013-04-29 11:26:42', '1');
INSERT INTO `t_s_menu` VALUES ('9', '4', '1','菜单查询', '1', null, '1#2#4#9', '3', '/system/menuList.jsp', 0,'centerFrame', '2012-12-16 14:15:20', '2013-04-26 20:12:33', '1');
INSERT INTO `t_s_menu` VALUES ('10', '8', '1','权限添加', '1', null, '1#2#8#10', '3', '/system/permissionAdd.jsp', 0,'centerFrame', '2012-12-20 14:58:29', '2013-04-26 20:12:38', '1');
INSERT INTO `t_s_menu` VALUES ('13', '8', '1','权限查询', '1', null, '1#2#8#13', '3', '/system/permissionList.jsp', 0,'centerFrame', '2012-12-20 16:28:03', '2013-04-26 20:12:43', '1');
INSERT INTO `t_s_menu` VALUES ('14', '6', '1','角色添加', '1', null, '1#2#6#14', '3', '/system/roleAdd.jsp', 0,'centerFrame', '2012-12-22 12:36:14', '2013-04-26 20:12:48', '1');
INSERT INTO `t_s_menu` VALUES ('15', '6', '1','角色查询', '1', null, '1#2#6#15', '3', '/system/roleList.jsp', 0,'centerFrame', '2012-12-22 14:29:28', '2013-04-26 20:12:53', '1');
INSERT INTO `t_s_menu` VALUES ('16', '5', '1','用户添加', '1', null, '1#2#5#16', '3', '/system/userAdd.jsp', 0,'centerFrame', '2012-12-22 18:34:26', '2013-04-26 20:12:57', '1');
INSERT INTO `t_s_menu` VALUES ('17', '5', '1','用户查询', '1', null, '1#2#5#17', '3', '/system/userList.jsp', 0,'centerFrame', '2012-12-22 19:56:13', '2013-04-26 20:13:01', '1');
-- ----------------------------
-- Table structure for t_s_privilege
-- ----------------------------
DROP TABLE IF EXISTS `t_s_privilege`;
CREATE TABLE `t_s_privilege` (
`pri_id` varchar(64) NOT NULL COMMENT '权限ID',
`sys_id` varchar(64) DEFAULT NULL,
`pri_code` varchar(64) DEFAULT NULL COMMENT '权限编码',
`pri_name` varchar(64) DEFAULT NULL COMMENT '权限名称',
`pri_desc` varchar(255) DEFAULT NULL COMMENT '权限描述',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`operator_id` varchar(64) DEFAULT NULL COMMENT '操作员ID',
PRIMARY KEY (`pri_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for t_s_pri_user
-- ----------------------------
DROP TABLE IF EXISTS `t_s_pri_user`;
CREATE TABLE `t_s_pri_user` (
`user_id` varchar(64) NOT NULL,
`pri_id` varchar(64) NOT NULL,
PRIMARY KEY (`user_id`,`pri_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for t_s_role
-- ----------------------------
DROP TABLE IF EXISTS `t_s_role`;
CREATE TABLE `t_s_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rolecode` varchar(32) DEFAULT NULL,
`rolename` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for t_s_role_menu
-- ----------------------------
DROP TABLE IF EXISTS `t_s_role_menu`;
CREATE TABLE `t_s_role_menu` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`roleid` int(10) DEFAULT NULL,
`menuid` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for t_s_sys
-- ----------------------------
DROP TABLE IF EXISTS `t_s_sys`;
CREATE TABLE `t_s_sys` (
`sys_id` varchar(32) DEFAULT NULL COMMENT '系统ID--唯一标识',
`sys_code` varchar(32) DEFAULT NULL COMMENT '系统编码',
`sys_name` varchar(255) DEFAULT NULL COMMENT '系统名称',
`sys_desc` varchar(255) DEFAULT NULL,
`enable` varchar(255) DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`operator_id` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='系统信息表';
-- ----------------------------
-- Table structure for t_s_sys_user
-- ----------------------------
DROP TABLE IF EXISTS `t_s_sys_user`;
CREATE TABLE `t_s_sys_user` (
`sys_id` varchar(32) NOT NULL DEFAULT '' COMMENT '系统ID',
`user_id` varchar(32) NOT NULL DEFAULT '' COMMENT '用户ID',
`password` varchar(128) DEFAULT NULL,
`user_type_id` varchar(64) DEFAULT NULL COMMENT '类型ID',
`state` tinyint(1) DEFAULT '1' COMMENT '0 禁用 1 正常',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`operator_id` varchar(64) DEFAULT NULL,
PRIMARY KEY (`sys_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for t_s_user
-- ----------------------------
DROP TABLE IF EXISTS `t_s_user`;
CREATE TABLE `t_s_user` (
`user_id` varchar(32) NOT NULL COMMENT '用户ID',
`login_account` varchar(64) DEFAULT NULL COMMENT '登录帐号',
`full_name` varchar(64) DEFAULT NULL COMMENT '用户姓名',
`nick_name` varchar(64) DEFAULT NULL COMMENT '昵称',
`email` varchar(64) DEFAULT NULL COMMENT '电子邮箱',
`mobile` varchar(16) DEFAULT NULL COMMENT '联系电话',
`remark` varchar(512) DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`operator_id` varchar(64) DEFAULT NULL COMMENT '操作员id',
PRIMARY KEY (`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
-- ----------------------------
-- Table structure for t_s_user_pri
-- ----------------------------
DROP TABLE IF EXISTS `t_s_user_pri`;
CREATE TABLE `t_s_user_pri` (
`user_id` varchar(64) DEFAULT NULL,
`pri_id` varchar(64) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for t_s_user_role
-- ----------------------------
DROP TABLE IF EXISTS `t_s_user_role`;
CREATE TABLE `t_s_user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) DEFAULT NULL,
`roleid` int(11) DEFAULT NULL,
`operator` varchar(255) DEFAULT NULL,
`createtime` datetime DEFAULT NULL,
`modifytime` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Function structure for getChildList
-- ----------------------------
DROP FUNCTION IF EXISTS `getChildList`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` FUNCTION `getChildList`(rootId INT) RETURNS varchar(1000) CHARSET utf8
BEGIN
DECLARE sTemp VARCHAR(1000);
DECLARE sTempChd VARCHAR(1000);
SET sTemp='$';
SET sTempChd =cast(rootId as CHAR);
WHILE sTempChd is not null DO
SET sTemp = concat(sTemp,',',sTempChd);
SELECT group_concat(id) INTO sTempChd FROM t_s_menu where FIND_IN_SET(parentid,sTempChd)>0;
END WHILE;
RETURN sTemp;
END
;;
DELIMITER ;
|
Markdown
|
UTF-8
| 5,763
| 2.546875
| 3
|
[] |
no_license
|
---
description: "Recipe of Any-night-of-the-week Crispy Baked Rosemary Chicken &amp; Potatoes"
title: "Recipe of Any-night-of-the-week Crispy Baked Rosemary Chicken &amp; Potatoes"
slug: 662-recipe-of-any-night-of-the-week-crispy-baked-rosemary-chicken-and-amp-potatoes
date: 2021-05-30T22:04:19.319Z
image: https://img-global.cpcdn.com/recipes/5046900944273408/680x482cq70/crispy-baked-rosemary-chicken-potatoes-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5046900944273408/680x482cq70/crispy-baked-rosemary-chicken-potatoes-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5046900944273408/680x482cq70/crispy-baked-rosemary-chicken-potatoes-recipe-main-photo.jpg
author: Lizzie Curtis
ratingvalue: 4.5
reviewcount: 31018
recipeingredient:
- "6 Chicken breast"
- "8 small Red potatoes quartered"
- "1/2 cup Red onions sliced"
- "1/2 cup Extravirgin oil or as needed"
- "1 tsp Garlic minced"
- "1/2 tsp Red pepper fresh minced"
- "1/4 cup Butter"
- "1/3 tsp Rosemary dried"
- "1/3 tsp Oregano dried"
- "1/3 tsp Parsley flakes dried"
- "1 tbsp Italian dressing"
- "1 Salt to taste"
recipeinstructions:
- "Preheat the oven to 375 (190 degrees C)."
- "Heat up the oil on medium heat, then melt butter in the oil. Once the butter is melted, add onions and cook for about 1 minute. Next add garlic, pepper, rosemary, oregano, parsley, Italian dressing, and salt to taste. Cook for about 5 minutes on low heat. Set sauce aside."
- "Cut the potatoes and place in a bowl. Mix some of the sauce into the bowl of potatoes well. Place potatoes in a baking pan and place in oven with the white part of the potatoes facing downward. Bake for 30 minutes."
- "While the potatoes is baking, slice each chicken into 3-4 slices per breast and put in a bowl. Mix some of the sauce into the bowl of chicken and set aside."
- "After the potatoes has baked for 30 minutes, turn the potatoes to the other white side facing downward on the pan. Baste sauce over the potatoes and chicken breasts and place in oven for another 30 minutes.(If the chicken and potatoes does not all fit on one pan, you may bake the chicken and potatoes on separate pans BUT place the pan of potatoes in the bottom oven AND keep an eye on the potatoes to avoid burning.)"
- "Optional, baste during the last 15 minutes for extra crispness."
categories:
- Recipe
tags:
- crispy
- baked
- rosemary
katakunci: crispy baked rosemary
nutrition: 195 calories
recipecuisine: American
preptime: "PT12M"
cooktime: "PT56M"
recipeyield: "3"
recipecategory: Lunch
---

Hey everyone, I hope you're having an incredible day today. Today, I will show you a way to prepare a special dish, crispy baked rosemary chicken & potatoes. It is one of my favorites food recipes. For mine, I am going to make it a little bit tasty. This is gonna smell and look delicious.
Crispy Baked Rosemary Chicken & Potatoes is one of the most popular of current trending foods on earth. It is appreciated by millions daily. It's easy, it's quick, it tastes yummy. Crispy Baked Rosemary Chicken & Potatoes is something which I've loved my entire life. They're nice and they look wonderful.
To get started with this recipe, we have to first prepare a few ingredients. You can cook crispy baked rosemary chicken & potatoes using 12 ingredients and 6 steps. Here is how you cook that.
<!--inarticleads1-->
##### The ingredients needed to make Crispy Baked Rosemary Chicken & Potatoes:
1. Make ready 6 Chicken breast
1. Get 8 small Red potatoes quartered
1. Make ready 1/2 cup Red onions; sliced
1. Get 1/2 cup Extra-virgin oil, or as needed
1. Prepare 1 tsp Garlic; minced
1. Take 1/2 tsp Red pepper; fresh & minced
1. Prepare 1/4 cup Butter
1. Make ready 1/3 tsp Rosemary; dried
1. Make ready 1/3 tsp Oregano; dried
1. Get 1/3 tsp Parsley flakes; dried
1. Make ready 1 tbsp Italian dressing
1. Make ready 1 Salt to taste
<!--inarticleads2-->
##### Steps to make Crispy Baked Rosemary Chicken & Potatoes:
1. Preheat the oven to 375 (190 degrees C).
1. Heat up the oil on medium heat, then melt butter in the oil. Once the butter is melted, add onions and cook for about 1 minute. Next add garlic, pepper, rosemary, oregano, parsley, Italian dressing, and salt to taste. Cook for about 5 minutes on low heat. Set sauce aside.
1. Cut the potatoes and place in a bowl. Mix some of the sauce into the bowl of potatoes well. Place potatoes in a baking pan and place in oven with the white part of the potatoes facing downward. Bake for 30 minutes.
1. While the potatoes is baking, slice each chicken into 3-4 slices per breast and put in a bowl. Mix some of the sauce into the bowl of chicken and set aside.
1. After the potatoes has baked for 30 minutes, turn the potatoes to the other white side facing downward on the pan. Baste sauce over the potatoes and chicken breasts and place in oven for another 30 minutes.(If the chicken and potatoes does not all fit on one pan, you may bake the chicken and potatoes on separate pans BUT place the pan of potatoes in the bottom oven AND keep an eye on the potatoes to avoid burning.)
1. Optional, baste during the last 15 minutes for extra crispness.
So that is going to wrap this up with this exceptional food crispy baked rosemary chicken & potatoes recipe. Thanks so much for your time. I'm sure that you will make this at home. There's gonna be interesting food in home recipes coming up. Remember to save this page on your browser, and share it to your family, friends and colleague. Thank you for reading. Go on get cooking!
|
Markdown
|
UTF-8
| 3,341
| 3.5
| 4
|
[] |
no_license
|
# CSS4 Missing Manuals 笔记
## 第三章 选择符
所有的选择器,都可以连用。
### 1 类型选择符--选取HTML标签名
```CSS
p {
border: 1px solid black;
}
```
可以选择同名的所有HTML标签
### 2 类选择符--精确控制某一个类型,必须给HTML标签设置一个类名
```css
.copyright {
color: #fff;
}
```
一个标签可以同时使用多个类,用空格分割类名.
常见类的使用是,使用一个类控制一个类别的基础样式,再用特定的类控制这个类别中具体类别的表现形式,比如UI框架中经常使用的按钮类:
```html
<button class="btn btn-primary">Click Me</button>
.btn {
......
}
.btn-primary {
......
}
```
### 3 ID选择符--精确选择某一个指定元素,一个页面内只有一个ID元素
```CSS
#submitbutton {
border-raidus: 10px;
}
```
Web设计中,CSS语言较少使用ID选择符。ID通常用于JS程序控制。
### 4 标签组选择符
```CSS
h1, h2, h3 {
color: #F1CD33;
}
```
逗号分割的部分是平行的,即样式将同时用于所有的h1, h2, h3标签。
还可以使用通用选择符*号。
```
* {
margin: 0;
padding: 0;
}
```
### 5 后代选择符
```css
.main a {
text-decoration: none;
}
```
选择.main类之下的所有a标签,后代指的是所有该标签之中符合条件的内容,而不是子代
### 6 属性选择符
```
a[href="http://conyli.cc"] {
color: orange;
}
```
选择所有具备该属性条件的标签或者其他类型的带有属性的选择器。
### 7 子代选择符
```
ul>li {
display:inline-block;
}
```
选择某个选择器的子代元素。
### 8 同辈选择符
```
h2 + p {
text-align: center;
}
h2 ~ p {
text-align: center;
}
```
### 9 伪类和伪元素
- a:link 尚未单击的普通链接,伪类
- a:visited 已访问的链接,伪类
- a:hover 修改鼠标悬停其上的链接, :hover伪类可用于任何元素
- a:active 按下鼠标到松开之前那很短的一段时间,伪类
现代Web设计一般将 link和visited设置为一组,hover和active一组设置,这样使得链接只有两种外形,简洁
- ::first-letter 第一个字母,伪元素,CSS3中伪元素以两个冒号开始
- ::first-line 第一行,伪元素
- :focus 伪类,当元素获得焦点的时候生效
- ::after 伪元素,在前部选择器的内部的最后插入内容,使用content 参数添加内容,非常常用
- ::before 伪元素,在前部选择器的内部的最前边插入内容,非常常用
- ::selection 伪元素,用户在网页中选择的内容,单独使用即可,无需在前边添加其他选择器。这个伪元素没有单冒号版本
### 10 子代中的特殊伪类
- :first-child 作为其他元素的子元素的第一个选择器
- :last-child 作为其他元素的子元素的最后一个选择器
- :only-child 作为其他元素的唯一一个子元素的选择器
- :nth-child 带括号参数
- :first-of-type 作为其他元素的子代的第一个某个类型的元素
- :last-of-type 作为其他元素的子代的最后一个某个类型的元素
- :nth-of-type 使用括号参数来灵活选择
### 11 特殊选择符
:target 与ID和锚点配合使用
:not 括号里指定选择器中取反的部分:
```CSS
p:not(.classy) {color:blue;}
```
|
Python
|
UTF-8
| 3,975
| 2.59375
| 3
|
[] |
no_license
|
import argparse
import io
from google.cloud import vision
from google.cloud.vision import types
import exifread
from datetime import datetime
def detect_labels(path):
"""Detects labels in the file."""
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description)
def annotate(path):
"""Returns web annotations given the path to an image."""
client = vision.ImageAnnotatorClient()
if path.startswith('http') or path.startswith('gs:'):
image = types.Image()
image.source.image_uri = path
else:
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
web_detection = client.web_detection(image=image).web_detection
return web_detection
def report(annotations):
"""Prints detected features in the provided web annotations."""
# if annotations.pages_with_matching_images:
# print('\n{} Pages with matching images retrieved'.format(
# len(annotations.pages_with_matching_images)))
#
# for page in annotations.pages_with_matching_images:
# print('Url : {}'.format(page.url))
#
# if annotations.full_matching_images:
# print ('\n{} Full Matches found: '.format(
# len(annotations.full_matching_images)))
#
# for image in annotations.full_matching_images:
# print('Url : {}'.format(image.url))
# #
# if annotations.partial_matching_images:
# print ('\n{} Partial Matches found: '.format(
# len(annotations.partial_matching_images)))
#
# for image in annotations.partial_matching_images:
# print('Url : {}'.format(image.url))
if annotations.web_entities:
# print ('\n{} Web entities found: '.format(
# len(annotations.web_entities)))
for entity in annotations.web_entities[:1]:
f = open(args.image_url,'rb')
tags = exifread.process_file(f, strict=True)
try:
tlat = tags['GPS GPSLatitude'].values
tlon = tags['GPS GPSLongitude'].values
lon = tlon[0].num/tlon[0].den + tlon[1].num/tlon[1].den/60.0 + tlon[2].num/tlon[2].den/3600.0
# To check how to do this properly!!
lon = -lon
lat = tlat[0].num/tlat[0].den + tlat[1].num/tlat[1].den/60.0 + tlat[2].num/tlat[2].den/3600.0
h, m, s = tags["GPS GPSTimeStamp"].values
datum = "{} {}:{}:{}".format(tags["GPS GPSDate"],str(h), str(m),str(s))
# timestamp = datetime.strptime(datum[:-4], '%Y:%m:%d %I:%M:%S')
except:
lon = 'nan'
lat = 'nan'
datum='nan____'
f.close()
with open('annotations.csv','a') as my_file:
my_file.write(','.join([args.image_url.split('/')[-1],datum[:-4], str(lat), str(lon),(entity.description),str(entity.score)[:4]+'\n']))
my_file.close()
print(','.join([args.image_url.split('/')[-1],datum[:-4],str(lat), str(lon), (entity.description),str(entity.score)[:4]]))
# print('Score : {}'.format(entity.score))
# print('Description: {}'.format(entity.description))
print('')
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
path_help = str('The image to detect, can be web URI, '
'Google Cloud Storage, or path to local file.')
parser.add_argument('image_url', help=path_help)
args = parser.parse_args()
report(annotate(args.image_url))
|
Java
|
UTF-8
| 6,868
| 4.15625
| 4
|
[] |
no_license
|
package sjsu.vo.cs146.project2;
enum Color { //colors to check whether the node has been discovered or not
WHITE, GREY, BLACK //WHITE is undiscovered, GREY is discovered but not fully explored, BLACK is fully explored
}
/**
* This class defines a Linked List to be used in the Adjacency List
* @authors Chris Vo and Wendy Chen
* @Version 1.0
*/
public class LinkedList {
//class variable declarations
private Node head; //a pointer to always point to the first node in the list.
private Node pointer; //to point to the current node in the list
private Node current; //to store the ID of the vertex in the maze
private int size; //the total number of nodes in the list
private int charindex; //the room # of the node in the ASCII maze
/**
* Constructor #1: This constructor creates a new instance of LinkedList with class variables initialized to 0 or equivalent.
* @param none
* @return none
*/
public LinkedList() {
head = new Node();
pointer = new Node();
current = new Node();
size = 0;
charindex = 0;
}
/**
* Constructor #2: This constructor creates a new instance of LinkedList, setting the vertex's ID
* to distinguish between each list
* @param ID - the node's identity number
* @return none
*/
public LinkedList(int ID) {
head = new Node();
pointer = new Node();
current = new Node(ID);
size = 0;
charindex = 0;
}
/**
* This method returns the size of the list
* @param none
* @return size - the total number of nodes in the list
*/
public int getSize() {
return size;
}
/**
* This method returns the pointer of the list
* @param none
* @return pointer - a Node that point to the current node in the list
*/
public Node getPointer() {
return pointer;
}
/**
* This method sets the pointer to the next node (or the head) in the list
* @param pointer - a Node that point to the current node in the list
* @return none
*/
public void setPointer(Node next) {
this.pointer = next;
}
/**
* This method returns the head of the list
* @param none
* @return head - a Node that references the first node in the list
*/
public Node getHead() {
return head;
}
/**
* This method returns a vertex in the adjacency list representation of the graph
* @param none
* @return current - a vertex in the graph
*/
public Node getCurrent() {
return current;
}
/**
* This method sets the value of CharIndex to the value of the parameter
* @param CharIndex - the room number of the node
* @return none
*/
public void setCharIndex(int charindex) {
this.charindex = charindex;
}
/**
* This method returns the value of CharIndex
* @param none
* @return CharIndex - the room number of the node
*/
public int getCharIndex() {
return charindex;
}
/**
* This method checks whether the list has nodes or not
* @param none
* @return boolean value - true if the list has no nodes, false otherwise
*/
public boolean isEmpty() {
if(size == 0)
return true;
else
return false;
}
/**
* This method appends a new node to the front of the list
* @param neighbor - a node the current vertex shares an edge with
* @return none
*/
public void addNode(Node neighbor) {
neighbor.next = head.next; //the new node points to the node head is currently pointing
head.next = neighbor; //the head will point to the new node
size++; //increments the total amount of nodes in the list
}
/**
* This inner class defines a customized node for the Linked List class
* @authors Chris Vo and Wendy Chen
* @Version 1.0
*/
public static class Node {
//class variable declarations
private Node next; //points to the vertex it shares an edge with
private Node prev; //points to the previous node. This is used for a Queue
private Color color; //color of the node to remember traversal order
private Node parent; //the parent node of the current node
private int start;
private int finish;
private int ID; //used to identify the nodes in the maze
/**
* Constructor #1: This constructor creates a new instance of Node with class variables initialized to 0 or equivalent.
* @param none
* @return none
*/
public Node() {
next = null;
prev = null;
parent = null;
start = 0;
finish = 0;
color = Color.WHITE;
ID = 0;
}
/**
* Constructor #2: This constructor creates a new instance of Node and initializes it's ID while setting
* all other variables to 0 or equivalent
* @param ID - the node's identity
* @return none
*/
public Node(int ID) {
next = null;
prev = null;
parent = null;
start = 0;
finish = 0;
color = Color.WHITE;
this.ID = ID;
}
/**
* This method sets the node's ID to a new value
* @param ID - the node's identity number
* @return none
*/
public void setID(int ID) {
this.ID = ID;
}
/**
* This method returns the node's ID
* @param none
* @return ID - the node's identity number
*/
public int getID() {
return ID;
}
/**
* This method connects the current node to an indicated node
* @param next - a node the current node points to
* @return none
*/
public void setNext(Node next) {
this.next = next;
}
/**
* This method returns the node the current node points to
* @param none
* @return next - a node the current node points to
*/
public Node getNext() {
return next;
}
/**
* This method connects the current node to an indicated node
* @param prev - a node the current node points to
* @return none
*/
public void setPrev(Node prev) {
this.prev = prev;
}
/**
* This method returns the node the current node points to
* @param none
* @return prev - a node the current node points to
*/
public Node getPrev() {
return prev;
}
/**
* This method sets the color of the node to a new value
* @param color - the color of the node to remember traversal order
* @return none
*/
public void setColor(Color color) {
this.color = color;
}
/**
* This method returns the color of the node
* @param none
* @return color - the color of the node to remember traversal order
*/
public Color getColor() {
return color;
}
/**
* This method returns the parent node
* @param none
* @return parent - the parent of this node
*/
public void setParent(Node parent) {
this.parent = parent;
}
/**
* This method sets the parent node to a new value
* @param parent - the parent of this node
* @return none
*/
public Node getParent() {
return parent;
}
public void setStart(int start) {
this.start = start;
}
public int getStart() {
return start;
}
public void setFinish(int finish) {
this.finish = finish;
}
public int getFinish() {
return finish;
}
}
}
|
Markdown
|
UTF-8
| 342
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
# vomit
control flow callback<->promise magic helper
## example
```js
var math = {};
math.sum = function (a, b, cb) { cb(null, a+b); };
math.mul = function (a, b, cb) { cb(null, a*b); };
vomit(math, function (sum, mul) {
return mul(sum(1, sum(2,2)), 3);
}, function(err, result){
console.log(result); // 15
});
```
## License
MIT
|
Java
|
UTF-8
| 2,380
| 2.265625
| 2
|
[] |
no_license
|
// import org.openqa.selenium.By;
// import org.openqa.selenium.WebDriver;
// import org.openqa.selenium.WebElement;
// import org.openqa.selenium.firefox.FirefoxDriver;
// import java.util.Random;
// public class Test {
// public static void main(String[] args) throws InterruptedException {
// System.setProperty("webdriver.gecko.driver",
// "/eclipsework/geckodriver.exe");
// WebDriver driver = new FirefoxDriver();
// driver.get("file:///D:/2dpacking/Base%20GUI/Capstone_allocation.html");
// Random r = new Random();
// //a
// WebElement imgUpload1 = driver.findElement(By.id("uploaded-file"));
// imgUpload1.sendKeys("D:\\2dpacking\\Base GUI\\Capstone 2019
// Layout_Page_1_clean.png");
// Thread.sleep(2000);
// //b
// WebElement imgUpload2 = driver.findElement(By.id("uploaded-file2"));
// imgUpload2.sendKeys("D:\\2dpacking\\Base GUI\\Capstone 2019
// Layout_Page_2._clean.png");
// Thread.sleep(2000);
// //c
// WebElement container = driver.findElement(By.id("container"));
// //d
// WebElement container2 = driver.findElement(By.id("container2"));
// //e
// WebElement excelUpload = driver.findElement(By.id("uploaded-excel"));
// excelUpload.sendKeys("D:\\2dpacking\\2019 Showcase Space and Logistics
// Requirements_7Aug2019.xlsx");
// //f
// //g
// WebElement runBtn = driver.findElement(By.id("runBtn"));
// runBtn.click();
// //h
// WebElement saveBtn = driver.findElement(By.id("save-button"));
// saveBtn.click();
// //i
// WebElement saveBtn2 = driver.findElement(By.id("save-button2"));
// saveBtn2.click();
// //j
// WebElement drawBtn = driver.findElement(By.id("drawBtn"));
// drawBtn.click();
// //k
// //l
// //m
// WebElement editBtn = driver.findElement(By.id("editBtn"));
// editBtn.click();
// //n
// //o
// //p
// WebElement zin = driver.findElement(By.id("zoomIn"));
// zin.click();
// //q
// WebElement zout = driver.findElement(By.id("zoomOut"));
// zout.click();
// //r
// WebElement zin2 = driver.findElement(By.id("zoomIn2"));
// zin2.click();
// //s
// WebElement zout2 = driver.findElement(By.id("zoomOut2"));
// zout2.click();
// //t
// //u
// //v
// WebElement binSize = driver.findElement(By.id("binSize"));
// int newRatio = r.nextInt(401)+100;
// String newRat = Integer.toString(newRatio);
// binSize.sendKeys("value", newRat);
// //w
// WebElement ratioBtn = driver.findElement(By.id("ratioButton"));
// ratioBtn.click();
// }
// }
|
Java
|
UTF-8
| 1,461
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.gbif.occurrence.downloads.launcher.config;
import org.apache.oozie.client.OozieClient;
import org.gbif.occurrence.downloads.launcher.pojo.RegistryConfiguration;
import org.gbif.registry.ws.client.OccurrenceDownloadClient;
import org.gbif.ws.client.ClientBuilder;
import org.gbif.ws.json.JacksonJsonObjectMapperProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** Configuration for the clients used by the launcher. */
@Configuration
public class ClientConfiguration {
/**
* Provides an Oozie client.
*
* @param url the Oozie URL
* @return an Oozie client
*/
@Bean
public OozieClient providesOozieClient(@Value("${occurrence.download.oozie.url}") String url) {
return new OozieClient(url);
}
/**
* Provides an OccurrenceDownloadClient.
*
* @param configuration the registry configuration
* @return an OccurrenceDownloadClient
*/
@Bean
public OccurrenceDownloadClient occurrenceDownloadClient(RegistryConfiguration configuration) {
return new ClientBuilder()
.withUrl(configuration.getApiUrl())
.withCredentials(configuration.getUserName(), configuration.getPassword())
.withObjectMapper(JacksonJsonObjectMapperProvider.getObjectMapperWithBuilderSupport())
.withFormEncoder()
.build(OccurrenceDownloadClient.class);
}
}
|
Java
|
UTF-8
| 1,337
| 2.53125
| 3
|
[] |
no_license
|
package com.team3.mbts.entity;
/**
*
* Project:moviebookticketsystem
* Package:com.team3.mbts.entity
* FileName:Area.java 行政区划表
* Comments:
* JDK Version:
* Author : 徐晓聪
* Create Date:2015-2-10 下午8:37:53
* Modified By :
* Modified Time:
* What is Modified:
* Version:
*/
public class Area {
/**
* 行政区编号
*/
private int areaId;
/**
* 行政区名
*/
private String areaName;
/**
* 父级行政区编号
*/
private int parentId;
/**
* 行政区级别 1省/2市/3区县
*/
private byte areaLevel;
/**
* 状态,1可用/0不可用
*/
private byte status = 1;
public int getAreaId() {
return areaId;
}
public void setAreaId(int areaId) {
this.areaId = areaId;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public byte getAreaLevel() {
return areaLevel;
}
public void setAreaLevel(byte areaLevel) {
this.areaLevel = areaLevel;
}
public byte getStatus() {
return status;
}
public void setStatus(byte status) {
this.status = status;
}
}
|
Python
|
UTF-8
| 1,997
| 3.15625
| 3
|
[] |
no_license
|
def prim(adj, start):
weight = [1000000] * (V + 1)
mst = [0] * (V + 1)
weight[start] = 0 # 초기화 필수
result = 0
for _ in range(V + 1):
# 현재 갈 수 있는 경로 중 가장 가중치가 작은 경로를 선택
min_w = 10000000
min_v = 0
for i in range(V + 1):
if mst[i] == 0 and weight[i] < min_w:
min_w = weight[i]
min_v = i
mst[min_v] = 1 # 체크체크
result += min_w
for i in range(V + 1):
if 0 < adj[min_v][i] < weight[i] and not mst[i]:
weight[i] = adj[min_v][i]
return result
for tc in range(1, int(input()) + 1):
V, E = map(int, input().split())
adj = [[0] * (V + 1) for _ in range(V + 1)]
for i in range(E):
s, e, w = map(int, input().split())
adj[s][e] = w
adj[e][s] = w
print('#{} {}'.format(tc, prim(adj, 0)))
'''
3
2 3
0 1 1
0 2 1
1 2 6
4 7
0 1 9
0 2 3
0 3 7
1 4 2
2 3 8
2 4 1
3 4 8
4 6
0 1 10
0 2 7
1 4 2
2 3 10
2 4 3
3 4 10
'''
# kruskal 로 풀어보기 겨수님 풀이
#
# def make_set(x):
# p[x] = x
#
#
# def find_set(x):
# if p[x] != x:
# p[x] = find_set(p[x])
# return p[x]
#
#
# def union(x, y):
# p[find_set(y)] = find_set(x)
#
#
# for tc in range(1, int(input()) + 1):
# V, E = map(int, input().split())
#
# edges = [list(map(int, input().split())) for _ in range(E)]
#
# p = [0] * (V + 1)
#
# # 가중치 정렬
#
# edges = sorted(edges, key=lambda x: x[2])
# for i in range(V + 1):
# make_set(i)
#
# ans = 0
# cnt = 0 # 간선을 v개 선택을 해야하니깐
# idx = 0
#
# while cnt < V:
# x = edges[idx][0]
# y = edges[idx][1]
#
# if find_set(x) != find_set(y): # 같은 그룹이아닐때만 union
# union(x, y)
# cnt += 1 # 간선을 선택 한것임
# ans += edges[idx][2]
# idx += 1
# print(ans)
|
Markdown
|
UTF-8
| 5,590
| 2.796875
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Contributing
We love contributions! and we'd love to have you hang out in our community.
**Impostor syndrome disclaimer**: We want your help. No, really.
There may be a little voice inside your head that is telling you that you're not
ready to be an open source contributor; that your skills aren't nearly good
enough to contribute. What could you possibly offer a project like this one?
We assure you - the little voice in your head is wrong. If you can write code at
all, you can contribute code to open source. Contributing to open source
projects is a fantastic way to advance one's coding skills. Writing perfect code
isn't the measure of a good developer (that would disqualify all of us!); it's
trying to create something, making mistakes, and learning from those
mistakes. That's how we all improve, and we are happy to help others learn.
Being an open source contributor doesn't just mean writing code, either. You can
help out by writing documentation, tests, or even giving feedback about the
project (and yes - that includes giving feedback about the contribution
process). Some of these contributions may be the most valuable to the project as
a whole, because you're coming to the project with fresh eyes, so you can see
the errors and assumptions that seasoned contributors have glossed over.
## What Can I Do?
* Tackle any [issues](https://github.com/ELSPL/ml_practices_2018/issues) you wish! We have a special
label for issues that beginners might want to try. Have a look at our
[current beginner issues.](https://github.com/ELSPL/ml_practices_2018/issues?q=is%3Aopen+is%3Aissue+label%3Astarter)
Also have a look at if the issue is already assigned to someone - this helps us make sure
that work is not duplicated if the issue is already being worked on by members. If its assigned it will have label "Status: In Progress"
* Contribute code you already have. It does not need to be perfect! We will help you clean
things up, test it, etc.
* Make a tutorial or example of how to do something.
* Improve documentation of a feature you found troublesome. You can add tutorials, books or any helpful resources you found necessary while working in this community.
* File a new issue if you run into problems!
## Ground Rules
The goal is to maintain a diverse community that's pleasant for everyone. Please
be considerate and respectful of others by following our
[code of conduct](https://github.com/ELSPL/ml_practices_2018/blob/master/.github/CODE_OF_CONDUCT.md).
Other items:
* Each pull request should consist of a logical collection of changes. You can
include multiple bug fixes in a single pull request, but they should be related.
For unrelated changes, please submit multiple pull requests.
* Do not commit changes to files that are irrelevant to your feature or bugfix
(eg: .gitignore).
* Be willing to accept criticism and work on improving your code; we don't want
to break other users' code, so care must be taken not to introduce bugs.
* Be aware that the pull request review process is not immediate, and is
generally proportional to the size of the pull request.
## Usage questions
The best place to submit questions about how to get started or any query is via the
[slack](https://elsplworkspace.slack.com/messages/CF28SJ8PM/) channel.
Usage question in the issue tracker will probably go unanswered.
## Reporting issues
The easiest way to get involved is to report issues you encounter when using our repository or by
requesting something you think is missing.
* Head over to the [issues](https://github.com/ELSPL/ml_practices_2018/issues) page.
* Search to see if your issue already exists or has even been solved previously.
* If you indeed have a new issue or request, click the "New Issue" button. Select type of Issue.
* Fill in as much of the issue template as is relevant. Please be as specific as possible.
Include the version of the code you were using, as well as what operating system you
are running. If possible, include complete, minimal example code that reproduces the problem.
* Whenever possible, please also include a [short, self-contained code example](http://sscce.org) that demonstrates the problem.
## Contributing code
First of all, thanks for your interest in contributing!
Refer to [GIT_WORKFLOW.md](https://github.com/ELSPL/ml_practices_2018/blob/master/.github/GIT_WORKFLOW.md) for branching guide.
### Coding Style, Standards and Convention
#### Python coding style
Changes to Python code should conform to
[Google Python Style Guide](https://google.github.io/styleguide/pyguide.html)
Use `pylint` to check your Python changes. To install `pylint` and
retrieve our custom style definition:
```bash
pip install pylint
```
<!--- wget -O /tmp/pylintrc https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/tools/ci_build/pylintrc -->
To check a file with `pylint`:
```bash
pylint --rcfile=/tmp/pylintrc myfile.py
```
### Merging
Once we're all happy with the pull request, it's time for it to get merged in. Only the
maintainers can merge pull requests and you should never merge a pull request you have commits
on as it circumvents the code review. If this is your first or second pull request, we'll
likely help by rebasing and cleaning up the commit history for you. As your developement skills
increase, we'll help you learn how to do this.
## More Questions?
If you're stuck somewhere or are interested in being a part of the community in
other ways, feel free to contact us:
* [Slack Channel](https://elsplworkspace.slack.com/messages/CF28SJ8PM/)
|
JavaScript
|
UTF-8
| 1,926
| 2.53125
| 3
|
[] |
no_license
|
const express = require('express');
const mysql = require('mysql');
const path = require('path');
const bodyParser = require('body-parser');
//https://stackabuse.com/node-js-express-examples-rendered-rest-and-static-websites/ // Gutes Beispiel
//https://www.tutorialspoint.com/nodejs/nodejs_event_emitter.htm // Events
// Vue.js https://vuejs.org/v2/guide/
//Create connectoin
const db = mysql.createConnection({
host: "s224.goserver.host",
user: "web234",
password : "jsukj3jpLZCsVDE",
database: 'web234_db2'
});
db.connect((err) => {
if(err){
throw err;
}
console.log("Database connection established");
})
//EXCLUDE!
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
/**
* API
*/
//CREATE DB
app.get('/createdb', (req,res) => {
let sql = 'CREATE DATABASE nodemysql';
db.query(sql, (err,result) => {
if (err) throw err;
console.log(result);
res.send('db created');
})
})
//web234_db2.users
/*
id auto
full name varchar(45) not Null
phone varchar(45) null
email varchar(45) not Null
gender varchar(1) null
photos blob null
age int(11) null
*/
app.get('/addUser', (req, res) => {
for(var i = 0; i < 60; i++){
var duude = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
let data = {
full_name: "duude"+duude,
email: duude+"@test.com",
gender: "m",
age: "67"
}
let sql = 'INSERT INTO web234_db2.users SET ?';
let query = db.query(sql,data, (err,result) => {
if (err) throw err;
console.log(result);
});
res.send('users added');
}
});
/**
* STATIC FILES
*/
app.use('/', express.static('app'));
//Default every except api to ->
app.get('*', function(req,res){
res.sendFile(path.join(__dirname + '/app/index.html'));
})
module.exports =app;
|
Java
|
UTF-8
| 140
| 2.3125
| 2
|
[] |
no_license
|
package ru.aglophotis.patterns.facade;
public class SumOperation {
public static int sum(int a, int b) {
return a + b;
}
}
|
Java
|
UTF-8
| 278
| 2.53125
| 3
|
[] |
no_license
|
public abstract class AttendanceAdapter implements Attendence{
Student S=null;
void setStudent(Student f){ //object pass
S = f; // assign
}
//@override
public void giveAttendanc(){
S.getGiveAttendance();//method call
}
}
|
Go
|
UTF-8
| 9,529
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
package main
// TODO Test suite
// TODO Render to browser - see https://golang.org/doc/articles/wiki/#tmp_6
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"math/rand"
"net/http"
"os"
"reflect"
"strings"
"time"
"github.com/jinzhu/inflection"
)
type MazeData struct {
Features []string
Paths []string // TODO Should this be a struct with the description?
Items []string
CombatGear []string // TODO What about list of actual items inside categories? random(random?
Appearances []string
PhysicalDetails []string
Backgrounds []string
Clothing []string
Personalities []string
Mannerisms []string
Characters struct {
MaleNames []string
FemaleNames []string
UpperClassSurnames []string
LowerClassSurnames []string
}
Magic struct {
PhysicalEffects []string
PhysicalElements []string
PhysicalForms []string
EtherialEffects []string
EtherialElements []string
EtherialForms []string
}
}
type MazeChar struct {
Strength int
Dexterity int
Will int
Health int
ArmorRating int
AttackBonus int
SpellSlotsMax int // number of spell slots TODO needed when Feature=SS recorded? starting characters only
SpellSlots []string // actual generated spells
Feature string // what feature you got, for obviousness
Path string // can be empty
Items []string
CombatGear []string
Appearance string
PhysicalDetail string
Background string
Clothing string
Personality string
Mannerism string
FirstName string
Surname string
Level int
XP int
}
// globals
var data MazeData
var char MazeChar
var tpl *template.Template
// Used for generating MazeData.Magic
var spellTable [6][2][2]string
// why, golang?
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
var vowels = []string{"a", "e", "i", "o", "u"}
/**
* Given a string input, return it formatted for a sentence.
* Doesn't care about capitalization, that's handled by css.
* E.g. "Battle Scars" -> "Battle Scars" (plural)
* "Birthmark" -> "a Birthmark" (a)
* "Animal Scent" -> "an Animal Scent" (an)
* As more cases as discovered, reveal here.
*/
func naturalLanguageSplice(input string) string {
input = strings.TrimSpace(input)
// plural test, "Battle Scars" means NO a OR an.
if isPlural(input) {
return input
}
// vowel test for "an apple" etc.
first := strings.ToLower(input[0:1])
if contains(vowels, first) {
return "an " + input
}
return "a " + input
}
func isPlural(input string) bool {
words := strings.Split(input, " ")
lastWord := strings.ToLower(words[len(words)-1])
singular := inflection.Singular(lastWord)
plural := inflection.Plural(lastWord)
// log.Printf("lastWord=%s, singular=%s, plural=%s", lastWord, singular, plural)
if singular != plural && lastWord == plural {
return true
}
return false
}
func randInt(min, max int) int {
return (min + rand.Intn((max+1)-min))
}
func prettyPrint(data interface{}) string {
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
return ""
}
return string(b[:]) // fuck sake, golang
}
func loadData(filePath string) (MazeData, error) {
var data MazeData
dataFile, err := os.Open(filePath)
defer dataFile.Close()
if err != nil {
return data, err
}
jsonParser := json.NewDecoder(dataFile)
err = jsonParser.Decode(&data)
return data, err
}
func randAbility() int {
switch randInt(1, 6) {
case 1, 2:
return 0
case 3, 4, 5:
return 1
case 6:
return 2
default:
log.Fatal("Unrecognised ability score.")
}
return 0
}
// TODO Pass array of exclusions to avoid dupes. See randomItems() and contains()
func getRandom(options []string) string {
return options[rand.Intn(len(options))]
}
func randomItems(options []string, max int) []string {
var items = make([]string, 0)
var current = 0
var item string
// TODO limit iterations by reducing options instead of checking for dupes.
for current < max {
item = getRandom(options)
if contains(items, item) == false {
items = append(items, item)
current = current + 1
}
}
return items
}
func initSpellTable() {
spellTable[0][0][0] = "PhysicalEffects"
spellTable[0][0][1] = "PhysicalForms"
spellTable[0][1][0] = "EtherialElements"
spellTable[0][1][1] = "PhysicalForms"
spellTable[1][0][0] = "PhysicalEffects"
spellTable[1][0][1] = "EtherialForms"
spellTable[1][1][0] = "EtherialElements"
spellTable[1][1][1] = "EtherialForms"
spellTable[2][0][0] = "EtherialEffects"
spellTable[2][0][1] = "PhysicalForms"
spellTable[2][1][0] = "PhysicalEffects"
spellTable[2][1][1] = "PhysicalElements"
spellTable[3][0][0] = "EtherialEffects"
spellTable[3][0][1] = "EtherialForms"
spellTable[3][1][0] = "PhysicalEffects"
spellTable[3][1][1] = "EtherialElements"
spellTable[4][0][0] = "PhysicalElements"
spellTable[4][0][1] = "PhysicalForms"
spellTable[4][1][0] = "EtherialEffects"
spellTable[4][1][1] = "PhysicalElements"
spellTable[5][0][0] = "PhysicalElements"
spellTable[5][0][1] = "EtherialForms"
spellTable[5][1][0] = "EtherialEffects"
spellTable[5][1][1] = "EtherialElements"
}
func initInflections() {
inflection.AddUncountable("cautious")
}
func generateStartingFeature(data MazeData, char *MazeChar) {
char.Feature = getRandom(data.Features)
switch char.Feature {
case "AB":
char.AttackBonus = char.AttackBonus + 1
case "SS":
char.SpellSlotsMax = char.SpellSlotsMax + 1
case "PA":
char.Path = getRandom(data.Paths)
default:
log.Fatal("Unknown feature:", char.Feature)
}
}
func generateCombatGear(data MazeData, char *MazeChar) {
// Everyone gets light armor and a shield
char.CombatGear = append(char.CombatGear,
"Light Armor (+1 armor)",
"Shield (+1 armor, 1 hand)",
getRandom(data.CombatGear),
getRandom(data.CombatGear),
)
}
func generateCharacter(data MazeData) MazeChar {
var char MazeChar
char.Level = 1
char.XP = 0
char.Strength = randAbility()
char.Dexterity = randAbility()
char.Will = randAbility()
char.Health = 4
char.ArmorRating = 6 // base human, may increase with armor
char.AttackBonus = 0
char.SpellSlotsMax = 0
generateStartingFeature(data, &char)
char.Items = randomItems(data.Items, 2) // TODO 6, when more data
generateCombatGear(data, &char)
char.Appearance = getRandom(data.Appearances)
char.PhysicalDetail = getRandom(data.PhysicalDetails)
char.Background = getRandom(data.Backgrounds)
char.Clothing = getRandom(data.Clothing)
char.Personality = getRandom(data.Personalities)
char.Mannerism = getRandom(data.Mannerisms)
// TODO Should we determine gender?
char.FirstName = getRandom(append(data.Characters.MaleNames, data.Characters.FemaleNames...))
char.Surname = getRandom(append(data.Characters.UpperClassSurnames, data.Characters.LowerClassSurnames...))
log.Println("Generated " + char.FirstName + " " + char.Surname + ", " + char.Background)
return char
}
// Use the spellTable and json Magic data to generate a random combination spellname.
func generateSpellName() string {
row := randInt(0, 5)
col := randInt(0, 1)
spellType1 := spellTable[row][col][0]
spellType2 := spellTable[row][col][1]
// log.Println("row:", row+1, "col:", col+1, "spellType1:", spellType1, "spellType2:", spellType2)
v := reflect.ValueOf(data.Magic)
spellValue1 := v.FieldByName(spellType1).Interface().([]string)
spellValue2 := v.FieldByName(spellType2).Interface().([]string)
spellName := getRandom(spellValue1) + " " + getRandom(spellValue2)
log.Println("spellName (" + spellType1 + " + " + spellType2 + "): " + spellName)
return spellName
}
func renderCharacterAsHtml(w http.ResponseWriter, char MazeChar) {
err := tpl.Execute(w, char)
if err != nil {
log.Println(err)
}
}
func writeJsonHeaders(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
}
func renderCharacterAsJson(w http.ResponseWriter, char MazeChar) {
writeJsonHeaders(w)
fmt.Fprintf(w, prettyPrint(char))
}
func handleJson(w http.ResponseWriter, r *http.Request) {
char = generateCharacter(data)
renderCharacterAsJson(w, char)
}
func handleHtml(w http.ResponseWriter, r *http.Request) {
char = generateCharacter(data)
renderCharacterAsHtml(w, char)
}
func handleJsonSpell(w http.ResponseWriter, r *http.Request) {
writeJsonHeaders(w)
fmt.Fprintf(w, prettyPrint(generateSpellName()))
}
func initData() {
var err error
data, err = loadData("./data.json")
if err != nil {
log.Fatal(err)
}
// log.Println("data:", prettyPrint(data))
}
func main() {
log.Println("maze-rats-chargen server starting up.")
rand.Seed(time.Now().Unix()) // pseudorandom
// Load shared resources once on start, not every request.
var err error
initData()
file, err := ioutil.ReadFile("./chargen.html")
if err != nil {
log.Fatal(err)
}
funcs := template.FuncMap{
"join": strings.Join,
"nls": naturalLanguageSplice,
}
tpl, err = template.New("chargen").Funcs(funcs).Parse(string(file))
if err != nil {
log.Fatal(err)
}
initSpellTable()
initInflections()
http.HandleFunc("/", handleHtml)
http.HandleFunc("/json", handleJson) // TODO What about using accept header?
http.HandleFunc("/spell", handleJsonSpell)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
http.ListenAndServe(":5000", nil)
}
|
Java
|
UTF-8
| 714
| 2.484375
| 2
|
[] |
no_license
|
import java.lang.reflect.InvocationTargetException;
public class TestingClass {
@BeforeSuite
public static void test1(){
System.out.println("test 1");
}
@Test(prior=1)
public static void test2(){
System.out.println("test 2");
}
@Test(prior=3)
public static void test3(){
System.out.println("test 3");
}
@AfterSuite
//@Test(prior=2)
public static void test4(){
System.out.println("test 4");
}
@AfterSuite
public static void test5(){
System.out.println("test 5");
}
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
MyTest.start(TestingClass.class);
}
}
|
Java
|
UTF-8
| 5,590
| 2.046875
| 2
|
[] |
no_license
|
package com.official.read.ui;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.widget.RadioGroup;
import com.github.jdsjlzx.recyclerview.LuRecyclerView;
import com.official.read.R;
import com.official.read.base.BaseActivity;
import com.official.read.base.BasePresenter;
import com.official.read.util.Toaster;
import com.official.read.weight.my_diy.RadarView;
import com.official.read.weight.my_diy.StatisticsView;
import com.official.read.weight.my_diy.SuperStatisticsView;
import java.util.ArrayList;
import java.util.List;
public class DIYActivity extends BaseActivity {
RadarView twoView;
StatisticsView statisticsView;
RadioGroup group;
SuperStatisticsView superStatisticsView;
@Override
protected int getDisplayState() {
// return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
return super.getDisplayState();
}
@Override
protected int getContentView() {
return R.layout.activity_diy;
}
@Override
protected BasePresenter initPresenter() {
return null;
}
@Override
protected void initView(Bundle savedInstanceState) {
setTitle("TEST-DIY-PAGE");
twoView = (RadarView) $(R.id.diy_twoView);
twoView.setRadarClickListener(new RadarView.RadarClickListener() {
@Override
public void start() {
Toaster.makeText("雷达开始工作");
}
@Override
public void stop() {
Toaster.makeText("雷达停止工作");
}
});
group = (RadioGroup) $(R.id.diy_statisticsGroup);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
switch (checkedId) {
case R.id.diy_1:
statisticsView.setRectangleShow();
break;
case R.id.diy_2:
statisticsView.setDiscountShow();
break;
}
}
});
superStatisticsView = (SuperStatisticsView) $(R.id.diy_superStatisticsView);
superStatisticsView.setData(getData());
statisticsView = (StatisticsView) $(R.id.diy_statisticsView);
statisticsView.setData(getData());
statisticsView.setStatisticsClickListener(new StatisticsView.StatisticsClickListener() {
@Override
public void click(int position, StatisticsView.Statistics statistics) {
Toaster.makeText("当前查看的是:" + statistics.name + ",份数为:" + statistics.data);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
twoView.clear();
}
@Override
protected void initData(Bundle savedInstanceState) {
}
@Override
protected int getStatusColor() {
return 0;
}
@Override
protected SwipeRefreshLayout getSwipeRefreshLayout() {
return null;
}
@Override
protected LuRecyclerView getLuRecyclerView() {
return null;
}
private List<StatisticsView.Statistics> getData() {
List<StatisticsView.Statistics> list = new ArrayList<>();
StatisticsView.Statistics statistics1 = new StatisticsView.Statistics();
statistics1.data = 500;
statistics1.name = "java";
statistics1.percentage = 0.50;
StatisticsView.Statistics statistics2 = new StatisticsView.Statistics();
statistics2.data = 300;
statistics2.name = "C++";
statistics2.percentage = 0.30;
StatisticsView.Statistics statistics3 = new StatisticsView.Statistics();
statistics3.data = 150;
statistics3.name = "iOS";
statistics3.percentage = 0.15;
StatisticsView.Statistics statistics4 = new StatisticsView.Statistics();
statistics4.data = 50;
statistics4.name = "C#";
statistics4.percentage = 0.05;
StatisticsView.Statistics statistics5 = new StatisticsView.Statistics();
statistics5.data = 45;
statistics5.name = "JS";
statistics5.percentage = 0.04;
StatisticsView.Statistics statistics6 = new StatisticsView.Statistics();
statistics6.data = 205;
statistics6.name = "H5";
statistics6.percentage = 0.22;
StatisticsView.Statistics statistics7 = new StatisticsView.Statistics();
statistics7.data = 145;
statistics7.name = "PHP";
statistics7.percentage = 0.06;
StatisticsView.Statistics statistics8 = new StatisticsView.Statistics();
statistics8.data = 335;
statistics8.name = "Ajax";
statistics8.percentage = 0.14;
StatisticsView.Statistics statistics9 = new StatisticsView.Statistics();
statistics9.data = 245;
statistics9.name = "ASP";
statistics9.percentage = 0.10;
StatisticsView.Statistics statistics10 = new StatisticsView.Statistics();
statistics10.data = 109;
statistics10.name = "GO";
statistics10.percentage = 0.04;
list.add(statistics1);
list.add(statistics2);
list.add(statistics3);
list.add(statistics4);
list.add(statistics5);
list.add(statistics6);
list.add(statistics7);
list.add(statistics8);
list.add(statistics9);
list.add(statistics10);
return list;
}
}
|
Python
|
UTF-8
| 4,792
| 2.640625
| 3
|
[] |
no_license
|
'''
Created on Apr 1, 2017
@author: WKaczurb
'''
import time
import logging
from timer.TimerHandler import TimerHandler
from timer.TimerSetting import TimerSetting
from gpios.GpioPin import GpioPin
#from nt import abort
# TODO: Add logger, uncomment prints in ZoneHandler.gpioOutput and chnage them to output via logger.
class ZoneHandler(object):
'''
classdocs
'''
def __init__(self, zoneSetting, gpioPin):
'''
Constructor
'''
#self.noDataTimeoutTime = 30 # 30 seconds acceptable when no data is received.
self.logger = logging.getLogger('ZoneHandler')
if (not ZoneHandler.isValidZoneSettings(zoneSetting)):
self.zoneSetting = None
raise ValueError("zoneSetting must contain keys 'mode' and 'automaticModeSettings'")
else:
self.zoneSettingTimestamp = time.time() # timestamp when last time setting was received.
self.zoneSetting = zoneSetting
if not isinstance(gpioPin, GpioPin):
raise TypeError("gpioPin must be of type GpioPin (from gpios.GpioPin module)")
self.timerHandler = None # placeholder
self.gpioPin = gpioPin # placeholder for class that handles Gpio's Pin.
self.applyZoneSettings()
def setGpioPin(self, gpioPin):
self.gpioPin = gpioPin
def getGpioPin(self):
return self.gpioPin
# TODO: This funciton should be moved to a seprate class ZoneSetting or similar.
@staticmethod
def isValidZoneSettings(z):
if not isinstance(z, dict):
return False
if not (z.keys().__contains__("mode") and z.keys().__contains__("automaticModeSettings")):
raise ValueError("zoneSetting must contain keys 'mode' and 'automaticModeSettings'")
if not (z.keys().__contains__("mode") and z.keys().__contains__("automaticModeSettings")):
return False
#raise ValueError("zoneSetting must contain keys 'mode' and 'automaticModeSettings'")
return True
def applyZoneSettings(self):
if (self.zoneSetting == None):
assert (self.timerHandler != None) # timerHandler should be defined here.
self.timerHandler.notifyObservers()
return
timerSettings = TimerSetting.createTimerSettings(self.zoneSetting['automaticModeSettings'])
if (self.timerHandler == None):
self.timerHandler = TimerHandler()
self.timerHandler.setTimerSettings(timerSettings)
self.timerHandler.addObserver(lambda x: self.update(x)) # x => timerHandler
self.timerHandler.start()
else:
self.timerHandler.setTimerSettings(timerSettings)
self.timerHandler.notifyObservers()
def getTimerHandler(self):
return self.timerHandler
def getZoneSetting(self):
return self.zoneSetting
def setZoneSetting(self, zoneSetting):
if (ZoneHandler.isValidZoneSettings(zoneSetting)):
self.zoneSetting = zoneSetting
self.zoneSettingTimestamp = time.time()
else:
self.zoneSetting = None
self.applyZoneSettings()
def kill(self):
"""Remove timer handler, remove observers. """
# unregister everything... and remove observers
self.timerHandler.removeAllObservers()
self.timerHandler.stop()
self.timerHandler = None
self.removeTimerHandler()
self.gpioOutput(False)
# TODO: timerHandler argument is redundant in this case; remove it
def update(self, timerHandler):
if (self.zoneSetting == None):
self.logger.warn("No valid data received - switching off zone.")
self.gpioOutput(False)
return
if (self.zoneSetting["mode"] == "MANUAL_ON"):
self.gpioOutput(True)
elif (self.zoneSetting["mode"] == "MANUAL_OFF"):
self.gpioOutput(False)
elif (self.zoneSetting["mode"] == "AUTOMATIC"):
# in the automatic mode - output depends on time:
if (self.timerHandler.checkIfFits()):
self.gpioOutput(True)
else:
self.gpioOutput(False)
else:
raise ValueError("ZoneSetting['mode'] should be within MANUAL_ON, MANUAL_OFF, AUTOMATIC")
pass
def gpioOutput(self, on):
if (on == True):
self.gpioPin.gpioOutputHigh()
else:
self.gpioPin.gpioOutputLow()
|
Java
|
UTF-8
| 1,748
| 3.328125
| 3
|
[] |
no_license
|
package chess;
import alogrithm.BaseStepNode;
import alogrithm.Search;
import java.util.HashMap;
import java.util.Map;
/**
* 玩家, 心里边有自己的思路, 有自己的棋局,
* @author lixiangyang
*
*/
public class Player {
private Board board;
private char color;
private Search search;
private int step;
/**
* 玩家自己的棋子.
*/
private Map<String, Piece> ownPieces;
public Player(Board board, char color, Search search){
this.board = board;
this.color = color;
this.search = search;
this.ownPieces = new HashMap<String, Piece>();
// 初始化自己的棋子.
for(Piece piece : this.board.pieces.values()){
if(piece.key.startsWith(color + "")){
ownPieces.put(piece.key, piece);
}
}
// 初始化 search.
search.setPlayer(this);
}
public BaseStepNode play(){
BaseStepNode node = search.search();
// 更新棋子状态.
return node;
}
public char getColor(){
return color;
}
public void killPiece(int[] loc) {
Piece newPiece = this.board.getPiece(loc);
if(newPiece != null && newPiece.color == this.color){
this.ownPieces.remove(newPiece.key);
}
}
public void updatePiece(String key, int[] position) {
Piece piece = this.ownPieces.get(key);
// 判断它是否吃子.
Piece eaten = this.board.getPiece(position);
// 判断它是否将军.
boolean isKillBoss = Rules.isKillBoss(key, position, board);
// 更新步长.
this.step += 1;
piece.update(position, eaten != null, isKillBoss, this.step);
}
public Board getBoard(){
return this.board;
}
public int getStep() {
return this.step;
}
}
|
C++
|
UTF-8
| 6,516
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
#include <sstream>
#include <Common/Logger.hpp>
#include <Math/Vec2.hpp>
#include <Render/Renderer.hpp>
namespace jerobins {
namespace render {
Renderer::Renderer() {}
// Load opengl
void Renderer::Init() {
// Initialize OpenGL
if (!gladLoadGL()) {
jerobins::common::Logger::GetLogger()->Log(
"Could not load opengl", jerobins::common::LoggingLevel::Fatal);
exit(-1);
}
// Verify
if (GLVersion.major != 3 || GLVersion.minor != 0) {
std::stringstream ss;
ss << "Expected OpenGL version 4.0, found " << GLVersion.major << "."
<< GLVersion.minor;
throw std::runtime_error(ss.str());
}
// Default background color
CheckGL(glClearColor(0.0f, 0.0f, 0.0f, 0.0f));
// TODO(jerobins): Generated Arrays/Buffers for other components
// Create and bind a VBO for vertices
CheckGL(glGenBuffers(1, &VertexArrayID));
CheckGL(glBindBuffer(GL_ARRAY_BUFFER, VertexArrayID));
// TODO(jerobins): Default for now, determine best practices
CheckGL(glBufferData(GL_ARRAY_BUFFER, 4098, NULL, GL_STATIC_DRAW));
}
void Renderer::Render(std::vector<jerobins::render::IRenderable> objects) {
auto iter = objects.begin();
while (iter != objects.end()) {
Render(*iter);
++iter;
}
}
/*
* Load:
* Vertices
* Color
* Normals
* Textures
*
* 1. Load data
* 2. Enable attribute pointer
* 3. Update sub buffer offset
*
*/
void Renderer::Render(jerobins::render::IRenderable &obj) {
obj.Program().Attach();
CheckOpenGLError();
uint32_t subBufferOffset = 0;
// Vertices
GLsizei elementSize = sizeof(jerobins::math::Vec3<float>);
auto vertices = obj.GetVertices();
auto numVertices = obj.VertexCount() * elementSize;
// Target type, first index, how many (bytes), data
CheckGL(glBindBuffer(GL_ARRAY_BUFFER, VertexArrayID));
CheckGL(glBufferSubData(GL_ARRAY_BUFFER, subBufferOffset, numVertices,
vertices));
// index, sizeof of element, type, normalized, stride, start of data
CheckGL(glEnableVertexAttribArray(0));
CheckGL(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, elementSize,
(uint8_t *)0 + subBufferOffset));
subBufferOffset += elementSize * obj.VertexCount();
// Color
if (obj.ColorCount() == 1) {
glDisableVertexAttribArray(colorAttrPtr);
Color color = obj.GetColors()[0];
glVertexAttrib4f(colorAttrPtr, color.Red, color.Green, color.Blue,
color.Alpha);
CheckOpenGLError();
} else if (obj.ColorCount() == obj.VertexCount()) {
elementSize = sizeof(Color);
// Copy over color
// Target type, first index, how many (bytes), data
glBufferSubData(GL_VERTEX_ARRAY, subBufferOffset,
obj.ColorCount() * elementSize, obj.GetColors());
CheckOpenGLError();
// Enable color attribute
// index, sizeof of element, type, normalized, stride, start of data
CheckGL(glEnableVertexAttribArray(colorAttrPtr));
CheckGL(glVertexAttribPointer(colorAttrPtr, 3, GL_FLOAT, GL_FALSE,
elementSize,
(uint8_t *)0 + subBufferOffset));
subBufferOffset += elementSize * obj.NormalCount();
} else {
// CheckGL(glDisableVertexAttribArray(colorAttrPtr));
CheckGL(glVertexAttrib4f(1, 1, 1, 1, 1));
}
// Normals
if (obj.NormalCount()) {
elementSize = sizeof(jerobins::math::Vec3<float>);
// Copy over normals
// Target type, first index, how many (bytes), data
CheckGL(glBufferSubData(GL_VERTEX_ARRAY, subBufferOffset,
obj.NormalCount() *
sizeof(jerobins::math::Vec3<float>),
obj.GetNormals()));
// Enable normal attribute
// index, sizeof of element, type, normalized, stride, start of data
CheckGL(glEnableVertexAttribArray(normalAttrPtr));
CheckGL(glVertexAttribPointer(normalAttrPtr, 3, GL_FLOAT, GL_FALSE,
sizeof(jerobins::math::Vec3<float>),
(uint8_t *)0 + subBufferOffset));
subBufferOffset +=
sizeof(jerobins::math::Vec3<float>) * obj.NormalCount();
} else {
// CheckGL(glDisableVertexAttribArray(normalAttrPtr));
}
// Textures
if (obj.TextureCount()) {
elementSize = sizeof(jerobins::math::Vec2<int>);
// Copy over textures
// Target type, first index, how many (bytes), data
CheckGL(glBufferSubData(GL_VERTEX_ARRAY, subBufferOffset,
obj.TextureCount() * elementSize,
obj.GetTexureCoords()));
// Enable texture attribute
// index, sizeof of element, type, normalized, stride, start of data
CheckGL(glEnableVertexAttribArray(textureAttrPtr));
CheckGL(glVertexAttribPointer(textureAttrPtr, 3, GL_FLOAT, GL_FALSE,
elementSize,
(uint8_t *)0 + subBufferOffset));
subBufferOffset += elementSize * obj.TextureCount();
} else {
// Check(glDisableVertexAttribArray(textureAttrPtr));
}
if (obj.IndicesCount()) {
CheckGL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
CheckGL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0,
sizeof(int) * obj.IndicesCount(),
obj.GetIndices()));
}
GLuint type = RenderTypeToGLType(obj.Type());
if (type != GL_INVALID_ENUM) {
if (obj.IndicesCount()) {
CheckGL(glDrawElements(type, obj.VertexCount(), GL_UNSIGNED_INT, 0));
} else {
CheckGL(glDrawArrays(type, 0, obj.VertexCount()));
}
}
glBindVertexArray(0);
CheckOpenGLError();
obj.Program().Detach();
CheckOpenGLError();
}
} // namespace render
} // namespace jerobins
|
Markdown
|
UTF-8
| 2,217
| 2.734375
| 3
|
[] |
no_license
|
> npm install --save axios
<br>
> app目录下创建utils目录
<br>
> utils目录下创建githubHelpers.js
<br>
var axios = require('axios');
var id = "YOUR_CLIENT_ID";
var sec = "YOUR_SECRET_ID";
var param = "?client_id=" + id + "&client_secret=" + sec;
function getUserInfo (username) {
return axios.get('https://api.github.com/users/' + username + param);
}
var helpers = {
//players是一个有关用户名的数组
getPlayersInfo: function (players) {
return axios.all(players.map(function (username) {
return getUserInfo(username)
}))
.then(function (info) {
return info.map(function (user) {
return user.data
})
})
.catch(function (err) {console.warn('Error in getPlayersInfo: ', err)})
}
};
module.exports = helpers;
<br>
> app/components/ConfirmBattle.js
<br>
var React = require('react');
function puke (obj) {
return <pre>{JSON.stringify(obj, null, ' ')}</pre>
}
function ConfirmBattle (props) {
return props.isLoading === true
? <p>LOADING</p>
: <div>CONFIRM BATTLE: {puke(props)}</div>
}
module.exports = ConfirmBattle;
<br>
> app/containers/ConfirmBattleContainer.js
<br>
var React = require('react');
var ConfirmBattle = require('../components/ConfirmBattle');
var githubHelpers = require('../utils/githubHelpers');
var ConfirmBattleContainer = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState: function () {
return {
isLoading: true,
playersInfo: [],
}
},
componentDidMount: function () {
var query = this.props.location.query;
githubHelpers.getPlayersInfo([query.playerOne, query.playerTwo])
.then(function (players) {
this.setState({
isLoading: false,
playersInfo: [players[0], players[1]]
})
}.bind(this))
},
render: function () {
return (
<ConfirmBattle
isLoading={this.state.isLoading}
playersInfo={this.state.playersInfo} />
)
}
});
module.exports = ConfirmBattleContainer;
<br>
> localhost:8080
<br>
可以输入如下参赛选手:
tylermcginnis
jake
|
PHP
|
UTF-8
| 1,628
| 2.796875
| 3
|
[] |
no_license
|
<?php
class single_page_css_Public {
/**
* The ID of this plugin.
*
* @since 1.0.0
* @access private
* @var string $plugin_name The ID of this plugin.
*/
private $plugin_name;
/**
* The version of this plugin.
*
* @since 1.0.0
* @access private
* @var string $version The current version of this plugin.
*/
private $version;
/**
* Initialize the class and set its properties.
*
* @since 1.0.0
* @param string $plugin_name The name of the plugin.
* @param string $version The version of this plugin.
*/
public function __construct( $plugin_name, $version ) {
$this->plugin_name = $plugin_name;
$this->version = $version;
}
/**
* Register the stylesheets for the public-facing side of the site.
*
* @since 1.0.0
*/
public function enqueue_styles() {
wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/single-page-css-public.css', array(), $this->version, 'all' );
}
/**
* Register the JavaScript for the public-facing side of the site.
*
* @since 1.0.0
*/
public function enqueue_scripts() {
wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/single-page-css-public.js', array( 'jquery' ), $this->version, false );
}
public function get_metabox_meta() {
$css_field_content = get_post_meta( get_the_ID(), '_single_page_css_content', true );
// Check if set
if ( ! empty( $css_field_content ) ) {
echo '<!-- Single Page Css --><style type="text/css">' . $css_field_content . '</style><!-- End Single Page Css -->';
}
}
}
|
Python
|
UTF-8
| 1,050
| 4.125
| 4
|
[] |
no_license
|
# Affine cipher:
def encrypt():
k1=int(input("enter key1"))
k2=int(input("enter key2"))
pt=input("enter plain text")
ct=""
for i in range(len(pt)):
x=pt[i]
y=ord(x)-ord("a")
z=(y*k1+k2)%26
ct+=chr(z+ord("a"))
print(ct)
def modulo_multiplicative_inverse(A):
"""
Returns multiplicative modulo inverse of A under M, if exists
Returns -1 if doesn't exist
"""
# This will iterate from 0 to M-1
for i in range(0, 26):
if (A*i) % 26 == 1:
return i
return -1
def decrypt():
k1=int(input("enter key1"))
k2=int(input("enter key2"))
ct=input("enter cipher text")
key=modulo_multiplicative_inverse(k1)
pt=""
for i in range(len(ct)):
x=ct[i]
y=ord(x)-ord("a")
z=(y-k2)*key%26
pt+=chr(z+ord("a"))
print(pt)
print("AFFINE CIPHER press 1. Encryption and 2. Decryption")
r=int(input("enter your choice"))
if(r==1):
encrypt()
elif(r==2):
decrypt()
else:
print("Invalid choice")
|
Markdown
|
UTF-8
| 5,454
| 3.421875
| 3
|
[
"MIT"
] |
permissive
|
## Playtest
Playtest is a card game printer. It takes card specification as input and prints pages of numbered and versioned cards in the correct quantities so they can be play tested. It can also export a zip file of PNGs that can be added as a deck in [GameCrafter](https://www.thegamecrafter.com/).
### Deck Spec
Card decks are described using a table of information about each card. The first row of the table names each column. Each following row of the table represents a single unique card.
```
type,cost
knave,$1
queen,$3
wizard,$5
```
In the example, column names are `type` and `cost`. Columns of the table can be anything you want, but there are a couple of column names that have special meaning.
* `quantity` specifies the number of that card type that will be in the deck. If the table does not include a `quantity` column, then one card of each type will be included in your deck.
```
type,cost,quantity
knave,$1,5
queen,$2,2
wizard,$5,1
```
In the example, Playtest would print five copies of knave, two copies of queen, and one wizard.
* `layers` specifies which named svg groups should be displayed. If a `layers` column is present, all layers are hidden unless explicitly listed in a given row. Multiple layers should be delimited by the pipe symbol (`|`).
```
type,cost,quantity,layers
knave,$1,5,base
queen,$2,2,base|queen
wizard,$5,1,base
```
In the example, only the layer titled `base` would display for the knave card and wizard card, but the queen card would have `base` and `queen` layers displayed.
### Card Design
Playtest card designs are specified in a single SVG file with multiple layers. The deck specification determines which layer is shown when each card is printed. Text labels in the SVG may also include template values that Playtest will substitute for column values. The template has this format: `{{ column_name }}`.
### User Interface
The latest version of this project is hosted [here](http://playtest.meteor.com).
#### Quirks
* Each unique card is displayed at the top under "Cards". Click on the card to open an in-browser SVG editor. Changes made in this editor must be saved by clicking SVG Edit -> Save Image, or they'll be lost when you click on another card (or reload the page).
* The text box on the bottom on the left labeled "Deck" is the deck specification as described above. Click outside the text box after making changes to save them.
* The text box on the bottom on the right labeled "Design" is the SVG card design. It's for debugging. As with the deck specification, click outside after making changes to save them.
* If you are not logged in, any new games are public and show up in everyone's list. If you're logged in, any new games you create are private and only accessible to you.
### Export to GameCrafter
An especially alpha feature is GameCrafter export. This should, in theory, let you print a physical copy of your game for about $10. I haven't yet printed a game this way but will update this when I do.
- press the "Export as GameCrafter Bridge Deck" button. This will save a zip file containing PNGs of each card. (A couple of alpha pitfalls: 1. card PNGs are named based on the "name" field, or get a number if there's no such field. The name should be filename safe or you might get some odd results. 2. content for cards can't run all the way to the edge of the card area.)
- go to http://thegamecrafter.com
- log in
- click on Make Games -> My Games
- click Create a Custom Game
- click Create Custom Game Cards
- click Bridge Deck
- click Add
- click Edit Cards
- click the folder icon
- under Create a Sub-Folder, enter "My Cards" (or something like that) and press Create
- unzip the file from Play Test
- drag and drop the PNGs into the Drop files
- click Choose This Folder
- click Import "My Cards"
- finish ordering the game in GameCrafter
### TODO
- finish documenting GameCrafter game printing stuff
- print diffs, to save time when tweaking game rules
- automatically show odds of drawing various cards and card combinations
- google docs API integration
### Admin stuff
Back up production database
```
$ meteor mongo --url playtest.meteor.com
$ # within 1 minute, pull username and password from that and put them here:
$ mongodump -h production-db-b1.meteor.io --port 27017 --username client-5ea1628f --password c72bbef2-b251-758d-7376-cbbd398534c3 -d playtest_meteor_com
```
Convert BSON to JSON
```
$ for f in dump/playtest_meteor_com/*.bson; do bsondump "$f" > "$f.json"; done
```
Restore from production database backup.
```
$ meteor mongo --url playtest.meteor.com
$ # again, 1 minute to construct something like following command:
$ mongorestore -u client -h production-db-b2.meteor.io:27017 -d myApp_meteor_com dump/2014_10_21_v2/myApp_meteor_com -p [password from meteor mongo --url]
```
The above mongorestore command doesn't actually work. I get this error. Need to figure out why.
```
ERROR: trying to write to non-master production-db-b2.meteor.io:27017
isMaster info: { setName: "production-b", ismaster: false, secondary: true, hosts: [ "production-db-b2.meteor.io:27017", "production-db-b1.meteor.io:27017", "production-db-b3.meteor.io:27017" ], arbiters: [ "production-dbarb-b2.meteor.io:27017", "production-dbarb-b1.meteor.io:27017" ], primary: "production-db-b1.meteor.io:27017", me: "production-db-b2.meteor.io:27017", maxBsonObjectSize: 16777216, maxMessageSizeBytes: 48000000, localTime: new Date(1412194885641), ok: 1.0 }
```
|
Python
|
UTF-8
| 1,599
| 3.53125
| 4
|
[] |
no_license
|
#! /usr/bin/env/python3
import argparse
import re
import sys
import os
from pathlib import Path
# handle arguments
parser = argparse.ArgumentParser(
description='A tree clone written in python. This program will take a directory path and recursively print all sub folders and files')
parser.add_argument('directory', help='directory to parse', action='store')
parser.add_argument('-a', help='All files are printed, including hidden ones', action='store_true')
parser.add_argument('-d', help='List directories only', action='store_true')
parser.add_argument('-f', help='Prints the full path prefix for each file', action='store_true')
parser.add_argument('-v', '--verbose', help='log more verbosely', action='store_true')
args = parser.parse_args()
directory = Path(args.directory)
# Recursively print files/directories based on options
def printItemsRecursively(path):
for child in path.iterdir():
if child.is_dir():
# Check if object is a hidden directory
if str(child)[0] == '.':
# Check flag to verify we want to print hidden directories and files
if args.a:
print(child.resolve())
printItemsRecursively(child)
else:
print(child.resolve())
printItemsRecursively(child)
# Check if object is a file and if we want to print out files based on flag
elif child.is_file and not args.d:
print(child.resolve())
# Make sure it's a valid directory
if directory.exists():
printItemsRecursively(directory)
|
Rust
|
UTF-8
| 3,511
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
use std::io::prelude::*;
use std::u8;
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Hash)]
pub enum Instr {
Forward(usize),
Backward(usize),
Increment(u8),
Decrement(u8),
Output,
Input,
Jump(isize),
}
pub fn opt(instr: Vec<Instr>) -> Vec<Instr> {
use Instr::*;
let mut stack = Vec::with_capacity(instr.len() / 2);
for i in instr {
match stack.pop() {
Some(x) => {
let n = match (x, i) {
(Forward(a), Forward(b)) => Forward(a.saturating_add(b)),
(Backward(a), Backward(b)) => Backward(a.saturating_add(b)),
(Increment(a), Increment(b)) => Increment(a.wrapping_add(b)),
(Decrement(a), Decrement(b)) => Decrement(a.wrapping_add(b)),
(x, i) => {
stack.push(x);
i
}
};
stack.push(n)
}
None => stack.push(i),
}
}
stack
}
fn compile(source: &str) -> Vec<Instr> {
let mut v = source
.chars()
.filter_map(|ch| match ch {
'>' => Some(Instr::Forward(1)),
'<' => Some(Instr::Backward(1)),
'+' => Some(Instr::Increment(1)),
'-' => Some(Instr::Decrement(1)),
'.' => Some(Instr::Output),
',' => Some(Instr::Input),
'[' => Some(Instr::Jump(1)),
']' => Some(Instr::Jump(-1)),
_ => None,
})
.collect::<Vec<Instr>>();
v = opt(v);
// patch in jumps
let mut stack_fwd = Vec::new();
let mut stack_back = Vec::new();
for (idx, x) in v.iter_mut().enumerate() {
match x {
Instr::Jump(i) if *i > 0 => {
stack_fwd.push(idx);
}
Instr::Jump(i) if *i < 0 => {
let loc = stack_fwd.pop().expect("] before [!");
*i = loc as isize - idx as isize;
stack_back.push((loc, idx as isize));
}
_ => {}
}
}
for (idx, jump) in stack_back {
v[idx] = Instr::Jump(jump - idx as isize);
}
v
}
fn input() -> Option<u8> {
std::io::stdin()
.bytes()
.next()
.and_then(|result| result.ok())
}
fn run(instr: &[Instr]) {
let mut data: Vec<u8> = (0..1000).map(|_| 0).collect::<Vec<_>>();
let mut pc = 0;
let mut ptr = 0;
loop {
match instr.get(pc) {
Some(Instr::Jump(i)) => {
if *i > 0 {
if data[ptr] == 0 {
pc = (pc as isize + *i) as usize;
}
} else {
if data[ptr] != 0 {
pc = (pc as isize + *i) as usize;
}
}
}
Some(Instr::Forward(i)) => ptr += i,
Some(Instr::Backward(i)) => ptr -= i,
Some(Instr::Increment(i)) => data[ptr] = data[ptr].wrapping_add(*i),
Some(Instr::Decrement(i)) => data[ptr] = data[ptr].wrapping_sub(*i),
Some(Instr::Output) => print!("{}", data[ptr] as char),
Some(Instr::Input) => data[ptr] = input().unwrap(),
None => break,
}
pc += 1;
}
}
fn main() {
run(&compile("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."));
std::io::stdout().flush().unwrap();
}
|
C++
|
UTF-8
| 854
| 2.546875
| 3
|
[] |
no_license
|
#ifndef MIN_HEAP_H
#define MIN_HEAP_H
#include <string>
#include <vector>
#include "heap.h"
namespace heap_t {
// string is the target station name, int32_t is current minimun length
// from source_station to target_station
typedef std::pair<std::string, int32_t> distance_to_station_t;
class MinHeap : public Heap {
public:
static MinHeap* CreateHeap(
const std::vector<distance_to_station_t>& pairs);
~MinHeap(void);
public:
virtual void Top(); // final
virtual bool Empty(void); // final
virtual void Push(void); // final
virtual void Pop(void); // final
private:
MinHeap(const std::vector<distance_to_station_t>& pairs);
virtual void Heaplify(void); // final
virtual void Adjust(void); // final
private:
heap_type_t type_;
}; //end of class MinHeap : public Heap
} //end of namespace heap_t
#endif
|
Java
|
UTF-8
| 2,210
| 2.3125
| 2
|
[] |
no_license
|
package com.negocio.impl;
import java.util.List;
import java.util.Queue;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.negocio.dto.LlamadaDto;
import com.negocio.dto.Recepcionresponse;
import com.negocio.dto.Respuesta;
import com.negocio.util.Cantidades;
import com.negocio.util.Estados;
import com.negocio.util.Textos;
/**
* @author HABUR
*El onjetivo de la calse es gestionar Las llamadas desde la bd, para un contactcenter
*/
@Service
public class RecepcionLlamadasBDImpl extends Dispatcher{
private static final Logger LOGGER = Logger.getLogger(RecepcionLlamadasBDImpl.class.getName());
@Autowired private ConsultaLLamadasImpl consultaLLamadasImpl;
/**
* @return Recepcionresponse
* Este metodo gestiona las llamadas a otras implementaciones como consultar
* llamadas y llamar a gestion llamadas para gestionar el contact center desde bd
*/
public Recepcionresponse gestionarLlamadas() {
Recepcionresponse recepcionresponse = new Recepcionresponse();
try {
long init = System.currentTimeMillis();
Queue<LlamadaDto> queue = consultaLLamadasImpl.consultarLlamadas();
recepcionresponse = super.atenderLLamadas(queue);
guardadoLlamadasProcesadas(recepcionresponse);
LOGGER.info(Textos.TIEMPO_PROCESADO.getTexto() + (System.currentTimeMillis() - init) / Cantidades.VALOR_MULTIPLICADOR.getCantidad() + Textos.SEGUNDOS.getTexto());
} catch (Exception e) {
LOGGER.info(e);
Respuesta resp = new Respuesta(Estados.FALLO.getEstado());
resp.setObservacion(e.getMessage());
recepcionresponse.setRespuesta(resp);
}
return recepcionresponse;
}
/**
* @param recepcionresponse
* valida la lista de llamadas procesadas para ser guardas
*/
private void guardadoLlamadasProcesadas(Recepcionresponse recepcionresponse) {
if(recepcionresponse.getListaLLamadas()!=null ){
guardarLlamadasProcesadas(recepcionresponse.getListaLLamadas());
}
}
/**
* @param list
* Guarda la lista de llamadas procesadas
*/
private void guardarLlamadasProcesadas(List<LlamadaDto> list){
consultaLLamadasImpl.guardarLlamadas(list);
}
}
|
C++
|
UTF-8
| 26,280
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
#define URHO3D_ANGELSCRIPT 1 // we want angelscript support
#define URHO3D_LOGGING 1 // we want debug log message support
#include <Urho3D/Urho3DAll.h>
using namespace Urho3D;
/// Fixed-rate object rotation via frame dT
/// Free-Look camera behaviour
/// Custom Debug-Drawing (object local primary axes)
/// HOTLOADING: Load/Save snapshot of scene at any time, including camera view
/// Take screen shots (png file)
/// Custom UI: Save/Load UI Layout (xml file)
/// Refactored - public methods are inherited, all custom methods are private.
///
class MyApp : public Application
{
public:
/// Typical Urho class constructor
MyApp(Context* context):Application(context) { }
/// Configure application prior to App Window creation
void Setup()
{
engineParameters_["FullScreen"]=true;
//engineParameters_["FullScreen"]=false;
//engineParameters_["WindowWidth"]=1280;
//engineParameters_["WindowHeight"]=720;
//engineParameters_["WindowResizable"]=true;
//engine_->DumpResources();
}
/// Custom initialization prior to first frame update
void Start()
{
// We're not using AngelScript just yet...
// context_->RegisterSubsystem(new Script(context_));
/// Register to receive events of interest
SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(MyApp,HandleKeyDown)); // Keypress
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(MyApp,HandleFrameUpdate)); // Frame Update
SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(MyApp,HandlePostRenderUpdate)); // Post-Render Update
SubscribeToEvent(E_UIMOUSECLICK, URHO3D_HANDLER(MyApp,HandleControlClicked)); // User clicked a UI element
/// Perform our custom application setup / initialization
Setup_UI();
Setup_Scene();
URHO3D_LOGINFO("OK! Our application is now ready to rock!");
// Set mouse behaviour:
//GetSubsystem<Input>()->SetMouseMode(MM_RELATIVE);
// GetSubsystem<Input>()->SetMouseVisible(true);
}
private:
/// Set up our 2D GUI
void Setup_UI(){
/// Obtain access to the root element of the UI system
uiRoot_ = GetSubsystem<UI>()->GetRoot();
/// Load XML file containing default UI style sheet
auto* style = GetSubsystem<ResourceCache>()->GetResource<XMLFile>("UI/DefaultStyle.xml");
/// Set the loaded style as default style
uiRoot_->SetDefaultStyle(style);
/// Attempt to load UI Layout from xml file
if(LoadGUIFromXML(myGUILayoutFilePath_))
URHO3D_LOGINFO("Loaded GUI Layout from XML!");
/// If that fails, we'll use code to populate our UI
/// and then we'll dump the UI content to xml file for future reference
else
{
PopulateUI();
SaveGUIToXML(myGUILayoutFilePath_);
URHO3D_LOGINFO("Populated new GUI Layout and saved to XML!");
}
}
/// Set up our 3D Scene
void Setup_Scene(){
/// Create a new Scene, and store the pointer in a "SharedPtr" smartpointer container
/// This arrangement ensures that when our App dies, the Scene will be automatically deleted.
gameScene_ = new Scene(context_);
/// We'll give our new scene a name, just because we can
gameScene_->SetName(mySceneFilePath_);
/// Attempt to load scene content from xml file
if(LoadSceneFromXML(mySceneFilePath_))
URHO3D_LOGINFO("Loaded GameScene from XML!");
/// If that fails, we'll use code to populate our scene
/// and then we'll dump the scene content to xml file for future reference
else{
PopulateGameScene();
SaveSceneToXML(mySceneFilePath_);
URHO3D_LOGINFO("Populated new GameScene and saved to XML!");
}
}
/// Save gameScene to XML file
bool SaveSceneToXML(String filepath){
bool success=false;
// Dump our Scene to disk, so we can use it to load from in future
Urho3D::File file(context_, filepath, FILE_WRITE);
if(file.IsOpen()){
success = gameScene_->SaveXML(file);
file.Close();
}
return success;
}
/// Load gameScene from XML file
bool LoadSceneFromXML(String filepath){
bool success = false;
/// Open a SceneFile for Loading
Urho3D::File file(context_, filepath, FILE_READ);
if(file.IsOpen())
{
success = gameScene_->LoadXML(file);
if(success)
OnSceneReloaded();
file.Close();
}
return success;
}
/// Save UI content to XML file
bool SaveGUIToXML(String filepath){
bool success=false;
// Dump our Scene to disk, so we can use it to load from in future
Urho3D::File file(context_, filepath, FILE_WRITE);
if(file.IsOpen()){
success = GetSubsystem<UI>()->SaveLayout(file,uiRoot_);
file.Close();
}
return success;
}
/// Load UI content from XML file
bool LoadGUIFromXML(String filepath){
bool success=false;
/// Reload UI from xml file
File file(context_);
file.Open(filepath);
if(file.IsOpen()){
SharedPtr<UIElement> newRoot = GetSubsystem<UI>()->LoadLayout(file);
if(newRoot!=nullptr){
/// Attach resulting UI element to the root of the UI system
uiRoot_->AddChild(newRoot);
success=true;
OnGUIReloaded();
}
file.Close();
}
return success;
//SharedPtr<UIElement> newRoot = GetSubsystem<UI>()->LoadLayout(GetSubsystem<ResourceCache>()->GetResource<XMLFile>("UI/UILoadExample.xml"));
}
/// Restore any UI-dependent object pointers...
/// After loading GUI from xml file, we need to fix up our weak pointers
/// and set up our event subscription based on the new values
void OnGUIReloaded(){
/// Restore object pointers / Hook up our UI events after UI reload
window_= uiRoot_->GetChild("Window",true)->Cast<Window>();
auto* slider = uiRoot_->GetChild("Slider",true);
auto* buttonClose = uiRoot_->GetChild("CloseButton",true);
SubscribeToEvent(slider, E_SLIDERCHANGED,URHO3D_HANDLER(MyApp, HandleSliderChanged));
SubscribeToEvent(buttonClose, E_RELEASED, URHO3D_HANDLER(MyApp, HandleClosePressed));
}
/// Restore any scene-dependent object pointers...
/// When the new scene is loaded, the old scene is destroyed!
/// gameScene_ now points to a different scene object.
/// Some of our object pointers have become invalid.
/// Also, the viewport has been trashed.
/// In order to remedy the situation, we will query the new scene!
void OnSceneReloaded(){
/// Locate our camera node in the reloaded scene
cameraNode_ = gameScene_->GetChild("Camera Node");
/// If the scene does not contain a camera node (!!?!) then create it now.
if(!cameraNode_)
cameraNode_ = gameScene_->CreateChild("Camera Node");
/// Extract initial pitch and yaw values from camera's current orientation
Vector3 eulers = cameraNode_->GetWorldRotation().EulerAngles();
yaw_ = eulers.y_;
pitch_ = eulers.x_;
/// Access our camera component
auto* camera = cameraNode_->GetOrCreateComponent<Camera>();
/// Restore our viewport
WeakPtr<Viewport> viewport (new Viewport(context_, gameScene_, camera));
GetSubsystem<Renderer>()->SetViewport(0, viewport);
/// Restore DebugRenderer
debugDraw_ = gameScene_->GetOrCreateComponent<DebugRenderer>();
}
/// Implements "free-look" camera behaviour
/// Use WASD to move the camera, and mouse to look around.
void MoveCamera(float timeStep){
/// Sanity Check!
if(!cameraNode_)
return;
auto* input = GetSubsystem<Input>();
/// If system cursor is visible, or app window loses input focus, just get outta here
if(input->IsMouseVisible() || !input->HasFocus())
return;
// Do not move if the UI has a focused element (the console)
auto* ui = GetSubsystem<UI>();
if (ui->GetFocusElement())
return;
/// Movement speed (world units per second)
const float MOVE_SPEED = 18.0f;
/// Mouse sensitivity (degrees per pixel, scaled to match display resolution)
const float MOUSE_SENSITIVITY = 0.1f * (768.0f / GetSubsystem<Graphics>()->GetHeight());
/// Convert mouse movement into change in camera pitch and yaw
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
/// We clamp the pitch to +/- 90 degrees so the camera can't flip upside down
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
/// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));
/// Watch the WASD Keys - notice we're not using the KeyDown event to do so.
/// Translation will be performed in "Local Space" - so relative to current camera orientation.
if (input->GetKeyDown(KEY_W))
cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_S))
cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_A))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep);
if (input->GetKeyDown(KEY_D))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep);
}
/// Populate a (presumably) empty scene
void PopulateGameScene(){
/// The first component our new scene needs is an Octree.
/// This component allows Urho to perform visibility based culling
/// which helps improve rendering performance in more complex scenes
/// Since this component does not require a Transform, we'll attach it
/// directly to the scene root (whose transform is always Identity).
gameScene_->CreateComponent<Octree>();
/// Add a debug drawer
debugDraw_ = gameScene_->CreateComponent<DebugRenderer>();
/// Next we'll create a Camera for rendering a 3D scene ...
/// The camera will require a node to provide rotation and translation.
/// We'll create a new Node as a child of our scene
/// and we'll store it in a "WeakPtr" smartpointer object.
/// The reason we use WeakPtr, and not SharedPtr, is because
/// the Node was not created with "new" - its lifetime is already
/// being managed by the scene.
/// WeakPtr won't "keep the object alive", but should the object die,
/// the weakptr will hold "null", which alerts us that the pointer has become invalid.
cameraNode_ = gameScene_->CreateChild("Camera Node");
cameraNode_->Translate(Vector3(20,20,-20)); /// Move camera back, and way up
cameraNode_->LookAt(Vector3::ZERO, Vector3::UP); /// Make camera look down and forward at the World Origin
/// We'll create the Camera component itself as a child of our "Camera Node"
/// The node provides us with a "transform" to position and rotate the camera,
/// while the camera component contains the camera-specific code and data.
Camera* camera = cameraNode_->CreateComponent<Camera>();
/// We'll set the camera's far clip plane to something reasonable for our scene
/// This effectively sets the limit for the max. viewing distance that the camera can "see"
camera->SetFarClip(100.0f);
/// Create and Setup a Viewport - effectively associating a camera with the scene it will render
/// We need WeakPtr here to safely hand over ownership of this special object to Urho
/// Even though we used "new", we don't own this object - this is an exception to the rule!
WeakPtr<Viewport> viewport (new Viewport(context_, gameScene_, camera));
/// Hand (ownership of) the viewport to the Rendering system
GetSubsystem<Renderer>()->SetViewport(0, viewport);
/// Extract the initial pitch and yaw values from the current camera orientation
/// We won't implement camera roll behavior
Vector3 eulers = cameraNode_->GetWorldRotation().EulerAngles();
yaw_ = eulers.y_;
pitch_ = eulers.x_;
/// That's the camera creation taken care of...
/// Next we'll add a "Zone" component.
/// This component provides ambient light and fog.
/// Without a Zone, and with no other sources of light, our scene will remain totally black...
/// Our scene objects don't need to be children of the zone to fall within its volume...
Node* zoneNode = gameScene_->CreateChild("My Zone");
auto* zone = zoneNode->CreateComponent<Zone>();
/// Set Ambient Light (RGB) to soft white, almost black
zone->SetAmbientColor(Color(0.25f, 0.25f, 0.25f));
/// Set up Fog
zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));
zone->SetFogStart(80.0f);
zone->SetFogEnd(100.0f);
/// Provide the extents (or size) of the Zone BoundingBox
zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
/// Create "the floor" using a StaticModel component with its own transform node
/// We'll use "Scale" to stretch a "unit cube" model to form the floor.
/// First we create our node, and may as well set up its transform
Node* floorNode = gameScene_->CreateChild("Floor");
//floorNode->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
floorNode->SetScale(Vector3(100.0f, 1.0f, 100.0f));
/// Then we attach our component to the node
auto* object = floorNode->CreateComponent<StaticModel>();
/// We'll manually set up a Model and Material for this simple entity
/// Urho provides some assets we can play with while getting started...
auto* cache = GetSubsystem<ResourceCache>();
object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
object->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
Node* boxNode = gameScene_->CreateChild("Box1");
boxNode->SetPosition(Vector3(0.0f, 1.0f, 0.0f));
object = boxNode->CreateComponent<StaticModel>();
object->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
object->SetMaterial(cache->GetResource<Material>("Materials/MyFirstMaterial.xml"));
}
/// Populate a custom user interface via hardcode
void PopulateUI(){
/// Note about ownership of UI elements...
/// We create them with "new", but we hand over ownership via AddChild
/// This method effectively passes ownership, and responsibility for deletion, to Urho
/// so we don't need to worry about deleting attached UI elements.
// Create a GUI Window and add it to the UI's root node
window_ = new Window(context_);
uiRoot_->AddChild(window_);
// Set Window size and layout settings
window_->SetMinWidth(384);
window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6));
window_->SetAlignment(HA_CENTER, VA_CENTER);
window_->SetName("Window");
// Create Window 'titlebar' container
auto* titleBar = new UIElement(context_);
titleBar->SetMinSize(0, 24);
titleBar->SetVerticalAlignment(VA_TOP);
titleBar->SetLayoutMode(LM_HORIZONTAL);
// Create the Window title Text
auto* windowTitle = new Text(context_);
windowTitle->SetName("WindowTitle");
windowTitle->SetText("Hello GUI! Press TAB to enable/disable cursor!");
// Create the Window's close button
auto* buttonClose = new Button(context_);
buttonClose->SetName("CloseButton");
// Add the controls to the title bar
titleBar->AddChild(windowTitle);
titleBar->AddChild(buttonClose);
// Add the title bar to the Window
window_->AddChild(titleBar);
// Apply styles
window_ ->SetStyleAuto();
windowTitle->SetStyleAuto();
buttonClose->SetStyle("CloseButton");
/// Subscribe to buttonClose release (following a 'press') events
/// NOTE!!!
/// This is a request to receive "FROM A SPECIFIC SENDER" (buttonClose) "A SPECIFIC EVENT" (E_RELEASED)
SubscribeToEvent(buttonClose, E_RELEASED, URHO3D_HANDLER(MyApp, HandleClosePressed));
/// Subscribe also to all UI mouse clicks just to see where we have clicked
/// NOTE!!!
/// This is a request to receive "FROM ANY SENDER" a specific event...
SubscribeToEvent( E_UIMOUSECLICK, URHO3D_HANDLER(MyApp, HandleControlClicked));
/// Populate our UI Window:
// Create a CheckBox
auto* checkBox = new CheckBox(context_);
checkBox->SetName("CheckBox");
// Create a Button
auto* button = new Button(context_);
button->SetName("Button");
button->SetMinHeight(24);
// Create a LineEdit
auto* lineEdit = new LineEdit(context_);
lineEdit->SetName("LineEdit");
lineEdit->SetMinHeight(24);
auto* slider=new Slider(context_);
slider->SetName("Slider");
slider->SetMinHeight(24);
slider->SetRange(100.0f);
SubscribeToEvent(slider, E_SLIDERCHANGED, URHO3D_HANDLER(MyApp, HandleSliderChanged));
// Add controls to Window
window_->AddChild(checkBox);
window_->AddChild(button);
window_->AddChild(lineEdit);
window_->AddChild(slider);
/// Individual UI elements can use different stylesheets!
/// Here we're telling them all to use the default style we set previously.
checkBox->SetStyleAuto();
button->SetStyleAuto();
lineEdit->SetStyleAuto();
slider->SetStyleAuto();
}
/// Frame Update event handler is used to perform per-frame logic
/// All Urho events use "VariantMap" to pass any relevant data along with the event.
/// The data sent is different for every Urho event.
/// VariantMap is an alias for "Map<StringHash, Variant>"
/// Variant is an Urho value container that can hold almost any kind of value or object.
/// These will likely become more familiar in time, but know they are Urho classes.
void HandleFrameUpdate(StringHash eventType, VariantMap& eventData){
/// Let's unpack the event data for E_UPDATE (frame update)
/// The only event data for this event is "frame delta-time", as a float
using namespace Update;
float deltaTime = eventData[P_TIMESTEP].GetFloat();
/// Update our camera behaviour
MoveCamera(deltaTime);
/// Let's say we wanted "the box" to rotate at 30 degrees per second, around the World Up Axis
/// At this rate, it will take 12 seconds to complete one revolution (360 / 30 = 12)
/// We'll use a Quaternion to represent rotation, and we'll use "angle and axis" to construct it.
Quaternion myRot(30.0f * deltaTime, Vector3::UP);
/// Now we apply our rotation to the Node, optionally we provide the desired Transform Space (world, not local).
gameScene_->GetChild("Box1")->Rotate( myRot, TS_WORLD);
}
/// A keyboard press was detected..
/// This "event handler" will be triggered to respond to that particular event.
//
void HandleKeyDown(StringHash eventType, VariantMap& eventData){
using namespace KeyDown;
int key = eventData[P_KEY].GetInt();
if (key == KEY_ESCAPE) // Escape key to quit application
engine_->Exit();
else if(key==KEY_TAB) // toggle mouse cursor visibility
{
auto* input = GetSubsystem<Input>();
input->SetMouseVisible(!input->IsMouseVisible());
}
// TAKE SCREEN SHOT
else if(key==KEY_BACKSPACE)
{
// Create temporary Urho3D::Image object to receive screenshot
Image screenshot(context_);
// Take screen shot
GetSubsystem<Graphics>()->TakeScreenShot(screenshot);
// Save image to file
screenshot.SavePNG("ScreenShot.png");
}
// LOAD SCENE FROM XML FILE
else if(key==KEY_F11)
LoadSceneFromXML(mySceneFilePath_);
// SAVE SCENE TO XML FILE
else if(key==KEY_F12)
SaveSceneToXML(mySceneFilePath_);
}
/// When scene rendering is "complete", we can perform custom debug-drawing
/// In our case, we'll draw some RGB coloured lines to help visualize orientation...
/// Red is the X axis, or Right.
/// Green is the Y axis, or Up.
/// Blue is the Z axis, or Forwards.
void HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData){
/// Obtain access to our "box node"
Node* boxnode = gameScene_->GetChild("Box1");
/// Query the position of the origin of our box, in worldspace terms
/// This will be the starting point for drawing three coloured lines
/// intended to visually describe the orientation of our test object
Vector3 boxPos = boxnode->GetWorldPosition();
/// DebugRenderer generally wants coordinates in worldspace
/// We'll transform the major axes from local space to world space, and make them a bit longer than 1
/// Now we can see which way our object is "facing" - which is usually very important for games!
/// Color is RGBA floats from 0 to 1 - A is Alpha Transparency - Alpha of 1 is Opaque
/// The bool argument means "Use Depth-Testing" to hide debugdraw content when its "behind" other surfaces.
debugDraw_->AddLine(boxPos, boxnode->LocalToWorld(Vector3::RIGHT * 3.0f), Color(1, 0, 0, 1), true); /// X Axis
debugDraw_->AddLine(boxPos, boxnode->LocalToWorld(Vector3::UP * 3.0f), Color(0, 1, 0, 1), true); /// Y Axis
debugDraw_->AddLine(boxPos, boxnode->LocalToWorld(Vector3::FORWARD * 3.0f), Color(0, 0, 1, 1), true); /// Z Axis
}
/// User has clicked a "ui window close button"
void HandleClosePressed(StringHash eventType, VariantMap& eventData){
if (GetPlatform() != "Web")
engine_->Exit();
}
/// User has clicked a "ui window close button"
void HandleSliderChanged(StringHash eventType, VariantMap& eventData){
using namespace SliderChanged;
auto* clicked = static_cast<UIElement*>(eventData[P_ELEMENT].GetPtr());
float value = eventData[P_VALUE].GetFloat();
URHO3D_LOGINFO(String(value));
}
/// User has clicked a "ui element" (of any kind)
void HandleControlClicked(StringHash eventType, VariantMap& eventData){
/// Get control that was clicked
using namespace UIMouseClick;
auto* clicked = static_cast<UIElement*>(eventData[P_ELEMENT].GetPtr());
/// Access the Text element acting as the Window's title
/// This code performs a static-cast to the given type.
/// The boolean "true" indicates that the search should be recursive.
auto* windowTitle = window_->GetChildStaticCast<Text>("WindowTitle", true);
/// Set window title to reflect the name of the clicked ui element
String name = "...?";
if (clicked) name = clicked->GetName();
windowTitle->SetText("Hello " + name + "!");
}
///!/////////////////////////////////////////////////////////////////////////////////////////////////////
///! Generally, I like to put all the data members together, either at the top or bottom of the class ///
///!/////////////////////////////////////////////////////////////////////////////////////////////////////
/// The default filepath for loading/saving scene content
String mySceneFilePath_ = "MyGameScene.xml";
/// The default filepath for loading/saving UI content
String myGUILayoutFilePath_ = "MyGUI.xml";
/// Our scene object - we used "new" - we very much own it, so we use a SharedPtr to hold it
/// This object will live until our MyApp object is about to be destroyed
/// at which point SharedPtr will delete it.
/// Note: loading scene from file will cause the scene to be deleted and replaced.
SharedPtr<Scene> gameScene_;
/// We introduce the notion of "custom" debug drawing
/// We'll need a DebugRenderer component in our Scene somewhere...
/// All component lifetime is tied to that of the owner Scene
/// which means again, we're responsible for restoring this guy after a scene reload.
WeakPtr<DebugRenderer> debugDraw_;
/// Our camera control node, used to rotate and translate our camera
/// We don't own nodes or components, scenes do...
/// Since "its not ours", we store it in a WeakPtr
/// Why not just store it in a naked Node* ???
/// Because if the node was for any reason destroyed "somewhere else", we'd never know,
/// and the next time we tried to access the pointer, we'd crash badly.
/// At least with a weak pointer, you will end up landing in a "null pointer exception"
/// which is a massive clue that your weakptr became invalidated...
/// WeakPtr lets you at least check before you try to use a bad pointer
/// eg "if (cameraNode_ != nullptr) doStuff();"
/// If the scene is reloaded, its up to us to restore this pointer from the new scene!
WeakPtr<Node> cameraNode_;
/// Our camera pitch and yaw angles are two of the three "Euler" angles (pitch, yaw, roll)
/// They describe our camera node's current orientation, in degrees
float yaw_, pitch_;
/// The UI system's root UIElement
WeakPtr<UIElement> uiRoot_;
/// UI Window
WeakPtr<Window> window_;
};
URHO3D_DEFINE_APPLICATION_MAIN(MyApp)
|
C#
|
UTF-8
| 2,780
| 3.390625
| 3
|
[] |
no_license
|
using System;
using System.IO;
using System.Net;
namespace SkinAndCapeStealer
{
internal class Program
{
static void Main(string[] args)
{
if (!Directory.Exists(@"Result")) Directory.CreateDirectory(@"Result");
Console.WriteLine("[!] Choice\n1 - Optifine Cape Stealer\n2- Skin Stealer");
int i = int.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine("Username: ");
string username = Console.ReadLine();
switch (i)
{
case 1:
OptifineCape(username);
break;
case 2:
Skin(username);
break;
}
}
public static void OptifineCape(string username)
{
string saveLocation = $@"Result\{username}_Cape.png";
byte[] imageBytes;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create($"http://s.optifine.net/capes/"+username+".png");
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream ))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
public static void Skin(string username)
{
string saveLocation = $@"Result\{username}_Skin.png";
byte[] imageBytes;
HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create($"https://minotar.net/skin/"+username);
WebResponse imageResponse = imageRequest.GetResponse();
Stream responseStream = imageResponse.GetResponseStream();
using (BinaryReader br = new BinaryReader(responseStream ))
{
imageBytes = br.ReadBytes(500000);
br.Close();
}
responseStream.Close();
imageResponse.Close();
FileStream fs = new FileStream(saveLocation, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(imageBytes);
}
finally
{
fs.Close();
bw.Close();
}
}
}
}
|
C#
|
UTF-8
| 1,175
| 2.859375
| 3
|
[] |
no_license
|
using UnityEngine;
using UnityEngine.UI;
public class Hud : MonoBehaviour
{
[SerializeField] private Text _infoPlayer1, _infoPlayer2;
private readonly string [] _templatesText = {"Time for Player1", "Time for Player2", "Your turn", "Defence!", "Abandon defense"};
private static Hud _instance;
public static Hud Instance
{
get { return _instance; }
set { _instance = value; }
}
private void Awake()
{
_instance = this;
}
private void YourTurn(bool firstPlayer)
{
var temp = firstPlayer ? _infoPlayer1 : _infoPlayer2;
temp.text = _templatesText[2];
}
public void TimeForPlayer(bool firstPlayer)
{
if (firstPlayer)
{
_infoPlayer2.text = _templatesText[0];
YourTurn(true);
}
else
{
_infoPlayer1.text = _templatesText[1];
YourTurn(false);
}
}
public void Defence()
{
_infoPlayer1.text = _infoPlayer2.text = _templatesText[3];
}
public void AbandonDefence()
{
_infoPlayer1.text = _infoPlayer2.text = _templatesText[4];
}
}
|
Python
|
UTF-8
| 463
| 4.5625
| 5
|
[] |
no_license
|
# Basic if statement
number = 3 # Will print the statements indented in the if statement
# number = -5 # Will not print the statements indented in the if statement
if number > 0: # Condition
print("The number is positive") # Instruction to execute when condition is True
print("Number is", number) # Not indented therefore will always be executed.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.