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
| 316
| 3.234375
| 3
|
[] |
no_license
|
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float x; float y; float z;
float p;
cout<<"Ingrese el primer numero: ";
cin>>x;
cout<<"Ingrese el segundo numero: ";
cin>>y;
cout<<"Ingrese el tercer numero: ";
cin>>z;
p=(x+y+z)/3;
cout<<"Promedio: ";
cout<<p;
}
|
Markdown
|
UTF-8
| 1,699
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
# Amber-s-Training-Widget-1
This is to help with css flexbox mock ups, and understanding :)
-Yours Truly Amber Meador (Lambda TL extraordinaire)
Starter Questions / Things to Do
1. I want to center up the title "Amber's Widget" so it aligns with the rest of the content?
2. I would like the nav 'Things' to be spread edge to edge of the red, and touching it?
3. I would like there to be some space around the red box, so it's not touching/overlapping with any of the other boxes?
4. The images are breaking out of their containers. I want them to fit inside the pink box?
5. The Part 1/2 heading text are against the pink box... I want them away from it about 5 to 10 pixels?
6. I need a footer. I want it to look just like my nav header?
7. I want the overall width a little bigger. Like, maybe 1000px?
8. I'd like the second 'holder1' div to hold 3 smaller containers instead of two... how do I do this?
9. I'd like the border aspect of each of the boxes to go away so I can have a cleaner looking site?
10. What else can I do to make this more streamlined and fancy looking?
LET'S MAKE IT MOBILE !!!!
1. If everything is within the primary css 'container', and all widths are %'s, and you make one media query for container everything shrinks down auto-magically to fit inside :)
2. Now let's make a column out of the first holder instead of having them side by side ?
3. Let's lign everything up again. Space out holder1a for the new 'column' view and make sure nothing is overlapping
4. Let's make a new image class, and one image will shrink to fit, and the other will display none on the tablet view?
FINISH !!!
Solution code will be in the solution branch for you guys :)
|
C++
|
UTF-8
| 2,012
| 2.859375
| 3
|
[] |
no_license
|
class Solution {
public:
bool check (int start, int end, vector<int>& leagle) {
bool ok = false;
for (int i = start; i <= end; i++) {
if (leagle[i] == 2) {
return false;
} else if (leagle[i] == 1) {
ok = true;
}
}
return ok;
}
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
vector<pair<int,int>>roll;
int count = 0 , start;
bool touch = false, first = true;
A.emplace_back(R+1);
for (int i = 0; i < A.size(); i++) {
if (A[i] < L) {
if (first) {
start = i;
first = false;
}
} else if (A[i] > R) {
if (touch)roll.emplace_back(pair<int,int>(start,i-1));
touch = false;
first = true;
} else {
if (first) {
start = i;
first = false;
}
touch = true;
}
}
vector<int>leagle(A.size(),1);
for (int i = 0; i < A.size(); i++) {
if (A[i] < L) {
leagle[i] = 0;
} else if (A[i] > R) {
leagle[i] = 2;
}
}
for (auto it:roll) {
for (int i = it.first; i<= it.second; i++) {
for (int j = i; j <= it.second; j++) {
if (check(i,j,leagle)) count++;
}
}
}
return count;
}
};
//the fatest method
static const auto __ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
int ans = 0, s=-1, l=-1;
for(int i=0; i<A.size(); i++){
if(A[i]>R){s=i; l=i; continue;}
if(A[i]>=L)l=i;
ans+=(l-s);
}
return ans;
}
};
|
C++
|
UTF-8
| 2,263
| 2.875
| 3
|
[] |
no_license
|
/*
* File: main.cpp
* Author: peter
*
* Created on March 25, 2014, 5:01 PM
*/
#include <iostream>
#include <locale>
class Money {
public:
Money( long int amount) : amount_(amount) {}
operator long int() { return amount_; }
private:
long int amount_;
};
class My_money_io : public std::moneypunct<char, true > {
public:
explicit My_money_io(size_t r = 0) : std::moneypunct<char, true > (r) {
}
string_type do_curr_symbol() const {
return "USD ";
}
string_type do_positive_sign() const {
return "+";
}
typedef std::money_base mb;
std::money_base::pattern do_pos_format() const {
static mb::pattern pattern;
pattern.field[ 0] = mb::sign;
pattern.field[ 1] = mb::symbol;
pattern.field[ 2] = mb::value;
pattern.field[ 3] = mb::none;
return pattern;
}
};
std::ostream& operator<< ( std::ostream& s, Money& m) {
return s;
}
/*
*
*/
int main(int argc, char** argv) {
double d = 123;
std::ostream& s = std::cout;
std::ostream::sentry guard( s);
try {
const std::money_put<char>& f = std::use_facet< std::money_put<char> >( s.getloc());
std::cout << std::use_facet< std::moneypunct<char, true> >( s.getloc()).curr_symbol();
std::cout << std::use_facet< std::moneypunct<char, true> >( s.getloc()).decimal_point();
std::cout << std::use_facet< std::moneypunct<char, true> >( s.getloc()).negative_sign();
std::money_base::pattern pattern = std::use_facet< std::moneypunct<char> >( s.getloc()).pos_format();
if ( f.put( s, true, s, s.fill(), d).failed()) {
s.setstate( std::ios_base::badbit);
}
} catch ( std::exception& e) {
std::cout << e.what();
}
try {
s.imbue( std::locale( s.getloc(), new My_money_io));
const std::money_put<char>& f = std::use_facet< std::money_put<char> >( s.getloc());
std::cout << std::use_facet< My_money_io >( s.getloc()).curr_symbol();
if ( f.put( s, true, s, s.fill(), d).failed()) {
s.setstate( std::ios_base::badbit);
}
} catch ( std::exception& e) {
std::cout << e.what();
}
return 0;
}
|
Java
|
UTF-8
| 2,946
| 3.65625
| 4
|
[] |
no_license
|
import java.util.*;
// Recursive implementation of
// word break problem in java
public class WordBreakProblem {
// set to hold dictionary values
private static Set<String> dictionary = new HashSet<>();
public static void main(String[] args) {
// array of strings to be added in dictionary set.
String temp_dictionary[] = { "mobile", "samsung", "sam", "sung", "man", "mango", "icecream", "and", "go", "i",
"like", "ice", "cream" };
// loop to add all strings in dictionary set
for (String temp : temp_dictionary) {
dictionary.add(temp);
}
workBreakBT("ilikesamsung");
//workBreakBT("ilikelikeimangoiii");
//workBreakBT("samsungandmango");
// sample input cases
/* System.out.println(wordBreak("ilikesamsung"));
System.out.println(wordBreak("iiiiiiii"));
System.out.println(wordBreak(""));
System.out.println(wordBreak("ilikelikeimangoiii"));
System.out.println(wordBreak("samsungandmango"));
System.out.println(wordBreak("samsungandmangok"));*/
}
public static void workBreakBT(String str) {
wordBreakUtil(str, str.length(), "");
}
public static void wordBreakUtil(String str, int n, String result)
{
//Process all prefixes one by one
for (int i=1; i <=n; i++)
{
//extract substring from 0 to i in prefix
String prefix = str.substring(0, i);
// if dictionary conatins this prefix, then
// we check for remaining string. Otherwise
// we ignore this prefix (there is no else for
// this if) and try next
if (dictionary.contains(prefix))
{
// if no more elements are there, print it
if (i == n)
{
// add this element to previous prefix
result += prefix;
System.out.println(result);
return;
}
wordBreakUtil(str.substring(i, n), n-i,
result + prefix + " ");
}
} //end for
}//end function
// returns true if the word can be segmented into parts such
// that each part is contained in dictionary
public static boolean wordBreak(String word) {
int size = word.length();
// base case
if (size == 0)
return true;
// else check for all words
for (int i = 1; i <= size; i++) {
// Now we will first divide the word into two parts ,
// the prefix will have a length of i and check if it is
// present in dictionary ,if yes then we will check for
// suffix of length size-i recursively. if both prefix and
// suffix are present the word is found in dictionary.
if (dictionary.contains(word.substring(0, i)) && wordBreak(word.substring(i, size)))
return true;
}
// if all cases failed then return false
return false;
}
}
// This code is contributed by Sparsh Singhal
|
Markdown
|
UTF-8
| 17,050
| 2.9375
| 3
|
[] |
no_license
|
---
id: manage-your-families
themes: catalog-settings
title: Manage your **families and variant families**
popular: false
ee: false
related: what-is-a-family
---
# Manage your families
## See all your families
To see your families, edit them or create a new family go to `Settings/Families`.

## How to create a family?
**Families are used to gather attributes that are common to several products**. The [completeness](what-is-the-completeness.html) of your products is also defined at the family level.
To create a new family, follow these steps:
1. Go to `Settings/Families`
1. Click on `Create family`

