language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C# | UTF-8 | 1,290 | 2.75 | 3 | [
"Apache-2.0"
] | permissive | namespace Carter.App.MetaData.Extra
{
using Carter.OpenApi;
/// <summary>
/// Helper to avoid repetition while documenting.
/// </summary>
public class MetaDataExtra
{
/// <summary>
/// Gets documentation for the ?bson query string option.
/// </summary>
/// <returns>
/// Documentation.
/// </returns>
public static QueryStringParameter GetBsonDocumentation()
{
return new QueryStringParameter
{
Name = "bson",
Description = "When true, encode the responce in BSON format.",
Type = typeof(bool),
};
}
/// <summary>
/// Gets documentation for the ?ugly query string option.
/// </summary>
/// <returns>
/// Documentation.
/// </returns>
public static QueryStringParameter GetUglyDocumentation()
{
return new QueryStringParameter
{
Name = "ugly",
Description = "When true, strip whitespace from the JSON responce. "
+ "Uses less resources. "
+ "Nothing happens with ?bson=true.",
Type = typeof(bool),
};
}
}
} |
Python | UTF-8 | 842 | 3.140625 | 3 | [] | no_license | class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
m=len(word1)
n=len(word2)
dp=[[0 for i in range(n+1)]for j in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i ==0:
dp[i][j]=j
elif j==0:
dp[i][j]=i
elif word1[i-1]==word2[j-1]:
dp[i][j]=dp[i-1][j-1]
else:
dp[i][j]=1+min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])
return dp[m][n]
word1="horse"
word2="ros"
s=Solution()
print(s.minDistance(word1,word2))
#use dp
#dp[i][j] 表示长度为i的word1和长度为j的word2distance
#word[i-1] 这里 因为长度为3的word最后一位是2 |
Markdown | UTF-8 | 8,631 | 2.75 | 3 | [
"MIT"
] | permissive | ---
title: 'Using SNS And SQS As Target For AWS Lambda Dead Letter Queue'
date: '2020-08-19'
image: 'Using-SNS-And-SQS-As-Target-For-AWS-Lambda-Dead-Letter-Queue'
tags:
- lambda
- cloudwatch
- sns
- sqs
categories:
- AWS
- Serverless
- Terraform
authors:
- Andrei Maksimov
---
As soon as you’re starting developing microservice applications in the Serverless world, you start accepting the idea, that sometimes your microservices may fail. And it’s OK if it does not affect your application or your customer.
But what if your Lambda function does something very important and it becomes critical to know if the function execution failed. For such cases, you may start actively looking for a solutions to monitor your Lambda functions.
There’re several ways you can do it:
* **Collecting and analyzing logs** - you can set up CloudWatch Log Metric Filter and Alarm in the response to the world “Error” or “Exception” occurrence during some time.
* **Collecting and analyzing monitoring metrics** - AWS provides us with a very comprehensive list of [Lambda invocation, performance, and concurrency metrics](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-metrics.html), which you may put to CloudWatch Dashboard. You may set up CloudWatch Alarms on them as well.
Lambda Dead Letter Queue (DLQ) is a special feature, which was [released](https://aws.amazon.com/about-aws/whats-new/2016/12/aws-lambda-supports-dead-letter-queues/) on Dec 1, 2016. This feature allows you to collect information about asynchronous invocation events, which your Lambda failed to process.
Currently, you have 2 options to process is the information:
* SQS.
* SNS.
{{< my-picture name="Dead Letter Queue Options" >}}
## SQS as Dead Letter Queue.
Using SQS as a Lambda DLQ allows you to have a durable store for failed events that can be monitored and picked up for resolution at your convenience. You can process information about Lambda failure events in bulk, have a defined wait period before re-triggering the original event, or you may do something else instead.
Here’s how it works:
{{< my-picture name="Using SQS And SNS For Lambda Dead Letter Queues-SQS" max_width="50%" >}}
* Lambda receives any information from AWS service from the service itself or Eventbridge.
* Lambda attempts to do something meaningful in response to the event, but fails.
* Incoming event information (JSON document) is sent it DLQ if it is configured.
* CloudWatch Alarm may be configured and triggered if the number of messages in SQS is greater than a certain limit.
### SQS Pros.
* Bulk processing - you may collect error messages in the queue and process them in a bulk later.
* Guaranteed delivery - messages deleted from the queue only when they are processed by some other process or after 14 days by timeout.
### SQS Cons.
* Not event-driven - messages must be pulled from the queue.
## SNS as Dead Letter Queue.
SNS or Simple Notification Service from the other side is a key part of any event-driven architecture in AWS. It allows you to process its events almost instantaneously and fan them out to multiple subscribers.
You can use an SNS Topic as a Lambda Dead Letter Queue. This allows you to instantly take action on the failure. For example, you can attempt to re-process the event, alert an individual or a process, or store the event message in SQS for later follow up. And you can do all those things at the same time in parallel.
Here’s how it works:
{{< my-picture name="Using SQS And SNS For Lambda Dead Letter Queues-SNS" >}}
* Lambda receives any information from AWS service from the service itself or Eventbridge.
* Lambda attempts to do something meaningful in response to the event, but fails.
* Incoming event information (JSON document) is sent it DLQ if it is configured.
* SNS immediately sends the incoming message to multiple destinations.
The advantage of using SNS is its ability to send messages to multiple subscribers almost instantaneously in parallel.
### SNS Pros.
* Event-driven: SNS will take action instantly upon receiving a message.
* Fan-out: SNS allows multiple actions to be taken by different subscribers at the same time in parallel.
### SNS Cons.
* SNS is non-durable storage - it will delete received event in 1 hour if it was not processed by any reason.
### Terraform implementation.
Here’s Terraform implementation of using SNS as Lambda DLQ. Complete source code including scripts and Lambda function is available at [our GitHub](https://github.com/hands-on-cloud/hands-on.cloud/tree/master/hugo/content/Using%20SNS%20And%20SQS%20As%20Target%20For%20AWS%20Lambda%20Dead%20Letter%20Queue/src) repository:
```tf
variable "region" {
default = "us-east-1"
description = "AWS Region to deploy to"
}
variable "app_env" {
default = "failure_detection_example"
description = "AWS Region to deploy to"
}
variable "sns_subscription_email_address_list" {
type = string
description = "List of email addresses as string(space separated)"
}
data "aws_caller_identity" "current" {}
data "archive_file" "lambda_zip" {
source_dir = "${path.module}/lambda/"
output_path = "${path.module}/lambda.zip"
type = "zip"
}
provider "aws" {
region = "${var.region}"
}
resource "aws_iam_policy" "lambda_policy" {
name = "${var.app_env}-lambda-policy"
description = "${var.app_env}-lambda-policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"sns:Publish"
],
"Effect": "Allow",
"Resource": "${aws_sns_topic.dlq.arn}"
},
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
EOF
}
resource "aws_iam_role" "iam_for_terraform_lambda" {
name = "${var.app_env}-lambda-role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow"
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "terraform_lambda_iam_policy_basic_execution" {
role = "${aws_iam_role.iam_for_terraform_lambda.id}"
policy_arn = "${aws_iam_policy.lambda_policy.arn}"
}
resource "aws_lambda_function" "error_function" {
filename = "lambda.zip"
source_code_hash = data.archive_file.lambda_zip.output_base64sha256
function_name = "${var.app_env}-lambda"
role = "${aws_iam_role.iam_for_terraform_lambda.arn}"
handler = "index.handler"
runtime = "python3.6"
dead_letter_config {
target_arn = aws_sns_topic.dlq.arn
}
}
resource "aws_sns_topic" "dlq" {
name = "${var.app_env}-errors-sns"
provisioner "local-exec" {
command = "sh sns_subscription.sh"
environment = {
sns_arn = self.arn
sns_emails = var.sns_subscription_email_address_list
}
}
}
resource "aws_cloudwatch_log_group" "lambda_loggroup" {
name = "/aws/lambda/${aws_lambda_function.error_function.function_name}"
retention_in_days = 14
}
```
This Terraform configuration deploys errored Lambda function, which returns an error during every execution. Lambda function has permissions to send messages to SNS topic and log its errors to CloudWatch.
You may use the following code block to add CloudWatch Metric Filter and Alarm to the Lambda function logs as well:
```tf
resource "aws_cloudwatch_log_metric_filter" "lambda_exceptions" {
name = "${var.app_env}_lambda_exceptions"
pattern = "\"Exception\""
log_group_name = "${aws_cloudwatch_log_group.lambda_loggroup.name}"
metric_transformation {
name = "${var.app_env}_lambda_exceptions"
namespace = "MyCustomMetrics"
value = 1
}
}
resource "aws_cloudwatch_metric_alarm" "lambda_exceptions" {
alarm_name = "${var.app_env}_lambda_exceptions"
comparison_operator = "GreaterThanOrEqualToThreshold"
evaluation_periods = "1"
metric_name = "${var.app_env}_lambda_exceptions"
namespace = "MyCustomMetrics"
period = "10"
statistic = "Average"
threshold = "1"
alarm_description = "This metric monitors Lambda logs for 'Exception' keyword"
insufficient_data_actions = []
alarm_actions = [aws_sns_topic.dlq.arn]
}
```
## Resume.
In this article, we covered differences in the usage of SNS and SQS as targets for your Lambda functions.
We hope, that this article was helpful. If yes, please, help us spread it to the world!
If you have any questions, which are not covered by this blog, please, feel free to reach us out. We’re willing to help.
|
JavaScript | UTF-8 | 1,694 | 2.9375 | 3 | [] | no_license | function take_val(val) {
var last_sym = document.getElementById('field').value.slice(-1);
var oper = ['+','-','*','/'];
if(oper.indexOf(val)!=-1 && oper.indexOf(last_sym)!=-1){ //замена последнего оператора
back()
}
if(!(
((last_sym=='' || last_sym=='.') && (oper.indexOf(val)!=-1 ||val=='.' ))|| //оператор или точка после точки или в начале выражения
(val=='.' && (oper.indexOf(last_sym)!=-1 || last_sym=='.')) || //точка после . или {+,-,*,/}
((val=='.' && last_num_contain_point()) //точка есть в последнем числе
)))
{
document.getElementById('field').value = document.getElementById('field').value + val;
}
}
function equal() {
var v = document.getElementById('field').value;
document.getElementById('field').value = eval(v).toFixed(5);
}
function clean() {
document.getElementById('field').value = "";
}
function back() {
var v = document.getElementById('field').value;
document.getElementById('field').value = v.substring(0,v.length-1);
}
function last_num_contain_point()
{
var str = document.getElementById('field').value;
var last_sym = str.slice(-1);
if(['+','-','*','/','.',''].indexOf(last_sym)==-1)
{
while(['+','-','*','/',''].indexOf(last_sym)==-1)
{
str=str.substring(0,str.length-1);
last_sym = str.slice(-1);
console.log(str);
if(last_sym=='.')
{
return true;
}
}
}
return false;
}
|
Java | UTF-8 | 356 | 2.984375 | 3 | [] | no_license | package 제18차시;
public class TruckMain {
public static void main(String[] args) {
Truck myTruck = new Truck();
myTruck.carName = "프론티어";
myTruck.ton = 3;
System.out.println("나의 트럭은 " + myTruck.color + "이다.");
System.out.println(myTruck.carName + "는 " + myTruck.ton + "톤을 실을 수 있다.");
}
}
|
Shell | UTF-8 | 186 | 2.828125 | 3 | [] | no_license | #!/bin/bash
CUR_DIR=$(cd "$(dirname "$0")"; pwd)
echo ${CUR_DIR}
print_in_purple "\n Git\n ------------------------------\n"
git config --global include.path ${CUR_DIR}/.gitconfig
|
Markdown | UTF-8 | 10,826 | 3.09375 | 3 | [] | no_license | # King County Housing
## Executive Summary
This report provides an analysis and evaluation of the current and prospective housing market in King County, Washington. Methods include data and feature analysis, feature engineering, and linear/polynomial regression analysis. Other calculations involve model assessment and cross validation. All calculations can be found in the associated notebooks. Results of data analyzed produce applicable models in evaluating the sale price of a house in King County based on its identifying factors.
The resulting models can be compounded in order to gain a menial understanding as to what an acceptable or expected selling price for a house could be based on its location and features. A more accurate model with a smaller margin of error would require further investigation but this analysis provides a template based on the available dataset.
Recommendations discussed include:
Most and least expensive areas to purchase a home in King County
10 most cost-related zip codes
The report also investigates the fact that the analysis conducted has limitations. Some of the limitations include:
- Monetary figures are not nominalized, giving extra weight to more recent films.
- Projections derived from regression analysis bare statistical shortcomings that inhibit suggestions from providing use outside their given ranges.
- Further analysis could utilize additional resources in order to identify additional content development strategies.
## Technologies
This project was created using the following languages and libraries. An environment with the correct versions of the following libraries will allow re-production and improvement on this project.
- Python version: 3.6.9
- Matplotlib version: 3.0.3
- Seaborn version: 0.9.0
- Pandas version: 0.24.2
- Numpy version: 1.16.2
- Statsmodels 0.9.0
-Scikit Learn 0.4.0
# ETL - Blind Regression
This project begins with the provided dataset that encapsulates sales of houses in King County, Washington between 2014 and 2015. The dataset contains 21,597 unique non-null values in the largest variable and missing values in the `waterfront` and `yr_renovated` category. There are no duplicate rows but we find duplicate `id` values that represent houses that were sold at different times. After an initial investigation into these houses with multiple sells, they are included in the dataset as unique values that can contribute information to the business case.
A quick search finds that the provided dataset is incomplete while the original provided by Kaggle has full values of the missing columns. Merging these two tables on the duplicate `id` and `date` values makes the decision of what to do with Nan values very easy. Once the table is full, we are able to adjust the datatypes and remove irrelevant values.
To build a foundation of this project, we’ll take this cleaned dataset and plug it into a model against the sale price to see what kind of relationship we’re dealing with. Though the assumptions of linearity is not met by this model, an adjusted R-squared value of 0.696 and mostly statistically significant P-values gives us hope that we’ll be able to explain sales price through regression analysis.
 - BASELINE MODEL GRAPH
## EDA and Model-1 -
This model began with the import of our cleaned data and a quick look at values within the table. After looking at the descriptive values we plotted histograms for each variable :

Looking at this list we can see that we have a `date` variable so we go ahead and engineer some initial variables by converting the datatype to datetime and creating a `month`, `age`, and `day_of_year` variable. We also go ahead and create a `reno_age` variable based on the age of the last renovation.
### Categorical Variables
Visualizations help understand the data in some of the categorical variables `Bedrooms, Floors, Bathrooms / Bedrooms:

Doesn't look like there's a strong linear relationship here but maybe some of them are related with oneanother - can you say 3d visualizations?

Interesting but a little unnecessary at this point as we will want to asses these relationships later in multicolinear relationships within our model. Let's look at other categoricals for relationship with price before we decide to dummy them out:

Based on this cursory look we’ll want to convert `['floors','waterfront','yr_renovated','sqft_basement']` to more binary variables that we’ll call `['multiple_stories','on_water','renovated','has_basement']`.
### Continuous Variables
Just by filtering values we filter continuous variables into `['id', 'date', 'price', 'sqft_living', 'sqft_lot', 'sqft_above', 'yr_built', 'lat', 'long', 'sqft_living15', 'sqft_lot15', 'age']` then plot histograms again:

These don’t look good so we clean them up with a logarithmic transformation and drop the originals:

### Multicollinearity Check
From the following matrix we determine that many of the variable s involving sqft show high multicollinearity so we decide to drop them and engineer some new features

## Feature Engineering and Model Assessment
To utilize some of the features hidden within our current data set we use the months of the year to create `spring` and `summer` variables. Similarly we split each zipcode value into its own dummy variable. Since this initially widened the dataset too much, we ran a quick regression model and plucked those zipcodes with the highest positive coefficients to include in this model. Our top ten that are currently included are:
`['zip_98039', 'zip_98004', 'zip_98112', 'zip_98040', 'zip_98102', 'zip_98199', 'zip_98109', 'zip_98105', 'zip_98119', 'zip_98115',]`
Once we build out a proper model we find an ### Adjusted R-Squared of .710 #### and all P-Values below Alpha. The residuals for this model however reveal some pretty discomforting errors from this model - making it unviable for the moment.

## Model-2 -Logarithmic Transformation of the Target
This approach to building a model will look deeper at each variable before incorporating it into a model and make new attempts at more accurate feature engineering. The priority for this model is to mitigate RMSE and fulfill the assumptions of linearity.
[Notebook Associated with this Section](https://github.com/ElliotEvins/king-county-housing-analysis/blob/master/Notebooks/3_model_2_log_target.ipynb)
We begin with the data and collection of variables from the last model and decide which factors to remove from the model moving forward. `id` and `date` useful to keep as an index but we don’t need it in our model. Similarly, though we’re transforming the target variable to train this model, we’ll need to keep `price` in the data set to verify our predictions. `[‘day_of_year’,’lat’,’long’,’zipcode’]` are all redundant in our model so we drop them as well.

With this change we have a slight bump in R-Squared value and much more normalized residuals.

From there we can engineer a new feature to see if we can strengthen the model. Looking at the distribution of sales with an overlap of price indicated by hue:

A closer look at the priciest houses show that they are above a latitude of 47.5 Degrees and East of -122.2. With this distribution we can divide the area into 4 sections and introduce each section as a categorical variable in the next model. This model gives us an R-Squared value of 0.823 with immaculate P-Values. Running the same model against the testing data provides near identical output furthering the validity.

Further engineering is possible from here by utilizing outside data sources that can reflect larger macroeconomic sentiments that usually influence the housing market. The Bureau of Labor and Statistics CSI could help provide this model with an explanation of the business cycle or recessions that can influence prices.
## Model-3 - Polynomial Regression
This approach to building a model will once again incorporate the deeper at look into each variable before incorporating it into a model. We will attempt to apply higher-order relationships and build a polynomial regression. We begin by building a simplified version of our last model by taking out the location oriented variables. Though this knocks down the statistical significance of the model, it will allow us to run higher order models without destroying our computers.
Moving from higher features to lower ones we test at each level and find that 2 features yields the most relevant model in this case. After splitting the training and testing data we find that the model is valid though not quite as strong as our previously engineered linear regression model. A further avenue of exploration woud be to approach our previously engineered variables based on location and apply higher order regression through this 2 feature approach.

# Recommendations
Whether as a real-estate professional, homeowner, or hopeful homeowner - consult these three approaches to assess an estimated selling price of a home in King County.
If seeking value for the house then stay away from the top 10 zipcodes identified in this study, which come with a premium.
The negative coefficient on renovations tells us that expensive makeovers might add as much value to the price of a home as they may cost
Similarly multiple stories and basements are not as significant as most other factors like sqft living space, condition, or even the season in which the home is on the market!
# Conclusion
This broadly scoped analysis yielded actionable insights and opportunities for further investigation. The findings herein will help narrow the field of possibility in the real estate transaction process and increase the chances of sustainability and success in some of the largest purchases individuals will ever make. While the preceding investigations are based on significant bodies of data, the deliverables and conclusions reached are intended to act as guidelines and a starting point for future investigations. Multiple avenues of further exploration have been presented over the course of this investigation and we have aimed to clearly identify our thinking for each step of the research process. Moving forward our models, findings, and approaches - presented here as deliverables - should be revisited with updated data and compared with realized future sales.
|
C# | UTF-8 | 780 | 2.984375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace NA.Framework.Core.Tools
{
public class ImageHelper
{
/// <summary>
/// 获取图片的base64编码
/// </summary>
/// <param name="imgPath"></param>
/// <returns></returns>
public static string ConvertImg2Base64(string imgPath)
{
if (imgPath == null)
throw new ArgumentNullException(nameof(imgPath));
if (!File.Exists(imgPath))
throw new FileNotFoundException("指定图片不存在", imgPath);
byte[] bytes = File.ReadAllBytes(imgPath);
string base64Str = Convert.ToBase64String(bytes);
return base64Str;
}
}
}
|
Shell | UTF-8 | 356 | 2.984375 | 3 | [] | no_license | #!/usr/bin/env bash
if ibmcloud plugin list | grep -q observe-service; then
echo "The ibmcloud cli observe-service plugin is already installed"
else
sleep $(( (RANDOM % 60) + 10 ))
if ! ibmcloud plugin list | grep -q observe-service; then
echo "Installing the ibmcloud cli observe-service"
ibmcloud plugin install observe-service -f
fi
fi
|
Java | UTF-8 | 2,860 | 3.15625 | 3 | [] | no_license | package com.example.michaelusa.screengods;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* Created by michaelusa on 4/29/17.
*/
class GoogleFinanceAPI {
private double livePrice;
GoogleFinanceAPI(String ticker) {
this.livePrice = parseLiveTickerPrice(ticker);
}
public double getLivePrice() {
return livePrice;
}
/**
* My usual parseJson function with an additional conversion to a ByteArray so that an
* InputStreamReader can be used for the creation of the JsonReader.
*
* @param JsonAsString The raw JSON data passed in as a String to be converted to JsonReader.
*/
private static JsonReader parseJson (String JsonAsString) {
InputStream stream = new ByteArrayInputStream(JsonAsString.getBytes(StandardCharsets.UTF_8));
return new JsonReader(new InputStreamReader(stream));
}
/**
* Basic parser function for the Google Finance API. Need to substring the contents
* first, as it is in a non-standard format that isn't JSON to begin with.
*
* Got some code from the Oracle Javadocs for pulling a string from a URL:
* https://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html
*
* @param ticker stock to parse from Google Finance API
* @return JsonReader (raw JSON data from API)
*/
private static JsonReader getGoogleFinanceAPIData(String ticker) throws IOException {
URL gFinance = new URL(Utilities.GOOG_FINANCE_URL + ticker);
BufferedReader in = new BufferedReader(new InputStreamReader(gFinance.openStream()));
String currentURLLine, outJSONString = "";
while ((currentURLLine = in.readLine()) != null)
outJSONString += currentURLLine;
in.close();
return parseJson(outJSONString.substring(4, outJSONString.length() - 1));
}
/**
* Basic try catch (for IOException) to use GSON to parse the JsonReader object
* into something that can be evaluated as a primitive type.
*
* @param ticker stock to parse from Google Finance API
* @return currentPrice (current price of requested stock ticker)
*/
private static double parseLiveTickerPrice(String ticker) {
Gson gson = new Gson();
double currentPrice = 0;
try {
JsonReader rawJson = getGoogleFinanceAPIData(ticker);
GF_API_Stock stock = gson.fromJson(rawJson, GF_API_Stock.class);
currentPrice = stock.getL_cur();
}catch (IOException e) {
e.getCause();
}
return currentPrice;
}
} |
Markdown | UTF-8 | 2,922 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | kmeans-coreset
======================================================
[](https://travis-ci.org/lpradel/kmeans-coreset)
This is a heuristic C++ implementation of the constant-size coresets algorithm for *k*-means by Feldman, Schmidt and Sohler. The heuristic lies in the initial *k*-means++ sampling and the modified *k*-means++ sampling (*'D²-sampling'*) in the recursive component of the original algorithm. The implementation is based on the following paper of the authors:
**Dan Feldman, Melanie Schmidt, and Christian Sohler. 2013. Turning big data into tiny data: constant-size coresets for k-means, PCA and projective clustering. In Proceedings of the Twenty-Fourth Annual ACM-SIAM Symposium on Discrete Algorithms (SODA '13). Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, 1434-1453.**
## Installation
The installation process of this algorithm relies on the CMake build tool. If you are unfamiliar with CMake, the necessary steps are listed below:
### CMake
- Change into the `build` directory of the project
- Run the command `cmake ..`
- You will find the compiled binaries for Debug and Release in the `build` directory depending on your specific CMake configuration
### Dependencies
The implementation itself has no library dependencies. It does however use the **C++11** standard.
You will have to ensure the presence of a suitable compiler for this (e.g. GCC or Clang).
## Usage
You can execute the algorithm over the command line interface:
```
./kmeans-coreset input k output
```
The arguments are as follows:
- `input`: The file containing your clustering data. Data points are separated by newlines and the dimensions of a data point are delimited by a comma (`,`). See `MATRIX_FILE_DELIMITER` in `Coreset.h`
- `k`: The number of centers and clusters
- `output`: The file to store the resulting coreset. The datapoints are formatted the same as in the `input` file
## Contributing
1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :)
## History
- Version 1.0: Initial release.
## Credits
- [Lukas Pradel](https://github.com/lpradel)
## License
Copyright 2015 Lukas Pradel
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.
|
Java | UTF-8 | 3,421 | 1.796875 | 2 | [
"MIT"
] | permissive | package com.nathaliebize.sphynx.controller;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.nathaliebize.sphynx.repository.UserRepository;
import com.nathaliebize.sphynx.routing.SiteMap;
import com.nathaliebize.sphynx.service.SphynxUserDetailsService;
import com.nathaliebize.sphynx.service.UserService;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HomeControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@MockBean
private SphynxUserDetailsService sphynxUserDetailsService;
@MockBean
private UserService userService;
@MockBean
private UserRepository userRepository;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testShowHomePage() throws Exception {
this.mockMvc.perform( MockMvcRequestBuilders
.get("/")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(view().name(SiteMap.INDEX.getPath()));
}
@Test
public void testShowHomePage_withIndexPath() throws Exception {
this.mockMvc.perform( MockMvcRequestBuilders
.get("/index")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(view().name(SiteMap.INDEX.getPath()));
}
@Test
public void testShowTermsPage() throws Exception {
this.mockMvc.perform( MockMvcRequestBuilders
.get("/terms")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(view().name(SiteMap.TERMS.getPath()));
}
@Test
public void testShowInfoPage() throws Exception {
this.mockMvc.perform( MockMvcRequestBuilders
.get("/info")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(view().name(SiteMap.INFO.getPath()));
}
@Test
public void testIncorrectPath() throws Exception {
this.mockMvc.perform( MockMvcRequestBuilders
.get("/random")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is(404))
.andExpect(unauthenticated());
}
}
|
Java | UTF-8 | 1,065 | 3.25 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.List;
public class Permute {
public List<List<Integer>> generate(int nums[]) {
List<List<Integer>> res = new ArrayList<>();
if (nums.length < 1) {
return res;
}
helper(res, new ArrayList<>(),nums,new boolean[nums.length]);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> cur, int nums[], boolean visited[]) {
if (cur.size() == nums.length) {
res.add(new ArrayList<>(cur));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) {//初始为false
continue;//进行下一次循环
}
cur.add(nums[i]);
visited[i]=true;
helper(res,cur,nums,visited);
cur.remove(cur.size()-1);
visited[i]=false;
}
}
public static void main(String[] args) {
int a[]={1,2,3,4};
Permute test=new Permute();
System.out.println(test.generate(a));
}
}
|
C# | UTF-8 | 7,344 | 2.5625 | 3 | [] | no_license | using Horse_Dev.com.hordev.utilities;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Horse_Dev.com.horsedev.pages
{
class TimeNMaterial
{
IWebDriver driver;
HomePage homePage;
TimeNMaterial timeNMaterial;
public TimeNMaterial(IWebDriver driver)
{
this.driver = driver;
}
internal IWebElement TimenMaterial => driver.FindElement(By.XPath("//a[contains(text(), 'Time & Materials')]"));
internal IWebElement CreateNew => driver.FindElement(By.CssSelector("a[class='btn btn-primary']"));
internal IWebElement PricePerUnit => driver.FindElement(By.CssSelector("input[class=\"k-formatted-value k-input\"]"));
internal IWebElement Code => driver.FindElement(By.Id("Code"));
internal IWebElement Description => driver.FindElement(By.Id("Description"));
internal IWebElement Save => driver.FindElement(By.Id("SaveButton"));
internal IWebElement GoToNext => driver.FindElement(By.CssSelector("a[title='Go to the next page']"));
internal void SetCode(string TMCode)
{
Code.SendKeys(TMCode);
}
internal void SetDescription(string Desc)
{
Description.SendKeys(Desc);
}
internal void SetPricePerUnit(string price)
{
PricePerUnit.SendKeys(price);
}
internal void ClickTimenMaterial()
{
TimenMaterial.Click();
}
internal void ClickOnSave()
{
Save.Click();
}
// Create Time and material record
internal void CreateNewRecord(string code, string desc, string price, string TypeCode)
{
CreateNew.Click();
var dropDown = driver.FindElement(By.XPath("//span[@role=\"listbox\"] //span[@class=\"k-icon k-i-arrow-s\"]"));
dropDown.Click();
//Select the Typecode from the dropdown
List<IWebElement> DropDownList = new List<IWebElement>(driver.FindElements(By.XPath("//ul[contains(@id,'TypeCode_listbox')]//li")));
for (int i = 0; i < DropDownList.Count; i++)
{
if (DropDownList[i].Text == TypeCode)
{
DropDownList[i].Click();
}
}
Code.SendKeys(code);
Description.SendKeys(desc);
PricePerUnit.SendKeys(price);
Save.Click();
}
//Checking the record is existing
internal int ValidateRecord(string code)
{
homePage = new HomePage(driver);
timeNMaterial = new TimeNMaterial(driver);
homePage.ClickOnAdministration();
timeNMaterial.ClickTimenMaterial();
IWebElement VerifyCode = null;
while (true)
{
for (int i = 1; i <= 10; i++)
{
//waiting for the element to be visible
string waitingEle = "//*[@id='tmsGrid']/div[3]/table/tbody/tr[" + i + "]/td[1]";
WaitHelper.ElementVisible(driver, waitingEle, "xpath");
VerifyCode = driver.FindElement(By.XPath(waitingEle));
//check if the code is available in Tome and material
if (VerifyCode.Text == code)
{
Console.WriteLine("Code exists");
return 1;
}
}
//Navigate to next page if 'nextpage' button is enabled
if (timeNMaterial.GoToNext.Enabled)
{
IWebElement GoToNextPage = driver.FindElement(By.XPath("//a[@title='Go to the next page']"));
GoToNextPage.Click();
}
else if(!timeNMaterial.GoToNext.Enabled && VerifyCode.Text!=code)
{
return -1;
}
}
}
//Edit the existing record
internal int EditRecord(string code, string NewCode, string Description, string Price, string TypeCode)
{
homePage.ClickOnAdministration();
timeNMaterial.ClickTimenMaterial();
IWebElement VerifyCode = null;
while (true)
{
for (int i = 1; i <= 10; i++)
{
//waiting for element to be available
string waitingEle = "(\"//*[@id='tmsGrid']/div[3]/table/tbody/tr[" + i + "]/td[1]\")";
WaitHelper.ElementVisible(driver, waitingEle, "xpath");
VerifyCode = driver.FindElement(By.XPath(waitingEle));
if (VerifyCode.Text == code)
{
IWebElement EditBtn = driver.FindElement(By.XPath("(//a[contains(@class,'k-button k-button-icontext k-grid-Edit')])[" + i + "]"));
EditBtn.Click();
timeNMaterial.Code.Clear();
timeNMaterial.SetCode(NewCode);
timeNMaterial.Description.Clear();
timeNMaterial.SetDescription(Description);
timeNMaterial.SetPricePerUnit(Price);
timeNMaterial.ClickOnSave();
return -1;
}
}
if (timeNMaterial.GoToNext.Enabled)
{
IWebElement GoToNextPage = driver.FindElement(By.XPath("//a[@title='Go to the next page']"));
GoToNextPage.Click();
}
else if (!timeNMaterial.GoToNext.Enabled && VerifyCode.Text != code)
{
return -1;
}
}
}
//Deleting the time and material record
internal int DeleteRecord(string code)
{
IWebElement VerifyCode = null;
while (true)
{
for (int i = 1; i <= 10; i++)
{
string waitingEle = "//*[@id='tmsGrid']/div[3]/table/tbody/tr[" + i + "]/td[1]";
WaitHelper.ElementVisible(driver, waitingEle, "xpath");
VerifyCode = driver.FindElement(By.XPath(waitingEle));
if (VerifyCode.Text == code)
{
IWebElement DeleteBtn = driver.FindElement(By.XPath("//*[@id=\"tmsGrid\"]/div[3]/table/tbody/tr[" + i + "]/td[5]/a[2]"));
DeleteBtn.Click();
driver.SwitchTo().Alert().Accept();
return 1;
}
}
if (timeNMaterial.GoToNext.Enabled)
{
IWebElement GoToNextPage = driver.FindElement(By.XPath("//a[@title='Go to the next page']"));
GoToNextPage.Click();
}
else if (!timeNMaterial.GoToNext.Enabled && VerifyCode.Text != code)
{
return -1;
}
}
}
}
} |
Python | UTF-8 | 3,268 | 3.015625 | 3 | [] | no_license | import numpy as np
from sklearn.metrics import precision_recall_fscore_support
def find_max_indices(prediction_results):
"""
Find the max indices in prediction results
:param prediction_results:
:return:
"""
N = prediction_results.shape[0]
indices = np.zeros(N, dtype=int)
# Find max probability in each row
for i in range(0, N):
result = prediction_results[i]
idx = np.argmax(result)
indices[i] = idx
return indices
# Evaluate Multiple Class
def evaluate_mutiple(ground_truth, prediction, find_max=False, f_beta = 1.0, avg_method=None):
"""
:param ground_truth: 1-d array, e.g. gt: [1, 1, 2, 2, 3]
:param prediction: 1-d array, e.g. prediction: [1, 1, 2, 2, 4]
:return: recall, precision, f-value
"""
prediction_indices = prediction
if find_max or len(prediction.shape) == 2:
prediction_indices = find_max_indices(prediction)
# Find Precision & Recall & F-value
precision, recall, f_value, support = None, None, None, None
if len(prediction.shape) == 2:
M = prediction.shape[1]
precision, recall, f_value, support \
= precision_recall_fscore_support(ground_truth,
prediction_indices,
beta=f_beta,
pos_label=M,
average=avg_method)
else:
precision, recall, f_value, support \
= precision_recall_fscore_support(ground_truth,
prediction_indices,
beta=f_beta,
average=avg_method)
return precision, recall, f_value
def find_binary_values(prediction_results, multiple_index, threshold):
"""
Find the item that beyond the threshold
:param prediction_results:
:param multiple_index:
:param threshold:
:return:
"""
N = prediction_results.shape[0]
values = np.zeros(N, dtype=int)
# Find max probability in each row
for i in range(0, N):
result = prediction_results[i]
if result[multiple_index] >= threshold:
values[i] = 1
return values
# Evaluate Binary Class
def evaluate_binary(ground_truth, prediction, multiple_index=None, threshold=None, f_beta=1.0):
"""
:param ground_truth: 1-d array, e.g. gt: [1, 0, 1, 0, 0], 1 is True
:param prediction: 1-d array, e.g. prediction: [0, 0, 1, 0, 0]
if prediction is 2-d array, then multiple_index, threshold should be configured
:return: recall, precision, f-value
"""
prediction_results = prediction
if threshold is not None and multiple_index is not None:
prediction_results = find_binary_values(prediction, multiple_index, threshold)
# Find Precision & Recall & F-value
precision, recall, f_value, support \
= precision_recall_fscore_support(ground_truth,
prediction_results,
average='binary',
beta=f_beta)
return precision, recall, f_value
|
Java | UTF-8 | 1,472 | 2.5 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dyno.swing.designer.beans.painters;
import dyno.swing.designer.beans.HoverPainter;
import dyno.swing.designer.beans.SwingDesigner;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
public class GridLayoutPainter extends GridLayoutAnchorPainter implements HoverPainter {
private Point point;
private Component current;
public GridLayoutPainter(SwingDesigner designer, Container container) {
super(designer, container);
}
public void setHotspot(Point p) {
point = p;
}
public void setComponent(Component component) {
this.current = component;
}
@Override
public void paint(Graphics g) {
super.paint(g);
int x = point.x - designer.getLeftOffset();
int y = point.y - designer.getTopOffset();
int column = grid_layout.getColumns();
int row = grid_layout.getRows();
if (column == 0) {
column = 1;
}
if (row == 0) {
row = 1;
}
double w = (double) hotspot.width / column;
double h = (double) hotspot.height / row;
int ix = (int) (x / w);
int iy = (int) (y / h);
x = (int) (ix * w + hotspot.x);
y = (int) (iy * h + hotspot.y);
drawHotspot(g, x, y, (int) w, (int) h, SELECTION_COLOR);
}
}
|
Swift | UTF-8 | 757 | 2.5625 | 3 | [] | no_license | //
// NewsAbstractViewModel.swift
// News
//
// Created by Harsha M G on 15/06/17.
// Copyright © 2017 Harsha M G. All rights reserved.
//
import UIKit
class NewsAbstractViewModel: NSObject {
var newsSource: NewsSource?
var newsArticles = [NewsArticle]()
func hasArticlesViewModelGotValue(completion: @escaping (Bool) -> ()){
let newsArticlesViewModel = NewsArticlesViewModel()
completion(true)
}
func getUrlForNews() -> String{
return (newsSource?.url)!
}
func getDescription()-> String{
return (newsSource?.discription)!
}
func getSource()-> String{
return (newsSource?.id)!
}
}
|
Python | UTF-8 | 14,384 | 2.5625 | 3 | [] | no_license | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Eml - Wrapper class for email-objects
This Class is supposed to add needed decoding and formating to the email objects.
Furthermore file attachments get hashed.
In the Future these objects are supposed to be items in searchable catalogue.
@author tke
"""
import email
import hashlib
import inspect
import multiprocessing as mp
import os
import re
from functools import lru_cache
import chardet
import magic
from dateutil.parser import parse
from pytz import timezone
def depricated(fn):
def wraper(*args, **kwargs):
print(f'''>{inspect.stack()[1].function} called depricated function {fn.__name__}''')
return fn(*args, **kwargs)
return wraper
class Eml(object):
re_pat_email = r'''(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[
\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[
a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[
0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[
\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) '''
re_pat_ipv4 = r"""((25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})"""
received_p_from_details = r'''\((?P<fqdn>[^\[\] ]+)?\s?(\[(?P<ip>\S+)\])?\s*(\([^\)]+\))?\)\s*(\([^\)]+\))?\s*'''
received_p_from = r'''from (?P<from>\S+)\s*''' + received_p_from_details
received_p_by = r'''\s*by\s+(?P<by>\S+)\s*(\([^\)]+\))?'''
received_p_with = r'''\s*(with\s+(?P<with>.*))?'''
received_p_id = r'''\s*(id\s+(?P<id>\S+))\s*(\([^\)]+\))?'''
received_p_for = r'''\s*(for\s+(?P<for>\S*))?'''
received_p_date = r''';\s*(?P<date>\w+,\s\d+\s\w+\s\d+\s[\d:]+\s[\d+-]+\s\(\w+\)).*\s*(\([^\)]+\))?'''
re_pat_f_received = received_p_from + received_p_by + \
received_p_with + received_p_id + received_p_for + received_p_date
re_pattern = {
'email': re_pat_email,
'ipv4': re_pat_ipv4,
'received': re_pat_f_received
}
def get_header(self, field):
"""Get a decoded list of all values for given header field."""
for v in self.get_header_raw(field):
for value,encoding in email.header.decode_header(v):
if encoding != None and not encoding == 'unknown-8bit':
value=value.decode(encoding)
else:
value=self.__decode(value)
yield ' '.join(value.split())
def get_header_raw(self, field):
"""Get list of all raw values for given header field."""
# msg=self.get_eml()
items = []
for key, value in self.header:
if key.lower() == field.lower():
items.append(value)
return items
@lru_cache(maxsize=2)
def get_eml(self):
"""Get email.email Object for this email."""
if self.data is None:
data=open(self.filename, 'rb').read()
self.data = data
else:
data = self.data
self.md5=hashlib.md5(data).hexdigest()
self.sha256=hashlib.sha256(data).hexdigest()
self.sha1=hashlib.sha1(data).hexdigest()
return email.message_from_bytes(data)
def __get_from_struct(self, fieldname, struct=None):
if struct is None:
struct = self.struct
if fieldname in struct and struct[fieldname] is not None:
yield struct[fieldname]
if "parts" in struct and len(struct["parts"]) > 0:
for child in struct["parts"]:
for hit in self.__get_from_struct(fieldname, child):
yield hit
def __get_sub_struct(self, msg_part,level=0,index=0):
tmp_struct = {}
tmp_struct['content_type'] = msg_part.get_content_type()
tmp_struct['content_disposition'] = msg_part.get_content_disposition()
tmp_struct['level'] = level
tmp_struct['index'] = index
tmp_struct['filename'] = None
tmp_struct['data'] = None
if msg_part.is_multipart():
tmp_struct["parts"] = [self.__get_sub_struct(part,level=level+1,index=index+1+sub_index) for sub_index, part in enumerate(msg_part.get_payload())]
else:
data = msg_part.get_payload(decode=True)
tmp_struct['data'] = data
if msg_part.get_filename():
filename = msg_part.get_param('filename', None, 'content-disposition')
if filename is None:
filename = msg_part.get_param('name', None, 'content-type')
filename=self.__decode(filename.strip())
tmp_struct['filename'] = (filename)
tmp_struct['size'] = len(tmp_struct['data'])
try:
tmp_struct['mime'] = magic.from_buffer(data,mime=True)
tmp_struct['magic'] = magic.from_buffer(data)
except:
pass
tmp_struct["md5"] = hashlib.md5(data).hexdigest()
tmp_struct["sha1"] = hashlib.sha1(data).hexdigest()
tmp_struct["sha256"] = hashlib.sha256(data).hexdigest()
return tmp_struct
@property
def struct(self):
"""Get structure of email as dictionary."""
if self._struct is None:
self._struct = self.__get_sub_struct(self.get_eml())
return self._struct
@property
def flat_struct(self):
"""Get structure of email as array."""
return self.__flatten_struct(self.struct)
def __flatten_struct(self, struct):
x = struct
yield x
if 'parts' in x:
for y in x['parts']:
for element in self.__flatten_struct(y):
yield element
return self._struct
def get_mail_path(self):
"""Get mail delivery path as reconstructed from received fields as list."""
pass
def get_timeline(self):
"""Get all timebased events for the mail as a list."""
pass
def get_date(self, tz='UTC'):
"""Get date of mail converted to timezone. Default is UTC."""
date = [parse(x, fuzzy=True) for x in self.get_header("Date")]
if len(date) > 0:
if not tz is None:
date = [self.__convert_date_tz(d, tz) for d in date]
return date[0] if len(date) == 1 else date
else:
return None
def get_from(self):
"""Get all sender indicating fields of mail as dictionary"""
# from
return self.get_header("from")
# reply-to
# return-path
# received envelope info
pass
def get_to(self):
"""Get all recipient indicating fields of mail as a dictionary"""
pass
def get_subject(self):
"""Get subject line of mail"""
pass
def get_index(self):
"""Get tokenized index of all parsable text. A bit like linux strings."""
pass
def get_hash(self, part='all', hash_type='md5'):
"""
Get hash for selected parts.
part = (all,body,attachments,index) index from get_struct
type = (md5,sha1,sha256)
"""
hashes = []
if part == "all" or part == "attachments":
hashes.extend([x for x in self.__get_from_struct(hash_type)])
return hashes
def get_attachments(self, filename=None):
"""Get list of attachments as list of dictionaries. (filename,mimetype,md5,sha256,rawdata)"""
pass
def get_lang(self):
"""Get a guess about content language."""
pass
def get_iocs(self, ioc_type='all'):
"""Get dictionary of iocs"""
pass
def as_string(self, formatstring):
"""Return string representation of mail based on formatstring."""
pass
def has_attachments(self):
"""Return True if mail has Files Attached."""
return len(self.attachments) > 0
def contains_hash(self, string):
"""Return True if the hash of any part of the Mail equals supplied string"""
if len(string) == 64:
return string.lower() in self.get_hash(hash_type='sha256')
if len(string) == 32:
return string.lower() in self.get_hash()
return False
def contains_string(self, string: str) -> bool:
"""Return True if mail contains string in its text."""
return string.lower() in self.get_index()
def check_spoof(self) -> bool:
'''Perform spoof Check on mail an return result'''
return False
def check_sig(self) -> bool:
'''Perform valide smime if available and return result'''
return False
def check_dkim(self) -> bool:
'''Perform check on dkim signature if available return result'''
return False
def check_header(self) -> bool:
'''Perform consistancy check on header fields result'''
return False
def extract_from_text(self, text, pattern='email'):
pat = re.compile(self.re_pattern["email"], re.IGNORECASE)
match = pat.findall(text)
return match
def __decode(self, string):
'''Decode string as far as possible'''
if isinstance(string, str):
fulltext=""
for (text,encoding) in email.header.decode_header(string):
if hasattr(text,"decode"):
fulltext+=text.decode() if encoding is None else text.decode(encoding)
else:
fulltext+=text
return fulltext
if isinstance(string, bytes):
encodings = ['utf-8-sig', 'utf-16', 'iso-8859-15']
detection = chardet.detect(string)
if "encoding" in detection and len(detection["encoding"]) > 2:
encodings.insert(0,detection["encoding"])
for encoding in encodings:
try:
return string.decode(encoding)
except UnicodeDecodeError:
pass
def __convert_date_tz(self, datetime, tz='UTC'):
return datetime.astimezone(tz=timezone(tz))
def __struct_str(self,struct,pre_indent=0,index=0):
content_disposition = struct['content_disposition'] if struct['content_disposition'] else ''
if 'attachment' in content_disposition:
content_disposition='📎'
output = ''
indent = " " + " " * struct['level']
output += f'{struct["index"]:_<{len(indent)}d}{struct["content_type"]} {content_disposition}\n'
if 'filename' in struct:
output += f'{indent} filename : {struct["filename"]}\n'
if 'size' in struct:
output += f'{indent} size : {struct["size"]}\n'
if 'mime' in struct:
if struct['mime'] != struct['content_type']:
output += f'{indent} !MIME! : {struct["mime"]}\n'
if 'magic' in struct:
if struct['magic'] != struct['content_type']:
output += f'{indent} magic : {struct["magic"][:180]}\n'
if 'md5' in struct:
output += f'{indent} md5 : {struct["md5"]}\n'
if 'sha1' in struct:
output += f'{indent} sha1 : {struct["sha1"]}\n'
if 'sha256' in struct:
output += f'{indent} sha256 : {struct["sha256"]}\n'
if 'parts' in struct and len(struct['parts'])>0:
for x in struct['parts']:
output += self.__struct_str(x,pre_indent=pre_indent)
return output
def __str__(self):
output = f"╦═══>{self.full_filename}<\n"
output +=f"╟╌┄MD5 : {self.md5}\n"
output +=f"╟╌┄SHA1 : {self.sha1}\n"
output +=f"╙╌┄SHA256 : {self.sha256}\n"
if "done" in self.status:
for f in self.froms:
output += f"From : {f}\n"
for t in self.tos:
output += f"To : {t}\n"
output += f"Date : {self.date}\n"
for s in self.subject:
output += f"Subject: {s}\n"
output += f"MAIL-PARTS ⮷ \n{self.__struct_str(self.struct,pre_indent=3)}"
return output
def __init__(self, filename=None , data=None, hash_attachments=True):
self.status = "new"
if filename is None:
if data is None:
raise ValueError()
self.filename = 'unknown'
self.full_filename = 'unknown'
else:
self.filename = filename
self.full_filename = os.path.abspath(filename)
self.data = data
try:
self.header = self.get_eml().items()
self.status = "processing_header"
self.froms = self.get_header("from")
self.tos = self.get_header("To")
self.ccs = self.get_header("CC")
self.subject = self.get_header("Subject")
self.id = self.get_header("Message-ID")
self.date = self.get_date()
self.received = self.get_header("Received")
self.status = "processing_attachments"
self.attachments = []
self._struct = None
self.struct
self.status = "done"
except Exception as e:
print(e)
self.status = "not_parsable" + str(e)
def create_newmail(filename):
return Eml(filename)
def scan_folder(basepath):
list_of_mail = []
base_count = len(basepath.split(os.sep)) - 1
if os.path.isfile(basepath):
e = Eml(basepath)
print(e)
else:
with mp.Pool(processes=mp.cpu_count()) as pool:
for root, dirs, files in os.walk(basepath):
path = root.split(os.sep)
relpath = os.sep.join(root.split(os.sep)[base_count:])
new_mails = pool.map(create_newmail, [root + os.sep + s for s in files])
list_of_mail.extend(new_mails)
pool.close()
pool.join()
return list_of_mail
if __name__ == '__main__':
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('mail',help="Mail you want to analyze")
args=parser.parse_args()
with open(args.mail,'rb') as md:
data=md.read()
#malmail=Eml(args.mail)
malmail=Eml(data=data)
print(malmail)
|
Java | UTF-8 | 967 | 2.453125 | 2 | [
"Apache-2.0"
] | permissive | package io.aops.aspects;
import static org.slf4j.LoggerFactory.getLogger;
import io.aops.annotations.Idempotent;
import io.aops.annotations.Idempotent.IsDuplicateFunction;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
@Aspect
public class IdempotentAspect {
private final static Logger LOG = getLogger(IdempotentAspect.class);
private final IsDuplicateFunction isDuplicateFunction;
public IdempotentAspect(IsDuplicateFunction isDuplicateFunction) {
this.isDuplicateFunction = isDuplicateFunction;
}
@Around(Idempotent.IDEMPOTENT_ANNOTATION)
public Object around(ProceedingJoinPoint point) throws Throwable {
if (isDuplicateFunction.apply(point.getArgs())) {
LOG.info("No need to proceed");
return null;
}
LOG.info("No entries found, proceed");
Object proceed = point.proceed();
return proceed;
}
} |
Java | UTF-8 | 601 | 1.992188 | 2 | [] | no_license | package com.orders.repository;
import java.util.List;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.orders.domain.Order;
import com.orders.domain.Person;
@Repository
public interface OrderRepository extends CrudRepository<Order, Long>{
List<Order> findByPerson(Person person);
List<Order> findByPersonId(Integer personId);
List<Order> findByPerson(Person person, Pageable limit);
PageImpl<Order> findAll(Pageable limit);
} |
Python | UTF-8 | 7,195 | 3.4375 | 3 | [
"MIT"
] | permissive | """ A mouse wiggler for the NeoKey Trinkey.
This has three modes, based on stoplight colours.
1. Red is off, where no mouse wiggling happens.
2. Yellow wiggles the mouse every 1 to 4 minutes at random.
3. Green wiggles the mouse constantly.
You can see the current mode by touching the capacitive
button, and cycle modes with the big button.
"""
import time
import random
import board
import neopixel
import usb_hid
import touchio
from adafruit_hid.mouse import Mouse
from digitalio import DigitalInOut, Pull
# The three stoplight colours. We use these both for setting the
# light colour, and for tracking the mode we're currently in with
# the `current_mode` global.
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
# How many times does the mouse move around when it wiggles.
MOVES_PER_WIGGLE = 5
# How far is the mouse allowed to move when it wiggles.
MAX_WIGGLE_DISTANCE = 15
# Time between wiggles when in yellow mode, in seconds.
MIN_DELAY = 1 * 60
MAX_DELAY = 4 * 60
# The neopixel rgb led.
PIXEL = neopixel.NeoPixel(board.NEOPIXEL, 1)
# The object which lets us behave like a mouse.
MOUSE = Mouse(usb_hid.devices)
def do_nothing():
""" Does nothing. Used as the default action for buttons. """
pass
class Button:
""" A class for treating some input as a button with 4 distinct
state callbacks which are called based on button state changes
every time `tick` is called.
1. `on_press` when the button goes from active to inactive.
2. `on_held` when the button is stayed active.
3. `on_release` when the button goes from active to inactive.
4. `on_rest` when the button stayed inactive.
Users will want to assign these callbacks useful values.
Make sure `tick` isn't called too often, as there's no built-in
switch [debounce][] here.
[debounce]: https://learn.adafruit.com/make-it-switch/debouncing
"""
def __init__(self, input, name):
""" Create a new `Button`.
- `input` should be an object with a `value` which indicates
if the input is actuated.
- `name` is used to identify which button is in what state in
the program's output.
"""
self.input = input
self.name = name
self.previous = None
self.on_press = do_nothing
self.on_held = do_nothing
self.on_release = do_nothing
self.at_rest = do_nothing
def is_active(self):
""" A predicate for if the `input` we're modelling as a button
currently actuated?
"""
return self.input.value
def tick(self):
""" This method should be called in the main loop. It looks
at the `previous` state and if the button `is_active`, and
then calls the correct callbacks.
This will return the result of any callback called.
"""
current = self.is_active()
if current and not self.previous:
print("{} was pressed".format(self.name))
result = self.on_press()
elif current and self.previous:
print("{} is held".format(self.name))
result = self.on_held()
elif not current and self.previous:
print("{} was released".format(self.name))
result = self.on_release()
else:
result = self.at_rest()
# so previous is correctly tracked for next tick
self.previous = current
return result
def next_colour(c):
""" Takes a colour and returns the next stoplight colour, in the
following order: `RED`, `YELLOW`, `GREEN`.
Will return `RED` as the next colour for unrecognized colours.
"""
if c == RED:
return YELLOW
elif c == YELLOW:
return GREEN
else:
return RED
def update_current_colour():
""" Updates the `current_colour` to the `next_colour`. """
global current_colour
current_colour = next_colour(current_colour)
def set_led_to_current_colour():
""" Set the led PIXEL to `current_colour`. """
global current_colour
PIXEL.fill(current_colour)
def wiggle(mouse):
""" Wiggles the `mouse` around.
Makes `MOVES_PER_WIGGLE` moves, going at most `MAX_WIGGLE_DISTANCE`
in either direction horizontally and vertically.
In testing, the wigging was annoying since it would jump the cursor
away from the path I had it on, so there's an extra final move back
towards the original coordinates.
"""
print("wiggle!")
# This code doesn't seem to reliably work, but I can't figure out
# why. It helps make the wiggles stay closer to the same point
# though, so I'm leaving it in.
dx = 0
dy = 0
for _ in range(MOVES_PER_WIGGLE):
x = random.randint(-MAX_WIGGLE_DISTANCE, MAX_WIGGLE_DISTANCE)
y = random.randint(-MAX_WIGGLE_DISTANCE, MAX_WIGGLE_DISTANCE)
dx -= x
dy -= y
mouse.move(x=x, y=y)
# Move the mouse back to the starting position.
mouse.move(x=dx, y=dy)
def schedule_future_wiggle():
""" Picks a new time in the future to wiggle, some time between
(inclusive) `MIN_DELAY` and `MAX_DELAY` seconds from now.
"""
global wiggle_time
delay = random.randint(MIN_DELAY, MAX_DELAY)
wiggle_time = time.monotonic() + delay
def make_button():
""" Make a `Button` to model the MX switch and set up our
callbacks for lighting up the LED and cycling `current_colour`.
"""
pin = DigitalInOut(board.SWITCH)
pin.switch_to_input(pull=Pull.DOWN)
button = Button(pin, "button")
button.on_press = update_current_colour
button.on_release = schedule_future_wiggle
button.on_held = set_led_to_current_colour
return button
def make_touch():
""" Make a `Button` to model the touch sensor and set up the
callback for showing `current_colour` on the LED.
"""
touch = Button(touchio.TouchIn(board.TOUCH), "touch")
touch.on_held = set_led_to_current_colour
return touch
def after(scheduled_time, action=None, *args, **kwargs):
""" Returns `True` if the current time is after the `scheduled_time`.
These arguments are in seconds.
If an `action` is given, it will be called (with any extra arguments)
if it's passed the `scheduled_time` as well.
"""
current_time = time.monotonic()
if current_time >= scheduled_time:
action(*args, **kwargs)
return True
else:
return False
button = make_button()
touch = make_touch()
current_colour = RED
wiggle_time = time.monotonic()
while True:
button.tick()
touch.tick()
if current_colour == GREEN:
wiggle(MOUSE)
elif current_colour == YELLOW:
if after(wiggle_time, wiggle, MOUSE):
schedule_future_wiggle()
else:
wait = wiggle_time - time.monotonic()
print("next wiggle in {} seconds".format(wait))
else:
# We don't do any wiggling if we're RED.
pass
# Make sure the light is turned off if nothing is pressed.
if not button.is_active() and not touch.is_active():
PIXEL.fill(0)
# We need to sleep a bit to debounce the switches.
time.sleep(1.0/60.0)
|
C# | UTF-8 | 2,692 | 3.125 | 3 | [] | no_license | using System;
using System.Globalization;
namespace Donut.Parsing
{
public class DateParser
{
public bool TryParse(string value, out DateTime timeValue, out double? doubleValue)
{
double doubleValueTmp;
if (Double.TryParse(value, out doubleValueTmp))
{
doubleValue = doubleValueTmp;
timeValue = DateTime.MinValue;
return false;
}
doubleValue = null;
var pvd = CultureInfo.InvariantCulture;
if (DateTime.TryParse(value, pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd-MM-yy", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd/MM/yyyy H:mm:ss", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd/MM/yyyy H:mm", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd/MM/yy H:mm:ss", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd/MM/yy H:mm", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd-MM-yyyy H:mm:ss", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd-MM-yy H:mm:ss", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd-MM-yy H:mm", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd-MM-yy HH:mm:ss", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else if (DateTime.TryParseExact(value, "dd-MM-yy HH:mm", pvd, DateTimeStyles.AssumeUniversal, out timeValue))
{
return true;
}
else
{
timeValue = DateTime.MinValue;
}
return false;
}
}
} |
Swift | UTF-8 | 2,199 | 2.921875 | 3 | [
"MIT"
] | permissive | //
// ViewController.swift
// SelfSizingTable
//
// Created by Lukasz Pikor on 10.03.2016.
// Copyright © 2016 Lukasz Pikor. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let data = ["First", "Second", "Third", "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. THE END", "Bla, bla, bla bla \n \n \n \n END :) "]
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
/// If constraints in TableViewCell are configured correclty that's all you need to set.
/// When configuring constraints think of width as input, height: output you want to determine.
tableview.rowHeight = UITableViewAutomaticDimension
tableview.estimatedRowHeight = 200
}
}
private typealias TableViewDataSource = ViewController
extension TableViewDataSource: UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Self Sizing Cell", forIndexPath: indexPath) as! SelfSizingTableViewCell
let hue = CGFloat(drand48())
let saturation = CGFloat(drand48())
let brightness = CGFloat(drand48())
let randomColor = UIColor.init(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
cell.contentView.backgroundColor = randomColor
cell.viewData = SelfSizingTableViewCell.ViewData(title: data[indexPath.row])
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
}
|
Java | UTF-8 | 1,052 | 2.390625 | 2 | [] | no_license | package com.nesaak.packetapi;
import org.bukkit.Bukkit;
public class Reflection {
private static final String VER = Bukkit.getVersion().getClass().getPackage().getName().split("\\.")[3];
public static final Class CraftPlayer = getCraftBukkitClass("entity.CraftPlayer");
public static final Class EntityPlayer = getNMSClass("EntityPlayer");
public static final Class PlayerConnection = getNMSClass("PlayerConnection");
public static final Class NetworkManager = getNMSClass("NetworkManager");
public static Class<?> getNMSClass(String name) {
try {
return Class.forName("net.minecraft.server." + VER + "." + name);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static Class<?> getCraftBukkitClass(String name) {
try {
return Class.forName("org.bukkit.craftbukkit." + VER + "." + name);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
|
Markdown | UTF-8 | 3,681 | 3.28125 | 3 | [] | no_license | # 条件测试误差或期望测试误差?
| 原文 | [The Elements of Statistical Learning](../book/The Elements of Statistical Learning.pdf) |
| ---- | ---------------------------------------- |
| 翻译 | szcf-weiya |
| 时间 | 2017-02-20:2017-02-20 |
图7.14和7.15验证了交叉验证是否能很好地估计$Err_{\cal T}$的问题,其中$Err_{\cal T}$表示在给定训练集$\cal T$上的误差(228页的式(7.15)),它与期望预测误差相对。对于从图7.3的右上图的“回归问题/(最优子集)线性拟合”的设定中产生的100个训练集中的每一个训练集,图7.14显示了条件误差$Err_{\cal T}$作为子集大小的函数图象(左上图)。接下来两张图显示了10折交叉验证和N折交叉验证,后者也称作舍一法(LOO)。每张图的红色粗线表示期望误差Err,而黑色粗线表示期望交叉验证。右下图则显示了交叉验证近似条件误差和期望误差的程度。
可能会认为N折交叉验证能很好地近似$Err_{\cal T}$,因为它几乎用了整个训练样本来拟合新的测试点。另一方面,可能会期望10折交叉验证会很好地估计Err,因为它平均了不同的训练集。从图中看到估计$Err_{\cal T}$时10折交叉验证比N折做得更好,而且估计时$Err$更好。确实如此,两条黑色曲线与红色曲线的相似性表明两个CV曲线对Err近似无偏,且10折有更小的方差。类似的趋势由Efron(1983)给出。

> 图7.14. 从图7.3的右上图得到的100个模拟值的条件预测误差$Err_{\cal T}$,10折交叉验证,以及舍一交叉验证的曲线。红色粗线为期望预测误差$Err$,而黑色粗线为期望CV曲线$E_{\cal T}CV_{10}$和$E_{\cal T}CV_N$。右下图显示了CV曲线与条件误差的绝对偏差的期望$E_{\cal T}\vert CV_k-Err_{\cal T}\vert$,$K=10$(蓝色)以及$K=N$(绿色),并且也显示了CV曲线与期望误差之间绝对偏差的期望$E_{\cal T}\vert CV_{10}-Err\vert$(橘黄色)。
图7.15显示了100次模拟中,10折交叉验证和N折交叉验证对误差的估计关于真是条件误差的散点图。尽管散点图没有表明太多的相关性,但右下图表明对于大部分来说是呈负相关的,之前已经观察到的神奇现象。这种负相关解释了为什么任意形式的CV都能很好地估计$Err_{\cal T}$。每张图的虚线是在$Err(p)$处画的,$Err(p)$是对于最优子集大小$p$时的期望误差。我们再一次看到两种形式的CV对于期望误差是近似无偏的,但是对于不同训练集的测试误差的方差是相当不同的。
在7.3的四种实验条件下,“回归/线性”条件表现出实际测试误差与预测测试误差最高的相关性。这个现象也发生在自助法估计误差时,而且我们会猜测,对任意其他的条件预测误差的估计都成立。
我们得出结论,仅仅给出从与训练集相同的数据,一般情况下得到特定训练集的测试误差的估计不是很容易的。相反地,交叉验证和相关的方法可能可以对期望误差Err给出合理的估计。

> 图7.15. 对100个训练集的每个CV估计误差关于真实条件误差的图象,模拟的设定与图7.3的右上图相同。前三张图对应不同的子集大小$p$,且水平直线和垂直直线是在$Err(p)$处画的。尽管看起来这些图象没有多大的关联,但是我们从右下图看到大部分是负相关的。
!!! notes "weiya 注"
真实条件误差如何给出?
|
Go | UTF-8 | 993 | 4.1875 | 4 | [
"MIT"
] | permissive | package main
import "fmt"
type Human struct {
name string
age int
}
func (h Human) Say() {
fmt.Printf("I can say, I am %s, %d years old\n", h.name, h.age)
}
func (h Human) Run() {
fmt.Printf("%s is running\n", h.name)
}
type Singer struct {
Human
collecton string
}
func (s Singer) Sing() {
fmt.Printf("%s can sing %s\n", s.name, s.collecton)
}
type Student struct {
Human
lesson string
}
func (s Student) Learn() {
fmt.Printf("%s nee learn %s\n", s.name, s.lesson)
}
// interface
type Men interface {
Say()
Run()
}
func main() {
tom := Singer{
Human: Human{"Tom", 22},
collecton: "learn golang",
}
peter := Student{
Human: Human{"Perter", 18},
lesson: "learn php",
}
jerrk := Human{"jerrk", 26}
var men Men
// men 存 tom
men = tom
men.Say()
men.Run()
men = peter
men.Say()
men.Run()
men = jerrk
men.Say()
men.Run()
x := make([]Men, 3)
x[0], x[1], x[2] = tom, peter, jerrk
for _, value := range x {
value.Say()
value.Run()
}
}
|
C++ | UTF-8 | 3,147 | 2.671875 | 3 | [] | no_license | #include "lecture_fichiers.h"
lecture_fichiers::lecture_fichiers()
{
}
double** lecture_fichiers::allocation_m(QString titre, int* nb_passage,int *num_passage,char *cas,int *numTransition, QString *dateTime,bool caseTab[])
{
FILE *g;
char lecture_v[300];
int taille=0,k=0,plateau=0;
char date[12],heure[13];
errno_t err = fopen_s(&g, titre.toStdString().c_str(), "r+");
if (err)
printf_s("The file fscanf.out was not opened \n");
double** data= (double**)calloc(4,sizeof(double*));
k=0;
int validate=-1;
while ( fgets(lecture_v,300,g) && ( validate != (*num_passage + 1) ) ) {
sscanf(lecture_v,"%s %s %d %d %c %d\n",date,heure,&plateau,&taille,cas,numTransition);
*dateTime=QString("").append(date).append(" ").append(heure).append(" "+QString::number(plateau));
if ( k == *num_passage && caseTab[0] && caseTab[1] ){
validate = *num_passage;
}
else if ( caseTab[0] && !caseTab[1] && *cas == 's' ) {
validate += 1;
}
else if ( caseTab[1] && !caseTab[0] && *cas == 'c' ) {
validate += 1;
}
if ( validate == *num_passage ) {
data[0] = (double*)calloc(taille,sizeof(double));
data[1] = (double*)calloc(taille,sizeof(double));
data[2] = (double*)calloc(taille,sizeof(double));
data[3] = (double*)calloc(taille,sizeof(double));
*nb_passage = -1;
validate += 1;
}
else {
k++;
}
}
if ( validate != (*num_passage + 1) ) {
validate = -1;
*num_passage = -1;
}
else {
*num_passage = k;
}
*nb_passage = validate + 1;
fclose(g);
return data;
}
int lecture_fichiers::lire_fichier(QString titre, double*** data, int* nb_valeur, int* nb_passage, char* cas, int *numTransition, int num_passage,QString *dateTime, bool caseTab[2])
{
FILE *f;
int k = 0, sortie = 0,incr=0,num_R_passage=num_passage;
char lecture[30];
QString chemin_ref="";
int res = 0;
chemin_ref.append(titre);
if ( chemin_ref == chemin_ref.replace("Manchot","reference") ) {
chemin_ref.replace("plateau","reference");
}
(*data)=allocation_m(chemin_ref,nb_passage,&num_R_passage,cas,numTransition,dateTime,caseTab);
errno_t err = fopen_s(&f,titre.toStdString().c_str(), "r+");
if (err) {
printf_s("The file fscanf.out was not opened\n");
res = 1;
}
k = 0;
incr = 0;
while ( fgets(lecture, 30, f) && !sortie && (num_R_passage != -1) ) {
if ( strcmp(lecture, "fin\n") == 0 ) {
incr++;
}
else if ( incr == num_R_passage ) {
sscanf(lecture,"%lf %lf %lf\n",&(*data)[0][k],&(*data)[1][k],&(*data)[2][k]);
(*data)[3][k] = (*data)[0][k] + (*data)[1][k] + (*data)[2][k];
k++;
}
else if (incr > num_R_passage ){
sortie = 1;
}
}
*nb_valeur = k;
chemin_ref.clear();
if ( num_passage > num_R_passage ) {
res = 2;
}
fclose(f);
return res;
}
|
Ruby | UTF-8 | 3,120 | 3.703125 | 4 | [] | no_license | #!/usr/bin/env ruby
class Page
@@count = 0
attr_reader :id
attr_accessor :keywords
def initialize()
@id = @@count + 1
@keywords = Hash.new
@@count += 1
end
end
class Query
@@count = 0
attr_reader :id
attr_accessor :keywords
def initialize()
@id = @@count + 1
@keywords = Hash.new
@@count += 1
end
end
class PageStrength
attr_reader :pageid
attr_accessor :strength
def initialize(id, strength)
@pageid = id
@strength = strength
end
end
class SearchRanking
# pages, to contain all page object
# queries, to contain all query objects
@@pages = []
@@queries = []
def parse
# parses the standard input (file in this case)
# and builds array of Page and Query objects
begin
file = File.new("input", "r")
while (line = file.gets)
if line.start_with?('P')
keywords = line.split()
# create Page object
page = Page.new()
keywords.delete(keywords[0])
keyword_index_pair = keywords.zip((0...8))
keyword_index_pair.each do |keyword, index|
page.keywords[keyword.downcase] = 8-index
end
@@pages.push(page)
elsif line.start_with?('Q')
keywords = line.split()
# create Query object
query = Query.new()
keywords.delete(keywords[0])
keyword_index_pair = keywords.zip((0...8))
keyword_index_pair.each do |keyword, index|
query.keywords[keyword.downcase] = 8 - index
end
@@queries.push(query)
end
end
file.close
rescue => err
puts "Exception: #{err}"
err
end
end
def rank_pages
# calculates the strength of each page against each query and
# displays the ranking of pages based on decreasing order of strength
@@queries.each do |query|
page_strengths = []
@@pages.each do |page|
strength = 0
query.keywords.each_key do |qkey|
if page.keywords.has_key?(qkey)
strength = strength + query.keywords[qkey]*page.keywords[qkey]
end
end
pstrength = PageStrength.new(page.id, strength)
page_strengths.push(pstrength)
end
# ranking pages: sorting in descending order based on strength value.
# a stable nlogn sorting algorithm can be used instead of bubble sort
# to reduce time complexity of the problem.
bubble_sort(page_strengths)
# display topfive(or fewer) pages for a particular query
print "Q#{query.id}: "
page_strengths[0, 5].each do |ps|
if ps.strength != 0
print "P#{ps.pageid} "
end
end
puts
end
end
end
def bubble_sort(array)
# it is a stable sort and sorts an array descending order
n = array.length
loop do
swapped = false
(n-1).times do |i|
if array[i].strength < array[i+1].strength
array[i], array[i+1] = array[i+1], array[i]
swapped = true
end
end
break if not swapped
end
array
end
if __FILE__ == $0
sr = SearchRanking.new()
sr.parse()
sr.rank_pages()
end |
Java | UTF-8 | 3,972 | 2.015625 | 2 | [
"BSD-3-Clause"
] | permissive | package org.revenj.patterns;
import rx.Observable;
import java.io.IOException;
import java.util.*;
public interface DataContext {
<T extends Identifiable> List<T> find(Class<T> manifest, Collection<String> uris);
default <T extends Identifiable> Optional<T> find(Class<T> manifest, String uri) {
List<T> found = find(manifest, Collections.singletonList(uri));
return found.size() == 1 ? Optional.of(found.get(0)) : Optional.<T>empty();
}
default <T extends Identifiable> List<T> find(Class<T> manifest, String[] uris) {
return find(manifest, Arrays.asList(uris));
}
<T extends DataSource> Query<T> query(Class<T> manifest, Specification<T> filter);
default <T extends DataSource> Query<T> query(Class<T> manifest) {
return query(manifest, null);
}
<T extends DataSource> List<T> search(Class<T> manifest, Specification<T> filter, Integer limit, Integer offset);
default <T extends DataSource> List<T> search(Class<T> manifest) {
return search(manifest, null, null, null);
}
default <T extends DataSource> List<T> search(Class<T> manifest, Specification<T> filter) {
return search(manifest, filter, null, null);
}
default <T extends DataSource> List<T> search(Class<T> manifest, Specification<T> filter, int limit) {
return search(manifest, filter, limit, null);
}
<T extends DataSource> long count(Class<T> manifest, Specification<T> filter);
default <T extends DataSource> long count(Class<T> manifest) {
return count(manifest, null);
}
<T extends DataSource> boolean exists(Class<T> manifest, Specification<T> filter);
default <T extends DataSource> boolean exists(Class<T> manifest) {
return exists(manifest, null);
}
<T extends AggregateRoot> void create(Collection<T> aggregates) throws IOException;
default <T extends AggregateRoot> void create(T aggregate) throws IOException {
create(Collections.singletonList(aggregate));
}
<T extends AggregateRoot> void updatePairs(Collection<Map.Entry<T, T>> pairs) throws IOException;
default <T extends AggregateRoot> void update(T oldAggregate, T newAggregate) throws IOException {
updatePairs(Collections.singletonList(new HashMap.SimpleEntry<>(oldAggregate, newAggregate)));
}
default <T extends AggregateRoot> void update(T aggregate) throws IOException {
updatePairs(Collections.singletonList(new HashMap.SimpleEntry<>(null, aggregate)));
}
default <T extends AggregateRoot> void update(Collection<T> aggregates) throws IOException {
Collection<Map.Entry<T, T>> collection = new ArrayList<>(aggregates.size());
for (T item : aggregates) {
collection.add(new AbstractMap.SimpleEntry<>(null, item));
}
updatePairs(collection);
}
<T extends AggregateRoot> void delete(Collection<T> aggregates) throws IOException;
default <T extends AggregateRoot> void delete(T aggregate) throws IOException {
delete(Collections.singletonList(aggregate));
}
<T extends DomainEvent> void submit(Collection<T> events);
default <T extends DomainEvent> void submit(T event) {
submit(Collections.singletonList(event));
}
<T extends DomainEvent> void queue(Collection<T> events);
default <T extends DomainEvent> void queue(T event) {
queue(Collections.singletonList(event));
}
<T> T populate(Report<T> report);
<T extends Identifiable> Observable<DataChangeNotification.TrackInfo<T>> track(Class<T> manifest);
<T extends ObjectHistory> List<History<T>> history(Class<T> manifest, Collection<String> uris);
default <T extends ObjectHistory> Optional<History<T>> history(Class<T> manifest, String uri) {
List<History<T>> found = history(manifest, Collections.singletonList(uri));
return found.size() == 1 ? Optional.of(found.get(0)) : Optional.<History<T>>empty();
}
default <T extends ObjectHistory> List<History<T>> history(Class<T> manifest, String[] uris) {
return history(manifest, Arrays.asList(uris));
}
}
|
C++ | UTF-8 | 1,323 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdio>
#include <vector>
using namespace std;
int main( int argc, char **argv )
{
if (argc<3)
{
cerr << "create_timeline machine maxTime" << endl;
exit(EXIT_FAILURE);
}
int m = stoi(argv[1]);
int time = stoi(argv[2]);
ifstream file("solution.txt");
string line;
int num,j,m0,t0,mf,tf,one,zero;
vector<vector<string>> timeline;
timeline = vector<vector<string>>(time+1, vector<string>(m+2));
while( getline( file, line ) )
{
sscanf(line.c_str(), "%d x(%d,%d,%d,%d,%d) %d %d", &num, &j, &m0, &t0, &mf, &tf,&one,&zero);
cout << j << " " << m0 << " " << t0 << " " << mf << " " << tf << endl;
if (m0 == mf){
timeline[t0][m0]= timeline[t0][m0]+","+to_string(j)+"w";
} else {
for (int i = t0; i < tf; i++ ){
timeline[i][m0] = timeline[i][m0]+","+to_string(j)+"p";
}
}
}
ofstream f;
f.open ("timeline.txt");
f << "-";
for (int i = 1; i <= m; i++){
f << "\t " << i;
}
f << endl;
for (int t = 1; t < time+1; t++){
f << t;
for (int m0 = 1; m0 <= m; m0++){
f << "\t" << timeline[t][m0];
}
f << endl;
}
f.close();
} |
Java | UTF-8 | 1,232 | 1.78125 | 2 | [] | no_license | package com.xebia.assessmenttool.web.request;
import com.xebia.assessmenttool.entity.DraftQuestion;
import java.util.List;
public class EditTestRequest {
private int id;
private int orgId;
private String name;
private List<String> framework;
private List<DraftQuestion> draftQuestions;
private String flag;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrgId() {
return orgId;
}
public void setOrgId(int orgId) {
this.orgId = orgId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getFramework() {
return framework;
}
public void setFramework(List<String> framework) {
this.framework = framework;
}
public List<DraftQuestion> getDraftQuestions() {
return draftQuestions;
}
public void setDraftQuestions(List<DraftQuestion> draftQuestions) {
this.draftQuestions = draftQuestions;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
|
C++ | UTF-8 | 2,111 | 3.875 | 4 | [] | no_license | /*
CH08-320142
a4_p2.cpp
Aashish Paudel
aasispaudel@jacobs-university.de
*/
#include <iostream>
#include <string>
using namespace std;
class Creature {
public:
Creature();
void run() const;
~Creature();
protected:
int distance;
};
Creature::Creature(): distance(10)
{cout << "Calling constructor:: Creature" << endl;}
Creature::~Creature(){
cout << "Calling destructor:: Creature" << endl;
}
void Creature::run() const
{
cout << "running " << distance << " meters!\n";
}
class Wizard : public Creature {
public:
Wizard();
~Wizard();
void hover() const;
private:
int distFactor;
};
Wizard::Wizard() : distFactor(3)
{cout << "Constructor called: Wizard" << endl;}
Wizard::~Wizard(){
cout << "Destructor called : Wizard" << endl;
}
void Wizard::hover() const
{
cout << "hovering " << (distFactor * distance) << " meters!\n";
}
/*class Unicorn
It has jump method and height as its parameter
*/
class Unicorn : public Creature {
public:
Unicorn();
~Unicorn();
void jump() const;
private:
int height;
};
Unicorn::Unicorn(): height(6) {
cout << "Constructor called: Unicorn" << endl;
}
Unicorn::~Unicorn() {
cout << "Destructor called: unicorn" << endl;
}
void Unicorn::jump() const {
cout << "Jumping " << height << " meters High and " << distance << " meters long" << endl;
}
/*
Class Dragon
It has breathe as its function and fire as its parameter
*/
class Dragon : public Creature {
public:
Dragon();
~Dragon();
void breathe() const;
private:
string fire;
};
Dragon::Dragon(): fire("Fire") {
cout << "Constructor called: Dragon" << endl;
}
Dragon::~Dragon() {
cout << "Destructor called: Dragon" << endl;
}
void Dragon::breathe() const {
cout << "Breathing " << fire << endl;
}
int main()
{
cout << "Creating an Creature.\n";
Creature c;
c.run();
cout << "\nCreating a Wizard.\n";
Wizard w;
w.run();
w.hover();
cout << "\nCreating a Unicorn.\n";
Unicorn u;
u.run();
u.jump();
cout<< "\nCreating a Dragon\n";
Dragon d;
d.run();
d.breathe();
return 0;
}
|
Python | UTF-8 | 484 | 2.890625 | 3 | [
"MIT"
] | permissive | from voronoi.events.event import Event
from voronoi.graph.coordinate import Coordinate
class SiteEvent(Event):
circle_event = False
def __init__(self, point: Coordinate):
"""
Site event
:param point:
"""
self.point = point
@property
def x(self):
return self.point.x
@property
def y(self):
return self.point.y
def __repr__(self):
return "SiteEvent"#(x={self.point.x}, y={self.point.y})"
|
Python | UTF-8 | 3,698 | 2.625 | 3 | [] | no_license | import csv
import unittest
from time import sleep
from automate_driver.automate_driver import AutomateDriver
from model.connect_sql import ConnectSql
from pages.base.base_page import BasePage
from pages.login.log_in_page_read_csv import LogInPageReadCsv
from pages.login.login_page import LoginPage
from pages.organize_management.organize_management import OrganizeManagement
from pages.organize_management.organize_management_read_csv import OrganizeManagementReadCsv
from pages.role_management.role_management import RoleManagement
from pages.role_management.role_management_read_csv import RoleManagementReadCsv
from pages.user_center.user_center import UserCenter
from pages.user_center.user_center_read_csv import UserCenterReadCsv
class TestCase05RoleManageSearchRole(unittest.TestCase):
# 测试角色管理搜索角色
def setUp(self):
self.driver = AutomateDriver()
self.base_url = self.driver.base_url
self.base_page = BasePage(self.driver, self.base_url)
self.login_page = LoginPage(self.driver, self.base_url)
self.user_center = UserCenter(self.driver, self.base_url)
self.role_management = RoleManagement(self.driver, self.base_url)
self.log_in_page_read_csv = LogInPageReadCsv()
self.user_center_read_csv = UserCenterReadCsv()
self.role_management_read_csv = RoleManagementReadCsv()
self.driver.set_window_max()
self.connect_sql = ConnectSql()
self.driver.wait(1)
self.driver.clear_cookies()
self.driver.wait(1)
def tearDown(self):
self.driver.quit_browser()
def test_search_role(self):
# 通过csv测试搜索角色功能
csv_file = self.role_management_read_csv.read_csv('search_role.csv')
csv_data = csv.reader(csv_file)
for row in csv_data:
search_role = {
"account": row[0],
"password": row[1],
"search_name": row[2],
}
# 打开风控首页-登录页
self.base_page.open_page()
sleep(1)
# 登录账号
self.login_page.user_login(search_role['account'],search_role['password'])
# 判断登录成功后招呼栏的用户名是否正确
username = self.user_center.get_username()
# 从数据库获取登录账号的用户名
account_info = self.user_center.get_account_info_by_sql(search_role['account'])
print(account_info)
account_name = account_info[1]
self.assertEqual(account_name, username, '登录成功后招呼栏的用户名错误')
# 点击进入角色管理
self.role_management.click_role_manage()
# 输入搜索关键词进行搜索
self.role_management.search_role(search_role['search_name'])
# 获取搜索结果
num = int(self.role_management.get_search_result_num())
role_name = self.role_management.get_search_result_all()
# 数据库查询搜索结果
role_name_by_sql = self.role_management.get_search_result_rolename_by_sql(search_role['account'],search_role['search_name'])
num_by_sql = self.role_management.get_search_result_num_by_sql(search_role['account'], search_role['search_name'])
# 验证搜索结果是否一致
self.assertEqual(num, num_by_sql)
self.assertEqual(set(role_name), set(role_name_by_sql))
# 跳出外层frame
self.role_management.switch_to_default_content()
# 退出登录
self.user_center.logout()
csv_file.close()
|
C++ | UTF-8 | 2,286 | 4.125 | 4 | [] | no_license | # include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
class createNode{
public:
Node *first=NULL, *last=NULL;
void CNode(int d){
Node *t;
if(first==NULL){
first = new Node;
first->data = d;
first->next=NULL;
last = first;
}
else{
t = new Node;
t->data = d;
t->next = NULL;
last->next = t;
last = t;
}
}
void display(){
int a=0;
Node *p = first;
while(p != NULL){
cout<<a<<". "<<p->data<<" "<<p->next<<endl;
p = p->next;
a++;
}
}
void countNodes();
void findNode();
};
void createNode :: countNodes(){
Node *p = first;
int count=0;
while(p){
count++;
p=p->next;
}
cout<<"\nTotal Number of nodes in linked list: "<<count<<endl;
}
void createNode :: findNode(){
Node *ptr = first;
int pos=0, ninput, flag=0;
cout<<"Enter the node which you wnat to find: ";
cin>>ninput;
while(ptr->data != ninput){
ptr = ptr->next;
pos++;
if(ptr->data==ninput){
flag = 1;
}
}
if(flag == 1){
cout<<"Node found at posotion: "<<pos<<endl;
}
else{
cout<<"Node not found in the list";
}
}
int main(){
createNode obj;
int d, ch=1;
while(ch!=5){
cout<<"\n1.Create\n2.Display\n3.Count number of nodes\n4.Find the node\n5.Exit"<<endl;
cout<<"\nEnter your choice: ";
cin>>ch;
if(ch == 1){
cout<<"Enter data: ";
cin>>d;
obj.CNode(d);
obj.display();
}
else if(ch == 2){
obj.display();
}
else if (ch==3){
obj.countNodes();
}
else if(ch==4){
obj.findNode();
}
else if(ch==5){
break;
return 0;
}
else{
cout<<"Invalid input try again !";
}
}
return 0;
}
// Written by Ishan Jawade. ✌🏻
|
TypeScript | UTF-8 | 516 | 2.6875 | 3 | [] | no_license | import { useState, useEffect } from 'react';
import { LatLngExpression } from 'leaflet';
const useCurrentPosition = (): LatLngExpression => {
const [position, setPosition] = useState<LatLngExpression>([-3.7241674, -38.5924303]);
useEffect(() => {
navigator.geolocation.getCurrentPosition((position) => {
const { latitude, longitude } = position.coords;
setPosition([latitude, longitude]);
});
}, []);
return position;
};
export default useCurrentPosition;
|
C++ | UTF-8 | 2,220 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | #include "default_timer.h"
#include "statistic.h"
namespace atlas {
namespace meter {
DefaultTimer::DefaultTimer(const IdPtr& id, const Clock& clock,
int64_t freq_millis)
: Meter{id, clock},
count_(0),
total_time_(0),
sub_count_(id->WithTag(statistic::count), clock, freq_millis),
sub_total_sq_(id->WithTag(statistic::totalOfSquares), clock, freq_millis),
sub_total_time_(id->WithTag(statistic::totalTime), clock, freq_millis),
sub_max_(id->WithTag(statistic::max), clock, freq_millis) {
Updated(); // start the expiration timer
}
void DefaultTimer::Record(std::chrono::nanoseconds nanos) {
const auto nanos_count = nanos.count();
if (nanos_count >= 0) {
sub_count_.Increment();
++count_;
total_time_ += nanos_count;
sub_total_time_.Add(nanos_count);
auto nanos_sq =
static_cast<double>(nanos_count) * static_cast<double>(nanos_count);
sub_total_sq_.Add(nanos_sq);
sub_max_.Update(nanos_count);
}
Updated();
}
int64_t DefaultTimer::Count() const noexcept {
return count_.load(std::memory_order_relaxed);
}
int64_t DefaultTimer::TotalTime() const noexcept {
return total_time_.load(std::memory_order_relaxed);
}
std::ostream& DefaultTimer::Dump(std::ostream& os) const {
os << "DefaultTimer{";
sub_count_.Dump(os) << ", ";
sub_total_time_.Dump(os) << ", ";
sub_total_sq_.Dump(os) << ", ";
sub_max_.Dump(os) << "}";
return os;
}
static constexpr auto kCnvSeconds =
1.0 / 1e9; // factor to convert nanos to seconds
static constexpr auto kCnvSquares =
kCnvSeconds * kCnvSeconds; // factor to convert nanos squared to seconds
Measurements DefaultTimer::Measure() const {
auto count_measurement = sub_count_.Measure()[0];
auto total_time_measurement =
factor_measurement(sub_total_time_.Measure()[0], kCnvSeconds);
auto total_sq_measurement =
factor_measurement(sub_total_sq_.Measure()[0], kCnvSquares);
auto max_measurement = factor_measurement(sub_max_.Measure()[0], kCnvSeconds);
return Measurements{count_measurement, total_time_measurement,
total_sq_measurement, max_measurement};
}
} // namespace meter
} // namespace atlas
|
C# | UTF-8 | 1,116 | 3.078125 | 3 | [] | no_license | namespace ParticleSystem
{
using System;
using System.Collections.Generic;
public class ChaoticParticle : Particle, IRenderable, IMovingParticle
{
private const int MaxSpeedPerCoordinate = 2;
public ChaoticParticle(MatrixCoords position, MatrixCoords speed, Random randomGenerator)
: base(position, speed)
{
this.RandomGenerator = randomGenerator;
}
protected Random RandomGenerator { get; private set; }
public override IEnumerable<Particle> Update()
{
var randomAcceleration = GetRandomAcceleration();
this.Accelerate(randomAcceleration);
return base.Update();
}
protected virtual MatrixCoords GetRandomAcceleration()
{
int randomRowAcceleration = RandomGenerator.Next(-MaxSpeedPerCoordinate, MaxSpeedPerCoordinate + 1);
int randomColAcceleration = RandomGenerator.Next(-MaxSpeedPerCoordinate, MaxSpeedPerCoordinate + 1);
return new MatrixCoords(randomRowAcceleration, randomColAcceleration);
}
}
}
|
C++ | UTF-8 | 2,211 | 3.765625 | 4 | [] | no_license | #include<iostream>
#include<fstream>
#include <string>
#include <unordered_map>
using namespace std;
/**
* This class represents a single row that will be inside of the Resource.
* For example, a "Person" resource would store a row with his ID, name,
* surname e.t.c.
*/
class Row
{
};
/**
* This class represents a single Resource that will be stored
* in the database. A database may contain many resources such
* as: Person, Company, Dog e.t.c.
*/
class Resource
{
};
/**
* This class represents the Database in which resources will be stored.
*/
class Database
{
private:
/**
* key -> name of the resource ex. "person"
* value -> the resource "person"
*/
unordered_map<string, Resource> resources;
public:
Database();
unordered_map<string, Resource> get_resources() { return resources; }
string hello_world() {
return "Hello world";
}
};
class HelloWorldOperation
{
private:
ofstream stream;
public:
/**
* Name of operation.
*/
string name;
/**
* Every command should have a Receiver which will execute the logic
* according to that command. In this case, the database is the Receiver.
*/
Database* db;
HelloWorldOperation(string file_name) {
name = "Hello World";
stream.open(file_name);
}
void execute() {
stream<<db->hello_world()<<endl;
}
void revert() {
stream<<db->hello_world()<<" reverted!"<<endl;
}
string get_name() { return name; }
};
class OperationParser {
public:
static void parse_command(string command) {
if (command.rfind("Say hello", 0) == 0) {
HelloWorldOperation op("/your_path/output.txt");
op.execute();
op.revert();
return ;
}
}
};
int main() {
ifstream input;
input.open("/your_path/input.txt");
string line;
if (input.is_open()) {
while (getline(input,line)) {
OperationParser().parse_command(line);
}
input.close();
}
return 0;
} |
Java | UTF-8 | 4,487 | 1.953125 | 2 | [] | no_license | package nl.rls.ci.soap.impl;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import nl.rls.ci.soapinterface.ObjectFactory;
import nl.rls.ci.soapinterface.UICMessage;
import nl.rls.ci.soapinterface.UICMessageResponse;
import nl.rls.ci.soapinterface.UICReceiveMessage;
@Endpoint
public class CiEndpoint implements UICReceiveMessage {
private static final Logger log = LoggerFactory.getLogger(CiEndpoint.class);
private static final String NAMESPACE_URI = "http://uic.cc.org/UICMessage";
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "UICMessage")
@ResponsePayload
public JAXBElement<UICMessageResponse> getMessage(@RequestPayload JAXBElement<UICMessage> request) {
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance(UICMessage.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(request, sw);
String xmlString = sw.toString();
System.out.println(xmlString);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ObjectFactory factory = new ObjectFactory();
JAXBElement<UICMessageResponse> response = factory.createUICMessageResponse(new UICMessageResponse());
String technicalAck = " <LI_TechnicalAck>\n" +
" <ResponseStatus>NACK</ResponseStatus>\n" +
" <AckIndentifier>ACKIDSOAP bericht van Berend</AckIndentifier>\n" +
" <MessageReference>\n" +
" <MessageType>TrainCompositionMessage</MessageType>\n" +
" <MessageTypeVersion>2.1.6</MessageTypeVersion>\n" +
" <MessageIdentifier>SOAP bericht van Berend</MessageIdentifier>\n" +
" <MessageDateTime>2019-12-16T11:17:24.444</MessageDateTime>\n" +
" </MessageReference>\n" +
" <Sender>9001</Sender>\n" +
" <Recipient>84</Recipient>\n" +
" <RemoteLIName>ci-bpr.prorail.nl</RemoteLIName>\n" +
" <RemoteLIInstanceNumber>01</RemoteLIInstanceNumber>\n" +
" <MessageTransportMechanism>WEBSERVICE</MessageTransportMechanism>\n" +
" </LI_TechnicalAck>\n" +
"";
response.getValue().setReturn(technicalAck);
log.info("getMessage (UICMessageResponse): "+response.toString());
return response;
}
@Override
public UICMessageResponse uicMessage(UICMessage parameters, String messageIdentifier, String messageLiHost,
boolean compressed, boolean encrypted, boolean signed) {
ObjectFactory factory = new ObjectFactory();
JAXBElement<UICMessageResponse> response = factory.createUICMessageResponse(new UICMessageResponse());
String technicalAck = " <LI_TechnicalAck>\n" +
" <ResponseStatus>NACK</ResponseStatus>\n" +
" <AckIndentifier>ACKIDSOAP bericht van Berend</AckIndentifier>\n" +
" <MessageReference>\n" +
" <MessageType>TrainCompositionMessage</MessageType>\n" +
" <MessageTypeVersion>2.1.6</MessageTypeVersion>\n" +
" <MessageIdentifier>SOAP bericht van Berend</MessageIdentifier>\n" +
" <MessageDateTime>2019-12-16T11:17:24.444</MessageDateTime>\n" +
" </MessageReference>\n" +
" <Sender>9001</Sender>\n" +
" <Recipient>84</Recipient>\n" +
" <RemoteLIName>ci-bpr.prorail.nl</RemoteLIName>\n" +
" <RemoteLIInstanceNumber>01</RemoteLIInstanceNumber>\n" +
" <MessageTransportMechanism>WEBSERVICE</MessageTransportMechanism>\n" +
" </LI_TechnicalAck>\n" +
"";
response.getValue().setReturn(technicalAck);
log.info("getMessage (UICMessageResponse): "+response.toString());
return response.getValue();
}
}
|
Go | UTF-8 | 711 | 2.84375 | 3 | [
"BSD-3-Clause"
] | permissive | package codecs
import (
"encoding/json"
"time"
"github.com/lfkeitel/spartan/event"
)
// The JSONPrettyCodec encodes/decodes an event as formatted, pretty JSON.
type JSONPrettyCodec struct{}
func init() {
register("json_pretty", newJSONPrettyCodec)
}
func newJSONPrettyCodec() (Codec, error) {
return &JSONPrettyCodec{}, nil
}
// Encode Event as JSON object.
func (c *JSONPrettyCodec) Encode(e *event.Event) []byte {
e.SetTimestamp(time.Unix(e.GetTimestamp().Unix(), 0))
data := e.Squash()
j, _ := json.MarshalIndent(data, "", " ")
return j
}
// Decode byte slice into an Event. CURRENTLY NOT IMPLEMENTED.
func (c *JSONPrettyCodec) Decode(data []byte) (*event.Event, error) {
return nil, nil
}
|
C# | UTF-8 | 749 | 2.625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using ItemsInterfaces;
using UnityEngine;
namespace Ui.Scripts
{
public abstract class CellsMenuHandlerBase : MonoBehaviour
{
protected readonly List<ItemCell> ItemsCells = new List<ItemCell>();
public void UpdateCells(List<IInventoryItem> items)
{
var k = 0;
foreach (var cell in ItemsCells)
{
try
{
cell.InitWithInventoryItem(items[k]);
}
catch
{
throw new IndexOutOfRangeException("Items cells count more then inventory can keep up");
}
k++;
}
}
}
} |
JavaScript | UTF-8 | 2,928 | 2.65625 | 3 | [] | no_license | //'US' dropdown menu (only activated by hover);
const dropdownUS = document.querySelector('.US-dropdown-visible');
const dropdownUSHidden = document.querySelector('.US-dropdown-selection');
dropdownUS.addEventListener('mouseover', function() {
dropdownUSHidden.style.display = 'block';
})
dropdownUSHidden.addEventListener('mouseover', function() {
dropdownUSHidden.style.display = 'block';
})
dropdownUSHidden.addEventListener('mouseout', function() {
dropdownUSHidden.style.display = 'none';
})
dropdownUS.addEventListener('mouseout', function() {
dropdownUSHidden.style.display = 'none';
})
//'find a warehouse' dropdown
const dropdownWarehouse = document.querySelector('.findWarehouse-visible');
const dropdownWarehouseHidden = document.querySelector('.findWarehouse-hidden');
dropdownWarehouse.addEventListener('mouseover', function() {
dropdownWarehouseHidden.style.display = 'block';
})
dropdownWarehouseHidden.addEventListener('mouseover', function() {
dropdownWarehouseHidden.style.display = 'block';
})
dropdownWarehouseHidden.addEventListener('mouseout', function() {
dropdownWarehouseHidden.style.display = 'none';
})
dropdownWarehouse.addEventListener('mouseout', function() {
dropdownWarehouseHidden.style.display='none';
})
//footer drop down MOBILE DISPLAY HIDDEN
const allIcons = document.querySelectorAll('.footer-two-mobile-nonexpand');
const allDropdowns = document.querySelectorAll('.footer-two-mobile-drop');
for (let i = 0; i<allIcons.length; i++) {
allIcons[i].addEventListener('click', function() {
const plus = document.querySelector(`.plus-icon${i}`);
const minus = document.querySelector(`.minus-icon${i}`);
const dropdown = document.querySelector(`.footer-two-mobile-drop${i}`);
//if you click on a plus, symbol changes to minus and dropdown appears
if (plus.style.display === 'block') {
plus.style.display = 'none';
minus.style.display = 'block';
dropdown.style.display = 'block';
let index = i;
console.log(index);
//allows only one dropdown menu to be opened at a time
for (let i = 0; i<allIcons.length; i++) {
if (i !== index) {
const plus = document.querySelector(`.plus-icon${i}`);
const minus = document.querySelector(`.minus-icon${i}`);
const dropdown = document.querySelector(`.footer-two-mobile-drop${i}`);
dropdown.style.display = 'none';
plus.style.display = 'block';
minus.style.display = 'none';
}
}
//if you click on a minus, symbol changes to plus and dropdown dissapears
} else {
plus.style.display = 'block';
minus.style.display = 'none';
dropdown.style.display = 'none';
}
})
}
|
Python | UTF-8 | 1,465 | 2.625 | 3 | [] | no_license | from Nov2018.helper import generate_sine_data
import matplotlib.pyplot as plt
import cntk as C
import numpy as np
from cntk.layers import Dense
from sklearn.utils import shuffle
x, y = generate_sine_data(100)
x, y = x[:, None].astype(np.float32), y[:, None].astype(np.float32)
x, y = shuffle(x, y)
input_tensor = C.input_variable(1, name="input_tensor")
target_tensor = C.input_variable(1, name="target_tensor")
# model
inner = Dense(16, activation=C.relu)(input_tensor)
inner = Dense(16, activation=C.relu)(inner)
inner = Dense(16, activation=C.relu)(inner)
inner = Dense(16, activation=C.relu)(inner)
prediction_tensor = Dense(1, activation=None)(inner)
loss = C.squared_error(prediction_tensor, target_tensor)
# sgd_momentum = C.momentum_sgd(prediction_tensor.parameters, 0.001, 0.9)
adam = C.adam(prediction_tensor.parameters, 0.01, 0.9) # optimiser
trainer = C.Trainer(prediction_tensor, (loss, ), [adam])
# training loop
num_epoch = 1000
minibatch_size = 10
for epoch in range(num_epoch):
for i in range(0, x.shape[0], minibatch_size):
lbound, ubound = i, i + minibatch_size
x_mini = x[lbound:ubound]
y_mini = y[lbound:ubound]
trainer.train_minibatch({input_tensor: x_mini,
target_tensor: y_mini})
print(f"loss: {trainer.previous_minibatch_loss_average}")
prediction = prediction_tensor.eval({input_tensor: x})
plt.scatter(x, y)
plt.scatter(x, prediction)
plt.show()
|
Java | UTF-8 | 5,373 | 3.171875 | 3 | [] | no_license | package com.example.lucas.hangman666;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Evil game play
* Game determines the largest group of words, either containing the guess at [index], or not
* containing the guess at all.
* Multiple matches are discarded, as it gives the player too much information about possible
* guesses.
*/
public class EvilGamePlay extends Gameplay{
private int targetLength;
protected void createUnderscores(int target){
targetLength = target;
String underscores = "";
for (int i = 0; i< target - 1; i++) {
underscores = underscores + "_ ";
}
// set last underscore without space at end
underscores = underscores + "_";
// set the underscores
Gameplay.wordContainer.setText(underscores);
}
protected Boolean evilClick(Character c) {
if (usedWords.size() != 1){
// stores words in temporary array
int x = targetLength + 1;
// create array for indices
int[] array = new int[x];
// create list for words
List<String> values;
values = new ArrayList<>();
// array for non containing words
List<String> noContain = new ArrayList<>();
// loops over array of words
for (int i = 0; i < usedWords.size(); i++){
// index and amount of times letter present in word
int numbInWord = 0;
int index = 0;
// nothing added yet
Boolean added = Boolean.FALSE;
// loop over current word
for (int j = 0; j < usedWords.get(i).length(); j++) {
// if found guess
if (usedWords.get(i).charAt(j) == c) {
// update index of match
index = j;
// update number of matches
numbInWord++;
}
}
// for single matches
if (numbInWord == 1) {
// update value of words with letter at index
array[index + 1]++;
added = Boolean.TRUE;
}
// if number not present update not containing list
if (!added && numbInWord == 0) {
array[0]++;
noContain.add(usedWords.get(i));
}
}
// clear values and add not containing words to hash map
values.clear();
// determines index of largest equivalence class
int maximumIndex = 0;
for (int i = 1; i < array.length; i++) {
// compares values and sets maximum index correspondingly
if (array[i] > array[maximumIndex]) {
maximumIndex = i;
}
}
// if words without guess larger
if (maximumIndex == 0) {
usedWords.clear();
usedWords.addAll(noContain);
return false;
}
else {
// update with guess
updateUnderscores(c, maximumIndex - 1);
// updates words to words from largest equivalence class
for (int i = 0; i < usedWords.size(); i++){
if (usedWords.get(i).charAt(maximumIndex - 1) == c){
values.add(usedWords.get(i));
}
}
usedWords.clear();
usedWords.addAll(values);
return true;
}
}
// if one word in array, resume regular game play
else{
// updates evilGuess
currentEvilGuess = usedWords.get(0);
Boolean correct = Boolean.FALSE;
// loops over word for matches and updates
for (int i =0; i < currentEvilGuess.length(); i++){
if (currentEvilGuess.charAt(i) == c){
updateUnderscores(c, i);
correct = Boolean.TRUE;
}
}
// returns value
return correct;
}
}
final void updateUnderscores(char letter, int index){
// turn underscores into string and character array
String underscores = wordContainer.getText().toString();
char[] charsArray = underscores.toCharArray();
// correct index for spaces and set letter
index = index * 2;
charsArray[index] = letter;
// turn into string and update
underscores = String.valueOf(charsArray);
wordContainer.setText(underscores);
// update correct counter to see if won yet
lettersCorrect++;
if (lettersCorrect == wordLength){
Toast.makeText(this, "You win!", Toast.LENGTH_SHORT).show();
// determines time at end of game
long endTime = System.currentTimeMillis();
// creates record for played game, corrected for length of guessed word
record = ((endTime - startTime) / wordLength) * (2 - ((6 - limbs) / 6));
// ask name input
promptName(record);
}
}
} |
C++ | UTF-8 | 4,046 | 2.546875 | 3 | [
"MIT"
] | permissive | #ifndef CONNECTIONGRAPH_H
#define CONNECTIONGRAPH_H
#include <list>
#include <vector>
#include <cstdint>
#include <typeindex>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <map>
#include <functional>
#include <memory>
#include <algorithm>
namespace dps {
using param_index_t = uint8_t;
using chain_index_t = uint32_t;
using subscriber_index_t = uint32_t;
using string_t = std::string;
enum class Operation {
Lt,
Gt,
Lte,
Gte,
Eq,
Neq,
Contains,
Exists
};
// TODO: variant type
union ParamValue{
int64_t integer_;
double double_;
string_t string_;
bool raw_exists_;
};
template<typename T>
using connection_t = std::unordered_map<dps::param_index_t,std::pair<dps::Operation,T>>;
template<typename T>
using connection_list_t = std::vector<connection_t<T>>;
template<typename T>
using param_list_t = std::unordered_map<dps::param_index_t, T>;
}
namespace std {
template <>
struct hash<dps::Operation>
{
size_t operator()(const dps::Operation& op) const
{
return hash<int>()(static_cast<int>(op));
}
};
}
namespace dps {
template <typename T>
struct ValueNode {
T value;
std::unordered_set<chain_index_t> chains;
};
template <typename T>
inline bool value_node_compare(ValueNode<T> a, ValueNode<T> b){
return a.value < b.value;
}
template <typename T>
struct OperationNode {
OperationNode():val_nodes(value_node_compare<T>){}
Operation op;
std::set<ValueNode<T>,bool(*)(ValueNode<T>, ValueNode<T>)> val_nodes;
};
class ParamNode {
param_index_t id_;
std::unordered_set<chain_index_t> chains_;
public:
ParamNode() = delete;
virtual ~ParamNode(){}
ParamNode(param_index_t id): id_(id){}
inline param_index_t id() const {return id_;}
inline std::unordered_set<chain_index_t> chains() const {return chains_;}
inline void add_chain(chain_index_t chain){chains_.insert(chain);}
inline void remove_chain(chain_index_t chain){chains_.erase(chain);}
};
template <typename T>
class ParamNodeImpl : public ParamNode {
std::unordered_map<Operation, OperationNode<T>> op_nodes;
std::function<bool(const T, const T)> get_comparator(Operation op) const;
public:
ParamNodeImpl() = delete;
ParamNodeImpl(param_index_t id): ParamNode(id){}
std::unordered_set<Operation> operation_set() const;
void add_condition(chain_index_t chain, Operation op, const T val);
void remove_condition(chain_index_t chain);
// should use dynamic_cast:(
void eval(const T *value, std::unordered_set<chain_index_t> &excluded_chains) const;
};
}
#if TEST_ENV
class ConnectionGraphTest;
#endif
namespace dps {
class ConnectionGraph
{
#if TEST_ENV
friend class ::ConnectionGraphTest;
#endif
std::unordered_map<param_index_t, std::shared_ptr<dps::ParamNode>> params_;
std::vector<std::vector<std::shared_ptr<dps::ParamNode>>> param_graph_; //tiers of same weight nodes
std::unordered_map<chain_index_t, std::unordered_set<subscriber_index_t>> subscriber_map;
chain_index_t next_chain_index_;
void sort_graph();
public:
ConnectionGraph();
~ConnectionGraph();
template<typename T>
void eval(const param_list_t<T> ¶m_val, std::unordered_set<dps::subscriber_index_t> &subscribers);
// TODO: add connection for existing chain
template<typename T>
chain_index_t add_connection(const connection_t<T> &chain, subscriber_index_t subscriber_id, chain_index_t chain_id = 0);
void remove_connection(chain_index_t);
};
}
#include "connectiongraph.tpl.hpp"
#endif // CONNECTIONGRAPH_H
|
Java | UTF-8 | 38,371 | 2.046875 | 2 | [] | no_license | package com.abcrentals.binu.thankachan.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.abcrentals.binu.thankachan.constants.RentalWebsiteConstants;
import com.abcrentals.binu.thankachan.entity.Address;
import com.abcrentals.binu.thankachan.entity.ContactInfo;
import com.abcrentals.binu.thankachan.entity.RenterProfile;
import com.abcrentals.binu.thankachan.entity.Country;
import com.abcrentals.binu.thankachan.entity.EmployerInfo;
import com.abcrentals.binu.thankachan.entity.PrivateInfo;
import com.abcrentals.binu.thankachan.entity.RenterProfile;
import com.abcrentals.binu.thankachan.entity.StateOrProvince;
import com.abcrentals.binu.thankachan.entity.User;
import com.abcrentals.binu.thankachan.service.AddressService;
import com.abcrentals.binu.thankachan.service.ContactInfoService;
import com.abcrentals.binu.thankachan.service.CountryService;
import com.abcrentals.binu.thankachan.service.EmployerInfoService;
import com.abcrentals.binu.thankachan.service.PrivateInfoService;
import com.abcrentals.binu.thankachan.service.RenterProfileService;
import com.abcrentals.binu.thankachan.service.StateOrProvinceService;
import com.abcrentals.binu.thankachan.user.RenterUserProfile;
import com.abcrentals.binu.thankachan.user.RenterUserProfile;
/*
* Controller class to specify handler methods for users with a role of renter
*
*
*
*/
@Controller
@RequestMapping("/renter")
public class RenterController {
private Logger logger = Logger.getLogger(getClass().getName());
@Autowired
private CountryService countryService;
@Autowired
private StateOrProvinceService stateOrProvinceService;
@Autowired
private AddressService addressService;
@Autowired
private ContactInfoService contactInfoService;
@Autowired
private EmployerInfoService employerInfoService;
@Autowired
private PrivateInfoService privateInfoService;
@Autowired
private RenterProfileService renterProfileService;
// method to load countries list as model attribute and countries and statesOrProvinces lists as session attributes
@ModelAttribute("countries")
public List<Country> initializeCountries(HttpServletRequest request) {
List<Country> countries = countryService.findAllCountries();
Country country = countryService.findAllCountries().get(0);
HttpSession se = request.getSession();
se.setAttribute("countries", countries);
List<StateOrProvince> statesOrProvinces = stateOrProvinceService.findByCountry(country.getCountryName());
se.setAttribute("statesOrProvinces", statesOrProvinces);
System.out.println("in RenterController class initializeCountry() method: countries= " + countries.toString());
System.out.println("In RenterController initializeCountries() method country= " + countries);
System.out.println("In RenterController initializeCountries() method country.getCountryName()= "
+ country.getCountryName());
System.out.println("In RenterController initializeCountries() method statesOrProvinces= "
+ statesOrProvinces + "\n\n");
return countries;
}
// handler method to display the add renter profile page
@GetMapping("/showAddRenterProfilePage")
public ModelAndView showAddRenterProfilePage(HttpServletRequest request, Model theModel) {
ModelAndView mv = new ModelAndView("renter/add-renter-profile");
mv.addObject("renterUserProfile", new RenterUserProfile());
// theModel.addAttribute("renterUserProfile", new RenterUserProfile());
HttpSession se = request.getSession();
List<Country> countries = (List<Country>) se.getAttribute("countries");
List<StateOrProvince> statesOrProvinces = (List<StateOrProvince>) se.getAttribute("statesOrProvinces");
mv.addObject("countries", countries);
mv.addObject("statesOrProvincesForHomeAddress", statesOrProvinces);
mv.addObject("statesOrProvincesForEmployerAddress", statesOrProvinces);
mv.addObject("statesOrProvincesForBillingAddress", statesOrProvinces);
se.setAttribute("countries", countries);
se.setAttribute("statesOrProvincesForHomeAddress", statesOrProvinces);
se.setAttribute("statesOrProvincesForEmployerAddress", statesOrProvinces);
se.setAttribute("statesOrProvincesForBillingAddress", statesOrProvinces);
System.out.println("In RenterController showAddRenterProfilePage() method countries= " + countries);
System.out.println("In RenterController showAddRenterProfilePage() method statesOrProvinces= "
+ statesOrProvinces + "\n\n");
// return "add-renter-profile";
return mv;
}
// handler method to process the add renter profile form
@PostMapping("/processAddRenterProfileForm")
public ModelAndView processAddRenterProfileForm(HttpServletRequest request,
@Valid @ModelAttribute("renterUserProfile") RenterUserProfile theRenterUserProfile,
BindingResult theBindingResult, Model theModel) {
String contactInfoFirstName = theRenterUserProfile.getContactInfoFirstName();
String contactInfoLastName = theRenterUserProfile.getContactInfoLastName();
logger.info("Processing Add Renter Profile form for: " + contactInfoFirstName + " " + contactInfoLastName);
System.out.println("theRenterUserProfile: " + theRenterUserProfile.toString());
HttpSession se = request.getSession();
// form validation
if (theBindingResult.hasErrors()) {
System.out.println(
"in processAddRenterProfileForm() method: there are errors | redirecting to add-renter-profile page");
System.out.println(
"in processAddRenterProfileForm() method: | " + theBindingResult.getAllErrors().toString());
ModelAndView mv = new ModelAndView("renter/add-renter-profile");
mv.addObject("statesOrProvincesForHomeAddress", theRenterUserProfile);
mv.addObject("countries", se.getAttribute("countries"));
mv.addObject("statesOrProvincesForHomeAddress", se.getAttribute("statesOrProvincesForHomeAddress"));
mv.addObject("statesOrProvincesForEmployerAddress", se.getAttribute("statesOrProvincesForEmployerAddress"));
mv.addObject("statesOrProvincesForBillingAddress", se.getAttribute("statesOrProvincesForBillingAddress"));
return mv;
}
System.out.println("In RenterController processAddRenterProfileForm() method theRenterUserProfile= "
+ theRenterUserProfile);
Address homeAddress = new Address();
Address employerAddress = new Address();
Address billingAddress = new Address();
// save the home address in the db
if (!"".equals(theRenterUserProfile.getContactInfoHomeAddrLine1())) {
homeAddress.setAddressType(theRenterUserProfile.getContactInfoHomeAddressType());
homeAddress.setAddrLine1(theRenterUserProfile.getContactInfoHomeAddrLine1());
homeAddress.setAddrLine2(theRenterUserProfile.getContactInfoHomeAddrLine2());
homeAddress.setAddrLine3(theRenterUserProfile.getContactInfoHomeAddrLine3());
homeAddress.setAddrLine4(theRenterUserProfile.getContactInfoHomeAddrLine4());
homeAddress.setCity(theRenterUserProfile.getContactInfoHomeCity());
homeAddress.setState(stateOrProvinceService.findById(theRenterUserProfile.getContactInfoHomeState())
.getStateOrProvince());
homeAddress.setPostalCode(theRenterUserProfile.getContactInfoHomePostalCode());
homeAddress.setCountry(countryService.findByCountryCode(theRenterUserProfile.getContactInfoHomeCountry())
.getCountryName());
addressService.save(homeAddress);
}
// save the employer address in the db
if (!"".equals(theRenterUserProfile.getEmployerInfoEmployerAddrLine1())) {
employerAddress.setAddressType(theRenterUserProfile.getEmployerInfoEmployerAddressType());
employerAddress.setAddrLine1(theRenterUserProfile.getEmployerInfoEmployerAddrLine1());
employerAddress.setAddrLine2(theRenterUserProfile.getEmployerInfoEmployerAddrLine2());
employerAddress.setAddrLine3(theRenterUserProfile.getEmployerInfoEmployerAddrLine3());
employerAddress.setAddrLine4(theRenterUserProfile.getEmployerInfoEmployerAddrLine4());
employerAddress.setCity(theRenterUserProfile.getEmployerInfoEmployerCity());
employerAddress.setState(stateOrProvinceService
.findById(theRenterUserProfile.getEmployerInfoEmployerState()).getStateOrProvince());
employerAddress.setPostalCode(theRenterUserProfile.getEmployerInfoEmployerPostalCode());
employerAddress.setCountry(countryService
.findByCountryCode(theRenterUserProfile.getEmployerInfoEmployerCountry()).getCountryName());
addressService.save(employerAddress);
}
// save the billing address in the db
if (!"".equals(theRenterUserProfile.getPrivateInfoCCBillingAddrLine1())) {
billingAddress.setAddressType(theRenterUserProfile.getPrivateInfoCCBillingAddressType());
billingAddress.setAddrLine1(theRenterUserProfile.getPrivateInfoCCBillingAddrLine1());
billingAddress.setAddrLine2(theRenterUserProfile.getPrivateInfoCCBillingAddrLine2());
billingAddress.setAddrLine3(theRenterUserProfile.getPrivateInfoCCBillingAddrLine3());
billingAddress.setAddrLine4(theRenterUserProfile.getPrivateInfoCCBillingAddrLine4());
billingAddress.setCity(theRenterUserProfile.getPrivateInfoCCBillingCity());
billingAddress.setState(stateOrProvinceService.findById(theRenterUserProfile.getPrivateInfoCCBillingState())
.getStateOrProvince());
billingAddress.setPostalCode(theRenterUserProfile.getPrivateInfoCCBillingPostalCode());
billingAddress.setCountry(countryService
.findByCountryCode(theRenterUserProfile.getPrivateInfoCCBillingCountry()).getCountryName());
addressService.save(billingAddress);
}
ContactInfo contactInfo = new ContactInfo();
// save the Contact Info record in the db, while setting home address in the
// join table
if (!"".equals(theRenterUserProfile.getContactInfoFirstName())) {
contactInfo.setFirstName(theRenterUserProfile.getContactInfoFirstName());
contactInfo.setLastName(theRenterUserProfile.getContactInfoLastName());
contactInfo.setPrimaryEmail(theRenterUserProfile.getContactInfoPrimaryEmail());
contactInfo.setSecondaryEmail(theRenterUserProfile.getContactInfoSecondaryEmail());
contactInfo.setHomePhoneNo(theRenterUserProfile.getContactInfoHomePhoneNo().toString());
contactInfo.setWorkPhoneNo(theRenterUserProfile.getContactInfoWorkPhoneNo().toString());
contactInfo.setCellPhoneNo(theRenterUserProfile.getContactInfoCellPhoneNo().toString());
List<Address> homeAddresses = new ArrayList<Address>();
homeAddresses.add(homeAddress);
contactInfo.setHomeAddresses(homeAddresses);
contactInfoService.save(contactInfo);
}
EmployerInfo employerInfo = new EmployerInfo();
// save the Employer Info record in the db, while setting employer address in
// the join table
if (!"".equals(theRenterUserProfile.getEmployerInfoEmployerName())) {
employerInfo.setEmployerName(theRenterUserProfile.getEmployerInfoEmployerName());
employerInfo.setEmployerPhoneNo(theRenterUserProfile.getEmployerInfoEmployerPhoneNo().toString());
List<Address> employerAddresses = new ArrayList<Address>();
employerAddresses.add(employerAddress);
employerInfo.setEmployerAddresses(employerAddresses);
employerInfoService.save(employerInfo);
}
PrivateInfo privateInfo = new PrivateInfo();
// save the Private Info record in the db, while setting billing address in the
// join table
if (!"".equals(theRenterUserProfile.getPrivateInfoCCBillingAddrLine1())) {
privateInfo.setCreditCardNo(theRenterUserProfile.getPrivateInfoCreditCardNo().toString());
privateInfo.setCreditCardNoExpMonth(theRenterUserProfile.getPrivateInfoCreditCardNoExpMonth());
privateInfo.setCreditCardNoExpYear(theRenterUserProfile.getPrivateInfoCreditCardNoExpYear());
privateInfo.setCreditCardNoCCVCode(theRenterUserProfile.getPrivateInfoCreditCardNoCCVCode());
privateInfo.setGender(theRenterUserProfile.getPrivateInfoGender());
privateInfo.setEthnicity(theRenterUserProfile.getPrivateInfoEthnicity());
privateInfo.setSsn(theRenterUserProfile.getPrivateInfoSsn().toString());
privateInfo.setDob(theRenterUserProfile.getPrivateInfoDob());
List<Address> creditCardBillingAddresses = new ArrayList<Address>();
creditCardBillingAddresses.add(billingAddress);
privateInfo.setCreditCardBillingAddresses(creditCardBillingAddresses);
privateInfoService.save(privateInfo);
}
// get the user from the session and add it to the RenterProfile
User user = (User) se.getAttribute("user");
System.out.println("In RenterController processAddRenterProfileForm() method: user= id: " + user.getId()
+ " | name: " + user.getFirstName() + " " + user.getLastName() + " | username: "
+ user.getUserName());
RenterProfile renterProfile = renterProfileService.findById(user.getId());
System.out.println("14a: In RenterProfileController processAddRenterProfileForm() method: renterProfile= "
+ renterProfile + " | user.getId()= " + user.getId());
if (renterProfile == null)
renterProfile = new RenterProfile();
System.out.println(
"14b: In RenterController processAddRenterProfileForm() method: renterProfile= " + renterProfile);
// Now save the RenterProfile record to the database
renterProfile.setTypeOfProfile("RENTER");
if (user != null) {
renterProfile.setUser(user);
}
if (contactInfo != null) {
renterProfile.setContactInfo(contactInfo);
}
if (employerInfo != null) {
renterProfile.setEmployerInfo(employerInfo);
}
if (privateInfo != null) {
renterProfile.setPrivateInfo(privateInfo);
}
// save the renter profile record
renterProfileService.save(renterProfile);
ModelAndView mv = new ModelAndView("renter/add-renter-profile-confirmation");
mv.addObject("renterUserProfile", theRenterUserProfile);
return mv;
}
// handler method to display the update renter profile page
@GetMapping("/showUpdateRenterProfilePage")
public ModelAndView showUpdateRenterProfilePage(HttpServletRequest request, Model theModel) {
System.out.println("a1: Entering RenterController showUpdateRenterProfilePage() method");
ModelAndView mv = new ModelAndView("renter/update-renter-profile");
RenterUserProfile renterUserProfile = new RenterUserProfile();
mv.addObject("renterUserProfile", new RenterUserProfile());
HttpSession se = request.getSession();
User user = (User) se.getAttribute("user");
System.out.println("a2: ---> In RenterController showUpdateRenterProfilePage() method user= " + user.getId()
+ " | " + user.getUserName() + " | " + user.getFirstName() + " " + user.getLastName());
mv.addObject("user", user);
// now that we have the user, use the user id to find the Renter Profile record
// with that user id
RenterProfile renterProfile = renterProfileService.findByUserId(user.getId());
System.out.println("a3: ---> In RenterController showUpdateRenterProfilePage() method renterProfile= "
+ renterProfile);
mv.addObject("renterProfile", renterProfile);
// from the renterProfile record, get the Contact Info record and Employer Info
// record
System.out.println(
"a4a: ---> In RenterController showUpdateRenterProfilePage() method renterProfile.getUser().getId()= "
+ renterProfile.getUser().getId());
System.out.println(
"a4a: ---> In RenterController showUpdateRenterProfilePage() method renterProfile.getContactInfo().getId()= "
+ renterProfile.getContactInfo().getId());
ContactInfo contactInfo = contactInfoService.findContactInfoById(renterProfile.getContactInfo().getId());
System.out.println("a4b: ---> In RenterController showUpdateRenterProfilePage() method contactInfo= "
+ contactInfo.toString());
System.out.println(
"a5a: ---> In RenterController showUpdateRenterProfilePage() method renterProfile.getEmployerInfo().getId()= "
+ renterProfile.getEmployerInfo().getId());
EmployerInfo employerInfo = employerInfoService.findEmployerInfoById(renterProfile.getEmployerInfo().getId());
System.out.println("a5b: ---> In RenterController showUpdateRenterProfilePage() method employerInfo= "
+ employerInfo.toString());
System.out.println(
"a6a: ---> In RenterController showUpdateRenterProfilePage() method renterProfile.getPrivateInfo().getId()= "
+ renterProfile.getPrivateInfo().getId());
PrivateInfo privateInfo = privateInfoService.findPrivateInfoById(renterProfile.getPrivateInfo().getId());
System.out.println("a6b: ---> In RenterController showUpdateRenterProfilePage() method privateInfo= "
+ privateInfo.toString());
mv.addObject("contactInfo", contactInfo);
List<Address> homeAddresses = new ArrayList<Address>();
homeAddresses.add(contactInfo.getHomeAddresses().get(0));
mv.addObject("contactInfo_homeAddresses", homeAddresses);
System.out.println("a7a: ---> In RenterController showUpdateRenterProfilePage() method homeAddresses= "
+ homeAddresses.toString());
String state_to_find = contactInfo.getHomeAddresses().get(0).getState();
System.out.println(
"a7b:In RenterController in showUpdateRenterProfilePage() method state_to_find= " + state_to_find);
int stateOrProvinceStateIndx = stateOrProvinceService.findStateOrProvinceIndex(state_to_find);
System.out.println("a7c:In RenterController in showUpdateRenterProfilePage() method state_to_find= "
+ state_to_find + " | stateOrProvinceStateIndx= " + stateOrProvinceStateIndx);
mv.addObject("contactInfoHomeAddressStateIndx", stateOrProvinceStateIndx);
mv.addObject("employerInfo", employerInfo);
List<Address> employerAddresses = new ArrayList<Address>();
employerAddresses.add(employerInfo.getEmployerAddresses().get(0));
mv.addObject("employerInfo_employerAddresses", employerAddresses);
state_to_find = employerInfo.getEmployerAddresses().get(0).getState();
System.out.println(
"a8a:In RenterController in showUpdateRenterProfilePage() method state_to_find= " + state_to_find);
stateOrProvinceStateIndx = stateOrProvinceService.findStateOrProvinceIndex(state_to_find);
System.out.println("a8b:In RenterController in showUpdateRenterProfilePage() method state_to_find= "
+ state_to_find + " | stateOrProvinceStateIndx= " + stateOrProvinceStateIndx);
mv.addObject("employerInfoEmployerAddressStateIndx", stateOrProvinceStateIndx);
mv.addObject("privateInfo", privateInfo);
List<Address> creditCardBillingAddresses = new ArrayList<Address>();
creditCardBillingAddresses.add(privateInfo.getCreditCardBillingAddresses().get(0));
mv.addObject("privateInfo_creditCardBillingAddresses", creditCardBillingAddresses);
state_to_find = privateInfo.getCreditCardBillingAddresses().get(0).getState();
System.out.println(
"a9a:In RenterController in showUpdateRenterProfilePage() method state_to_find= " + state_to_find);
stateOrProvinceStateIndx = stateOrProvinceService.findStateOrProvinceIndex(state_to_find);
System.out.println("a9b:In RenterController in showUpdateRenterProfilePage() method state_to_find= "
+ state_to_find + " | stateOrProvinceStateIndx= " + stateOrProvinceStateIndx);
mv.addObject("privateInfoCreditCardBillingStateIndx", stateOrProvinceStateIndx);
// get countries and states from the session object and add them to the model
// and view object
List<Country> countries = (List<Country>) se.getAttribute("countries");
System.out.println(
"a10: ---> In RenterController showUpdateRenterProfilePage() method countries= " + countries);
List<StateOrProvince> statesOrProvinces = (List<StateOrProvince>) se.getAttribute("statesOrProvinces");
System.out.println("a11: ---> In RenterController showUpdateRenterProfilePage() method statesOrProvinces= "
+ statesOrProvinces);
mv.addObject("countries", countries);
mv.addObject("statesOrProvincesForHomeAddress", statesOrProvinces);
mv.addObject("statesOrProvincesForEmployerAddress", statesOrProvinces);
mv.addObject("statesOrProvincesForCreditCardBillingAddress", statesOrProvinces);
// se.setAttribute("countries", countries);
se.setAttribute("statesOrProvincesForHomeAddress", statesOrProvinces);
se.setAttribute("statesOrProvincesForEmployerAddress", statesOrProvinces);
se.setAttribute("statesOrProvincesForCreditCardBillingAddress", statesOrProvinces);
Map<Integer, String> ccExpirationYearList = new HashMap<Integer, String>();
int i=0;
for(String str: RentalWebsiteConstants.CC_EXP_YEARS) {
ccExpirationYearList.put(Integer.parseInt(str), str);
}
mv.addObject("ccExpirationYearList", ccExpirationYearList);
Map<Integer, String> ccExpirationMonthList = new HashMap<Integer, String>();
i=1;
for(String str: RentalWebsiteConstants.MONTHS_2DIGIT_PLUS_NAME) {
ccExpirationMonthList.put(i++, str);
}
mv.addObject("ccExpirationMonthList", ccExpirationMonthList);
Map<Integer, String> ethnicityList = new HashMap<Integer, String>();
i=0;
for(String str: RentalWebsiteConstants.ETHNICITIES) {
ethnicityList.put(i++, str);
}
mv.addObject("ethnicityList", ethnicityList);
//int ccExpirationYearIndx = privateInfo.getCreditCardNoExpYear();
System.out.println(
"z98: Exiting RenterController showUpdateRenterProfilePage() method countries= " + countries);
System.out.println("z99: Exiting RenterController showUpdateRenterProfilePage() method statesOrProvinces= "
+ statesOrProvinces + "\n\n");
return mv;
}
// handler method to process the update renter profile form
@PostMapping("/processUpdateRenterProfileForm")
public ModelAndView processUpdateRenterProfileForm(HttpServletRequest request,
@Valid @ModelAttribute("renterUserProfile") RenterUserProfile theRenterUserProfile,
BindingResult theBindingResult, Model theModel) {
String contactInfoFirstName = theRenterUserProfile.getContactInfoFirstName();
String contactInfoLastName = theRenterUserProfile.getContactInfoLastName();
logger.info("Processing Update Renter Profile form for: " + contactInfoFirstName + " " + contactInfoLastName);
System.out.println("theRenterUserProfile: " + theRenterUserProfile.toString());
HttpSession se = request.getSession();
// form validation
if (theBindingResult.hasErrors()) {
System.out.println(
"in processUpdateRenterProfileForm() method: there are errors | redirecting to update-renter-profile page");
System.out.println(
"in processUpdateRenterProfileForm() method: | " + theBindingResult.getAllErrors().toString());
ModelAndView mv = new ModelAndView("renter/update-renter-profile");
mv.addObject("statesOrProvincesForHomeAddress", theRenterUserProfile);
mv.addObject("countries", se.getAttribute("countries"));
mv.addObject("statesOrProvincesForHomeAddress", se.getAttribute("statesOrProvincesForHomeAddress"));
mv.addObject("statesOrProvincesForEmployerAddress", se.getAttribute("statesOrProvincesForEmployerAddress"));
mv.addObject("statesOrProvincesForCreditCardBillingAddress", se.getAttribute("statesOrProvincesForCreditCardBillingAddress"));
return mv;
}
System.out.println("In RenterController processUpdateRenterProfileForm() method theRenterUserProfile= "
+ theRenterUserProfile);
Address homeAddress = null;
Address employerAddress = null;
;
// update the home address in the db
if (!"".equals(theRenterUserProfile.getContactInfoHomeAddrLine1())) {
homeAddress = addressService.findByAddressId(theRenterUserProfile.getContactInfoHomeAddressId());
if (homeAddress == null)
homeAddress = new Address();
homeAddress.setAddressType(theRenterUserProfile.getContactInfoHomeAddressType());
homeAddress.setAddrLine1(theRenterUserProfile.getContactInfoHomeAddrLine1());
homeAddress.setAddrLine2(theRenterUserProfile.getContactInfoHomeAddrLine2());
homeAddress.setAddrLine3(theRenterUserProfile.getContactInfoHomeAddrLine3());
homeAddress.setAddrLine4(theRenterUserProfile.getContactInfoHomeAddrLine4());
homeAddress.setCity(theRenterUserProfile.getContactInfoHomeCity());
homeAddress.setState(stateOrProvinceService.findById(theRenterUserProfile.getContactInfoHomeState())
.getStateOrProvince());
homeAddress.setPostalCode(theRenterUserProfile.getContactInfoHomePostalCode());
homeAddress.setCountry(countryService.findByCountryCode(theRenterUserProfile.getContactInfoHomeCountry())
.getCountryName());
addressService.save(homeAddress);
}
// update the employer address in the db
if (!"".equals(theRenterUserProfile.getEmployerInfoEmployerAddrLine1())) {
employerAddress = addressService.findByAddressId(theRenterUserProfile.getEmployerInfoEmployerAddressId());
if (employerAddress == null)
employerAddress = new Address();
employerAddress.setAddressType(theRenterUserProfile.getEmployerInfoEmployerAddressType());
employerAddress.setAddrLine1(theRenterUserProfile.getEmployerInfoEmployerAddrLine1());
employerAddress.setAddrLine2(theRenterUserProfile.getEmployerInfoEmployerAddrLine2());
employerAddress.setAddrLine3(theRenterUserProfile.getEmployerInfoEmployerAddrLine3());
employerAddress.setAddrLine4(theRenterUserProfile.getEmployerInfoEmployerAddrLine4());
employerAddress.setCity(theRenterUserProfile.getEmployerInfoEmployerCity());
employerAddress.setState(stateOrProvinceService
.findById(theRenterUserProfile.getEmployerInfoEmployerState()).getStateOrProvince());
employerAddress.setPostalCode(theRenterUserProfile.getEmployerInfoEmployerPostalCode());
employerAddress.setCountry(countryService
.findByCountryCode(theRenterUserProfile.getEmployerInfoEmployerCountry()).getCountryName());
addressService.save(employerAddress);
}
ContactInfo contactInfo = null;
// update the Contact Info record in the db
if (!"".equals(theRenterUserProfile.getContactInfoFirstName())) {
contactInfo = contactInfoService.findContactInfoById(theRenterUserProfile.getContactInfoId());
if (contactInfo == null)
contactInfo = new ContactInfo();
contactInfo.setFirstName(theRenterUserProfile.getContactInfoFirstName());
contactInfo.setLastName(theRenterUserProfile.getContactInfoLastName());
contactInfo.setPrimaryEmail(theRenterUserProfile.getContactInfoPrimaryEmail());
contactInfo.setSecondaryEmail(theRenterUserProfile.getContactInfoSecondaryEmail());
contactInfo.setHomePhoneNo(theRenterUserProfile.getContactInfoHomePhoneNo().toString());
contactInfo.setWorkPhoneNo(theRenterUserProfile.getContactInfoWorkPhoneNo().toString());
contactInfo.setCellPhoneNo(theRenterUserProfile.getContactInfoCellPhoneNo().toString());
List<Address> homeAddresses = new ArrayList<Address>();
homeAddresses.add(homeAddress);
contactInfo.setHomeAddresses(homeAddresses);
contactInfoService.save(contactInfo);
}
EmployerInfo employerInfo = null;
// update the Employer Info record in the db
if (!"".equals(theRenterUserProfile.getEmployerInfoEmployerName())) {
employerInfo = employerInfoService.findEmployerInfoById(theRenterUserProfile.getEmployerInfoId());
if (employerInfo == null)
employerInfo = new EmployerInfo();
employerInfo.setEmployerName(theRenterUserProfile.getEmployerInfoEmployerName());
employerInfo.setEmployerPhoneNo(theRenterUserProfile.getEmployerInfoEmployerPhoneNo().toString());
List<Address> employerAddresses = new ArrayList<Address>();
employerAddresses.add(employerAddress);
employerInfo.setEmployerAddresses(employerAddresses);
employerInfoService.save(employerInfo);
}
// get the user from the session and add it to the RenterProfile
User user = (User) se.getAttribute("user");
System.out.println("In RenterController processUpdateRenterProfileForm() method: user= id: "
+ user.getId() + " | name: " + user.getFirstName() + " " + user.getLastName() + " | username: "
+ user.getUserName());
// Now update the RenterProfile record in the database
RenterProfile renterProfile = renterProfileService.findByUserId(user.getId());
System.out.println("14a: In RenterController processUpdateRenterProfileForm() method: renterProfile= "
+ renterProfile + " | user.getId()= " + user.getId());
if (renterProfile == null)
renterProfile = new RenterProfile();
System.out.println("14b: In RenterController processUpdateRenterProfileForm() method: renterProfile= "
+ renterProfile);
renterProfile.setTypeOfProfile("RENTER");
if (user != null) {
renterProfile.setUser(user);
}
if (contactInfo != null) {
renterProfile.setContactInfo(contactInfo);
}
if (employerInfo != null) {
renterProfile.setEmployerInfo(employerInfo);
}
// update the renter profile record
renterProfileService.save(renterProfile);
ModelAndView mv = new ModelAndView("renter/update-renter-profile-confirmation");
mv.addObject("renterUserProfile", theRenterUserProfile);
return mv;
}
// handler method to display the renter profile page
@GetMapping("/showDisplayRenterProfilePage")
public ModelAndView showDisplayRenterProfilePage(HttpServletRequest request, Model theModel) {
System.out.println("a1: Entering RenterController showDisplayRenterProfilePage() method");
ModelAndView mv = new ModelAndView("renter/display-renter-profile");
RenterUserProfile renterUserProfile = new RenterUserProfile();
mv.addObject("renterUserProfile", new RenterUserProfile());
HttpSession se = request.getSession();
User user = (User) se.getAttribute("user");
System.out.println("a2: ---> In RenterController showDisplayRenterProfilePage() method user= "
+ user.getId() + " | " + user.getUserName() + " | " + user.getFirstName() + " " + user.getLastName());
mv.addObject("user", user);
// now that we have the user, use the user id to find the Renter Profile record
// with that user id
RenterProfile renterProfile = renterProfileService.findByUserId(user.getId());
System.out.println("a3: ---> In RenterController showDisplayRenterProfilePage() method renterProfile= "
+ renterProfile);
mv.addObject("renterProfile", renterProfile);
// from the renterProfile record, get the Contact Info record and Employer Info
// record
System.out.println(
"a4a: ---> In RenterController showDisplayRenterProfilePage() method renterProfile.getUser().getId()= "
+ renterProfile.getUser().getId());
System.out.println(
"a4a: ---> In RenterController showDisplayRenterProfilePage() method renterProfile.getContactInfo().getId()= "
+ renterProfile.getContactInfo().getId());
ContactInfo contactInfo = contactInfoService.findContactInfoById(renterProfile.getContactInfo().getId());
System.out.println("a4b: ---> In RenterController showDisplayRenterProfilePage() method contactInfo= "
+ contactInfo.toString());
System.out.println(
"a5a: ---> In RenterController showDisplayRenterProfilePage() method renterProfile.getEmployerInfo().getId()= "
+ renterProfile.getEmployerInfo().getId());
EmployerInfo employerInfo = employerInfoService.findEmployerInfoById(renterProfile.getEmployerInfo().getId());
System.out.println("a5b: ---> In RenterController showDisplayRenterProfilePage() method employerInfo= "
+ employerInfo.getEmployerName());
System.out.println(
"a5c: ---> In RenterController showDisplayRenterProfilePage() method renterProfile.getEmployerInfo().getId()= "
+ renterProfile.getEmployerInfo().getId());
PrivateInfo privateInfo = privateInfoService.findPrivateInfoById(renterProfile.getPrivateInfo().getId());
System.out.println("a5d: ---> In RenterController showDisplayRenterProfilePage() method privateInfo= "
+ privateInfo.getCreditCardNo());
mv.addObject("contactInfo", contactInfo);
List<Address> homeAddresses = new ArrayList<Address>();
homeAddresses.add(contactInfo.getHomeAddresses().get(0));
mv.addObject("contactInfo_homeAddresses", homeAddresses);
System.out.println("a5e: ---> In RenterController showDisplayRenterProfilePage() method homeAddresses= "
+ homeAddresses.toString());
String state_to_find = contactInfo.getHomeAddresses().get(0).getState();
System.out.println(
"a6a:In RenterController in showDisplayRenterProfilePage() method state_to_find= " + state_to_find);
int stateOrProvinceStateIndx = stateOrProvinceService.findStateOrProvinceIndex(state_to_find);
System.out.println("a6b: In RenterController in showDisplayRenterProfilePage() method state_to_find= "
+ state_to_find + " | stateOrProvinceStateIndx= " + stateOrProvinceStateIndx);
mv.addObject("contactInfoHomeAddressStateIndx", stateOrProvinceStateIndx);
mv.addObject("employerInfo", employerInfo);
List<Address> employerAddresses = new ArrayList<Address>();
employerAddresses.add(employerInfo.getEmployerAddresses().get(0));
mv.addObject("employerInfo_employerAddresses", employerAddresses);
state_to_find = employerInfo.getEmployerAddresses().get(0).getState();
System.out.println("a7a: In RenterController in showDisplayRenterProfilePage() method state_to_find= "
+ state_to_find);
stateOrProvinceStateIndx = stateOrProvinceService.findStateOrProvinceIndex(state_to_find);
System.out.println("a7b: In RenterController in showDisplayRenterProfilePage() method state_to_find= "
+ state_to_find + " | stateOrProvinceStateIndx= " + stateOrProvinceStateIndx);
mv.addObject("employerInfoEmployerAddressStateIndx", stateOrProvinceStateIndx);
mv.addObject("privateInfo", privateInfo);
List<Address> creditCardBillingAddresses = new ArrayList<Address>();
creditCardBillingAddresses.add(privateInfo.getCreditCardBillingAddresses().get(0));
mv.addObject("privateInfo_creditCardBillingAddresses", creditCardBillingAddresses);
System.out.println(
"a8a: ---> In RenterController showDisplayRenterProfilePage() method creditCardBillingAddresses= "
+ creditCardBillingAddresses.toString());
state_to_find = privateInfo.getCreditCardBillingAddresses().get(0).getState();
System.out.println(
"a8b:In RenterController in showDisplayRenterProfilePage() method state_to_find= " + state_to_find);
stateOrProvinceStateIndx = stateOrProvinceService.findStateOrProvinceIndex(state_to_find);
System.out.println("a8c: In RenterController in showDisplayRenterProfilePage() method state_to_find= "
+ state_to_find + " | stateOrProvinceStateIndx= " + stateOrProvinceStateIndx);
mv.addObject("privateInfoCreditCardBillingAddressStateIndx", stateOrProvinceStateIndx);
// get countries and states from the session object and add them to the model
// and view object
List<Country> countries = (List<Country>) se.getAttribute("countries");
System.out.println(
"a10: ---> In RenterController showDisplayRenterProfilePage() method countries= " + countries);
List<StateOrProvince> statesOrProvinces = (List<StateOrProvince>) se.getAttribute("statesOrProvinces");
System.out.println("a11: ---> In RenterController showDisplayRenterProfilePage() method statesOrProvinces= "
+ statesOrProvinces);
mv.addObject("countries", countries);
mv.addObject("statesOrProvincesForHomeAddress", statesOrProvinces);
mv.addObject("statesOrProvincesForEmployerAddress", statesOrProvinces);
// se.setAttribute("countries", countries);
se.setAttribute("statesOrProvincesForHomeAddress", statesOrProvinces);
se.setAttribute("statesOrProvincesForEmployerAddress", statesOrProvinces);
System.out.println("a11a: ---> In RenterController ");
int genderIndx = privateInfo.getGender();
System.out.println("a11aa: ---> In RenterController genderIndx= " + genderIndx);
String gender = RentalWebsiteConstants.GENDERS[genderIndx];
mv.addObject("gender", gender);
System.out.println("a11b: ---> In RenterController ");
int ethnicityIndx = privateInfo.getEthnicity();
String ethnicity = RentalWebsiteConstants.ETHNICITIES[ethnicityIndx];
mv.addObject("ethnicity", ethnicity);
System.out.println("a11c: ---> In RenterController ");
int creditCardNoExpMonthIndx = privateInfo.getCreditCardNoExpMonth();
String ccExpMonth = RentalWebsiteConstants.MONTHS_SHORT[creditCardNoExpMonthIndx];
mv.addObject("ccExpMonth", ccExpMonth);
System.out.println("a11d1: ---> In RenterController ");
//int creditCardNoExpYearIndx = privateInfo.getCreditCardNoExpYear();
//System.out.println("a11d2: ---> In RenterController creditCardNoExpYearIndx= " + creditCardNoExpYearIndx);
String ccExpYear = privateInfo.getCreditCardNoExpYear().toString();
System.out.println("a11d3: ---> In RenterController ccExpYear= " + ccExpYear);
mv.addObject("ccExpYear", ccExpYear);
System.out.println("a11e: ---> In RenterController ");
// System.out.println("z96: Exiting RenterController showDisplayRenterProfilePage() method privateInfo= " + privateInfo.toString());
// System.out.println("z97: Exiting RenterController showDisplayRenterProfilePage() method genderIndx= " + genderIndx + " | ethnicity= " + ethnicity + " | ccExpMonth= " + ccExpMonth + " | ccExpYear= " + ccExpYear);
System.out.println(
"z98: Exiting RenterController showDisplayRenterProfilePage() method countries= " + countries);
System.out.println("z99: Exiting RenterController showDisplayRenterProfilePage() method statesOrProvinces= "
+ statesOrProvinces + "\n\n");
return mv;
}
// handler method to display the delete renter profile page
@PostMapping("/showDeleteRenterProfilePage")
public ModelAndView showDeleteRenterProfilePage(HttpServletRequest request) {
// TODO -- complete the rest of this method in the future
ModelAndView mv = new ModelAndView();
return mv;
}
// TODO -- finish the delete renter profile processing in the future
}
|
Markdown | UTF-8 | 861 | 2.640625 | 3 | [] | no_license | # x2713
**x2713** is an operating system designed for [Deep Thought](https://en.wikipedia.org/wiki/List_of_minor_The_Hitchhiker%27s_Guide_to_the_Galaxy_characters#Deep_Thought), a fictional computer in [The Hitchhiker's Guide to the Galaxy](https://en.wikipedia.org/wiki/The_Hitchhiker%27s_Guide_to_the_Galaxy).
You can regard **x2713** as a s-expression: `(× 2 7 1 3) = 42`.
## Usage
```
git clone https://github.com/whichxjy/x2713.git
cd x2713
make qemu
```
## Extract from the novel
"You're really not going to like it," observed Deep Thought.
"Tell us!"
"Alright," said Deep Thought. "The Answer to the Great Question..."
"Yes...!"
"Of Life, the Universe and Everything..." said Deep Thought.
"Yes...!"
"Is..." said Deep Thought, and paused.
"Yes...!"
"Is..."
"Yes...!!!...?"
"Forty-two," said Deep Thought, with infinite majesty and calm.
|
C++ | UTF-8 | 1,179 | 3.15625 | 3 | [] | no_license | // -------------------------------------------------------------------
// Author: lfwu
// Date: September-09-2013
// Note:
// Email:zgwulongfei@gmail.com
// Blog:http://blog.csdn.net/hackmind
// -------------------------------------------------------------------
#include <iostream>
#include <string>
#include <map>
using namespace std;
map<char, int> map_word;
void InitWordMap() {
// The vowels are a,e,i,o,u
map_word.insert(make_pair('a', 0));
map_word.insert(make_pair('e', 0));
map_word.insert(make_pair('i', 0));
map_word.insert(make_pair('o', 0));
map_word.insert(make_pair('u', 0));
}
int
main(int argc, char** argv){
// Init the word map, and get the statistics
InitWordMap();
string word;
while(cin>>word) {
char ch = word[0];
char lower = tolower(ch);
auto fiter = map_word.find(lower);
if(fiter == map_word.end()) {
continue;
}
map_word[ch] += 1;
}
// Print the result
decltype(map_word)::iterator iter = map_word.begin();
for(; iter != map_word.end(); ++iter) {
cout<<"the vowels:"<<iter->first<<" count is: "<<iter->second<<endl;
}
return 0;
}
|
C# | UTF-8 | 307 | 2.78125 | 3 | [] | no_license | DataTable dt = new DataTable();
SQLiteConnection cnn = new SQLiteConnection(dbConnection);
cnn.Open();
SQLiteCommand mycommand = new SQLiteCommand(cnn);
mycommand.CommandText = sql;
SQLiteDataAdapter adapter = new SQLiteDataAdapter(mycommand);
adapter.Fill(dt);
cnn.Close();
|
Java | UTF-8 | 6,042 | 2.265625 | 2 | [] | no_license | package com.charlesmadere.android.classygames;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Window;
import com.charlesmadere.android.classygames.models.Person;
import com.charlesmadere.android.classygames.server.Server;
import com.charlesmadere.android.classygames.utilities.FacebookUtilities;
import com.charlesmadere.android.classygames.utilities.Utilities;
import com.facebook.*;
import com.facebook.Request.GraphUserCallback;
import com.facebook.model.GraphUser;
/**
* This class is the app's entry point.
*/
public final class MainActivity extends SherlockActivity
{
public final static int GAME_FRAGMENT_ACTIVITY_REQUEST_CODE_FINISH = 8;
private UiLifecycleHelper uiHelper;
private boolean isResumed = false;
/**
* Used to obtain the current user's Facebook identity.
*/
private AsyncGetFacebookIdentity asyncGetFacebookIdentity;
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_activity);
final Session.StatusCallback sessionStatusCallback = new Session.StatusCallback()
{
@Override
public void call(final Session session, final SessionState state, final Exception exception)
{
onSessionStateChange(session, state);
}
};
uiHelper = new UiLifecycleHelper(this, sessionStatusCallback);
uiHelper.onCreate(savedInstanceState);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onBackPressed()
{
if (isAnAsyncTaskRunning())
{
cancelRunningAnyAsyncTask();
}
else
{
super.onBackPressed();
}
}
@Override
protected void onDestroy()
{
cancelRunningAnyAsyncTask();
isResumed = false;
uiHelper.onDestroy();
super.onDestroy();
}
@Override
protected void onPause()
{
isResumed = false;
uiHelper.onPause();
super.onPause();
}
@Override
protected void onResume()
{
super.onResume();
uiHelper.onResume();
isResumed = true;
final Person whoAmI = Utilities.getWhoAmI(this);
if (whoAmI != null && whoAmI.isValid())
{
startCentralFragmentActivity();
}
}
@Override
protected void onSaveInstanceState(final Bundle outState)
{
uiHelper.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
/**
* Cancels the AsyncRefreshGamesList AsyncTask if it is currently
* running.
*/
private void cancelRunningAnyAsyncTask()
{
if (isAnAsyncTaskRunning())
{
asyncGetFacebookIdentity.cancel(true);
}
}
/**
* @return
* Returns true if an AsyncTask is running.
*/
private boolean isAnAsyncTaskRunning()
{
return asyncGetFacebookIdentity != null;
}
private void onSessionStateChange(final Session session, final SessionState state)
{
if (isResumed)
// only make changes if this activity is visible
{
if (state.equals(SessionState.OPENED))
// if the session state is open, show the authenticated activity
{
// store the user's Facebook Access Token for retrieval later
FacebookUtilities.setAccessToken(this, session.getAccessToken());
asyncGetFacebookIdentity = new AsyncGetFacebookIdentity(this,
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), session, (ViewGroup) findViewById(R.id.main_activity_listview));
asyncGetFacebookIdentity.execute();
}
}
}
private void startCentralFragmentActivity()
{
final Intent intent = new Intent(this, GameFragmentActivity.class);
startActivityForResult(intent, GAME_FRAGMENT_ACTIVITY_REQUEST_CODE_FINISH);
}
private final class AsyncGetFacebookIdentity extends AsyncTask<Void, Void, Person>
{
private Context context;
private LayoutInflater inflater;
private Session session;
private ViewGroup viewGroup;
private AsyncGetFacebookIdentity(final Context context, final LayoutInflater inflater, final Session session,
final ViewGroup viewGroup)
{
this.context = context;
this.inflater = inflater;
this.session = session;
this.viewGroup = viewGroup;
}
@Override
protected Person doInBackground(final Void... params)
{
final Person facebookIdentity = new Person();
if (!isCancelled())
{
Request.newMeRequest(session, new GraphUserCallback()
{
@Override
public void onCompleted(final GraphUser user, final Response response)
{
facebookIdentity.setId(user.getId());
facebookIdentity.setName(user.getName());
}
}).executeAndWait();
Server.gcmPerformRegister(context);
}
return facebookIdentity;
}
private void cancelled()
{
session.closeAndClearTokenInformation();
viewGroup.removeAllViews();
asyncGetFacebookIdentity = null;
finish();
}
@Override
protected void onCancelled()
{
cancelled();
}
@Override
protected void onCancelled(final Person facebookIdentity)
{
cancelled();
}
@Override
protected void onPostExecute(final Person facebookIdentity)
{
if (facebookIdentity.isValid())
{
Utilities.setWhoAmI(context, facebookIdentity);
viewGroup.removeAllViews();
asyncGetFacebookIdentity = null;
startCentralFragmentActivity();
}
else
{
cancelled();
}
}
@Override
protected void onPreExecute()
{
viewGroup.removeAllViews();
inflater.inflate(R.layout.main_activity_loading, viewGroup);
}
}
}
|
Java | UTF-8 | 711 | 1.8125 | 2 | [
"Apache-2.0"
] | permissive | package in.hasirudala.dwcc.server.repository;
import in.hasirudala.dwcc.server.domain.Region;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@RepositoryRestResource(collectionResourceRel = "regions", path = "regions")
public interface RegionRepository extends JpaRepository<Region, Long> {
@RestResource(path = "findAllById", rel = "findAllById")
List<Region> findByIdIn(@Param("ids") Long[] ids);
}
|
PHP | UTF-8 | 1,163 | 2.578125 | 3 | [] | no_license | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStdNursingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('std_nursings', function (Blueprint $table) {
$table->bigIncrements('std_nursing_id');
$table->string('ward', 100);
$table->string('nts', 100);
$table->softDeletes();
$table->foreignId('student_id')->constrained('students', 'student_id');
$table->foreignId('hospital_id')->constrained('gen_hospitals', 'gen_hospital_id');
$table->dateTime("updated_on")->nullable();
$table->unsignedInteger("created_by")->nullable();
$table->unsignedInteger("updated_by")->nullable();
$table->unsignedInteger("deleted_by")->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('std_nursings');
}
}
|
Python | UTF-8 | 1,411 | 3.125 | 3 | [] | no_license | """
CS 221/224N, Stanford University, Summer/Fall 2013
Author: Samir Bajaj (http://www.samirbajaj.com)
You are free to use all or any part of this code, as long as you acknowledge this
contribution by including a reference in your work. This is a student research
project, and no warranties of any kind are implied.
"""
from __future__ import division
from util import Util
class Sentence:
def __init__(self, words, punctuation_re, stopwords, stemmer):
self.length = len(words)
self.sentence = ' '.join(words)
self.words = [w.lower() for w in words if not w.lower() in stopwords]
self.tokens = [punctuation_re.sub(' ', w).strip() for w in self.words]
self.stemmed = [stemmer.stem(t, 0, len(t)-1) for t in (' '.join(self.tokens)).split() if t not in stopwords]
self.score = 0
def __str__(self):
return self.sentence
def __hash__(self):
hash = 31
for w in self.stemmed:
hash = hash * 101 + w.__hash__()
return hash
def __eq__(x, y):
return cmp(x.stemmed, y.stemmed) == 0
def getLength(self):
return self.length
def tfidf(self, tf, df, num_docs):
if len(self.stemmed) == 0:
return 0
if not self.score == 0:
return self.score
for s in self.stemmed:
self.score += Util.tfidf(s, tf, df, num_docs)
return self.score |
Markdown | UTF-8 | 2,986 | 2.734375 | 3 | [] | no_license | # GITHUB-DESKTOP
Buscar en la página de Github el aplicativo [Github Desktop](https://desktop.github.com/) para instalarlo siguiendo el procedimiento habitual.
Vamos a crear una carpeta para una nueva web.
Para ello abrimos el aplicativo de github desktop


Creamos una carpeta

Click en **Create Repository**

Si vamos a la carpeta que nos ha creado en C:\Bitnami\meanstack-3.2.1-0\apps veremos que tenemos la nueva carpeta

Vamos al terminal de Bitnami y vamos a la carpeta que hemos creado (zapatos)

Mediante Yeoman creamos la estructura de la nueva web.
Cuando termine

Vamos al entorno gráfico y comprobamos que nos ha instalado todo el contenido necesario.

También podemos llegar a esta carpeta haciendo btn dr sobre la carpeta zapatos **open in explorer** desde github desktop.
Ahora pulsaremos la opción **publish** que nos aparece en el margen superior derecho.


Si pulsamos en **changes** veremos que nos ha creado la web zapatos.

Ahora sincronizar

Veremos en Github que tenemos la nueva carpeta

El siguiente paso sería arrastrar la carpeta **zapatos** hasta **Sublime text** (es suficiente con arrastrar la carpeta app)

Ahora arrancamos el servidor desde el terminal de Bitnami y ya podemos empezar a trabajar en nuestro proyecto.

Si cuando lo visualizamos en el navegador vemos que nos falta bootstrap hay que volverlo a instalar

Cada vez que queramos trabajar desde otro ordenador, lo primero que hay que hacer es abrir github desktop y clonar la carpeta desde github.
Después tendremos que instalar las carpetas **bower** y **npm** porque estas carpetas no se suben automáticamente.
```bash
$zapatos:bower install
$zapatos:npm install
```
[YEOMAN más info](https://github.com/MARIAEL/YEOMAN/blob/master/README.md)
|
PHP | UTF-8 | 299 | 2.515625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Kuvardin\Firebase\Models;
/**
* Interface RequestModelInterface
*
* @package Kuvardin\Firebase\Models
* @author Maxim Kuvardin <maxim@kuvard.in>
*/
interface RequestModelInterface
{
/**
* @return array
*/
public function getRequestData(): array;
}
|
Markdown | UTF-8 | 1,136 | 3.296875 | 3 | [] | no_license | # Day 21 Code
10550_Combination_lock.cpp
```cpp
#include <stdio.h>
int marks_counter_clockwise (int actual, int next)
{
if (next > actual)
return next - actual;
else
return (40 - actual) + next;
}
int marks_clockwise (int actual, int next)
{
if (next < actual)
return actual - next;
else
return (40 - next) + actual;
}
int main ()
{
int dial, n1, n2, n3, marks_to_degrees = 360/40;
while (scanf("%d %d %d %d", &dial, &n1, &n2, &n3),
dial != 0, n1 != 0, n2 != 0, n3 != 0)
{
printf("%d\n", 1080 +
(marks_clockwise(dial, n1)+ marks_counter_clockwise(n1, n2) + marks_clockwise(n2,n3)) * marks_to_degrees
);
}
}
```
11044_Searching_for_nessy.cpp
```cpp
#include <stdio.h>
int get_number_of_radars_per_direction (int n)
{
return n % 3 == 0 ? n/3 : (n/3) + 1;
}
int main ()
{
int N,n,m, i;
scanf("%d", &N);
while (N --)
{
scanf("%d %d", &n, &m);
printf("%d\n", get_number_of_radars_per_direction(n - 2) * get_number_of_radars_per_direction(m - 2));
}
}
``` |
JavaScript | UTF-8 | 3,824 | 2.8125 | 3 | [] | no_license | // Grid Rendering functions
// Should serve no purpose other than rendering.
// Any required data should be pulled from a public variable or input specifically into its parameters.
// These functions should NEVER call any external functions.
// Renders Grid According to mode.
// Renders Inventory
function gridRenderInv() {
console.log("GRID: Rendering INV");
clearGrid();
for (x=0; x < Object.keys(invJson).length; x++){
contentGrid.innerHTML += `<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
<div class="panel panel-default" id="itemPanel-${invJson[x].itemCode}" onclick="viewItemCard(${x});">
<div class="panel-heading">
<h3 class="panel-title" >
${invJson[x].name}
</h3>
</div>
<img class="img-responsive center-block" src="img/${invJson[x].itemCode}.png" onerror="this.src=\'img/juice.png\'"/>
<div class="panel-body" id="description">
Content Goes Here
</div>
</div>
</div>`;
}
}
function gridRenderInvTEST() {
clearGrid();
for (x=0; x < 100; x++){
contentGrid.innerHTML += `<div class="col-*-2">
<div class="panel panel-default" id="itemPanel-${invJson[0].itemCode}" onclick="alert('You Clicked on ${invJson[0].name}');">
<div class="panel-heading">
<h3 class="panel-title" >
${invJson[0].name}
</h3>
</div>
<img class="img-responsive center-block" src="img/juice.png" />
<div class="panel-body" id="description">
Content Goes Here
</div>
</div>
</div>`;
}
}
// Renders Filter Selection
function gridRenderFilters() {
clearGrid();
contentGrid.innerHTML += `<div class="jumbotron" id="gridJumbotron">
</div>`;
for (x=0; x < Object.keys(responseJson).length; x++) {
document.getElementById("gridJumbotron").innerHTML += `<a invTag="${responseJson[x].name}" onclick="setFilter(this);">${responseJson[x].name}</a><br>`;
}
}
// Renders inventory-add panel
function gridRenderInvAdd(test) {
clearGrid();
contentGrid.innerHTML += `<div class="col-md-7" id="imMenu"></div><br><div class="col-md-4 col-md-offset-1"><div class="panel panel-primary" id="invList"></div></div>`
callAPI(test, "GET", "", function() {
if (this.readyState !== 4) return;
if (this.status !== 200) return;
document.getElementById("imMenu").innerHTML = this.responseText;
});
callAPI("invList.php", "GET", "", function() {
if (this.readyState !== 4) return;
if (this.status !== 200) return;
document.getElementById("invList").innerHTML = this.responseText;
getInvW();
});
}
function gridRenderOptions() {
clearGrid();
callAPI("options.php", "GET", "", function() {
if (this.readyState !== 4) return;
if (this.status !== 200) return;
contentGrid.innerHTML = this.responseText;
});
}
// Renders Error Message In grid-space
function gridRenderMessage(message) {
clearGrid();
contentGrid.innerHTML ="<div class=\"col-sm-8 col-sm-offset-2\"><div class=\"alert alert-danger\" role=\"alert\">"+message+"</div></div>";
}
// Clears Content Grid
function clearGrid() {
contentGrid.innerHTML = "";
}
|
Java | UTF-8 | 1,513 | 2.5 | 2 | [] | no_license | package eRegulation;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import HVAC_Common.*;
//------------------------------------------------------------65|-------------------------93|--------------------------------------------------------------------
public class Z_Initialise_Weather
{
public static void main(String[] args)
{
String utct = "2014-05-04T15:00:00";
//================================================================================================================================
//
// Create Weather Object object
//
try
{
Ctrl_WeatherData weather = new Ctrl_WeatherData();
Long x =weather.dateTimeObtained;
}
catch (Exception e)
{
System.out.println(e);
}
//
//================================================================================================================================
}
public static Long dateTimeFromUTC(String utc)
{
SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
try
{
calendar.setTime(utcFormat.parse(utc));
return calendar.getTimeInMillis();
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0L;
}
}
|
C | UTF-8 | 752 | 2.6875 | 3 | [] | no_license | #include "pathfinder.h"
char **mx_append_city_to_arr(char *string) {
int counter = 0;
int counter_2 = 0;
char *temp_str = mx_strdup(string);
char **array = malloc(2 * 200);
for (int i = 0; i < 2; ++i) {
array[i] = mx_strnew(200);
}
mx_del_all_numbers_and_com(temp_str);
while (*temp_str != '-') {
temp_str++;
counter++;
}
temp_str -= counter;
array[0] = mx_strncpy(array[0], temp_str, counter);
temp_str += counter + 1;
counter++;
while (mx_in_alphabet(*temp_str)) {
temp_str++;
counter_2++;
}
temp_str -= counter_2;
array[1] = mx_strncpy(array[1], temp_str, counter_2);
temp_str -= counter;
mx_strdel(&temp_str);
return array;
}
|
C++ | UTF-8 | 713 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
srand(time(NULL));
int canswer=rand()%100;
int guess=0;
int count=0,cell=99,floor=0;
cout<<canswer<<endl;
string man;
while(guess !=canswer){
count += 1;
man = (count%2 != 0)?("P1"):("P2");
cout<< man << " enter a numer"<<"("<<floor<<"~"<<cell<<")"<<endl;
cin>>guess;
if(guess ==canswer){
cout<<man<<" Win!"<<endl;
break;
}
else if(guess == -1){
break;
}
else if(guess < canswer){
cout<<"Too small!"<<endl;
if(floor<guess)
floor=guess+1;
}
else{
cout<<"Too large"<<endl;
if(guess<cell)
cell=guess-1;
}
}
}
|
C | UTF-8 | 1,965 | 2.9375 | 3 | [] | no_license | /*************************************************************************
> File Name: serv.c
> Author: huangjia
> Mail: 605635529@qq.com
> Created Time: Tue 23 May 2017 11:15:35 PM PDT
************************************************************************/
#include<stdio.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<unistd.h>
#include<strings.h>
#include<netinet/in.h>
#include<string.h>
void usage(const char *str)
{
printf("%s [IP][PORT]\n",str);
}
//./serv 127.0.0.1 8000
int main(int argc ,char *argv[])
{
if(argc != 3)
{
usage(argv[0]);
exit(1);
}
struct sockaddr_in serv_addr,clie_addr;
int listenfd,connectfd;
int ret ;
socklen_t clie_addr_len;
listenfd = socket(AF_INET,SOCK_STREAM,0);
if(listenfd < 0)
{
perror("socket");
exit(2);
}
bzero(&serv_addr,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons( atoi( argv[2] ) );
serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
ret = bind(listenfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
if(ret < 0)
{
perror("bind");
exit(3);
}
ret = listen(listenfd,20);
if(ret < 0)
{
perror("listen");
exit(4);
}
while(1) //服务器一直处于工作状态,但是一次只能针对一个客户服务。
{
clie_addr_len = sizeof(clie_addr);
connectfd = accept(listenfd,(struct sockaddr*)&clie_addr,&clie_addr_len);
if(connectfd < 0)
{
perror("accept");
exit(5);
}
printf("clie ip %s,clie port %d\n",inet_ntoa(clie_addr.sin_addr),ntohs(clie_addr.sin_port));
int n = 0;
char buf[1024] = { 0 } ;
while(1)
{
n = read(connectfd,buf,sizeof(buf)-1); //最多读sizeof(buf)-1,留下一个空间放\0
if(n ==0 )
{
printf("clie quit!\n");
break;
}
else if(n < 0)
{
break;
}
else
{
buf[n] = 0;
printf("client say:%s\n",buf);
write(connectfd,buf,strlen(buf));
}
}
}
close(listenfd);
close(connectfd);
return 0;
}
|
Java | GB18030 | 1,195 | 3.328125 | 3 | [] | no_license | package com.guanzhong.paixu;
public class CountingSort
{
public static void main(String[] args) {
int[] input = {3,3,5,2,0};
int k = 7;
System.out.print("");
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + " ");
}
int[] output = new int[input.length];
countsort(input, output, k);
System.out.print("");
for (int i = 0; i < output.length; i++) {
System.out.print(output[i] + " ");
}
}
public static void countsort(int[] input, int[] output, int k) {
int[] c = new int[k];
int len = c.length;
for (int i = 0; i < len; i++) {
c[i] = 0;
}
for (int i = 0; i < input.length; i++) {
c[input[i]]++;
}
for (int i = 1; i < len; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = input.length - 1; i >= 0; i--) {
output[c[input[i]] - 1] = input[i];
c[input[i]]--;
}
}
}
|
Python | UTF-8 | 338 | 2.515625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | from ..models.heap_object import HeapObject
from .base_heap_object_factory import HeapObjectFactory
class UnknownHeapObjectFactory(HeapObjectFactory):
def get_value(self) -> str:
return self.get_type()
def create(self) -> HeapObject:
return HeapObject(self.get_id(), self.get_type(), self.get_value(), 'basic')
|
Java | UTF-8 | 908 | 1.914063 | 2 | [
"CC0-1.0"
] | permissive | package com.mrlast98.definetlynotminecraft.ilcore;
import com.mrlast98.definetlynotminecraft.DefinitelyNotMinecraft;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.block.Block;
import net.minecraft.block.Material;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public class CoreBlocks {
public static final Block ALTAR = new Block(FabricBlockSettings
.of(Material.METAL)
.strength(50F, 18000000F)
.luminance(15)
.breakByTool(FabricToolTags.SHOVELS, 2)
.requiresTool()
.sounds(BlockSoundGroup.GRASS));
public static void registerBlocks() {
Registry.register(Registry.BLOCK, new Identifier(DefinitelyNotMinecraft.MOD_ID, "altar"), ALTAR);
}
}
|
JavaScript | UTF-8 | 1,313 | 3.140625 | 3 | [] | no_license | /**
* Adapter for the FileSystem
*
* This is an adapter to the file system as a database.
* This class should mimic the other adapters like Blockchain, Distributed Storage, MongoDB, etc.
*/
const Sensors = require('../../sample_data/sensors');
const SensorData = require('../../sample_data/sensor_data');
class FileSystemAdapter {
/**
* Initiate the Class with reading the file system data saved to JSON files
*/
constructor() {
this.sensors = Sensors;
this.sensor_data = SensorData;
}
/**
* Gets all the sensors from the sensors database
* @returns {Promise<any>}
*/
getAllSensors() {
return new Promise(resolve => resolve(this.sensors));
}
/**
* Gets the records for each sensor
* @param {Number|String} sensorId ID of the Sensor
* @returns {Promise<any>}
*/
getSensorRecordsForSensor(sensorId) {
return new Promise(resolve => resolve(
this.sensor_data.filter(s => s.sensor_id.toString() === sensorId.toString()),
));
}
/**
* Gets the count of records for each sensor
* @param {Number|String} sensorId ID of the sensor
* @returns {Promise<any>}
*/
getCountOfRecords(sensorId) {
return new Promise(resolve => resolve(this.getSensorRecordsForSensor(sensorId).length));
}
}
module.exports = FileSystemAdapter;
|
Java | UTF-8 | 420 | 1.703125 | 2 | [] | no_license | package com.bea.dao;
import com.bea.olp.BIZ_APP_INFO_XW;
public interface BIZ_APP_INFO_XWMapper {
int deleteByPrimaryKey(String appNo);
int insert(BIZ_APP_INFO_XW record);
int insertSelective(BIZ_APP_INFO_XW record);
BIZ_APP_INFO_XW selectByPrimaryKey(String appNo);
int updateByPrimaryKeySelective(BIZ_APP_INFO_XW record);
int updateByPrimaryKey(BIZ_APP_INFO_XW record);
} |
C# | UTF-8 | 21,934 | 3.171875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client.Classes.Config
{
/// <summary>
/// 配置信息,采用域-值模型:Field - Values。如:Pixes = 1|2|3|4
/// </summary>
class Config
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private string field;
private string value;
private string[] items;
private bool ok;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// 域
/// </summary>
public string Field
{
set { field = value; }
get { return field; }
}
/// <summary>
/// 值
/// </summary>
public string Value
{
set
{
this.value = value;
if (this.value == null || this.value.Length == 0) { items = new string[0]; return; }
items = this.value.Split('|');
}
get
{
return value;
}
}
/// <summary>
/// 值的每一项
/// </summary>
public string[] Items
{
get
{
return items;
}
set
{
items = value;
if (items == null || items.Length == 0) { this.value = ""; return; }
this.value = Tools.String.Link(items, "|");
}
}
/// <summary>
/// 操作是否成功
/// </summary>
public bool OK
{
set { ok = value; }
get { return ok; }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// 生成一个空的域-值模型。
/// </summary>
public Config()
{
initThis();
}
/// <summary>
/// 读取一行字符串为域-值模型。如:Pixes = 1|2|3|4。
/// </summary>
/// <param name="line">字符串</param>
public Config(string line)
{
initThis();
if (line == null || line.Length == 0) { return; }
int idx = line.IndexOf('=');
if (idx == -1)
{
field = "";
Value = Tools.String.ClearLRSpace(line);
return;
}
string f = line.Substring(0, idx);
string v = line.Substring(idx + 1);
field = Tools.String.ClearLRSpace(f);
value = Tools.String.ClearLRSpace(v);
}
/// <summary>
/// 利用域和值信息构造域-值模型。
/// </summary>
/// <param name="field">域</param>
/// <param name="value">值</param>
public Config(string field, string value)
{
initThis();
if (field == null) { this.field = ""; } else { this.field = Tools.String.ClearLRSpace(field); }
if (value == null) { Value = ""; } else { Value = Tools.String.ClearLRSpace(value); }
}
private void initThis()
{
field = "";
value = "";
items = new string[0];
ok = true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static Config ToThis(string s)
{
return new Config(s);
}
public override string ToString()
{
return (field == null || field.Length == 0) ? value : (field + " = " + value);
}
public void CopyReference(Config c)
{
this.field = c.field;
this.value = c.value;
this.items = c.items;
this.ok = c.ok;
}
public void CopyValue(Config c)
{
CopyReference(c);
items = new string[c.items.Length]; for (int i = 0; i < c.items.Length; i++) { items[i] = c.items[i]; }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public bool AddToTop(string item)
{
if (item == null) { ok = false; return ok; }
string v = item + "|" + value;
Value = v;
ok = true;
return ok;
}
public bool AddToTop(bool item)
{
//if (item == null) { ok = false; return ok; }
string v = (item ? "1" : "0") + "|" + value;
Value = v;
ok = true;
return ok;
}
public bool AddToTop(int item)
{
//if (item == null) { ok = false; return ok; }
string v = item.ToString() + "|" + value;
Value = v;
ok = true;
return ok;
}
public bool AddToTop(long item)
{
//if (item == null) { ok = false; return ok; }
string v = item.ToString() + "|" + value;
Value = v;
ok = true;
return ok;
}
public bool AddToTop(double item)
{
//if (item == null) { ok = false; return ok; }
string v = item.ToString() + "|" + value;
Value = v;
ok = true;
return ok;
}
public bool AddToBottom(string item)
{
if (item == null) { ok = false; return ok; }
string v = value + "|" + item;
Value = v;
ok = true;
return ok;
}
public bool AddToBottom(bool item)
{
//if (item == null) { ok = false; return ok; }
string v = value + "|" + (item ? "1" : "0");
Value = v;
ok = true;
return ok;
}
public bool AddToBottom(int item)
{
//if (item == null) { ok = false; return ok; }
string v = value + "|" + item.ToString();
Value = v;
ok = true;
return ok;
}
public bool AddToBottom(long item)
{
//if (item == null) { ok = false; return ok; }
string v = value + "|" + item.ToString();
Value = v;
ok = true;
return ok;
}
public bool AddToBottom(double item)
{
//if (item == null) { ok = false; return ok; }
string v = value + "|" + item.ToString();
Value = v;
ok = true;
return ok;
}
public bool DeleteFirstItem()
{
if (items == null || items.Length == 0) { ok = false; return false; }
Value = Tools.String.Link(items, "|", 1);
return ok = true;
}
public bool DeleteLastItem()
{
if (items == null || items.Length == 0) { ok = false; return false; }
Value = Tools.String.Link(items, "|", 0, items.Length - 1);
ok = true;
return true;
}
public string GetString_Field()
{
return field;
}
public string GetString()
{
ok = true;
return value;
}
public string GetString(int index)
{
if (items == null) { ok = false; return ""; }
if (index < 0 || index >= items.Length) { ok = false; return ""; }
ok = true;
return items[index];
}
public List<string> GetStringList()
{
if (items == null) { ok = false; return new List<string>(); }
ok = true;
return items.ToList();
}
public bool GetBool_Field()
{
try
{
ok = true;
return int.Parse(field) != 0;
}
catch
{
ok = false;
return false;
}
}
public bool GetBool()
{
try
{
ok = true;
return int.Parse(value) != 0;
}
catch
{
ok = false;
return false;
}
}
public bool GetBool(int index)
{
if (items == null) { ok = false; return false; }
if (index < 0 || index >= items.Length) { ok = false; return false; }
try
{
ok = true;
return int.Parse(items[index]) != 0;
}
catch
{
ok = false;
return false;
}
}
public List<bool> GetBoolList()
{
if (items == null) { ok = false; return new List<bool>(); }
List<bool> res = new List<bool>();
foreach (string s in items)
{
try
{
res.Add(int.Parse(s) != 0);
}
catch
{
ok = false;
return res;
}
}
return res;
}
public int GetInt_Field()
{
try
{
ok = true;
return int.Parse(field);
}
catch
{
ok = false;
return 0;
}
}
public int GetInt()
{
try
{
ok = true;
return int.Parse(value);
}
catch
{
ok = false;
return 0;
}
}
public int GetInt(int index)
{
if (items == null) { ok = false; return 0; }
if (index < 0 || index >= items.Length) { ok = false; return 0; }
try
{
ok = true;
return int.Parse(items[index]);
}
catch
{
ok = false;
return 0;
}
}
public List<int> GetIntList()
{
if (items == null) { ok = false; return new List<int>(); }
List<int> res = new List<int>();
foreach (string s in items)
{
try
{
res.Add(int.Parse(s));
}
catch
{
ok = false;
return res;
}
}
return res;
}
public long GetLong_Field()
{
try
{
ok = true;
return long.Parse(field);
}
catch
{
ok = false;
return 0;
}
}
public long GetLong()
{
try
{
ok = true;
return long.Parse(value);
}
catch
{
ok = false;
return 0;
}
}
public long GetLong(int index)
{
if (items == null) { ok = false; return 0; }
if (index < 0 || index >= items.Length) { ok = false; return 0; }
try
{
ok = true;
return long.Parse(items[index]);
}
catch
{
ok = false;
return 0;
}
}
public List<long> GetLongList()
{
if (items == null) { ok = false; return new List<long>(); }
List<long> res = new List<long>();
foreach (string s in items)
{
try
{
res.Add(long.Parse(s));
}
catch
{
ok = false;
return res;
}
}
return res;
}
public double GetDouble_Field()
{
try
{
ok = true;
return double.Parse(field);
}
catch
{
ok = false;
return 0;
}
}
public double GetDouble()
{
try
{
ok = true;
return double.Parse(value);
}
catch
{
ok = false;
return 0;
}
}
public double GetDouble(int index)
{
if (items == null) { ok = false; return 0; }
if (index < 0 || index >= items.Length) { ok = false; return 0; }
try
{
ok = true;
return double.Parse(items[index]);
}
catch
{
ok = false;
return 0;
}
}
public List<double> GetDoubleList()
{
if (items == null) { ok = false; return new List<double>(); }
List<double> res = new List<double>();
foreach (string s in items)
{
try
{
res.Add(double.Parse(s));
}
catch
{
ok = false;
return res;
}
}
return res;
}
public string FetchFirst_String()
{
if (items == null || items.Length == 0) { ok = false; return ""; }
string s = GetString(0);
if (ok) { DeleteFirstItem(); }
return s;
}
public bool FetchFirst_Bool()
{
if (items == null || items.Length == 0) { ok = false; return false; }
bool b = GetBool(0);
if (ok) { DeleteFirstItem(); }
return b;
}
public int FetchFirst_Int()
{
if (items == null || items.Length == 0) { ok = false; return 0; }
int s = GetInt(0);
if (ok) { DeleteFirstItem(); }
return s;
}
public long FetchFirst_Long()
{
if (items == null || items.Length == 0) { ok = false; return 0; }
long s = GetLong(0);
if (ok) { DeleteFirstItem(); }
return s;
}
public double FetchFirst_Double()
{
if (items == null || items.Length == 0) { ok = false; return 0; }
double s = GetDouble(0);
if (ok) { DeleteFirstItem(); }
return s;
}
public string FetchLast_String()
{
if (items == null || items.Length == 0) { ok = false; return ""; }
string s = GetString(items.Length - 1);
if (ok) { DeleteLastItem(); }
return s;
}
public bool FetchLast_Bool()
{
if (items == null || items.Length == 0) { ok = false; return false; }
bool b = GetBool(items.Length - 1);
if (ok) { DeleteLastItem(); }
return b;
}
public int FetchLast_Int()
{
if (items == null || items.Length == 0) { ok = false; return 0; }
int s = GetInt(items.Length - 1);
if (ok) { DeleteLastItem(); }
return s;
}
public long FetchLast_Long()
{
if (items == null || items.Length == 0) { ok = false; return 0; }
long s = GetLong(items.Length - 1);
if (ok) { DeleteLastItem(); }
return s;
}
public double FetchLast_Double()
{
if (items == null || items.Length == 0) { ok = false; return 0; }
double s = GetDouble(items.Length - 1);
if (ok) { DeleteLastItem(); }
return s;
}
public void SetField(string field)
{
this.field = field;
ok = true;
}
public void SetField(bool field)
{
this.field = field ? "1" : "0";
ok = true;
}
public void SetField(int field)
{
this.field = field.ToString();
ok = true;
}
public void SetField(long field)
{
this.field = field.ToString();
ok = true;
}
public void SetField(double field)
{
this.field = field.ToString();
ok = true;
}
public void SetValue(string value)
{
this.value = value;
ok = true;
}
public void SetValue(bool value)
{
this.value = value ? "1" : "0";
ok = true;
}
public void SetValue(int value)
{
this.value = value.ToString();
ok = true;
}
public void SetValue(long value)
{
this.value = value.ToString();
ok = true;
}
public void SetValue(double value)
{
this.value = value.ToString();
ok = true;
}
public void SetValue(List<string> value)
{
if (value == null) { ok = false; return; }
this.Items = value.ToArray();
ok = true;
}
public void SetValue(List<bool> value)
{
if (value == null) { ok = false; return; }
List<string> items = new List<string>();
foreach (bool i in value)
{
items.Add(i ? "1" : "0");
}
ok = true;
SetValue(items);
}
public void SetValue(List<int> value)
{
if (value == null) { ok = false; return; }
List<string> items = new List<string>();
foreach (int i in value)
{
items.Add(i.ToString());
}
ok = true;
SetValue(items);
}
public void SetValue(List<long> value)
{
if (value == null) { ok = false; return; }
List<string> items = new List<string>();
foreach (int i in value)
{
items.Add(i.ToString());
}
ok = true;
SetValue(items);
}
public void SetValue(List<double> value)
{
if (value == null) { ok = false; return; }
List<string> items = new List<string>();
foreach (int i in value)
{
items.Add(i.ToString());
}
ok = true;
SetValue(items);
}
public void SetItem(int index, string item)
{
if (item == null) { ok = false; return; }
if (items == null) { ok = false; return; }
if (index < 0 || index >= items.Length) { ok = false; return; }
string[] temp = items;
temp[index] = item;
Items = temp;
ok = true;
}
public void SetItem(int index, bool item)
{
//if (item == null) { ok = false; return; }
if (items == null) { ok = false; return; }
if (index < 0 || index >= items.Length) { ok = false; return; }
string[] temp = items;
temp[index] = item ? "1" : "0";
Items = temp;
ok = true;
}
public void SetItem(int index, int item)
{
//if (item == null) { ok = false; return; }
if (items == null) { ok = false; return; }
if (index < 0 || index >= items.Length) { ok = false; return; }
string[] temp = items;
temp[index] = item.ToString();
Items = temp;
ok = true;
}
public void SetItem(int index, long item)
{
//if (item == null) { ok = false; return; }
if (items == null) { ok = false; return; }
if (index < 0 || index >= items.Length) { ok = false; return; }
string[] temp = items;
temp[index] = item.ToString();
Items = temp;
ok = true;
}
public void SetItem(int index, double item)
{
//if (item == null) { ok = false; return; }
if (items == null) { ok = false; return; }
if (index < 0 || index >= items.Length) { ok = false; return; }
string[] temp = items;
temp[index] = item.ToString();
Items = temp;
ok = true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
|
C | UTF-8 | 143 | 2.84375 | 3 | [] | no_license | void linspace(float begin,float end,int n,float p[])
{
int i;
p[0]=begin;
for(i=1;i<n-1;i++)
p[i]=begin+(end-begin)/(n-1)*i;
p[i]=end;
}
|
Markdown | UTF-8 | 1,591 | 2.5625 | 3 | [] | no_license | ## npm install
## Getting Started
First, run the development server:
```bash
npm run dev
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
```
### 미해결 내용
> > mobx를 적용해서 과제를 마무리 하지 못할 것 같아서 mobx보다 익순한 redux로 진행 했습니다.\
> > 각 버튼에 대한 기능들은(사고이력 선택, 사고이력 내용, 제조사 선택, 가격 입력, 초기화, 임시저장 했을 때, snackbar open) 기능완료 했으나, 임시저장을 했을 때, axios 요청 기능 미완료 됐습니다.
> >
> > > \*임시저장 버튼을 누르면 서버에 post 요청을 보낸면, middleware에서 캐치하여 isLoading이라는 값을 redux에 만들고 isLoading
> > > 값이 true면 spindle을 띄우고 서버에서 응답에 따라 성공과 에러 분기로 나눠서 관리해야 할 것 같습니다.
> > > 성공이면 snackbar를 띄우고 아니면 에러메세지를 띄우면 될 것 같습니다.
> > 다중 사진올리기 기능에 대해서 도전하다가 미완료 된 상태 입니다.
> >
> > > \*post 요청을 보내면 middleware에서 캐치하여 isLoading이라는 값을 redux에 만들고 isLoading 값이 true면
> > > spindle을 띄우고 서버에서 응답에 따라 성공과 에러 분기로 나눠서 관리해야 할 것 같습니다.
> > > 성공이면 redux store에 배열형태로 저장을 하고 data && data.map(item => <img src={item.url}/>) 방식으로 화면을 만들면 될것같습니다.
> > vercel 배포까지 진행하지 못했습니다.
|
Java | UTF-8 | 3,729 | 2.3125 | 2 | [] | no_license | /**
* Project Name: itee
* File Name: JsonProductTypeDetail.java
* Package Name: cn.situne.itee.manager.jsonentity
* Date: 2015-03-23
* Copyright (coffee) 2015, itee@kenes.com.cn All Rights Reserved.
*
*/
package cn.situne.itee.manager.jsonentity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import cn.situne.itee.common.constant.JsonKey;
import cn.situne.itee.common.utils.Utils;
/**
* ClassName:JsonProductTypeDetail <br/>
* Function: To set product type detail. <br/>
* Date: 2015-03-23 <br/>
*
* @author Luochao
* @version 1.0
* @see
*/
public class JsonProductTypeDetail extends BaseJsonObject implements Serializable {
private List<ProductTypeDetail> dataList;
public List<ProductTypeDetail> getDataList() {
return dataList;
}
public void setDataList(List<ProductTypeDetail> dataList) {
this.dataList = dataList;
}
public JsonProductTypeDetail(JSONObject jsonObject) {
super(jsonObject);
}
@Override
public void setJsonValues(JSONObject jsonObj) {
super.setJsonValues(jsonObj);
dataList = new ArrayList();
try {
JSONArray joDataList = Utils.getArrayFromJsonObjectWithKey(jsonObj, JsonKey.COMMON_DATA_LIST);
for (int i = 0; i < joDataList.length(); i++) {
JSONObject jsonObject = joDataList.getJSONObject(i);
ProductTypeDetail bean = new ProductTypeDetail();
bean.setReturnTime(Utils.getStringFromJsonObjectWithKey(jsonObject, JsonKey.SHOP_05_RETURN_TIME));
bean.setReserveStatus(Utils.getIntegerFromJsonObjectWithKey(jsonObject, JsonKey.SHOP_05_RESERVE_STATUS));
bean.setEnableSubclassStatus(Utils.getIntegerFromJsonObjectWithKey(jsonObject, JsonKey.SHOP_05_ENABLE_SUBCLASS_STATUS));
bean.setPrice(Utils.getDoubleFromJsonObjectWithKey(jsonObject, JsonKey.SHOP_05_PRICE));
bean.setQty(Utils.getIntegerFromJsonObjectWithKey(jsonObject, JsonKey.SHOP_05_QTY));
bean.setCode(Utils.getStringFromJsonObjectWithKey(jsonObject, JsonKey.SHOP_05_CODE));
dataList.add(bean);
}
} catch (JSONException e) {
Utils.log(e.getMessage());
}
}
class ProductTypeDetail implements Serializable {
private String returnTime;
private int reserveStatus;
private int enableSubclassStatus;
private double price;
private int qty;
private String code;
public String getReturnTime() {
return returnTime;
}
public void setReturnTime(String returnTime) {
this.returnTime = returnTime;
}
public int getReserveStatus() {
return reserveStatus;
}
public void setReserveStatus(int reserveStatus) {
this.reserveStatus = reserveStatus;
}
public int getEnableSubclassStatus() {
return enableSubclassStatus;
}
public void setEnableSubclassStatus(int enableSubclassStatus) {
this.enableSubclassStatus = enableSubclassStatus;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
}
|
Python | UTF-8 | 4,713 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | import pytest
import copy
from pysettings.base import BaseSettings
from pysettings.options import Option
from pysettings.exceptions import OptionNotAvailable, ConfigNotValid
def test_config_constructor():
"""Should contain options registry only for attributes of type Option"""
class SettingsTest(BaseSettings):
home = Option()
url = Option()
objects = []
config = SettingsTest()
assert sorted(config._options) == ["home", "url"]
def test_config_set_value():
"""Should set the underlying Option value"""
class SettingsTest(BaseSettings):
home = Option()
config = SettingsTest()
config.home = "test"
option = config._get_option("home")
assert option.value == "test"
def test_config_get_value():
"""Should get the underlying Option value"""
class SettingsTest(BaseSettings):
home = Option()
config = SettingsTest()
option = config._get_option("home")
option.value = "test"
assert config.home == "test"
def test_config_instance():
"""Should return a new instance of the config and not use the Class options"""
class SettingsTest(BaseSettings):
home = Option(default="klass")
config = SettingsTest()
config.home = "instance"
assert SettingsTest.home.value == "klass"
assert config.home == "instance"
def test_config_set_value_not_available():
"""Should raise an exception if the option is not present"""
class SettingsTest(BaseSettings):
pass
config = SettingsTest()
with pytest.raises(OptionNotAvailable):
config.test = "test"
def test_config_get_value_not_available():
"""Should raise an exception if the option is not present"""
class SettingsTest(BaseSettings):
pass
config = SettingsTest()
with pytest.raises(OptionNotAvailable):
config.test
def test_config_is_valid_all_options(mocker):
"""Should validate all Option attributes"""
class SettingsTest(BaseSettings):
option1 = Option()
option2 = Option()
config = SettingsTest()
option1 = config._get_option("option1")
option2 = config._get_option("option2")
# Mock config options
mocker.patch.object(option1, "_validate", return_value=(True, []))
mocker.patch.object(option2, "_validate", return_value=(True, []))
config.is_valid()
assert option1._validate.call_count == 1
assert option2._validate.call_count == 1
def test_config_is_valid(mocker):
"""Should return a success if the configuration is valid"""
class SettingsTest(BaseSettings):
home = Option()
config = SettingsTest()
option = config._get_option("home")
# Mock config options
mocker.patch.object(option, "_validate", return_value=(True, []))
assert config.is_valid() == (True, [])
def test_config_is_not_valid(mocker):
"""Should return a failure if the configuration is not valid and raise_exception is False"""
class SettingsTest(BaseSettings):
home = Option()
config = SettingsTest()
option = config._get_option("home")
# Mock config options
mocker.patch.object(
option, "_validate", return_value=(False, ["allow_null", "validator"])
)
assert config.is_valid(raise_exception=False) == (
False,
[{"home": ["allow_null", "validator"]}],
)
def test_config_is_not_valid_exception(mocker):
"""Should raise an exception if the configuration is not valid and raise_exception is True"""
class SettingsTest(BaseSettings):
home = Option()
config = SettingsTest()
option = config._get_option("home")
# Mock config options
mocker.patch.object(option, "_validate", return_value=(False, ["validator"]))
with pytest.raises(ConfigNotValid):
assert config.is_valid()
def test_config_deepcopy():
"""Should clone the configuration when deepcopy() is called"""
class SettingsTest(BaseSettings):
home = Option(default="original")
config = SettingsTest()
clone_config = copy.deepcopy(config)
clone_config.home = "clone"
# Should be different Settings
assert config != clone_config
assert config.home == "original"
assert clone_config.home == "clone"
def test_config_copy():
"""Should clone the configuration when copy() is called"""
class SettingsTest(BaseSettings):
home = Option(default="original")
config = SettingsTest()
clone_config = copy.copy(config)
clone_config.home = "shallow-copy"
# Should be different Settings but same Option (shallow copy)
assert config != clone_config
assert config.home == "shallow-copy"
assert clone_config.home == "shallow-copy"
|
Markdown | UTF-8 | 9,394 | 2.546875 | 3 | [
"Unlicense"
] | permissive |
# حماس: ندعم جهود تحقيق الوحدة وترتيب البيت الفلسطيني
Published at: **2019-11-02T07:14:00+00:00**
Author: ****
Original: [وكالة سوا الإخبارية](https://palsawa.com/post/232508/%D8%AD%D9%85%D8%A7%D8%B3-%D9%86%D8%AF%D8%B9%D9%85-%D8%AC%D9%87%D9%88%D8%AF-%D8%AA%D8%AD%D9%82%D9%8A%D9%82-%D8%A7%D9%84%D9%88%D8%AD%D8%AF%D8%A9-%D9%88%D8%AA%D8%B1%D8%AA%D9%8A%D8%A8-%D8%A7%D9%84%D8%A8%D9%8A%D8%AA-%D8%A7%D9%84%D9%81%D9%84%D8%B3%D8%B7%D9%8A%D9%86%D9%8A)
جددت حركة حماس في الذكرى الثانية بعد المائة لوعد بلفور دعمها لكل الجهود الهادفة إلى تحقيق الوحدة الفلسطينية وترتيب البيت الفلسطيني، على قاعدة الشراكة لمواجهة التحديات التي تحدق بالقضية الفلسطينية، ومشاريع تصفيتها، كما تؤكد جهوزيتها التامة لخوض وإنجاح العملية الديمقراطية، وإجراء الانتخابات الشاملة في الضفة و غزة و القدس لصياغة حالة فلسطينية جديدة ترعى مصالح شعبنا وقادرة على تحقيق طموحاته.
نص البيان كما ورد وكالة سوا الاخبارية
بيان صادر عن
حركة المقاومة الإسلامية "حماس"
في الذكرى الثانية بعد المائة لوعد بلفور المشؤوم
مقاومتنا مستمرة، وكل الوعود والصفقات والمؤامرات لن تمر
تمر ذكرى وعد بلفور الــ 102 على شعبنا الفلسطيني، وما زال يعاني الظلم والاضطهاد والعدوان المستمر ضد أرضه المحتلة، ومقدساته المسلوبة، وضد شعبه المشتت في مخيمات اللجوء، حيث يمارس الكيان الصهيوني أبشع الجرائم والانتهاكات ضد شعبنا الفلسطيني، من قتل وتشريد وحصار واعتقال وهدم وتدمير للبيوت والمؤسسات منذ إقامة كيانه الصهيوني المزعوم عام 1948م على أنقاض قرى شعبنا ومخيماته ومدنه بسبب الوعد الظالم المشؤوم من وزير خارجية بريطانيا الهالك بلفور، الذي مكّن العصابات الصهيونية من أرضنا الفلسطينية.
إن الحكومة البريطانية التي منحت هذا الوعد الظالم للصهاينة، سببت مأساة ومعاناة على مدار عقود من الزمن عاشها شعبنا الفلسطيني العظيم، وما زال حتى يومنا هذا، وإن من نتائج ومحصلات هذا الوعد الزائف الإعلان المرتقب لما يسمى ب صفقة القرن التي يرفضها شعبنا بأكمله، فوعد بلفور غير جائز قانونيًا، ويتناقض مع كل الأعراف الإنسانية والقوانين الدولية؛ وهو ما يتوجب على بريطانيا التراجع عنه، والاعتذار لشعبنا الفلسطيني عمّا سببه له من كوارث ومجازر على مدار ما يزيد على قرن من الزمان.
لقد واجه شعبنا الفلسطيني العظيم ومنذ وعد بلفور المشؤوم عام 1917م، واحتلال الكيان الصهيوني أرضه منذ عام 1948م وحتى يومنا كل أشكال العدوان، وأكد على مر التاريخ، ورغم الكثير من المحطات الدموية والمؤلمة والكثير من القرارات الباطلة والمؤامرات الدولية، تمسكه بوطنه فلسطين، وأنها لا تزال تسكن قلبه وروحه، ولديه الاستعداد للتضحية من أجل حريته واستقلاله، وأنه لا يمكن بحال من الأحوال أن يتخلى عن ذرة تراب منها، ووقف صامدًا ثابتًا مقاومًا، ولم تنجح كل المؤامرات والاتفاقيات الانهزامية من النيل من إرادته الصلبة، وكسر صموده الأسطوري، وإسقاط حقوقه العادلة رغم محاولات التطبيع مع الكيان الصهيوني، والهرولة نحوه لإضفاء شرعية زائفة عليه.
تأتي ذكرى وعد بلفور المشؤوم ومدينة القدس تتعرض لأشرس المحاولات الصهيونية لتهويدها، وتغيير معالمها، والاستيلاء على المسجد الأقصى الذي يواصل جنود الاحتلال وقطعان المستوطنين اقتحامه وتدنيسه، وإغلاق أبوابه، والاعتداء على المرابطين والمرابطات فيه، وطرد المصلين من ساحاته.
إننا في حركة المقاومة الإسلامية "حماس" وفي هذه الذكرى الأليمة بحق شعبنا نؤكد على:
أولاً: إن وعد بلفور الغادر الذي أسس لمأساة القرن، وأوجد أكبر مظلمة تاريخية ما زالت قائمة، وأنشأ كيانًا إحلاليًا صهيونيًا على أرضنا الفلسطينية، وبدعم من بريطانيا التي خولت لنفسها الحق في أن تتصرف في أرض شعبنا ومقدراته - هو وعد باطل منذ إطلاقه، وسرقة للتاريخ، ولحقوق شعبنا، وهي من تتحمل الكوارث والمآسي التي حلت بشعبنا بسببه.
ثانيًا: نحيي الأصوات الحرة التي صدحت في اجتماع الأمم المتحدة في الدورة الرابعة والسبعين، والتي أعلنت تضامنها مع شعبنا الفلسطيني، وأرضه المحتلة، وأنصفت شعبنا بالاعتراف بحقه في إقامة دولته واسترداد حقوقه، كما ندعو كل دول العالم أن تحذو حذوها في إنهاء الاحتلال ورحيله عن أرضنا.
ثالثًا: سيبقى شعبنا الفلسطيني متمسكًا بالمقاومة بكل أشكالها، وفي مقدمتها المقاومة المسلحة لمواجهة الاحتلال الصهيوني، وجرائمه البشعة بحق شعبنا، حتى تحقيق أهدافه المنشودة بالحرية والاستقلال.
رابعًا: إن محاولات التطبيع مع الكيان الصهيوني المغتصب لأرضنا مرفوضة بكل أشكالها، وهي خذلان لشعبنا الفلسطيني، وطعنة غادرة لتضحياته الجسام، ولا يمكن أن تمنح أي شرعية لهذا الكيان المسخ.
خامسًا: تجدد الحركة دعمها لكل الجهود الهادفة إلى تحقيق الوحدة الفلسطينية وترتيب البيت الفلسطيني، على قاعدة الشراكة لمواجهة التحديات التي تحدق بالقضية الفلسطينية، ومشاريع تصفيتها، كما تؤكد جهوزيتها التامة لخوض وإنجاح العملية الديمقراطية، وإجراء الانتخابات الشاملة في الضفة وغزة والقدس لصياغة حالة فلسطينية جديدة ترعى مصالح شعبنا وقادرة على تحقيق طموحاته.
سادسًا: حق عودة اللاجئين الفلسطينيين إلى ديارهم وأوطانهم التي هجروا منها هو حق شرعي وقانوني ثابت، ومكفول بالقوانين الدولية، والقرارات الأممية، ولا تراجع عنه ولا تفريط فيه أو المساومة عليه.
سابعًا: نحيي كل أبناء شعبنا الفلسطيني في كل أماكن تواجده، في الضفة الغربية والقدس وغزة وال48 والشتات والمهاجر، على هذا الثبات الأسطوري، والنضال الملحمي لدحر الاحتلال وعودة أرضنا فلسطين مستقلة وعاصمتها القدس، كما نحيي جموع المرابطين والمرابطات في المسجد الأقصى المبارك وعلى بواباته، وفي مدينة القدس المحتلة، ونعتبر القدس قلب فلسطين النابض، وجوهر الصراع الحقيقي مع هذا المحتل الغاشم.
ثامنًا: تعتبر مسيرات العودة وكسر الحصار أيقونة في العمل الوطني المشترك مع الفصائل الفلسطينية ومجموع شعبنا، وامتدادًا لمشواره الكفاحي الطويل، وقد شكلت تضحيات شعبنا وإرادته العظيمة خطوة متقدمة في مواجهة مشاريع تصفية قضيته العادلة، وإسقاط ما يسمى بصفقة القرن، وإسقاط وعد بلفور، وهو ما يتطلب تعزيز عوامل القوة والصمود، وتحشيد كل طاقات الأمة لدعمه، والوقوف إلى جانبه حتى تحرير أرضه ومقدساته.
حركة المقاومة الإسلامية "حماس"
السبت: 2 نوفمبر 2019م
|
C# | UTF-8 | 1,447 | 3 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ChaperoneServiceMonitor
{
public static class Crypt
{
public static string DecryptString(byte[] data)
{
byte[] bytes = Crypt.Decrypt(data);
return Encoding.Unicode.GetString(bytes);
}
private static byte[] Decrypt(byte[] data)
{
byte[] key = new byte[]
{
117,
37,
145,
84,
164,
99,
32,
73,
153,
188,
105,
20,
93,
55,
214,
47,
131,
145,
122,
128,
14,
137,
58,
163
};
return Crypt.EncryptOutput(key, data).ToArray<byte>();
}
private static byte[] EncryptInitalize(byte[] key)
{
byte[] array = (from i in Enumerable.Range(0, 256)
select (byte)i).ToArray<byte>();
int j = 0;
int num = 0;
while (j < 256)
{
num = (num + (int)key[j % key.Length] + (int)array[j] & 255);
Crypt.Swap(array, j, num);
j++;
}
return array;
}
private static IEnumerable<byte> EncryptOutput(byte[] key, IEnumerable<byte> data)
{
byte[] s = Crypt.EncryptInitalize(key);
int i = 0;
int j = 0;
return data.Select(delegate(byte b)
{
i = (i + 1 & 255);
j = (j + (int)s[i] & 255);
Crypt.Swap(s, i, j);
return b ^ s[(int)(s[i] + s[j] & byte.MaxValue)];
});
}
private static void Swap(byte[] s, int i, int j)
{
byte b = s[i];
s[i] = s[j];
s[j] = b;
}
}
}
|
JavaScript | UTF-8 | 2,216 | 2.53125 | 3 | [] | no_license | (function () {
'use strict';
app.factory('leaveService', leaveService);
leaveService.$inject = ['$http','$rootScope'];
function leaveService($http,$rootScope) {
var service = {};
service.viewAllLeaves = viewAllLeaves;
service.addLeaveInfo = addLeaveInfo;
service.viewLeaves = viewLeaves;
service.AcceptLeave = AcceptLeave;
service.RejectLeave = RejectLeave;
return service;
function viewLeaves() {
return $http.get('http://emp.azurewebsites.net/api/UserLeaves/').then(handleSuccess, handleError('Error getting all users'));
}
function viewAllLeaves() {
return $http.get('http://emp.azurewebsites.net/api/UserLeaves/').then(handleSuccess, handleError('Error getting all users'));
}
function addLeaveInfo(leave) {
return $http({
url: 'http://emp.azurewebsites.net/api/UserLeaves',
method: "POST",
data: leave,
headers: { 'Content-Type': 'application/json' }
}).then(handleSuccess, handleError('Error Creating a leave'));
}
function AcceptLeave(Form) {
Form.status="Accepted"
return $http({
url: 'http://emp.azurewebsites.net/api/UserLeaves/' + Form.formId,
method: "PUT",
data: Form,
headers: { 'Content-Type': 'application/json' }
}).then(handleSuccess, handleError('Error in accpeting leaves'));
}
function RejectLeave(Form) {
Form.status = "Rejected"
return $http({
url: 'http://emp.azurewebsites.net/api/UserLeaves/' + Form.formId,
method: "PUT",
data: Form,
headers: { 'Content-Type': 'application/json' }
}).then(handleSuccess, handleError('Error in accpeting leaves'));
}
function handleSuccess(res) {
return res;
}
function handleError(error) {
return function () {
return { success: false, message: error };
};
}
}
})();
|
SQL | UTF-8 | 1,824 | 4.28125 | 4 | [
"MIT"
] | permissive | """
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| sale_date | date |
| fruit | enum |
| sold_num | int |
+---------------+---------+
(sale_date,fruit) is the primary key for this table.
This table contains the sales of "apples" and "oranges" sold each day.
Write an SQL query to report the difference between number of apples and oranges sold each day.
Return the result table ordered by sale_date in format ('YYYY-MM-DD').
The query result format is in the following example:
Sales table:
+------------+------------+-------------+
| sale_date | fruit | sold_num |
+------------+------------+-------------+
| 2020-05-01 | apples | 10 |
| 2020-05-01 | oranges | 8 |
| 2020-05-02 | apples | 15 |
| 2020-05-02 | oranges | 15 |
| 2020-05-03 | apples | 20 |
| 2020-05-03 | oranges | 0 |
| 2020-05-04 | apples | 15 |
| 2020-05-04 | oranges | 16 |
+------------+------------+-------------+
Result table:
+------------+--------------+
| sale_date | diff |
+------------+--------------+
| 2020-05-01 | 2 |
| 2020-05-02 | 0 |
| 2020-05-03 | 20 |
| 2020-05-04 | -1 |
+------------+--------------+
Day 2020-05-01, 10 apples and 8 oranges were sold (Difference 10 - 8 = 2).
Day 2020-05-02, 15 apples and 15 oranges were sold (Difference 15 - 15 = 0).
Day 2020-05-03, 20 apples and 0 oranges were sold (Difference 20 - 0 = 20).
Day 2020-05-04, 15 apples and 16 oranges were sold (Difference 15 - 16 = -1).
Solution:
GROUP + SUM CASE
"""
SELECT sale_date, SUM(
CASE
WHEN fruit = 'apples'
THEN sold_num
ELSE -sold_num
END
) as diff
FROM Sales
GROUP BY sale_date |
Python | UTF-8 | 3,307 | 2.640625 | 3 | [] | no_license | # encoding:utf-8
from chenyao.supermarket.db import member
class Members:
@classmethod
def show_members(self):
# out_all = '编号\t\t手机号\t折扣\t积分\n'
# for mem in members:
# out_all += "%s\t%s\t%s\t%s\n" % (mem['id'], mem['tel'], mem['disc'], mem['score'])
# return out_all
members_dic = {
'members': member.members
}
return members_dic
@classmethod
def show_members_tel(cls, tel):
members_list = []
for mem in member.members:
if mem['tel'] == tel:
members_list.append(mem)
break
elif mem['tel'].endswith(tel):
members_list.append(mem)
target_members = {
'count': len(members_list),
'members': members_list
}
return target_members
@classmethod
def show_members_uid(cls, uid):
members_list = []
for mem in member.members:
if mem['uid'] == uid:
members_list.append(mem)
break
target_uid = {
'return_code': 200,
'msg_uid': 'return uid succes',
'members': members_list
}
return target_uid
@classmethod
def add_member(cls, tel):
new_member = {'tel': tel, 'disc': 1, 'score': 0}
new_member['uid'] = str(len(member.members) + 1)
member.members.append(new_member)
return new_member
@classmethod
def update_member(cls, uid, new_member_info):
# 根据uid,以及传入的new_member-info对现有用户信息进行修改
for i in range(len(member.members)):
if member.members[i]['uid'] == uid:
for key in new_member_info.keys():
member.members[i][key] = new_member_info[key]
return member.members[i]
return {}
@classmethod
def update_member_score(cls,uid,score):
for i in range(len(member.members)):
if member.members[i]['uid'] == uid:
score_before=member.members[i]['score']
score_after =score_before + int(score)
member.members[i]['score']=score_after
tet_dict={
'uid':member.members[i]['uid'],
'tel':member.members[i]['tel'],
'score_before':score_before,
'score_after' :score_after,
'score_change':score
}
return tet_dict
@classmethod
def inactive_member(cls,uid):
for i in range(len(member.members)):
if member.members[i]['uid'] == uid:
member.members[i]['active'] ='0'
tet_dict = {
'uid': member.members[i]['uid'],
'tel': member.members[i]['tel'],
'active': '0',
'discount': 1,
}
return tet_dict
@classmethod
def filter_member_by_score(cls,score):
member_list=[]
for mem in member.members:
if str(mem['score'])>=score:
member_list.append(mem)
tet_dict={
'count':len(member_list),
'members':member_list
}
return tet_dict
|
Java | UTF-8 | 394 | 2.875 | 3 | [] | no_license | public class Premium extends Basic {
private int nr_P;
public Premium(String name, int nr_B, int nr_P) {
super(name, nr_B);
this.nr_P = nr_P;
}
@Override
public String decrement() {
if (this.nr_P == 0) {
return super.decrement();
} else {
this.nr_P--;
return "Premium";
}
}
} |
Python | UTF-8 | 3,128 | 2.59375 | 3 | [] | no_license | import urllib.request,urllib.error,urllib.parse
import json
import time
import subprocess
import sys
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
install('paramiko')
ssh = urllib.request.urlopen("https://gist.githubusercontent.com/dufferzafar/8068684e2914bb08ed9d10f3764aacce/raw/f0f651c00096199a278b001323103d42cd7f1b5f/IIT%2520D%2520-%2520Citadel.json")
json = json.loads(ssh.read())
timeline = [json]
tags = list(json.keys())
import paramiko
from scp import SCPClient
host = "col100.iitd.ac.in"
port = 22
username = input("TELL YOUR IITD USERNAME(eg cs1190000): ")
password = input("Enter your kerberos password(Don't worry it's safe): ")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
print("\n")
print("JUST DOME INFO:")
print("CAN GO BACK USING COMMAND ----> BACK")
print("JUST ONE DAY OLD PROGRAM SO FULL OF BUGS")
print("FAIR USE IS MUCH APPRECIATED")
print("IT IS OPEN SOURCE MAKE AS MANY CHANGES YOU LIKE")
print("TO SELECT A FILE OR FOLDER JUST TYPE THE NUMBER CORRESPONDING TO IT")
print("FOR E.G. 5. MTL101 THAN YOU SHOULD COMMAND 5 TO OPEN IT ")
print("CONTACT ME AT kuldeepsan09@gmail.com")
print("FILES WILL BE DOWNLOADED IN THE SAME FOLDER YOU RUN YOUR PROGRAM")
def printTotals(transferred, toBeTransferred):
print("Transferred: {0}\tOut of: {1}".format(transferred, toBeTransferred))
input("READ INSTRUCTIONS: YES OR NO: ")
print("Ï DON'T CARE YES OR NO IT WAS JUST FOR A GAP")
print("Select your option number")
i = 0
while(i<len(tags)):
print(str(i+1)+" "+tags[i])
i+=1
index = int(input("TELL YOUR OPTION NUMBER: "))-1
while(True):
json = json[tags[index]]
timeline = timeline + [json]
if(type(json) == str):
print("DOWNLOADING WAIT A FEW SECONDS ")
stdin, stdout, stderr = ssh.exec_command("wget https://study.devclub.in"+json.replace(" ","%20"))
exit_status = stdout.channel.recv_exit_status() # Blocking call
if exit_status == 0:
sftp = ssh.open_sftp()
file = open(tags[index],'w+')
i = 0
while(i<len(tags)):
print(str(i+1)+" "+tags[i])
i+=1
sftp.get(tags[index],tags[index],callback=printTotals)
stdin, stdout, stderr = ssh.exec_command("rm "+tags[index])
print ("Hurrah File Downloaded")
file.close()
else:
print("SORRY THERE WAS AN ERROR TRY AGAIN", exit_status)
timeline.pop()
json = timeline[-1]
tags = list(json.keys())
tags = list(json.keys())
i = 0
while(i<len(tags)):
print(str(i+1)+" "+tags[i])
i+=1
response = input("TELL YOUR OPTION NUMBER: ")
while(response=="BACK"):
timeline.pop()
json = timeline[-1]
tags = list(json.keys())
i = 0
while(i<len(tags)):
print(str(i+1)+" "+tags[i])
i+=1
response = input("TELL YOUR OPTION NUMBER: ")
index = int(response)-1
print("Done")
|
Markdown | UTF-8 | 3,012 | 2.65625 | 3 | [
"CC0-1.0"
] | permissive | ---
layout: post
title: "Importing Yamaha Dx7's ROMS"
---
The [Yamaha Dx7](https://en.wikipedia.org/wiki/Yamaha_DX7) is a popular FM synthesizer that is a must have for electronic music enthusiasts (but this unit really spreads among a pletora of genres).

By combining the controls of the Dx7 you can obtain different sounds ranging from electric pianos to bells or strings. You can also produce nice pads, of course.
The combination of the controls can be saved in the original machine in a file called ROM. It's a sysex file (a binary file that can be send over midi to the machine
and whoose protocol is _**specific**_ for this machine)
On the web, you can find a _HUGE_ amount of ROMs [here](http://bobbyblues.recup.ch/yamaha_dx7/dx7_patches.html)
and there is also a _**new**_ nice web service that creates random ROMs for you using AI, see [here](https://www.thisdx7cartdoesnotexist.com/)
# Dexed lv2 plugin
On _**Aida DSP OS**_ and in the _**Mod-Duo**_ you will find the excellent _**Dexed**_ plugin already installed.
[  ](dexed1rev-full-size.png)
this plugin is a gem since it emulates the original sound of the Dx7 in a perfect way and it's also open source.
# How to import Dx7's ROMs
You need a way to convert the .SYX rom file into a .ttl preset file that you can use on the board [1].
I've made a script that does that for you [2]: I have tested it on _Linux Ubuntu_. It should be possible to run it in _Windows 10_ using the Ubuntu shell but I'll leave the tests for you.
On the [Aida DSP OS Share](https://drive.google.com/drive/folders/11b5uSavJboytXnDFgocN8cjFrTf7xIc7?usp=sharing) folder there is a dir named _**Dexed**_. You need
to download this folder into your Pc.
Then you need to invoke the script in this way
```
$ cd Dexed
$ scripts/create_dexed_ttls roms/PAD1.SYX pads
```
and it's done! under now you need to copy ./out/dexed-pads.lv2 folder into
the lv2 plugins partition of Aida DSP OS (see [User Manual]({{ '/aida_dsp_os_manual.html' | absolute_url }}))
and at the next start the new presets will be added to the existing ones:

The procedure can be uses also by Mod Duo's users, the change is only in the way to copy files
back to the unit.
Of course you can specify another .SYX file, just change the command to your needs.
Enjoy!
---
**NOTES**
1. The plugin version of Dexed running on Aida DSP OS/Mod Duo is a stripped version
which doesn't have the GUI to manually select a ROM file. The format that we need is .ttl (RDF), used to store presets among lv2 plugins. The advantage
of this format against the .SYX is that it's editable and readable by a human (ascii text).
2. Some credits here: this script relies on other scripts and tools which are open source and are part of Dexed sources that
you can find [here](https://github.com/dcoredump/dexed). I've only modified these scripts to my needs.
---
[Go to the Home Page]({{ '/' | absolute_url }})
|
Java | UTF-8 | 751 | 3.59375 | 4 | [] | no_license | /**
* Created by Harry Chou at 2019/7/23.
*/
import java.util.PriorityQueue;
public class GetMedian {
private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
int counter = 0;
public void Insert(Integer num) {
if ((counter & 1) == 0) {
minHeap.add(num);
maxHeap.add(minHeap.poll());
} else {
maxHeap.add(num);
minHeap.add(maxHeap.poll());
}
counter++;
}
public Double GetMedian() {
if ((counter & 1) == 0) {
return (minHeap.peek() + maxHeap.peek()) / 2.0;
} else {
return 1.0 * maxHeap.peek();
}
}
}
|
C | UTF-8 | 1,274 | 3.5 | 4 | [] | no_license | /**
* @file structures.h
* @brief Contains doubly linked list and its functions and structure that holds data on food
* @author Lukasz Kwiecien
*/
#ifndef STRUCTURES_H_INCLUDED
#define STRUCTURES_H_INCLUDED
/** doubly-linked list for storing informations about the snake */
struct coordinate
{
int x; /**< x position */
int y;/**< y position */
int lifes;/**<number of lifes */
int direction;/**< directon of movement */
int length;/**< length of the snake */
struct coordinate *next;/**< pointer to the next element of the list */
struct coordinate *prev;/**< pointer to the previous element of the list */
};
struct coordinate *head;
/** structure that holds data on food*/
struct food_
{
int x;/**< x position */
int y;/**< y position */
int hit;/**< variable for checking if food has been eaten*/
};
struct food_ food;
/** Function adds new element at the end of the doubly linked list.
*
* \param head struct coordinate** Pointer to a pointer to the first element of the list
*
*
*/
void append(struct coordinate** head);
/** Function removes all elements of the list.
*
* \param head struct coordinate** Pointer to a pointer to the first element of the list
*
*
*/
void free_mem(struct coordinate ** head);
#endif
|
Java | UTF-8 | 2,825 | 3.59375 | 4 | [] | no_license | public class DoubleLink<Item> {
private Node head=null;
private Node tail=null;
private int N=0;
private class Node{
Node prior;
Node next;
Item item;
}
/*
* 在后面加入数据
*/
public void addTailData(Item data){
Node newNode=new Node();
newNode.item=data;
if(N==0){
head=newNode;
tail=newNode;
}
else{
tail.next=newNode;
newNode.prior=tail;
tail=newNode;
}
N++;
}
/*
* 在后面加入数据
*/
public void addHeadData(Item data){
Node newNode=new Node();
newNode.item=data;
if(N==0){
head=newNode;
tail=newNode;
}
else{
newNode.next=head;
head.prior=newNode;
head=newNode;
}
N++;
}
/*
* 删除第i个位置的元素(i从0开始算的)并返还该元素
*/
public Item deleteData(int i){
Node reData;//要返回的节点
if(i<0||i>N-1){
System.out.println("delete fail!");
return null;
}
else if(i==0){
head=null;
tail=null;
return null;
}
else{
Node p=head;
int j=0;
while(j!=i-1){
p=p.next;
j++;
}
reData=p.next;
p.next=p.next.next;
p.next.prior=p;
}
N--;
return reData.item;
}
/*
* 在第i个节点后面插入data
*/
public void innersetData(int i,Item data){
if(i>=0&&i<N-1){
Node newNode=new Node();
newNode.item=data;
//System.out.println("进来啦");
Node p=head;
int j=0;
while(j!=i){
p=p.next;
j++;
}
newNode.next=p.next;
p.next.prior=newNode;
p.next=newNode;
newNode.prior=p;
N++;
}
else if(i==N-1){
addTailData(data);
}
else{
System.out.println("插入为位置不对!");
}
}
/*
* 返回链表长度N
*/
public int size(){
return N;
}
/*
* 从前向后遍历
*/
public void printHeadToTail(){
Node p=head;
System.out.print("head-->tail: ");
while(p!=null){
System.out.printf("%s->>",p.item);
p=p.next;
}
System.out.println();
}
/*
* 从后向遍历
*/
public void printTailToHead(){
Node p=tail;
System.out.print("tail-->head: ");
while(p!=null){
System.out.printf("%s->>",p.item);
p=p.prior;
}
System.out.println();
}
public static void main(String[] args){
DoubleLink<Integer> doubleLink=new DoubleLink<Integer>();
doubleLink.addHeadData(1);
doubleLink.addHeadData(2);
doubleLink.addHeadData(3);
doubleLink.addTailData(4);
doubleLink.addTailData(5);
doubleLink.addTailData(6);
doubleLink.addTailData(7);
doubleLink.addTailData(8);
doubleLink.addTailData(9);
int linkSize=doubleLink.size();
System.out.println("链表大小 "+linkSize);
int deleteIndex=2;
int data=doubleLink.deleteData(deleteIndex);
System.out.println("删除的下标是 "+deleteIndex+" 删除的数据是 "+data);
doubleLink.innersetData(7,10);
doubleLink.printHeadToTail();
doubleLink.printTailToHead();
}
}
|
Python | UTF-8 | 2,103 | 2.59375 | 3 | [] | no_license | import string
import csv
import random
from enum import Enum, auto
from datetime import datetime
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
from dataclasses_json import dataclass_json, LetterCase
from flask import json
room_id_to_room = {}
player_id_to_player = {}
ID_LENGTH = 5
prompts_file = Path(__file__).parent / "prompts.csv"
@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass(frozen=True)
class Prompt:
low: str
high: str
prompts = [
Prompt(**row) for row in csv.DictReader(prompts_file.read_text().splitlines())
]
@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass(frozen=True)
class Player:
id: int
name: str
room_id: str
def generate_height():
return round(random.uniform(0, 1), 2)
@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass(frozen=True)
class Teder:
prompt: Prompt
hinter: Player
actual_height: float = field(default_factory=generate_height)
hint: Optional[str] = None
guessed_height: float = 0.5
guess_is_final: bool = False
def new_id():
chars = string.ascii_uppercase + string.digits
id = "".join(random.sample(chars, ID_LENGTH))
if id not in room_id_to_room:
return id
return new_id()
class AutoName(Enum):
def _generate_next_value_(name, start, count, last_values):
return name
class RoomState(AutoName):
WAITING = auto()
HINTING = auto()
GUESSING = auto()
SCORING = auto()
CLOSED = auto()
@dataclass_json(letter_case=LetterCase.CAMEL)
@dataclass
class Room:
id: str = field(default_factory=new_id)
state: RoomState = RoomState.WAITING
players: list[Player] = field(default_factory=list)
tedarim: list[Teder] = field(default_factory=list)
last_updated: datetime = field(default_factory=datetime.now)
def __post_init__(self):
room_id_to_room[self.id] = self
# Needed for serializing of RoomStates
def to_socket_json(self):
return json.loads(self.to_json())
player_id_to_player: dict[str, Player]
room_id_to_room: dict[str, Room]
|
Markdown | UTF-8 | 280 | 2.65625 | 3 | [] | no_license | Какое выражение больше при достаточно больших $n$:
$$
\begin{aligned}
&\text{a) } 100n + 200 \text{ или } 0.01n^2?; \quad \text{б) } 2^n \text{ или } n^{1000}?;
\\
&\text{в) } 1000^n \text{ или } n!?
\end{aligned}
$$ |
C++ | UTF-8 | 569 | 3.109375 | 3 | [] | no_license | #include "../../Source/SOLID/InterfaceSegregation.h"
#include <gtest/gtest.h>
/*
* Interface Segregation Principle (ISP)
* Do not create interfaces that are too large
* or require implementators to implement too much
*/
TEST(SOLIDInterfaceSegregation, test1)
{
Printer printer;
Scanner scanner;
std::string expected_printer = "print";
std::string expected_scanner = "scan";
Machine machine(printer, scanner);
bool bTestPassed = machine.print() == expected_printer && machine.scan() == expected_scanner;
EXPECT_EQ(bTestPassed, true);
} |
Markdown | UTF-8 | 3,627 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | # Raspberry Pi Builds
TensorFlow's old official docs for building on Raspberry Pi. Needs an owner.
Maintainer: @angerson (TensorFlow, SIG Build)
* * *
**Important: TensorFlow for the Raspberry Pi is no longer supported by the
TensorFlow team. (last tested on 2.3.0rc2). See the [Build TensorFlow Lite for
Raspberry Pi](https://www.tensorflow.org/lite/guide/build_rpi) guide.**
**This guide is a mirror of the old official documentation and may not work. If
you'd like to own this and keep it up-to-date, please file a PR!**
# Build from source for the Raspberry Pi
This guide builds a TensorFlow package for a
[Raspberry Pi](https://www.raspberrypi.org/) device running
[Raspbian 9.0](https://www.raspberrypi.org/downloads/raspbian/).
While the instructions might work for other Raspberry Pi variants, it is only
tested and supported for this configuration.
We recommend *cross-compiling* the TensorFlow Raspbian package.
Cross-compilation is using a different platform to build the package than deploy
to. Instead of using the Raspberry Pi's limited RAM and comparatively slow
processor, it's easier to build TensorFlow on a more powerful host machine
running Linux, macOS, or Windows.
## Setup for host
### Install Docker
To simplify dependency management, the build script uses
[Docker](https://docs.docker.com/install/) to create a virtual Linux development
environment for compilation. Verify your Docker install by executing: `docker
run --rm hello-world`
### Download the TensorFlow source code
Use [Git](https://git-scm.com/) to clone the
[TensorFlow repository](https://github.com/tensorflow/tensorflow):
```
git clone https://github.com/tensorflow/tensorflow.git
cd tensorflow
```
The repo defaults to the `master` development branch. You can also checkout a
[release branch](https://github.com/tensorflow/tensorflow/releases)
to build:
```
git checkout <branch_name> # r1.9, r1.10, etc.
```
Key Point: If you're having build problems on the latest development branch, try
a release branch that is known to work.
## Build from source
Cross-compile the TensorFlow source code to build a Python *pip* package with
ARMv7 [NEON instructions](https://developer.arm.com/technologies/neon) that
works on Raspberry Pi 2, 3 and 4 devices. The build script launches a Docker
container for compilation. You can also build ARM 64-bit binary (aarch64) by
providing `AARCH64` parameter to the `build_raspberry_pi.sh` script. Choose
among Python 3.8, Python 3.7, Python 3.5 and Python 2.7 for the target package:
### Python 3.5
```
tensorflow/tools/ci_build/ci_build.sh PI-PYTHON3 \
tensorflow/tools/ci_build/pi/build_raspberry_pi.sh
```
### Python 3.7
```
tensorflow/tools/ci_build/ci_build.sh PI-PYTHON37 \
tensorflow/tools/ci_build/pi/build_raspberry_pi.sh
```
### Python 3.8 (64bit)
```
tensorflow/tools/ci_build/ci_build.sh PI-PYTHON38 \
tensorflow/tools/ci_build/pi/build_raspberry_pi.sh AARCH64
```
### Python 2.7
```
tensorflow/tools/ci_build/ci_build.sh PI \
tensorflow/tools/ci_build/pi/build_raspberry_pi.sh
```
To build a package that supports all Raspberry Pi devices—including the Pi 1 and
Zero—pass the `PI_ONE` argument, for example:
```
tensorflow/tools/ci_build/ci_build.sh PI \
tensorflow/tools/ci_build/pi/build_raspberry_pi.sh PI_ONE
```
When the build finishes (~30 minutes), a `.whl` package file is created in the
output-artifacts directory of the host's source tree. Copy the wheel file to the
Raspberry Pi and install with `pip`:
```
pip install tensorflow-<version>-cp35-none-linux_armv7l.whl
```
Success: TensorFlow is now installed on Raspbian.
|
Python | UTF-8 | 78 | 3.171875 | 3 | [] | no_license | sale=float(input("Enter the Sale of Employee: "))
if(sale>50000) : bonus=500 |
Java | UTF-8 | 5,364 | 2.03125 | 2 | [
"MIT"
] | permissive | package org.wysaid.cgeDemo.demoUtils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.opengl.GLES20;
import android.util.Log;
import org.wysaid.common.Common;
import org.wysaid.common.FrameBufferObject;
import org.wysaid.common.ProgramObject;
import org.wysaid.nativePort.CGEFaceTracker;
import org.wysaid.view.TrackingCameraGLSurfaceView;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* Author: wangyang
* Mail: admin@wysaid.org
* Data: 2017/10/29
* Description:
*/
public class FaceTrackingDemo implements TrackingCameraGLSurfaceView.TrackingProc {
protected static final String VSH = "" +
"attribute vec2 vPosition;\n" +
"uniform vec2 canvasSize;\n" +
"void main()\n" +
"{\n" +
" gl_PointSize = 10.0;\n" +
" gl_Position = vec4((vPosition / canvasSize) * 2.0 - 1.0, 0.0, 1.0);\n" +
" gl_Position.y = -gl_Position.y;\n" + // Mirror on screen.
"}";
protected static final String FSH = "" +
"precision mediump float;\n" +
"uniform vec4 color;\n" +
"void main()\n" +
"{\n" +
" gl_FragColor = color;\n" +
"}";
private int mOriginWidth, mOriginHeight;
private int mMaxSize = 320;
private ByteBuffer mImageCacheBuffer;
private Bitmap mBitmapSrc, mBitmapDst;
private Matrix mTransformMatrix;
private Canvas mTransformCanvas;
protected CGEFaceTracker mTracker;
protected int mWidth, mHeight;
protected int[] mFaceTrackingLock = new int[0];
protected ProgramObject mProgramObject;
protected CGEFaceTracker.FaceResult mFaceResult;
@Override
public boolean setup(int width, int height) {
mTracker = CGEFaceTracker.createFaceTracker();
mProgramObject = new ProgramObject();
mProgramObject.bindAttribLocation("vPosition", 0);
if (!mProgramObject.init(VSH, FSH)) {
mProgramObject.release();
mProgramObject = null;
return false;
}
resize(width, height);
return true;
}
@Override
public void resize(int width, int height) {
if (mOriginWidth == width && mOriginHeight == height)
return;
float scaling = mMaxSize / (float) Math.max(width, height);
if (scaling > 1.0f) {
mWidth = width;
mHeight = height;
} else {
mWidth = (int) (width * scaling);
mHeight = (int) (height * scaling);
}
mOriginWidth = width;
mOriginHeight = height;
mProgramObject.bind();
mProgramObject.sendUniformf("canvasSize", mWidth, mHeight);
mProgramObject.sendUniformf("color", 1, 0, 0, 0);
mImageCacheBuffer = ByteBuffer.allocateDirect(mWidth * mHeight).order(ByteOrder.nativeOrder());
mBitmapSrc = Bitmap.createBitmap(mOriginHeight, mOriginWidth, Bitmap.Config.ALPHA_8);
mBitmapDst = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ALPHA_8);
mTransformMatrix = new Matrix();
mTransformMatrix.setScale(scaling, -scaling);
mTransformMatrix.postRotate(90);
mTransformMatrix.postTranslate(-mWidth / 2, -mHeight / 2);
mTransformMatrix.postRotate(180);
mTransformMatrix.postTranslate(mWidth / 2, mHeight / 2);
mTransformCanvas = new Canvas(mBitmapDst);
mTransformCanvas.setMatrix(mTransformMatrix);
}
@Override
public void processTracking(ByteBuffer luminanceBuffer) {
if (luminanceBuffer == null) {
return;
}
mBitmapSrc.copyPixelsFromBuffer(luminanceBuffer.position(0));
mBitmapDst.eraseColor(0);
mTransformCanvas.drawBitmap(mBitmapSrc, 0.0f, 0.0f, null);
mBitmapDst.copyPixelsToBuffer(mImageCacheBuffer.position(0));
long tm = System.currentTimeMillis();
mImageCacheBuffer.position(0);
boolean ret = mTracker.detectFaceWithGrayBuffer(mImageCacheBuffer, mWidth, mHeight, mWidth);
synchronized (mFaceTrackingLock) {
if (ret) {
mFaceResult = mTracker.getFaceResult();
} else {
mFaceResult = null;
}
}
long totalTime = System.currentTimeMillis() - tm;
Log.i(Common.LOG_TAG, String.format("tracking time: %g s", totalTime / 1000.0f));
}
@Override
public void render(TrackingCameraGLSurfaceView glView) {
glView.drawCurrentFrame();
synchronized (mFaceTrackingLock) {
if (mProgramObject == null || mFaceResult == null)
return;
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
GLES20.glEnableVertexAttribArray(0);
GLES20.glVertexAttribPointer(0, 2, GLES20.GL_FLOAT, false, 0, mFaceResult.faceKeyPoints.position(0));
mProgramObject.bind();
GLES20.glDrawArrays(GLES20.GL_POINTS, 0, 66);
}
GLES20.glFinish();
}
@Override
public void release() {
if (mTracker != null) {
mTracker.release();
mTracker = null;
}
if (mProgramObject != null) {
mProgramObject.release();
mProgramObject = null;
}
}
}
|
SQL | UTF-8 | 390 | 2.921875 | 3 | [] | no_license | use mysql;
select host, user from user;
-- 因为mysql版本是5.7,因此新建用户为如下命令:
create user daxiang_docker identified by '123456';
-- 将daxiang数据库的权限授权给创建的daxiang_docker用户,密码为123456:
grant all on daxiang.* to daxiang_docker@'%' identified by '123456' with grant option;
-- 这一条命令一定要有:
flush privileges; |
Java | UTF-8 | 2,761 | 2.21875 | 2 | [] | no_license | package com.trongdung.website.controller.AdminController;
import com.trongdung.website.model.CategoryDTO;
import com.trongdung.website.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/admin")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@GetMapping("/category")
public String cate() {
categoryService.delete(categoryService.getById(1));
return "user";
}
@GetMapping("/category/list")
public String listCategory(Model model) {
List<CategoryDTO> categories = categoryService.getAll();
model.addAttribute("categories", categories);
return "admin/category/listCategory";
}
@GetMapping("/category/add")
public String addCategory(Model model) {
model.addAttribute("newCategory", new CategoryDTO());
return "admin/category/addCategory";
}
@PostMapping("/category/add")
public String addCategory(@ModelAttribute("newCateogry") CategoryDTO categoryDTO, BindingResult bindingResult) {
if(categoryDTO.getName().isEmpty()){
bindingResult.rejectValue("name","error.empty");
}else if(bindingResult.hasErrors()){
return "redirect: /admin/category/add";
}else{
categoryService.add(categoryDTO);
}
return "redirect:/admin/category/list";
}
@GetMapping("/category/{id}/edit")
public String editCategory(@PathVariable("id") int id, Model model) {
CategoryDTO categoryDTO = categoryService.getById(id);
model.addAttribute("categoryEdit", categoryDTO);
return "admin/category/editCategory";
}
@PostMapping("/category/{id}/edit")
public String editCategory(@ModelAttribute("categoryEdit") CategoryDTO categoryDTO) {
categoryService.edit(categoryDTO);
return "redirect:/admin/category/list";
}
@GetMapping("/category/{id}/delete")
public String deleteProduct(@PathVariable("id") int id, CategoryDTO categoryDTO) {
categoryDTO = categoryService.getById(id);
categoryService.delete(categoryDTO);
return "redirect:/admin/category/list";
}
@GetMapping("/category/searchByName")
public String searchByName(@RequestParam(name = "name", required = false) String name, Model model) {
CategoryDTO categoryDTO = categoryService.getByName(name);
model.addAttribute("categories", categoryDTO);
return "admin/category/listCategory";
}
}
|
Java | UTF-8 | 954 | 2.796875 | 3 | [] | no_license | package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class BOJ_2156_포도주시식 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int[] arr = new int[N];
for(int i=0; i<N; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
int[][] D = new int[N][3];
D[0][0] = 0;
D[0][1] = arr[0];
if(N > 1) {
D[1][0] = arr[0];
D[1][1] = arr[1];
D[1][2] = arr[0] + arr[1];
}
if(N > 2) {
for(int i=2; i<N; i++) {
D[i][0] = Math.max(Math.max(D[i-1][0], D[i-1][1]), D[i-1][2]);
D[i][1] = D[i-1][0] + arr[i];
D[i][2] = D[i-1][1] + arr[i];
}
}
int max = 0;
for(int i=0; i<3; i++) {
max = Math.max(max, D[N-1][i]);
}
System.out.println(max);
}
}
|
C# | UTF-8 | 1,102 | 2.6875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using Car_Galery.Managers.Abstract;
using Car_Galery.Models;
using Car_Galery.Repositories;
using Car_Galery.Repositories.Abstract;
namespace Car_Galery.Managers
{
public class EFUnitOfWork : IUnitOfWork
{
private DbContext _dbContext;
public EFUnitOfWork(DbContext dbContext)
{
Database.SetInitializer<ApplicationDbContext>(null);
if(dbContext == null)
throw new ArgumentNullException("dbContext can not be null.");
_dbContext = dbContext;
}
public void Dispose()
{
_dbContext.Dispose();
}
public IRepository<T> GetRepository<T>() where T : class
{
return new EFRepository<T>(_dbContext);
}
public int SaveChanges()
{
try
{
return _dbContext.SaveChanges();
}
catch
{
throw;
}
}
}
} |
Markdown | UTF-8 | 961 | 2.640625 | 3 | [] | no_license | - 👋 Hi, I’m James T. [@turajbjt]
- 👀 I’m interests vary, so I'm always trying new things. Some of my long term intrests include coding (mostly in Perl), web design, computers/networking, 3D printing, wood working, model railroading & gardening, to name a few...
- 🌱 I’m currently learning newer web technologies (such as those related to doing things in the Cloud) & better understanding how to use more mainstream programming languanges.
- 💞️ I’m not looking to collaborate on anything specifically. With a somewhat busy schedule, I just do a little here & there, as free time permits.
- 📫 How to reach me - well you don't. If you needed to reach me, you would already have my contact info. If not, then there is likely a reason for it...
<!---
turajbjt/turajbjt is a ✨ special ✨ repository because its `README.md` (this file) appears on your GitHub profile.
You can click the Preview link to take a look at your changes.
--->
|
Python | UTF-8 | 1,492 | 3.125 | 3 | [] | no_license | import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
from gensim.summarization import summarize,keywords
class ReviewSummarizer:
def __init__(self,reviews):
self.ratio=0.1
self.wordcount=20
self.reviews=reviews
def getSummarizedText(self):
txt=' '.join(self.reviews)
#print (self.reviews)
txt_input=' '.join(self.reviews)
if len(self.reviews) == 0 or len(self.reviews) == 1:
return " "
elif len(self.reviews) <5:
for i in range(10):
self.reviews.extend(self.reviews)
#print(len(self.reviews))
txt_input=' '.join(self.reviews)
# if len(txt) < 500:
# return txt
try:
summary = summarize(text=txt_input,ratio=self.ratio,word_count=self.wordcount)
#print("sy")
except Exception as e:
#print(e)
summary = txt
return summary
def getKeyWords(self):
txt = ' '.join(self.reviews)
return(keywords(text=txt, ratio=self.ratio))
'''if __name__== "__main__":
reviews = [' Test', 'This is a great course. I learnt a lot',
'Learnt a lot about databases and how they work in the background']
sumsr = ReviewSummarizer(reviews)
#print(sumsr.getKeyWords())
print(sumsr.getSummarizedText())
# with open("mockdata.txt") as fp:
# reviews = fp.readlines()'''
|
Markdown | UTF-8 | 2,017 | 2.625 | 3 | [] | no_license | # WebsiteMonitoring
Клиент-серверное приложение с веб-интерфейсом, тестирующее несколько сайтов с сервера параллельно, и выводящее результат в браузер.
Результат мониторинга выдается в виде таблицы на HTML странице (через сервлет или jsp).
Временное выключение/включение мониторинга URL-а через веб-интерфейс.
Конфигурация мониторинга (добавление, настройка, удаление URL-ов мониторинга) задается через веб-интерфейс и сохраняется в базе данных.
Технологии:
Java EE, Maven.
База данных : PostgreSQL.
Сервер : Tomcat 9.
Среда разработки где был реализован данный проект : IntelliJ Idea Ultimate.
Операционная система машины : Ubuntu 19.04.
На главной странице отображаеться таблица со всеми URL, которые можно можна редактировать или удалать, так же с этой страницы можно запустить мониторинг.
На странице мониторинга отображаеться таблица с URL и их параметрами.
Инструкция:
1) Установить JDK
2) Установить Maven
3) Установить Tomcat
4) Запустить через Intelij Idea либо :
1. Получить war архив(перейти в каталог где находится pom.xml и выполнить команду mvn clean install)
2. Поместить war архив в папку webapps(находится в папке tomcat)
3. Открить в браузере http://localhost:8080/monitoringTool_war
|
Shell | UTF-8 | 888 | 3.6875 | 4 | [
"MIT"
] | permissive | #!/bin/sh
in='meta/build-info.template'
tag=$(git describe --tags --abbrev=0)
changelog_line=$(grep "$tag" CHANGELOG.md)
changelog_date=$(echo "$changelog_line" | grep -Eo '\d{4}-\d{2}-\d{2}')
tag_without_dots=$(echo "$tag" | tr -d .)
changelog_anchor="$tag_without_dots-$changelog_date"
make_info_for_browser() {
browser_pretty=$1
browser_var=$2
sed \
-e "s/CHANGELOG_ANCHOR/$changelog_anchor/g" \
-e "s/VERSION_NUMBER/$tag/g" \
-e "s/BROWSER_PRETTY/$browser_pretty/g" \
-e "s/BROWSER_VAR/$browser_var/g" \
< $in
}
echo // Firefox
echo
make_info_for_browser Firefox firefox
echo
echo
echo // Opera
echo
make_info_for_browser Opera opera
echo
echo
github_zip_file=$tag.zip
github_code_url="https://github.com/matatk/landmarks/archive/$github_zip_file"
echo "Downloading <$github_code_url>..."
curl \
--location "$github_code_url" \
--remote-name \
--remote-header-name
|
JavaScript | UTF-8 | 695 | 2.984375 | 3 | [] | no_license | function mostrar()
{
var contador=0;
var positivo=0;
var negativo=1;
var contadorDeNotas;
var numero;
var respuesta='si';
while(respuesta != "n")
{
numero = prompt("ingrese numeros");
numero = parseInt(numero);
//respuesta = prompt("quiere seguir sumando??") //texto predeterminado
//numero = prompt("ingrese numeros"); //texto predeterminado
if ( numero > 0) {
positivo = positivo + numero;
}else
{
negativo = negativo * numero;
}
respuesta = prompt("para salir ingrese 'n' ");
}
document.getElementById('suma').value=positivo;
document.getElementById('producto').value=negativo;
}//FIN DE LA FUNCIÓN |
Markdown | UTF-8 | 8,002 | 2.796875 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive | # Open Source Contribution Project
*Author :* Jérome Eertmans
*Date :* September-December 2020
*NOMA :* 1355-16-00
## Research and Selection of the Project
[](https://www.python.org/)
### Starting with **Pandas**
[](https://pypi.python.org/pypi/pandas/) [](https://pypi.python.org/pypi/pandas/) [](https://GitHub.com/pandas-dev/pandas/graphs/contributors/)
As I am a frequent user of numerical libraries in Python, I would like to contribute to one of them. The one which can still grow a lot, in my opinion, is [Pandas](https://github.com/pandas-dev/pandas) and it is why I first wanted to contribute to this great package. After digging in the [Pandas' contribution guide](https://pandas.pydata.org/docs/dev/development/contributing.html#where-to-start) and the various issues, I started becoming less attracted by contributing to issues that I didn't even care about: as Pandas is very popular, most interesting issues to me are closed very quickly and what is left is to build tests. I think that tests are important but it was not how I wanted to contribute to an open source project, at least for now. The Pandas unit tests are a painful way to start contributing as they need very long compilation time, a lot of side packages and trying to build everything came with a lot more issues than it started with.
### Changing to **Numba**
[](https://pypi.python.org/pypi/numba/) [](https://pypi.python.org/pypi/numba/) [](https://GitHub.com/numba/numba/graphs/contributors/)
Later, I was coding in Python for an another course and I started using the [Numba](https://numba.pydata.org/) library for performances purposes, which is something I am very interested in. After a few minutes, I encountered a reference bug within the package. Before raising the alarm to the Numba community, I read their documentation, went through multiple issues and even came to find a fix to this issue.
In short, Numba increases Python's performances by compiling function using an optimized compiler, while keeping the code pretty simple:
```python
def some_function(x): # Any function using pure Python or even Numpy functions
"""
Some code
"""
import numba
@numba.njit
def some_function(x): # Same function but Numba will optimize it
"""
Some code
"""
```
<p align="center">
<img src="https://i1.wp.com/murillogroupmsu.com/wp-content/uploads/2018/01/plot-3.png?resize=648%2C648&ssl=1">
</img>
</p>
<p align="center">
Source: https://murillogroupmsu.com/numba-versus-c/
</p>
## Starting to contribute to the project
Because it was a simple error that I understood quite well, I created an [issue](https://github.com/numba/numba/issues/6276) that I documented as much as possible, while also following their guidelines. Quickly, a contributor replied to me and told me that I could try to fix this issue. After some comments we exchanged, we discovered that it was actually 2 separated issues: he assigned me to the first one and I kept investigating on the second one.
### First contribution to Numba
It turned out that the latter was not an issue related to Numba but more likely to Python's behavior. Anyway, my fix was pretty easy and my [PR](https://github.com/numba/numba/pull/6277) got accepted within the first 24 hours of existence of the [issue](https://github.com/numba/numba/issues/6276). My PR has been now merged and will be released with version [0.52](https://github.com/numba/numba/milestone/40): 
```diff
diff --git numba/numba/np/arraymath.py jeertmans/numba/np/arraymath.py
@@ -4395,7 +4395,7 @@ def impl(a, b):
raise ValueError((
"Dimensions for both inputs is 2.\n"
"Please replace your numpy.cross(a, b) call with "
- "numba.numpy_extensions.cross2d(a, b)."
+ "a call to `cross2d(a, b)` from `numba.np.extensions`."
))
return impl
```
Even though fixing the error was quite an easy task, I learned many interesting things on how to contribute and here is a quick summary:
#### 1. Reproducible error
Numba's community asks issues to fulfill two criteria:
- [x] I have tried using the latest released version of Numba (most recent is
visible in the change log (https://github.com/numba/numba/blob/master/CHANGE_LOG).
- [x] I have included below a minimal working reproducer (if you are unsure how
to write one see http://matthewrocklin.com/blog/work/2018/02/28/minimal-bug-reports).
Before posting my issue, I made sure to check them and that there was no similar issue already existing.
#### 2. Searching for a fix
I think that, when you post an issue, it is important to at least search for a fix. It will help other people understand what really goes wrong and how to quickly address your problem. I did search a fix and even found one.
So, I also proposed to be the one in charge of fixing the issue.
#### 3. Deciding the field of the fix
It is important to determine what should be fixed and what should not. Even if an error can be very wide, some of the **bad** behavior can be intentional. With the help of the Numba's contributors, we defined the field of what should be done.
#### 4. Making a Pull Request and adapting it
When I got the issue fixed, I made a PR. Quickly after, I received comment on what was good and what could be improved in my fix. The reviewers were super nice to me and helped me understand everything I needed to check before my PR could be considered a valid.
So, even if my fix started with a one line change in the code, I ended up updating
other parts of the code as well as checking that everything was working as expected
with unit tests.
<img src="https://dev.azure.com/numba/numba/_apis/build/status/numba.numba?buildId=6745"></img>
### Second contribution to Numba
Because I still wanted to contribute to Numba, I searched through the proposed implementations listed in this [issue](https://github.com/numba/numba/issues/4074) and decided to implement the [`numpy.allclose`](https://numpy.org/doc/stable/reference/generated/numpy.allclose.html) function. I tried to be as complete as possible so I took other successful [PR](https://github.com/numba/numba/pull/6277) as example.
Once I was quite confident about my implementation, I started a [PR](https://github.com/numba/numba/pull/6286).
Quickly, a reviewer reached me and we started discussing about my implementation. I made several changes to my initial commits because, even if my code was optimized, it was not a perfect copy of the behavior of `numpy.allclose` function. They prefer to have a reliable code, even it is comes with a performance cost.
My PR is for the moment in the *Waiting on reviewer* state and I am actively working on it.
Because Numba's main purpose is to accelerate execution time, it is interesting to see how my implementation compares with the original function (almost 6 times faster !).
```python
import numba as nb
import numpy as np
@nb.njit # What I implemented (code is hidden behind the `njit` wrapper)
def allclose(a, b):
return np.allclose(a, b)
a = np.random.rand(100, 100)
np.allclose(a, a)
>>> True
allclose(a, a)
>>> True
%timeit allclose(a, a) # My implementation
>>> 10.9 µs ± 31.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.allclose(a, a) # Reference function
>>> 59.4 µs ± 221 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
```
|
C# | UTF-8 | 1,224 | 3.40625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ex_1101
{
class Program
{
static void Main(string[] args)
{
string[] vet = Console.ReadLine().Split(' ');
int M, N,maior,menor;
M = int.Parse(vet[0]);
N = int.Parse(vet[1]);
int total = 0;
maior = M;
menor = N;
if (N > M)
{
maior = N;
menor = M;
}
while(M > 0 & N > 0)
{
for(int i = menor; i <= maior; i++)
{
Console.Write(i+" ");
total = i + total;
}
Console.WriteLine("Sum=" + total);
vet = Console.ReadLine().Split(' ');
M = int.Parse(vet[0]);
N = int.Parse(vet[1]);
total = 0;
maior = M;
menor = N;
if (N > M)
{
maior = N;
menor = M;
}
}
Console.ReadKey();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.