1. The creation of a family popin is prompted
1. Enter a new family code (this code must be unique)
1. Click on `Save`
Your new family is now created. The family's `Properties` tab is displayed.
You can give additional properties to your family:
* **Set an `attribute used as label` (required)**: a **text or identifier attribute** that will be used as the **default name for products** belonging to this family. The attribute selected as label **will appear in the product grid** (as the "Label" column) and in **the product form's header**.
* **Set an `attribute used as the main picture`**: an **`image` or `assets collection` attribute** that will be used as **"the main picture" for products** belonging to this family. This attribute used as main image will be displayed **in the product grid** (as the "image" column) and in **the product form's header**. **Localizable and/or scopable attributes cannot be used as main product pictures**.
* Translate the family's label with `Labels translations`: allow you to translate your family name into the locales enabled in the PIM.
These information can be edited afterwards.
Once a family is created, you can configure your family:
* Add/remove attributes from the family
* Edit these attributes’ completeness
:::info
The PIM supports many formats for the `Image` and `Asset Collection` thumbnail generation. You’ll find [here](https://imagemagick.org/script/formats.php) the whole list of supported extensions (such as jpg, jpeg, png, gif, psd, tiff...). If you use asset collections, you can also preview PDF and Youtube & Vimeo media links.
:::
:::warning
The formats mentioned in the ImageMagick documentation are supported if they don’t require any other extension, with the exception of the ones requiring Ghostcript, which are supported (for example: the PIM is capable to read **EPS** images but not **FIG** since FIG requires TransFig, which has not been configured.)
Please note that this list might evolve on ImageMagick side without notice.
:::
:::info
You must be granted a specific role permission to be able to create a family. Please refer to [Manage your user roles](build-your-user-roles.html).
:::
## Manage attributes in a family
**Attributes can be used in one or several families, but an attribute can only be added once to a family**.
You can easily add attributes to or remove them from a family using the user interface or through [imports](imports.html).
### Add an attribute to a family
Once you are on your family edit form, go under the `Attributes` tab:
1. Click on `Add Attributes` on the right side of the screen

1. Select the attributes to add by clicking on their labels
1. Click on `Add`
1. Click on `Save`
You can also add a group of attributes, to do so click on `Add by groups` on the right side of the screen

Select the attribute groups to add by clicking on their labels and click on `Add` and then `Save`.
The attributes will be added to the current family.
::: info
If you do not see the `Add Attributes` or `Add by groups` button, it might be because you do not have the relevant rights. Please refer to [Manage your user roles](build-your-user-roles.html).
:::
### Remove an attribute
You can also remove attributes from a family:
1. Go under the `Attributes` tab
1. Click on the `Delete` icon to remove the relevant attribute(s)

1. `Save` your update
The attribute(s) will be back under the `Add attributes` list. If you need it later, you will be able to add it again.
## Manage your family’s completenesses
:::info
The **completeness represents the percentage of completion of a product**, it is displayed as a progress bar or as a percentage in the PIM. **It is calculated for each product and for each channel/locale combination.**
**A product is considered as complete** (or 100% completeness) **when its required attributes** (defined at the family level) **have values.**
For more details about the completeness, please refer to [Understand product completeness](what-is-the-completeness.html).
:::
When an attribute is added to a family, it is not set as required for any channel by default. **Only your product identifier attribute is automatically added and set as required for all families**.
Under the attribute’s family tab, you will see
- **Circles** meaning that the attribute is **not required** in the channel’s completeness
- **Checks** meaning that the attribute is already set as **required** for this channel
### Set an attribute as required for a channel
1. Go under the `Attributes` tab
1. Select the attributes to be required for your family
1. Click on the circles to make them required for the channel’s completeness
1. Circles are automatically converted into a “check”
1. Click on `Save`

:::warning
Once changes are saved, the PIM will automatically run a completeness calculation to update your product information.
:::
:::tips
Save time by using the **Family Mass action** (available from the families grid)! You will be be able to add one or several attributes (or attribute groups) to a selection of families, and also manage their completeness at the same time, read our section [Mass edit your families](manage-your-families.html#mass-edit-families) available below.
:::
### Remove an attribute as required from a channel
1. Go under the `Attributes` tab
1. Select the attributes required for your family
1. Click on the checks to remove them from being required for the channel’s completeness
1. Checks are automatically converted into circles
1. Click on `Save`
:::warning
Once changes are saved, the PIM will automatically run a completeness calculation to update your product information.
:::
## Mass edit families
**Like for products you can mass edit families and add several attributes at once for several families**, and through the same action define if they are required or not for the selected channels.
To add attributes (or a group of attributes) to several families:
1. Go to `Settings/Families`
1. Check the families on which you want to add the same attributes
1. A toolbar will be displayed at the bottom of the page: choose `All` to select all existing families, `All visible` to only select the families displayed on the current page or `None` to unselect all the families)
1. Click on the `Bulk actions` button in the toolbar

1. The mass edit window will be displayed
1. Select the operation `Set attributes requirements`
1. Click on `Next`

1. Add the relevant attributes by attributes or by attribute groups
1. Set the attributes required for the product completeness of the channels
1. Click on `Next`
1. Confirm the action with the `Confirm` button to add attributes to the selected families
The attributes have been added to the families.
## Check the family history
Changes made on a family are recorded and visible under the `History` tab.
For each change, a version of the family is created. The following information is tracked down for each version:
- The person or system that made the changes
- The date and time (down to seconds) at which the changes took place
- The old value and the new value of each modified field
To view the family versions:
1. Open and edit the family tab.
1. Click on the `History` tab. The list of versions is displayed
## Delete a family
::: info
Deleting a family does not remove the attributes from the PIM and does not delete the products associated to it.
**Attributes that had values will remain visible in the product form** to keep the product information. These attributes will become “optional”.
**Products without a family will no longer have a completeness**.
:::
You have two ways of removing a family.
Through the family form:
1. Go to `Settings/Families` to list the families
1. Click on the family to delete
1. Click on `...` for other actions and then `Delete` on the top right corner

1. Confirm the action via the validation message
Through the `Delete` shortcut in the grid:

1. Select the family you want to remove from the family datagrid
1. Place your mouse over the line of family in the grid, the button delete is prompted (trash can icon)
1. Click on the trash can icon
1. Confirm the action in the validation message
::: warning
A family with family variants cannot be deleted. You first need to [delete its family variants](manage-your-families.html#delete-a-family-variant).
:::
::: warning
A family cannot be deleted if there are some products within this family, you first need to remove the products from this family (refer to [the bulk action change family of products](product-mass-actions.html)).
:::
::: ee
A family used by a published product cannot be deleted. You first need to unpublish your products to delete the family.
:::
# Manage family variants
A [family variant](what-about-products-variants.html#what-is-a-family-variant) allows you to define the global structure of your products with variants and will enable you to create [product models](what-about-products-variants.html#what-is-a-product-model).
The family variants are managed in a dedicated tab called `Variants` in `Settings/Families`.
## See your family variants
To see the existing family variants or create a new one:
1. Go to `Settings/Families`
1. Select the family to edit in the grid and click on it
1. Open the `Variants` tab for the family

## Display a family variant
1. In `Settings/Families`, choose a family and open the `Variants` tab
1. Click on a family variant to display it
1. The family variant details are displayed

You can see how the attributes are distributed between the different levels:
- The **common attributes** in the 1st column for all the products in a product model
- The **variant attributes for the level 1** in the 2nd column are the attributes which will vary according to the variant axes of the level 1
- If the family variant has 2 variant levels, **the variant attributes for the level 2** in the 3rd column are the attributes which vary according to the variant axes of the level 2 (and level 1)
In our clothing example which varies on 2 levels by color and then by size, the common attributes are: the name, the collection, the description, the brand, etc. The attributes that vary by color (variant level 1) are the composition, the pictures and the attributes that differ by color and size (variant level 2) are the EAN, the SKU and the weight.
## Create a new family variant
You can create one or more family variants in each family.
1. In `Settings/Families`, choose a family and select the `Variants` tab
1. Click on `Add variant` to create a new variant for the family
1. The creation of a family variant popin is prompted

1. The following properties are required to create a family variant:
- A **code** to identify the family variant
- A **label**
- A number of **variant levels**: 1 or 2
- The **variant axes** for each level: the variant axes are attributes of the family which identify the variant product in the product model. Their values must differ from a variant product to another in the product model (unicity). For examples, the `color` and `size` for a clothing model (there is only one product with the color blue and the size S and one product with the color blue and the size M for a t-shirt model), the `color` for a chair model, the `dimensions` for a mattress model.
1. Click on `Create`, the family variant is created.
::: info
An attribute of the family could be a **variant axis** only if its attribute type is **structured**:
- **Simple select**
- **Reference entity single link** _(EE only)_
- [**Measurement**](what-about-measurements.html)
- **Boolean (Yes/No)**
You cannot use scopable and/or localizable or locale specific attributes as variant axis.
:::
::: info
A **family variant cannot have more than 5 attributes used as a variant axis.**
:::
Then, a screen to distribute the attributes between the different levels (`common attributes`, `variant attributes level 1` and `variant attributes level 2`) for the family variant will be displayed.
1. Drag and drop attributes or attribute groups from the `common attributes` to the selected variant level to have these attributes managed at each variant level

1. Click on `Save`, the family variant will be updated
::: info
By default, the `common attributes` are all the attributes of the family, except the variant axes attributes (available for each variant level) and the attributes with the property `unique value` at `Yes` which are at the last variant level = product level (for example the `SKU` and `EAN`).
:::
## Edit a family variant
1. In `Settings/Families`, choose a family and open the `Variants` tab
1. Click on a family variant
1. The family variant edit page is displayed

1. You can move attributes or attribute groups by a drag and drop from the `common attributes` to the selected variant level or from the `variant attributes level 1` to the `variant attributes level 2`
1. You can remove an attribute from a variant level by clicking on the cross
1. A confirmation opens

1. Click on `OK` to confirm the remove
1. When you have made all your updates on the family variant attributes, click on `Save`

::: info
Moving attributes from `common attributes` to a variant level or from the `variant attributes level 1` to the `variant attributes level 2` means that the selected attributes will be managed at another level. If **these attributes were already filled in, those values will be kept and visible in the new level**. For instance, to keep our `Clothing` example, if you move the `Description` attribute from the `common attributes` to the `variant attributes level 1`, the description previously filled in will be kept for all variant products, but you will be able to change it at the product variant level 1. Basically, you will have the possibility to fill in a description for each color.
:::
::: warning
**You cannot move a variant axis** or **an attribute with the property `unique value` at `Yes`**.
:::
::: info
You can edit the variant axis value of a variant product in each product sheet, simply by editing the attribute value that is used as variant axis.
:::
## Translate a family variant label
1. In `Settings/Families`, choose a family and open the `Variants` tab
1. Click on a family variant
1. The family variant edit page is displayed
1. Select the `Label translations` tab
1. Translate the family variant label in the different enabled locales

1. Click on `Save`
## Delete a family variant
::: warning
**A family variant can be deleted if it does not contain any [product model](what-about-products-variants.html#what-is-a-product-model)**. If it has product models, an error message will be displayed. You will have to delete those products to be able to delete your family variant.
:::
1. In `Settings/Families`, choose a family and open the `Variants` tab
1. Place your mouse over the line of the family variant you want to remove in the grid, the button delete is prompted (trash can icon)

1. Click on the trash can icon, a confirmation opens
1. Click on `Delete` to confirm the action in the confirmation message
|
Markdown
|
UTF-8
| 1,374
| 2.5625
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: 'Como: Substituir a árvore lógica'
ms.date: 03/30/2017
helpviewer_keywords:
- overriding the logical tree [WPF]
- logical tree [WPF], overriding
ms.assetid: 0ae4d074-8113-4b06-b4fa-e0f39d4967a6
ms.openlocfilehash: bf3459fff1a90326794d6713dd39c73596b0e960
ms.sourcegitcommit: 9b552addadfb57fab0b9e7852ed4f1f1b8a42f8e
ms.translationtype: MT
ms.contentlocale: pt-BR
ms.lasthandoff: 04/23/2019
ms.locfileid: "61768440"
---
# <a name="how-to-override-the-logical-tree"></a>Como: Substituir a árvore lógica
Embora não seja necessário na maioria dos casos, autores de controle avançados tem a opção de substituir a árvore lógica.
## <a name="example"></a>Exemplo
Este exemplo descreve como subclasse <xref:System.Windows.Controls.StackPanel> para substituir a árvore lógica, nesse caso, para impor um comportamento que o painel pode ter somente e renderizará somente um único elemento filho. Isso não é necessariamente um comportamento praticamente desejável, mas é mostrado aqui como um meio de que ilustra o cenário para substituir a árvore lógica normal de um elemento.
[!code-csharp[LogicalOverride#SingletonPanel](~/samples/snippets/csharp/VS_Snippets_Wpf/LogicalOverride/CSharp/SDKSampleLibrary/class1.cs#singletonpanel)]
Para obter mais informações sobre a árvore lógica, consulte [Árvores no WPF](trees-in-wpf.md).
|
JavaScript
|
UTF-8
| 812
| 2.984375
| 3
|
[] |
no_license
|
const Paint = require('./paint.js')
const Room = require('./room.js')
const Decorator = function () {
this.stock = [];
}
Decorator.prototype.addPaint = function (paint) {
this.stock.push(paint);
}
Decorator.prototype.countLitres = function () {
total = 0;
for (i = 0; i < this.stock.length; i++) {
total += this.stock[i].litres;
}
return total;
}
Decorator.prototype.canPaintRoom = function (room) {
if (this.countLitres() < room.area) {
return false;
}
else {
return true;
}
};
Decorator.prototype.paintRoom = function (room) {
if (this.canPaintRoom(room)) {
i = 0;
total = 0;
while (total !== room.area) {
total += this.stock[i].litres;
i++;
}
this.stock = this.stock.slice(i);
room.painted = true;
}
};
module.exports = Decorator;
|
C++
|
WINDOWS-1256
| 370
| 2.984375
| 3
|
[] |
no_license
|
/**
* Author
* Date 2019/3/27
* Version 1.0
*/
#include <iostream>
using namespace std;
int main()
{
double ba, interestRate;
cout<<"Enter balance and interest rate (e.g., 3 for 3%): ";
cin>>ba>>interestRate;
double in = ba * (interestRate / 1200);
cout<<"The interest is "<<in<<endl;
return 0;
}
|
JavaScript
|
UTF-8
| 364
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
/* Start Scroll Top Button */
var scrollbtn = document.getElementById('scrollup');
window.onscroll = function() {
if (window.pageYOffset >= 900) {
scrollbtn.style.display = "block";
} else {
scrollbtn.style.display = "none";
}
};
scrollbtn.onclick = function() {
window.scrollTo(0, 0);
};
/* End Scroll Top Button */
|
Java
|
UTF-8
| 770
| 2.390625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pbo10119913latihan59;
/**
* Nama :Muhammad Alvin Rizqi Ramdahn
* Kelas : IF10K
* NIM : 10119913
* @author Lenovo
*/
public class PemeranPendukung extends KarakterPemain{
private String panggilan;
public PemeranPendukung(String name, String food, String sifat, int umur) {
super(name, food, sifat, umur);
this.nama=name;
this.makanan=food;
this.sifat=sifat;
this.umur=umur;
}
public String getPanggilan() {
return panggilan;
}
public void setPanggilan(String panggilan) {
this.panggilan = panggilan;
}
}
|
PHP
|
UTF-8
| 31,780
| 2.96875
| 3
|
[] |
no_license
|
<?php
use SebastianBergmann\CodeCoverage\Driver\Xdebug;
/**
* Classe d'accès aux données.
*
* PHP Version 7
*
*
* @category PPE
* @package GSB\Includes
* @author Cheri Bibi - Réseau CERTA <contact@reseaucerta.org>
* @author José GIL - CNED <jgil@ac-nice.fr>
* @copyright 2017 Réseau CERTA
* @license Réseau CERTA
* @version GIT: <0>
* @link http://www.php.net/manual/fr/book.pdo.php PHP Data Objects sur php.net
*/
class PdoGsb
{
private static $serveur = 'mysql:host=localhost';
private static $bdd = 'dbname=gsb_frais';
private static $user = 'userGsb';
private static $mdp = 'secret';
private static $monPdo;
private static $monPdoGsb = null;
/**
* Constructeur privé, crée l'instance de PDO qui sera sollicitée
* pour toutes les méthodes de la classe
*/
private function __construct()
{
PdoGsb::$monPdo = new PDO(
PdoGsb::$serveur . ';' . PdoGsb::$bdd,
PdoGsb::$user,
PdoGsb::$mdp
);
PdoGsb::$monPdo->query('SET CHARACTER SET utf8');
}
/**
* Méthode destructeur appelée dès qu'il n'y a plus de référence sur un
* objet donné, ou dans n'importe quel ordre pendant la séquence d'arrêt.
*/
public function __destruct()
{
PdoGsb::$monPdo = null;
}
/**
* Fonction statique qui crée l'unique instance de la classe
* Appel : $instancePdoGsb = PdoGsb::getPdoGsb();
*
* @return l'unique objet de la classe PdoGsb
*/
public static function getPdoGsb()
{
if (PdoGsb::$monPdoGsb == null) {
PdoGsb::$monPdoGsb = new PdoGsb();
}
return PdoGsb::$monPdoGsb;
}
/**
* Retourne les informations d'un utilisateur
*
* @param String $login Login de l'utilisateur
* @param String $mdp Mot de passe de l'utilisateur
* @param String $table Table qui contient l'enregistrement
*
* @return l'id, le nom et le prénom sous la forme d'un tableau associatif
*/
public function getInfosUtilisateur($login, $mdp, $table)
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT $table.id AS id, $table.nom AS nom, "
. "$table.prenom AS prenom "
. "FROM $table "
. "WHERE $table.login = '$login' AND $table.mdp = '$mdp'"
);
$requetePrepare->execute();
return $requetePrepare->fetch();
}
/**
* Retourne les informations d'un utilisateur
*
* @param String $idUtilisateur id de l'utilisateur
* @param String $table Table qui contient l'enregistrement
*
* @return l'id, le nom et le prénom sous la forme d'un tableau associatif
*/
public function getNomUtilisateur($idUtilisateur, $table)
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT $table.id AS id, $table.nom AS nom, "
. "$table.prenom AS prenom "
. "FROM $table "
. "WHERE $table.id = '$idUtilisateur'"
);
$requetePrepare->execute();
return $requetePrepare->fetch();
}
/**
* Retourne sous forme d'un tableau associatif toutes les lignes de frais
* hors forfait concernées par les deux arguments.
* La boucle foreach ne peut être utilisée ici car on procède
* à une modification de la structure itérée - transformation du champ date-
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
*
* @return array : tous les champs des lignes de frais hors forfait sous la forme
* d'un tableau associatif
*/
public function getLesFraisHorsForfait($idVisiteur, $mois)
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT * FROM lignefraishorsforfait "
. "WHERE lignefraishorsforfait.idvisiteur = '$idVisiteur' "
. "AND lignefraishorsforfait.mois = '$mois'"
);
$requetePrepare->execute();
$lesLignes = $requetePrepare->fetchAll();
for ($i = 0; $i < count($lesLignes); $i++) {
$date = $lesLignes[$i]['date'];
$lesLignes[$i]['date'] = dateAnglaisVersFrancais($date);
}
return $lesLignes;
}
/**
* Retourne le nombre de justificatif d'un visiteur pour un mois donné
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
*
* @return int : le nombre entier de justificatifs
*/
public function getNbjustificatifs($idVisiteur, $mois)
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT fichefrais.nbjustificatifs as nb FROM fichefrais "
. "WHERE fichefrais.idvisiteur = '$idVisiteur' "
. "AND fichefrais.mois = '$mois'"
);
$requetePrepare->execute();
$laLigne = $requetePrepare->fetch();
return $laLigne['nb'];
}
/**
* Retourne sous forme d'un tableau associatif toutes les lignes de frais
* au forfait concernées par les deux arguments
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
*
* @return l'id, le libelle et la quantité sous la forme d'un tableau
* associatif
*/
public function getLesFraisForfait($idVisiteur, $mois)
{
$requetePrepare = PdoGSB::$monPdo->prepare(
"SELECT fraisforfait.id as idfrais, "
. "fraisforfait.libelle as libelle, "
. "lignefraisforfait.quantite as quantite "
. "FROM lignefraisforfait "
. "INNER JOIN fraisforfait "
. "ON fraisforfait.id = lignefraisforfait.idfraisforfait "
. "WHERE lignefraisforfait.idvisiteur = '$idVisiteur' "
. "AND lignefraisforfait.mois = '$mois' "
. "ORDER BY lignefraisforfait.idfraisforfait"
);
$requetePrepare->execute();
return $requetePrepare->fetchAll();
}
/**
* Fonction qui reçoit en paramètre un tableau de frais forfait,
* qui calcule le montant total de chaque frais et qui retourne
* un tableau réarrangé pour l'impression.
*
* @param array $lesFrais
* @return array $LesFraisForfaitCalcules
*/
public function getLesFraisForfaitCalcules($lesFrais, $tableFrais)
{
$LesFraisForfaitCalcules = array();
foreach ($lesFrais as $unFrais){
$idFrais = $unFrais['idfrais'];
$libelle = $unFrais['libelle'];
$quantite = $unFrais['quantite'];
$montantFrais = $this->getMontantFraisForfait($idFrais, $tableFrais);
$total = floatval($montantFrais) * floatval($quantite);
$LesFraisForfaitCalcules[] = array(
'libelle' => $libelle,
'quantite' => $quantite,
'montant' => $montantFrais,
'total' => number_format($total, 2, ',', ' ')
);
}
return $LesFraisForfaitCalcules;
}
/**
* Retourne sous forme d'un tableau associatif toutes les lignes de frais
* kilométriques concernées par les deux arguments
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
*
* @return l'id, le libelle et la quantité sous la forme d'un tableau
* associatif
*/
public function getLesFraisKm($idVisiteur, $mois)
{
$requetePrepare = PdoGSB::$monPdo->prepare(
"SELECT fraiskilometrique.id as idfrais, "
. "fraiskilometrique.libelle as libelle, "
. "lignefraisforfait.quantite as quantite "
. "FROM lignefraisforfait "
. "INNER JOIN fraiskilometrique "
. "ON fraiskilometrique.id = lignefraisforfait.idfraiskm "
. "WHERE lignefraisforfait.idvisiteur = '$idVisiteur' "
. "AND lignefraisforfait.mois = '$mois' "
. "ORDER BY lignefraisforfait.idfraiskm"
);
$requetePrepare->execute();
return $requetePrepare->fetchAll();
}
/**
* Retourne tous les id de la table FraisForfait
*
* @return array : un tableau associatif
*/
public function getLesIdFrais()
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT fraisforfait.id as idfrais "
. "FROM fraisforfait ORDER BY fraisforfait.id"
);
$requetePrepare->execute();
return $requetePrepare->fetchAll();
}
/**
* Retourne tous les id de la table Fraiskilometrique
*
* @return array : un tableau associatif
*/
public function getLesIdFraisKm()
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT fraiskilometrique.id as idfrais "
. "FROM fraiskilometrique "
. "ORDER BY fraiskilometrique.id"
);
$requetePrepare->execute();
return $requetePrepare->fetchAll();
}
/**
* Met à jour la table ligneFraisForfait
* Met à jour la table ligneFraisForfait pour un visiteur et
* un mois donné en enregistrant les nouveaux montants
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
* @param Array $lesFrais tableau associatif de clé idFrais et
* de valeur la quantité pour ce frais
*
* @return null
*/
public function majFraisForfait($idVisiteur, $mois, $lesFrais)
{
$lesCles = array_keys($lesFrais);
foreach ($lesCles as $unIdFrais) {
$qte = $lesFrais[$unIdFrais];
$requetePrepare = PdoGSB::$monPdo->prepare(
"UPDATE lignefraisforfait "
. "SET lignefraisforfait.quantite = $qte "
. "WHERE lignefraisforfait.idvisiteur = '$idVisiteur' "
. "AND lignefraisforfait.mois = '$mois' "
. "AND lignefraisforfait.idfraisforfait = '$unIdFrais'"
);
$requetePrepare->execute();
}
}
/**
* Met à jour la table ligneFraisForfait (frais kilometriques)
* Met à jour la table ligneFraisForfait pour un visiteur et
* un mois donné en enregistrant les nouveaux montants
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
* @param Array $lesFraisKm tableau associatif de clé idfrais
* et de valeur la quantité pour ce frais
*
* @return null
*/
public function majFraisKm($idVisiteur, $mois, $lesFraisKm)
{
$lesCles = array_keys($lesFraisKm);
foreach ($lesCles as $unIdFraisKm) {
$qte = $lesFraisKm[$unIdFraisKm];
$requetePrepare = PdoGSB::$monPdo->prepare(
"UPDATE lignefraisforfait "
. "SET lignefraisforfait.quantite = $qte "
. "WHERE lignefraisforfait.idvisiteur = '$idVisiteur' "
. "AND lignefraisforfait.mois = '$mois' "
. "AND lignefraisforfait.idfraiskm = '$unIdFraisKm'"
);
$requetePrepare->execute();
}
}
/**
* Met a jour la BDD en ajoutant la mention
* "REFUSE" devant le libellé du frais rejeté
* et en passant le montant a 0
* @param string $idFrais : ID de la ligne de frais
*/
public function rejeterFraisHorsForfait($idFrais)
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT lignefraishorsforfait.libelle "
. "FROM lignefraishorsforfait "
. "WHERE lignefraishorsforfait.id = '$idFrais'"
);
$requetePrepare->execute();
$resultat = $requetePrepare->fetch();
$libelle = 'REFUSE ' . $resultat['libelle'];
// vérifie que le nouveau libellé ne dépasse pas la taille maximum
// de 100 caract�res
$longueurLibelle = strlen($libelle);
if ($longueurLibelle > 100){
$libelle = substr($libelle, 0, 100);
}
$libelle = filtrerChainePourBD($libelle);
$requetePrepare = PdoGsb::$monPdo->prepare(
"UPDATE lignefraishorsforfait "
. "SET lignefraishorsforfait.libelle = '$libelle' "
. ", lignefraishorsforfait.montant = 0 "
. "WHERE lignefraishorsforfait.id = '$idFrais'"
);
$requetePrepare->execute();
}
/**
* Modifie la BDD pour reporter une ligne de frais hors
* forfait sur la fiche du mois suivant
* Création de la fiche du mois suivant si inexistante
*
* @param string $idVisiteur : ID du visiteur
* @param string $mois : $mois de la fiche en cours
* @param integer $idFrais : ID de la ligne de frais hors
* forfait
*/
public function reporterFraisHorsForfait($idVisiteur, $mois, $idFrais)
{
// récupère le mois suivant
$moisSuivant = getMoisSuivant($mois);
// vérifie qu'une fiche pour le mois suivant existe
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT fichefrais.idVisiteur "
. "FROM fichefrais "
. "WHERE fichefrais.idVisiteur = '$idVisiteur' "
. "AND fichefrais.mois = '$moisSuivant'"
);
$requetePrepare->execute();
$resultat = $requetePrepare->fetch();
if (!is_array($resultat)){
// créé la fiche Mois+1
$this->creeNouvellesLignesFrais($idVisiteur, $moisSuivant);
}
// Reporte la ligne au Mois+1
$requetePrepare = PdoGsb::$monPdo->prepare(
"UPDATE lignefraishorsforfait "
. "SET lignefraishorsforfait.mois = '$moisSuivant' "
. "WHERE lignefraishorsforfait.id = '$idFrais'"
);
$requetePrepare->execute();
}
/**
* Met à jour le nombre de justificatifs de la table fichefrais
* pour le mois et le visiteur concerné
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
* @param Integer $nbJustificatifs Nombre de justificatifs
*
* @return null
*/
public function majNbJustificatifs($idVisiteur, $mois, $nbJustificatifs)
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"UPDATE fichefrais "
. "SET nbjustificatifs = $nbJustificatifs "
. "WHERE fichefrais.idvisiteur = '$idVisiteur' "
. "AND fichefrais.mois = '$mois'"
);
$requetePrepare->execute();
}
/**
* Teste si un visiteur possède une fiche de frais pour le mois passé en argument
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
*
* @return boolean : vrai ou faux
*/
public function estPremierFraisMois($idVisiteur, $mois)
{
$boolReturn = false;
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT fichefrais.mois FROM fichefrais "
. "WHERE fichefrais.mois = '$mois' "
. "AND fichefrais.idvisiteur = '$idVisiteur'"
);
$requetePrepare->execute();
if (!$requetePrepare->fetch()) {
$boolReturn = true;
}
return $boolReturn;
}
/**
* Retourne le dernier mois en cours d'un visiteur
*
* @param String $idVisiteur ID du visiteur
*
* @return String : le mois sous la forme aaaamm
*/
public function dernierMoisSaisi($idVisiteur)
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT MAX(mois) as dernierMois "
. "FROM fichefrais "
. "WHERE fichefrais.idvisiteur = '$idVisiteur'"
);
$requetePrepare->execute();
$laLigne = $requetePrepare->fetch();
$dernierMois = $laLigne['dernierMois'];
return $dernierMois;
}
/**
* Crée une nouvelle fiche de frais et les lignes de frais au forfait
* pour un visiteur et un mois donnés
*
* Récupère le dernier mois en cours de traitement, met à 'CL' son champs
* idEtat, crée une nouvelle fiche de frais avec un idEtat à 'CR' et crée
* les lignes de frais forfait de quantités nulles
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
*
* @return null
*/
public function creeNouvellesLignesFrais($idVisiteur, $mois)
{
// cloture de la fiche de frais précédente
$dernierMois = $this->dernierMoisSaisi($idVisiteur);
$laDerniereFiche = $this->getLesInfosFicheFrais($idVisiteur, $dernierMois);
if ($laDerniereFiche['idEtat'] == 'CR') {
$this->majEtatFicheFrais($idVisiteur, $dernierMois, 'CL');
}
// création d'une nouvelle fiche pour le mois en cours
$requetePrepare = PdoGsb::$monPdo->prepare(
"INSERT INTO fichefrais (idvisiteur,mois,nbjustificatifs,"
. "montantvalide,datemodif,idetat) "
. "VALUES ('$idVisiteur','$mois',0,0,now(),'CR')"
);
$requetePrepare->execute();
// création des lignes de frais forfait
$lesIdFrais = $this->getLesIdFrais();
foreach ($lesIdFrais as $unIdFrais) {
$idFrais = $unIdFrais['idfrais'];
$requetePrepare = PdoGsb::$monPdo->prepare(
"INSERT INTO lignefraisforfait (idvisiteur,mois,"
. "idfraisforfait,quantite) "
. "VALUES('$idVisiteur', '$mois', '$idFrais', 0)"
);
$requetePrepare->execute();
}
// création des lignes de frais kilométrique
$lesIdFraisKm = $this->getLesIdFraisKm();
foreach ($lesIdFraisKm as $unIdFraisKm){
$idFraisKm = $unIdFraisKm['idfrais'];
$requetePrepare = PdoGsb::$monPdo->prepare(
"INSERT INTO lignefraisforfait (idvisiteur,mois,"
. "idfraiskm,quantite) "
. "VALUES('$idVisiteur', '$mois', '$idFraisKm', 0)"
);
$requetePrepare->execute();
}
}
/**
* Crée un nouveau frais hors forfait pour un visiteur un mois donné
* à partir des informations fournies en paramètre
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
* @param String $libelle Libellé du frais
* @param String $date Date du frais au format français jj//mm/aaaa
* @param Float $montant Montant du frais
*
* @return null
*/
public function creeNouveauFraisHorsForfait(
$idVisiteur,
$mois,
$libelle,
$date,
$montant
) {
$dateFr = dateFrancaisVersAnglais($date);
$requetePrepare = PdoGSB::$monPdo->prepare(
"INSERT INTO lignefraishorsforfait "
. "VALUES (null, '$idVisiteur','$mois', '$libelle', '$dateFr',"
. "$montant) "
);
$requetePrepare->execute();
}
/**
* Supprime le frais hors forfait dont l'id est passé en argument
*
* @param String $idFrais ID du frais
*
* @return null
*/
public function supprimerFraisHorsForfait($idFrais)
{
$requetePrepare = PdoGSB::$monPdo->prepare(
"DELETE FROM lignefraishorsforfait "
. "WHERE lignefraishorsforfait.id = '$idFrais'"
);
$requetePrepare->execute();
}
/**
* Retourne les mois pour lesquel un visiteur a une fiche de frais
*
* @param String $idVisiteur ID du visiteur
*
* @return array : un tableau associatif de clé un mois -aaaamm- et de valeurs
* l'année et le mois correspondant
*/
public function getLesMoisDisponibles($idVisiteur)
{
$requetePrepare = PdoGSB::$monPdo->prepare(
"SELECT fichefrais.mois AS mois FROM fichefrais "
. "WHERE fichefrais.idvisiteur = '$idVisiteur' "
. "ORDER BY fichefrais.mois desc"
);
$requetePrepare->execute();
$lesMois = array();
while ($laLigne = $requetePrepare->fetch()) {
$mois = $laLigne['mois'];
$numAnnee = substr($mois, 0, 4);
$numMois = substr($mois, 4, 2);
$lesMois[] = array(
'mois' => $mois,
'numAnnee' => $numAnnee,
'numMois' => $numMois
);
}
return $lesMois;
}
/**
* Récupère tous les visiteurs de la base de données
* @return array : un tableau associatif qui contien l'id, le nom et prénom
* de chaque visiteur
*/
public function getLesVisiteurs()
{
$requetePrepare = PdoGSB::$monPdo->prepare(
"SELECT visiteur.id AS id, visiteur.nom AS nom, "
. "visiteur.prenom AS prenom "
. "FROM visiteur "
. "ORDER BY visiteur.nom ASC"
);
$requetePrepare->execute();
$lesVisiteurs = array();
while($laLigne = $requetePrepare->fetch()) {
$idVisiteur = $laLigne['id'];
$nomVisiteur = $laLigne['nom'];
$prenomVisiteur = $laLigne['prenom'];
$lesVisiteurs[] = array(
'id' => $idVisiteur,
'nom' => $nomVisiteur,
'prenom' => $prenomVisiteur
);
}
return $lesVisiteurs;
}
/**
* Retourne les informations d'une fiche de frais d'un visiteur pour un
* mois donné
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
*
* @return array : un tableau avec des champs de jointure entre une fiche de frais
* et la ligne d'état
*/
public function getLesInfosFicheFrais($idVisiteur, $mois)
{
$requetePrepare = PdoGSB::$monPdo->prepare(
"SELECT fichefrais.idetat as idEtat, "
. "fichefrais.datemodif as dateModif,"
. "fichefrais.nbjustificatifs as nbJustificatifs, "
. "fichefrais.montantvalide as montantValide, "
. "etat.libelle as libEtat, "
. "fichefrais.auteurvalidation as comptable, "
. "fichefrais.datevalidation as datevalidation "
. "FROM fichefrais "
. "INNER JOIN etat ON fichefrais.idetat = etat.id "
. "WHERE fichefrais.idvisiteur = '$idVisiteur' "
. "AND fichefrais.mois = '$mois'"
);
$requetePrepare->execute();
$laLigne = $requetePrepare->fetch();
return $laLigne;
}
/**
* Modifie l'état et la date de modification d'une fiche de frais.
* Modifie le champ idEtat et met la date de modif à aujourd'hui.
*
* @param String $idVisiteur ID du visiteur
* @param String $mois Mois sous la forme aaaamm
* @param String $etat Nouvel état de la fiche de frais
*
* @return null
*/
public function majEtatFicheFrais($idVisiteur, $mois, $etat)
{
if($etat == 'VA'){
$idComptable = $_SESSION['idUtilisateur'];
$requetePrepare = PdoGSB::$monPdo->prepare(
"UPDATE fichefrais "
. "SET idetat = '$etat', datemodif = now(), "
. "auteurvalidation = '$idComptable', datevalidation = now() "
. "WHERE fichefrais.idvisiteur = '$idVisiteur' "
. "AND fichefrais.mois = '$mois'"
);
} else {
$requetePrepare = PdoGSB::$monPdo->prepare(
"UPDATE fichefrais "
. "SET idetat = '$etat', datemodif = now() "
. "WHERE fichefrais.idvisiteur = '$idVisiteur' "
. "AND fichefrais.mois = '$mois'"
);
}
$requetePrepare->execute();
}
/**
* Procédure qui met a jour dans la base de données le
* montant validé d'une fiche de frais
* @param $idVisiteur = id du visiteur
* @param $mois = mois de la fiche de frais
* @param $montant = montant total validé
*/
public function majMontantFicheFrais($idVisiteur, $mois, $montant)
{
$requetePrepare = PdoGSB::$monPdo->prepare(
"UPDATE fichefrais "
. "SET montantvalide = $montant, datemodif = now() "
. "WHERE fichefrais.idvisiteur = '$idVisiteur' "
. "AND fichefrais.mois = '$mois'"
);
$requetePrepare->execute();
}
public function calculeMontantTotalFiche(
$lesFraisForfait, $lesFraisKm, $lesFraisHorsForfait)
{
$montant = 0;
// calcul des frais forfait
foreach ($lesFraisForfait as $unFraisForfait){
$qteFrais = intval($unFraisForfait['quantite']);
if ($qteFrais <> 0){
$idFrais = $unFraisForfait['idfrais'];
$montantFrais = $this->getMontantFraisForfait($idFrais, 'fraisforfait');
$montant += intval($montantFrais) * $qteFrais;
}
}
// calcul des frais kilométriques
foreach ($lesFraisKm as $unFraisKm){
$qteFrais = intval($unFraisKm['quantite']);
if ($qteFrais <> 0){
$idFraisKm = $unFraisKm['idfrais'];
$montantFrais = $this->getMontantFraisForfait($idFraisKm, 'fraiskilometrique');
$montant += floatval($montantFrais) * $qteFrais;
}
}
// calcul des frais hors forfait
foreach ($lesFraisHorsForfait as $unFraisHorsForfait){
$libelle = ($unFraisHorsForfait['libelle']);
$debut_libelle = substr($libelle, 0,6);
if ($debut_libelle <> 'REFUSE'){
$montantFrais = intval($unFraisHorsForfait['montant']);
$montant += $montantFrais;
}
}
return $montant;
}
/**
* Fonction qui retourne le montant correspondant
* au frais forfait passé en paramètre
* @param $idFrais = id du frais forfait
* @return String chaine qui contient le montant correspondant
*/
public function getMontantFraisForfait($idFrais, $table)
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT montant as mnt FROM $table "
. "WHERE id = '$idFrais'"
);
$requetePrepare->execute();
$laLigne = $requetePrepare->fetch();
return $laLigne['mnt'];
}
/**
* Fonction qui met jour la base de donnée et qui
* cloture toutes les fiches de frais non cloturées
* du mois précédent
*/
public function clotureFichesMoisPrecedent()
{
$moisActuel = date('Ym');
$moisPrecedent = getMoisPrecedent($moisActuel);
$requetePrepare = PdoGsb::$monPdo->prepare(
"UPDATE fichefrais "
. "SET idetat = 'CL', datemodif = now() "
. "WHERE mois = '$moisPrecedent' "
. "AND idetat = 'CR'"
);
$requetePrepare->execute();
}
/**
* Récupère et retourne toutes les fiches qui
* ont été validées et qui sont donc a l'état :
* - validé - VA
* - mise en paiement - MP
* - remboursee - RB
*
* @return array : tableau associatif des fiches de frais
*/
public function getLesFichesValidees()
{
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT fichefrais.idvisiteur as idVisiteur, "
. "fichefrais.mois as mois, "
. "fichefrais.nbjustificatifs as nbJustificatifs, "
. "fichefrais.montantvalide as montantValide, "
. "visiteur.nom as nomVisiteur, "
. "visiteur.prenom as prenomVisiteur "
. "FROM fichefrais INNER JOIN visiteur "
. "ON fichefrais.idvisiteur = visiteur.id "
. "WHERE fichefrais.idetat <> 'CL' "
. "AND fichefrais.idetat <> 'CR' "
. "ORDER BY fichefrais.mois DESC"
);
$requetePrepare->execute();
$lesFichesValidees = array();
while($laLigne = $requetePrepare->fetch()) {
$idVisiteur = $laLigne['idVisiteur'];
$nomVisiteur = $laLigne['nomVisiteur'];
$prenomVisiteur = $laLigne['prenomVisiteur'];
$mois = $laLigne['mois'];
$montantValide = $laLigne['montantValide'];
$nbJustificatifs = $laLigne['nbJustificatifs'];
$lesFichesValidees[] = array(
'idVisiteur' => $idVisiteur,
'nomVisiteur' => $nomVisiteur,
'prenomVisiteur' => $prenomVisiteur,
'mois' => $mois,
'montantValide' => $montantValide,
'nbJustificatifs' => $nbJustificatifs,
);
}
return $lesFichesValidees;
}
/**
* Fonction utilisée une seule fois suite au changement de
* structure de la base de données pour la gestion des
* frais kilométrique.
* La fonction parcours les fiches de frais et insert
* des lignes de frais kilométrique la ou il en manque.
* Peut être réutilisée si ajout de frais kilométrique dans
* la base de données.
*/
public function insertFraisKmPrecedentesFiches()
{
//récupération de toutes les fiches
$requetePrepare = PdoGsb::$monPdo->prepare(
"SELECT idvisiteur as idVisiteur, "
. "mois as mois FROM fichefrais"
);
$requetePrepare->execute();
$lesFiches = array();
while($laLigne = $requetePrepare->fetch()) {
$idVisiteur = $laLigne['idVisiteur'];
$mois = $laLigne['mois'];
$lesFiches[] = array(
'idVisiteur' => $idVisiteur,
'mois' => $mois,
);
}
// récupération des id frais km
$lesIdFraisKm = $this->getLesIdFraisKm();
// parcours des fiches
foreach ($lesFiches as $uneFiche){
//récupère les lignes de frais km
$levisiteur = $uneFiche['idVisiteur'];
$lemois = $uneFiche['mois'];
$lesFraisKm = $this->getLesFraisKm($levisiteur, $lemois);
// parcours des ID de frais km
foreach ($lesIdFraisKm as $unIdFraisKm){
$idFraisKm = $unIdFraisKm['idfrais'];
$trouve = false;
foreach ($lesFraisKm as $unFraisKm){
if ($idFraisKm == $unFraisKm['idfrais']){
$trouve = true;
}
}
if (!$trouve){
// insertion dans la table
$requetePrepare = PdoGsb::$monPdo->prepare(
"INSERT INTO lignefraisforfait VALUES "
. "('$levisiteur', '$lemois', NULL , '$idFraisKm', 0, '')"
);
$requetePrepare->execute();
}
}
}
}
}
|
C#
|
ISO-8859-3
| 3,625
| 2.6875
| 3
|
[] |
no_license
|
// DOSBox, Scrum.org, Professional Scrum Developer Training
// Authors: Rainer Grau, Daniel Tobler, Zhlke Technology Group
// Copyright (c) 2012 All Right Reserved
using System.Collections.Generic;
using System.Linq;
using DosBox.Filesystem;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace DosBoxTest.Filesystem
{
[TestClass]
public class DirectoryTest
{
private Directory rootDir;
private Directory subDir1;
private Directory subDir2;
private File file1InSubDir1;
private File file2InSubDir1;
[TestInitialize]
public void setUp()
{
this.rootDir = new Directory("root");
this.subDir1 = new Directory("subDir1");
rootDir.Add(this.subDir1);
this.subDir2 = new Directory("subDir2");
rootDir.Add(this.subDir2);
this.file1InSubDir1 = new File("file1InSubDir1", "content1");
subDir1.Add(this.file1InSubDir1);
this.file2InSubDir1 = new File("file2InSubDir1", "content2");
subDir1.Add(this.file2InSubDir1);
}
[TestMethod]
public void Constructor_CreateWithName_IsCorrectlyCreated()
{
string name = "root";
var testdir = new Directory(name);
Assert.AreEqual(name, testdir.Name);
Assert.AreEqual(0, testdir.GetNumberOfContainedDirectories());
Assert.AreEqual(0, testdir.GetNumberOfContainedFiles());
Assert.IsNull(testdir.Parent);
}
[TestMethod]
public void Content_Subdirectory_RootContainsValidData_BaseForNextTests()
{
IEnumerable<FileSystemItem> content = rootDir.Content;
Assert.IsNotNull(content);
Assert.AreEqual(2, content.Count());
}
[TestMethod]
public void Content_Subdirectory_Element0HasCorrectName()
{
FileSystemItem item = rootDir.Content.ElementAt(0);
Assert.IsTrue(item.IsDirectory());
Assert.AreEqual(subDir1.Name, item.Name);
Assert.AreSame(this.subDir1, item);
}
[TestMethod]
public void Content_Subdirectory_ParentIsSetCorrectly()
{
FileSystemItem item = rootDir.Content.ElementAt(0);
FileSystemItem parent = item.Parent;
Assert.IsTrue(parent.IsDirectory());
Assert.AreSame(this.rootDir, parent);
}
[TestMethod]
public void Content_Subdirectory_ParentIsSetCorrectly1()
{
FileSystemItem item = rootDir.Content.ElementAt(0);
FileSystemItem parent = item.Parent;
Assert.IsNotNull(parent.Parent == null);
string path = item.Path;
Assert.IsTrue(path.CompareTo(rootDir.Name + "\\" + subDir1.Name) == 0);
}
[TestMethod]
public void testContainingFiles()
{
FileSystemItem dir = rootDir.Content.ElementAt(0);
FileSystemItem file1 = dir.Content.ElementAt(0);
Assert.IsNotNull(file1);
Assert.AreEqual(this.file1InSubDir1, file1);
}
[TestMethod]
public void testForDirectory()
{
Assert.IsTrue(rootDir.IsDirectory());
Assert.IsTrue(subDir2.IsDirectory());
}
[TestMethod]
public void testRename()
{
subDir1.Name = "NewName";
Assert.IsTrue(subDir1.Name.CompareTo("NewName") == 0);
}
[TestMethod]
public void testNumberOfFilesAndDirectories()
{
// TODO
}
}
}
|
C++
|
UTF-8
| 1,069
| 2.90625
| 3
|
[] |
no_license
|
#ifndef EVENTS_HPP
#define EVENTS_HPP
#include <iostream>
#include <random>
#include <string>
#include "../../spark.hpp"
class Die {
private:
std::mt19937 eng{std::random_device{}()};
unsigned int rolls, sides;
public:
unsigned int roll() {
unsigned int roll = 0;
for(unsigned int i = 0; i < rolls; ++i) {
roll += std::uniform_int_distribution<unsigned int>{1, sides}(eng);
}
return roll;
}
Die(unsigned int _rolls, unsigned int _sides): rolls(_rolls), sides(_sides) { }
};
enum EventType {
EVENT_DAMAGE = 0,
EVENT_HEAL,
EVENT_DEAL_DAMAGE,
EVENT_INCREMENT_POSITION,
EVENT_UPDATE,
EVENT_GET_RENDER_DATA
};
enum DamageType {
DAMAGE_FIRE = 0,
DAMAGE_ICE,
DAMAGE_SLASH
};
struct Damage {
int damageDealt;
DamageType type;
Damage(int _damageDealt, DamageType _type): damageDealt(_damageDealt), type(_type) { }
};
struct DealDamageEvent { std::vector<Damage> damageVec; };
struct HealEvent { int health; };
struct PositionIncrementEvent { int incAmount; };
struct RenderEvent {
std::string name, description;
char symbol;
};
#endif
|
Java
|
UTF-8
| 17,426
| 2.265625
| 2
|
[] |
no_license
|
package com.test;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.apache.commons.io.FileUtils;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.index.lucene.unsafe.batchinsert.LuceneBatchInserterIndexProvider;
import org.neo4j.unsafe.batchinsert.BatchInserter;
import org.neo4j.unsafe.batchinsert.BatchInserterIndex;
import org.neo4j.unsafe.batchinsert.BatchInserterIndexProvider;
import org.neo4j.unsafe.batchinsert.BatchInserters;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Created by Diak on 2017/5/27.
* bloomfilter查询试验与cypher查询试验
*/
public class Test1 {
private String dbPath;
private long nodeCount;
private static enum RelTypes implements RelationshipType {
aggragetes;//����ֻ��֧��һ�ֹ�ϵ
}
public Test1(String dbPath, long nodeCount){
this.dbPath = dbPath;
this.nodeCount = nodeCount;
}
private void clearDB(){
try{
FileUtils.deleteDirectory(new File(dbPath));//�������IJ���
} catch (IOException e) {
e.printStackTrace();
}
}
public void storeWithoutIndex(){
BatchInserter inserter = null;
try{
long start,end;
clearDB();
inserter = BatchInserters.inserter(new File(dbPath));
Map<String, Object> nodeMap = new HashMap<>();
start = System.currentTimeMillis();
for(long i = 1; i < nodeCount; i++){
nodeMap.put("attribute1",i%10);
nodeMap.put("attribute2",i%1000);
nodeMap.put("attribute3",i%100000);
nodeMap.put("attribute4",i%10000000);
if(i<(nodeCount/2)){
inserter.createNode(i, nodeMap, Label.label("First"));//����Ҫ����label
}else{
inserter.createNode(i, nodeMap, Label.label("Second"));
}
}
end = System.currentTimeMillis();
System.out.println("create-node-time:" + (end - start) + "ms");
// GraphDatabaseService graphdb = new GraphDatabaseFactory().newEmbeddedDatabase(new File(dbPath));
// String query1 = "explain ";
// Transaction tx = graphdb.beginTx();
// try {
// Iterable<IndexDefinition> indexs = graphdb.schema().getIndexes(label1);
// tx.success();
// } catch (Exception e){
// e.printStackTrace();
// tx.failure();
// }finally {
// tx.close();
// }
}catch (IOException e){
e.printStackTrace();
}finally {
if(inserter != null){
inserter.shutdown();
}
}
}
public GraphDatabaseService openDB(){
GraphDatabaseService graphdb = new GraphDatabaseFactory().newEmbeddedDatabase(new File(dbPath));
return graphdb;
}
public void storeDepthData(){
BatchInserter inserter = null;
try{
long start,end;
// clearDB();
inserter = BatchInserters.inserter(new File(dbPath));
Map<String, Object> nodeMap = new HashMap<>();
start = System.currentTimeMillis();
for(long i = 100; i < 200; i++){
nodeMap.put("name","name" + i);
inserter.createNode(i, nodeMap, Label.label("IfcObject1"));
}
for(long i = 1000; i < 2000; i++){
nodeMap.put("name","name" + i);
inserter.createNode(i, nodeMap, Label.label("IfcObject2"));
}
for(long i = 10000; i < 20000; i++){
nodeMap.put("name","name" + i);
inserter.createNode(i, nodeMap, Label.label("IfcObject3"));
}
for(long i = 100000; i < 200000; i++){
nodeMap.put("name","name" + i);
inserter.createNode(i, nodeMap, Label.label("IfcObject4"));
}
for(long i = 1000000; i < 2000000; i++){
nodeMap.put("name","name" + i);
inserter.createNode(i, nodeMap, Label.label("IfcObject5"));
}
for(long i = 2000000; i < 3000000; i++){
nodeMap.put("name","name" + i);
inserter.createNode(i, nodeMap, Label.label("IfcObject6"));
}
for(long i = 3000000; i < 4000000; i++){
nodeMap.put("name","name" + i);
inserter.createNode(i, nodeMap, Label.label("IfcObject7"));
}
end = System.currentTimeMillis();
System.out.println("insert-node-time:" + (end-start));
//create relationship
//1 aid to 10 bid aid*10+(0/1/2/3/4/5/6/7/8/9)
start = System.currentTimeMillis();
for(long i = 100; i < 200; i++){
for(int j = 0; j < 10; j++){
inserter.createRelationship(i, i*10 + j,RelTypes.aggragetes,null);
}
}
for(long i = 1000; i < 2000; i++){
for(int j = 0; j < 10; j++){
inserter.createRelationship(i, i*10 + j,RelTypes.aggragetes,null);
}
}
for(long i = 10000; i < 20000; i++){
for(int j = 0; j < 10; j++){
inserter.createRelationship(i, i*10 + j,RelTypes.aggragetes,null);
}
}
for(long i = 100000; i < 200000; i++){
for(int j = 0; j < 10; j++){
inserter.createRelationship(i, i*10 + j,RelTypes.aggragetes,null);
}
}
for(long i = 100; i <200; i++ ){
for(int j = 0; j < 10000; j++){
inserter.createRelationship(i, i*10000 + j + 1000000,RelTypes.aggragetes,null);
}
}
for(long i = 1000; i <2000; i++ ){
for(int j = 0; j < 1000; j++){
inserter.createRelationship(i, i*1000 + j + 2000000,RelTypes.aggragetes,null);
}
}
end = System.currentTimeMillis();
System.out.println("insert-rel-time:" + (end-start));
}catch (IOException e){
e.printStackTrace();
}finally {
if(inserter != null){
inserter.shutdown();
}
}
}
public void query(GraphDatabaseService graphdb){
long start,end;
Result result;
String[] querys = {
// "match (n{attribute1:9}) return count(n)",//query-node-attribute1 1
// "match (n{attribute2:9}) return count(n)",//query-node-attribute2 2
// "match (n{attribute3:9}) return count(n)",//query-node-attribute3 3
// "match (n{attribute4:9}) return count(n)",//query-node-attribute4 4
// "match (n) where id(n)=9999 return count(n),id(n),n.label,n.attribute1,n.attribute2,n.attribute3,n.attribute4",//query-node-id 0
// "match (n) where id(n)=9999 return count(n),id(n),n.label,n.attribute1,n.attribute2,n.attribute3,n.attribute4",
// "match (n) where id(n)=9999 return count(n),id(n),n.label,n.attribute1,n.attribute2,n.attribute3,n.attribute4"
// "match (n:First{attribute1:9}) return count(n)",//query-node-label-attribute1 5
// "match (n:First{attribute2:9}) return count(n)",//query-node-label-attribute2 6
// "match (n:First{attribute3:9}) return count(n)",//query-node-label-attribute3 7
// "match (n:First{attribute4:9}) return count(n)",//query-node-label-attribute4 8
// "create index on:First(attribute1)",//create-index-First-attribute1 9
// "create index on:First(attribute2)",//create-index-First-attribute2 10
// "create index on:First(attribute3)",//create-index-First-attribute3 11
// "create index on:First(attribute4)",//create-index-First-attribute4 12
// "match (n{attribute1:9}) return count(n)",//query-node-attribute1 13
// "match (n{attribute2:9}) return count(n)",//query-node-attribute2 14
// "match (n{attribute3:9}) return count(n)",//query-node-attribute3 15
// "match (n{attribute4:9}) return count(n)",//query-node-attribute4 16
// "match (n:First{attribute1:9}) return count(n)",//query-node-label-attribute1 17
// "match (n:First{attribute2:9}) return count(n)",//query-node-label-attribute2 18
// "match (n:First{attribute3:9}) return count(n)",//query-node-label-attribute3 19
// "match (n:First{attribute4:9}) return count(n)",//query-node-label-attribute4 20
};
for(int i = 0; i < querys.length; i++){
start = System.currentTimeMillis();
result = graphdb.execute(querys[i]);
end = System.currentTimeMillis();
System.out.println("querys[" + i + "]:" + (end - start) + "ms");
Map<String, Object> row;
while(result.hasNext()){
row = result.next();
for(String key : result.columns()){
System.out.print(key + ":" + row.get(key) + " ");
}
System.out.println("\n");
}
}
}
public void newQuery(GraphDatabaseService graphdb){
long start, end;
//neoe4j create index
String[] createIndex = {
"create index on :IfcObject1(name)",
"create index on :IfcObject2(name)",
"create index on :IfcObject3(name)",
"create index on :IfcObject4(name)",
"create index on :IfcObject5(name)",
"create index on :IfcObject6(name)",
"create index on :IfcObject7(name)"
};
// Transaction transaction;
// transaction = graphdb.beginTx();
for(int i = 0; i < createIndex.length; i++){
graphdb.execute(createIndex[i]);
}
// Iterator<IndexDefinition> iterator = graphdb.schema().getIndexes().iterator();
// int indexCount = 0;
// while (iterator.hasNext()){
// iterator.next();
// indexCount++;
// }
// transaction.success();
// transaction.close();
// System.out.println("indexCount: " + indexCount);
// System.out.println();
//construct bloomfilter
int expectedInsertions = 1000000;
double fpp = 0.000001;
BloomFilter bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), expectedInsertions, fpp);
start = System.currentTimeMillis();
for(int j = 100;j < 200; j++) {
for (int k = 0; k < 10; k++) {
for (int t = 0; t < 1000; t++) {
bloomFilter.put(String.valueOf(j) + String.valueOf(j*10 + k) + String.valueOf((j*10 + k)*1000 + t + 2000000));
}
}
}
end = System.currentTimeMillis();
System.out.println("create-bloomfilter-time: " + String.valueOf(end - start) + " ms");
System.out.println();
//neo4j depth data query
// transaction = graphdb.beginTx();
for(int i = 1; i < 4; i++){
//��ֵ������������;��ֵ��ѯ����д��
start = System.currentTimeMillis();
Result result = null;
String queryStr = null;
List<String> keyList = null;
Map<String, Object> row = null;
int inGraphCount = 0;
int outofGraphCount = 0;
for(int j = 100;j < 110; j++){
for(int k = 0; k < 10; k++){
for(int t = 0; t < 100; t++){
queryStr = "match (n:IfcObject1{name:\"name" + j + "\"})"
+ " - [r1] -> " + "(m:IfcObject2{name:\"name" + String.valueOf(j*10 + k) + "\"})"
+ " - [r2] -> " + "(s:IfcObject7{name:\"name"+ String.valueOf((j*10 + k)*1000 + t + 2000000) + "\"})"
+ " return id(n),id(m),id(s)";
// if(j == 101 && k == 2 && t == 3){
// System.out.println(queryStr);
// }
result = graphdb.execute(queryStr);
if(result.hasNext()){
keyList = result.columns();
row = result.next();
row.get(keyList.get(0));
row.get(keyList.get(1));
row.get(keyList.get(2));
inGraphCount++;
} else{
outofGraphCount++;
}
}
}
}
end = System.currentTimeMillis();
System.out.println(i + "th" + "-lookup-time based on Cypher: " + String.valueOf(end - start) + " ms");
// System.out.println("inGraphCount: " + inGraphCount);
// System.out.println("outofGraphCount: " + outofGraphCount);
System.out.println();
}
// transaction.success();
// transaction.close();
//my way to query
// transaction = graphdb.beginTx();
for(int i = 1; i < 4; i++){
//��ֵ������������;��ֵ��ѯ����д��
Result myResult = null;
String bfQueryStr = null; //�����ֵҪ�������һ�£�
StringBuilder composedId = null;
List<String> keyList = null;
int inbfCount = 0;
int outofbfCount = 0;
start = System.currentTimeMillis();
for(int j = 100;j < 110; j++){
for(int k = 0; k < 10; k++){
for(int t = 0; t < 100; t++){
composedId = new StringBuilder();
bfQueryStr = "match (n:IfcObject1{name:\"name" + j + "\"}) return id(n)";
myResult = graphdb.execute(bfQueryStr);
keyList = myResult.columns();
if(myResult.hasNext()){
composedId.append(myResult.next().get(keyList.get(0)));
} else {
outofbfCount++;
break;
}
bfQueryStr = "match (m:IfcObject2{name:\"name" + String.valueOf(j*10 + k) + "\"}) return id(m)";
myResult = graphdb.execute(bfQueryStr);
keyList = myResult.columns();
if (myResult.hasNext()){
composedId.append(myResult.next().get(keyList.get(0)));
} else {
outofbfCount++;
break;
}
bfQueryStr = "match (s:IfcObject7{name:\"name" + String.valueOf((j*10 + k)*1000 + t + 2000000) + "\"}) return id(s)";
myResult = graphdb.execute(bfQueryStr);
keyList = myResult.columns();
if (myResult.hasNext()){
composedId.append(myResult.next().get(keyList.get(0)));
} else {
outofbfCount++;
break;
}
if (bloomFilter.mightContain(composedId.toString())){
inbfCount++;
}
}
}
}
end = System.currentTimeMillis();
System.out.println(i + "th" + "-lookup-time based on BloomFilter: " + String.valueOf(end - start) + " ms");
// System.out.println("inbfCount: " + inbfCount);
// System.out.println("outofbfCount: " + outofbfCount);
System.out.println();
}
// transaction.success();
// transaction.close();
}
public static void main(String args[]){
Test1 test1 = new Test1(args[0],Long.parseLong(args[1]));
// test1.storeDepthData();
GraphDatabaseService graphdb = test1.openDB();
test1.newQuery(graphdb);
// String query = "match (n) return count(n)";
// String query = "match (n:IfcObject1{name:\"name100\"}) - [r1] -> (m:IfcObject2{name:\"name1000\"}) - [r2] -> (s:IfcObject7{name:\"name3000000\"}) return id(n),id(m),id(s)";
// Result result = graphdb.execute(query);
// Map<String, Object> row = null;
// while(result.hasNext()){
// row = result.next();
// System.out.println(row.get(result.columns().get(0)));
// }
graphdb.shutdown();
}
}
|
Java
|
UTF-8
| 757
| 2.234375
| 2
|
[] |
no_license
|
package com.QuasarFireOperationMS.web.model.base;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class ResponseModel<T> extends ResponseInfo {
T data;
public ResponseModel(T data) {
this.data = data;
}
private ResponseModel(String code, String message) {
this.code = code;
this.message = message;
}
public static <T> ResponseModel<T> success(T data) {
return new ResponseModel<>(data);
}
public static <T> ResponseModel<T> success() {
return new ResponseModel<>();
}
public static <T> ResponseModel<T> info(String code, String message) {
return new ResponseModel<>(code, message);
}
}
|
Java
|
UTF-8
| 2,678
| 2.546875
| 3
|
[] |
no_license
|
package com.cs414.monopoly.ui.dialog;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.cs414.monopoly.entities.GetOutOfJailFree;
import com.cs414.monopoly.entities.Player;
import com.cs414.monopoly.game.GameState;
import com.cs414.monopoly.game.PreRollState;
import com.cs414.monopoly.ui.MonopolySkin;
public class JailDialog extends BlankDialog {
Player current = GameState.getInstance().getCurrentPlayer();
public JailDialog() {
super("You're in Jail! Select an option...");
show(GameState.getInstance().getStage());
TextButton close = new TextButton("Roll", new MonopolySkin());
close.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
remove();
}
});
TextButton pay_$50 = new TextButton("Pay $50", new MonopolySkin());
pay_$50.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
pay();
remove();
}
});
TextButton chance = new TextButton("Chest\nGet out of Jail", new MonopolySkin());
TextButton chest = new TextButton("Chance\nGet out of Jail", new MonopolySkin());
if(current.getMoney() < 50) {
disable(pay_$50);
}
GetOutOfJailFree cards = current.getGetOutOfJail();
if(!cards.hasCard(GetOutOfJailFree.CHANCE)) {
disable(chance);
}
if(!cards.hasCard(GetOutOfJailFree.CHEST)) {
disable(chest);
}
defaults().width(getWidth()/4.1f);
add(chance);
add(chest);
add(pay_$50);
add(close);
}
private void disable(TextButton btn) {
btn.setColor(Color.RED);
btn.setTouchable(Touchable.disabled);
}
private void pay() {
current.modifyMoney(-50);
releasePlayer();
}
private void useCard(GetOutOfJailFree card) {
current.getGetOutOfJail().removeCard(card);
}
private void releasePlayer() {
current.inJail = 0;
current.space.placePlayer(current);
GameState.getInstance().getCurrentContext().currentState = new PreRollState();
}
/**
* Called by the framework when an actor is added to or removed from a group.
*
* @param parent May be null if the actor has been removed from the parent.
*/
@Override
protected void setParent(Group parent) {
super.setParent(parent);
setSize(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/5);
}
}
|
C
|
UTF-8
| 2,051
| 2.765625
| 3
|
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_fill_env.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jlange <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/11/03 18:42:28 by jlange #+# #+# */
/* Updated: 2017/11/03 19:50:38 by jlange ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static inline char *find_value(char *env)
{
char *new_env;
char *value;
int i;
i = 0;
while (env[i] && env[i] != '=')
i++;
value = ft_itoa(ft_atoi(&env[i + 1]) + 1);
new_env = ft_strjoin("SHLVL=", value);
free(value);
return (new_env);
}
static inline char **up_sh_lvl(char **env, int i)
{
char **new_env;
if (ft_getenv("SHLVL", env) == NULL)
{
new_env = ft_setenv("SHLVL", "1", env);
return (new_env);
}
if (!(new_env = (char**)malloc(sizeof(char*) * (i + 1))))
return (NULL);
i = 0;
while (env[i])
{
if (ft_strncmp("SHLVL=", env[i], ft_strlen("SHLVL=")))
new_env[i] = ft_strdup(env[i]);
else
new_env[i] = find_value(env[i]);
i++;
}
new_env[i] = NULL;
return (new_env);
}
void ft_fill_env(t_shell *sh, char **env)
{
char pwd[PATH_MAX];
char *pwd2;
sh->env = up_sh_lvl(env, tab_2d_len(env));
if ((pwd2 = ft_getenv("PWD", env)) == NULL)
{
getcwd(pwd, sizeof(pwd));
sh->env = ft_replace_env(ft_setenv("PWD", pwd, sh->env), sh->env);
sh->pwd = ft_strdup(pwd);
}
else
{
sh->pwd = ft_strdup(&pwd2[4]);
sh->env = ft_replace_env(ft_setenv("PWD", sh->pwd, sh->env), sh->env);
}
}
|
Java
|
UTF-8
| 4,275
| 2.671875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package contactmanagementsoftware.strategy.pattern;
import contactmanagementsoftware.Acquaintances;
import contactmanagementsoftware.MUI;
import contactmanagementsoftware.ProfessionalFriends;
/**
*
* @author luxianze
*/
public class ProfessionalFriendsUISetter extends UISetter {
public ProfessionalFriendsUISetter(MUI muiInstance) {
super(muiInstance);
}
@Override
public void setUI() {
/**
* Set text to compose title
*/
muiInstance.getjLabel7().setText("Common Interests: ");
muiInstance.getjLabel7().setVisible(true);
muiInstance.getjLabel8().setVisible(false);
muiInstance.textAreaTwo.setVisible(false);
muiInstance.jScrollPane4.setVisible(false);
muiInstance.getjLabel9().setVisible(false);
muiInstance.textAreaThree.setVisible(false);
muiInstance.jScrollPane5.setVisible(false);
muiInstance.getjButton10().setVisible(true);
muiInstance.getjButton11().setVisible(true);
muiInstance.getNameTextField().setEditable(!muiInstance.getIsDisplayOnly());
muiInstance.getMobileTextField().setEditable(!muiInstance.getIsDisplayOnly());
muiInstance.getEmailTextField().setEditable(!muiInstance.getIsDisplayOnly());
muiInstance.textAreaOne.setEditable(!muiInstance.getIsDisplayOnly());
muiInstance.textAreaTwo.setEditable(!muiInstance.getIsDisplayOnly());
muiInstance.textAreaThree.setEditable(!muiInstance.getIsDisplayOnly());
if (muiInstance.getIsAddContact()) {
/**
* If we are adding new, set all input boxes content to empty
*/
muiInstance.getNameTextField().setText("");
muiInstance.getMobileTextField().setText("");
muiInstance.getEmailTextField().setText("");
muiInstance.textAreaOne.setText("");
muiInstance.textAreaTwo.setText("");
muiInstance.textAreaThree.setText("");
muiInstance.op = "Add";
muiInstance.getjButton10().setText("Add");
muiInstance.getjPanel3().setBorder(javax.swing.BorderFactory.createTitledBorder(null, muiInstance.op + " Professional Friends Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DialogInput", 1, 16)));
} else {
/**
* - Set the text for all the fields since they should already have
* some values - If we are not adding, we can fall into edit/view
* full details mode, therefore do another checking here
*/
Acquaintances selectedAcquaintance = muiInstance.getCurrentAcquaintance();
muiInstance.getNameTextField().setText(selectedAcquaintance.getName());
muiInstance.getMobileTextField().setText(selectedAcquaintance.getMobileNo());
muiInstance.getEmailTextField().setText(selectedAcquaintance.getEmail());
ProfessionalFriends professionalFriend = (ProfessionalFriends) selectedAcquaintance;
muiInstance.textAreaOne.setText(professionalFriend.getCommonInterests());
if (muiInstance.getIsDisplayOnly()) {
muiInstance.getjButton10().setText("Back to main menu");
muiInstance.getjButton11().setVisible(false);
muiInstance.getjPanel3().setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Display Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DialogInput", 1, 16)));
} else {
muiInstance.op = "Edit";
muiInstance.getjButton10().setText("Save");
muiInstance.getjPanel3().setBorder(javax.swing.BorderFactory.createTitledBorder(null, muiInstance.op + " Professional Friends Details", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("DialogInput", 1, 16)));
}
}
}
}
|
Python
|
UTF-8
| 394
| 2.90625
| 3
|
[] |
no_license
|
res1 = []
r, c = [int(temp) for temp in input().split()]
for temp in range(c + 1) : res1.append(0)
for tem in range(r) :
tem1 = [temp for temp in input().split()]
tem2 = list(map(int, tem1))
print(' '.join(tem1) + ' ' + str(sum(tem2)))
for mak in range(c) :
res1[mak] = res1[mak] + tem2[mak]
res1[c] += sum(tem2)
res2 = list(map(str, res1))
print(' '.join(res2))
|
Markdown
|
UTF-8
| 1,786
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
# About
The tests use [Intern](https://theintern.github.io/intern/).
There are unit tests and functional tests.
The unit tests test the *was-the-site-loaded-from-cache* decision making,
and the functional tests are used to capture Resource Timing data from a
[dummy site](./www/) (which can be used as input to the the
*was-the-site-loaded-from-cache* decision making code).
The functional test will use the URL set by `config.urlToCaptureEntriesFor`
in the `test/intern/intern-functional.js` file and:
- Open the URL, capture the `Performance.getEntriesByType("resource")` data
using the tag `first`.
- Call `window.location.reload(true)` in the browser to simulate a Ctrl+R
force refresh (to send `If-Modified-Since` HTTP requests). Capture
the `Performance.getEntriesByType("resource")` data again using the tag
`reload`.
- Open the URL again to simulate a repeat visit (resources should come from
browser cache). Capture the `Performance.getEntriesByType("resource")` data
again using the tag `revisit`.
# Running
Start the [capture server](../src/capture-server/README.md).
Start Selenium. The tests require Selenium to be running. This can either be
a local server, or something like [Sauce Labs](https://saucelabs.com).
Run the tests:
node node_modules/intern/bin/intern-runner.js config=test/config/intern-functional
To take resource timings from a different URL, pass `urlToCaptureEntriesFor`
at the command line:
node node_modules/intern/bin/intern-runner.js config=test/config/intern-functional urlToCaptureEntriesFor=http://www.example.com/the/page/
## Unit Tests
Use `intern-client.js` (not `intern-runner.js`) and `intern-base` (not
`intern-functional`).
node node_modules/intern/bin/intern-client.js config=test/config/intern-base
|
Shell
|
UTF-8
| 566
| 3.15625
| 3
|
[] |
no_license
|
#!/bin/bash
net="2001:470:5816:f::/64"
out_dir=/tmp/keylogger/
ip route add local "$net" dev lo
tcpdump -l -i any "icmp6[icmptype] == icmp6-echo and dst net $net" \
| awk -v out_dir="$out_dir" -f <(cat - <<-'SCRIPT'
function save_char(n, ip) {
n = strtonum("0x"n)
if(n == 0xd) {
n = 0xa;
}
if((n >= 0x20 && n < 0x80) || n == 0xa) {
printf("%c", n) >> out_dir ip
}
}
{
split($5, a, ":");
for(i = 4; i < length(a); i++) {
save_char(substr(a[i], 1, 2), $3)
save_char(substr(a[i], 3, 2), $3)
}
fflush()
}
SCRIPT
)
|
Java
|
UTF-8
| 993
| 1.953125
| 2
|
[] |
no_license
|
package au.edu.rmit.bdm.Torch.mapMatching;
import au.edu.rmit.bdm.Torch.base.Torch;
public class MMProperties {
public String vehicleType = Torch.vehicleType.CAR;
public String mmAlg = Torch.Algorithms.HMM_PRECOMPUTED;
public String trajSrcPath;
public String osmPath;
public int batchSize = 10000;
public int preComputationRange = 1000;
public String baseDir = "Torch";
public MMProperties(){}
public MMProperties(MMProperties p){
vehicleType = p.vehicleType;
mmAlg = p.mmAlg;
trajSrcPath = p.trajSrcPath;
osmPath = p.osmPath;
batchSize = p.batchSize;
preComputationRange = p.preComputationRange;
baseDir = p.baseDir;
}
public void reset() {
vehicleType = Torch.vehicleType.CAR;
mmAlg = Torch.Algorithms.HMM_PRECOMPUTED;
trajSrcPath = null;
osmPath = null;
batchSize = 10000;
preComputationRange = 1000;
baseDir = "Torch";
}
}
|
Java
|
UTF-8
| 1,024
| 3.640625
| 4
|
[] |
no_license
|
package Structural.Facade.Subsistem;
public class GameCoins {
private int gameCoins = 60;
public int getGameCoins() {
return this.gameCoins;
}
public void decreaseGameCoins(int spentCoins) {
this.gameCoins -= spentCoins;
}
public void increaseGameCoins(int earnedCoins) {
this.gameCoins += earnedCoins;
}
public boolean haveEnoughGameCoins(int gameCoinsRequired) {
if(gameCoinsRequired > getGameCoins()) {
System.out.println("You don't have enough coins");
System.out.println("Current coins: " + getGameCoins());
return false;
} else {
decreaseGameCoins(gameCoinsRequired);
System.out.println("Current coins: " + getGameCoins());
return true;
}
}
public void earnCoins(int coinsToEarn) {
increaseGameCoins(coinsToEarn);
System.out.println("Coins earned!!");
System.out.println("Current coins: " + getGameCoins());
}
}
|
C#
|
UTF-8
| 1,792
| 3.453125
| 3
|
[] |
no_license
|
using System;
using System.Threading;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
Student student = new Student("Долженко Илья Андреевич", 32, "ТПО", 98, DateTime.Now);
Console.WriteLine($"Студент: {student.getName()}, Группа: {student.getGroup()}");
Console.WriteLine($"Предмет: {student.getSubject()}, Оценка: {student.getMark()}, Дата: {student.getTime()}");
Console.WriteLine("----------------------------------------------------");
Student student2 = new Student("Волобуев Юрий Сергеевич", 32, "ТПО", 65, DateTime.Now);
Console.WriteLine($"Студент: {student2.getName()}, Группа: {student2.getGroup()}");
Console.WriteLine($"Предмет: {student2.getSubject()}, Оценка: {student2.getMark()}, Дата: {student2.getTime()}");
Console.ReadKey();
}
}
public class Student
{
private string name;
private int group;
private int mark;
private string subject;
private DateTime time;
public Student(string name, int group, string subject, int mark, DateTime time)
{
this.group = group;
this.name = name;
this.subject = subject;
this.mark = mark;
this.time = time;
}
public string getName()
{
return name;
}
public int getGroup()
{
return group;
}
public int getMark()
{
return mark;
}
public string getSubject()
{
return subject;
}
public DateTime getTime()
{
return time;
}
}
}
|
Swift
|
UTF-8
| 466
| 2.609375
| 3
|
[] |
no_license
|
//
// InvestmentModel.swift
// MyInvestment
//
// Created by Daniel Yount on 1/30/19.
// Copyright © 2019 Daniel Yount. All rights reserved.
//
import Foundation
struct Investment: Codable {
let name: String
let amount: Double
let returnOnInvestment: Double
let id: Int
enum CodingKeys: String, CodingKey {
case name = "name"
case amount = "amount"
case returnOnInvestment = "ROI"
case id = "id"
}
}
|
Java
|
UTF-8
| 1,992
| 2.234375
| 2
|
[] |
no_license
|
package pl.edu.pw.bgtTracker.db.entities;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import net.minidev.json.JSONObject;
import org.springframework.format.annotation.DateTimeFormat;
import pl.edu.pw.bgtTracker.db.entities.base.NamedEntity;
import javax.persistence.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Entity
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Bill extends NamedEntity {
private long amount;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private Date dueDate;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private Date paymentDate;
private String bankNumber;
private boolean paid;
private String note;
@ManyToOne(optional = false)
@JoinColumn(name = "category_id", referencedColumnName = "id")
private ExpenseCategory category;
@ManyToOne(optional = false)
@JoinColumn(name = "user_id", referencedColumnName = "id")
@JsonIgnore
private AppUser user;
public JSONObject toJSON() {
JSONObject json = new JSONObject();
json.put("id", Long.toString(id));
json.put("amount", amount);
json.put("name", name);
json.put("category", category.getName());
json.put("category_id", category.getId());
json.put("user", user.getId());
DateFormat dateFromat = new SimpleDateFormat("dd.MM.yyyy"); // dobrze zwraca 20.12.2020
String strDate = dateFromat.format(dueDate);
json.put("date", strDate);
if(paymentDate == null)
{
json.put("paymentDay","");
}
else{
String strDate2 = dateFromat.format(paymentDate);
json.put("paymentDay",strDate2);
}
json.put("bankAccount", bankNumber);
json.put("isPaid", paid);
json.put("note", note);
return json;
}
}
|
Python
|
UTF-8
| 1,021
| 2.546875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
import torch
import io
from torchtext.utils import download_from_url, extract_archive, unicode_csv_reader
from torchtext.data.utils import ngrams_iterator
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
def _csv_iterator(data_path, ngrams, yield_cls=False):
tokenizer = get_tokenizer("basic_english")
with io.open(data_path, encoding="utf8") as f:
reader = unicode_csv_reader(f)
for row in reader:
tokens = ' '.join(row[1:])
# print(tokens)
tokens = tokenizer(tokens)
# print(tokens)
if yield_cls:
yield int(row[0]) - 1, ngrams_iterator(tokens, ngrams)
else:
yield ngrams_iterator(tokens, ngrams)
# vocab = build_vocab_from_iterator(_csv_iterator(".data/ag_news_csv/train.csv", 2))
vocab = build_vocab_from_iterator(_csv_iterator(".data/aclass/train_word.csv", 2))
print ('Vocab Size: %d' % len(vocab))
torch.save(vocab, "test_vocab.i")
|
C
|
UTF-8
| 2,629
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* k w i l d . c
*
* perform a wildcard match and place in the file list
* Original by VSL International, Switzerland.
* Modified: 01-May-87 J. A. Pickering, Southampton Univ., UK.
* Modified: Aug 1987 E. Zakrajsek, Cromemco Inc.
*/
#include "kermit.h"
extern char *strchr();
extern char *malloc();
/*
* g e t n a m e s
*
* getnames puts all the names that match the names given into list at
* count
*/
getnames(list, string, count)
char *list[] ;
char *string;
int count;
{
FILE *dirfile; /* directory file */
char dirname[MAXWORD], /* directory prefix */
olddir[MAXWORD], /* old directory */
matchstr[MAXWORD], /* matching string */
file[MAXLINE]; /* file name */
register char *pattern, /* search pattern */
*indname; /* a pointer to dirname */
register i, /* a counter */
last; /* files before these */
/* initialize */
last = count;
/* strip off the directory prefix */
indname = pattern = dirname;
strcpy(dirname, string);
if (debug > 1)
fprintf(dpfp,"> (Getnames) looking for %s\n", indname);
while (indname = strchr(indname, '/'))
pattern = ++indname;
if (*pattern == '^')
++pattern;
strcpy(matchstr, pattern);
if (*(pattern - 1) == '/')
*(pattern - 1) = '\0';
else
*pattern = '\0';
if (!*dirname) {
*dirname = '.';
dirname[1] = '\0';
}
if (!(dirfile = fopen(dirname, "r")) ||
fstat(dirname, st_ftype) != is_direct) {
printmsg("Cannot open the directory '%s'.", dirname);
return (count);
}
if (debug > 1)
fprintf(dpfp,"> (Getnames) pattern is %s/%s\n", dirname, matchstr);
while ((*file = getc(dirfile)) != EOF) {
for (i = 1; i < 32; i++)
file[i] = getc(dirfile);
if ( match(matchstr, file)) {
list[count] = malloc(MAXWORD);
sprintf(list[count++], "%s/%s", dirname, file);
if (debug > 1)
fprintf(dpfp,"> (Getnames) %s\n", list[count - 1]);
}
}
if (last == count)
error("No match on %s/%s\n", dirname,matchstr);
fclose(dirfile);
return(count);
}
/*
* m a t c h
*
* match string to pattern
*/
match(pattern, line)
register char *pattern;
register char *line;
{
while (*pattern) {
if (*pattern == Allwild) {
if(!*++pattern)
return(TRUE);
while (*line)
if (match(pattern, line++))
return(TRUE);
return(FALSE);
}
else if (*pattern == Onewild) {
if (!*line++)
return(FALSE);
++pattern;
}
else if (*pattern++ != *line++)
return(FALSE);
}
return(!*line);
}
|
JavaScript
|
UTF-8
| 1,098
| 2.90625
| 3
|
[] |
no_license
|
import React from 'react'
class TodoList extends React.Component {
constructor() {
super()
this.state = {
item:'',
items: []
}
this.handleInputChange=this.handleInputChange.bind(this)
this.addItem=this.addItem.bind(this)
}
handleInputChange(event){
let name = event.target.name
let value = event.target.value
this.setState({[name]:value})
}
addItem(){
let items = this.state.items
let item = this.state.item
items.push(item)
this.setState({items:items})
}
render() {
return (
<div>
<br></br>
<br></br>
<input type="text" name="item" placeholder="type your text here" onChange={this.handleInputChange}></input>
<br></br>
<br></br>
<button type="button" onClick={this.addItem}>Add item</button>
{this.state.items.map((item)=> {
return (
<p>{item}</p>
)
})}
</div>
)
}
}
export default TodoList;
|
C
|
UTF-8
| 162
| 3.0625
| 3
|
[] |
no_license
|
#include <stdio.h>
int main() {
char arr[101];
int i=0;
gets(arr);
while(arr[i]!='\0') i++;
for(i-=1; i>=0; i--) printf("%c", arr[i]);
return 0;
}
|
JavaScript
|
UTF-8
| 4,928
| 2.625
| 3
|
[] |
no_license
|
import conf from './conf';
const addYears = (dt, years) => {dt.setFullYear(dt.getFullYear() + years); return dt;}
const yearsAdded = (dt, years) => addYears(new Date(dt), years);
const addMonths = (dt, months) => dt.setMonth(dt.getMonth() + months);
const monthsAdded = (dt, months) => addMonths(new Date(dt), months);
const addDays = (dt, days) => {dt.setDate(dt.getDate() + days); return dt}
const daysAdded = (dt, days) => addDays(new Date(dt), days);
export function getDateDiff(pre, now) {
pre = new Date(pre);
const sign = pre < now ? 1 : -1;
if (sign < 0) {
[pre, now] = [now, pre];
}
let years = now.getFullYear() - pre.getFullYear();
if (yearsAdded(pre, years) > now) {
years -= 1;
}
addYears(pre, years);
let months = 1;
for (; months <= 12; months += 1) {
if (monthsAdded(pre, months) > now) {
months -= 1;
break;
}
}
addMonths(pre, months);
let days = 1;
for (; days <= 31; days += 1) {
if (daysAdded(pre, days) > now) {
days -= 1;
break;
}
}
addDays(pre, days);
let val = (now - pre) / 1000;
const seconds = val % 60;
val = Math.floor(val / 60);
const minutes = val % 60;
val = Math.floor(val / 60);
const hours = val;
return [years, months, days, hours, minutes, seconds];
}
export async function fetchData(method, url, data, success, error) {
if (data instanceof Function) {
error = success;
success = data;
data = undefined;
}
const externalURL = url.startsWith('http');
let options;
[url, options] = prepareFetch(method, url, data);
console.log(method + ' ' + url);
if (method === 'POST' || method === 'PUT') {
console.log(options);
}
const resp = await fetch(url, options);
const text = resp.text();
if (externalURL) {
text.then(success);
}
text.then(text => {
try {
const json = JSON.parse(text);
console.log('\n');
console.log('=== RESPONSE ==================================');
console.log(method + ' ' + url);
console.log(json);
if (json.errno) {
console.log('[RESPONSE with nonzero errno]');
if (error) {
error(json);
}
} else if (success) {
success(json);
}
console.log('=== RESPONSE END ==============================');
console.log('\n');
} catch (e) {
console.log('\n');
console.log('[ERROR] ' + method + ' ' + url);
console.log(e);
console.log('================ Body ================');
console.log(text);
console.log('============ End of body =============');
console.log('[ERROR end]');
console.log('\n');
}
}).catch(e => {
console.log('\n');
console.log('[ERROR] ' + method + ' ' + url);
console.log(e);
console.log('[ERROR end]');
console.log('\n');
});
}
export async function fetchJSON(method, url, data) {
let options;
[url, options] = prepareFetch(method, url, data);
console.log('-----> ' + method + ' ' + url);
if (method === 'POST' || method === 'PUT') {
console.log(options);
}
const resp = await fetch(url, options);
const json = resp.json();
json.then((json) => {
console.log('\n');
console.log('=== RESPONSE ==================================');
console.log(method + ' ' + url);
console.log(json);
console.log('=== RESPONSE END ==============================');
console.log('\n');
});
if (json.errno) {
alert(json.detail);
console.log(json.detail);
throw Error(json);
}
return json;
}
function prepareFetch(method, url, data) {
if (!url.startsWith('http')) {
url = conf.backend_origin + url;
}
data = data || {};
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
if (conf.backend_origin.slice(5) !== 'https') {
headers.append('Cache-Control', 'no-cache');
}
const options = {
method: method,
headers: headers,
credentials: 'include',
}
if (method === 'POST' || method === 'PUT') {
Object.assign(options, {
body: JSON.stringify(data)
});
} else if ((method === 'GET' && data) || method === 'DELETE') {
let args = [];
Object.keys(data).forEach((key) => {
let value = data[key];
if (value !== undefined && value !== null) {
if (value instanceof Array) {
value = `[${value.map(encodeURIComponent).join(',')}]`;
}
const arg = encodeURIComponent(key) + '=' + encodeURIComponent(value);
args.push(arg);
}
});
if (args.length > 0) {
url += '?' + args.join('&');
}
}
return [url, options];
}
export function getCurrentUser(then) {
fetchData('GET', '/api/me', then, then);
}
export function excludedSpread(props, excludes) {
excludes = excludes || [];
props = {...props};
for (const propName of excludes) {
delete props[propName];
}
return props;
}
|
Java
|
UTF-8
| 2,420
| 1.78125
| 2
|
[] |
no_license
|
// Generated code from Butter Knife. Do not modify!
package com.example.ui;
import android.view.View;
import butterknife.ButterKnife.Finder;
import butterknife.ButterKnife.ViewBinder;
public class MainActivity$$ViewBinder<T extends com.example.ui.MainActivity> implements ViewBinder<T> {
@Override public void bind(final Finder finder, final T target, Object source) {
View view;
view = finder.findRequiredView(source, 2131361797, "field 'viewPager1'");
target.viewPager1 = finder.castView(view, 2131361797, "field 'viewPager1'");
view = finder.findRequiredView(source, 2131361799, "field 'tv1' and method 'onClick'");
target.tv1 = finder.castView(view, 2131361799, "field 'tv1'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131361800, "field 'tv2' and method 'onClick'");
target.tv2 = finder.castView(view, 2131361800, "field 'tv2'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131361801, "field 'tv3' and method 'onClick'");
target.tv3 = finder.castView(view, 2131361801, "field 'tv3'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131361802, "field 'tv4' and method 'onClick'");
target.tv4 = finder.castView(view, 2131361802, "field 'tv4'");
view.setOnClickListener(
new butterknife.internal.DebouncingOnClickListener() {
@Override public void doClick(
android.view.View p0
) {
target.onClick(p0);
}
});
view = finder.findRequiredView(source, 2131361798, "field 'caidan'");
target.caidan = finder.castView(view, 2131361798, "field 'caidan'");
}
@Override public void unbind(T target) {
target.viewPager1 = null;
target.tv1 = null;
target.tv2 = null;
target.tv3 = null;
target.tv4 = null;
target.caidan = null;
}
}
|
Java
|
UTF-8
| 659
| 1.523438
| 2
|
[] |
no_license
|
/*
* Copyright 2001-2008 Aqris Software AS. All rights reserved.
*
* This program is dual-licensed under both the Common Development
* and Distribution License ("CDDL") and the GNU General Public
* License ("GPL"). You may elect to use one or the other of these
* licenses.
*/
package net.sf.refactorit.classmodel;
import net.sf.refactorit.vfs.Source;
/**
* @author Tonis Vaga
*/
public final class JspCompilationUnit extends CompilationUnit {
public JspCompilationUnit(final Source aSource, final Project project) {
super(aSource, project);
//DebugInfo.trace("created JspCompilationUnit "+aSource.getName());
}
}
|
Java
|
UTF-8
| 466
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.store.sale.converters;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.store.sale.input.SaleInput;
import com.store.sale.model.Sale;
@Component
public class SaleDisassemblerInput {
@Autowired
private ModelMapper modelMapper;
public Sale toDomainObject (SaleInput saleInput) {
return modelMapper.map(saleInput, Sale.class);
}
}
|
Python
|
UTF-8
| 1,164
| 3.703125
| 4
|
[] |
no_license
|
#!/usr/bin/env python
# _*_coding:utf-8 _*_
#@Time :2019/1/3 16:31
#@Author :ZYK
#@FileName: 590_n-ary-tree-postorder-traversal.py
'''
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树 :
返回其后序遍历: [5,6,3,2,4,1].
'''
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
# if not root:
# return []
# if not root.children:
# return [root.val]
# result = []
# for child in root.children:
# result += self.postorder(child)
# result += [root.val]
# return result
if not root:
return []
stack = []
result = []
stack.append(root)
while stack:
curr = stack.pop()
result.append(curr.val)
if curr.children:
curr.children.reverse()
stack += curr.children
return result
|
Java
|
UTF-8
| 1,887
| 2.5625
| 3
|
[] |
no_license
|
package com.example.demo.config;
import com.example.demo.bean.UserBase;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class JwtTokenUtil {
/**
* token过期时间
*/
@Value("${jwt.validity-time}")
private long validityTime; // 24 hours validity
/**
* header中标识
*/
@Value("${jwt.header}")
private String header;
/**
* 加密密钥
*/
@Value("${jwt.secret}")
private String secret;
/**
* 验签
* 从用户中创建一个jwt Token
* @param userDTO 用户
* @return token
*/
public String create(UserBase userBase ) {
return Jwts.builder()
.setExpiration(new Date(System.currentTimeMillis() + validityTime))
.setIssuedAt(new Date(System.currentTimeMillis() + validityTime/3*2 ))
.claim("username",userBase.getUserName())
.claim("password",userBase.getPassword())
.claim("roles",userBase.getRole())
.claim("id",userBase.getId())
.signWith(SignatureAlgorithm.HS256,secret)
.compact();
}
/**
* 从token中取出用户
*/
public UserBase parse(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
UserBase userDTO = new UserBase();
userDTO.setPassword(claims.get("password",String.class));
userDTO.setUserName(claims.get("username",String.class));
userDTO.setRole( claims.get("roles",String.class));
userDTO.setId( claims.get("id",Integer.class));
return userDTO;
}
}
|
Python
|
UTF-8
| 1,584
| 2.8125
| 3
|
[] |
no_license
|
# Removing outliers using a Conditional or RadiusOutlier removal
# http://pointclouds.org/documentation/tutorials/remove_outliers.php#remove-outliers
import pcl
import numpy as np
import random
import argparse
parser = argparse.ArgumentParser(
description='PointCloudLibrary example: Remove outliers')
parser.add_argument('--Removal', '-r', choices=('Radius', 'Condition'), default='',
help='RadiusOutlier/Condition Removal')
args = parser.parse_args()
def main():
cloud = pcl.load('../data/table_scene_lms400.pcd')
cloud_filtered = pcl.PointCloud()
if args.Removal == 'Radius':
outrem = cloud.make_RadiusOutlierRemoval()
outrem.set_radius_search(1.0)
outrem.set_MinNeighborsInRadius(2)
cloud_filtered = outrem.filter()
elif args.Removal == 'Condition':
range_cond = cloud.make_ConditionAnd()
range_cond.add_Comparison2('z', pcl.CythonCompareOp_Type.GT, 0.0)
range_cond.add_Comparison2('z', pcl.CythonCompareOp_Type.LT, 1.0)
# build the filter
condrem = cloud.make_ConditionalRemoval()
condrem.set_KeepOrganized(True)
# apply filter
cloud_filtered = condrem.filter()
# Test
# cloud_filtered = cloud
else:
print("please specify command line arg paramter 'Radius' or 'Condition'")
print('Cloud before filtering: ')
print(cloud.size)
print('Cloud after filtering: ')
print(cloud_filtered.size)
if __name__ == "__main__":
# import cProfile
# cProfile.run('main()', sort='time')
main()
|
Markdown
|
UTF-8
| 2,328
| 3.515625
| 4
|
[] |
no_license
|
一致性hash
凡是涉及到分布式的系统,就会有负载均衡和数据分布的问题。为了让连接(或者数据)能够分布得更均匀,很多时候会使用到Hash算法
Hash算法:
把任意长度得输入,通过Hash算法变换成固定长度的输出,这个输出就是Hash值,哈希值的空间远小于输入的空间,所以可能会发生“哈希碰撞”,即两个不同的输入产生了同一个输出。
负载均衡
先Hash再取模,在负载均衡中十分常见
hash(request)%n
假设我们现在有三个服务器,想要做负载均衡,就可以对请求的ip地址或者用户id等使用hash函数,然后计算得出hash值对3取模,余数为几,就把请求分配到相应的服务器上
弊端:
在分布式场景下,横向伸缩是一个很正常的需求。试想,当上述的3台服务器需要扩展到4台服务器,那绝大多数请求基本上都需要重新映射到另一个节点。因为Hash值没变,除数变了,余数必然会变
这种变动有时候是不能接受的。比如在Web负载均衡的情景下,session会保存在每个节点里,如果是“无状态”的服务,那不会存在这个问题。但如果数据持久化场景,这种大的变动显然是不能接受的。因为如果增加或者删除了一个节点,就会导致导致几乎所有的数据都需要重新迁移。
一致性hash
使用一致性Hash可以解决因为横向伸缩导致的大规模数据变动。
用节点数量作为除数去求余。而一致性Hash的除数是2^32.从0到2^32-1,首位相连构成一个环,我们先对服务器节点的IP进行hash,然后除以2^32得到服务器节点在这个Hash环中的位置:
现在有请求过来了,同样进行Hash然后处于2^32求余。如果落在Hash环上,然后顺时针找到第一个节点,这个节点就负责处理这个请求;
分布不均匀问题:
一致性hash算法在节点数量较少的时候,会出现分布不均匀的问题
解决方法:在Hash环上增加虚拟节点
实现方式很多,比如:
hash("SERVER_IP_A#1")%2^32
一致性Hash有什么用?
除了前面提到的负载均衡,Web session和数据库分库分表可以应用外,其实一致性Hash应用得最多的领域是分布式缓存
|
C#
|
UTF-8
| 757
| 2.859375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ChangePass
{
public partial class ChangePassword : Form
{
static string path = "pass.data";
public ChangePassword()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(path))
{
file.WriteLine(textBox1.Text);
file.WriteLine(textBox2.Text);
}
Close();
}
}
}
|
JavaScript
|
UTF-8
| 1,661
| 3.8125
| 4
|
[] |
no_license
|
// Los elementos que queremos
let lista = document.getElementById("listaDeTareas");
let botonAgregarTarea = document.getElementById("botonAgregarTarea");
let inputTareaNueva = document.getElementById("nuevaTarea")
// Reaccionamos al clic
botonAgregarTarea.addEventListener("click", agregarTareaALista);
function agregarTareaALista(){
// Una lista requiere de Items, en HTML
// estos son elementos <li>contenido</li>
// Podemos acceder al contenido del elemento UL
// por medio del atributo innerHTML
//lista.innerHTML = "<li>"+ inputTareaNueva.value +"</li>"
// El código anterior únicamente permite mantener un item no agrega.
// Concatenamos en valor anterior, para tener un nuevo LI (usamos TEMPLATE STRINGS)
lista.innerHTML = lista.innerHTML + `<li>${inputTareaNueva.value}</li>`;
/* Los TEMPLATE STRINGS son una nueva característica de JS que nos permite INTERPOLAR
(insertar) expresiones y valores dentro de la cadena usando ${}; aprende más en:
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/template_strings */
inputTareaNueva.value = "";
}
// Esto no nos funciona, queremos que se agregue al dar enter, mejoremos esto
// inputTareaNueva.addEventListener("keypress", agregarTareaALista);
inputTareaNueva.addEventListener("keypress", function(event){
// podemos verificar el código de la tecla presionada (https://keycode.info/),
// y ejecutar el código 13 pertenece al enter
if(event.keyCode==13) agregarTareaALista();
// Tambien podríamos emular el clic sobre el boton
// if(event.keyCode==13) botonAgregarTarea.click();
});
|
Java
|
ISO-8859-1
| 5,738
| 3.390625
| 3
|
[] |
no_license
|
package dados.repositorios;
import negocios.classesBasicas.Cliente;
import negocios.classesBasicas.Produto;
import negocios.exceptions.EmptyListException;
/**
* Classe que representa o repositorio de clientes implementado em Lista.
*
* @author lfs
*
*/
public class RepositorioClientesLista implements RepositoriosClientes, Iterator {
private Node<Cliente> primeiroNo;
private Node<Cliente> ultimoNo;
private int indiceIterator;
private Cliente[] iterator;
public RepositorioClientesLista() {
this.primeiroNo = this.ultimoNo = null;
}
private RepositorioClientesLista(Cliente[] itr) {
this.indiceIterator = 0;
this.iterator = itr;
}
/**
* Metodo que cria um novo No, adiciona a informacao(Cliente) nesse n e
* liga ele Lista.
*
* @param clientes
* Cliente - Cliente a ser inserido na Lista.
*/
public void inserir(Cliente clientes) {
if (isEmpty()) {
primeiroNo = ultimoNo = new Node<Cliente>(clientes);
} else {
Node<Cliente> aux = ultimoNo;
Node<Cliente> novo = new Node<Cliente>(ultimoNo, clientes, null);
ultimoNo = novo;
if (aux == null) {
primeiroNo = novo;
} else {
aux.setProximo(novo);
}
}
}
/**
* Metodo que recebe um ID e procura, na lista, um objeto No que contenha,
* como dado, um objeto Cliente que possua um ID igual ao que se procura. Ao
* encontrar, retorna o objeto Cliente.
*
* @param id
* String - ID do cliente a ser procurado
* @return resposta Cliente - Cliente que possui ID igual ao procurado.
*/
public Cliente procurar(String id) {
Cliente resposta = null;
boolean achou = false;
Node<Cliente> atual = primeiroNo;
while (atual != null && achou == false) {
if (atual.getDado().getId().equals(id)) {
resposta = atual.getDado();
achou = true;
}
atual = atual.getProximo();
}
return resposta;
}
/**
* Recebe um ID e um Cliente, a fim de trocar as informacoes do cliente que
* possui aquele ID.
*
* @param id
* String - ID do cliente a ser atualizado.
* @param clientes
* Cliente - Novo objeto atualizado a ser alocado no lugar do
* antigo.
*/
public void atualizar(String id, Cliente clientes) {
Node<Cliente> atual = this.procurarNode(id);
atual.setDado(clientes);
}
/**
* Recebe um ID e, usando o metodo procurarNode(), encontra o N que contem
* aquele cliente como dado. Depois, simplesmente desvincula aquele n da
* lista. Mais tarde, ele ser pego pelo GarbageCollector
*
* @param id
* String - ID do cliente a ser removido da lista.
*/
public void remover(String id) {
if (this.procurarNode(id) == null) {
System.out.println("Nao existe na lista");
} else {
final Node<Cliente> atual = this.procurarNode(id);
final Node<Cliente> proximo = atual.getProximo();
final Node<Cliente> anterior = atual.getAnterior();
if (anterior == null) {
primeiroNo = proximo;
} else {
anterior.setProximo(proximo);
}
if (proximo == null) {
ultimoNo = anterior;
} else {
proximo.setAnterior(anterior);
}
}
}
/**
* Metodo que retorna a informao de se a lista est ou no vazia.
*
* @return boolean - True se tiver vazia, False se no.
*/
public boolean isEmpty() {
return primeiroNo == null;
}
/**
* Metodo que recebe um ID e procura, n a n, um objeto Cliente que
* contenha aquele ID. Caso encontre, ele retorna o n que contm o Cliente
* possuidor daquele ID.
*
* @param id
* String - ID do cliente que se procura
* @return Node<Cliente> - N que contem, como dado, o cliente procurado.
*/
private Node<Cliente> procurarNode(String id) {
Node<Cliente> resposta = null;
boolean achou = false;
Node<Cliente> atual = primeiroNo;
while (atual != null && achou == false) {
if (atual.getDado().getId().equals(id)) {
resposta = atual;
achou = true;
}
atual = atual.getProximo();
}
return resposta;
}
/**
* Recebe um obejto Cliente e procura, n a n, um objeto idntico. Caso
* encontre, retorna true. Caso no, retorna false.
*
* @param clientes
* @return boolean - True se existir, False se no.
*/
public boolean existe(Cliente clientes) {
Node<Cliente> atual = this.primeiroNo;
while (atual != null) {
if (atual.getDado().equals(clientes)) {
return true;
}
atual = atual.getProximo();
}
return false;
}
public int size() {
int count = 0;
Node<Cliente> atual = primeiroNo;
while (atual != null) {
count++;
atual = atual.getProximo();
}
return count;
}
public String toString() {
String resposta = "";
if (isEmpty()) {
resposta = "Lista vazia";
} else {
Node<Cliente> atual = primeiroNo;
// Enquanto nao chegar ao fim, coloca os dados de cada objeto na
// resposta
while (atual != null) {
resposta = resposta + atual.getDado().toString() + "\n\n";
atual = atual.getProximo();
}
}
return resposta;
}
public Iterator<Cliente> getIterator() throws EmptyListException {
if (isEmpty()) {
throw new EmptyListException();
}
int count = 0;
Cliente[] itr = new Cliente[this.size()];
Node<Cliente> atual = primeiroNo;
while (atual != null) {
itr[count] = atual.getDado().clone();
atual = atual.getProximo();
count++;
}
RepositorioClientesLista iterator = new RepositorioClientesLista(itr);
return iterator;
}
public Cliente next() {
Cliente resposta = null;
resposta = this.iterator[this.indiceIterator];
this.indiceIterator++;
return resposta;
}
public boolean hasNext() {
if(indiceIterator >= iterator.length) {
return false;
}
return this.iterator[this.indiceIterator] != null;
}
}
|
Ruby
|
UTF-8
| 206
| 2.625
| 3
|
[] |
no_license
|
require './Egoing'
#require_relative 'Egoing' #상대경로
module K8805_a #대문자로 써야 되네?
module_function()
def b()
return 'B'
end
end
puts(Egoing.a())
puts(K8805_a.b())
|
PHP
|
UTF-8
| 4,215
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
<?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer;
use PhpCsFixer\Fixer\FixerInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
* @author Katsuhiro Ogawa <ko.fivestar@gmail.com>
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*/
class Config implements ConfigInterface
{
private string $cacheFile = '.php-cs-fixer.cache';
/**
* @var FixerInterface[]
*/
private array $customFixers = [];
/**
* @var null|iterable<\SplFileInfo>
*/
private ?iterable $finder = null;
private string $format = 'txt';
private bool $hideProgress = false;
private string $indent = ' ';
private bool $isRiskyAllowed = false;
private string $lineEnding = "\n";
private string $name;
/**
* @var null|string
*/
private $phpExecutable;
/**
* @TODO: 4.0 - update to @PER
*
* @var array<string, array<string, mixed>|bool>
*/
private array $rules = ['@PSR12' => true];
private bool $usingCache = true;
public function __construct(string $name = 'default')
{
$this->name = $name;
}
public function getCacheFile(): string
{
return $this->cacheFile;
}
public function getCustomFixers(): array
{
return $this->customFixers;
}
/**
* @return Finder
*/
public function getFinder(): iterable
{
if (null === $this->finder) {
$this->finder = new Finder();
}
return $this->finder;
}
public function getFormat(): string
{
return $this->format;
}
public function getHideProgress(): bool
{
return $this->hideProgress;
}
public function getIndent(): string
{
return $this->indent;
}
public function getLineEnding(): string
{
return $this->lineEnding;
}
public function getName(): string
{
return $this->name;
}
public function getPhpExecutable(): ?string
{
return $this->phpExecutable;
}
public function getRiskyAllowed(): bool
{
return $this->isRiskyAllowed;
}
public function getRules(): array
{
return $this->rules;
}
public function getUsingCache(): bool
{
return $this->usingCache;
}
public function registerCustomFixers(iterable $fixers): ConfigInterface
{
foreach ($fixers as $fixer) {
$this->addCustomFixer($fixer);
}
return $this;
}
public function setCacheFile(string $cacheFile): ConfigInterface
{
$this->cacheFile = $cacheFile;
return $this;
}
public function setFinder(iterable $finder): ConfigInterface
{
$this->finder = $finder;
return $this;
}
public function setFormat(string $format): ConfigInterface
{
$this->format = $format;
return $this;
}
public function setHideProgress(bool $hideProgress): ConfigInterface
{
$this->hideProgress = $hideProgress;
return $this;
}
public function setIndent(string $indent): ConfigInterface
{
$this->indent = $indent;
return $this;
}
public function setLineEnding(string $lineEnding): ConfigInterface
{
$this->lineEnding = $lineEnding;
return $this;
}
public function setPhpExecutable(?string $phpExecutable): ConfigInterface
{
$this->phpExecutable = $phpExecutable;
return $this;
}
public function setRiskyAllowed(bool $isRiskyAllowed): ConfigInterface
{
$this->isRiskyAllowed = $isRiskyAllowed;
return $this;
}
public function setRules(array $rules): ConfigInterface
{
$this->rules = $rules;
return $this;
}
public function setUsingCache(bool $usingCache): ConfigInterface
{
$this->usingCache = $usingCache;
return $this;
}
private function addCustomFixer(FixerInterface $fixer): void
{
$this->customFixers[] = $fixer;
}
}
|
C++
|
UTF-8
| 2,752
| 2.5625
| 3
|
[
"BSL-1.0"
] |
permissive
|
/*
* ExpressionTree.h
*
* Created on: 2013/06/18
* Author: kryozahiro
*/
#ifndef EXPRESSIONTREE_H_
#define EXPRESSIONTREE_H_
#include <random>
#include <boost/property_tree/ptree.hpp>
#include "../../solver/GeneticOperable.h"
#include "../Program.h"
#include "ConstantNode.h"
#include "ExpressionNode.h"
#include "OperatorNode.h"
#include "VariableNode.h"
class ExpressionTree : public Program, public GeneticOperable<ExpressionTree> {
public:
static std::vector<std::shared_ptr<Program>> generate(const ProgramType& programType, const boost::property_tree::ptree& node, int size, std::mt19937_64& randomEngine);
/// ramped half and halfによる式木の集合の生成
static std::vector<std::shared_ptr<Program>> rampedHalfAndHalf(const ExpressionTree& prototype, int size, int maxDepth, std::mt19937_64& randomEngine);
/// GeneticOperableの実装
static void normalCrossover(ExpressionTree& parent1, ExpressionTree& parent2, int rootIndex, std::mt19937_64& randomEngine);
static void normalMutation(ExpressionTree& solution, int rootIndex, std::mt19937_64& randomEngine);
/// コンストラクタ
/** @param maxDepth 葉までの最長パスの長さ
*/
ExpressionTree(const ProgramType& programType, int maxDepth);
ExpressionTree(const ExpressionTree& tree);
virtual ~ExpressionTree() = default;
/// Programの実装
CPPUTIL_CLONEABLE;
virtual std::vector<double> operator()(const std::vector<double>& input) override;
virtual std::string toString() const override;
/// GeneticOperableの実装
virtual void crossoverImpl(const std::string& method, ExpressionTree& other, std::mt19937_64& randomEngine) override;
virtual void mutationImpl(const std::string& method, std::mt19937_64& randomEngine) override;
/// 使用するオペレータの設定
void addOperator(std::shared_ptr<ExpressionNode> op);
/// 式木の生成
void full(std::mt19937_64& randomEngine);
void grow(std::mt19937_64& randomEngine);
private:
using MethodMakeNode = std::shared_ptr<ExpressionNode>(ExpressionTree::*)(int, int, std::mt19937_64&);
std::shared_ptr<ExpressionNode> makeSubTree(int depth, std::mt19937_64& randomEngine, MethodMakeNode method);
std::shared_ptr<ExpressionNode> makeNodeByGrow(int thisDepth, int maxDepth, std::mt19937_64& randomEngine);
std::shared_ptr<ExpressionNode> makeNodeByFull(int thisDepth, int maxDepth, std::mt19937_64& randomEngine);
/// 問題の仕様
int maxDepth = 10;
/// 式木
std::vector<std::shared_ptr<ExpressionNode>> roots;
/// 使用するオペレータのリスト
std::vector<std::shared_ptr<ExpressionNode>> nonterminals;
std::vector<std::shared_ptr<ExpressionNode>> terminals;
};
GAMESOLVER_PROGRAM_MODULE(ExpressionTree);
#endif /* EXPRESSIONTREE_H_ */
|
Shell
|
UTF-8
| 836
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
#!/bin/bash
yc_app=($(yc compute instance list | grep reddit-app | awk '{print $4, $10}'))
yc_db=($(yc compute instance list | grep reddit-db | awk '{print $4, $10}'))
if [[ "$1" == "--list" ]]; then
#heredoc
cat<<EOF
{
"_meta": {
"hostvars": {
"${yc_app[0]}": {
"ansible_host": "${yc_app[1]}"
},
"${yc_db[0]}": {
"ansible_host": "${yc_db[1]}"
}
}
},
"all": {
"children": [
"app",
"db",
"ungrouped"
]
},
"app": {
"hosts": [
"${yc_app[0]}"
],
"vars": {
"db_host": "${yc_db[1]}"
}
},
"db": {
"hosts": [
"${yc_db[0]}"
]
}
}
EOF
else
echo "re-run with arguments"
fi
|
Markdown
|
UTF-8
| 1,083
| 3.3125
| 3
|
[] |
no_license
|
# GitHub_Issue_Tracker
Problem Description
Create a repository on GitHub and write a program in any programming language that will do the following:
Input : User can input a link to any public GitHub repository
Output :
Your UI should display a table with the following information -
- Total number of open issues
- Number of open issues that were opened in the last 24 hours
- Number of open issues that were opened more than 24 hours ago but less than 7 days ago
- Number of open issues that were opened more than 7 days ago
Solution:
This is a program to track open issue count for a public Git repo.
The scrpit is written in python and I used the Flask frame work to design the solution.
To keep track of the time I am useing python standatrd datetime libraries. And the solution is designed based on the RESTful webservice provided by GitHub to keep track of the issues.
This application is live on https://istr.herokuapp.com/ for next 14 hrs from now(till 8 AM 27-mar-16).
Input is any public Git repo url and output will be according to the problem description.
|
Markdown
|
UTF-8
| 15,466
| 2.546875
| 3
|
[] |
no_license
|
[m-dictionary-item name="D_HEADER_JUMBOTRON"]
# "Two inline pictures with text first right" component (PRO)
[/m-dictionary-item]
[m-dictionary-item name="D_MAIN_CONTENT"]
D_COMPONENT
[m-component component="two-inline-pictures-with-text-first-right" folder="images-and-text" M_ATTRIBUTES=""]
[m-component-item name="M_ITEM_1" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-secondary text-full-white l-vertical-align flex-s" M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6 box-inverted"]
[m-tag tag="div" attributes="class:padding-left-right-large"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-tag]
[/m-component-item]
[m-component-item name="M_ITEM_2" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-secondary text-full-white l-vertical-align " M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6"]
[m-tag tag="div" attributes="class:padding-left-right-large"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-tag]
[/m-component-item]
[/m-component]
D_CODE
[m-tag tag="div" attributes="id:code"]
[raw]
```
[m-help]
Main component properties
M_ATTRIBUTES: Adds html attributes to element. Example attributes="class: foo, rel=bar"
Item component properties
M_IMAGE_NAME: The full image path
M_IMAGE_PATH: The image directory
M_IMAGE_ALT: The image alt attribute. This parameter is mandatory and cannot be blank
M_IMAGE_TITLE: The image title attribute
M_IMAGE_CLASSES: CSS classes added to the image
M_IMAGE_ACTIONS: Grav image actions added to the image. Action and values are separated by a colon and properties are separated by a semicolon. Example="lightbox:600,800;resize:200,200"
M_ATTRIBUTES: Adds extra html attributes to class element. to add an extra foo class and a new rel attribute, you can define this parameter as follows: M_EXTRA_ATTRIBUTES="foo, rel=bar
M_ROW_ATTRIBUTES: Adds html attributes to the item's grid row
M_LEFT_COLUMN_ATTRIBUTES: Adds html attributes to the left grid column
M_RIGHT_COLUMN_ATTRIBUTES: Adds html attributes to the right grid column
[/m-help]
[m-component component="two-inline-pictures-with-text-first-right" folder="images-and-text" M_ATTRIBUTES=""]
[m-component-item name="M_ITEM_1" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-secondary text-full-white l-vertical-align flex-s" M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6 box-inverted"]
[m-tag tag="div" attributes="class:padding-left-right-large"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-tag]
[/m-component-item]
[m-component-item name="M_ITEM_2" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-secondary text-full-white l-vertical-align " M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6"]
[m-tag tag="div" attributes="class:padding-left-right-large"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-tag]
[/m-component-item]
[/m-component]
```
[/raw]
[/m-tag]
[m-clipboard target-id="code" button-label="Copy to clipboard" icon="content_copy" icon-attributes="class:left"][/m-clipboard]
D_THE_CODE_COMPONENT
[m-tag tag="div" attributes="id:component-code"]
[raw]
```
[m-grid container="false" attributes="M_ATTRIBUTES"]
[m-grid-row attributes="M_ITEM_1.M_ROW_ATTRIBUTES"]
[m-grid-col attributes="M_ITEM_1.M_RIGHT_COLUMN_ATTRIBUTES"]
M_ITEM_1.M_CONTENT
[/m-grid-col]
[m-grid-col attributes="M_ITEM_1.M_LEFT_COLUMN_ATTRIBUTES"]
[m-image image="M_ITEM_1.M_IMAGE_NAME" image-path="M_ITEM_1.M_IMAGE_PATH" alt="M_ITEM_1.M_IMAGE_ALT" title="M_ITEM_1.M_IMAGE_TITLE" classes="M_ITEM_1.M_IMAGE_CLASSES" actions="M_ITEM_1.M_IMAGE_ACTIONS"][/m-image]
[/m-grid-col]
[/m-grid-row]
[m-grid-row attributes="M_ITEM_2.M_ROW_ATTRIBUTES"]
[m-grid-col attributes="M_ITEM_2.M_LEFT_COLUMN_ATTRIBUTES"]
[m-image image="M_ITEM_2.M_IMAGE_NAME" image-path="M_ITEM_2.M_IMAGE_PATH" alt="M_ITEM_2.M_IMAGE_ALT" title="M_ITEM_2.M_IMAGE_TITLE" classes="M_ITEM_2.M_IMAGE_CLASSES" actions="M_ITEM_2.M_IMAGE_ACTIONS"][/m-image]
[/m-grid-col]
[m-grid-col attributes="M_ITEM_2.M_RIGHT_COLUMN_ATTRIBUTES"]
M_ITEM_2.M_CONTENT
[/m-grid-col]
[/m-grid-row]
[/m-grid]
```
[/raw]
[/m-tag]
[m-clipboard target-id="component-code" button-label="Copy to clipboard" icon="content_copy" icon-attributes="class:left"][/m-clipboard]
D_NO_VERTICAL_ALIGNMENT
[m-component component="two-inline-pictures-with-text-first-right" folder="images-and-text" M_ATTRIBUTES=""]
[m-component-item name="M_ITEM_1" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-secondary text-full-white flex-s" M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6 padding-medium box-inverted"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-component-item]
[m-component-item name="M_ITEM_2" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-secondary text-full-white" M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6 padding-medium"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-component-item]
[/m-component]
[m-tag tag="div" attributes="id:code-no-vertical-align"]
[raw]
```
[m-help]
Main component properties
M_ATTRIBUTES: Adds html attributes to element. Example attributes="class: foo, rel=bar"
Item component properties
M_IMAGE_NAME: The full image path
M_IMAGE_PATH: The image directory
M_IMAGE_ALT: The image alt attribute. This parameter is mandatory and cannot be blank
M_IMAGE_TITLE: The image title attribute
M_IMAGE_CLASSES: CSS classes added to the image
M_IMAGE_ACTIONS: Grav image actions added to the image. Action and values are separated by a colon and properties are separated by a semi-colon. Example="lightbox:600,800;resize:200,200"
M_ATTRIBUTES: Adds extra html attributes to class element. to add an extra foo class and a new rel attribute, you can define this parameter as follows: M_EXTRA_ATTRIBUTES="foo, rel=bar
M_ROW_ATTRIBUTES: Adds html attributes to the item's grid row
M_LEFT_COLUMN_ATTRIBUTES: Adds html attributes to the left grid column
M_RIGHT_COLUMN_ATTRIBUTES: Adds html attributes to the right grid column
[/m-help]
[m-component component="two-inline-pictures-with-text-first-left" folder="images-and-text" M_ATTRIBUTES=""]
[m-component-item name="M_ITEM_1" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-secondary text-full-white" M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6 padding-medium"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-component-item]
[m-component-item name="M_ITEM_2" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-secondary text-full-white flex-s" M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6 box-inverted padding-medium"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-component-item]
[/m-component]
```
[/raw]
[/m-tag]
[m-clipboard target-id="code-no-vertical-align" button-label="Copy to clipboard" icon="content_copy" icon-attributes="class:left"][/m-clipboard]
D_CELL_COLOR
[m-component component="two-inline-pictures-with-text-first-right" folder="images-and-text" M_ATTRIBUTES=""]
[m-component-item name="M_ITEM_1" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-primary text-full-white l-vertical-align flex-s" M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6 box-inverted"]
[m-tag tag="div" attributes="class:padding-left-right-large"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-tag]
[/m-component-item]
[m-component-item name="M_ITEM_2" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-primary text-full-white l-vertical-align " M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6"]
[m-tag tag="div" attributes="class:padding-left-right-large"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-tag]
[/m-component-item]
[/m-component]
[m-tag tag="div" attributes="id:code-cell-color"]
[raw]
```
[m-help]
Main component properties
M_ATTRIBUTES: Adds html attributes to element. Example attributes="class: foo, rel=bar"
Item component properties
M_IMAGE_NAME: The full image path
M_IMAGE_PATH: The image directory
M_IMAGE_ALT: The image alt attribute. This parameter is mandatory and cannot be blank
M_IMAGE_TITLE: The image title attribute
M_IMAGE_CLASSES: CSS classes added to the image
M_IMAGE_ACTIONS: Grav image actions added to the image. Action and values are separated by a colon and properties are separated by a semi-colon. Example="lightbox:600,800;resize:200,200"
M_ATTRIBUTES: Adds extra html attributes to class element. to add an extra foo class and a new rel attribute, you can define this parameter as follows: M_EXTRA_ATTRIBUTES="foo, rel=bar
M_ROW_ATTRIBUTES: Adds html attributes to the item's grid row
M_LEFT_COLUMN_ATTRIBUTES: Adds html attributes to the left grid column
M_RIGHT_COLUMN_ATTRIBUTES: Adds html attributes to the right grid column
[/m-help]
[m-component component="two-inline-pictures-with-text-first-right" folder="images-and-text" M_ATTRIBUTES=""]
[m-component-item name="M_ITEM_1" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-primary text-full-white l-vertical-align flex-s" M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6 box-inverted"]
[m-tag tag="div" attributes="class:padding-left-right-large"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-tag]
[/m-component-item]
[m-component-item name="M_ITEM_2" M_IMAGE_NAME="image.jpg" M_IMAGE_PATH="" M_IMAGE_ALT="Image alt" M_IMAGE_TITLE="Image title" M_IMAGE_CLASSES="responsive-img" M_IMAGE_ACTIONS="" M_ATTRIBUTES="" M_ROW_ATTRIBUTES="class:box-bg-primary text-full-white l-vertical-align " M_LEFT_COLUMN_ATTRIBUTES="class: s12 m12 l6 no-padding no-line-height" M_RIGHT_COLUMN_ATTRIBUTES="class: s12 m12 l6"]
[m-tag tag="div" attributes="class:padding-left-right-large"]
### Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
[/m-tag]
[/m-component-item]
[/m-component]
```
[/raw]
[/m-tag]
[m-clipboard target-id="code-cell-color" button-label="Copy to clipboard" icon="content_copy" icon-attributes="class:left"][/m-clipboard]
[/m-dictionary-item]
|
Python
|
UTF-8
| 8,320
| 2.53125
| 3
|
[] |
no_license
|
# engine.py
"""
Mini engine. Rewrite of source.engine due to removal of ui from old engine.
Defines systems, components, and managers that should be created and processed
during the main game.
"""
import random
import time
from source.common import join, join_drop_key, squares
from source.ecs import Position
from source.ecs.components import (AI, CurrentTurn, Information, Input,
Movement, Position, TileMap, Turn)
from source.ecs.managers import ComponentManager, EntityManager
from source.generate import dimensions, matrix
from source.keyboard import keypress_to_direction
room = """
###############
#.............#
#.............#
#...#..#..#...#
#.............#
#.............#
###############"""[1:]
tick_time = 0.0
def timeout(tick_duration):
"""Times out if function processes faster than framerate"""
def decorate(fn):
def call(*args):
global tick_time
start = time.time()
fn(*args)
tick_time += time.time() - start
if tick_time < tick_duration:
time.sleep(tick_duration - tick_time)
tick_time = 0.0
return
return call
return decorate
def system_info(debug):
def decorate(fn):
def call(*args):
arg, *args = args
if debug:
print(fn.__name__,
arg.entity,
arg.current_turns.find(arg.entity))
fn(arg)
return call
return decorate
@system_info(False)
def move_system(engine):
for i, (p, m) in join(engine.positions, engine.movements):
p.x += m.x
p.y += m.y
engine.movements.remove(i)
@system_info(False)
def initiative_system(engine):
while True:
entity = engine.entity
# end of entity list
if entity is None:
engine.reset_entity_index()
continue
# entities that don't take any actions (tiles/items) are skipped
if not engine.inputs.find(entity) and not engine.ais.find(entity):
engine.next_entity()
continue
# add a current_turn component to make sure when iterating systems
# only one entity is processed
engine.current_turns.components.clear()
engine.current_turns.add(entity, CurrentTurn())
break
@system_info(True)
def input_system(engine):
c = engine.current_turns.find(engine.entity)
takes_turn = engine.inputs.find(engine.entity)
if not c.finished and takes_turn:
print('taking input')
if takes_turn.needs_input:
if engine.action is None:
engine.requires_input = True
return
engine.inject_action()
c.finished = True
@system_info(False)
def ai_system(engine):
c = engine.current_turns.find(engine.entity)
ai = engine.ais.find(engine.entity)
if not c.finished and ai:
room = engine.tilemaps.find(engine.room)
position = engine.positions.find(engine.entity)
spaces = {
(x, y)
for y in range(1, room.height-1)
for x in range(1, room.width-1)
}
moveable = [
(x, y)
for x, y in squares(exclude_center=True)
if (position.x+x, position.y+y) in spaces
]
engine.movements.add(engine.entity,
Movement.random_move(moveable))
c.finished = True
@system_info(False)
def cleanup_system(engine):
engine.next_entity()
# def turn_system(engine):
# room = engine.tilemaps.find(engine.room)
# spaces = {
# (x, y) for y in range(1, room.height-1) for x in range(1, room.width-1)
# }
# for e, p in engine.positions:
# moveable = [ (x, y) for x, y in squares() if (p.x+x, p.y+y) in spaces ]
# engine.movements.add(e, Movement.random_move(possible_spaces=moveable))
class Engine:
def __init__(self):
self.requires_input = False
self.entities = EntityManager()
self.player = None
self.entity = None
self.entity_index = -1
self.system = None
self.system_index = 0
self.systems = []
self.action = None
def add_component(self, component_type):
setattr(self,
component_type.manager,
ComponentManager(component_type))
def add_components(self, *component_types):
for ct in component_types:
self.add_component(ct)
def new_entity(self):
return self.entities.create()
def reset_entity_index(self):
self.entity_index = 0
self.entity = self.entities.entity_ids[self.entity_index]
def next_entity(self):
self.entity_index += 1
if self.entity_index > len(self.entities.entity_ids) - 1:
self.entity = None
else:
self.entity = self.entities.entity_ids[self.entity_index]
def add_player(self):
if self.player:
return
self.player = self.new_entity()
self.positions.add(self.player, Position(1, 1))
self.infos.add(self.player, Information("player"))
self.inputs.add(self.player, Input(True))
def del_player(self):
self.positions.remove(self.player)
self.infos.remove(self.player)
self.inputs.remove(self.player)
self.entities.remove(self.player)
self.player = None
self.requires_input = False
def add_enemy(self):
enemy = self.new_entity()
self.positions.add(enemy, Position(5, 5))
self.ais.add(enemy, AI())
self.infos.add(enemy, Information("enemy"))
def add_map(self):
m = matrix(room)
w, h = dimensions(m)
self.room = self.new_entity()
self.tilemaps.add(self.room, TileMap(w, h))
self.infos.add(self.room, Information("map"))
def add_system(self, system):
self.systems.append(system)
def add_systems(self, *systems):
self.systems += systems
def reset_system_index(self):
self.system_index = 0
self.system = self.systems[self.system_index]
def next_system(self):
self.system_index += 1
if self.system_index > len(self.systems) - 1:
self.system = None
else:
self.system = self.systems[self.system_index]
def handle_keypress(self, keypress):
self.action = None
print(keypress)
if keypress in keypress_to_direction:
self.action = Movement.keypress_to_direction(keypress)
self.requires_input = False
else:
self.action = Movement(1, 1)
self.requires_input = False
print(self.action, self.requires_input)
def inject_action(self):
if not self.action or self.player:
return
manager = getattr(self, self.action.manager)
manager.add(self.player, self.action)
self.action = None
# @timeout(tick_duration=.33)
def process(self):
global tick_time
if not self.player:
tick_duration = .33
else:
tick_duration = .0
start = time.time()
while True:
if self.system is None:
self.reset_system_index()
break
self.system(self) # process
if self.requires_input:
break
self.next_system()
tick_time += time.time() - start
if tick_time < tick_duration:
time.sleep(tick_duration - tick_time)
tick_time = 0.0
@classmethod
def demo(self):
e = Engine()
e.add_components(Position,
Information,
AI,
Movement,
Input,
TileMap,
CurrentTurn)
# e.add_player()
e.add_enemy()
e.add_enemy()
e.add_enemy()
e.add_map()
# e.add_systems(turn_system, move_system)
e.add_systems(initiative_system,
input_system,
ai_system,
move_system,
cleanup_system)
return e
|
C
|
UTF-8
| 2,090
| 2.65625
| 3
|
[
"Unlicense"
] |
permissive
|
#ifndef __CONFIG_H_
#define __CONFIG_H_
/* 1 to add a space to the right of the bar. 0 for no pad. */
#define RIGHTPAD 1
/* The delimeter between modules */
#define MODULE_DELIMETER " | "
#define SIGBUF 256 /* This is how many bytes any given module can hold */
#define STATUSBUF 256 /* This is how many bytes the statusbar can hold */
#include "modules.h"
/*
* THIS IS THE FILE WHERE ALL THE MODULE CONFIGURATION GOES.
* ==========================================================
*
* Below is the "modules" array. In this array you should put the names of all
* the modules you would like loaded in your statusbar, in the order in which
* you would like to have them loaded.
*
* Since this statusbar is completely signal based, you will need to find ways
* to signal to each module that it needs to update. An easy way to do so is as
* follows:
*
* $ kill -XX mstatus
*
* In the above command, you must replace "XX" with the correct signal number.
* The signal number you need to send is the modules position in the statusbar
* plus 33. For example, if your statusbar contains a clock, battery health
* meter, and date in that order, then to signal to the clock to update you need
* to send the signal 34. This is because the clock is the first item in the
* status bar, and 33 + 1 = 34. Likewise, to signal to the battery meter and
* date modules, you need to send the signals 35 and 36 respectively.
*
* If you would like to send a signal on a set cycle (such as once a minute for
* a clock), you could look into using cronjobs. To detect something such as a
* charger being plugged in, udev might be of use to you (see `man 3 udev`).
*
* For more information on how to create your own modules, check out the comment
* in `src/modules.h`.
*
*
* IMPORTANT
* =========
* After ANY change to the program, configuration, or modules, you MUST
* recompile the program. You can do so as follows:
*
* # make clean install
*/
static void (*modules[])(int) = {sb_volume, sb_brightness, sb_battery, sb_clock, sb_date};
#endif /* __CONFIG_H_ */
|
PHP
|
UTF-8
| 795
| 2.921875
| 3
|
[] |
no_license
|
<?php
class Session {
public static $account = null;
public static function logged_in() {
if(isset($_SESSION["loggedIn"]) && $_SESSION["loggedIn"] == true) {
return true;
} else {
return false;
}
}
public static function login($admin) {
$_SESSION["loggedIn"] = true;
$_SESSION["admin"] = $admin;
}
public static function developer() {
if(static::logged_in()) {
return Session::$account->type == Admin::TYPE_DEVELOPER;
} else {
return false;
}
}
public static function logout() {
$_SESSION["loggedIn"] = false;
$_SESSION["admin"] = null;
}
}
session_start();
if(Session::logged_in()) {
Session::$account = $_SESSION["admin"];
}
|
JavaScript
|
UTF-8
| 490
| 3.421875
| 3
|
[
"MIT"
] |
permissive
|
/**
* Calculte player ELO rating after match
*/
export default ({ playerRating, opponentRating, victory }) => {
// K - factor
let K = 32;
if (playerRating >= 2100 && playerRating <= 2400) {
K = 24;
} else if (playerRating > 2400) {
K = 16;
}
// Calculate new ELO rating
const winProbability = 1 / (1 + 10 ** ((opponentRating - playerRating) / 400));
const newRating = playerRating + K * (victory - winProbability);
return Math.round(newRating * 100) / 100;
};
|
PHP
|
UTF-8
| 16,365
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
<?php
define('RSS1', 'RSS 1.0', true);
define('RSS2', 'RSS 2.0', true);
define('ATOM', 'ATOM', true);
/**
* RSS Feeds - Feed Writer class
*
* Genarate RSS 1.0, RSS2.0 and ATOM Feed
*
* @package RSS Feeds PHP
* @author Anis uddin Ahmad <anisniit@gmail.com>
* @author Guenther Mair <guenther.mair@hoslo.ch>
* @link http://www.crowdedplace.com
*
* $Id: FeedWriter.php 6 2012-01-14 11:01:21Z gunny $
*/
class FeedWriter
{
private $version = null;
private $header = "Content-type: application/xml; charset=utf-8";
private $namespaces = array(); // xml namespaces (used to link to images)
private $channels = array(); // collection of channel elements
private $items = array(); // collection of FeedItem objects
private $CDATAEncoding = array(); // tag names to encode in CDATA blocks
/**
* Constructor
*
* @param constant RSS1/RSS2/ATOM (defaults to RSS2)
* @return object this
*/
public function __construct($version = RSS2) {
$this->version = $version;
// set default values for essential channel elements
$this->setChannelElement('title', $version . ' Feed');
$this->setChannelElement('link', 'http://www.crowdedplace.com');
// set default namespaces
switch ($this->version) {
case RSS2:
$this->setNamespace("http://purl.org/rss/1.0/modules/content/", "content");
$this->setNamespace("http://wellformedweb.org/CommentAPI/", "wfw");
break;
case RSS1:
$this->setNamespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf");
$this->setNamespace("http://purl.org/rss/1.0/");
$this->setNamespace("http://purl.org/dc/elements/1.1/", "dc");
break;
case ATOM:
$this->setNamespace("http://www.w3.org/2005/Atom");
break;
}
// tag names to encode in CDATA blocks
$this->setCDATAEncoding('description');
$this->setCDATAEncoding('content:encoded');
$this->setCDATAEncoding('summary');
return $this;
}
/**
* Set a tag to be encoded in CDATA blocks
*
* @access public
* @param string tag
* @return object this
*/
public function setCDATAEncoding($value) {
$this->CDATAEncoding[] = $value;
return $this;
}
/**
* Set a namespace
*
* @access public
* @param string namespace URI
* @param string xmlns short tag (optional)
* @return object this
*/
public function setNamespace($value, $xmlns = null) {
$this->namespaces[] = 'xmlns'.(($xmlns !== null) ? ':'.$xmlns : '').'="'.$value.'"';
return $this;
}
/**
* Set the header
*
* @access public
* @return object this
*/
public function setHeader($header) {
$this->header = $header;
return $this;
}
/**
* Create a channel element
*
* @access public
* @param string name
* @param string content
* @param string attributes (optional)
* @return object this
*/
public function setChannelElement($name, $content, $attributes = null) {
$this->channels[$name]['name'] = $name;
$this->channels[$name]['content'] = $content;
$this->channels[$name]['attributes'] = $attributes;
return $this;
}
/**
* Create multiple channel elements (no attributes)
*
* @access public
* @param array channels in 'channelName' => 'channelContent' notation
* @return object this
*/
public function setChannelElements($elements) {
if ( ! is_array($elements))
return $this;
foreach ($elements as $name => $content)
$this->setChannelElement($name, $content);
return $this;
}
/**
* Genarate the actual RSS/ATOM file
*
* @access public
* @param boolean directly print header and body (defaults to TRUE)
* @return array feed array (header and body)
*/
public function generateFeed($doEcho = TRUE) {
$output = $this->printXMLHead() .
$this->printHead() .
$this->printChannels() .
$this->printItems() .
$this->printClosureTag();
if ($doEcho === TRUE) {
header($this->header);
echo $output;
}
return array("header" => $this->header, "body" => $output);
}
/**
* Create a new FeedItem
*
* @access public
* @return object instance of FeedItem class
*/
public function createNewItem() {
$Item = new FeedItem($this->version);
return $Item;
}
/**
* Add a FeedItem to the main class
*
* @access public
* @param object instance of FeedItem class
* @return object this
*/
public function addItem($feedItem) {
$this->items[] = $feedItem;
return $this;
}
// ---------------------------------------------------------------------------
/**
* Set the 'title' channel element (wrapper method)
*
* @access public
* @param string value of 'title' channel tag
* @return object this
*/
public function setTitle($title) {
return $this->setChannelElement('title', $title);
}
/**
* Set the 'description' channel element (wrapper method)
*
* @access public
* @param string value of 'description' channel tag
* @return object this
*/
public function setDescription($desciption) {
return $this->setChannelElement('description', $desciption);
}
/**
* Set the 'link' channel element (wrapper method)
*
* @access public
* @param string value of 'link' channel tag
* @return object this
*/
public function setLink($link) {
return $this->setChannelElement('link', $link);
}
/**
* Set the 'image' channel element (wrapper method)
*
* @access public
* @param string title of image
* @param string link url of the imahe
* @param string path url of the image
* @return object this
*/
public function setImage($title, $link, $url) {
return $this->setChannelElement('image', array('title' => $title, 'link' => $link, 'url' => $url));
}
/**
* Set the 'about' channel element (RSS 1.0 only)
*
* @access public
* @param string value of 'about' channel tag
* @return object this
*/
public function setChannelAbout($url) {
$this->data['ChannelAbout'] = $url;
return $this;
}
/**
* Genarates an UUID
*
* @access public
* @param string an optional prefix
* @return string the formated uuid
*/
public function uuid($key = null, $prefix = '') {
$chars = md5(($key == null) ? uniqid(rand()) : $key);
return $prefix . substr($chars,0,8) . '-' .
substr($chars,8,4) . '-' .
substr($chars,12,4) . '-' .
substr($chars,16,4) . '-' .
substr($chars,20,12);
}
// --------------------------------------------------------------------------
/**
* Print the xml opening tag
*
* @access private
* @return string XML 1.0 UTF-8 header
*/
private function printXMLHead() {
return '<?xml version="1.0" encoding="utf-8"?>' . "\n";
}
/**
* Print rss header and namespaces
*
* @access private
* @return string RSS XML header
*/
private function printHead() {
switch ($this->version) {
case RSS2:
return '<rss version="2.0" '.implode(" ", $this->namespaces).'>' . PHP_EOL;
case RSS1:
return '<rdf:RDF '.implode(" ", $this->namespaces).'>' . PHP_EOL;
case ATOM:
return '<feed '.implode(" ", $this->namespaces).'>' . PHP_EOL;
}
}
/**
* Pring rss closing tags
*
* @access private
* @return string RSS XML footer
*/
private function printClosureTag() {
switch ($this->version) {
case RSS2:
return '</channel>' . PHP_EOL . '</rss>';
case RSS1:
return '</rdf:RDF>';
case ATOM:
return '</feed>';
}
}
/**
* Create a single node from a tag (recursive)
*
* @access private
* @param string name of the tag
* @param mixed tag value as string or array of nested tags in 'tagName' => 'tagValue' notation
* @param array attributes (if any) in 'attrName' => 'attrValue' notation
* @return string formatted xml tag
*/
private function makeNode($tagName, $tagContent, $attributes = null) {
// setup attributes
$attrText = '';
if (is_array($attributes))
foreach ($attributes as $key => $value)
$attrText .= " $key=\"$value\"";
if (is_array($tagContent) && $this->version == RSS1)
$attrText = ' rdf:parseType="Resource"';
$attrText .= (in_array($tagName, $this->CDATAEncoding) && $this->version == ATOM) ? ' type="html"' : '';
// setup content
if ( empty($tagContent) ) {
$nodeText = "<{$tagName}{$attrText} />";
} else {
$nodeText = (in_array($tagName, $this->CDATAEncoding)) ? "<{$tagName}{$attrText}><![CDATA[" : "<{$tagName}{$attrText}>";
if (is_array($tagContent)) {
foreach ($tagContent as $key => $value)
$nodeText .= $this->makeNode($key, $value);
} else {
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? $tagContent : htmlentities($tagContent);
}
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? "]]></$tagName>" : "</$tagName>";
}
return $nodeText . PHP_EOL;
}
/**
* Print channels
*
* @access private
* @return string xml string
*/
private function printChannels() {
// start channel tag
switch ($this->version) {
case RSS2:
$output = '<channel>' . PHP_EOL;
// channel will be closed at the EOF (see printClosureTag)
break;
case RSS1:
$output = (isset($this->data['ChannelAbout'])) ? "<channel rdf:about=\"{$this->data['ChannelAbout']}\">" : "<channel rdf:about=\"{$this->channels['link']}\">";
break;
}
// Print channel items
foreach ($this->channels as $channel) {
if ($this->version == ATOM && $channel['name'] == 'link') {
// ATOM prints link element as href attribute
$output .= $this->makeNode($channel['name'], '', array('href' => $channel['content']));
// add ID for ATOM
$output .= $this->makeNode('id', $this->uuid($channel['content'], 'urn:uuid:'));
} else {
$output .= $this->makeNode($channel['name'], $channel['content'], $channel['attributes']);
}
}
// RSS 1.0: uses a special <rdf:Seq> tag for channels
if ($this->version == RSS1) {
$output .= "<items>" . PHP_EOL . "<rdf:Seq>" . PHP_EOL;
foreach ($this->items as $item) {
$itemElements = $item->getElements();
$output .= "<rdf:li resource=\"{$itemElements['link']['content']}\"/>" . PHP_EOL;
}
$output .= "</rdf:Seq>" . PHP_EOL . "</items>" . PHP_EOL . "</channel>" . PHP_EOL;
}
return $output;
}
/**
* Print feed items
*
* @access private
* @return string xml string
*/
private function printItems() {
$items = '';
foreach ($this->items as $item) {
$itemElements = $item->getElements();
// RSS 1.0: the argument is printed as rdf:about attribute
$items .= $this->startItem($itemElements['link']['content']);
foreach ($itemElements as $element)
$items .= $this->makeNode($element['name'], $element['content'], $element['attributes']);
$items .= $this->endItem();
}
return $items;
}
/**
* Start item tag
*
* @access private
* @param string value of about tag to be used (only used by RSS 1.0)
* @return string xml string
*/
private function startItem($about = false) {
switch ($this->version) {
case RSS2:
return '<item>' . PHP_EOL;
case RSS1:
if ($about)
return '<item rdf:about="'.$about.'">' . PHP_EOL;
else
die('Link element not set, but required by RSS 1.0 (about attribute for all items).');
case ATOM:
return '<entry>' . PHP_EOL;
}
}
/**
* Close item tag
*
* @access private
* @return string xml string
*/
private function endItem() {
switch ($this->version) {
case RSS2:
case RSS1:
return '</item>' . PHP_EOL;
case ATOM:
return "</entry>" . PHP_EOL;
}
}
} // end of class FeedWriter
/**
* RSS Feeds PHP - FeedItem class
*
* Used for feed elements in FeedWriter class
*
* @package RSS Feeds PHP
* @author Anis uddin Ahmad <anisniit@gmail.com>
* @author Guenther Mair <guenther.mair@hoslo.ch>
* @link http://www.crowdedplace.com
*/
class FeedItem
{
private $version;
private $elements = array(); // collection of feed elements
/**
* Constructor
*
* @param content RSS1/RSS2/ATOM (defaults to RSS2)
* @return object this
*/
function __construct($version = RSS2) {
$this->version = $version;
return $this;
}
/**
* Add an element
*
* @access public
* @param string tag name of an element
* @param string content of the tag
* @param array attributes (if any) in 'attrName' => 'attrValue' notation
* @return object this
*/
public function addElement($name, $content, $attributes = null) {
$this->elements[$name]['name'] = $name;
$this->elements[$name]['content'] = $content;
$this->elements[$name]['attributes'] = $attributes;
return $this;
}
/**
* Add multiple elements (no attributes)
*
* @access public
* @param array array of elements in 'tagName' => 'tagContent' notation
* @return object this
*/
public function addElements($elements) {
if ( ! is_array($elements))
return;
foreach ($elements as $name => $content)
$this->addElement($name, $content);
return $this;
}
/**
* Return the collection of elements in this feed item
*
* @access public
* @return array
*/
public function getElements() {
return $this->elements;
}
// --------------------------------------------------------------------------
/**
* Set the 'description' element (wrapper method)
*
* @access public
* @param string content of 'description' element
* @return object this
*/
public function setDescription($description) {
return $this->addElement(($this->version == ATOM) ? 'summary' : 'description', $description);
}
/**
* Set the 'title' element (wrapper method)
*
* @access public
* @param string content of 'title' element
* @return object this
*/
public function setTitle($title) {
return $this->addElement('title', $title);
}
/**
* Set the 'date' element (wrapper method)
*
* @access public
* @param string content of 'date' element
* @return object this
*/
public function setDate($date) {
if ( ! is_numeric($date))
$date = strtotime($date);
switch ($this->version) {
case ATOM:
return $this->addElement('updated', date(DATE_ATOM, $date));
case RSS2:
return $this->addElement('pubDate', date(DATE_RSS, $date));
case RSS1:
return $this->addElement('dc:date', date("Y-m-d", $date));
}
}
/**
* Set the 'link' element (wrapper method)
*
* @access public
* @param string content of 'link' element
* @return object this
*/
public function setLink($link) {
switch ($this->version) {
case RSS2:
case RSS1:
return $this->addElement('link', $link);
case ATOM:
$this->addElement('link', '', array('href' => $link));
$this->addElement('id', FeedWriter::uuid($link, 'urn:uuid:'));
return $this;
}
}
/**
* Set the 'enclosure' element (wrapper method -- RSS 2.0 only)
*
* @access public
* @param string type attribute
* @param string url attribute
* @param string length attribute
* @return object this
*/
public function setEnclosure($type, $url, $length) {
if ($this->version == RSS2)
return $this->addElement('enclosure', '', array('type' => $type, 'url' => $url, 'length' => $length));
else
return $this;
}
} // end of class FeedItem
|
C#
|
UTF-8
| 1,850
| 3.953125
| 4
|
[] |
no_license
|
using System;
namespace InClassWeek6_Arrays
{
class Program
{
static void Main(string[] args)
{
// *********************************************** Monday 11/25/19 ************************************************************
//string person1 = "Lopa";
//string person2 = "Shengyu";
//string person3 = "Trevor";
//string person4 = "Christi";
//string person5 = "Ryan";
string[] people = new string[5]; // length is 5 ; people is just refering to anywhere in memory
people[0] = "Maria";
people[1] = "Naddie";
people[2] = "Rafia";
people[3] = "Christi";
people[4] = "Ryan";
string[] major = { "Cyber Security" ,
"Computer Science" ,
"Networking" ,
"Software Developer" ,
"Programming and Development" };
string[] number = new string[5];
number[0] = "2";
number[1] = "4";
number[2] = "5";
number[3] = "28";
number[4] = "55";
Console.WriteLine($"Hello, {people[2]} !");
for (int i = 0; i < people.Length; i++) // Here, length is 5 so the condition says less than 5
{
Console.WriteLine(people[i] + ":" + major[i] + ":" + number[i]);
// writing i will print all elements in array from 0 till 4 (total 5)
}
foreach (string person in people) // people is name of array
{
Console.WriteLine(person);
}
//********************* NO CLASS WEDNESDAY 11/25/19 ****************************************************
}
}
}
|
Shell
|
UTF-8
| 1,302
| 2.953125
| 3
|
[] |
no_license
|
#!/usr/bin/env bash
set -o errexit
echo "verify config file exists"
if [ ! -f src/config.json ]; then
echo "--- missing src/config.json ---"
exit
fi
echo "remove www dir"
rm -rf www && mkdir -p www/js www/css
echo "eslint before copying"
./node_modules/.bin/eslint src
echo "copy src files to www"
cp src/healthmeasures.gif www/
cp src/ajax-loader.gif www/
cp src/healthmeasures.ico www/
cp src/index.html www/
cp -r src/js/* www/js/
cp -r src/css/* www/css/
cp ./node_modules/angular/angular.min.js www/js/
cp ./node_modules/angular-route/angular-route.min.js www/js/
cp ./node_modules/angular-resource/angular-resource.min.js www/js/
mkdir -p www/partials/
cp -r src/partials/* www/partials/
mkdir -p www/vendor/css/
cp -r src/vendor/css/* www/vendor/css/
mkdir -p www/vendor/js/
cp -r src/vendor/js/* www/vendor/js/
mkdir -p www/vendor/css/font-awesome/fonts
cp -r ./node_modules/font-awesome/fonts/* www/vendor/css/font-awesome/fonts
mkdir -p www/vendor/css/font-awesome/css
cp ./node_modules/font-awesome/css/font-awesome.min.css www/vendor/css/font-awesome/css
cp ./node_modules/moment/moment.js www/js/
cp ./src/config.json ./www/config.json
mkdir -p www/vendor/font/
cp -r src/vendor/font/* www/vendor/font/
mkdir -p www/vendor/fonts/
cp -r src/vendor/fonts/* www/vendor/fonts/
|
Python
|
UTF-8
| 1,735
| 3.734375
| 4
|
[] |
no_license
|
import random
while True:
try:
"""Taking input from user"""
first_name = str(input("Enter first name:"))
last_name = str(input("Enter last name:"))
if len(first_name) == 0 or len(last_name) == 0:
raise ValueError
except ValueError:
print("Invalid Input!")
continue
else:
break
password_length = int(input("Enter password length:"))
digits = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
symbols = ['+', '-', '*', '@', '$', '#']
def first_convert():
return list(first_name)
def second_convert():
return list(last_name)
a = first_convert()
b = second_convert()
Name = first_name + " " + last_name
j = 0
if password_length >=8:
while j < len(Name):
if len(last_name) == 1:
combined = a + digits + symbols
rand_first_name = random.choice(a)
rand_digits = random.choice(digits)
rand_symbols = random.choice(symbols)
temp_pass = rand_first_name + rand_digits + rand_symbols
for x in range(password_length - 3):
temp_pass = temp_pass + random.choice(combined)
else:
combined = a + b + digits + symbols
rand_first_name = random.choice(a)
rand_last_name = random.choice(b)
rand_digits = random.choice(digits)
rand_symbols = random.choice(symbols)
temp_pass = rand_first_name + rand_last_name + rand_digits + rand_symbols
for x in range(password_length - 4):
temp_pass = temp_pass + random.choice(combined)
j += 1
print(temp_pass)
else:
print("Invalid Length")
|
C#
|
UTF-8
| 2,447
| 2.546875
| 3
|
[] |
no_license
|
namespace CarolineCottage.Repository.Migrations
{
using System;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.History;
using System.Linq;
using CarolineCottageClasses;
internal sealed class Configuration : DbMigrationsConfiguration<CarolineCottage.Repository.CarolineCottageDatabase.CarolineCottageDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = @"Migrations";
//SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
//SetHistoryContextFactory("MySql.Data.MySqlClient", (conn, schema) => new MySqlHistoryContext(conn, schema));
}
protected override void Seed(CarolineCottage.Repository.CarolineCottageDatabase.CarolineCottageDbContext dbContext)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
if (dbContext.Users.Count() == 0)
{
User user = new User();
user.Name = "nina";
user.Salt = "9gj8BVfA";
user.PasswordEnc = "B6Zz0WZf9qUuY1vRaypyTLUq4Fk=";
user.DateSet = DateTime.Now;
dbContext.Users.Add(user);
dbContext.SaveChanges();
}
}
}
//public class MySqlHistoryContext : HistoryContext
//{
// public MySqlHistoryContext(DbConnection connection, string defaultSchema) : base(connection, defaultSchema)
// {
// }
// protected override void OnModelCreating(DbModelBuilder modelBuilder)
// {
// base.OnModelCreating(modelBuilder);
// modelBuilder.Entity<HistoryRow>().Property(h => h.MigrationId).HasMaxLength(100).IsRequired();
// modelBuilder.Entity<HistoryRow>().Property(h => h.ContextKey).HasMaxLength(200).IsRequired();
// }
//}
}
|
Markdown
|
UTF-8
| 1,276
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
# Take
Берет только определенное количество значений, после чего завершается
> 💡 `take` является противоположным оператором оператора `skip`, если `take` берет *n* значений и закрывается, то `skip` пропускает эти значения
## Сигнатура
```typescript
take<T>(count: number): MonoTypeOperatorFunction<T>
```
## Параметры
<dl>
<dt><code>count</code></dt>
<dd>Количество значений которые нужно взять</dd>
</dl>
## Примеры
```typescript
// RxJS v6+
import { of } from 'rxjs';
import { take } from 'rxjs/operators';
//emit 1,2,3,4,5
const source = of(1, 2, 3, 4, 5);
//take the first emitted value then complete
const example = source.pipe(take(1));
//output: 1
const subscribe = example.subscribe(val => console.log(val));
```
## Полезные ссылки
- 📰 Официальная документация: [take](https://rxjs.dev/api/operators/take)
- 📁 Исходный код: [https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/take.ts](https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/take.ts)
|
Java
|
UTF-8
| 14,836
| 1.65625
| 2
|
[] |
no_license
|
package com.arpit.miraquee.afterauthenticated;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.arpit.miraquee.RequestNotif.ApiServe;
import com.arpit.miraquee.RequestNotif.Client;
import com.arpit.miraquee.RequestNotif.Data;
import com.arpit.miraquee.RequestNotif.MyResponse;
import com.arpit.miraquee.RequestNotif.NotificationSender;
import com.arpit.miraquee.R;
import com.arpit.miraquee.SharedPreferences.Preferences;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.SetOptions;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.mikhaellopez.circularimageview.CircularImageView;
import com.squareup.picasso.Picasso;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Search_recycler_adapter extends RecyclerView.Adapter<Search_recycler_adapter.myAdapter> {
List<SearchModel> list;
Context context;
FirebaseFirestore db;
FirebaseAuth mAuth;
String uid;
Preferences prefs;
ApiServe apiServe;
StorageReference storageReference;
public Search_recycler_adapter(List<SearchModel> list, Context context) {
this.list = list;
this.context = context;
prefs = new Preferences(context);
db = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
uid = mAuth.getCurrentUser().getUid();
apiServe = Client.getClient("https://fcm.googleapis.com/").create(ApiServe.class);
}
@NonNull
@Override
public Search_recycler_adapter.myAdapter onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_search_element,
parent,
false);
return new Search_recycler_adapter.myAdapter(view);
}
@Override
public void onBindViewHolder(@NonNull Search_recycler_adapter.myAdapter holder, int position) {
holder.bind(list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
class myAdapter extends RecyclerView.ViewHolder {
TextView name, username;
CircularImageView image;
Button addContact;
public myAdapter(@NonNull View itemView) {
super(itemView);
}
public void bind(SearchModel searchModel) {
name =itemView.findViewById(R.id.searchname);
username = itemView.findViewById(R.id.searchusername);
image = itemView.findViewById(R.id.searchChatCiv);
addContact = itemView.findViewById(R.id.addContact);
//to denote the users signs when start up
db.collection("All Users").document(searchModel.getUid()).collection("Contacts")
.document(uid).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Boolean status = documentSnapshot.getBoolean("Status");
String SorR = documentSnapshot.getString("SentOrRecieved");
if(status == null){
}
else{
if(status == false) {
if(SorR.equals("R")){
addContact.setBackgroundResource(R.drawable.ic_request_sent);
}
if(SorR.equals("S")){
addContact.setBackgroundResource(R.drawable.ic_request_received);
}
}
if(status == true){
addContact.setBackgroundResource(R.drawable.ic_friends);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(context, "Update Failed", Toast.LENGTH_SHORT).show();
}
});
addContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//same thing but only when the user presses it
db.collection("All Users").document(searchModel.getUid()).collection("Contacts")
.document(uid).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Boolean status = documentSnapshot.getBoolean("Status");
if(status == null){
sendContactRequest(searchModel);
}
else{
if(status == false) {
removeRequest(searchModel);
}
if(status == true){
Toast.makeText(context, "Already Friends", Toast.LENGTH_SHORT).show();
}
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(context, "Update Failed", Toast.LENGTH_SHORT).show();
}
});
}
});
//For Name, username, and Profile Pic
name.setText(searchModel.getName());
username.setText("@"+searchModel.getUsername());
StorageReference profoleRef = storageReference.child("Profile Photos").child(searchModel.getUid());
profoleRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Log.d("Check", "Uri has been received");
Picasso.get().load(uri).into(image);
}
});
}
private void removeRequest(@NotNull SearchModel searchModel) {
db.collection("All Users").document(searchModel.getUid()).collection("Contacts")
.document(uid).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String SorR = documentSnapshot.getString("SentOrRecieved");
if(SorR.equals("R")){
db.collection("All Users").document(searchModel.getUid()).collection("Contacts")
.document(uid).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
removeFromMyContactList(searchModel);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
if(SorR.equals("S")){
Toast.makeText(context, "This person has sent you the request! You can only accept it", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
private void removeFromMyContactList(@NotNull SearchModel searchModel) {
db.collection("All Users").document(uid).collection("Contacts")
.document(searchModel.getUid()).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
addContact.setEnabled(false);
addContact.postDelayed(new Runnable() {
@Override
public void run() {
addContact.setEnabled(true);
}
}, 500);
addContact.setBackgroundResource(R.drawable.ic_person_add);
Toast.makeText(context, "Request Deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(context, "Update Failed", Toast.LENGTH_SHORT).show();
}
});
}
private void sendContactRequest(SearchModel searchModel) {
DocumentReference documentReference = db.collection("All Users").document(searchModel.getUid()).collection("Contacts")
.document(uid);
Map<String, Object> request = new HashMap<>();
request.put("SentOrRecieved","R");
request.put("OpponentUid",uid);
request.put("Status",false);
request.put("OpponentUsername", prefs.getData("username"));
request.put("OpponentName", prefs.getData("usernameAdded"));
documentReference.set(request, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
addContact.setBackgroundResource(R.drawable.ic_request_sent);
updateMyContactlist(searchModel);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(context, "Update Failed", Toast.LENGTH_SHORT).show();
}
});
}
private void updateMyContactlist(SearchModel searchModel) {
DocumentReference documentReference = db.collection("All Users").document(uid).collection("Contacts")
.document(searchModel.getUid());
Map<String, Object> request = new HashMap<>();
request.put("SentOrRecieved","S");
request.put("OpponentUid",searchModel.getUid());
request.put("Status",false);
request.put("OpponentUsername",searchModel.getUsername());
request.put("OpponentName", searchModel.getName());
documentReference.set(request, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
addContact.setEnabled(false);
addContact.postDelayed(new Runnable() {
@Override
public void run() {
addContact.setEnabled(true);
sendCloudNotification(searchModel);
}
}, 500);
Toast.makeText(context, "Request Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(context, "Update Failed", Toast.LENGTH_SHORT).show();
}
});
}
private void sendCloudNotification(SearchModel searchModel) {
//get opponents token
db.collection("All Users").document(searchModel.getUid()).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String opponentsToken;
opponentsToken = documentSnapshot.getString("FCM_token");
if(opponentsToken!= null){
String Title = "New Request!";
String Message = "@"+prefs.getData("username") + " wants to be your Contact! Open Requests in the application to see all pending requests";
Data data = new Data(Title, Message);
NotificationSender sender= new NotificationSender(data, opponentsToken);
apiServe.sendNotification(sender).enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if(response.code() == 200){
if(response.body().success != 1){
Toast.makeText(context, "Failed! The user is inactive", Toast.LENGTH_SHORT).show();
}
else{
// Toast.makeText(context, "FCM sent", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(context, "Failed!"+ t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
}
|
TypeScript
|
UTF-8
| 3,794
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
import { expect } from "chai";
import GildedRose from "../app/GildedRose";
import AgedBrie from "../app/AgedBrie";
import BackstagePasses from "../app/BackstagePasses";
import StandardItem from "../app/StandardItem";
import Sulfuras from "../app/Sulfuras";
describe("Gilded Rose", function () {
it("SellIn value is decreased", () => {
const items = [new StandardItem("whatever", 10, 0)];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].sellIn).to.equal(9);
});
it("Quality value is decreased", () => {
const items = [new StandardItem("whatever", 1, 10)];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(9);
});
it("Quality decreases twice as much when SellIn is passed", () => {
const items = [new StandardItem("whatever", 0, 10)];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(8);
});
it("Quality is never negative", () => {
const items = [new StandardItem("whatever", 0, 0)];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(0);
});
it("Aged Brie increases quality by one before SellIn passes", () => {
const items = [new AgedBrie("Aged Brie", 5, 5)];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(6);
});
it("Aged Brie increases quality by two after SellIn passes", () => {
const items = [new AgedBrie("Aged Brie", -1, 5)];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(7);
});
it("Quality never increases past fifty", () => {
const items = [new AgedBrie("Aged Brie", 10, 50)];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(50);
});
it("Sulfuras never changes", () => {
const items = [new Sulfuras("Sulfuras, Hand of Ragnaros", 10, 35)];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(35);
});
it("Backstage pass increases quality by one if SellIn greater then ten", () => {
const items = [
new BackstagePasses("Backstage passes to a TAFKAL80ETC concert", 11, 20),
];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(21);
});
it("Backstage pass increases quality by two if SellIn smaller than ten", () => {
const items = [
new BackstagePasses("Backstage passes to a TAFKAL80ETC concert", 6, 20),
];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(22);
});
it("Backstage pass increases quality by three if SellIn smaller than five", () => {
const items = [
new BackstagePasses("Backstage passes to a TAFKAL80ETC concert", 5, 20),
];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(23);
});
it("Backstage pass loses value after SellIn passes", () => {
const items = [
new BackstagePasses("Backstage passes to a TAFKAL80ETC concert", 0, 20),
];
const gildedRose = new GildedRose();
const updatedItems = gildedRose.updateQuality(items);
expect(updatedItems[0].quality).to.equal(0);
});
});
|
Python
|
UTF-8
| 384
| 3.578125
| 4
|
[
"MIT"
] |
permissive
|
# Script will start by asking for input.
# Then it will scan that input for big H and little h
# occurrences and print those out.
# See https://github.com/Static-Void-Academy/Module0-Challenges/blob/master/M0_C2.md
message = input('Input message: ')
H = 0
h = 0
for char in message:
if char == 'H':
H += 1
elif char == 'h':
h += 1
print(f'H: {H}, h: {h}')
|
Python
|
UTF-8
| 8,279
| 2.875
| 3
|
[] |
no_license
|
#coding=utf-8
import math
import copy
class Iris:
attribute=[]
data=[]
label=[]
pass
def load_dataset(filename="Iris_train.txt"):
f=open(filename)
line=f.readline().strip()
propty=line.split(',')[:-1]#属性名
total=Iris()
total.attribute=propty
dataset=[]#保存每一个样本的数据信息+
label=[]#保存样本的标签
while line:
line=f.readline().strip()
if(not line):
break
temp=line.split(',')
content=[]
for i in temp[0:-1]:
content.append(float(i))
dataset.append(content)
label.append(temp[-1])
total.data=dataset
total.label=label
return total
class DCTree:
attribute=[]
data=[]
label=[]
partition_value=[]
data_loaded=False
trained=False
attribute2num={}
num2attribute={}
total_D=[]
tree=[]#用来存放节点的树结构
def __init__(self):
pass
def load_traindata(self,traindata,label,attribute):#traindata为一个二维列表
self.data=traindata
self.label=label
self.attribute=attribute
self.data_loaded=True
r=range(len(attribute))
self.attribute2num=dict(zip(attribute,r))
for i,j in zip(traindata,label):
self.total_D.append([i,j])
#计算信息熵
def Ent(self,D):#D为带标签的数组
label=[]
for i in D:
label.append(i[1])
label_set=set(label)
sum_=0
for i in label_set:
temp=label.count(i)/float(len(label))
if temp==1:
continue
else:
sum_-=temp*math.log(2,temp)#迭代计算信息熵
return sum_
#基于二分的方式,选出当前数据集D中最所有属性的最优划分点,返回一个字典保存attribute_中属性和对应划分点的值的键值对
def compute_partition_value(self,D,attribute_):
attribute_2_attribute_value={}
for i in attribute_:
temp=[]
for j in D:
temp.append(j[0][self.attribute2num[i]])
temp=sorted(temp)#将每种属性的值放在一个列表中并排序
partition_temp=[]
for j in range(len(temp)-1):
partition_temp.append((temp[j]+temp[j+1])/2)
max_parti_value=partition_temp[0]
max_gain=-999999
D_a=[]
for j in D:
D_a.append([j[0][self.attribute2num[i]],j[1]])
ent_d=self.Ent(D_a)#计算D整体样本集的信息熵
for j in partition_temp:
D1=[]
D2=[]
for k in D_a:
if(k[0]<j):
D1.append(k)
else:
D2.append(k)
temp_gain=ent_d-(len(D1)*self.Ent(D1)/float(len(D_a))+len(D2)*self.Ent(D2)/float(len(D_a)))
if temp_gain>max_gain:
max_parti_value=j
attribute_2_attribute_value[i]=max_parti_value
return attribute_2_attribute_value
#计算信息增益
def Gain(self,D,attribute_,a):#D为带标签的数组,[[属性值,标签],...],a为划分属性属性
attribute_2_parti_value_dict=self.compute_partition_value(D,attribute_)
max_gain=-999999
a_id=self.attribute2num[a]
D_a=[]
for i in D:
D_a.append([i[0][a_id],i[1]])
ent_d=self.Ent(D_a)#计算D整体样本集的信息熵
D1=[]
D2=[]
for j in D_a:
if(j[0]<attribute_2_parti_value_dict[a]):
D1.append(j)
else:
D2.append(j)
gain_value=ent_d-(len(D1)*self.Ent(D1)/float(len(D_a))+len(D2)*self.Ent(D2)/float(len(D_a)))
return gain_value
#为当前数据集构造决策树,递归过程
def generate_dctree(self,D,attributes_):#D为带标签的样本集,attributes为还未划分的属性
tree=[]#定义子决策树
# print D
label=[]
for i in D:
label.append(i[1])
print label
set_label=set(label)
#递归返回条件:1.当前数据集中所有对象属于同一个类别;2.没有剩余的划分属性了;3.当前数据集为空;满足一个便可将当前数据集作为一个叶子节点
if len(set_label)==1:#当前数据集中所有对象属于同一个类别,该类别就作为当前叶子节点的类别
print "leaf_1: ",set_label[0]
return ["leaf node",set_label[0]]
print "attributes_:",attributes_
if len(attributes_)==0:#若没有在可以用来划分的属性,取该叶子中所有数据集中类别最多的一类
max_count=0
leaf_label=""
for i in set_label:
print "i:",i
if label.count(i)>max_count:
print label.count(i)
max_count=label.count(i)
leaf_label=i
print "leaf_2: ",leaf_label
return ["leaf node",leaf_label]
if len(D)==0:#若当前数据集为空则返回空
print "NULL"
return
max_a=-9999
best_attribute=""
attribute_2_parti_value_dict=self.compute_partition_value(D,attributes_)
for a in attributes_:
temp=self.Gain(D,attributes_,a)
if temp>max_a:
max_a=temp
best_attribute=a
#定义用于递归的子数据集
sub_D1=[]
sub_D2=[]
parti_value=attribute_2_parti_value_dict[best_attribute]
print "best_attribute:",best_attribute,"pativalue:",parti_value
a_id=self.attribute2num[best_attribute]
#将当前数据集根据当前最优属性的划分点分成两个子数据集
for i in D:
if i[0][a_id]<parti_value:
sub_D1.append(i)
else:
sub_D2.append(i)
print "sub_D1:",sub_D1
print "sub_D2:",sub_D2
node_info="not leaf node"
tree.append(node_info)#是否是叶子节点信息
tree.append(best_attribute)#若不是叶子节点,当前节点的划分属性
tree.append(parti_value)#当前节点的划分属性的划分值
new_attribute_=copy.copy(attributes_)
new_attribute_.remove(best_attribute)#移除当前节点使用的属性,剩余的属性作为子决策树的属性集
sub_tree1=self.generate_dctree(sub_D1,new_attribute_)
sub_tree2=self.generate_dctree(sub_D1,new_attribute_)
tree.append(sub_tree1)
tree.append(sub_tree2)
return tree #返回当前决策树
#训练函数
def train(self):
if not self.data_loaded:
print "No data loaded!"
return
#生成决策树
self.tree=self.generate_dctree(self.total_D,self.attribute)
self.trained=True
#预测函数
def predict(self,testdata):#testdata为一个一维列表
if not self.trained:
print "Please train DCT first!"
return
curr_tree=copy.deepcopy(self.tree)
#决策树从根节点开始的沿着路径向下寻找对应叶节点
while curr_tree[0]!="leaf node":
curr_attribute=curr_tree[1]
a_id=self.attribute2num[curr_attribute]
if testdata[a_id]<curr_tree[2]:
curr_tree=curr_tree[3]#左子树
else:
curr_tree=curr_tree[4]#右子树
result=curr_tree[1]
return result
if __name__ == '__main__':
dataset=load_dataset("Iris_train.txt")
print dataset
dct=DCTree()#读入样本属性集
dct.load_traindata(dataset.data,dataset.label,dataset.attribute)
dct.train()
print dct.tree
#加载测试集
testset=load_dataset("Iris_test.txt")
predict_result=[]
for i in testset.data:
predict_result.append(dct.predict(i))
print predict_result
print testset.label
|
JavaScript
|
UTF-8
| 302
| 3.59375
| 4
|
[] |
no_license
|
function distancePoints(x1, y1, x2, y2) {
let point1 = { x: x1, y: y1 };
let point2 = { x: x2, y: y2 };
let distanseX = Math.pow(point1.x - point2.x, 2);
let distanseY = Math.pow(point1.y - point2.y, 2);
console.log(Math.sqrt(distanseX + distanseY));
}
distancePoints(2, 4, 5, 0);
|
Markdown
|
UTF-8
| 3,719
| 4
| 4
|
[] |
no_license
|
### python闭包
在一个内部函数中,对外部作用域的变量进行引用,(并且一般外部函数的返回值为内部函数),那么内部函数就被认为是闭包
闭包存在的意义就是它夹带了外部变量(私货),如果它不夹带私货,它和普通的函数就没有任何区别。**同一个的函数**夹带了**不同的私货**,就实现了不同的功能。其实你也可以这么理解,闭包和面向接口编程的概念很像,可以把闭包理解成轻量级的接口封装。
函数身为第一类对象,它可以作为函数的返回值返回,现在我们来考虑如下的例子:
```python
def print_msg():
# print_msg 是外围函数
msg = "zen of python"
def printer():
# printer 是嵌套函数
print(msg)
return printer
another = print_msg()
# 输出 zen of python
another()
```
一般情况下,函数中的局部变量仅在函数的执行期间可用,一旦 print_msg() 执行过后,我们会认为 msg变量将不再可用。然而,在这里我们发现 print_msg 执行完之后,在调用 another 的时候 msg 变量的值正常输出了,这就是闭包的作用,闭包使得局部变量在函数外被访问成为可能。
**在函数中可以(嵌套)定义另一个函数时,如果内部的函数引用了外部的函数的变量,则可能产生闭包。闭包可以用来在一个函数与一组“私有”变量之间创建关联关系。在给定函数被多次调用的过程中,这些私有变量能够保持其持久性**
> > **在计算机科学中,闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。所以,有另一种说法认为闭包是由函数和与其相关的引用环境组合而成的实体。**
> >
> > 这里的 another 就是一个闭包,闭包本质上是一个函数,它有两部分组成,printer 函数和变量 msg。闭包使得这些变量的值始终保存在内存中。
> >
> > 闭包,顾名思义,就是一个封闭的包裹,里面包裹着自由变量,就像在类里面定义的属性值一样,自由变量的可见范围随同包裹,哪里可以访问到这个包裹,哪里就可以访问到这个自由变量
> ### 为什么要使用闭包
>
> 闭包避免了使用全局变量,此外,闭包允许将函数与其所操作的某些数据(环境)关连起来。这一点与面向对象编程是非常类似的,在面对象编程中,对象允许我们将某些数据(对象的属性)与一个或者多个方法相关联。
>
> 一般来说,当对象中只有一个方法时,这时使用闭包是更好的选择。来看一个例子:
>
> ```python
> def adder(x):
> def wrapper(y):
> return x + y
> return wrapper
>
> adder5 = adder(5)
> # 输出 15
> adder5(10)
> # 输出 11
> adder5(6)
>
>
> 这比用类来实现更优雅,此外装饰器也是基于闭包的一中应用场景。所有函数都有一个 __closure__属性,如果这个函数是一个闭包的话,那么它返回的是一个由 cell 对象 组成的元组对象。cell 对象的cell_contents 属性就是闭包中的自由变量。
>
> ···
> >>> adder.__closure__
> >>> adder5.__closure__
> (<cell at 0x103075910: int object at 0x7fd251604518>,)
> >>> adder5.__closure__[0].cell_contents
> 5
>
>
> 解释了为什么局部变量脱离函数之后,还可以在函数之外被访问的原因的,因为它存储在了闭包的 cell_contents中了。
> ```
>
>
|
Python
|
UTF-8
| 2,426
| 3.59375
| 4
|
[] |
no_license
|
import unittest
from character import *
from item import *
from location import *
from parse import *
class LocationTest(unittest.TestCase):
player = Player("hero", "i'm so brave", 100)
sword = Weapon("sword", "ouch it's sharp!", 100, 20)
front_gate = Location("Front gate", "You're outside the front gate of town. A town guard is in front of it and a rock is on the floor nearby.")
guard = Npc("guard", "He's standing in front of the town gate. Looks angry...")
rock = Item("rock", "A small rock. No bigger than your palm.")
key = Item("Key", "a key to town!")
main_street = Location("Main street", "The main street of town")
shield = Armour("shield", "a solid shield to protect you!", 50, 25)
front_gate.add_item(sword)
front_gate.add_item(rock)
front_gate.add_path({"north": main_street})
front_gate.add_player(player)
guard.add_item(key)
def test_add_and_get_item(self):
self.front_gate.add_item(self.shield)
self.assertEqual(self.front_gate.items, [self.sword, self.rock, self.shield])
self.assertEqual(self.front_gate.get_item("shield"), self.shield)
def test_add_and_get_character(self):
self.front_gate.add_character(self.player)
self.assertEqual(self.front_gate.characters, [self.player])
self.assertEqual(self.front_gate.get_character("hero"), self.player)
def test_search_objects(self):
self.assertEqual(self.front_gate.search_objects("sword"), self.sword)
self.assertEqual(self.front_gate.search_objects("hero"), self.player)
self.assertEqual(self.front_gate.search_objects("shield"), self.shield)
self.assertEqual(self.front_gate.search_objects("north"), self.front_gate.paths.get('north'))
self.assertEqual(self.front_gate.search_objects("key"), self.key)
def test_process_event(self):
self.player.add_item(self.rock)
sentence = "use rock"
self.front_gate.event = {"action_verb": "use", "action_object": "rock", "reaction_object": "Key",
"reaction_verb": "can_trade", "reaction_desc": "You threw the rock at the guard. \
it knocked him over in one!"}
parser = Parser(self.player, self.front_gate)
use_action = parser.parse(sentence)
self.front_gate.process_event(use_action)
self.assertTrue(self.key.tradeable)
|
Python
|
UTF-8
| 3,305
| 3.015625
| 3
|
[] |
no_license
|
from dataclasses import dataclass
from typing import Dict, List, Optional
MIN_BYR = 1920
MAX_BYR = 2002
MIN_IYR = 2010
MAX_IYR = 2020
MIN_EYR = 2020
MAX_EYR = 2030
HEIGHT_UNIT_INCHES = "in"
HEIGHT_UNIT_CENTIMETERS = "cm"
MIN_HEIGHT_INCHES = 59
MAX_HEIGHT_INCHES = 76
MIN_HEIGHT_CENTIMETERS = 150
MAX_HEIGHT_CENTIMETERS = 193
HAIR_COLOR_PREFIX = "#"
EYE_COLORS = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
PASSPORT_ID_LENGTH = 9
@dataclass(frozen=True)
class Passport:
byr: str
iyr: str
eyr: str
hgt: str
hcl: str
ecl: str
pid: str
cid: Optional[str] = None
def __post_init__(self):
int_byr = int(self.byr)
if int_byr < MIN_BYR or MAX_BYR < int_byr:
raise ValueError()
int_iyr = int(self.iyr)
if int_iyr < MIN_IYR or MAX_IYR < int_iyr:
raise ValueError()
int_eyr = int(self.eyr)
if int_eyr < MIN_EYR or MAX_EYR < int_eyr:
raise ValueError()
hgt_val = int(self.hgt[:-2])
hgt_unit = self.hgt[-2:]
valid_inches = hgt_unit == HEIGHT_UNIT_INCHES and MIN_HEIGHT_INCHES <= hgt_val <= MAX_HEIGHT_INCHES
valid_centimeters = hgt_unit == HEIGHT_UNIT_CENTIMETERS and MIN_HEIGHT_CENTIMETERS <= hgt_val <= MAX_HEIGHT_CENTIMETERS
if not valid_inches and not valid_centimeters:
raise ValueError()
# Check the prefix of the hair color. Check the color value is valid by casting to hexadecimal int
int(self.hcl[1:], 16)
if not self.hcl[0] == HAIR_COLOR_PREFIX:
raise ValueError()
if self.ecl not in EYE_COLORS:
raise ValueError()
if not len(self.pid) == PASSPORT_ID_LENGTH or not self.pid.isdecimal():
raise ValueError()
def build_passport(data: Dict[str, str]) -> Optional[Passport]:
try:
return Passport(**data)
except TypeError:
# If a TypeError occurs it's because we didn't meet the requirements of a passport
return None
except ValueError:
# Same as TypeError
return None
def find_valid_passports() -> List[Passport]:
# Iterate through file and group passwords so its one per line
passport_data = {}
passports = []
with open("/app/advent2020/inputs/passport_processing.txt", "r") as input_file:
for line in input_file:
clean_line = line.strip()
if clean_line:
# Split the line by whitespace. Separate the key from the val and add to a dict.
key_vals = dict(key_val.split(":") for key_val in clean_line.split())
# Merge the active passport data with the most recently passport data
passport_data.update(key_vals)
elif bool(passport_data):
passport = build_passport(passport_data)
passport_data = {}
if passport:
passports.append(passport)
passport = build_passport(passport_data)
if passport:
passports.append(passport)
return passports
if __name__ == "__main__":
passports = find_valid_passports()
print("# of Valid Passports Found:", len(passports))
|
C#
|
UTF-8
| 338
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
namespace Tests.Models.Inheritance
{
public abstract class Shape
{
protected Shape(bool prefill = false, string id = "123")
{
Id = id;
if (!prefill) return;
Color = "Purple";
}
public string Id { get; set; }
public string Color { get; set; }
}
}
|
Python
|
UTF-8
| 2,946
| 2.875
| 3
|
[] |
no_license
|
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer, ListTrainer
def create_chatbot():
"""Creates a ChatBot instance"""
bot = ChatBot(
'Xaman',
logic_adapters=[
{
'import_path': 'chatterbot.logic.BestMatch',
'default_response': 'I am sorry, but I do not understand.',# If its not sure of the response, this will be the default response
'maximum_similarity_threshold': 1.0 # Responds if is sure of the response
},
],
read_only=True
)
return train_chatbot(bot)
def train_chatbot(bot):
"""Train the bot to respond to an user input."""
bot.storage.drop()
# List trainers will establish each item in the list as a possible response to it’s predecessor in the list.
trainer1 = ListTrainer(bot)
trainer1.train([
'Hello',
'Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
'Hi',
'Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
'Hi Bot',
'Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
'Hi Chatterbot',
'Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
'Hey',
'Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
'Can you help me with my trip?',
'Sure! Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
'Help',
'Sure! Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
'Help me',
'Sure! Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
'Trip',
'Please provide the date of your next trip? The date must be within the next 5 days. Format: dd/mm/yyyy',
])
trainer2 = ListTrainer(bot)
trainer2.train([
'Thank you',
'You are welcome. Can I help you with anything else?',
'Thanks',
'You are welcome. Can I help you with anything else?',
'Ok',
'Can I help you with anything else?',
'No',
'Ok, take care and enjoy your trip',
'I will',
'I am sure you will!',
])
trainer3 = ListTrainer(bot)
trainer3.train([
'What is your name',
'My name is Xaman'
])
# Corpus trainer trains bot using data from the ChatterBot dialog corpus
trainer4 = ChatterBotCorpusTrainer(bot)
trainer4.train( # We specify the corpus data modules we want to use
"chatterbot.corpus.english.conversations",
"chatterbot.corpus.english.botprofile"
)
return bot
|
Java
|
UTF-8
| 3,767
| 3.34375
| 3
|
[] |
no_license
|
/**
* Copyright © zuoguoqing
*
* @description
* @package name.zuoguoqing.concurrency.async
* @file Shop.java
* @author zuoguoqing
* @date 2020年10月11日
* @version
*/
package name.zuoguoqing.concurrency.async;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author zuoguoqing
*
*/
public class Shop {
private String shopName;
private Random random = new Random(7);
public Shop(String shopName) {
super();
this.shopName = shopName;
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
private double caculatePrice(String product) {
delay();
return random.nextDouble() * product.charAt(0) + product.charAt(1);
}
private static void delay() {
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 同步方式API
* @param product
* @return
*/
public double getPrice(String product) {
return caculatePrice(product);
}
/**
* 传统异步方式
* @param product
* @return
*/
public Future<Double> getPriceAsync1(String product) {
return Executors.newSingleThreadExecutor().submit(() -> {
return caculatePrice(product);
});
}
/**
* CompletableFuture实现异步
* @param product
* @return
*/
public Future<Double> getPriceAsync2(String product) {
CompletableFuture<Double> future = new CompletableFuture<>();
new Thread(() -> {
double price = caculatePrice(product);
future.complete(price);
}).start();;
return future;
}
/**
* 异步异常处理
* @param product
* @return
*/
public Future<Double> getPriceAsync3(String product) {
CompletableFuture<Double> future = new CompletableFuture<Double>();
new Thread(() -> {
try {
double price = caculatePrice(product);
future.complete(price);
} catch (Exception e) {
future.completeExceptionally(e);
}
}).start();;
return future;
}
/**
* 静态方法supplyAsync实现异步API
* @param product
* @return
*/
public Future<Double> getPriceAsync(String product) {
return CompletableFuture.supplyAsync(() -> caculatePrice(product));
}
/**
* @param args
*/
public static void main(String[] args) {
Shop shop = new Shop("BestShop");
long begin = System.currentTimeMillis();
Future<Double> futurePrice = shop.getPriceAsync("my favorite pruduct");
doSomethingElse();
double price = 0D;
try {
price = futurePrice.get(3000, TimeUnit.MILLISECONDS);
System.out.format("Price is %.2f%n", price);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
long retrivalTime = System.currentTimeMillis() - begin;
System.out.println("Price returned after " + retrivalTime + " ms.");
}
private static void doSomethingElse() {
// TODO Auto-generated method stub
}
}
|
PHP
|
UTF-8
| 1,763
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
<?php
namespace inklabs\kommerce\EntityDTO\Builder;
use inklabs\kommerce\Entity\ShipmentTracker;
use inklabs\kommerce\EntityDTO\ShipmentTrackerDTO;
class ShipmentTrackerDTOBuilder implements DTOBuilderInterface
{
use IdDTOBuilderTrait, TimeDTOBuilderTrait;
/** @var ShipmentTracker */
protected $entity;
/** @var ShipmentTrackerDTO */
protected $entityDTO;
/** @var DTOBuilderFactoryInterface */
protected $dtoBuilderFactory;
public function __construct(ShipmentTracker $shipmentTracker, DTOBuilderFactoryInterface $dtoBuilderFactory)
{
$this->entity = $shipmentTracker;
$this->dtoBuilderFactory = $dtoBuilderFactory;
$this->entityDTO = new ShipmentTrackerDTO;
$this->setId();
$this->setTime();
$this->entityDTO->trackingCode = $this->entity->getTrackingCode();
$this->entityDTO->externalId = $this->entity->getExternalId();
$this->entityDTO->carrier = $this->dtoBuilderFactory
->getShipmentCarrierTypeDTOBuilder($this->entity->getCarrier())
->build();
if ($this->entity->getShipmentRate() !== null) {
$this->entityDTO->shipmentRate = $this->dtoBuilderFactory
->getShipmentRateDTOBuilder($this->entity->getShipmentRate())
->build();
}
if ($this->entity->getShipmentLabel() !== null) {
$this->entityDTO->shipmentLabel = $this->dtoBuilderFactory
->getShipmentLabelDTOBuilder($this->entity->getShipmentLabel())
->build();
}
}
protected function preBuild()
{
}
public function build()
{
$this->preBuild();
unset($this->entity);
return $this->entityDTO;
}
}
|
Java
|
UTF-8
| 4,640
| 2.078125
| 2
|
[] |
no_license
|
package com.hxx.flexboxlayoutdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.flexbox.FlexboxLayout;
public class MainActivity extends AppCompatActivity {
private Spinner mSpinner_flexDirection;
private Spinner mSpinner_flexWrap;
private Spinner mSpinner_justifyContent;
private Spinner mSpinner_alignItems;
private Spinner mSpinner_alignContent;
private FlexboxLayout mFlexbox_layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initFlexBox();
initSpinners();
}
private void initSpinners() {
ArrayAdapter<String> adapterFlexDirection = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
ArrayAdapter<String> adapterFlexWrap = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
ArrayAdapter<String> adapterJustifyContent = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
ArrayAdapter<String> adapterAlignItems = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
ArrayAdapter<String> adapterAlignContent = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
adapterFlexDirection.addAll("row", "row-reverse", "column", "column-reverse");
adapterFlexWrap.addAll("nowrap", "wrap", "wrap_reverse");
mSpinner_flexDirection.setAdapter(adapterFlexDirection);
mSpinner_flexDirection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
mFlexbox_layout.setFlexDirection(FlexboxLayout.FLEX_DIRECTION_ROW);
break;
case 1:
mFlexbox_layout.setFlexDirection(FlexboxLayout.FLEX_DIRECTION_ROW_REVERSE);
break;
case 2:
mFlexbox_layout.setFlexDirection(FlexboxLayout.FLEX_DIRECTION_COLUMN);
break;
case 3:
mFlexbox_layout.setFlexDirection(FlexboxLayout.FLEX_DIRECTION_COLUMN_REVERSE);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
mFlexbox_layout.setFlexDirection(FlexboxLayout.FLEX_DIRECTION_ROW);
}
});
mSpinner_flexWrap.setAdapter(adapterFlexWrap);
mSpinner_flexWrap.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
mFlexbox_layout.setFlexWrap(FlexboxLayout.FLEX_WRAP_NOWRAP);
break;
case 1:
mFlexbox_layout.setFlexWrap(FlexboxLayout.FLEX_WRAP_WRAP);
break;
case 2:
mFlexbox_layout.setFlexWrap(FlexboxLayout.FLEX_WRAP_WRAP_REVERSE);
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void initFlexBox() {
char[] chars = "我爱北京天安门".toCharArray();
for (char c : chars) {
TextView textView = new TextView(this);
textView.setWidth(200);
textView.setGravity(Gravity.CENTER);
textView.setText(c + "");
mFlexbox_layout.addView(textView);
}
}
private void initView() {
mSpinner_flexDirection = (Spinner) findViewById(R.id.spinner_flexDirection);
mSpinner_flexWrap = (Spinner) findViewById(R.id.spinner_flexWrap);
mSpinner_justifyContent = (Spinner) findViewById(R.id.spinner_justifyContent);
mSpinner_alignItems = (Spinner) findViewById(R.id.spinner_alignItems);
mSpinner_alignContent = (Spinner) findViewById(R.id.spinner_alignContent);
mFlexbox_layout = (com.google.android.flexbox.FlexboxLayout) findViewById(R.id.flexbox_layout);
}
}
|
C++
|
GB18030
| 1,414
| 2.859375
| 3
|
[] |
no_license
|
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
/*
Ҫ˼·ȰѱȻ鼯жǷͨ kruskal=+鼯
*/
struct node
{
int u,v,w;
bool operator < (const node &x)const//ijԱʽthisָ
{ //ڳԱconstʾݵһָthisָ
// const node *const this
return w<x.w;//w=this->w;
}
} q[1000002];
int e=0;
int fa[100002];
int findset(int x)//鼯
{
return fa[x]!=x?fa[x]=findset(fa[x]):x;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
int i;
for(i=0; i<m; i++)
scanf("%d%d%d",&q[i].u,&q[i].v,&q[i].w);
sort(q,q+m);//
for(i=0; i<=n; i++)
fa[i]=i;
int ans=0;
int cnt=0;
for(int k=0; k<m; k++)
{
if(findset(q[k].u)!=findset(q[k].v))
{
fa[fa[q[k].u]]=fa[q[k].v];//ѹ
ans+=q[k].w;
cnt++;
if(cnt==n-1)//дׯͨ
break;
}
}
if(cnt==n-1)
printf("%d\n",ans);
else
printf("-1\n");
}
return 0;
}
|
Markdown
|
UTF-8
| 5,953
| 3.4375
| 3
|
[
"MIT"
] |
permissive
|
# Angular Bootstrap Popup & Spinner
A simple and elegant angular service inspired by [ionic popup](http://ionicframework.com/docs/v1/api/service/$ionicPopup) to show loader/spinner and popup(or dialogue) window for `alert` and `confirm` with custom content and look.
## Dialoge Box
PopupSvc exposes two methods `alert` and `confirm` which takes one parameter either string/html template or an [option](#advance-usage) object for customized look and feel.
These methods returns [promise](https://docs.angularjs.org/api/ng/service/$q) which is resolved when the popup is dismissed. It also returns `close` method to programmatically close it.
## Spinner
Use below methods to display a loader or spinner as overlay driven by Bootstrap modal window
1. spin : Show a spinner/loader
2. stopSpin: Stop the spinner
## Dependency
[Angular](https://code.angularjs.org/1.5.3/docs/api) (tested on v1.5.3)
[Angular UI Bootstrap](http://angular-ui.github.io/bootstrap/versioned-docs/1.3.3/) (tested on v1.3.3)
> PopupSvc should work fine with any Angular/UI Bootstrap version supporting [ControllerAs](https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/) syntax.
## Demo
Check out the demo at [Plunker](https://embed.plnkr.co/RX0pIj/)
## Dialoge Usage
```javascript
angular.module('myApp', ['popup']);//add popup module dependency
angular.controller('myCtrl', ['PopupSvc', function(PopupSvc){//Inject the PopupSvc service into your controller
//1. Basic Usage
PopupSvc.alert("<strong>Hey!</strong> How you doing");//html string
PopupSvc.confirm("Are you sure?");//normal text
//2. Reacting on popup dismissal/button click
var popup = PopupSvc.alert("Hey! How you doing");
popup.then(function(){
console.log('Alert dismissed');
});
PopupSvc.confirm("Hey! How you doing").then(function(response){
if(response){
console.log('Primary/OK button clicked');
}else{
console.log('Secondary/Cancel button clicked');
}
});
//Programmatically closing the popup using `close` method
//close method must be executed in next tick as popup creation is asynchronous
var popup = PopupSvc.alert("Hey! How you doing");
window.setTimeout(popup.close, 3000);
//3. Customized popup
var popupOption = {//only fewer options here
title: 'Confirm',
subTitle: '<span style="color: red;">Are you sure?</span>',
body: 'Operation can not be reverted',
okText: 'Delete',
okClass: 'btn-danger',
size: 'md'//show a medium size modal popup
};
PopupSvc.confirm(popupOption);
}]);
```
## Spinner Usage
```javascript
PopupSvc.spin();//spinner without leading text
PopupSvc.spin('Saving...');//spinner with leading text
PopupSvc.stopSpin();//stop and remove the last spinner
//Advance usage to stop the required spinner in case of multiple spinner showing at a time
var modal = PopupSvc.spin();//will create the spinner and return modal reference to stop it
modal.close();//stop or close the spinner
```
## Install
Download the script file directly from Github.
https://raw.githubusercontent.com/amiteshhh/angular-uib-popup/master/popup.service.min.js
Add `script` reference to your html then add `popup` module as angular module dependency. Now you can use `PopupSvc` service.
## Advance Usage
To have a custom look and feel (e.g button texts etc.) use below option as a parameter to `alert` or `confirm`. All of the option properties are optional. Of course you will provide value for `body` or `title` to render some text.
> popup is created using bootstrap $uibModal hence there are few properties related to that as well
```javascript
{
title: '', // String. The title of the popup.
subTitle: '', // String. The sub-title of the popup. only applicable when title provided
body: '',//String to place in the popup body.
okText: 'OK',//text for OK button
okClass: 'btn-info',//class(es) to be added to OK button; e.g 'btn-info btn-small'
cancelText: 'Cancel',//not applicable for alert
cancelClass: 'btn-secondary',
headerClass: 'text-center',//class to be added to bootstrap modal-header
bodyClass: '',//class for bootstrap modal-body
footerClass: '',//class for bootstrap modal-footer
//Below are the three uibModal related properties, see uibModal Bootstrap documentation for details
backdrop: 'static',//Controls presence of a backdrop. Allowed values: true (default), false (no backdrop), 'static' (disables modal closing by click on the backdrop).
keyboard: false,//Indicates whether the dialog should be closable by hitting the ESC key.
size: 'sm',//modal or popup size, default is small
/*NOTE: Below are the app level configuration applicable when input parameter is string. It can be set during angular config phase.
*/
showStringAs: 'body',//it will display the text as modal body(left aligned smaller font text). Other value is 'title' (center aligned h5 element)
enableDynamicSize: true,//show medium size popup when input string extends the below character limit
extendSizeCharLength: 300
};
```
> Sice all applicable string inputs can contains `html` tags therefore you can easily control the style.
## Default Configuration
You can easily configure the default popup option for the application during config phase using `PopupSvcProvider` as below.
```javascript
angular.module('myApp', ['popup'])
.config(['PopupSvcProvider', function(PopupSvcProvider){
PopupSvcProvider.setDefaults({
okText: 'Dismiss',//Now instead of 'OK' popup will show button with text 'Dismiss'
okClass: 'btn-primary',
cancelText: 'Close',
keyboard: true//popup can be closed now with ESC key.
});
}]);
```
However the option parameter will still take precedence over app level configuration.
## License
MIT
|
Swift
|
UTF-8
| 1,123
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// NeumorphismTabTests.swift
// NeumorphismTabTests
//
// Created by touyou on 2020/01/08.
// Copyright © 2020 touyou. All rights reserved.
//
import XCTest
@testable import NeumorphismTab
class NeumorphismTabTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func test_lighterColor() {
let color = UIColor(hue: 0.5, saturation: 0.8, brightness: 0.9, alpha: 1.0)
let sameColor = color.lighterColor(value: 0.0)
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if sameColor.getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
XCTAssertEqual(0.5, h, accuracy: 0.1)
XCTAssertEqual(0.8, s, accuracy: 0.1)
XCTAssertEqual(0.9, b, accuracy: 0.1)
} else {
XCTFail("Cannot get HSB value.")
}
}
}
|
Java
|
UTF-8
| 2,601
| 2.390625
| 2
|
[] |
no_license
|
package controllers;
import backend.api.AgencyServiceGenerator;
import backend.api.ReservationService;
import backend.model.Payment;
import backend.model.PaymentType;
import backend.model.Reservation;
import backend.model.ReservationStatus;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class MakePaymentController {
@FXML public Label labelTotalToPay;
@FXML public Label labelDeadlineDate;
@FXML public Label labelError;
@FXML public ComboBox<String> comboBoxPaymentType;
@FXML public Button buttonCancel;
@FXML public Button buttonConfirm;
private final ReservationService reservationService = AgencyServiceGenerator.createService(ReservationService.class);
private final Reservation reservation = Main.getReservation();
private final List<String> paymentsTypes = Arrays.stream(PaymentType.values())
.map(Enum::name).collect(Collectors.toList());
@FXML
public void initialize() {
initLabels();
initComboBox();
}
private void initLabels() {
labelTotalToPay.setText(String.valueOf(reservation.getTotalPrice()));
labelDeadlineDate.setText(String.valueOf(reservation.getPayment().getDeadlineDate()));
}
private void initComboBox() {
comboBoxPaymentType.getItems().addAll(paymentsTypes);
}
@FXML
public void onCancelClick() {
closeWindow();
}
@FXML
public void onConfirmClick() {
int selectedPaymentTypeIndex = comboBoxPaymentType.getSelectionModel().getSelectedIndex();
if (selectedPaymentTypeIndex != -1) {
Payment updatedPayment = reservation.getPayment();
updatedPayment.setPaymentType(paymentsTypes.get(selectedPaymentTypeIndex));
reservation.setPayment(updatedPayment);
reservation.setStatus(ReservationStatus.PAYMENT_PAID.name());
try {
reservationService.update(reservation).execute();
closeWindow();
} catch (IOException e) {
e.printStackTrace();
}
} else {
labelError.setText("Wybierz metodę płatności!");
}
}
private void closeWindow() {
Stage currentStage = (Stage) buttonConfirm.getScene().getWindow();
currentStage.close();
}
}
|
Python
|
UTF-8
| 60
| 3.3125
| 3
|
[] |
no_license
|
a=3.5
b=4.5
add=a+b
sub=a-b
mul=a*b
print(add)
print(sub)
|
Python
|
UTF-8
| 606
| 3.765625
| 4
|
[
"MIT"
] |
permissive
|
'''
Compute hypotenuse length given angle and opposite side length.
Status: Accepted
'''
import math
###############################################################################
def compute_length(length, angle):
'''Compute hypotenuse length'''
return math.ceil(length / math.sin(angle * math.pi / 180.0))
###############################################################################
if __name__ == '__main__':
length, angle = [int(i) for i in input().split()]
print(compute_length(length, angle))
###############################################################################
|
C#
|
UTF-8
| 99,442
| 2.625
| 3
|
[] |
no_license
|
namespace ReviewApplication.Data.Migrations
{
using Core.Domain;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<ReviewApplication.Data.Infrastructure.ReviewApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ReviewApplication.Data.Infrastructure.ReviewApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
//------------------------------------------------------------------------
//TODO: Set all the proper ID's and Attributes
//TODO: Make a way to 'Programmatically' Create ALL these Tables
//Build 20 Users
context.Users.AddOrUpdate(x => x.Id,
#region
new User
{
Id = 0,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-A",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 1,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-A",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 2,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-B",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 3,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-C",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 4,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-D",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 5,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-E",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 3,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-F",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 6,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-G",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 7,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-H",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 8,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-I",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 9,
IsArchived = false,
Email = "Example@example.com",
ResetEmail = "ResetEmail@example.com",
UserName = "Company-J",
PasswordHash = "Password",
AccountType = "Company",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 10,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-A",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 11,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-B",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 12,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-C",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 13,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-D",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 14,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-E",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 15,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-F",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 16,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-G",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 17,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-H",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 18,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-I",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
},
new User
{
Id = 19,
IsArchived = false,
Email = "test@example.com",
ResetEmail = "resetEmail@example.com",
UserName = "InsuranceAgent-J",
PasswordHash = "Password",
AccountType = "InsuranceAgent",
CreatedDate = DateTime.Parse("01/01/2015")
});
#endregion
//Build 10 companies || => 7 Verified, 3 Un-Verified
context.Companies.AddOrUpdate(x => x.CompanyID,
#region
//Company 1 || Unverified
new Company
{
CompanyID = 0,
UserID = 0,
IsArchived = false,
Verified = false,
CompanyName = "Joe Schmoes Lead Company",
Address1 = "101 Wonder Way",
Address2 = "Suite: 290",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5553331234",
OtherTelephoneNumber = "5551231234",
EmailAddress = "Joe@leads.com",
SkypeHandle = "LeadCo",
WebsiteURL = "http://www.leadcompany.com",
PictureLogoURL = "https://lh5.ggpht.com/E3EDtjhawNHXNOhnid79xqMofjwy6wIciqHC_-Xe77F9HhPfDOYaJLFTyGBYsDeHvQ=w300",
Bio = "The best lead company ever. Like a pheonix we rise from the ashes.",
LeadNotes = "Our leads are generated by highly trained tele-sales professionals",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "joeLeads@leads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "Maximum transaction amount $675",
VenmoHandle = "JoesLeadsNow",
//Company Rating Depends on ReviewPosts
},
//Company 2 || Unverified
new Company
{
CompanyID = 1,
UserID = 1,
IsArchived = false,
Verified = false,
CompanyName = "All Star Leads Company",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
},
//Company 3 || Unverified
new Company
{
CompanyID = 2,
UserID = 2,
IsArchived = false,
Verified = false,
CompanyName = "Amazing Leads Inc",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
},
//Company 4 || Verified
new Company
{
CompanyID = 3,
UserID = 3,
IsArchived = false,
Verified = true,
CompanyName = "Precision Lead Co.",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
},
//Company 5 || Verified
new Company
{
CompanyID = 4,
UserID = 4,
IsArchived = false,
Verified = true,
CompanyName = "Best Leads Ever.",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
},
//Company 6 || Verified
new Company
{
CompanyID = 5,
UserID = 5,
IsArchived = false,
Verified = true,
CompanyName = "Best Leads Ever.",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
},
//Company 7 || Verified
new Company
{
CompanyID = 6,
UserID = 6,
IsArchived = false,
Verified = true,
CompanyName = "Lead Generation Services",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
},
//Company 8 || Verified
new Company
{
CompanyID = 7,
UserID = 7,
IsArchived = false,
Verified = true,
CompanyName = "SOlD! Leads",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
},
//Company 9 || Verified
new Company
{
CompanyID = 8,
UserID = 8,
IsArchived = false,
Verified = true,
CompanyName = "SouthWest Leads.",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
},
//Company 10 || Verified
new Company
{
CompanyID = 9,
UserID = 9,
IsArchived = false,
Verified = true,
CompanyName = "NorthEast Leads.",
Address1 = "111 Hollwood Blvd",
Address2 = "Suite: 880",
State = "CA",
City = "Los Angeles",
Zip = "90036",
TelephoneNumber = "5556667894",
OtherTelephoneNumber = "5557891234",
EmailAddress = "leads@allstarleads.com",
SkypeHandle = "AllStarLeads",
WebsiteURL = "http://www.AllStarleads.com",
PictureLogoURL = "http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png",
Bio = "All Star Leads Company. Our leads are 5-star!",
LeadNotes = "All of our leads are organic and come with a contact gurantee!",
PaymentNotes = "Please wait 2 days for payment to clear before lead generation begins",
//Payment Area || Stripe?
AcceptsCredit = true,
CreditComments = "We accept Credit",
AcceptsDebit = true,
DebitComments = "We accept Debit",
AcceceptsAmericanExpress = true,
AmericanExpressComments = "We accept American Express",
AcceptsPaypal = true,
PaypalEmailAddress = "leads@allstarleads.com",
PaypalComments = "We accept Paypal",
AcceptsMoneyOrder = true,
MoneyOrderComments = "Please allow 2 weeks for money order to arrive",
AcceptsVenmo = true,
VenmoComments = "We accept Venmo!",
VenmoHandle = "AllStarLeads",
//Company Rating Depends on ReviewPosts
}
#endregion
);
//Build 10 Insurance Agents || => 5 Verified, 5 Un-Verified
context.InsuranceAgents.AddOrUpdate(x => x.InsuranceAgentID,
#region
//InsuranceAgent 1 || Un-Verified
new InsuranceAgent
{
InsuranceAgentID = 0,
UserID = 10,
IsArchived = false,
ProfileName = "BossSales123",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "James",
LastName = "Marsden",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = false,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 2 || Un-Verified
new InsuranceAgent
{
InsuranceAgentID = 1,
UserID = 11,
IsArchived = false,
ProfileName = "Lucky777",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "Greg",
LastName = "Maverson",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = false,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 3 || Un-Verified
new InsuranceAgent
{
InsuranceAgentID = 2,
UserID = 12,
IsArchived = false,
ProfileName = "EliteSales",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "Edward",
LastName = "Cullen",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = false,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 4 || Un-Verified
new InsuranceAgent
{
InsuranceAgentID = 3,
UserID = 13,
IsArchived = false,
ProfileName = "TotallyAwesome",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "Suesan",
LastName = "Thomas",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = false,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 5 || Un-Verified
new InsuranceAgent
{
InsuranceAgentID = 4,
UserID = 14,
IsArchived = false,
ProfileName = "GameOnSales",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "Todd",
LastName = "Mills",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = true,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 6 || Verified
new InsuranceAgent
{
InsuranceAgentID = 5,
UserID = 15,
IsArchived = false,
ProfileName = "SleekSales",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "Steven",
LastName = "Smith",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = true,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 7 || Verified
new InsuranceAgent
{
InsuranceAgentID = 6,
UserID = 16,
IsArchived = false,
ProfileName = "TeleSalesAwesome",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "Kevin",
LastName = "Miller",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = true,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 8 || Verified
new InsuranceAgent
{
InsuranceAgentID = 7,
UserID = 17,
IsArchived = false,
ProfileName = "BrookeSanden123",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "Brooke",
LastName = "Sanden",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = true,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 9 || Verified
new InsuranceAgent
{
InsuranceAgentID = 8,
UserID = 18,
IsArchived = false,
ProfileName = "Jward01",
Territory = "Southern California",
YearsOfExperience = 5,
TypeOfAgent = "Life Insurnace",
FirstName = "Jeff",
LastName = "Ward",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = false,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = true,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
},
//InsuranceAgent 10 || Verified
new InsuranceAgent
{
InsuranceAgentID = 9,
UserID = 19,
IsArchived = false,
ProfileName = "LifeSales",
Territory = "California",
YearsOfExperience = 5,
TypeOfAgent = "Life and Health Insurnace",
FirstName = "Phillip",
LastName = "Knopp",
Bio = "This is a short Bio... Yada Yada Yada",
RecommendedLeadCompanies = "Amazing Leads Co",
TypesOfLeadsUsed = "Telemarketer Leads",
ProfilePictureURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Mr._Smiley_Face.svg/2000px-Mr._Smiley_Face.svg.png",
Gravatar = "YestGravatarUser",
TwitterHandle = "TwitterExampleHandle",
Verified = true,
InsuranceForumsHandle = "InsuranceForumsHandle",
AverageQuanitityOfLeadsTransactiondPerMonth = 100,
AverageQuanitityOfLeadsTransactiondPerWeek = 25,
TelemarketerLeads = true,
TelemarketingLeadNotes = "Telemarketer Leads are the best",
MailLeads = true,
MailLeadLeadNotes = "Mailers are my Bread and Butter",
Press1Leads = true,
Press1LeadNotes = "Great supplement to any week of leads",
InternetLeads = false,
InternetLeadNotes = "Not worth the money",
ColdCallPhoneNumberLists = false,
ColdCallPhoneNumberListLeadNotes = "Just invest Extra for the better leads. Time is money"
}
#endregion
);
//Build Industries || 5 Total
context.Industries.AddOrUpdate(x => x.IndustryID,
#region
new Industry
{
IndustryID = 0,
IsArchived = false,
Description = "Life Insurance"
},
new Industry
{
IndustryID = 1,
IsArchived = false,
Description = "Health Insurance"
},
new Industry
{
IndustryID = 2,
IsArchived = false,
Description = "Property and Casualty Insurance"
},
new Industry
{
IndustryID = 3,
IsArchived = false,
Description = "Medicare Insurance"
},
new Industry
{
IndustryID = 4,
IsArchived = false,
Description = "Annuities"
});
#endregion
//Build CompanyIndustries
context.CompanyIndustries.AddOrUpdate(x => x.CompanyID,
#region
//Company 1 || Life Insurance(0), Health(1), Medicare (3)
new CompanyIndustry
{
IndustryID = 0,
CompanyID = 0,
},
new CompanyIndustry
{
IndustryID = 1,
CompanyID = 0
},
new CompanyIndustry
{
IndustryID = 3,
CompanyID = 0
},
//Company 2 || Life Insurance(0), Health(1), Medicare (3), Annuities(4), P&C(2)
new CompanyIndustry
{
IndustryID = 0,
CompanyID = 1,
},
new CompanyIndustry
{
IndustryID = 1,
CompanyID = 1
},
new CompanyIndustry
{
IndustryID = 3,
CompanyID = 1
},
new CompanyIndustry
{
IndustryID = 4,
CompanyID = 1
},
new CompanyIndustry
{
IndustryID = 2,
CompanyID = 1
},
//Company 3 || Life Insurance(0)
new CompanyIndustry
{
IndustryID = 0,
CompanyID = 2
},
//Company 4 || Life Insurance(0), Health(1), Medicare (3),
new CompanyIndustry
{
IndustryID = 0,
CompanyID = 3
},
new CompanyIndustry
{
IndustryID = 1,
CompanyID = 3
},
new CompanyIndustry
{
IndustryID = 3,
CompanyID = 3
},
//Company 5|| Life Insurance(0), Health(1), Medicare (3),
new CompanyIndustry
{
IndustryID = 0,
CompanyID = 4
},
new CompanyIndustry
{
IndustryID = 1,
CompanyID = 4
},
new CompanyIndustry
{
IndustryID = 3,
CompanyID = 4
},
//Company 6|| Life Insurance(0), Health(1), Medicare (3),Annuities(4)
new CompanyIndustry
{
IndustryID = 0,
CompanyID = 5
},
new CompanyIndustry
{
IndustryID = 1,
CompanyID = 5
},
new CompanyIndustry
{
IndustryID = 3,
CompanyID = 5
},
new CompanyIndustry
{
IndustryID = 4,
CompanyID = 5
},
//Company 7|| Life Insurance(0), Health(1), Medicare (3),Annuities(4)
new CompanyIndustry
{
IndustryID = 0,
CompanyID = 6
},
new CompanyIndustry
{
IndustryID = 1,
CompanyID = 6
},
new CompanyIndustry
{
IndustryID = 3,
CompanyID = 6
},
new CompanyIndustry
{
IndustryID = 4,
CompanyID = 6
},
//Company 8 || P&C(2)
new CompanyIndustry
{
IndustryID = 2,
CompanyID = 7
},
//Company 9|| Life Insurance(0), Health(1), Medicare (3),Annuities(4)
new CompanyIndustry
{
IndustryID = 0,
CompanyID = 8
},
new CompanyIndustry
{
IndustryID = 1,
CompanyID = 8
},
new CompanyIndustry
{
IndustryID = 3,
CompanyID = 8
},
new CompanyIndustry
{
IndustryID = 4,
CompanyID = 8
},
//Company 10 || P&C(2)
new CompanyIndustry
{
IndustryID = 2,
CompanyID = 9
});
#endregion
//Build InsuranceAgentIndustries
context.InsuranceAgentIndustries.AddOrUpdate(x => x.InsuranceAgentID,
#region
//Insurance Agent 1 || Life Insurance(0), Health(1), Medicare (3), Annuities(4), P&C(2)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 0
},
new InsuranceAgentIndustry
{
IndustryID = 1,
InsuranceAgentID = 0
},
new InsuranceAgentIndustry
{
IndustryID = 3,
InsuranceAgentID = 0
},
new InsuranceAgentIndustry
{
IndustryID = 4,
InsuranceAgentID = 0
},
new InsuranceAgentIndustry
{
IndustryID = 2,
InsuranceAgentID = 1
},
//Insurance Agent 2 || LifeInsurance(0)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 1
},
//Insurance Agent 3 || Life Insurance(0), Health(1)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 2
},
new InsuranceAgentIndustry
{
IndustryID = 1,
InsuranceAgentID = 2
},
//Insurance Agent 4 || LifeInsurance(0) , Annuities(4)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 3
},
new InsuranceAgentIndustry
{
IndustryID = 4,
InsuranceAgentID = 3
},
//Insurance Agent 5 || Life Insurance(0), Health(1), Annuities(4)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 4
},
new InsuranceAgentIndustry
{
IndustryID = 1,
InsuranceAgentID = 4
},
new InsuranceAgentIndustry
{
IndustryID = 4,
InsuranceAgentID = 4
},
//Insurance Agent 6 || Life Insurance(0), Health(1), Medicare (3), Annuities(4), P&C(2)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 5
},
new InsuranceAgentIndustry
{
IndustryID = 1,
InsuranceAgentID = 5
},
new InsuranceAgentIndustry
{
IndustryID = 3,
InsuranceAgentID = 5
},
new InsuranceAgentIndustry
{
IndustryID = 4,
InsuranceAgentID = 5
},
new InsuranceAgentIndustry
{
IndustryID = 2,
InsuranceAgentID = 5
},
//Insurance Agent 7 || Life Insurance(0), Health(1), Medicare (3), Annuities(4), P&C(2)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 6
},
new InsuranceAgentIndustry
{
IndustryID = 1,
InsuranceAgentID = 6
},
new InsuranceAgentIndustry
{
IndustryID = 3,
InsuranceAgentID = 6
},
new InsuranceAgentIndustry
{
IndustryID = 4,
InsuranceAgentID = 6
},
new InsuranceAgentIndustry
{
IndustryID = 2,
InsuranceAgentID = 6
},
//Insurance Agent 8 || Life Insurance(0), Health(1), Medicare (3), Annuities(4), P&C(2)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 7
},
new InsuranceAgentIndustry
{
IndustryID = 1,
InsuranceAgentID = 7
},
new InsuranceAgentIndustry
{
IndustryID = 3,
InsuranceAgentID = 7
},
new InsuranceAgentIndustry
{
IndustryID = 4,
InsuranceAgentID = 7
},
new InsuranceAgentIndustry
{
IndustryID = 2,
InsuranceAgentID = 7
},
//Insurance Agent 9 || Annutitues(4)
new InsuranceAgentIndustry
{
IndustryID = 4,
InsuranceAgentID = 8
},
//Insurance Agent 10 || Life Insurance (0), Health(1), Medicare(3), Annutitues(4), P&C(2)
new InsuranceAgentIndustry
{
IndustryID = 0,
InsuranceAgentID = 7
},
new InsuranceAgentIndustry
{
IndustryID = 1,
InsuranceAgentID = 7
},
new InsuranceAgentIndustry
{
IndustryID = 3,
InsuranceAgentID = 7
},
new InsuranceAgentIndustry
{
IndustryID = 4,
InsuranceAgentID = 7
},
new InsuranceAgentIndustry
{
IndustryID = 2,
InsuranceAgentID = 7
});
#endregion
//Build LeadProducts
context.LeadProducts.AddOrUpdate(x => x.LeadProductID,
#region
//Company 1 Lead Products
/*
Telemarketer Product
Mail Lead Product
Press 1 Product
Cold Call List Product
Internet Lead Product
*/
new LeadProduct
{
LeadProductID = 0,
CompanyID = 0,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase",
},
new LeadProduct
{
LeadProductID = 1,
CompanyID = 0,
IsArchived = false,
Price = 14,
ProductNotes = "Price is PER Mail Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 30 days of purchase"
},
new LeadProduct
{
LeadProductID = 2,
CompanyID = 0,
IsArchived = false,
Price = 20,
ProductNotes = "Price is PER Press1 Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 3,
CompanyID = 0,
IsArchived = false,
Price = 5,
ProductNotes = "Price is PER Internet Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 min of purchase"
},
new LeadProduct
{
LeadProductID = 4,
CompanyID = 0,
IsArchived = false,
Price = 5.50,
ProductNotes = "Price is PER individual Name Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 2 Lead Products
/*
Telemarketer Product
Mail Lead Product
Press 1 Product
Cold Call List Product
Internet Lead Product
*/
new LeadProduct
{
LeadProductID = 5,
CompanyID = 1,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 6,
CompanyID = 1,
IsArchived = false,
Price = 14,
ProductNotes = "Price is PER Mail Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 30 days of purchase"
},
new LeadProduct
{
LeadProductID = 7,
CompanyID = 1,
IsArchived = false,
Price = 20,
ProductNotes = "Price is PER Press1 Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 8,
CompanyID = 1,
IsArchived = false,
Price = 5,
ProductNotes = "Price is PER Internet Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 min of purchase"
},
new LeadProduct
{
LeadProductID = 9,
CompanyID = 1,
IsArchived = false,
Price = 5.50,
ProductNotes = "Price is PER individual Name Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 3 Lead Products
/*
Telemarketer Product
Mail Lead Product
Press 1 Product
Cold Call List Product
Internet Lead Product
*/
new LeadProduct
{
LeadProductID = 10,
CompanyID = 2,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 11,
CompanyID = 2,
IsArchived = false,
Price = 14,
ProductNotes = "Price is PER Mail Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 30 days of purchase"
},
new LeadProduct
{
LeadProductID = 12,
CompanyID = 2,
IsArchived = false,
Price = 20,
ProductNotes = "Price is PER Press1 Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 13,
CompanyID = 2,
IsArchived = false,
Price = 5,
ProductNotes = "Price is PER Internet Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 min of purchase"
},
new LeadProduct
{
LeadProductID = 14,
CompanyID = 2,
IsArchived = false,
Price = 5.50,
ProductNotes = "Price is PER individual Name Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 4 Lead Products
/*
Telemarketer Product
Mail Lead Product
Press 1 Product
Cold Call List Product
Internet Lead Product
*/
new LeadProduct
{
LeadProductID = 15,
CompanyID = 3,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 16,
CompanyID = 3,
IsArchived = false,
Price = 14,
ProductNotes = "Price is PER Mail Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 30 days of purchase"
},
new LeadProduct
{
LeadProductID = 17,
CompanyID = 3,
IsArchived = false,
Price = 20,
ProductNotes = "Price is PER Press1 Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 18,
CompanyID = 3,
IsArchived = false,
Price = 5,
ProductNotes = "Price is PER Internet Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 min of purchase"
},
new LeadProduct
{
LeadProductID = 19,
CompanyID = 3,
IsArchived = false,
Price = 5.50,
ProductNotes = "Price is PER individual Name Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 5 Lead Products
/*
Telemarketer Product
Mail Lead Product
Press 1 Product
Cold Call List Product
Internet Lead Product
*/
new LeadProduct
{
LeadProductID = 20,
CompanyID = 4,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 21,
CompanyID = 4,
IsArchived = false,
Price = 14,
ProductNotes = "Price is PER Mail Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 30 days of purchase"
},
new LeadProduct
{
LeadProductID = 22,
CompanyID = 4,
IsArchived = false,
Price = 20,
ProductNotes = "Price is PER Press1 Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 23,
CompanyID = 4,
IsArchived = false,
Price = 5,
ProductNotes = "Price is PER Internet Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 min of purchase"
},
new LeadProduct
{
LeadProductID = 24,
CompanyID = 4,
IsArchived = false,
Price = 5.50,
ProductNotes = "Price is PER individual Name Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 6 Lead Products
/*
Telemarketer Product
Mail Lead Product
Press 1 Product
*/
new LeadProduct
{
LeadProductID = 25,
CompanyID = 5,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 26,
CompanyID = 5,
IsArchived = false,
Price = 14,
ProductNotes = "Price is PER Mail Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 30 days of purchase"
},
new LeadProduct
{
LeadProductID = 27,
CompanyID = 5,
IsArchived = false,
Price = 20,
ProductNotes = "Price is PER Press1 Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 7 Lead Products
/*
Telemarketer Product
Press 1 Product
*/
new LeadProduct
{
LeadProductID = 28,
CompanyID = 6,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 29,
CompanyID = 6,
IsArchived = false,
Price = 20,
ProductNotes = "Price is PER Press1 Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 8 Lead Products
/*
Cold Call List Product
Internet Lead Product
*/
new LeadProduct
{
LeadProductID = 30,
CompanyID = 7,
IsArchived = false,
Price = 5,
ProductNotes = "Price is PER Internet Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 min of purchase"
},
new LeadProduct
{
LeadProductID = 31,
CompanyID = 7,
IsArchived = false,
Price = 5.50,
ProductNotes = "Price is PER individual Name Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 9 Lead Products
/*
Telemarketer Product
Mail Lead Product
Cold Call List Product
Internet Lead Product
*/
new LeadProduct
{
LeadProductID = 32,
CompanyID = 8,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 33,
CompanyID = 8,
IsArchived = false,
Price = 14,
ProductNotes = "Price is PER Mail Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 30 days of purchase"
},
new LeadProduct
{
LeadProductID = 34,
CompanyID = 8,
IsArchived = false,
Price = 5,
ProductNotes = "Price is PER Internet Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 min of purchase"
},
new LeadProduct
{
LeadProductID = 35,
CompanyID = 8,
IsArchived = false,
Price = 5.50,
ProductNotes = "Price is PER individual Name Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
//Company 10 Lead Products
/*
Telemarketer Product
Mail Lead Product
Press 1 Product
*/
new LeadProduct
{
LeadProductID = 36,
CompanyID = 0,
IsArchived = false,
Price = 25,
ProductNotes = "Price is PER Telemarket Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
},
new LeadProduct
{
LeadProductID = 37,
CompanyID = 0,
IsArchived = false,
Price = 14,
ProductNotes = "Price is PER Mail Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 30 days of purchase"
},
new LeadProduct
{
LeadProductID = 38,
CompanyID = 0,
IsArchived = false,
Price = 20,
ProductNotes = "Price is PER Press1 Generated Lead",
OrderLink = "http://www.google.com",
TelemarketingLead = true,
TelemarketingLeadNotes = "Leads will be generated within 10 days of purchase"
});
#endregion
//TODO: Add more Lead Transactions
//Build LeadTransactions
context.LeadTransactions.AddOrUpdate(x => x.LeadTransactionID,
#region
//Insurance Agent 1 Lead Transaction -> Company 1
new LeadTransaction
{
LeadTransactionID = 0,
LeadProductID = 1,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("02/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 1
new LeadTransaction
{
LeadTransactionID = 1,
LeadProductID = 1,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("02/14/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 1
new LeadTransaction
{
LeadTransactionID = 2,
LeadProductID = 1,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("03/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 1
new LeadTransaction
{
LeadTransactionID = 3,
LeadProductID = 1,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("03/14/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 1
new LeadTransaction
{
LeadTransactionID = 4,
LeadProductID = 1,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("04/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 2
new LeadTransaction
{
LeadTransactionID = 5,
LeadProductID = 6,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("04/20/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 2
new LeadTransaction
{
LeadTransactionID = 6,
LeadProductID = 6,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("05/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 2
new LeadTransaction
{
LeadTransactionID = 7,
LeadProductID = 6,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("05/20/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 3
new LeadTransaction
{
LeadTransactionID = 8,
LeadProductID = 11,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("06/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 3
new LeadTransaction
{
LeadTransactionID = 9,
LeadProductID = 11,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("06/20/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 4
new LeadTransaction
{
LeadTransactionID = 10,
LeadProductID = 16,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("07/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 4
new LeadTransaction
{
LeadTransactionID = 11,
LeadProductID = 16,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("07/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 4
new LeadTransaction
{
LeadTransactionID = 12,
LeadProductID = 16,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("07/20/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 5
new LeadTransaction
{
LeadTransactionID = 13,
LeadProductID = 21,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("07/25/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 5
new LeadTransaction
{
LeadTransactionID = 14,
LeadProductID = 21,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("08/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 6
new LeadTransaction
{
LeadTransactionID = 15,
LeadProductID = 26,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("08/20/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 6
new LeadTransaction
{
LeadTransactionID = 16,
LeadProductID = 26,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("08/25/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 6
new LeadTransaction
{
LeadTransactionID = 17,
LeadProductID = 26,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("09/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 10
new LeadTransaction
{
LeadTransactionID = 18,
LeadProductID = 37,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("09/05/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 10
new LeadTransaction
{
LeadTransactionID = 19,
LeadProductID = 37,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("09/20/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 10
new LeadTransaction
{
LeadTransactionID = 20,
LeadProductID = 37,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("10/01/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//Insurance Agent 1 Lead Transaction -> Company 10
new LeadTransaction
{
LeadTransactionID = 21,
LeadProductID = 37,
InsuranceAgentID = 0,
IsArchived = false,
TransactionDate = DateTime.Parse("10/20/2015"),
TransactionPrice = 2100,
TransactionNotes = "150 Mail Leads at $14 each."
},
//----------------------------------------------------
//Insurance Agent 2 Lead Transaction -> Company 1
new LeadTransaction
{
LeadTransactionID = 22,
LeadProductID = 0,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("02/01/2015"),
TransactionPrice = 625,
TransactionNotes = "25 Tele Leads at $25 each."
},
//Insurance Agent 2 Lead Transaction -> Company 1
new LeadTransaction
{
LeadTransactionID = 23,
LeadProductID = 0,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("02/20/2015"),
TransactionPrice = 625,
TransactionNotes = "25 Tele Leads at $25 each."
},
//Insurance Agent 2 Lead Transaction -> Company 1
new LeadTransaction
{
LeadTransactionID = 24,
LeadProductID = 0,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("03/01/2015"),
TransactionPrice = 625,
TransactionNotes = "25 Tele Leads at $25 each."
},
//Insurance Agent 2 Lead Transaction -> Company 7
new LeadTransaction
{
LeadTransactionID = 25,
LeadProductID = 28,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("03/20/2015"),
TransactionPrice = 625,
TransactionNotes = "25 Tele Leads at $25 each."
},
//Insurance Agent 2 Lead Transaction -> Company 7
new LeadTransaction
{
LeadTransactionID = 26,
LeadProductID = 28,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("03/25/2015"),
TransactionPrice = 625,
TransactionNotes = "25 Tele Leads at $25 each."
},
//Insurance Agent 2 Lead Transaction -> Company 7
new LeadTransaction
{
LeadTransactionID = 27,
LeadProductID = 28,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("04/01/2015"),
TransactionPrice = 625,
TransactionNotes = "25 Tele Leads at $25 each."
},
//Insurance Agent 2 Lead Transaction -> Company 7
new LeadTransaction
{
LeadTransactionID = 28,
LeadProductID = 29,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("04/10/2015"),
TransactionPrice = 500,
TransactionNotes = "25 Press1 Leads at $20 each."
},
//Insurance Agent 2 Lead Transaction -> Company 7
new LeadTransaction
{
LeadTransactionID = 29,
LeadProductID = 29,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("04/20/2015"),
TransactionPrice = 500,
TransactionNotes = "25 Press1 Leads at $20 each."
},
//Insurance Agent 2 Lead Transaction -> Company 7
new LeadTransaction
{
LeadTransactionID = 30,
LeadProductID = 29,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("05/01/2015"),
TransactionPrice = 500,
TransactionNotes = "25 Press1 Leads at $20 each."
},
//Insurance Agent 2 Lead Transaction -> Company 7
new LeadTransaction
{
LeadTransactionID = 31,
LeadProductID = 29,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("05/20/2015"),
TransactionPrice = 500,
TransactionNotes = "25 Press1 Leads at $20 each."
},
//Insurance Agent 2 Lead Transaction -> Company 7
new LeadTransaction
{
LeadTransactionID = 29,
LeadProductID = 29,
InsuranceAgentID = 1,
IsArchived = false,
TransactionDate = DateTime.Parse("05/25/2015"),
TransactionPrice = 500,
TransactionNotes = "25 Press1 Leads at $20 each."
});
#endregion
//Build ReviewPosts || LeadProducts have Reviews AND Companies have Reviews
context.ReviewPosts.AddOrUpdate(x => x.ReviewPostID,
#region
//Build Review Posts
new ReviewPost
{ }
//TODO: Build REview posts => then Comments => then run API
);
#endregion
//Build Comments
}
}
}
|
Java
|
UTF-8
| 5,260
| 2.28125
| 2
|
[] |
no_license
|
package com.lmax.api.internal.events;
import java.util.HashMap;
import java.util.Map;
import com.lmax.api.FixedPointNumber;
import com.lmax.api.TimeInForce;
import com.lmax.api.order.Order;
import com.lmax.api.order.OrderType;
public class OrderEventBuilder
{
private String instructionId;
private String originalInstructionId;
private String orderId;
private long instrumentId;
private long accountId;
private FixedPointNumber quantity;
private FixedPointNumber filledQuantity;
private FixedPointNumber price;
private OrderType orderType;
private FixedPointNumber cancelledQuantity;
private FixedPointNumber stopReferencePrice;
private FixedPointNumber stopProfitOffset;
private FixedPointNumber stopLossOffset;
private boolean trailingStopLoss = false;
private FixedPointNumber commission;
private final Map<String, OrderType> orderTypes = new HashMap<>();
private final Map<String, TimeInForce> timeInForceTypes = new HashMap<>();
private TimeInForce timeInForce = TimeInForce.UNKNOWN;
public OrderEventBuilder()
{
orderTypes.put("STOP_COMPOUND_PRICE_LIMIT", OrderType.LIMIT);
orderTypes.put("PRICE_LIMIT", OrderType.LIMIT);
orderTypes.put("STOP_COMPOUND_MARKET", OrderType.MARKET);
orderTypes.put("MARKET_ORDER", OrderType.MARKET);
timeInForceTypes.put("GoodTilCancelled", TimeInForce.GOOD_TIL_CANCELLED);
timeInForceTypes.put("GoodForDay", TimeInForce.GOOD_FOR_DAY);
timeInForceTypes.put("ImmediateOrCancel", TimeInForce.IMMEDIATE_OR_CANCEL);
timeInForceTypes.put("FillOrKill", TimeInForce.FILL_OR_KILL);
}
public Order newInstance()
{
return new OrderImpl(originalInstructionId, instructionId, orderId, instrumentId, accountId, orderType, timeInForce, quantity,
filledQuantity, cancelledQuantity, price, stopReferencePrice, stopLossOffset, trailingStopLoss, stopProfitOffset, commission);
}
public OrderEventBuilder instructionId(final String anInstructionId)
{
instructionId = anInstructionId;
return this;
}
public OrderEventBuilder originalInstructionId(final String anOriginalInstructionId)
{
originalInstructionId = anOriginalInstructionId;
return this;
}
public OrderEventBuilder orderId(final String anOrderId)
{
orderId = anOrderId;
return this;
}
public OrderEventBuilder instrumentId(final long anInstrumentId)
{
this.instrumentId = anInstrumentId;
return this;
}
public OrderEventBuilder accountId(final long anAccountId)
{
this.accountId = anAccountId;
return this;
}
public OrderEventBuilder quantity(final FixedPointNumber aQuantity)
{
quantity = aQuantity;
return this;
}
public OrderEventBuilder filledQuantity(final FixedPointNumber aFilledQuantity)
{
this.filledQuantity = aFilledQuantity;
return this;
}
public OrderEventBuilder price(final FixedPointNumber aPrice)
{
this.price = aPrice;
return this;
}
public OrderEventBuilder orderType(final OrderType anOrderType)
{
this.orderType = anOrderType;
return this;
}
public OrderEventBuilder orderType(final String value)
{
final OrderType anOrderType = orderTypes.get(value);
if(anOrderType != null)
{
this.orderType(anOrderType);
}
else
{
try
{
this.orderType(OrderType.valueOf(value));
}
catch (IllegalArgumentException e)
{
this.orderType(OrderType.UNKNOWN);
}
}
return this;
}
public OrderEventBuilder cancelledQuantity(final FixedPointNumber aCancelledQuantity)
{
this.cancelledQuantity = aCancelledQuantity;
return this;
}
public OrderEventBuilder stopReferencePrice(final FixedPointNumber aStopReferencePrice)
{
stopReferencePrice = aStopReferencePrice;
return this;
}
public OrderEventBuilder stopProfitOffset(final FixedPointNumber aStopProfitOffset)
{
stopProfitOffset = aStopProfitOffset;
return this;
}
public OrderEventBuilder stopLossOffset(final FixedPointNumber aStopLossOffset)
{
stopLossOffset = aStopLossOffset;
return this;
}
public OrderEventBuilder commission(final FixedPointNumber aCommission)
{
commission = aCommission;
return this;
}
public OrderEventBuilder timeInForce(TimeInForce aTimeInForce)
{
this.timeInForce = aTimeInForce;
return this;
}
public OrderEventBuilder trailingStopLoss(final boolean aTrailingStopLoss)
{
this.trailingStopLoss = aTrailingStopLoss;
return this;
}
public void timeInForce(String value)
{
final TimeInForce aTimeInForce = timeInForceTypes.get(value);
if(aTimeInForce != null)
{
this.timeInForce(aTimeInForce);
}
else
{
this.timeInForce(TimeInForce.UNKNOWN);
}
}
}
|
Java
|
UTF-8
| 34,071
| 2.453125
| 2
|
[
"MIT"
] |
permissive
|
package duke.parser;
import duke.command.BackupCommand;
import duke.command.ExitCommand;
import duke.command.ListPriorityCommand;
import duke.command.UndoBudgetCommand;
import duke.command.Command;
import duke.command.SetPriorityCommand;
import duke.command.DeleteCommand;
import duke.command.FilterCommand;
import duke.command.FindTasksByPriorityCommand;
import duke.command.FindTasksByDateCommand;
import duke.command.ListCommand;
import duke.command.DoneCommand;
import duke.command.FindCommand;
import duke.command.AddCommand;
import duke.command.ShowNotesCommand;
import duke.command.AddNotesCommand;
import duke.command.DeleteNotesCommand;
import duke.command.DuplicateFoundCommand;
import duke.command.HelpCommand;
import duke.command.UpdateCommand;
import duke.command.ViewBudgetCommand;
import duke.command.ResetBudgetCommand;
import duke.command.AddContactsCommand;
import duke.command.ListContactsCommand;
import duke.command.DeleteContactCommand;
import duke.command.FindContactCommand;
import duke.command.AddBudgetCommand;
import duke.dukeexception.DukeException;
import duke.enums.ErrorMessages;
import duke.enums.Numbers;
import duke.task.TaskList;
import duke.task.Todo;
import duke.task.Deadline;
import duke.task.Task;
import duke.task.BudgetList;
import duke.task.ContactList;
import duke.task.DetectDuplicate;
import duke.task.FixedDuration;
import duke.task.Contacts;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Represents a parser that breaks down user input into commands.
*/
public class Parser {
private static final String EMPTY_STRING = "";
private static final Logger logr = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
private static DateParser dateParser = new DateParser();
//@@author maxxyx96
/**
* Trims the whitespaces of an input.
*
* @param input input to be trimmed.
* @return Returns the trimmed input.
*/
private static String trim(String input) {
return input.trim();
}
/**
* Checks whether the string input can be split by a set string.
* @param input the input to test if it is splittable.
* @param splitWith the characters to detect splitting.
* @return returns true if it can be split, false otherwise.
*/
private static boolean isSplittable(String input, String splitWith) {
try {
input = input.split(splitWith, 2)[1];
return true;
} catch (Exception e) {
return false;
}
}
/**
* Converts a string amount to look like what a typical monetary amount would look like..
*
* @param stringAmount The amount to be converted.
* @return the converted amount with 2 decimal places.
*/
private static String budgetAmountFormat(String stringAmount) {
DecimalFormat decimalFormat = new DecimalFormat("#.00");
float floatAmount = Float.parseFloat(stringAmount);
return decimalFormat.format(floatAmount);
}
//@@author
//@@author e0318465
private static void checkForEmptyContactDetail(String[] contactDetails) {
if (contactDetails[Numbers.ZERO.value].trim().isEmpty()) {
contactDetails[Numbers.ZERO.value] = "Nil";
}
if (contactDetails[Numbers.ONE.value].trim().isEmpty()) {
contactDetails[Numbers.ONE.value] = "Nil";
}
if (contactDetails[Numbers.TWO.value].trim().isEmpty()) {
contactDetails[Numbers.TWO.value] = "Nil";
}
if (contactDetails[Numbers.THREE.value].trim().isEmpty()) {
contactDetails[Numbers.THREE.value] = "Nil";
}
}
//@@author
/**
* Generates a command based on the user input.
*
* @param sentence User input.
* @param items The task list that contains a list of tasks.
* @param budgetList The list that contains a list of budget.
* @param contactList The list of Contacts.
* @return Command to be executed afterwards.
* @throws Exception If there is an error interpreting the user input.
*/
public static Command parse(String sentence, TaskList items, BudgetList budgetList,
ContactList contactList) throws Exception {
String[] arr = sentence.split(" ");
String taskDesc = "";
String dateDesc = "";
boolean emptyString = arr.length < Numbers.ZERO.value;
boolean getDate = false;
if (sentence.trim().isEmpty()) {
throw new DukeException(ErrorMessages.UNKNOWN_COMMAND.message);
} else if (sentence.contains("|")) {
throw new DukeException(ErrorMessages.AVOID_PIPELINE.message);
} else if (sentence.equals("list")) {
return new ListCommand();
} else if (sentence.equals("priority") || sentence.equals("listpriority") || sentence.equals("lp")) {
return new ListPriorityCommand();
} else if (!emptyString && (arr[Numbers.ZERO.value].equals("done")
|| arr[Numbers.ZERO.value].equals("delete"))) {
if (arr.length == Numbers.ONE.value) {
throw new DukeException(ErrorMessages.TASKNUM_IS_EMPTY.message);
} else {
int tasknum;
try {
tasknum = Integer.parseInt(arr[Numbers.ONE.value]) - Numbers.ONE.value;
} catch (NumberFormatException e) {
logr.log(Level.WARNING,ErrorMessages.TASKNUM_MUST_BE_INT.message);
throw new DukeException(ErrorMessages.TASKNUM_MUST_BE_INT.message);
}
if (tasknum < Numbers.ZERO.value || tasknum >= items.size()) {
throw new DukeException(ErrorMessages.TASKNUM_INVALID_INT.message);
} else {
if (arr[Numbers.ZERO.value].equals("done")) {
if (items.get(tasknum).isDone()) {
throw new DukeException(" (>_<) OOPS!! This task has been marked as done!");
}
return new DoneCommand(tasknum);
} else {
return new DeleteCommand(tasknum);
}
}
} //@@author talesrune
} else if (!emptyString && arr[Numbers.ZERO.value].equals("find")) {
if (arr.length == Numbers.ONE.value) {
throw new DukeException(ErrorMessages.KEYWORD_IS_EMPTY.message);
} else {
if (arr[Numbers.ONE.value].trim().isEmpty()) {
throw new DukeException(ErrorMessages.KEYWORD_IS_EMPTY.message);
} else {
String keyword = EMPTY_STRING;
for (int i = Numbers.ONE.value; i < arr.length; i++) {
keyword += arr[i] + " ";
}
return new FindCommand(keyword.trim());
}
}
} else if (!emptyString && arr[Numbers.ZERO.value].equals("filter")) {
if (arr.length == Numbers.ONE.value) {
throw new DukeException(ErrorMessages.TASKTYPE_IS_EMPTY.message);
} else {
if (arr[Numbers.ONE.value].trim().isEmpty()) {
throw new DukeException(ErrorMessages.TASKTYPE_IS_EMPTY.message);
} else {
return new FilterCommand(arr[Numbers.ONE.value]);
}
}
} else if (!emptyString && arr[Numbers.ZERO.value].equals("notes")) {
if (arr.length == Numbers.ONE.value) {
throw new DukeException(ErrorMessages.TASKNUM_IS_EMPTY.message);
} else {
int tasknum;
try {
tasknum = Integer.parseInt(arr[Numbers.ONE.value]) - Numbers.ONE.value;
} catch (NumberFormatException e) {
logr.log(Level.WARNING,ErrorMessages.TASKNUM_MUST_BE_INT.message);
throw new DukeException(ErrorMessages.TASKNUM_MUST_BE_INT.message);
}
if (tasknum < Numbers.ZERO.value || tasknum >= items.size()) {
throw new DukeException(ErrorMessages.TASKNUM_INVALID_INT.message);
} else if (arr.length < Numbers.THREE.value) {
throw new DukeException(" (>_<) OOPS!!! Insufficient parameters. "
+ "Format: notes <tasknum> <type> <notes description>");
} else {
int typeOfNotes = Numbers.MINUS_ONE.value;
String notesDesc = "";
for (int i = Numbers.TWO.value; i < arr.length; i++) {
if (i == Numbers.TWO.value) {
if (arr[i].trim().isEmpty()
|| (!arr[i].equals("/add") && !arr[i].equals("/delete")
&& !arr[i].equals("/show"))) {
throw new DukeException(" (>_<) OOPS!!! Unable to find either "
+ "/add, /delete, or /show.");
} else {
if (arr[i].equals("/add")) {
typeOfNotes = Numbers.ONE.value;
} else if (arr[i].equals("/delete")) {
typeOfNotes = Numbers.TWO.value;
break;
} else {
typeOfNotes = Numbers.THREE.value;
break;
}
}
} else {
notesDesc += arr[i] + " ";
}
}
notesDesc = notesDesc.trim();
if (typeOfNotes == Numbers.THREE.value) {
return new ShowNotesCommand(tasknum);
} else if (typeOfNotes == Numbers.TWO.value) {
if (items.get(tasknum).getNotes().equals("empty")) {
throw new DukeException(" (>_<) OOPS!!! The notes description of "
+ items.get(tasknum).toString() + " is already empty!");
}
return new DeleteNotesCommand(tasknum);
} else if (typeOfNotes == Numbers.ONE.value && notesDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The notes description of "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (typeOfNotes != Numbers.MINUS_ONE.value) {
return new AddNotesCommand(notesDesc,tasknum);
} else {
throw new DukeException(" (>_<) OOPS!!! There is something wrong "
+ " when trying to add notes");
}
}
} //@@author
} else if (!emptyString && arr[Numbers.ZERO.value].equals("todo")) {
String[] getDescription = sentence.split(" ", Numbers.TWO.value);
DetectDuplicate detectDuplicate = new DetectDuplicate(items);
for (int i = Numbers.ONE.value; i < arr.length; i++) {
taskDesc += arr[i] + " ";
}
taskDesc = taskDesc.trim();
if (taskDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of a "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (detectDuplicate.isDuplicate(getDescription[Numbers.ONE.value])) {
return new DuplicateFoundCommand();
} else {
Task taskObj = new Todo(taskDesc);
return new AddCommand(taskObj);
}
} else if (!emptyString && (arr[Numbers.ZERO.value].equals("deadline")
|| arr[Numbers.ZERO.value].equals("dl"))) {
for (int i = Numbers.ONE.value; i < arr.length; i++) {
if ((arr[i].trim().isEmpty()
|| !arr[i].equals("/by")) && !getDate) {
taskDesc += arr[i] + " ";
} else {
if (!getDate) {
getDate = true;
} else {
dateDesc += arr[i] + " ";
}
}
}
taskDesc = taskDesc.trim();
dateDesc = dateDesc.trim();
DetectDuplicate detectDuplicate = new DetectDuplicate(items);
if (taskDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of a "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (dateDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! Ensure that you have /by before writing date/time."
+ " The description of date/time for "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (detectDuplicate.isDuplicate(taskDesc)) {
return new DuplicateFoundCommand();
} else {
dateParser.isValidDateTime(dateDesc);
Task taskObj;
taskObj = new Deadline(taskDesc, dateDesc);
for (int i = Numbers.ZERO.value; i < items.size(); i++) {
if (taskObj.getDateTime().equals(items.get(i).getDateTime()) && !items.get(i).isDone()) {
throw new DukeException(" (>_<) OOPS!!! The date/time for "
+ arr[Numbers.ZERO.value] + " clashes with " + items.get(i).toString()
+ "\n Please choose another date/time! Or mark the above task as Done first!");
}
}
return new AddCommand(taskObj);
}
//@@author Dou-Maokang
} else if (!emptyString
&& (arr[Numbers.ZERO.value].equals("fixedduration") || arr[Numbers.ZERO.value].equals("fd"))) {
String description = "";
int duration;
String unit;
for (int i = Numbers.ONE.value; i < arr.length; i++) {
description += arr[i] + " ";
}
if (description.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of a "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
}
String[] descarr = description.split(" /for ");
if (descarr.length < 2) {
throw new DukeException(" (>_<) OOPS!!! The duration description of a "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
}
taskDesc = description.split(" /for ")[Numbers.ZERO.value].trim();
String durDesc = description.split(" /for ")[Numbers.ONE.value].trim();
DetectDuplicate detectDuplicate = new DetectDuplicate(items);
if (taskDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of a "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (durDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of duration for "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (detectDuplicate.isDuplicate(taskDesc)) {
return new DuplicateFoundCommand();
} else {
try {
duration = Integer.parseInt(durDesc.split(" ")[Numbers.ZERO.value].trim());
} catch (Exception e) {
logr.log(Level.WARNING, ErrorMessages.FIXEDDURATION_FORMAT.message);
throw new DukeException(ErrorMessages.FIXEDDURATION_FORMAT.message);
}
String[] durationarr = durDesc.split(" ");
if (durationarr.length < 2) {
throw new DukeException(" (>_<) OOPS!!! The unit of a "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
}
unit = durDesc.split(" ")[Numbers.ONE.value].trim();
if (unit.isEmpty() || (!unit.toLowerCase().contains("min") && !unit.toLowerCase().contains("h"))) {
throw new DukeException(ErrorMessages.FIXEDDURATION_FORMAT.message);
} else if ((!unit.toLowerCase().equals("minute"))
&& (!unit.toLowerCase().equals("minutes"))
&& (!unit.toLowerCase().equals("hour"))
&& (!unit.toLowerCase().equals("hours"))) {
throw new DukeException(" (>_<) OOPS!!! <unit> can only be minute(s) or hour(s)!");
} else {
if (unit.equals("min") || unit.equals("minutes")) {
unit = (duration > Numbers.ONE.value) ? "minutes" : "minute";
} else if (unit.contains("h")) {
unit = (duration > Numbers.ONE.value) ? "hours" : "hour";
}
FixedDuration fixedDuration = new FixedDuration(taskDesc, duration, unit);
return new AddCommand(fixedDuration);
}
}
} else if (!emptyString
&& (arr[Numbers.ZERO.value].equals("setpriority") || arr[Numbers.ZERO.value].equals("sp"))) {
String description = "";
int taskNum;
int priority;
for (int i = Numbers.ONE.value; i < arr.length; i++) {
description += arr[i] + " ";
}
String[] holder = description.split(" ");
if (holder.length < Numbers.TWO.value) {
throw new DukeException(ErrorMessages.PRIORITY_FORMAT.message);
} else {
try {
taskNum = Integer.parseInt(holder[Numbers.ZERO.value].trim());
} catch (Exception e) {
logr.log(Level.WARNING,ErrorMessages.TASKNUM_MUST_BE_INT.message);
throw new DukeException(ErrorMessages.TASKNUM_MUST_BE_INT.message);
}
if (taskNum <= Numbers.ZERO.value || taskNum > items.size()) {
throw new DukeException(ErrorMessages.TASKNUM_INVALID_INT.message);
}
try {
priority = Integer.parseInt(holder[Numbers.ONE.value].trim());
} catch (Exception e) {
logr.log(Level.WARNING,"The priority must be an integer");
throw new DukeException("The priority must be an integer");
}
if (!((priority > Numbers.ZERO.value) && (priority < Numbers.SIX.value))) {
throw new DukeException(" (>_<) OOPS!!! Invalid priority! (1 - High ~ 5 - Low).");
}
return new SetPriorityCommand(taskNum, priority);
}
} else if (!emptyString
&& (arr[Numbers.ZERO.value].equals("findpriority") || arr[Numbers.ZERO.value].equals("fp"))) {
if (arr.length == Numbers.ONE.value) {
throw new DukeException(" (>_<) OOPS!!! The target priority cannot be empty.");
} else {
int target;
if (arr[Numbers.ONE.value].trim().isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The target priority cannot be empty.");
} else {
try {
target = Integer.parseInt(arr[Numbers.ONE.value]);
} catch (Exception e) {
logr.log(Level.WARNING,"The target priority must be an integer");
throw new DukeException("The target priority must be an integer");
}
if (!((target > Numbers.ZERO.value) && (target < Numbers.SIX.value))) {
throw new DukeException(" (>_<) OOPS!!! Invalid target priority! (1 ~ 5).");
}
return new FindTasksByPriorityCommand(target);
}
}
} else if (!emptyString && arr[Numbers.ZERO.value].equals("finddate")) {
SimpleDateFormat datetimeFormat = new SimpleDateFormat("dd/MM/yyyy");
int sufIndex = Numbers.MINUS_ONE.value;
String description = "";
for (int i = Numbers.ONE.value; i < arr.length; i++) {
description += arr[i] + " ";
}
if (!description.contains("/on")) {
throw new DukeException(" (>_<) OOPS!!! The format for finddate is 'finddate /on <dd/mm/yyyy>'");
}
String[] holder = description.split("/on");
if (holder.length == 1) {
throw new DukeException(" (>_<) OOPS!!! The description of date/time for "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
}
dateDesc = description.split("/on")[Numbers.ONE.value].trim();
if (dateDesc.trim().isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of date/time for "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
}
dateParser.isValidDate(dateDesc);
Date date;
try {
date = datetimeFormat.parse(dateDesc);
} catch (Exception e) {
logr.log(Level.WARNING, ErrorMessages.DATE_FORMAT.message, e);
throw new DukeException(ErrorMessages.DATE_FORMAT.message);
}
int day = Integer.parseInt(new SimpleDateFormat("d").format(date));
if (day % 10 == Numbers.ONE.value) {
sufIndex = Numbers.ZERO.value;
} else if (day % 10 == Numbers.TWO.value) {
sufIndex = Numbers.ONE.value;
} else if (day % 10 == Numbers.THREE.value) {
sufIndex = Numbers.TWO.value;
} else if (day > Numbers.THREE.value && day < Numbers.THIRTY_ONE.value) {
sufIndex = Numbers.THREE.value;
}
String[] suf = { "st", "nd", "rd", "th" };
String suffixStr = day + suf[sufIndex];
SimpleDateFormat datetimeFormat2 = new SimpleDateFormat("MMMMM yyyy");
String displayDT = datetimeFormat2.format(date);
displayDT = suffixStr + " of " + displayDT;
return new FindTasksByDateCommand(displayDT);
//@@author talesrune
} else if (!emptyString && (arr[Numbers.ZERO.value].equals("update"))) {
if (arr.length == Numbers.ONE.value) {
throw new DukeException(ErrorMessages.TASKNUM_IS_EMPTY.message);
} else {
int tasknum = Integer.parseInt(arr[Numbers.ONE.value]) - Numbers.ONE.value;
if (tasknum < Numbers.ZERO.value || tasknum >= items.size()) {
throw new DukeException(ErrorMessages.TASKNUM_INVALID_INT.message);
} else if (arr.length < Numbers.FOUR.value) {
throw new DukeException(" (>_<) OOPS!!! Insufficient parameters. "
+ "Format: update <tasknum> <type> <desc or date>");
} else {
int typeOfUpdate = Numbers.MINUS_ONE.value;
String typeDesc = "";
for (int i = Numbers.TWO.value; i < arr.length; i++) {
if (i == Numbers.TWO.value) {
if (arr[i].trim().isEmpty()
|| (!arr[i].equals("/desc")
&& !arr[i].equals("/date")
&& !arr[i].equals("/type"))) {
throw new DukeException(" (>_<) OOPS!!! Unable to find either "
+ "/date, /desc, or /type.");
} else {
if (arr[i].equals("/desc")) {
typeOfUpdate = Numbers.ONE.value;
} else if (arr[i].equals("/date")) {
typeOfUpdate = Numbers.TWO.value;
} else {
typeOfUpdate = Numbers.THREE.value;
}
}
} else {
if (typeOfUpdate == Numbers.ONE.value) {
taskDesc += arr[i] + " ";
} else if (typeOfUpdate == Numbers.TWO.value) {
dateDesc += arr[i] + " ";
} else {
typeDesc += arr[i] + " ";
}
}
}
taskDesc = taskDesc.trim();
dateDesc = dateDesc.trim();
typeDesc = typeDesc.trim();
DetectDuplicate detectDuplicate = new DetectDuplicate(items);
if (typeOfUpdate == Numbers.ONE.value && taskDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of a "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (typeOfUpdate == Numbers.TWO.value && dateDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of date/time for "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (typeOfUpdate == Numbers.THREE.value && typeDesc.isEmpty()) {
throw new DukeException(" (>_<) OOPS!!! The description of type for "
+ arr[Numbers.ZERO.value] + " cannot be empty.");
} else if (detectDuplicate.isDuplicate(taskDesc)) {
return new DuplicateFoundCommand();
} else if (typeOfUpdate != Numbers.MINUS_ONE.value) {
for (int i = Numbers.ZERO.value; i < items.size(); i++) {
if (dateDesc.equals(items.get(i).getDateTime()) && !items.get(i).isDone()) {
throw new DukeException(" (>_<) OOPS!!! The date/time for "
+ arr[Numbers.ZERO.value] + " clashes with " + items.get(i).toString()
+ "\n Please choose another date/time! "
+ "Or mark the above task as Done first!");
}
}
if (typeOfUpdate == Numbers.TWO.value) {
dateParser.isValidDateTime(dateDesc);
}
return new UpdateCommand(taskDesc, dateDesc, typeDesc, typeOfUpdate, tasknum);
} else {
throw new DukeException(" (>_<) OOPS!!! There is something wrong "
+ " when trying to update");
}
}
} //@@author e0318465
} else if (!emptyString
&& (arr[Numbers.ZERO.value].equals("addcontact") || arr[Numbers.ZERO.value].equals("ac")
|| arr[Numbers.ZERO.value].equals("addcontacts"))) {
try {
String[] userInput = sentence.split(" ",Numbers.TWO.value);
String[] contactDetails = userInput[Numbers.ONE.value].split(",");
checkForEmptyContactDetail(contactDetails);
if (!contactDetails[Numbers.TWO.value].contains("@")
&& !contactDetails[Numbers.TWO.value].contains("Nil")) {
throw new DukeException(ErrorMessages.CONTACT_FORMAT.message);
}
Contacts contactObj = new Contacts(contactDetails[Numbers.ZERO.value],
contactDetails[Numbers.ONE.value],
contactDetails[Numbers.TWO.value], contactDetails[Numbers.THREE.value]);
return new AddContactsCommand(contactObj, contactList);
} catch (Exception e) {
logr.log(Level.WARNING, ErrorMessages.CONTACT_FORMAT.message, e);
throw new DukeException(ErrorMessages.CONTACT_FORMAT.message);
}
} else if (sentence.equals("listcontact") || sentence.equals("lc") || sentence.equals(("listcontacts"))) {
return new ListContactsCommand(contactList);
} else if (!emptyString
&& (arr[Numbers.ZERO.value].equals("deletecontact") || arr[Numbers.ZERO.value].equals("dc")
|| arr[Numbers.ZERO.value].equals("deletecontacts"))) {
try {
if (arr.length == Numbers.ONE.value) {
throw new DukeException(ErrorMessages.CONTACT_INDEX.message);
}
return new DeleteContactCommand(Integer.parseInt(arr[Numbers.ONE.value]), contactList);
} catch (NumberFormatException e) {
throw new DukeException(ErrorMessages.NON_INTEGER_ALERT.message);
}
} else if (!emptyString
&& (arr[Numbers.ZERO.value].equals("findcontact") || arr[Numbers.ZERO.value].equalsIgnoreCase("fc")
|| arr[Numbers.ZERO.value].equals("findcontacts"))) {
String[] keyword = sentence.split(" ", Numbers.TWO.value);
if (arr.length == Numbers.ONE.value || keyword[Numbers.ONE.value].trim().isEmpty()
|| keyword[Numbers.ONE.value].trim().equals(",")) {
throw new DukeException(ErrorMessages.KEYWORD_IS_EMPTY.message);
} else {
return new FindContactCommand(keyword[Numbers.ONE.value].toLowerCase(), contactList);
}
//@@author
} else if (!emptyString && arr[Numbers.ZERO.value].equals("budget")) { //@@author maxxyx96
try {
String budgetCommandString = sentence.split(" ", Numbers.TWO.value)[Numbers.ONE.value];
} catch (Exception e) {
throw new DukeException(" (>_<) OoPS!!! Invalid Budget Command. "
+ "\nIt should be: budget <new/add/minus/reset/view> <amount> ");
}
String budgetCommandString = sentence.split(" ", Numbers.TWO.value)[Numbers.ONE.value];
budgetCommandString = trim(budgetCommandString);
String budgetCommand = budgetCommandString.split(" ", Numbers.TWO.value)[Numbers.ZERO.value];
budgetCommand = trim(budgetCommand);
if (budgetCommand.equals("view") || budgetCommand.equals("list")) {
return new ViewBudgetCommand(budgetList);
} else if (budgetCommand.equals("undo")) {
return new UndoBudgetCommand(budgetList);
} else {
try {
String budgetRemark = EMPTY_STRING;
String budgetAmount = budgetCommandString.split(" ", Numbers.TWO.value)[Numbers.ONE.value];
if (isSplittable(budgetAmount, " ")) {
budgetRemark = budgetAmount.split(" ", Numbers.TWO.value)[Numbers.ONE.value];
budgetAmount = budgetAmount.split(" ")[Numbers.ZERO.value];
}
budgetAmount = budgetAmountFormat(budgetAmount);
if (budgetCommand.equals("new") || budgetCommand.equals("reset")) {
return new ResetBudgetCommand(budgetList, Float.parseFloat(budgetAmount));
} else if (Float.parseFloat(budgetAmount) == 0) {
throw new DukeException(" (>_<) OoPS!!! You cant add/subtract an empty amount!");
} else if (budgetCommand.equals("add") || budgetCommand.equals("+")) {
return new AddBudgetCommand(budgetList, Float.parseFloat(budgetAmount), budgetRemark);
} else if (budgetCommand.equals("minus") || budgetCommand.equals("-")) {
return new AddBudgetCommand(budgetList, -Float.parseFloat(budgetAmount), budgetRemark);
} else {
throw new DukeException(" (>_<) OoPS!!! Invalid Budget Command. "
+ "\n It should be more like: "
+ "\n budget <cmd> <amount> <desc(Optional)>"
+ "\n ,where cmd can be add/minus/view/reset. ");
}
} catch (Exception p) {
throw new DukeException(" (>_<) OoPS!!! Invalid Budget Command. "
+ "\n It should be more like: "
+ "\n budget <cmd> <amount> <desc(Optional)>"
+ "\n ,where cmd can be add/minus/view/reset. ");
}
} //@@author
} else if (sentence.equals("backup")) {
return new BackupCommand(); //@@author
} else if (sentence.equals("bye") || sentence.equals("exit")) {
return new ExitCommand();
//@@author gervaiseang
} else if (sentence.equals("help")) {
return new HelpCommand();
} else {
throw new DukeException(ErrorMessages.UNKNOWN_COMMAND.message);
}
}
}
|
JavaScript
|
UTF-8
| 1,486
| 2.578125
| 3
|
[] |
no_license
|
var fs = require("fs");
var path = require("path");
var utilities = require("./utilities");
var logger = require("console");
const ONE_REQUIRED_GRADLE_VERSION = "6.7.1";
const GRADLE_DISTRIBUTION_URL = "https\\://services.gradle.org/distributions/gradle-" + ONE_REQUIRED_GRADLE_VERSION + "-all.zip";
function bumpGradleWrapperDistribUrl(url) {
logger.log("One Plugin: bumping gradle version to the required %s...", ONE_REQUIRED_GRADLE_VERSION);
process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'] = url;
}
function checkMinGradleVersionSatisfied(url) {
const versionStr = /gradle-(.+)-all/g.exec(url)[1];
logger.log("One Plugin: %s version of the gradle wrapper is used", versionStr);
return Number(versionStr) >= ONE_REQUIRED_GRADLE_VERSION;
}
module.exports = {
checkGradleDistributionVersionAndBumpIdNeeded: function () {
// cordova looks for CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL environment variable to check whether user specified gradle version or not
// we do the same: if version was specified and satisfies our needs we keep it or set required version otherwise
var userDistribUrl = process.env['CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL'];
if (userDistribUrl) {
// if version is ok, return without doing anything
if (checkMinGradleVersionSatisfied(userDistribUrl)) {
return;
}
}
bumpGradleWrapperDistribUrl(GRADLE_DISTRIBUTION_URL);
}
};
|
JavaScript
|
UTF-8
| 519
| 3.96875
| 4
|
[] |
no_license
|
const todos = ['Go home', 'Pray', 'Sleep', 'Code', 'Watch movies']
// console.log(todos[todos.length - 1], todos[todos.length - 2])
console.log(todos)
// Delete the 3rd item
todos.splice(2, 1)
// Add a new item unto the end
todos.push('Call your girlfriend')
// Remove the first item from the list
todos.shift()
// console.log(todos)
todos.forEach(function(todo, index) {
console.log(index + 1 + '.', todo)
})
for (let count = 0; count < todos.length; count++) {
console.log(`${count+1}. ${todos[count]}`)
}
|
TypeScript
|
UTF-8
| 630
| 2.71875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import {
_GPSCoordinates,
_UnmarshalledGPSCoordinates
} from "./_GPSCoordinates";
/**
* <p>Specifies GPS-based criteria for including or excluding endpoints from a segment.</p>
*/
export interface _GPSPointDimension {
/**
* <p>The GPS coordinates to measure distance from.</p>
*/
Coordinates: _GPSCoordinates;
/**
* <p>The range, in kilometers, from the GPS coordinates.</p>
*/
RangeInKilometers?: number;
}
export interface _UnmarshalledGPSPointDimension extends _GPSPointDimension {
/**
* <p>The GPS coordinates to measure distance from.</p>
*/
Coordinates: _UnmarshalledGPSCoordinates;
}
|
Java
|
UTF-8
| 718
| 3.21875
| 3
|
[] |
no_license
|
package DayEleven;
public class WareHouse {
private int countOrder;
private double balance;
public WareHouse(int countOrder, double balance) {
this.countOrder = countOrder;
this.balance = balance;
}
public int getCountOrder() {
return countOrder;
}
public void increaseCountOrder() {
this.countOrder++;
}
public double getBalance() {
return balance;
}
public void increaseBalance() {
this.balance += 1000;
}
@Override
public String toString() {
return "WareHouse info " +
"количество заказов = " + countOrder +
", баланс = " + balance;
}
}
|
Shell
|
UTF-8
| 1,083
| 3.125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/sh
# Copyright 2017 Google Inc. All rights reserved.
# Modifications copyright 2019 Erik Maciejewski
#
# 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.
set -e
# concat all the certs.
CERT_FILE=./etc/ssl/certs/ca-certificates.crt
mkdir -p $(dirname $CERT_FILE)
CERTS=$(find usr/share/ca-certificates -type f | sort)
for cert in $CERTS; do
cat $cert >> $CERT_FILE
done
# discard all in usr/ except copyright (will preserve copyright path, since
# non-empty dirs will error when attempting to delete, and hence the || true)
find usr/ -not -name 'copyright' -delete >/dev/null 2>&1 || true
|
Java
|
UTF-8
| 1,032
| 2.21875
| 2
|
[] |
no_license
|
package com.technicalinterview.ldaprestapi.service;
import com.technicalinterview.ldaprestapi.domain.User;
import com.technicalinterview.ldaprestapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserRepository userRepository;
@Override
public List<User> getAllUsers() {
return userRepository.getAll();
}
@Override
public User getUser(String userId) {
return userRepository.getOne(userId);
}
@Override
public User create(User user) {
return userRepository.create(user);
}
@Override
public User update(User user) {
return userRepository.update(user);
}
@Override
public User remove(String userId) {
return userRepository.remove(userId);
}
@Override
public void removeAll() {
userRepository.removeAll();
}
}
|
Java
|
UTF-8
| 402
| 2.125
| 2
|
[] |
no_license
|
package bupt.lth;
import bupt.lth.SpringTextField;
//Spring界面皮肤工厂:具体工厂
public class SpringSkinFactory implements ISkinFactory {
public IButton createButton() {
return new SpringButton();
}
public ITextField createTextField() {
return new SpringTextField();
}
public IComboBox createComboBox() {
return new SpringComboBox();
}
}
|
PHP
|
UTF-8
| 544
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
<?php namespace AdventureTimeBundle\Model;
use AdventureTimeBundle\Constants;
use Symfony\Component\Finder\Exception\AccessDeniedException;
class PersonageModel
{
protected $em;
public function __construct($em)
{
$this->em = $em;
}
public function getPersonages()
{
return $this->em->getRepository('AdventureTimeBundle:Personage')->findAll();
}
public function getPersonageById($id)
{
return $this->em->getRepository('AdventureTimeBundle:Personage')->findOneById($id);
}
}
|
Python
|
UTF-8
| 3,119
| 2.65625
| 3
|
[] |
no_license
|
from numpy import *
def loadDataSetFile(fileName):
dataMat = []
f = open(fileName)
for line in f.readlines():
curLine = line.strip().split(',')
proj_lonlats_string = [curLine[1],curLine[2]]
proj_lonlats = map(float, proj_lonlats_string)
dataMat.append(proj_lonlats)
return dataMat
def distEclud_lonlats(A_lonlats, B_lonlats):
A_lonlat = A_lonlats.tolist()[0]
B_lonlat = B_lonlats.tolist()[0]
dlat = 111.0 * abs(A_lonlat[1] - B_lonlat[1])
dlon = 111.0 * abs(math.cos(math.radians((A_lonlat[1] + B_lonlat[1])/2)))*abs(A_lonlat[0]-B_lonlat[0])
return math.sqrt(dlat**2 + dlon**2)
def randCent(dataSet, k):
n = shape(dataSet)[1]
centroids = mat(zeros((k, n)))#create centroid mat
for j in range(n):
minJ = min(dataSet[:,j])
rangeJ = float(max(dataSet[:,j]) - minJ)
centroids[:, j] = minJ + rangeJ * random.rand(k, 1)
return centroids
def kMeans(dataSet, k, distMeans=distEclud_lonlats, createCent = randCent):
m = shape(dataSet)[0] #jilu de tiao shu
# first column stores which cluster this sample belongs to,
# second column stores the error between this sample and its centroid
clusterAssment = mat(zeros((m, 2)))
## step 1: init centroids
centroids = createCent(dataSet, k)
print "Initial centroid: "
print centroids
clusterChanged = True
count = 1
while clusterChanged:
print "iterating " + str(count) + " times"
clusterChanged = False
for i in range(m):
#set thi min distance
minDist = 10000000000000000
minIndex = 0
# step 2: find the centroid who is closest
for j in range(k):
distJI = distMeans(centroids[j,:], dataSet[i,:])
if distJI < minDist:
minDist = distJI
minIndex = j
# step 3: update its cluster
if clusterAssment[i,0] != minIndex:
clusterChanged = True
clusterAssment[i,:] = minIndex,0#minDist**2
## step 4: update centroids
for cent in range(k):
ptsInClust = dataSet[nonzero(clusterAssment[:,0].A==cent)[0]]
centroids[cent,:] = mean(ptsInClust, axis=0)
count = count + 1
return centroids, clusterAssment
pickup_file_dir = 'D:/Data/Tmp/'
pickup_filename = '04.txt'
datMat = mat(loadDataSetFile(pickup_file_dir + pickup_filename))
print 'begin k-means clustering'
Centroids, clustAssing = kMeans(datMat,20)
print 'finish k-means clustering'
datMat_list = datMat.tolist()
Centroids_list = Centroids.tolist()
clustAssing_list = clustAssing.tolist()
filename_suffix = pickup_filename.split('_')[1] + '_' + pickup_filename.split('_')[2].split('.')[0]
centroid_f = open(pickup_file_dir + 'centroids' + '.txt','w')
for centroid in Centroids_list:
centroid_f.write(str(centroid[0]) + ',' + str(centroid[1]) + '\n')
cluster_f = open(pickup_file_dir + 'pickup_cluster_' + filename_suffix + '.txt','w')
centroids_number = len(Centroids_list)
centroid_number = 0
while centroid_number < centroids_number:
print 'centroid_number:',centroid_number
for i in range(len(clustAssing_list)):
if int(clustAssing_list[i][0]) == centroid_number:
cluster_f.write(str(centroid_number) + ',' + str(datMat_list[i][0]) + ',' + str(datMat_list[i][1]) + '\n')
centroid_number = centroid_number + 1
|
Java
|
UTF-8
| 927
| 3.921875
| 4
|
[] |
no_license
|
import java.util.ArrayList;
public class ArrayGenericListEx {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*The problem with above ArrayList is we want only strings to be in the list, but we can add other than strings also like below
ArrayList names = new ArrayList();
names.add("sai");
names.add("ram");
names.add("krishna");
names.add(10); // addding numbers
names.add(12.2); // adding decimals
names.add(true); // adding booleans */
// Generic ArrayList will solve the problem where we can put only certain things like below
ArrayList<String> names = new ArrayList<String>();
names.add("soujanya");
names.add("Konduru");
names.add("Venkata");
for(int i=0; i<names.size();i++)
{
System.out.println("Names: "+names.get(i));
}
for( String name : names)
{
System.out.println("Name: " +name);
}
}
}
|
PHP
|
UTF-8
| 708
| 2.765625
| 3
|
[] |
no_license
|
<?php
$conn = new mysqli('localhost', 'root', '', 'proyecto');
// Check connection
if ($conn->connect_error) {
die("Database Connection failed: " . $conn->connect_error);
}
date_default_timezone_set('America/Mexico_City');
$d = date("Y-m-d");
$t = date("H:i:s");
if(!empty($_GET['tarjeta']) && !empty($_GET['val']))
{
$tarjeta = $_GET['tarjeta'];
$val = $_GET['val'];
$sql = "INSERT INTO entrada(Fecha, Id_Tarjeta, id_corto) VALUES ('".$d." ".$t."','".$tarjeta."','".$val."')";
if (mysqli_query($conn, $sql)) {
echo "OK";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
|
JavaScript
|
UTF-8
| 7,290
| 2.5625
| 3
|
[] |
no_license
|
var express = require('express');
var router = express.Router();
var pg = require('pg');
var path = require('path');
var connectionString = require(path.join(__dirname, '../', 'config'));
module.exports = router;
router.post('/api/v1/upload', function(req, res) {
if (!req.files)
return res.status(400).send('No files were uploaded.');
let sampleFile = req.files[Object.keys(req.files)[0]];
var csv = require('csv-parser');
var fs = require('fs');
var resp=[];
// Use the mv() method to place the file somewhere on your server
sampleFile.mv('C:/Users/marten/code/nodetest/temp.csv', function(err) {
if (err)
return res.status(500).send(err);
// res.send('File uploaded!');
});
fs.createReadStream('C:/Users/marten/code/nodetest/temp.csv')
.pipe(csv({quote: '"'}))
.on('data', function (data) {
console.log(data);
resp.push(data);
//console.log('Name: %s Age: %s', data.NAME, data.AGE)
})
.on('end', function () {
console.log(resp);
res.json(resp);
} )
//res.json([{ "name":"John", "age":30, "car":null },{ "name":"John", "age":30, "car":null }]);
});
router.post('/api/v1/liikmed', function(req, res) {
console.log(req.body);
var results =[] ;
var return_id;
// Grab data from http request
var data = {liikme_status: req.body.status, type: req.body.type, firstname: req.body.firstname, lastname: req.body.lastname};
// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({ success: false, data: err});
}
var query = client.query("insert into liikmed (status, type, lastname, firstname) values ($1, $2, $3, $4) returning id ", [data.liikme_status, data.type, data.lastname, data.firstname]);
console.log ("Insert into liikmed done");
query.on("row", function (row, result) {
result.addRow(row);
});
function returnInsertedRow (data, callback) {query.on("end", function (result) {
return_id = (result.rows[0].id);
done();
callback(null, return_id);
})
}
returnInsertedRow(data, function(err, content) {
if (err) {
console.log(err);
// Do something with your error...
} else {
var results = [];
// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({ success: false, data: err});
}
// SQL Query > Select Data
var query = client.query("SELECT firstname, lastname, status, type FROM liikmed where id= $1", [content]);
// Stream results back one row at a time
query.on('row', function(row) {
console.log(row);
results.push(row);
});
// After all data is returned, close connection and return results
query.on('end', function() {
done();
return res.json(results);
});
});
}
});
});
});
router.get('/api/v1/liikmed/', function(req, res) {
var results = [];
// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({ success: false, data: err});
}
// SQL Query > Select Data
var query = client.query("SELECT * FROM liikmed order by lastname, firstname asc");
// Stream results back one row at a time
query.on('row', function(row) {
results.push(row);
});
// After all data is returned, close connection and return results
query.on('end', function() {
done();
return res.json(results);
});
});
});
router.get('/api/v1/liikmed/:liikmed_id', function(req, res) {
var results = [];
var liikmed_id = req.params.liikmed_id;;
// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({ success: false, data: err});
}
// SQL Query > Select Data
var query = client.query("SELECT * FROM liikmed where id = $1", [liikmed_id]);
// Stream results back one row at a time
query.on('row', function(row) {
results.push(row);
});
// After all data is returned, close connection and return results
query.on('end', function() {
done();
return res.json(results);
});
});
});
router.get('/api/v1/types/', function(req, res) {
var results = [];
// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({ success: false, data: err});
}
// SQL Query > Select Data
var query = client.query("SELECT * FROM types");
// Stream results back one row at a time
query.on('row', function(row) {
results.push(row);
});
// After all data is returned, close connection and return results
query.on('end', function() {
done();
return res.json(results);
});
});
});
router.get('/api/v1/statuses/', function(req, res) {
var results = [];
// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({ success: false, data: err});
}
// SQL Query > Select Data
var query = client.query("SELECT * FROM statuses");
// Stream results back one row at a time
query.on('row', function(row) {
results.push(row);
});
// After all data is returned, close connection and return results
query.on('end', function() {
done();
return res.json(results);
});
});
});
router.put('/api/v1/liikmed', function(req, res) {
var results =[]
// Grab data from http request
console.log(req.body);
var data = {status: req.body.status, type: req.body.type, firstname: req.body.firstname, lastname: req.body.lastname, id:req.body.maksja};
// Get a Postgres client from the connection pool
pg.connect(connectionString, function(err, client, done) {
// Handle connection errors
if(err) {
done();
console.log(err);
return res.status(500).json({ success: false, data: err});
}
// SQL Query > Insert Data
//console.log(("INSERT INTO excluded(id, word) values(3, $1)", [word]))
client.query("UPDATE liikmed SET firstname = $1, lastname = $2, status=$3, type=$4 where id = $5", [data.firstname, data.lastname, data.status, data.type, data.id]);
return res.json(results);
});
});
|
JavaScript
|
UTF-8
| 3,292
| 2.59375
| 3
|
[] |
no_license
|
$(() => {
const params = window.location.search.replace('?', '').split('&').reduce(
(p, e) => {
const a = e.split('=');
p[decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
return p;
},
{},
);
const buyItem_currentCar = document.getElementsByClassName('order-settings__current-car');
buyItem_currentCar.innerHTML = `<p>Выбранный авто: <b>${params.carName}</b>;</p><p>Цена аренды: <b>${params.carPrice}</b> руб./час.</p>`;
const selectedAuto = `Выбранный авто: ${params.carName};\nЦена аренды: ${params.carPrice} руб./час.`;
function alertFinalDoc() {
console.log(selectedAuto);
function testDropDown(type, text) {
console.log(`${text}: ${$(type).text()}`);
}
const autoTransmission = document.getElementsByName('transmission')[0];
testDropDown(autoTransmission, 'Коробка передач');
const territoryOfUse = document.getElementsByName('territory-of-use')[0];
testDropDown(territoryOfUse, 'Территория использования');
const placeOfRenting = document.getElementsByName('place-of-renting')[0];
testDropDown(placeOfRenting, 'Место офромления аренды');
const rentAutoHours = document.getElementsByClassName('js-standard-slider__custom-handle')[0];
console.log(`Количество часов аренды: ${rentAutoHours.textContent}`);
const checkBoxArray = [];
function testCheckBox(type, text) {
if (type.checked) {
checkBoxArray[checkBoxArray.length] = text;
}
}
const childrenArmchair = document.getElementsByName('children-armchair')[0];
testCheckBox(childrenArmchair, 'Детское кресло');
const navigate = document.getElementsByName('navigate')[0];
testCheckBox(navigate, 'Навигатор');
const autoRefrigerator = document.getElementsByName('auto-refrigerator')[0];
testCheckBox(autoRefrigerator, 'Авто-холодильник');
if (checkBoxArray === '') {
console.log('Добавить в машину: Не выбрано');
} else {
console.log(`Добавить в машину: ${checkBoxArray}`);
}
const formSurname = document.getElementsByName('form-surname')[0];
const formName = document.getElementsByName('form-name')[0];
const formPatronymic = document.getElementsByName('form-patronymic')[0];
const formNumber = document.getElementsByName('form-number')[0];
const formEmail = document.getElementsByName('form-email')[0];
console.log(`ФИО: ${formSurname.value} ${formName.value} ${formPatronymic.value}\nКонтактный телефон: ${formNumber.value}\nE-mail: ${formEmail.value}`);
const selectedMonth = document.getElementsByClassName('ui-datepicker-month')[0];
const selectedDay = document.getElementsByClassName('ui-state-active')[0];
console.log(`Выбранная дата: ${selectedMonth.textContent} ${selectedDay.textContent}`);
const finalPrice = `${params.carPrice * rentAutoHours.textContent} руб.`;
console.log(`Сумма: ${finalPrice}`);
console.log('--/--/--/--/--/--/--/--/--/--/--/--/--/--');
}
$('.order-settings__button-send-request').on('click', alertFinalDoc);
});
|
Swift
|
UTF-8
| 471
| 2.75
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-facebook-software-license"
] |
permissive
|
/**
Returns a minimal `Location` from a `LocationFragment`
*/
extension Location {
static func location(from locationFragment: GraphAPI.LocationFragment) -> Location? {
guard let id = decompose(id: locationFragment.id) else { return nil }
return Location(
country: locationFragment.country,
displayableName: locationFragment.displayableName,
id: id,
localizedName: locationFragment.name,
name: locationFragment.name
)
}
}
|
Java
|
UTF-8
| 1,065
| 1.765625
| 2
|
[] |
no_license
|
/*
* generated by Xtext 2.16.0
*/
package org.xtext.msl.parser.antlr;
import com.google.inject.Inject;
import org.eclipse.xtext.parser.antlr.AbstractAntlrParser;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import org.xtext.msl.parser.antlr.internal.InternalMSLParser;
import org.xtext.msl.services.MSLGrammarAccess;
public class MSLParser extends AbstractAntlrParser {
@Inject
private MSLGrammarAccess grammarAccess;
@Override
protected void setInitialHiddenTokens(XtextTokenStream tokenStream) {
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
}
@Override
protected InternalMSLParser createParser(XtextTokenStream stream) {
return new InternalMSLParser(stream, getGrammarAccess());
}
@Override
protected String getDefaultRuleName() {
return "Specification";
}
public MSLGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(MSLGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
|
PHP
|
UTF-8
| 376
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace ODJuno\Interfaces;
/**
* Interface ODJunoInterface
*
* @author Fernando Campos de Oliveira <fernando@odesenvolvedor.net>
*
* @package ODJuno\Interfaces;
*/
interface ODJunoInterface
{
/**
* @param $json
*
* @return \stdClass
*/
public static function fromJson($json);
/**
* @param \stdClass $data
*/
public function populate(\stdClass $data);
}
|
Markdown
|
UTF-8
| 621
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
**Work in progress**
# Moira Helm Charts [](https://t.me/moira_alert)
If you're new here, better check out our main [README](https://github.com/moira-alert/moira/blob/master/README.md).
## Accessing repo charts
To add Moira charts repo execute:
```console
helm repo add moiracharts https://moira-alert.github.io/helmcharts
```
To list all available repo charts execute:
```console
helm search moiracharts
```
## Contributing repo charts
To get to know how to create, update and delete repo charts see [Contributing guide](CONTRIBUTING.md).
|
Python
|
UTF-8
| 1,244
| 2.546875
| 3
|
[] |
no_license
|
from django.shortcuts import render, HttpResponse
from .models import Account
def index(request):
return HttpResponse('<h1>Welcome to accounts application!</h1>')
def create(request, uname, psw):
account = Account(username = uname, password = psw)
account.save()
return HttpResponse('Account: {} was created'.format(account))
def all(request):
context = {}
accounts = Account.objects.all()
context['users'] = list(accounts)
return render(request, 'users.jinja', context)
def get_username(request, username):
account = Account.objects.get(username = username)
return HttpResponse('Id: {}, Account: {}, password: {}'.format(account.id,account, account.password))
def get(request, id):
account = Account.objects.get(id = id)
return HttpResponse('Id: {}, Account: {}, password: {}'.format(account.id,account, account.password))
def delete(request, uname):
account = Account.objects.get(username = uname)
account.delete()
return HttpResponse('Account was deleted')
def get_password(request, password):
context = {}
accounts = Account.objects.filter(password = password)
context['users'] = list(accounts)
return render(request, 'users.jinja', context)
|
Java
|
UTF-8
| 1,069
| 2.21875
| 2
|
[] |
no_license
|
package djs.com.happysharebuy.utils;
import android.content.Context;
import org.xutils.http.RequestParams;
/**
* Created by bin on 2017/7/1.
* 请求参数类
*/
public class CustomRequestParams {
// public CustomRequestParams(Context context) {
// super(HttpUrlUtils.url);
// int perid = PrefUtil.getIntPref(context, PrefUtil.USER_ID, 0);
// this.addBodyParameter("perid", perid + "");
// }
//
// public CustomRequestParams() {
// super(HttpUrlUtils.url);
// }
/**
* 不带ID的参数
* @return
*/
public static RequestParams getParams(){
RequestParams params = new RequestParams(HttpUrlUtils.url);
return params;
}
/**
* 带ID的参数
* @param context
* @return
*/
public static RequestParams getParams(Context context){
RequestParams params = new RequestParams(HttpUrlUtils.url);
int perid = PrefUtil.getIntPref(context, PrefUtil.USER_ID, 0);
params.addBodyParameter("perid", perid + "");
return params;
}
}
|
Java
|
UTF-8
| 953
| 3.265625
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class RFC {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String nombreCompleto= new String();
String nombre,aPaterno,aMaterno,rfc;
String fecha;
String dd,mm,aa;
int y;
System.out.println("Introduce tu nombre completo");
nombreCompleto=scanner.nextLine();
nombre=nombreCompleto.substring(0,1);
y=nombreCompleto.indexOf(" ");
aPaterno=nombreCompleto.substring(y+1, y+3);
y=nombreCompleto.lastIndexOf(" ");
aMaterno=nombreCompleto.substring(y+1, y+2);
//Fecha
System.out.println("Escribe tu fecha de nacimiento de la forma dd/mm/aaaa");
fecha=scanner.nextLine();
y=fecha.indexOf("/");
dd=fecha.substring(0,y);
mm=fecha.substring(y+1, y+3);
y=fecha.lastIndexOf("/");
aa=fecha.substring(y+3, y+5);
rfc=aPaterno+aMaterno+nombre+aa+mm+dd;
rfc=rfc.toUpperCase();
System.out.println(" El RFC de "+nombreCompleto+" es : "+rfc+"");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.