language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 361
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
# tiempo-perfecto
This JavaScript project allows users to create a schedule as a JSON string and plug the string into a parser which then displays their schedule in an informative, easy-to-read format.
[Create a schedule](https://smittycraft.github.io/tiempo-perfecto/creator/) or [view the schedule](https://smittycraft.github.io/tiempo-perfecto/schedule/).
|
Markdown
|
UTF-8
| 3,307
| 3.0625
| 3
|
[] |
no_license
|
## CSCI 2020u Final Project - Computer Vision Deep Learning Demo
by Tamilselvan Balasuntharam, Harrish Thasarathan, Tommy Turcotte and Spencer Denford
https://github.com/Harry-Thasarathan/Java-Project.git
### Introduction:
Here we present our final project for csci2020u, a computer vision and deep learning application with 3 interactive demonstrations. These include a hand written (single) digit recognizer, where the user can draw a number and our trained neural network will recognize it. A binary cat vs dog classifier, where the user can feed an image of a dog or cat and have a neural network determine which animal it is. As well as a Style Transfer demonstration where the user can take a webcam picture of themselves and have the style of the photo changed (similar to instagram filters).
## Prerequisites
- Java 1.8 (JDK)
- DeepLearning4j Library
- Maven
## Installation
- Clone this repo (allows use of DL4j libraries):
```bash
$ git clone https://github.com/deeplearning4j/dl4j-examples.git
$ cd dl4j-examples/
$ mvn clean install
```
- mvn clean install can take some time
- Note that the library is large, delete it from your system when finished if you prefer
- Clone our repo
```bash
$ git clone https://github.com/Harry-Thasarathan/Java-Project.git
$ cd Java-Project
$ mvn clean install
```
- Open the project in IntelliJ, navigate to the Java-Project folder (stuff outside gives us git errors to remove), that is where the working code is and run the server and then the client files from IntelliJ, this will show the main menu from there you can view the rest of the demos
## Hand Written Digit Recognizer:

Left click and draw a number (0 to 9), then press enter. Our code will print the networks prediction as to the number classification. Below that is a more detailed label
## Cat or Dog:

Upload a photo of a dog or a cat using our menu system. Press button to view the prediction on the left. Our code will distinguish weather it is a dog or a cat.
## Style Transfer:

Pressing the Capture! button will capture a webcam image. Pressing Stylize! will then run the style transfer algorithm on the webcam image. Since the style transfer image is computationally expensive and doesnt work well in the javafx thread (even as a seperate task), use our menu systems open command to open you file system and open the produced images to the screen. They are saved under resources.
## Server
- Tracks people in cliend
## Client
- provides main menu (run server then client)
## Contributions
Harry
- Hand Written Digits Demo (AlexNet network trained in python in google colab free tesla k80 GPU on Mnist dataset)
- Readme
- Cat vs Dog network trained in Python (CNN also google colab)
Tamilesh
- UI for cats vs dog prediction
- Style Transfer Algorithm Modifications
- Style Transfer UI
Spencer Denford
- Color extraction (ended up not using in demo for space)
- Readme
Tommy Turcotte
- Server functionality
- Client functionality
|
Java
|
UTF-8
| 781
| 3.109375
| 3
|
[] |
no_license
|
import java.io.*;
import java.util.*;
class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
StringBuffer sb = new StringBuffer();
if(n==0)System.out.println(0);
else{
while(n!=0){
if((n%2)==0){
n=-n/2;
sb.append("0");
}else{
n=-(n-1)/2;
sb.append("1");
}
}
System.out.println(sb.reverse());
}
}
}
|
C#
|
UTF-8
| 8,614
| 3.484375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace RoverOnMars
{
/// <summary>
/// Class that contains the questions to set up the Rover class.
/// </summary>
class RoverQuestions
{
/// <summary>
/// Validates if a user input is only a string of numbers.
/// </summary>
/// <param name="input">String input to be verified</param>
/// <returns>String that contains only numbers</returns>
private string IsValidNumber(string input)
{
while (Regex.IsMatch(input, @"^\d+$") == false)
{
Console.WriteLine("");
Console.WriteLine($"---{input} is not a valid positive integer. Please enter a valid positive integer.");
Console.Write("> ");
input = Console.ReadLine();
}
return input;
}
/// <summary>
/// Validates if a user input is a single direction string.
/// </summary>
/// <param name="input">String input to be verified</param>
/// <returns>Single letter string that gives rover facing direction</returns>
private string IsOnlyDirection(string input)
{
while(input.Length > 1 || input.Length == 0)
{
Console.WriteLine("");
Console.WriteLine("---Please enter a single letter direction (N/S/E/W).");
Console.Write("> ");
input = Console.ReadLine();
}
while(Regex.IsMatch(input, @"[^NnSsEeWw]"))
{
Console.WriteLine("");
Console.WriteLine($"---Please enter a compass direction (N/S/E/W). {input} is not a valid direction.");
Console.Write("> ");
input = Console.ReadLine();
}
return input;
}
/// <summary>
/// Prompts user for the plateau search area.
/// </summary>
/// <returns>int[] of height and width of the plateau area</returns>
public int[] PlateauArea()
{
int[] plateauAreaInput = new int[2];
Console.WriteLine("Welcome! Please provide the search area you would like to explore today.");
Console.WriteLine("Provide the width of exploration area as a positive integer.");
Console.Write("> ");
string plateauWidthInput = Console.ReadLine();
int plateuWidth = Convert.ToInt32(IsValidNumber(plateauWidthInput));
Console.WriteLine("");
Console.WriteLine("Provide the height of exploration area as a positive integer.");
Console.Write("> ");
string plateauHeightInput = Console.ReadLine();
int plateuHeight = Convert.ToInt32(IsValidNumber(plateauHeightInput));
plateauAreaInput[0] = plateuWidth;
plateauAreaInput[1] = plateuHeight;
return plateauAreaInput;
}
/// <summary>
/// Prompts user for where a rover is to start within the bounds of the plateau area and which direction the rover is facing.
/// </summary>
/// <param name="areaBounds">Plateau area bounds</param>
/// <returns>Tuple of the int x position, int y position and string of the facing direction</returns>
public Tuple<int,int,string> RoverStartPosition(int[] areaBounds)
{
Console.WriteLine("");
Console.WriteLine("The following will set deployment of a Rover.\n Deployment will continue until you no longer want to deploy a rover \n or a set of movement commands moves a rover out of the plateau area bounds.");
Thread.Sleep(5000);
Console.WriteLine("");
Console.WriteLine("========================================================");
Console.WriteLine($"Provide the starting latitude position of the rover as a positive integer between 0 and {areaBounds[0]}.");
Console.Write("> ");
string startingXInput = Console.ReadLine();
int startingX = Convert.ToInt32(IsValidNumber(startingXInput));
while(startingX > areaBounds[0] || startingX < 0)
{
while(startingX > areaBounds[0])
{
Console.WriteLine("");
Console.WriteLine($"---The starting latitude cannot be larger than {areaBounds[0]}");
Console.WriteLine("========================================================");
Console.WriteLine($"Please enter a starting latitude less than {areaBounds[0]}");
Console.Write("> ");
startingXInput = Console.ReadLine();
startingX = Convert.ToInt32(IsValidNumber(startingXInput));
}
while (startingX < 0)
{
Console.WriteLine("");
Console.WriteLine($"---The starting latitude cannot be less than 0");
Console.WriteLine("========================================================");
Console.WriteLine($"Please enter a starting latitude greater than 0");
Console.Write("> ");
startingXInput = Console.ReadLine();
startingX = Convert.ToInt32(IsValidNumber(startingXInput));
}
}
Console.WriteLine("");
Console.WriteLine($"Provide the starting longitude position of the rover as a positive integer between 0 and {areaBounds[1]}.");
Console.Write("> ");
string startingYInput = Console.ReadLine();
int startingY = Convert.ToInt32(IsValidNumber(startingYInput));
while(startingY > areaBounds[1] || startingY < 0)
{
while (startingY > areaBounds[1])
{
Console.WriteLine("");
Console.WriteLine($"---The starting longitude cannot be larger than {areaBounds[1]}");
Console.WriteLine("========================================================");
Console.WriteLine($"Please enter a starting longitude less than {areaBounds[1]}");
Console.Write("> ");
startingYInput = Console.ReadLine();
startingY = Convert.ToInt32(IsValidNumber(startingYInput));
}
while (startingY < 0)
{
Console.WriteLine("");
Console.WriteLine($"---The starting longitude cannot be less than 0");
Console.WriteLine("========================================================");
Console.WriteLine($"Please enter a starting longitude greater than 0");
Console.Write("> ");
startingYInput = Console.ReadLine();
startingY = Convert.ToInt32(IsValidNumber(startingYInput));
}
}
Console.WriteLine("");
Console.WriteLine("Provide the starting direction of the rover. (N/S/E/W)");
Console.Write("> ");
string startingDirectionInput = Console.ReadLine();
string startingDirection = IsOnlyDirection(startingDirectionInput).ToUpper();
Tuple<int, int, string> startPosition = new Tuple<int, int, string>(startingX, startingY, startingDirection);
return startPosition;
}
/// <summary>
/// Prompts the user to enter in a string of move commands
/// </summary>
/// <returns>String of move commands</returns>
public string MoveCommands()
{
Console.WriteLine("========================================================");
Console.WriteLine("Example movement command string: mmlmmr");
Console.WriteLine("");
Console.WriteLine("Actions performed: \n move 1 in direction facing, \n move 1 in direction facing, \n turn left 90 degrees, \n move 1 in direction facing, \n move 1 in direction facing, \n turn right 90 degrees.");
Thread.Sleep(2500);
Console.WriteLine("");
Console.WriteLine("Enter in your move commands (m/M = move, l/L = turn Left, r/R = turn Right)");
Console.Write("> ");
string moveCommands = Console.ReadLine().ToLower();
return moveCommands;
}
}
}
|
JavaScript
|
UTF-8
| 550
| 2.75
| 3
|
[] |
no_license
|
$.ajax({
type: "GET",
url: "/get_feeds",
}).done(function (data) {
var container=document.getElementsByClassName("container")[0];
var feeds = JSON.parse(data);
console.log(feeds)
feeds.forEach(element => {
var div = document.createElement("div");
div.className="little-link";
div.innerHTML=`<h3>${element.title}</h3><a>${element.link}</a>`
container.appendChild(div);
});
});
|
Java
|
UTF-8
| 5,744
| 2.140625
| 2
|
[] |
no_license
|
package com.android.liyun.adapter;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.liyun.R;
import com.android.liyun.bean.OrdersBean;
import com.android.liyun.bean.OrdersGoodsBean;
import com.android.liyun.utils.UIUtils;
import com.bumptech.glide.Glide;
import java.util.List;
public class CollocationListAdapter extends BaseExpandableListAdapter {
private LayoutInflater inflater;
private Context context;
private ExpandableListView elv_collocation;
private List<OrdersBean> data;
public CollocationListAdapter(Context context, ExpandableListView elv_collocation, List<OrdersBean> data) {
this.context = context;
this.elv_collocation = elv_collocation;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.data = data;
}
@Override
public int getGroupCount() {
return data.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return data.get(groupPosition).getGood().size();
}
@Override
public Object getGroup(int groupPosition) {
return data.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return data.get(groupPosition).getGood().get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;//如果子条目需要响应click事件,必需返回true
}
@Override
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
ParentViewHolder parentViewHolder;
if (null == convertView) {
convertView = inflater.inflate(R.layout.collocation_list_item_parent, parent, false);
parentViewHolder = new ParentViewHolder(convertView);
convertView.setTag(parentViewHolder);
} else {
parentViewHolder = (ParentViewHolder) convertView.getTag();
}
OrdersBean ordersBean = data.get(groupPosition);
parentViewHolder.txt_order_status.setText(ordersBean.getStatus());
parentViewHolder.txt_order_num_alias.setText(ordersBean.getOrder_num_alias());
return convertView;
}
@Override
public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ChildViewHolder childViewHolder;
if (null == convertView) {
convertView = inflater.inflate(R.layout.collocation_list_item_child, parent, false);
childViewHolder = new ChildViewHolder(convertView);
convertView.setTag(childViewHolder);
} else {
childViewHolder = (ChildViewHolder) convertView.getTag();
}
OrdersBean.GoodBean goodBean = data.get(groupPosition).getGood().get(childPosition);
if (!TextUtils.isEmpty(goodBean.getImage())) {
Glide
.with(UIUtils.getContext())
.load(goodBean.getImage())
.crossFade()
.into((childViewHolder.iv_goods));
}
childViewHolder.txt_name.setText(goodBean.getName());
// childViewHolder.tv_goods_title.setText(collocationSkuBean.getSkuTitle());
// childViewHolder.ll_root_view.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// //进入商品详情页操作
// }
// });
// if (childPosition == data.get(groupPosition).getCollocationSkuDoList().size() - 1) {
// //当前套餐的最后一个商品
// childViewHolder.ll_bottom.setVisibility(View.VISIBLE);
// childViewHolder.tv_collocation_price.setText(data.get(groupPosition).getTotalPrice().toString());
// childViewHolder.tv_add_cart.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// //把套餐商品加入购物车操作
// }
// });
// } else {
// childViewHolder.ll_bottom.setVisibility(View.GONE);
// }
return convertView;
}
class ParentViewHolder {
private TextView txt_order_num_alias, txt_order_status;
private ParentViewHolder(View view) {
txt_order_num_alias = (TextView) view.findViewById(R.id.txt_order_num_alias);
txt_order_status = (TextView) view.findViewById(R.id.txt_order_status);
}
}
private class ChildViewHolder {
private ImageView iv_goods;
private LinearLayout ll_bottom, ll_root_view;
private TextView txt_name, txt_total, txt_confirm_payment;
private ChildViewHolder(View view) {
iv_goods = (ImageView) view.findViewById(R.id.iv_goods);
txt_name = (TextView) view.findViewById(R.id.txt_name);
txt_total = (TextView) view.findViewById(R.id.txt_total);
txt_confirm_payment = (TextView) view.findViewById(R.id.txt_confirm_payment);
}
}
}
|
JavaScript
|
UTF-8
| 1,119
| 2.796875
| 3
|
[] |
no_license
|
// const categoriesContainer = document.getElementById('categories-container')
// const recipesContainer = document.getElementById('recipes-container')
// const categoryForm = document.getElementById("form-container")
// const recipeForm = document.getElementById("form-container")
const base_url = "http://127.0.0.1:3000"
const recipeService = new RecipeService(base_url)
const categoryService = new CategoryService(base_url)
const removeCategory = document.getElementById('delete-bttn')
const recipeForm = document.getElementById('recipe-form-container')
const recipesContainer = document.getElementById('recipes-container')
Category.categoryForm.addEventListener('submit', handleCategorySubmit)
categoryService.getCategories()
recipeService.getRecipies()
Category.renderForm()
Recipe.renderRecipeForm()
Recipe.recipeForm.addEventListener('submit', handleRecipeSubmit)
function handleCategorySubmit(){
event.preventDefault()
categoryService.createCategory()
event.target.reset()
}
function handleRecipeSubmit(){
event.preventDefault()
recipeService.createRecipe()
event.target.reset()
}
|
C++
|
UTF-8
| 185
| 2.84375
| 3
|
[] |
no_license
|
#include "Triangulo.h"
Triangulo::Triangulo(float base,float altura)
{
this->base=base;
this->altura=altura;
}
float Triangulo::calcularArea()
{
return (base*altura)/2;
}
|
C#
|
UTF-8
| 30,079
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
using Microsoft.Playwright;
using PlaywrightContrib.Extensions;
using PlaywrightContrib.FluentAssertions.Internal;
namespace PlaywrightContrib.FluentAssertions
{
/// <summary>
/// Contains a number of methods to assert that an <see cref="IPage"/> is in the expected state.
/// </summary>
public class PageAssertions : ReferenceTypeAssertions<IPage, PageAssertions>
{
/// <summary>
/// Initializes a new instance of the <see cref="PageAssertions"/> class.
/// </summary>
/// <param name="subject">The <see cref="IPage"/> to assert.</param>
public PageAssertions(IPage subject) => Subject = subject;
/// <summary>
/// Returns the type of the subject the assertion applies on.
/// </summary>
protected override string Identifier => nameof(IPage);
// Content
/// <summary>
/// Asserts that the page has the specified content.
/// </summary>
/// <param name="regex">A regular expression to test against <c>document.documentElement.textContent</c>.</param>
/// <param name="flags">A set of flags for the regular expression.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
/// <seealso href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"/>
public async Task<AndConstraint<PageAssertions>> HaveContentAsync(string regex, string flags = "", string because = "", params object[] becauseArgs)
{
var result = await Subject.HasContentAsync(regex, flags).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:page} to have content {0}{reason}.", $"/{regex}/{flags}");
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the page does not have the specified content.
/// </summary>
/// <param name="regex">A regular expression to test against <c>document.documentElement.textContent</c>.</param>
/// <param name="flags">A set of flags for the regular expression.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
/// <seealso href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"/>
public async Task<AndConstraint<PageAssertions>> NotHaveContentAsync(string regex, string flags = "", string because = "", params object[] becauseArgs)
{
var result = await Subject.HasContentAsync(regex, flags).ConfigureAwait(false);
Execute.Assertion
.ForCondition(!result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:page} not to have content {0}{reason}.", $"/{regex}/{flags}");
return new AndConstraint<PageAssertions>(this);
}
// Title
/// <summary>
/// Asserts that the page has the specified title.
/// </summary>
/// <param name="regex">A regular expression to test against <c>document.title</c>.</param>
/// <param name="flags">A set of flags for the regular expression.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
/// <seealso href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"/>
public async Task<AndConstraint<PageAssertions>> HaveTitleAsync(string regex, string flags = "", string because = "", params object[] becauseArgs)
{
var result = await Subject.HasTitleAsync(regex, flags).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:page} to have title {0}{reason}, but found {1}.", $"/{regex}/{flags}", await Subject.TitleAsync().ConfigureAwait(false));
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the page does not have the specified title.
/// </summary>
/// <param name="regex">A regular expression to test against <c>document.title</c>.</param>
/// <param name="flags">A set of flags for the regular expression.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
/// <seealso href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"/>
public async Task<AndConstraint<PageAssertions>> NotHaveTitleAsync(string regex, string flags = "", string because = "", params object[] becauseArgs)
{
var result = await Subject.HasTitleAsync(regex, flags).ConfigureAwait(false);
Execute.Assertion
.ForCondition(!result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:page} not to have title {0}{reason}.", $"/{regex}/{flags}");
return new AndConstraint<PageAssertions>(this);
}
// Visible
/// <summary>
/// Asserts that the element on page is visible.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveVisibleElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().IsVisibleAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} to be visible{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the element on page is hidden.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveHiddenElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().IsHiddenAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} to be hidden{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
// Checked
/// <summary>
/// Asserts that the element on page is checked.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
/// <remarks><![CDATA[Elements: <command>, <input>]]></remarks>
public async Task<AndConstraint<PageAssertions>> HaveCheckedElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().IsCheckedAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} to be checked{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the element on page is not checked.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
/// <remarks><![CDATA[Elements: <command>, <input>]]></remarks>
public async Task<AndConstraint<PageAssertions>> NotHaveCheckedElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().IsCheckedAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(!result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} not to be checked{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
// Disabled
/// <summary>
/// Asserts that the element on page is disabled.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
/// <remarks><![CDATA[Elements: <button>, <command>, <fieldset>, <input>, <keygen>, <optgroup>, <option>, <select>, <textarea>]]></remarks>
public async Task<AndConstraint<PageAssertions>> HaveDisabledElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().IsDisabledAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} to be disabled{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the element on page is enabled.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
/// <remarks><![CDATA[Elements: <button>, <command>, <fieldset>, <input>, <keygen>, <optgroup>, <option>, <select>, <textarea>]]></remarks>
public async Task<AndConstraint<PageAssertions>> HaveEnabledElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().IsEnabledAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} to be enabled{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
// Editable
/// <summary>
/// Asserts that the element on page is editable.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveEditableElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().IsEditableAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} to be editable{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the element on page is not editable.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> NotHaveEditableElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().IsEditableAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(!result)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} not to be editable{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
// Attribute
/// <summary>
/// Asserts that the element on page has the specified attribute.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="name">The attribute name.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveElementAttributeAsync(string selector, string name, string because = "", params object[] becauseArgs)
{
var result = await Subject.GetAttributeOrDefaultAsync(selector, name).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result != null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} to have attribute {1}{reason}.", selector, name);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the element on page does not have the specified attribute.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="name">The attribute name.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> NotHaveElementAttributeAsync(string selector, string name, string because = "", params object[] becauseArgs)
{
var result = await Subject.GetAttributeOrDefaultAsync(selector, name).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result == null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} not to have attribute {1}{reason}.", selector, name);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the element on page has the specified attribute value.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="name">The attribute name.</param>
/// <param name="value">The attribute value.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveElementAttributeValueAsync(string selector, string name, string value, string because = "", params object[] becauseArgs)
{
var result = await Subject.GetAttributeOrDefaultAsync(selector, name).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result == value)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} to have attribute {1} with value {2}{reason}, but found {3}.", selector, name, value, result);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the element on page does not have the specified attribute.
/// </summary>
/// <param name="selector">A selector to search for element. If there are multiple elements satisfying the selector, the first will be used.</param>
/// <param name="name">The attribute name.</param>
/// <param name="value">The attribute value.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> NotHaveElementAttributeValueAsync(string selector, string name, string value, string because = "", params object[] becauseArgs)
{
var result = await Subject.GetAttributeOrDefaultAsync(selector, name).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result != value)
.BecauseOf(because, becauseArgs)
.FailWith("Expected element {0} on {context:page} not to have attribute {1} with value {2}{reason}.", selector, name, value);
return new AndConstraint<PageAssertions>(this);
}
// Element
/// <summary>
/// Asserts that the page has the specified selector.
/// </summary>
/// <param name="selector">A selector to query for.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveElementAsync(string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().QuerySelectorAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result != null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:page} to have element matching {0}{reason}.", selector);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the page has the expected number of elements matching the specified selector.
/// </summary>
/// <param name="count">The expected number of elements matching the specified selector.</param>
/// <param name="selector">A selector to query for.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveElementCountAsync(int count, string selector, string because = "", params object[] becauseArgs)
{
var result = await Subject.GuardFromNull().QuerySelectorAllAsync(selector).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result.Count == count)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:page} to have {0} element(s) matching {1}{reason}, but found {2}.", count, selector, result.Count);
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the page has the specified selector with the specified content.
/// </summary>
/// <param name="selector">A selector to query for.</param>
/// <param name="regex">A regular expression to test against <c>element.textContent</c>.</param>
/// <param name="flags">A set of flags for the regular expression.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveElementWithContentAsync(string selector, string regex, string flags = "", string because = "", params object[] becauseArgs)
{
var result = await Subject.QuerySelectorWithContentAsync(selector, regex, flags).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result != null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:page} to have element matching {0} with content {1}{reason}.", selector, $"/{regex}/{flags}");
return new AndConstraint<PageAssertions>(this);
}
/// <summary>
/// Asserts that the page has the expected number of elements matching the specified selector with the specified content.
/// </summary>
/// <param name="count">The expected number of elements matching the specified selector.</param>
/// <param name="selector">A selector to query for.</param>
/// <param name="regex">A regular expression to test against <c>element.textContent</c>.</param>
/// <param name="flags">A set of flags for the regular expression.</param>
/// <param name="because">A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.</param>
/// <param name="becauseArgs">Zero or more objects to format using the placeholders in <paramref name="because"/>.</param>
/// <returns>An <see cref="AndConstraint{PageAssertions}"/> which can be used to chain assertions.</returns>
public async Task<AndConstraint<PageAssertions>> HaveElementWithContentCountAsync(int count, string selector, string regex, string flags = "", string because = "", params object[] becauseArgs)
{
var result = await Subject.QuerySelectorAllWithContentAsync(selector, regex, flags).ConfigureAwait(false);
Execute.Assertion
.ForCondition(result.Count == count)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:page} to have {0} element(s) matching {1} with content {2}{reason}, but found {3}.", count, selector, $"/{regex}/{flags}", result.Count);
return new AndConstraint<PageAssertions>(this);
}
}
}
|
Markdown
|
UTF-8
| 9,833
| 2.921875
| 3
|
[] |
no_license
|
# AdvancedDesign
## Projects:
1. Counterfeit/Bootleg/Appropriation
2. Remix
3. Subjective Dictionary
4. Process Book
## Rough Project Descriptions
### 1. Counterfeit/Bootleg/Appropriation
This project will run for the next several weeks (8/26–9/30), it has several parts. Each part is its own “sub project” — meaning a thread need not continue from stage to stage.
```
- Multi week project (4? 5?) -- start with one thing, and make a counterfeit; then make a bootleg; then make an appropriation... What kinds of reflection do we ask them to do at the end? what is the "learning" from this?
- workshops/lectures/readings: what is homage? what is appropriation? what is a bootleg? what is a counterfeit? seems like the curation stuff -- at least objects -- would fit in here potentially well; the translation of regularly encountered stuff into pattern library? - Something about collaboration or exchange, unexpected results? definitely automation/algorithms as they are so good at "copying" and looking for patterns/themes. Orson welles' F for Fake. Brazilian Cultural Cannibalism.
```
#### Counterfeit:
Definitions / To make an imitation or copy of (something), usually with the intent to defraud.; To carry on a deception; dissemble. made in imitation so as to be passed off fraudulently or deceptively as genuine; not genuine; forged. pretended; unreal. an imitation intended to be passed off fraudulently or deceptively as genuine; forgery. to make a counterfeit of; imitate fraudulently; forge. A ripoff of a legitimate thing that should exist/does exist…
Pick a designed something from out in the world. Make a counterfeit of it…
This thing you pick should be something that you think very highly of. How is it the best example of whatever design it is? what can you learn from replicating it?
#### Bootleg:
Definitions / To make, sell, or transport (alcoholic liquor) for sale illegally. To produce, distribute, or sell without permission or illegally. To engage in the bootlegging of alcoholic liquor or another product. an unauthorized audio or video recording. An unofficial remix. To attach a transmitter to a dish antenna, creating an uplink via which a signal is sent to a satellite without the knowledge of the satellite's owner. A product, especially alcoholic liquor, that is illicitly produced, distributed, or sold. Produced, sold, or transported illegally: bootleg gin; bootleg tapes. something that is made secretly and sold illegally. illegally made, copied, or sold. Something that shouldn’t exist. It is illegal not because it is fake or an illegitimate copy; but because it is meant to be controlled or desired to be kept out of the public (music bootleg tapes; bootleg alcohol made illegitimately to avoid prohibition or alcohol taxes)
#### Appropriation:
to take without permission or consent; seize; expropriate: He appropriated the trust funds for himself. to steal, especially to commit petty theft. the act of setting apart or taking for one's own use. the act of taking something such as an idea, custom, or style from a group or culture that you are not a member of and using it yourself. The act of taking or using things from a culture that is not your own, especially without showing that you understand or respect this culture. Appropriation in art is the use of pre-existing objects or images with little or no transformation applied to them. The taking over, into a work of art, of a real object or even an existing work of art.
- Watch: Catch me if you can
- Watch: F for Fake
- Read: Luke-Wood_Counterfeit-Design.pdf
- Read: Species of Spaces—Georges Perec
- Read: Excerpt from As Seen: Exhibition that Made Architecture and Design History
- Read: Jonathan Lethem, Ecstasy of Influence
- Read: Every Culture Appropriates - The Atlantic.pdf
### 2. Remix.
This Project will run from 10/07–10/28 (the four weeks of October)
> Special note for Fall break: All sections will be granted the week off, not just M/Tu; But I&K will be available for individual meetings the W/Th/F.
- Watch: Everything is a remix
- Watch: Ways of Seeing
- Read: Ways of Seeing? Barthes? Foucault?
- Listen: New Ways of Seeing (BBC Radio)
```
- (4 wks?) So we take a project of someone elses -- from the counterfeit et al project? -- and do a new "remix"
- This seems like a good companion to the communicating a design princple w/ limited means; the experience for someone who wasn't there through a new medium (again, sort of a remix)...
- Good opporunity to think about meaning making; how to use new metaphors or different forms/knowledge domains to convey the same ideas; or the same initial metaphors but with new meanings...
- Everything is a remix -- https://www.youtube.com/watch?v=nJPERZDfyWc
```
### 3. Dictionary 2.0
- Audit of Influences.
- Gerhart Richter Painting / Storehouse of treasures?
- (4 wks?) What inspires you; sure graphic design things; but let's look bigger and broader than that too -- there have to be other things you care about; are interested in; how do we catalog and utilize these things in one's desinging...
- Any of the criticality things work here...
- the everyday experience based design idea fits here well too
Create a dictionary to aid you in your potential degree project research and development. Research and define terms, ideas, and visual reference points associated with your questions and ideas. This “dictionary” is meant to help fill in conceptual gaps, refine direction, and enhance and inform so you can move forward with confidence.
Knowledge domain?
How might we questions?
### 4. Process Book.
the last 2 weeks are available for finalizing and producing
This is introduced the first day of the term
It is the documentation for all the projects
Must contain reflection on the term as well as all the different questions, outcomes, whatever created from the projects and workshops
Try to frame your current process; a practice; a praxis.
Show research that went into a project.
Share the “backstory” of your ideas/directions, etc.
Design isn’t magic: show us what really goes on to make something
±±±±±±±±±±±±±±±±±±±±
Specs:
8.5w x11h
Black and White (if you feel you need color, that’s fine, but we wanted to make it fast and cheap and easy to produce final physical copies to deliver to us)
Show more than final outputs. How did you start? how did you traverse the starting to the ending?
Written explanation. Try walking us through your working and thinking processes where you can.
Must contain documentation of all work made in AD1 over the fall term.
±±±±±±±±±±±±±±±±±±±±
The process book is a chronicle of your work flow and completed work during the course of the semester. It is a vehicle to gather research, scraps of notes, ideas, mock-ups, failures, successes, writing, reading, working files and final outcome of assignments and projects. It provides a narrative of the process in which you work — whether you make conscious, deliberate design decisions or more reactive “fooling around” or accidental or experimental design decisions. Both have value! We believe you will find the “process” of creating the process book worthwhile.
Your process book is a reflection of you — and more importantly your work and your thinking. A process book is both a scrapbook and a journal and design piece of its own. Process book’s should detail the process by which you developed your designs and your thinking this term. The formatting and the design style you create should feel authentic to your work and thoughts over the term. This is a visual and conceptual design project. The form should fit the content and contexts. If you have physical outputs, you will need to digitize the material to include.
Begin the process book immediately with the first projects, and try to keep up dating the process book as you complete assignments. You may add content from other courses, as well as figure out connections or interlink content from senior seminar as you go. You should also find ways to include the output and ideas from our in class charettes and prompts into the process book too.
We can give you feedback on your process book as it evolves if you desire. Create this process book in whatever tool you desire as long as you can make printable PDF pages at the end for getting it physically made. Make sure you run spell check on the content of your book and that you proofread it. At the END of the SEMESTER your will also be required to submit a physical and PDF process book to us.
## Workshops/Charettes/In Class Prompts:
1. Intro + Design Principles Installation
2. Translation Project
3. Curation of Objects
4. Exhibition Prototyping
5. Exhibition Prototyping
6. Audit of DP Ideas. Identify a trend or convention in graphic design and create a critical response to it.
7. Design something about your everyday experience. (ritual, rules, protocols, economies)
8. Design something that communicates the notion of time in a fixed/static medium
9. Opt. Ind Meetings
10. Use material choice to communicate the same message in different ways— opposite, subversive, enhanced
11. Exhibition Prototyping
12. Translate something that you encounter regularly into a graphic language / pattern library
13. Book Prototyping
14. Opt. Ind Meetings
15. Take an ethical stance on the design industry/technology
16. What is the future of the design profession?
## Lectures?
- Free/Libre/Open Source/Public Domain?
- Basic Semiotics refresher
- Finding Formal Fit: Form «» Content «» Context?
-
## Anything else??
## Other Good Questions:
- What do you think about this? what do you think you are supposed to think about this?
- how do you feel about this, how do you think you are supposed to feel about this?
- What is the weirdest thing you would advocate for?
|
Python
|
UTF-8
| 16,410
| 2.5625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""SOAP wrapper for CFME.
Enables to operate Infrastructure objects. It has better VM provisioning code. OOP encapsulated.
"""
from suds import WebFault
from utils import lazycache
from utils.conf import cfme_data
from utils.db import cfmedb
from utils.log import logger
from utils.soap import soap_client
from utils.wait import wait_for
client = None
def get_client():
global client
if client is None:
client = soap_client()
return client
def is_datastore_banned(datastore_name):
"""Checks whether the datastore is in the list of datastores not allowed to use
Args:
datastore_name: Name of the datastore
Returns: :py:class:`bool`
"""
banned_datastores = cfme_data.get("datastores_not_for_provision", [])
for banned_datastore in banned_datastores:
if banned_datastore in datastore_name:
return True
else:
return False
def set_client(client):
globals()["client"] = client
class MiqInfraObject(object):
"""Base class for all infrastructure objects.
Args:
id: GUID or ID of the object, it depends on what does the particular SOAP function wants.
"""
GETTER_FUNC = None
TAG_PREFIX = None
def __init__(self, id):
self._id = str(id)
assert self.GETTER_FUNC is not None, "You must specify GETTER_FUNC in the class!"
assert self.TAG_PREFIX is not None, "You must specify TAG_PREFIX in the class!"
@property
def id(self):
return self._id
@property
def object(self):
"""Accesses SOAP object
Accesses network.
Todo:
* cache?
"""
return getattr(get_client().service, self.GETTER_FUNC)(self.id)
@lazycache
def name(self):
return str(self.object.name)
@property
def exists(self):
try:
self.object
return True
except WebFault:
return False
@property
def ws_attributes(self):
"""Processes object.ws_attributes into builtin types"""
result = {}
for attribute in self.object.ws_attributes:
if attribute.value is None:
result[str(attribute.name)] = attribute.value
elif attribute.data_type == "string" or attribute.data_type == "array_of_string":
result[str(attribute.name)] = str(attribute.value)
elif attribute.data_type == "integer":
result[str(attribute.name)] = int(attribute.value)
elif attribute.data_type == "boolean":
result[str(attribute.name)] = str(attribute.value).lower().strip() == "true"
else: # TODO datetime
result[str(attribute.name)] = str(attribute.value)
return result
@property
def tags(self):
"""Return tags as an array of :py:class:`MiqTag` objects."""
fname = "%sGetTags" % self.TAG_PREFIX
return [
MiqTag(tag.category, tag.category_display_name, tag.tag_name, tag.tag_display_name,
tag.tag_path, tag.display_name)
for tag
in getattr(get_client().service, fname)(self.id)
]
def add_tag(self, tag):
"""Add tag to the object
Args:
tag: Tuple with tag specification.
"""
fname = "%sSetTag" % self.TAG_PREFIX
if (isinstance(tag, tuple) or isinstance(tag, list)) and len(tag) == 2:
return getattr(get_client().service, fname)(self.id, tag[0], tag[1])
elif isinstance(tag, MiqTag):
return getattr(get_client().service, fname)(self.id, tag.category, tag.tag_name)
else:
raise TypeError("Wrong type passed!")
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, repr(self.id))
def __getattribute__(self, name):
"""Delegates unknown calls to the received object"""
try:
return super(MiqInfraObject, self).__getattribute__(name)
except AttributeError as e:
try:
return getattr(self.object, name)
except AttributeError:
raise e
# Here comes rails (but in a good way)
class HasManyHosts(MiqInfraObject):
@lazycache
def hosts(self):
return [MiqHost(host.guid) for host in self.object.hosts]
class HasManyEMSs(MiqInfraObject):
@lazycache
def emss(self):
return [MiqEms(ems.guid) for ems in self.object.ext_management_systems]
class HasManyDatastores(MiqInfraObject):
@lazycache
def datastores(self):
return [MiqDatastore(store.id) for store in self.object.datastores]
class HasManyVMs(MiqInfraObject):
@property
def vms(self):
return [MiqVM(vm.guid) for vm in self.object.vms]
class HasManyResourcePools(MiqInfraObject):
@lazycache
def resource_pools(self):
return [MiqResourcePool(rpool.id) for rpool in self.object.resource_pools]
class BelongsToProvider(MiqInfraObject):
@lazycache
def provider(self):
return MiqEms(self.object.ext_management_system.guid)
class BelongsToCluster(BelongsToProvider):
@lazycache
def cluster(self):
return MiqCluster(self.object.parent_cluster.id)
class MiqEms(HasManyDatastores, HasManyHosts, HasManyVMs, HasManyResourcePools):
GETTER_FUNC = "FindEmsByGuid"
TAG_PREFIX = "Ems"
@lazycache
def port(self):
return self.object.port
@lazycache
def host_name(self):
return self.object.hostname
@lazycache
def ip_address(self):
return self.object.ipaddress
@lazycache
def clusters(self):
return [MiqCluster(cluster.id) for cluster in self.object.clusters]
@classmethod
def find_by_name(cls, name):
for ems in get_client().service.GetEmsList():
if ems.name.strip().lower() == name.strip().lower():
return cls(ems.guid)
else:
raise Exception("EMS with name %s not found!" % name)
@classmethod
def all(cls):
return [cls(ems.guid) for ems in get_client().service.GetEmsList()]
@lazycache
def direct_connection(self):
"""Returns an API from mgmt_system.py targeted at this provider"""
# Find the credentials entry
name = str(self.host_name)
from utils.conf import cfme_data, credentials
for prov_id, provider in cfme_data.get("management_systems", {}).iteritems():
if provider.get("hostname", None) == name or provider.get("region", None) == name:
credentials = credentials.get(provider["credentials"], {})
provider_id = prov_id
break
else:
raise NameError("Could not find provider %s in the credentials!" % name)
ptype = str(self.type).lower()
if ptype == "emsredhat":
from utils.mgmt_system import RHEVMSystem
return RHEVMSystem(self.host_name, credentials["username"], credentials["password"])
elif ptype == "emsvmware":
from utils.mgmt_system import VMWareSystem
return VMWareSystem(self.host_name, credentials["username"], credentials["password"])
elif ptype == "emsmicrosoft":
from utils.mgmt_system import SCVMMSystem
return SCVMMSystem(
hostname=self.host_name,
username=credentials["username"],
password=credentials["password"],
domain=credentials["domain"]
)
elif ptype == "emsamazon":
from utils.mgmt_system import EC2System
return EC2System(**credentials)
elif ptype == "emsopenstack":
from utils.mgmt_system import OpenstackSystem
credentials.update(
{"auth_url": cfme_data["management_systems"][provider_id]["auth_url"]}
)
return OpenstackSystem(**credentials)
else:
TypeError("Unknown Provider type!")
class MiqVM(HasManyDatastores, BelongsToCluster):
GETTER_FUNC = "FindVmByGuid"
TAG_PREFIX = "Vm"
@lazycache
def vendor(self):
return self.object.vendor
@property
def description(self):
return self.object.description
@property
def host(self):
return MiqHost(self.object.host.guid)
@property
def is_powered_on(self):
return self.object.power_state.strip().lower() == "on"
@property
def is_powered_off(self):
return self.object.power_state.strip().lower() == "off"
@property
def is_suspended(self):
return self.object.power_state.strip().lower() == "suspended"
def power_on(self):
return get_client().service.EVMSmartStart(self.id).result == "true"
def wait_powered_on(self, wait_time=120):
return wait_for(
lambda: self.is_powered_on, num_sec=wait_time, message="wait for power on", delay=5
)
def power_off(self):
return get_client().service.EVMSmartStop(self.id).result == "true"
def wait_powered_off(self, wait_time=120):
return wait_for(
lambda: self.is_powered_off, num_sec=wait_time, message="wait for power off", delay=5
)
def suspend(self):
return get_client().service.EVMSmartSuspend(self.id).result == "true"
def wait_suspended(self, wait_time=160):
return wait_for(
lambda: self.is_suspended, num_sec=wait_time, message="wait for suspend", delay=5
)
def delete(self):
"""Delete the VM from VMDB. To completely delete, use direct_connection."""
name = str(self.name)
if self.is_powered_on:
if not self.power_off():
raise Exception("Could not power off vm %s" % name)
self.wait_powered_off()
if not get_client().service.EVMDeleteVmByName(self.name):
raise Exception("Could not delete vm %s" % name)
wait_for(lambda: not self.exists, num_sec=60, delay=4, message="wait for VM removed")
@classmethod
def provision_from_template(cls, template_name, vm_name, wait_min=None, cpus=1, memory=1024,
vlan=None, first_name="Shadowman", last_name="RedHat", email="shadowm@n.redhat.com"):
"""Provision VM from template.
Works independently on the management system, tags appropriate VMDB objects to provision
without problems.
Args:
template_name: Name of the template to use.
vm_name: VM Name.
wait_min: How many minutes of wait for the provisioning to finish.
cpus: How many CPUs should the VM have.
memory: How much memory (in MB) should the VM have.
vlan: Where to connect the VM. Obligatory for RHEV
first_name: Name of the requestee
last_name: Surname of the requestee
email: Email of the requestee
Returns: :py:class:`MiqVM` object with freshly provisioned VM.
"""
vm_table = cfmedb()['vms']
for vm in cfmedb().session.query(vm_table.name, vm_table.guid)\
.filter(vm_table.template == True): # NOQA
# Previous line is ok, if you change it to `is`, it won't work!
if vm.name.strip() == template_name.strip():
template_guid = vm.guid
break
else:
raise Exception("Template %s not found!" % template_name)
template = cls(template_guid)
# Tag provider
for tag in template.provider.tags:
if tag.category == "prov_scope" and tag.tag_name == "all":
break
else:
logger.info("Tagging provider %s" % template.provider.name)
template.provider.add_tag(("prov_scope", "all"))
# Tag all provider's hosts
for host in template.provider.hosts:
for tag in host.tags:
if tag.category == "prov_scope" and tag.tag_name == "all":
break
else:
logger.info("Tagging host %s" % host.name)
host.add_tag(("prov_scope", "all"))
# Tag all provider's datastores
for datastore in template.provider.datastores:
ds_name = datastore.name
if is_datastore_banned(ds_name):
logger.info("Skipping datastore %s" % ds_name)
continue
for tag in datastore.tags:
if tag.category == "prov_scope" and tag.tag_name == "all":
break
else:
logger.info("Tagging datastore %s" % ds_name)
datastore.add_tag(("prov_scope", "all"))
# Create request
template_fields = get_client().pipeoptions(dict(guid=template_guid))
vm_fields = dict(
number_of_cpu=cpus,
vm_memory=memory,
vm_name=vm_name
)
if vlan: # RHEV-M requires this field
vm_fields["vlan"] = vlan
vm_fields = get_client().pipeoptions(vm_fields)
requester = get_client().pipeoptions(dict(
owner_first_name=first_name,
owner_last_name=last_name,
owner_email=email
))
try:
req_id = get_client().service.VmProvisionRequest(
"1.1", template_fields, vm_fields, requester, "", ""
).id
except WebFault as e:
if "'Network/vLan' is required" in e.message:
raise TypeError("You have to specify `vlan` parameter for this function! (RHEV-M?)")
else:
raise
logger.info("Waiting for VM provisioning request approval")
wait_for(
lambda: get_client().service.GetVmProvisionRequest(req_id).approval_state == "approved",
num_sec=180,
delay=5,
message="VM provision approval"
)
def check_whether_provisioning_finished():
request = get_client().service.GetVmProvisionRequest(req_id)
if request.status.lower().strip() == "error":
raise Exception(request.message) # change the exception class here
return request.status.lower().strip() == "ok" and len(request.vms) > 0
logger.info("Waiting for VM provisioning to be done")
wait_for(
check_whether_provisioning_finished,
num_sec=(wait_min * 60 if wait_min else 300), delay=5, message="provisioning"
)
vm_guid = get_client().service.GetVmProvisionRequest(req_id).vms[0].guid
new_vm = MiqVM(get_client().service.FindVmByGuid(vm_guid).guid)
# some basic sanity checks though they should always pass
assert new_vm.name == vm_name
assert new_vm.object.guid == vm_guid
logger.info("VM has been provisioned")
return new_vm
class MiqHost(HasManyDatastores, HasManyVMs, HasManyResourcePools, BelongsToCluster):
GETTER_FUNC = "FindHostByGuid"
TAG_PREFIX = "Host"
@classmethod
def all(cls):
return [cls(host.guid) for host in get_client().service.EVMHostList()]
class MiqDatastore(HasManyHosts, HasManyEMSs):
GETTER_FUNC = "FindDatastoreById"
TAG_PREFIX = "Datastore"
@classmethod
def all(cls):
return [cls(datastore.id) for datastore in get_client().service.EVMDatastoreList()]
class MiqCluster(
HasManyDatastores, HasManyHosts, HasManyVMs, HasManyResourcePools, BelongsToProvider):
GETTER_FUNC = "FindClusterById"
TAG_PREFIX = "Cluster"
@lazycache
def default_resource_pool(self):
return MiqResourcePool(self.object.default_resource_pool.id)
@classmethod
def all(cls):
return [cls(cluster.id) for cluster in get_client().service.EVMClusterList()]
class MiqResourcePool(HasManyHosts, HasManyEMSs):
GETTER_FUNC = "FindResourcePoolById"
TAG_PREFIX = "ResourcePool"
@lazycache
def store_type(self):
return str(self.object.store_type)
@classmethod
def all(cls):
return [cls(rpool.id) for rpool in get_client().service.EVMResourcePoolList()]
class MiqTag(object):
def __init__(self, category, category_dn, tag_name, tag_dname, tag_path, dn):
self.category = category
self.category_display_name = category_dn
self.tag_name = tag_name
self.tag_display_name = tag_dname
self.tag_path = tag_path
self.display_name = dn
|
C++
|
UTF-8
| 4,084
| 3.875
| 4
|
[
"WTFPL"
] |
permissive
|
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
//! One Dimensional Array Class
class oneDimArray
{
public:
//! Basic Constructor
/* Should be _generally_ avoided
*/
oneDimArray ();
//! One Dimensional Array Constructor
/* Generates a vector given a size (type int) and sets the
* middle cell to 1
*/
oneDimArray (const int& size);
//! Calculates the cells at time t+1
void calculateNext ();
//! Prints the array
void printArray () const;
//! Pretty print of the array
void printPretty () const;
char getStartLoc () const { return startLoc; };
protected:
//! Starting position
char startLoc;
private:
//! One Dimensional (1D) Array
std::vector <int> array;
//! Size of the array
int size;
//! Vector containing all possible patterns
std::vector <std::string> pattern;
//! Vector containing the state of the center cell at t+1
std::vector <int> state;
};
oneDimArray::oneDimArray ()
{
std::vector <int> array;
std::vector <std::string> pattern;
std::vector <int> state;
}
oneDimArray::oneDimArray (const int& s)
{
//! "Real" size of the array
/*! The 1D array has to meet two conditions in this program:
1. The array size is an odd number (so the middle is an integer)
2. The edges will always have to be zero, given that this program works with a fixed-size 1D array
*/
int nsize;
if (s % 2 == 0) {
nsize = s + 3;
} else {
nsize = s + 2;
}
size = nsize;
int start;
std::cout << "Select the starting postion: beginning, middle, end (b/m/e): ";
std::cin >> startLoc;
if (startLoc == 'b') {
// Beginning of the array
start = 1;
} else if (startLoc == 'm'){
// The middle of the array
start = (nsize / 2);
} else if (startLoc == 'e') {
// End of the array
start = nsize - 1;
} else {
std::cout << "Invalid entry! Exiting..." << std::endl;
exit(0);
}
for (int i=0; i<nsize; i++) {
array.push_back(0);
}
array[start] = 1;
// TODO This can be done so much better...
pattern.push_back("111");
pattern.push_back("110");
pattern.push_back("101");
pattern.push_back("100");
pattern.push_back("011");
pattern.push_back("010");
pattern.push_back("001");
pattern.push_back("000");
for (int i=0; i < pattern.size(); i++) {
int input;
std::cout << "What is the rule for " << pattern[i] << "(0/1): ";
std::cin >> input;
if (input > 1) {
std::cout << "Invalid entry! Exiting..." << std::endl;
exit(0);
}
state.push_back(input);
}
}
void oneDimArray::calculateNext ()
{
std::vector <int> narray (size, 0);
for (int i=1; i < array.size()-1; i++) {
std::string cellL = std::to_string(array[i-1]);
std::string cellM = std::to_string(array[i]);
std::string cellH = std::to_string(array[i+1]);
std::string cell = cellL + cellM + cellH;
for (int j=0; j < pattern.size(); j++) {
int pattL = pattern[j][0];
int pattM = pattern[j][1];
int pattH = pattern[j][2];
if (cell == pattern[j]) {
narray[i] = state[j];
break;
}
}
}
array = narray;
}
void oneDimArray::printArray () const
{
for (int i=1; i < array.size()-1; i++) {
std::cout << array[i];
}
std::cout << std::endl;
}
void oneDimArray::printPretty () const
{
for (int i=1; i< array.size()-1; i++) {
if (array[i] == 0) {
std::cout << ' ';
} else {
std::cout << '*';
}
}
std::cout << std::endl;
}
int main ()
{
std::string istr;
int size;
int printSize;
std::cout << "Input one dimensional array size (type 80 if in doubt): "
<< std::endl;
std::getline (std::cin, istr);
size = std::stoi (istr);
oneDimArray cells (size);
if (cells.getStartLoc() == 'm') {
printSize = size / 2;
} else {
printSize = size;
}
cells.printPretty();
for (int i=0; i < printSize; i++) {
cells.calculateNext();
cells.printPretty();
}
return 0;
}
|
JavaScript
|
UTF-8
| 4,552
| 3.203125
| 3
|
[] |
no_license
|
// <⚠️ DONT DELETE THIS ⚠️>
import "./styles.css";
// <⚠️ /DONT DELETE THIS ⚠️>
const KEYLISTPENDING = "PENDING";
const KEYLISTFINISHED = "FINISHED";
let listPending = [];
let listFinished = [];
const formAddTask = document.querySelector(".form-add-task");
const inputAddTask = document.querySelector("input");
const ulListPending = document.querySelector(".content__list-pending-items");
const ulListFinished = document.querySelector(".content__list-finished-items");
/////////////////////////
// Handle Function
////////////////////////
function handleSubmit(event) {
event.preventDefault();
const inputValue = inputAddTask.value;
const objKeyValue = generateItem(inputValue, "pending");
if (inputValue === "") {
return;
}
listPending.push(objKeyValue);
saveToLocalStorage(KEYLISTPENDING, listPending);
drawItem(objKeyValue, "pending");
inputAddTask.value = null;
}
function handleDelBtn(event) {
const btn = event.target;
const li = btn.parentNode;
const infoLi = li.id.split("-");
li.remove();
if (infoLi[0] === "pending") {
listPending = listPending.filter(
(item) => item.id !== parseInt(infoLi[1], 10)
);
saveToLocalStorage(KEYLISTPENDING, listPending);
} else if (infoLi[0] === "finished") {
listFinished = listFinished.filter(
(item) => item.id !== parseInt(infoLi[1], 10)
);
saveToLocalStorage(KEYLISTFINISHED, listFinished);
}
}
function handleDoneBtn(event) {
const btn = event.target;
const li = btn.parentNode;
const infoLi = li.id.split("-");
const text = li.querySelector("span").innerText;
li.remove();
listPending = listPending.filter(
(item) => item.id !== parseInt(infoLi[1], 10)
);
saveToLocalStorage(KEYLISTPENDING, listPending);
const objKeyValue = generateItem(text, "finished");
listFinished.push(objKeyValue);
saveToLocalStorage(KEYLISTFINISHED, listFinished);
drawItem(objKeyValue, "finished");
}
function handleRedoBtn(event) {
const btn = event.target;
const li = btn.parentNode;
const infoLi = li.id.split("-");
const text = li.querySelector("span").innerText;
li.remove();
listFinished = listFinished.filter(
(item) => item.id !== parseInt(infoLi[1], 10)
);
saveToLocalStorage(KEYLISTFINISHED, listFinished);
const objKeyValue = generateItem(text, "pending");
listPending.push(objKeyValue);
saveToLocalStorage(KEYLISTPENDING, listPending);
drawItem(objKeyValue, "pending");
}
/////////////////////////
// UTIL
/////////////////////////
function generateItem(text, type) {
let listItem = [];
let lastId = -1;
if (type === "pending") {
listItem = listPending;
} else if (type === "finished") {
listItem = listFinished;
}
if (listItem.length > 0) {
lastId = listItem[listItem.length - 1].id;
} else {
lastId = -1;
}
const objKeyValue = {
id: lastId + 1,
text: text,
};
return objKeyValue;
}
function drawItem(item, type) {
const li = document.createElement("li");
const span = document.createElement("span");
const btn1 = document.createElement("button");
const btn2 = document.createElement("button");
span.innerText = item.text;
btn1.innerText = "❌";
btn1.addEventListener("click", handleDelBtn);
if (type === "pending") {
btn2.innerText = "✅";
btn2.addEventListener("click", handleDoneBtn);
} else if (type === "finished") {
btn2.innerText = "↩️";
btn2.addEventListener("click", handleRedoBtn);
}
li.appendChild(span);
li.appendChild(btn1);
li.appendChild(btn2);
li.id = type + "-" + item.id;
if (type === "pending") {
ulListPending.appendChild(li);
} else if (type === "finished") {
ulListFinished.appendChild(li);
}
}
function drawItems(items, type) {
if (items !== null) {
for (let i = 0; i < items.length; i++) {
drawItem(items[i], type);
}
}
}
/////////////////////////
// UTIL LOCALSTORAGE
/////////////////////////
function saveToLocalStorage(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function loadFromLocalStorage(key) {
const listItems = localStorage.getItem(key);
if (listItems !== null) {
const parsedListItems = JSON.parse(listItems);
return parsedListItems;
} else {
return [];
}
}
function init() {
listPending = loadFromLocalStorage(KEYLISTPENDING);
listFinished = loadFromLocalStorage(KEYLISTFINISHED);
drawItems(listPending, "pending");
drawItems(listFinished, "finished");
}
formAddTask.addEventListener("submit", handleSubmit);
init();
|
Java
|
UTF-8
| 4,782
| 1.859375
| 2
|
[] |
no_license
|
/* *********************************************************************** *
* project: org.matsim.*
* Controler.java
* *
* *********************************************************************** *
* *
* copyright : (C) 2007 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
package org.matsim.contrib.drt.analysis.zonal;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.function.Consumer;
import org.matsim.api.core.v01.Coord;
import org.matsim.contrib.drt.schedule.DrtStayTask;
import org.matsim.contrib.dvrp.vrpagent.AbstractTaskEvent;
import org.matsim.contrib.dvrp.vrpagent.TaskEndedEvent;
import org.matsim.contrib.dvrp.vrpagent.TaskEndedEventHandler;
import org.matsim.contrib.dvrp.vrpagent.TaskStartedEvent;
import org.matsim.contrib.dvrp.vrpagent.TaskStartedEventHandler;
import org.matsim.core.controler.MatsimServices;
import org.matsim.core.controler.events.IterationEndsEvent;
import org.matsim.core.controler.listener.IterationEndsListener;
import org.matsim.core.utils.collections.Tuple;
import com.opencsv.CSVWriter;
public class ZonalIdleVehicleXYVisualiser
implements TaskStartedEventHandler, TaskEndedEventHandler, IterationEndsListener {
private final String mode;
private final DrtZonalSystem zonalSystem;
private final MatsimServices services;
private final Map<DrtZone, LinkedList<Tuple<Double, Integer>>> zoneEntries = new LinkedHashMap<>();
public ZonalIdleVehicleXYVisualiser(MatsimServices services, String mode, DrtZonalSystem zonalSystem) {
this.services = services;
this.mode = mode;
this.zonalSystem = zonalSystem;
initEntryMap();
}
private void initEntryMap() {
for (DrtZone z : zonalSystem.getZones().values()) {
LinkedList<Tuple<Double, Integer>> list = new LinkedList<>();
list.add(new Tuple<>(0d, 0));
zoneEntries.put(z, list);
}
}
@Override
public void handleEvent(TaskStartedEvent event) {
handleEvent(event, zone -> {
LinkedList<Tuple<Double, Integer>> zoneTuples = zoneEntries.get(zone);
Integer oldNrOfVeh = zoneTuples.getLast().getSecond();
zoneTuples.add(new Tuple<>(event.getTime(), oldNrOfVeh + 1));
});
}
@Override
public void handleEvent(TaskEndedEvent event) {
handleEvent(event, zone -> {
LinkedList<Tuple<Double, Integer>> zoneTuples = zoneEntries.get(zone);
Integer oldNrOfVeh = zoneTuples.getLast().getSecond();
zoneTuples.add(new Tuple<>(event.getTime(), oldNrOfVeh - 1));
});
}
private void handleEvent(AbstractTaskEvent event, Consumer<DrtZone> handler) {
if (event.getDvrpMode().equals(mode) && event.getTaskType().equals(DrtStayTask.TYPE)) {
DrtZone zone = zonalSystem.getZoneForLinkId(event.getLinkId());
if (zone != null) {
handler.accept(zone);
}
}
}
@Override
public void notifyIterationEnds(IterationEndsEvent event) {
String filename = services.getControlerIO()
.getIterationFilename(services.getIterationNumber(), mode + "_idleVehiclesPerZoneXY.csv");
try {
CSVWriter writer = new CSVWriter(Files.newBufferedWriter(Paths.get(filename)), ';', '"', '"', "\n");
writer.writeNext(new String[] { "zone", "X", "Y", "time", "idleDRTVehicles" }, false);
this.zoneEntries.forEach((zone, entriesList) -> {
Coord c = zone.getCentroid();
entriesList.forEach(entry -> writer.writeNext(
new String[] { zone.getId(), "" + c.getX(), "" + c.getY(), "" + entry.getFirst(),
"" + entry.getSecond() }, false));
});
writer.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
@Override
public void reset(int iteration) {
initEntryMap();
}
}
|
Java
|
UTF-8
| 847
| 2.65625
| 3
|
[] |
no_license
|
package com.opdapp.model;
import javax.persistence.*;
@Entity
public class Strength {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int strengthId;
@ManyToOne
@JoinColumn(name = "unitId")
private StrengthUnit strengthUnit;
private double strengthAmount;
public StrengthUnit getStrengthUnit() {
return strengthUnit;
}
public void setStrengthUnit(StrengthUnit strengthUnit) {
this.strengthUnit = strengthUnit;
}
public int getStrengthId() {
return strengthId;
}
public void setStrengthId(int strengthId) {
this.strengthId = strengthId;
}
public double getStrengthAmount() {
return strengthAmount;
}
public void setStrengthAmount(double strengthAmount) {
this.strengthAmount = strengthAmount;
}
}
|
C#
|
UTF-8
| 1,253
| 3.546875
| 4
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace LeetCode.Leets
{
class LevelOrderBottomSln : ISolution
{
public IList<IList<int>> LevelOrderBottom(TreeNode root)
{
IList<IList<int>> result = new List<IList<int>>();
if (root == null) return result;
int level = 0;
Dfs(root, level, ref result);
return result.Reverse().ToList();
}
public void Dfs(TreeNode root, int level, ref IList<IList<int>> result)
{
if (root == null) return;
if (result.Count == level)
{
result.Add(new List<int>());
}
result[level].Add(root.val);
Dfs(root.left, level+1, ref result);
Dfs(root.right, level+1, ref result);
}
public void Execute()
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2)
{
left = new TreeNode(4),
right = new TreeNode(5)
};
root.right = new TreeNode(3)
{
};
LevelOrderBottom(root);
Console.WriteLine("Hell!");
}
}
}
|
Java
|
UTF-8
| 847
| 2.171875
| 2
|
[] |
no_license
|
package com.nuts.demo.password;
import com.nuts.framework.PlatformAPI;
import com.nuts.framework.base.Response;
import com.nuts.framework.exception.UserInfoException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* Created by hsha on 2018/3/30 13:40
*/
@Controller
@RequestMapping("/password")
public class PasswordController{
/**
* 修改密码的demo
* @param oldPass 旧密码
* @param newPass 新密码
* @return
*/
@PutMapping
@ResponseBody
public Response modify(@RequestParam String oldPass, @RequestParam String newPass){
try{
PlatformAPI.changeUserPassword(oldPass,newPass);
return Response.ok();
}catch(UserInfoException e){
return Response.error(e.getMessage());
}
}
}
|
JavaScript
|
UTF-8
| 3,618
| 2.53125
| 3
|
[] |
no_license
|
/* eslint-disable no-unused-vars */
import './contact.css';
import React, { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faPhone, faEnvelope } from '@fortawesome/free-solid-svg-icons'
import { useForm } from 'react-hook-form';
const encode = (data) => {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&");
}
export function Contact () {
const { register, handleSubmit, errors } = useForm();
const [notification, setNotification] = useState('');
const [submitted, setSubmitted] = useState(false);
const onSubmit = data => {
//alert(JSON.stringify(data));
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": "contact", ...data })
})
.then(() => {
setNotification("Your message has been sent")
setSubmitted(true)
})
.catch(error => setNotification("Form Submission Failed!"));
};
return (
<div className='content'>
<div className='backgroundImage'>
<div className='contact' id='contact'>
<h3><FontAwesomeIcon icon={faEnvelope} /> Get in touch</h3>
<p>Contact via <FontAwesomeIcon icon={faPhone} />{' '}
<span className='iconify' data-icon='fa-whatsapp' data-inline='false'/>{' '}+49(0)1737586025</p>
<p>or message me directly:</p>
<h2>{notification}</h2>
{!submitted ? <form name="contact"
method="POST"
action="/thank-you"
data-netlify="true"
data-netlify-honeypot="bot-field"
onSubmit={handleSubmit(onSubmit)}>
<input type="hidden" name="contact" value="contact" />
<div className="form-control">
<label>Name {errors.name && <span>This field is required</span>}</label>
<input type="text" name="name" ref={register({ required: true})} />
</div>
<div className="form-control">
<label>Email { errors.email && <span>Please enter a valid email</span>}</label>
<input type="text" name="email" ref={register({
required: true,
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: "invalid email address"
}
})} />
</div>
<div className="form-control">
<label>Level {errors.level && <span>Select your level</span>}</label>
<select name="level" ref={register({ required: true })}>
<option value=""></option>
<option value="Beginner">Beginner</option>
<option value="Intermediate">Intermediate</option>
<option value="Advanced">Advanced</option>
</select>
</div>
<div className="form-control">
<label>Message {errors.message && <span>This field is required</span>}</label>
<textarea type="text" name="message" ref={register({ required: true})} />
</div>
<input type="hidden" name="form-name" value="contactForm" />
<div className="form-control">
<label></label>
<p className="screen-reader-text">
<label>Leave empty if you are human <input name="bot-field" /></label>
</p>
<button type="submit">Send</button>
</div>
</form> : <h1>Thank you!</h1> }
</div>
</div>
</div>
);
}
|
Markdown
|
UTF-8
| 2,508
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
---
title: "Oruxmaps - 地圖、行跡、GPS,一手搞定"
date: "2019-12-06"
permalink: "2019-12-06-ourxmaps"
---
# Oruxmaps - 地圖、行跡、GPS,一手搞定

> 本教學僅適用 android 手機喔~
嗨大家,今天來跟大家推薦登山的新好伙伴 -- Oruxmpas
大家是否曾在山上拿著手上的地圖、指北針、GPS 看著遠方並思索著:
- 我已經印了 10 張 A4 的地圖了,為什麼還是看不到對面的山頭是什麼!!
- 探勘掏出 GPS 還要跟地圖來個交叉比對三百回合!!
- 地圖上的行跡檔跟等高線每次都被紅筆跟綠筆劃過去根本看不出小地形!!
以上症狀,~~請打 0800~~ Oruxmpas 都可以在你的手機上一次解決!
:::warning
**使用手機 GPS 登山前,請先確認以下事項:**
- 有基本紙本地圖的定位能力
- 手機及 GPS 正常運作
- 電源充足(行動電源)
- 正確的航跡(本教學會提及)
- 離線圖地(本教學會提及)
:::
## 介紹篇 - 什麼是 Oruxmaps?
Oruxmpas 簡單來說就是一個自訂性非常高的地圖軟體,從地圖、導航、行跡等等都可以自己設定,意思是你想要拿他來開車、慢跑、爬山、旅遊、騎單車、尋寶都可以用上他。當然今天的重點就是在把 Oruxmpas 弄成~~你的~~登山的形狀。

讓大家欣賞一下,這就是登山的形狀。你看看那精美的地形陰影,可以放大到你阿嬤都看的到的等高線以及幫你標上速度顏色的行跡檔,實在太方便啦!
## 設定篇 - 來吧,讓 Oruxmaps 進來到我的手機裡面吧
要能夠讓 Oruxmaps 在山上派上用場需要準備三個東西:
- Oruxmaps 主程式與設定
- 離線地圖檔
- 你要走的路線行跡
### Oruxmaps 主程式
Oruxmaps 本來在 google play 上面是免費的,可是因為違反了 google play 的法規,所以在 google play 只能找到[捐款版](https://play.google.com/store/apps/details?id=com.orux.oruxmapsDonate&hl=zh_TW),而免費版本可以在[官網](www.oruxmaps.com)上面免費下載
www.oruxmaps.com

點上面的 Current version 就可以免費載到了!
> Oruxmaps 捐款版跟免費版功能一模一樣,免費版一點廣告都沒有,意思是開發者們沒有任何收入來源,如果覺得對你很有幫助就考慮捐款吧!
把載下來的 apk 檔安裝好我們就可以進到下一步囉
|
Python
|
UTF-8
| 1,137
| 4
| 4
|
[] |
no_license
|
# a nicer implementation
def mergeSort(array):
"""
mergesort
O(n log n) - time complexity
O(n) - space complexity
"""
# base case
if len(array) <= 1:
return array
# get midpoint
midpoint = len(array)//2
# split left and right half of array call recursively
left = mergeSort(array[:midpoint])
right = mergeSort(array[midpoint:])
return merge(left, right)
def merge(left, right):
"""Merge two sorted arrays"""
result = []
leftPointer = rightPointer = 0
# when there are elements in both arrays
while leftPointer < len(left) and rightPointer < len(right):
# which array has the biggest element
if left[leftPointer] < right[rightPointer]:
result.append(left[leftPointer])
leftPointer += 1
else:
result.append(right[rightPointer])
rightPointer += 1
# append the ends
result.extend(left[leftPointer:])
result.extend(right[rightPointer:])
return result
sequence = [3, 6, 1, 5, 3, 6,4, 234, 0, -4, -45, 8, 29, 1, 93, 4.5]
print(f'Merge-sort {mergeSort(sequence)}')
|
C
|
UTF-8
| 634
| 3.078125
| 3
|
[] |
no_license
|
#include "math.h"
#include "stdio.h"
#include "8slgq.c"
main()
{
int i, j;
double u, v, w;
double x[11], y[11], z[11][11];
for (i = 0; i <= 10; i++) {
x[i] = 0.1 * i;
y[i] = x[i];
}
for (i = 0; i <= 10; i++)
for (j = 0; j <= 10; j++) {
z[i][j] = exp(-(x[i] - y[j]));
}
printf("\n");
u = 0.35;
v = 0.65;
w = slgq(x, y, z, 11, 11, u, v);
printf("x=%7.3f, y=%7.3f, z(x,y)=%13.5e\n", u, v, w);
u = 0.45;
v = 0.55;
w = slgq(x, y, z, 11, 11, u, v);
printf("x=%7.3f, y=%7.3f, z(x,y)=%13.5e\n", u, v, w);
printf("\n");
}
|
Java
|
UTF-8
| 417
| 1.703125
| 2
|
[] |
no_license
|
package com.tohier.cartercoin.listener;
import com.tohier.cartercoin.bean.UserShareOptionRanking;
import java.util.ArrayList;
/**
* Created by Administrator on 2016/12/8.
*/
public interface ShareOptionRankingListener {
void successRanking(ArrayList<UserShareOptionRanking> list);
void fail(String msg);
void successSelfRanking(UserShareOptionRanking userShareOptionRanking);
}
|
Java
|
UTF-8
| 719
| 2.046875
| 2
|
[] |
no_license
|
package com.bosch.ubk.test.sample.host.internal.api.impl;
import org.junit.Assert;
import org.junit.Test;
public class LongRunningLRuntimeImplTest {
@Test
public void hardToTest() {
LongRunningRuntimeImplUncleaned testObj = new LongRunningRuntimeImplUncleaned();
Assert.assertNotNull(testObj.getPath());
}
@Test
public void cleanerCodeVariantIsSimplerToConfigTest() {
String pathToAnywhare = "path/to/anywhere/";
LongRunningLRuntimeImpl testObj = new LongRunningLRuntimeImpl(pathToAnywhare);
String expectedResult = testObj.getPath();
String actualResult = LongRunningLRuntimeImpl.concatPrefixBeforeConstantPathSuffix(pathToAnywhare);
Assert.assertEquals(expectedResult, actualResult);
}
}
|
Java
|
UHC
| 411
| 3.234375
| 3
|
[] |
no_license
|
package chapter14;
import java.util.Scanner;
public class NumberEx2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
System.out.println("ڸ Էϼ.");
//ڰ Ƿ ȯ Ұ Էϸ
int input = s.nextInt();
System.out.println(input);
}
}
|
Markdown
|
UTF-8
| 1,345
| 2.609375
| 3
|
[] |
no_license
|
# Toscana
Data source: https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-json/dpc-covid19-ita-regioni.json
Delta days analysis (j): 12
Analyses for other values of j for 2020-04-15 are avalable [here](../2020-04-15/README.md)
Analyses for Toscana for previous dates are avalable [here](../README.md)
## Fitting
|fit type|best fit equation|tafe|tfe|ipeak|izero|
|-------|-----|--------|------|---|---|
|exp|y = 1.5701 exp(-0.0239x) [TAFE=0.0949]|0.0949|0.0057|19|n/a|
|pow|y = 1.7245 x pow(-0.1495) [TAFE=0.0696]|0.0696|0.0034|39|n/a|

## Data
|Date|Daily deaths|Cumulated deaths|Deaths in the last 12 days|Deaths in the 12 days before|ratio|
|----|----------|-----------|-------|--------------------|-----|
|2020-04-15|18|556|266|199|1.3367|
|2020-04-14|20|538|270|196|1.3776|
|2020-04-13|23|518|265|206|1.2864|
|2020-04-12|28|495|251|206|1.2184|
|2020-04-11|13|467|236|209|1.1292|
|2020-04-10|46|454|239|198|1.2071|
|2020-04-09|16|408|210|184|1.1413|
|2020-04-08|23|392|215|169|1.2722|
|2020-04-07|19|369|211|152|1.3882|
|2020-04-06|25|350|208|137|1.5182|
|2020-04-05|18|325|196|124|1.5806|
|2020-04-04|17|307|198|108|1.8333|
[Download data as CSV](COVID-19_toscana_j12_2020-04-15.csv)
Generated April 19th, 2020 at 18:42:39 UTC+0200 with https://github.com/robianc/COVID-19
|
Java
|
UTF-8
| 1,364
| 2.53125
| 3
|
[] |
no_license
|
package com.crane.instafoll.machine.states;
import com.crane.instafoll.machine.Machine;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.telegram.telegrambots.meta.api.objects.Update;
import static com.crane.instafoll.Bot.getUserName;
import static com.crane.instafoll.machine.states.HandleMenuState.menuOptions;
@Slf4j
@RequiredArgsConstructor
public abstract class State {
public static final String RESTART = "restart";
public final Machine machine;
public abstract String getStateName();
protected abstract void doProcess(Update update);
public void process(Update update) {
log.info(String.format("%s's machine in: %s", getUserName(update), getStateName()));
if (machine.getMessageTest(update).equalsIgnoreCase(RESTART)) {
machine.changeStateTo(new HelloState(machine));
}
doProcess(update);
}
protected void relogin(Update update) {
machine.sendResponse(update, "Enter you login:");
machine.changeStateTo(new GetLoginState(machine));
}
protected void renderMenu(Update update) {
machine.sendResponse(update,
String.format("***Menu***\n%s",
String.join("\n", menuOptions)
)
);
machine.changeStateTo(new HandleMenuState(machine));
}
}
|
Python
|
UTF-8
| 253
| 2.9375
| 3
|
[] |
no_license
|
A, B, C, X, Y = map(int, input().split())
best = 10**9
for c in range(max(X, Y)*2+1):
a = X-c
b = Y-c
if a < 0:
a = 0
if b < 0:
b = 0
p = A*a + B*b + C*c*2
if p < best:
best = p
print(best)
|
Python
|
UTF-8
| 299
| 3.109375
| 3
|
[] |
no_license
|
import random
def select_random_sample(count):
random_indices = random.sample(range(0, income.shape[0]), count)
return income.iloc[random_indices]
random.seed(1)
random_sample = [select_random_sample(100)["median_income"].mean() for _ in range(1000)]
plt.hist(random_sample, 20)
plt.show()
|
PHP
|
UTF-8
| 1,098
| 2.734375
| 3
|
[] |
no_license
|
<?php
include "class.phpmailer.php";
// require_once('/home/appuser/php_lib/class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "smtp.optus.com.au"; // SMTP server
$mail->Port = 25; // set the SMTP port
$mail->SetFrom('peter.tan@optus.net.au', 'Peter Tan');
$mail->AddAddress('peter.tan@optus.net.au', 'Peter Tan');
$mail->Subject = 'PHPMailer Test';
$mail->AddEmbeddedImage("Optus-AU.png", "my-attach", "Optus-AU.png");
$mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';
$mail->IsHTML(true);
// $mail->AddAttachment('testRunApp.html'); // this is a regular attachment (Not inline)
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e)
{
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e)
{
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
|
JavaScript
|
UTF-8
| 3,344
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
const areaList = [{
name: '广东省',
id: 1,
parentId: 0
}, {
name: '广州市',
id: 2,
parentId: 1
}, {
name: '花都区',
id: 3,
parentId: 2
}, {
name: '白云区',
id: 4,
parentId: 2
}, {
name: '天河区',
id: 5,
parentId: 2
}, {
name: '从化区',
id: 6,
parentId: 2
}, {
name: '黄浦区',
id: 7,
parentId: 2
}]
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
multiArray: [],
multiIndex: [0, 0, 0],
province: []
},
/**
* 组件生命周期
*/
attached() {
const province = areaList.filter(item => item.parentId == 0)
const city = areaList.filter(item => item.parentId == province[0].id)
const area = areaList.filter(item => item.parentId == city[0].id)
const provinceList = province.map(item => item.name)
const cityList = city.map(item => item.name)
const regionList = area.map(item => item.name)
this.setData({
province: province,
multiArray: [provinceList, cityList, regionList]
})
},
/**
* 组件的方法列表
*/
methods: {
bindMultiPickerChange: function (e) {
const that = this
this.setData({
multiIndex: that.data.multiIndex
})
this.triggerEvent('pickerChange', {
region: this.data.multiArray[0][this.data.multiIndex[0]] + ' ' + this.data.multiArray[1][this.data.multiIndex[1]] + ' ' + this.data.multiArray[2][this.data.multiIndex[2]]
})
},
bindMultiPickerColumnChange: function (e) {
const that = this
this.data.multiIndex[e.detail.column] = e.detail.value
const provinceName = this.data.multiArray[0][this.data.multiIndex[0]]
let provinceId = ''
let regionList = [],
cityList = [],
provinceList = [],
city = [],
area = []
try {
this.data.province.forEach(item => {
if (item.name === provinceName) {
provinceId = item.id
throw (new Error('find item'))
}
})
} catch (err) {}
city = areaList.filter(item => {
return item.parentId == provinceId
})
if (e.detail.column == 0) {
this.data.multiIndex = [e.detail.value, 0, 0]
try {
area = areaList.filter(item => {
return item.parentId == city[this.data.multiIndex[1]].id
})
} catch (err) {}
} else if (e.detail.column == 1) {
this.data.multiIndex[2] = 0
area = areaList.filter(item => {
return item.parentId == city[e.detail.value].id
})
} else {
const cityName = this.data.multiArray[1][this.data.multiIndex[1]]
let cityId = ''
try {
areaList.forEach(item => {
if (item.name === cityName) {
cityId = item.id
throw (new Error('find item'))
}
})
} catch (err) {}
area = areaList.filter(item => {
return item.parentId == cityId
})
}
provinceList = this.data.province.map(item => item.name)
cityList = city.map(item => item.name)
regionList = area.map(item => item.name)
this.setData({
multiArray: [provinceList, cityList, regionList],
multiIndex: that.data.multiIndex
})
}
}
})
|
PHP
|
UTF-8
| 1,534
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Console\Commands;
use App\Customer;
use App\Loan;
use App\LoanSchedule;
use App\Notifications\LoanAdvice;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Notifications\Notifiable;
class EmailAdvice extends Command
{
use Notifiable;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'email:advice';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Advice clients five days before applying penalty fees to their loans';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
try {
$date = Carbon::now()->addDays(5)->format('Y-m-d');
$schedules = LoanSchedule::query()->where('end_date', '<=', $date)->where('status', false)->get();
foreach ($schedules as $schedule) {
$loan = Loan::query()->where('loan_id', $schedule->loan_id)->first();
$customer = Customer::query()->where('national_id', $loan->client_id)->first();
$cust = new Customer();
$cust->email = $customer->email;
$cust->notify(new LoanAdvice($customer, $schedule));
}
}
catch (\Exception $exception){
}
}
}
|
Markdown
|
UTF-8
| 1,845
| 2.71875
| 3
|
[] |
no_license
|
# 스프링프레임워크 공부 기록
✅ 인프런 강좌를 듣고 배운 내용을 요약, 정리하고 있습니다.
✅ 스프링 프레임워크, 스프링부트, JPA를 활용한 개발 내용을 포함하고 있습니다.
## 1. 스프링 핵심 원리 기본편
👉 출처 : [스프링 핵심 원리 - 기본편 (김영한) ](https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B8%B0%EB%B3%B8%ED%8E%B8/)
> 스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 다집니다.
## 2. 스프링 프레임워크 핵심 기술
👉 출처 : [스프링 프레임워크 핵심기술 (백기선)](https://www.inflearn.com/course/spring-framework_core/)
> 스프링 부트를 사용하여 스프링 핵심 기술을 학습합니다.
>
> 스프링 부트가 제공하는 여러 기능이 스프링의 핵심 기술과 어떻게 관련이 있는지 이해합니다.
## 3. 스프링 부트 개념과 활용
👉 출처 : [스프링부트 개념과 활용 (백기선)](https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8)
> 스프링부트의 핵심 원리에 대해 설명합니다.
>
> 스프링 부트가 제공하는 여러 기능을 ‘핵심 기능’과 ‘기술 연동’으로 나누어 설명합니다.
## 4. 스프링 웹 MVC
👉 출처 : [스프링 웹 MVC (백기선)](https://www.inflearn.com/course/%EC%9B%B9-mvc/)
> 자바 서블릿(Servlet) 기반의 MVC 프레임워크인 스프링 웹 MVC에 대해 학습합니다.
## 5. IntelliJ 가이드
👉 출처 : [IntelliJ를 시작하시는 분들을 위한 IntelliJ 가이드 (이동욱)](https://www.inflearn.com/course/intellij-guide/)
> IntelliJ 기반의 IDE에서 모두 사용가능한 기본 사용법을 익힙니다.
|
Markdown
|
UTF-8
| 5,021
| 3.140625
| 3
|
[] |
no_license
|
### CST356 Week 5 Lab - Rachel Soderberg
##### Exercise 1
###### 1. Create a new MVC project for this lab. Copy code from last week's lab as a starting point.
###### 2. Create a separate “repository” class with an associated interface for storing data in the database. Unlike the example, for the lab you can use a single repository class for both of your entities.
###### 3. Create an instance of the database context class in the constructor of your new “repository” class.
###### 4. Replace the reference to the database context in each of your controllers with a reference to the new “repository” class. Create an instance of the “repository class” in the constructor of each controller.
###### 5. Add methods to the “repository” interface and class that implement all of the database needs of your controllers.
###### 6. Move the code in the controllers that implements the calls to the database context to the methods in the new “repository class”.
###### 7. Add calls to the “repository” class methods in the controllers to satisfy their data access requirements.
###### 8. Run the application to test to see if you can still successfully apply each of the operations (list, create, view details, edit and delete) to each of the entities.
##### Exercise 2
###### 1. Install the SimpleInjector NuGet package.
###### 2. Add the code needed to configure dependency injection for the “repository” class. See Global.asax and DependencyInjectionConfig.cs in the Week5.WebApp1 example.
###### 3. Replace the creation of the “repository” class in each of the controllers with the injection of the “repository” class via a constructor in each controller.
###### 4. Run the application to test to see if you can still successfully apply each of the operations (list, create, view details, edit and delete) to each of the entities.
##### Exercise 3
###### 1. Create a service class with an interface for your second entity (the entity you created in the last lab).
###### 2. Add the code needed to configure dependency injection for the “service” class.
###### 3. Make the new service class serve the purpose of retrieving and sending the entity's data required by the related controller.
###### - Add methods to the new service for all the data needs of the controller.
###### - Inject the DbContext into the repository class instead of creating an instance in the repository constructor. You'll need to add the code needed to configure the dependency injection of your DbContext derived class.
###### - Inject the related repository class into the service class.
###### - Inject the service class into the related controller class.
###### - Call the methods on the service class in the controller to retrieve and save data.
###### 4. Run the application to test to see if you can still successfully apply each of the operations (list, create, view details, edit and delete) to each of the entities.
##### Exercise 4
###### 1. Add a method on the service to perform some "business rule logic" related to your entity that uses data in an instance of the entity.
###### 2. Call the service class method created in step 4 when the action for displaying the details of the entity is invoked.
###### 3. Display the results of the call to the service method in the entity’s detail view. Pass the result to the "details view" via the entity's view model.
###### 4. Run the application to test to see if the new "detail" based on the result of the service call is displayed correctly.
###### 5. Briefly explain what dependency injection is and why it is beneficial.
With dependency injection, the dependencies (services) of an object are supplied by another object. When the service is passed to the dependent object, it is called "injection." The benefit of dependency injection is simplicity: the client code does not need to be changed if there are changes to an object it depends on.
##### Exercise 5
###### 1. Create new project in your solution for unit tests.
###### 2. Install the following NuGet packages in your new "test" project:
###### - NUnit
###### - NUnit3TestAdapter
###### - FakeItEasy
###### 3. Create one or more unit tests to test the result of calling the "Business logic" service method. You'll need to create a fake/mock repository to control what data the service class gets when you run the test. For help, see the unit tests in the Week5.WebApp1 example.
###### 4. Run the unit tests via the Visual Studio test explorer (Test => Windows => Test Explorer). Did the tests succeed. If not, fix the application code or the unit test and rerun the unit tests.
###### 5. Break the service method being tested intentionally and return the unit test(s). You should see at least one unit test fail. Fix the tested service method and return the test. You should see all green now. Time to celebrate!
###### 6. Briefly explain what unit tests are and why they are beneficial?
|
Java
|
UTF-8
| 1,652
| 3.265625
| 3
|
[] |
no_license
|
import com.pi4j.io.gpio.*;
/**
* A class used to check if a bumper has made contact with anthing. It is very similar to Class Button but it uses
* PULL_UP instead of PULL_DOWN.
*
* @author Harry Schneider (HS308)
* @version 1.0
*/
public class Bumper
{
// The bumper instance is an input pin.
private GpioPinDigitalInput bumper;
// This array maps the GPIO pin numbers to ints
private static final Pin[] pinMap = new Pin[] {RaspiPin.GPIO_00, RaspiPin.GPIO_01, RaspiPin.GPIO_02, RaspiPin.GPIO_03, RaspiPin.GPIO_04,
RaspiPin.GPIO_05, RaspiPin.GPIO_06, RaspiPin.GPIO_07, RaspiPin.GPIO_08, RaspiPin.GPIO_09, RaspiPin.GPIO_10,
RaspiPin.GPIO_11, RaspiPin.GPIO_12, RaspiPin.GPIO_13, RaspiPin.GPIO_14, RaspiPin.GPIO_15, RaspiPin.GPIO_16,
RaspiPin.GPIO_17, RaspiPin.GPIO_18, RaspiPin.GPIO_19, RaspiPin.GPIO_20};
// The default pin, used by the constructor without parameters.
private final static int defaultPin = 16;
/**
* Sets the default pins if none are chosen for the constructor.
*/
public Bumper()
{
this(defaultPin);
}
/**
* Constructor for objects of class Bumper. Sets up a pin as an input to be used to check if a bumper is pressed.
*/
public Bumper(int pin)
{
// Get a gpio controller
GpioController gpio = GpioFactory.getInstance();
bumper = gpio.provisionDigitalInputPin(pinMap[pin], PinPullResistance.PULL_UP);
}
/**
* Checks to see if the bumpers is being pressed and returns true if it is.
*/
public boolean isPressed()
{
return bumper.isLow();
}
}
|
SQL
|
UTF-8
| 675
| 3.234375
| 3
|
[] |
no_license
|
drop table if exists house;
drop table if exists house_keeper;
create table if not exists house_keeper (
id varchar (36) primary key,
first_name varchar (255) not null,
last_name varchar (255) not null,
age integer not null,
level integer not null default 1,
status varchar not null default 'ACTIVE'
);
create table if not exists house (
id varchar (36) primary key,
name varchar (255) not null,
capacity integer not null,
object_size varchar (5) not null default 'XS',
status varchar not null default 'ACTIVE',
filled boolean not null default false,
house_keeper_id varchar (36) not null references house_keeper(id)
);
|
TypeScript
|
UTF-8
| 2,662
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
import * as SockJS from 'sockjs-client';
import * as Stomp from 'stompjs/lib/stomp';
interface TokenInfo {
access_token: string
expires_in: number
refresh_token: string
token_type: string
}
function apiFetch(...args) {
let [url, options] = args;
options.credentials = 'same-origin';
options.headers = {
...options.headers,
...getXSRF()
}
return fetch.apply(null, args);
}
function getXSRF() {
let spliter = document.cookie.split('XSRF-TOKEN=');
if (spliter.length > 0) {
return {
['X-XSRF-TOKEN']: spliter[1].split(';')[0]
}
}
return {}
}
function handleToken(response) {
let out: {[key: string]: string} = {};
if (!response.ok) {
return new Promise((resole, reject) => {
response.json().then(json => {
reject(json);
});
})
} else {
out = response
.json()
.then((tokenInfo: TokenInfo) => {
if (tokenInfo && tokenInfo.access_token) {
localStorage.setItem('user', JSON.stringify(tokenInfo));
}
});
}
return out;
}
export const socketService = {
setClient() {
let socket = new SockJS('/wsIn');
this.stompClient = Stomp.Stomp.over(socket);
},
send(...args) {
this.stompClient.send.apply(this.stompClient, args);
},
getClient() {
return this.stompClient;
},
connect(cb: Function) {
this.stompClient.connect(getXSRF(), cb);
},
subscribe(...args) {
this.stompClient.subscribe.apply(this.stompClient, args);
}
}
export const userService = {
info(): Promise<string> {
const rawToken = localStorage.getItem('user')
let token: TokenInfo;
if (rawToken) {
try {
token = JSON.parse(rawToken);
} catch (e) {
}
}
if (!token) {
return Promise.reject('Empty or wrong token');
}
return apiFetch('/users/info', {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token.access_token}`
},
})
.then(response => {
if (response.ok) {
return response.text();
} else {
return response.json()
.then(json => Promise.reject(json));
}
});
},
login(username, password): Promise<Object> {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
};
return apiFetch('/users/authenticate', requestOptions)
.then(handleToken)
.then();
},
logout() {
localStorage.removeItem('user');
},
register(user) {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user)
};
return apiFetch('/users/register', requestOptions)
.then(handleToken);
}
}
|
Java
|
UTF-8
| 1,016
| 1.835938
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 商品咨询信息
*
* @author auto create
* @since 1.0, 2023-01-17 15:17:44
*/
public class ItemConsultInfo extends AlipayObject {
private static final long serialVersionUID = 6728841296971122972L;
/**
* 商品id
*/
@ApiField("item_id")
private String itemId;
/**
* 商品优惠金额,单位为元
*/
@ApiField("promo_amount")
private String promoAmount;
/**
* 商品优惠数量
*/
@ApiField("promo_count")
private String promoCount;
public String getItemId() {
return this.itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getPromoAmount() {
return this.promoAmount;
}
public void setPromoAmount(String promoAmount) {
this.promoAmount = promoAmount;
}
public String getPromoCount() {
return this.promoCount;
}
public void setPromoCount(String promoCount) {
this.promoCount = promoCount;
}
}
|
C#
|
UTF-8
| 1,028
| 3.859375
| 4
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace GenericSwapMethodString
{
public class Launcher
{
public static void Main()
{
int inputStringsCount = int.Parse(Console.ReadLine());
IList<Box<string>> list = new List<Box<string>>();
for (int i = 0; i < inputStringsCount; i++)
{
Box<string> box = new Box<string>(Console.ReadLine());
list.Add(box);
}
int[] indexesToBeSwapped = Console.ReadLine().Split().Select(int.Parse).ToArray();
Swap(list, indexesToBeSwapped[0], indexesToBeSwapped[1]);
foreach (Box<string> box in list)
{
Console.WriteLine(box);
}
}
private static void Swap<T>(IList<T> inputList, int index1, int index2)
{
T tmp = inputList[index1];
inputList[index1] = inputList[index2];
inputList[index2] = tmp;
}
}
}
|
Python
|
UTF-8
| 1,274
| 2.90625
| 3
|
[] |
no_license
|
# A dictionary of movie critics and thier ratings of a small set of movies
critics= { 'Lisa Rose' : {'Lady in the Water' : 2.5,'Snakes on a Plane' : 3.5,'Just My Luck' : 3.0 ,'Superman Returns' : 3.5,
'You,Me and Dupree' : 2.5 , 'The Night Listener' : 3.0},
'Gene Seymour' : { 'Lady in the Water' : 3.0 , 'Snakes on a Plane' : 3.5 ,'Just My Luck' : 1.5 ,'Superman Returns' : 5.0,
'The Night Listener' : 3.0 , 'You,Me and Dupree' : 3.5 },
'Michael Phillips' : { 'Lady in the Water' : 2.5 , 'Snakes on a Plane' : 3.0 , 'Superman Returns' : 3.5,
'The Night Listener' : 4.0 },
'Claudia Puig' : { 'Snakes on a Plane' : 3.5 , 'Just My Luck' : 3.0 , 'The Night Listener' : 4.5 , 'Superman Returns' : 4.0 ,
'You,Me and Dupree' : 2.5 } ,
'Mick LaSalle' : { 'Lady in the Water' : 3.0,'Snakes on a Plane' : 4.0 ,'Just My Luck' : 2.0 ,'Superman Returns' : 3.0,
'You,Me and Dupree' : 2.0 , 'The Night Listener' : 3.0} ,
'Jack Matthews' : { 'Lady in the Water' : 3.0, 'Snakes on a Plane' : 4.0 , 'The Night Listener' : 3.0 , 'Superman Returns' : 5.0,
'You,Me and Dupree' : 3.5 },
'Toby' : { 'Snakes on a Plane' : 4.5 , 'You,Me and Dupree' : 1.0, 'Superman Returns' : 4.0 }
}
|
Swift
|
UTF-8
| 9,007
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// StoreAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
#if canImport(AnyCodable)
import AnyCodable
#endif
open class StoreAPI {
/**
Delete purchase order by ID
- parameter orderId: (path) ID of the order that needs to be deleted
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> RequestTask {
return deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in
switch result {
case .success:
completion((), nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Delete purchase order by ID
- DELETE /store/order/{orderId}
- For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
- parameter orderId: (path) ID of the order that needs to be deleted
- returns: RequestBuilder<Void>
*/
open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder<Void> {
var localVariablePath = "/store/order/{orderId}"
let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))"
let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Void>.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder()
return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
/**
Returns pet inventories by status
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) -> RequestTask {
return getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Returns pet inventories by status
- GET /store/inventory
- Returns a map of status codes to quantities
- API Key:
- type: apiKey api_key (HEADER)
- name: api_key
- returns: RequestBuilder<[String: Int]>
*/
open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> {
let localVariablePath = "/store/inventory"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
}
/**
Find purchase order by ID
- parameter orderId: (path) ID of pet that needs to be fetched
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) -> RequestTask {
return getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Find purchase order by ID
- GET /store/order/{orderId}
- For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions
- parameter orderId: (path) ID of pet that needs to be fetched
- returns: RequestBuilder<Order>
*/
open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder<Order> {
var localVariablePath = "/store/order/{orderId}"
let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))"
let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
localVariablePath = localVariablePath.replacingOccurrences(of: "{orderId}", with: orderIdPostEscape, options: .literal, range: nil)
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters: [String: Any]? = nil
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
/**
Place an order for a pet
- parameter order: (body) order placed for purchasing the pet
- parameter apiResponseQueue: The queue on which api response is dispatched.
- parameter completion: completion handler to receive the data and the error objects
*/
@discardableResult
open class func placeOrder(order: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) -> RequestTask {
return placeOrderWithRequestBuilder(order: order).execute(apiResponseQueue) { result in
switch result {
case let .success(response):
completion(response.body, nil)
case let .failure(error):
completion(nil, error)
}
}
}
/**
Place an order for a pet
- POST /store/order
-
- parameter order: (body) order placed for purchasing the pet
- returns: RequestBuilder<Order>
*/
open class func placeOrderWithRequestBuilder(order: Order) -> RequestBuilder<Order> {
let localVariablePath = "/store/order"
let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath
let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: order)
let localVariableUrlComponents = URLComponents(string: localVariableURLString)
let localVariableNillableHeaders: [String: Any?] = [
:
]
let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
let localVariableRequestBuilder: RequestBuilder<Order>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder()
return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
}
}
|
Java
|
UTF-8
| 988
| 1.882813
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 内部开放给金融云端用于查询pid下面所有小程序的详细信息
*
* @author auto create
* @since 1.0, 2022-09-04 22:04:30
*/
public class AlipayOpenMiniCloudDetailQueryModel extends AlipayObject {
private static final long serialVersionUID = 8748425785346198911L;
/**
* 应用的appid。partner_id和mini_appid不能同时为空。
*/
@ApiField("mini_appid")
private String miniAppid;
/**
* 商户和支付宝交互时,支付宝分配给商户ID。partner_id和mini_appid不能同时为空。
*/
@ApiField("partner_id")
private String partnerId;
public String getMiniAppid() {
return this.miniAppid;
}
public void setMiniAppid(String miniAppid) {
this.miniAppid = miniAppid;
}
public String getPartnerId() {
return this.partnerId;
}
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
}
|
JavaScript
|
UTF-8
| 2,303
| 2.703125
| 3
|
[] |
no_license
|
//使用nodejs 的MySQL库,直接管理MySQL数据库
//2015/12/12 @chaimol
//使用连接池方法连接数据库
var mysql = require('mysql');
var pool = mysql.createPool({
host: '127.0.0.1',
user: 'root',
password: '',
port: '3306',
database: 'phplesson1'
});
pool.getConnection(function(err, connection) {
//查询全部
// connection.query( 'SELECT * FROM lesson1;', function(err, result) {
// console.log(result);
// res.render(result);
// connection.release();
// });
/* //查
connection.query( 'SELECT * FROM lesson1 WHERE newsid=5;', function(err, result) {
console.log(result);
connection.release();
});
//增加
var userAddSql = "INSERT INTO lesson1(`newsid`,`newstitle`,`newstime`,`newscontent`,`newstype`)VALUES('2',?,?,?,?)";
var useADDcontent = ['我是新插入的','2015-1-6','测试测试测试','2'];
connection.query("set names 'utf-8'");
connection.query(userAddSql,useADDcontent,function(err,result){
if(err){
console.log('insert error-',err.message);
return;
}
console.log("insert",result);
connection.release();
});
*/ //改
var userModSql = 'UPDATE lesson1 SET newstitle = ?,newstime=?,newscontent=?,newstype=? WHERE newsid = 5';
var userModSql_Params = ['更新后的内容', '2015-1-1', '我是更新后的', '5'];
connection.query(userModSql, userModSql_Params, function(err, result) {
if (err) {
console.log('[UPDATE ERROR] - ', err.message);
return;
}
connection.release();
});
/* //删
var userDelSql = 'DELETE FROM lesson1 WHERE newsid=2';
connection.query(userDelSql,function (err, result) {
if(err){
console.log('[DELETE ERROR] - ',err.message);
return;
}
console.log('--------------------------DELETE----------------------------');
console.log('DELETE affectedRows',result.affectedRows);
console.log('-----------------------------------------------------------------\n\n');
connection.release();
});
*/
});
//连接池使用示例源码
|
Java
|
UTF-8
| 5,911
| 2.015625
| 2
|
[
"BSD-3-Clause",
"Apache-2.0",
"MPL-2.0"
] |
permissive
|
// *** WARNING: this file was generated by pulumi-java-gen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package com.pulumi.aws.connect.inputs;
import com.pulumi.core.Output;
import com.pulumi.core.annotations.Import;
import java.lang.String;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
public final class GetContactFlowArgs extends com.pulumi.resources.InvokeArgs {
public static final GetContactFlowArgs Empty = new GetContactFlowArgs();
/**
* Returns information on a specific Contact Flow by contact flow id
*
*/
@Import(name="contactFlowId")
private @Nullable Output<String> contactFlowId;
/**
* @return Returns information on a specific Contact Flow by contact flow id
*
*/
public Optional<Output<String>> contactFlowId() {
return Optional.ofNullable(this.contactFlowId);
}
/**
* Reference to the hosting Amazon Connect Instance
*
*/
@Import(name="instanceId", required=true)
private Output<String> instanceId;
/**
* @return Reference to the hosting Amazon Connect Instance
*
*/
public Output<String> instanceId() {
return this.instanceId;
}
/**
* Returns information on a specific Contact Flow by name
*
*/
@Import(name="name")
private @Nullable Output<String> name;
/**
* @return Returns information on a specific Contact Flow by name
*
*/
public Optional<Output<String>> name() {
return Optional.ofNullable(this.name);
}
/**
* Tags to assign to the Contact Flow.
*
*/
@Import(name="tags")
private @Nullable Output<Map<String,String>> tags;
/**
* @return Tags to assign to the Contact Flow.
*
*/
public Optional<Output<Map<String,String>>> tags() {
return Optional.ofNullable(this.tags);
}
/**
* Type of Contact Flow.
*
*/
@Import(name="type")
private @Nullable Output<String> type;
/**
* @return Type of Contact Flow.
*
*/
public Optional<Output<String>> type() {
return Optional.ofNullable(this.type);
}
private GetContactFlowArgs() {}
private GetContactFlowArgs(GetContactFlowArgs $) {
this.contactFlowId = $.contactFlowId;
this.instanceId = $.instanceId;
this.name = $.name;
this.tags = $.tags;
this.type = $.type;
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(GetContactFlowArgs defaults) {
return new Builder(defaults);
}
public static final class Builder {
private GetContactFlowArgs $;
public Builder() {
$ = new GetContactFlowArgs();
}
public Builder(GetContactFlowArgs defaults) {
$ = new GetContactFlowArgs(Objects.requireNonNull(defaults));
}
/**
* @param contactFlowId Returns information on a specific Contact Flow by contact flow id
*
* @return builder
*
*/
public Builder contactFlowId(@Nullable Output<String> contactFlowId) {
$.contactFlowId = contactFlowId;
return this;
}
/**
* @param contactFlowId Returns information on a specific Contact Flow by contact flow id
*
* @return builder
*
*/
public Builder contactFlowId(String contactFlowId) {
return contactFlowId(Output.of(contactFlowId));
}
/**
* @param instanceId Reference to the hosting Amazon Connect Instance
*
* @return builder
*
*/
public Builder instanceId(Output<String> instanceId) {
$.instanceId = instanceId;
return this;
}
/**
* @param instanceId Reference to the hosting Amazon Connect Instance
*
* @return builder
*
*/
public Builder instanceId(String instanceId) {
return instanceId(Output.of(instanceId));
}
/**
* @param name Returns information on a specific Contact Flow by name
*
* @return builder
*
*/
public Builder name(@Nullable Output<String> name) {
$.name = name;
return this;
}
/**
* @param name Returns information on a specific Contact Flow by name
*
* @return builder
*
*/
public Builder name(String name) {
return name(Output.of(name));
}
/**
* @param tags Tags to assign to the Contact Flow.
*
* @return builder
*
*/
public Builder tags(@Nullable Output<Map<String,String>> tags) {
$.tags = tags;
return this;
}
/**
* @param tags Tags to assign to the Contact Flow.
*
* @return builder
*
*/
public Builder tags(Map<String,String> tags) {
return tags(Output.of(tags));
}
/**
* @param type Type of Contact Flow.
*
* @return builder
*
*/
public Builder type(@Nullable Output<String> type) {
$.type = type;
return this;
}
/**
* @param type Type of Contact Flow.
*
* @return builder
*
*/
public Builder type(String type) {
return type(Output.of(type));
}
public GetContactFlowArgs build() {
$.instanceId = Objects.requireNonNull($.instanceId, "expected parameter 'instanceId' to be non-null");
return $;
}
}
}
|
Java
|
UTF-8
| 1,058
| 3.78125
| 4
|
[] |
no_license
|
package algorithm.structs;
/**
* created 4/16/2021 10:34 AM
*
* @author luowen <loovien@163.com>
*/
public class SingleDirectLink {
static class Node {
public Node next;
public String value;
public Node(String value) {
this.value = value;
}
}
public static void main(String[] args) {
Node a = new Node("a");
a.next = new Node("b");
a.next.next = new Node("c");
/*while (a != null) {
System.out.println(a.value);
a = a.next;
}*/
Node rev = rev(a);
System.out.println(rev);
while (rev != null) {
System.out.println(rev.value);
rev = rev.next;
}
}
/**
* a -> b -> c
*
* @param head
* @return
*/
public static Node rev(Node head) {
Node prev = null, next;
while (head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}
|
Python
|
UTF-8
| 8,018
| 2.609375
| 3
|
[] |
no_license
|
import tkinter as tk
from tkinter import *
from tkinter import filedialog
import mysql.connector
from mysql.connector import Error
import tkinter.font as font
import csv
from PIL import ImageTk, Image
from functools import partial
import os
from load_database import load_image_database
import shutil
names = []
def show_photo(i):
small_win = tk.Tk(screenName="Main")
print(names[i])
img = ImageTk.PhotoImage(Image.open("C:\\Users\\dell\\Documents\\python\\Kiran\\photos\\"+names[i]+".jpg"),
master = small_win)
panel = tk.Label(small_win, image = img) #set the image
panel.pack()
small_win.mainloop()
def select_photo(photo_entry):
filename = filedialog.askopenfilename(title ='"pen')
print(filename)
photo_entry.insert(0, filename)
return filename
def insert_into_database(win, insert_win, connection, cursor, id_txt, name, filename):
shutil.copy(filename, 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads')
statement = "insert into persons values("+id_txt+", '"+name+"', load_file('C:\\\\ProgramData\\\\MySQL\\\\MySQL Server 8.0\\\\Uploads\\\\"+name+".jpg'));"
print(statement)
cursor.execute(statement)
connection.commit()
print("Inserted into database")
connection.close()
database(insert_win)
def insert_database(win, connection, cursor):
win.destroy()
insert_win = tk.Tk(screenName = "Insert into Database")
insert_win.geometry("300x250") #You want the size of the app to be 500x500
insert_win.resizable(0, 0) #Don't allow resizing in the x or y direction
insert_win.pack_propagate(0)
title = tk.Label(insert_win, text = "Fill the information", font = "Helvetica 16 bold")
title.place(relx = 0.5, rely = 0.08, anchor = CENTER)
id_label = tk.Label(insert_win, text = "Id :")
id_label.place(relx = 0.2, rely = 0.3, anchor = CENTER)
id_entry = tk.Entry(insert_win, width = 25)
id_entry.place(relx = 0.55, rely = 0.3, anchor = CENTER)
name_label = tk.Label(insert_win, text = "Name :")
name_label.place(relx = 0.2, rely = 0.5, anchor = CENTER)
name_entry = tk.Entry(insert_win, width = 25)
name_entry.place(relx = 0.55, rely = 0.5, anchor = CENTER)
photo_label = tk.Label(insert_win, text = "Photo :")
photo_label.place(relx = 0.2, rely = 0.7, anchor = CENTER)
photo_entry = tk.Entry(insert_win, width = 25)
photo_entry.place(relx = 0.55, rely = 0.7, anchor = CENTER)
select_button = tk.Button(insert_win, text = "Select", command = lambda:select_photo(photo_entry))
select_button.place(relx = 0.9, rely = 0.7, anchor = CENTER)
insert_button = tk.Button(insert_win, text = "Insert",
command = lambda:insert_into_database(win, insert_win,connection, cursor, id_entry.get(),name_entry.get(),photo_entry.get()),
bg = "green", width = 10)
insert_button.place(relx = 0.5, rely = 0.9, anchor = CENTER)
insert_win.mainloop()
def delete_yes(win, connection, del_win, i, cursor):
del_win.destroy()
statement = "Delete from kirancha.persons where Name = '"+names[i]+"'"
print(statement)
cursor.execute(statement)
os.remove("C:\\Users\\dell\\Documents\\python\\Kiran\\photos\\"+names[i]+".jpg")
connection.commit()
connection.close()
suc_win = tk.Tk(screenName="Delete")
suc_win.geometry("200x100") #You want the size of the app to be 500x500
suc_win.resizable(0, 0) #Don't allow resizing in the x or y direction
suc_win.pack_propagate(0)
print(names[i])
txt = tk.Label(suc_win, text = "Deleted Successfully!!")
txt.place(relx = 0.5, rely = 0.2, anchor = CENTER)
no = tk.Button(suc_win, text = "Ok", bg = 'green',
command = lambda: delete_no(suc_win), width = 7)
no.place(relx = 0.5, rely = 0.7, anchor = CENTER)
suc_win.mainloop()
def delete_no(del_win):
database(del_win)
def delete_data(win,connection, i, cursor):
win.destroy()
del_win = tk.Tk(screenName="Delete")
del_win.geometry("200x100") #You want the size of the app to be 500x500
del_win.resizable(0, 0) #Don't allow resizing in the x or y direction
del_win.pack_propagate(0)
print(names[i])
txt = tk.Label(del_win, text = "Do you want to delete??")
txt.place(relx = 0.5, rely = 0.2, anchor = CENTER)
yes = tk.Button(del_win, text = "Yes", bg = 'green',
command = lambda: delete_yes(win, connection, del_win, i, cursor), width = 7)
yes.place(relx = 0.3, rely = 0.7, anchor = CENTER)
no = tk.Button(del_win, text = "No", bg = 'green',
command = lambda: delete_no(del_win), width = 7)
no.place(relx = 0.7, rely = 0.7, anchor = CENTER)
del_win.mainloop()
def database(window):
window.destroy()
win = tk.Tk()
load_image_database()
#heading names for database columns
col_names = ("Id", "Name", "Photo", "Delete Buttons")
button_identity = []
global names
row = 0 #to keep track of the rows
win.title("Datas from the database")
#window.destroy() #destroying previous window
myFont = font.Font(win, family='Helvetica', size=10, weight='bold')
heading = tk.Label(win, text = "Database data") #heading text
heading.grid(row = 0,column = 1)
heading['font'] = myFont
blank = tk.Label(win, text = "") #leave one row
blank.grid(row = 1,column = 1)
#try to develop connection
connection = mysql.connector.connect(
host = 'localhost',
user = 'root',
password = 'rohitkauri123',
auth_plugin='mysql_native_password',
database = 'kirancha')
db_Info = connection.get_server_info() #get the information about the db
print("Connected to mysql database with version ",db_Info)
cursor = connection.cursor() #defining cursor object
cursor.execute("Select * from persons")
myresult = cursor.fetchall() #fetch the returned data;
height = len(myresult)+1 #number of rows + heading
width = len(myresult[0])+1 #number of columns
print(width)
for i in range(height): #Rows
for j in range(width): #Columns
if i == 0:
# for putting headings
b = tk.Label(win, text=col_names[j],
fg = "light green",
bg = "dark green",
width = 20)
b.grid(row=i+1, column=j)
else:
#label for id and name
if j != 2 and j != 3:
b = tk.Label(win, text=myresult[i-1][j], width = 20)
b.grid(row=i+1, column=j)
elif j == 2:
#button for showing photo
show = tk.Button(win, text = "Show Photo",bg = 'yellow',
command = partial(show_photo, i-1), width = 19)
names.append(myresult[i-1][j-1])
show.grid(row = i+1, column = j)
print("Show : "+str(j))
elif j == 3:
#delete button
delete = tk.Button(win, text = "Delete Record",bg = 'red',
command = partial(delete_data, win, connection,
i-1, cursor), width = 19)
delete.grid(row = i+1, column = j)
print("Delete : "+str(j))
#button to return
insert = tk.Button(win,text = "Insert", bg = 'sky blue',
command = lambda: insert_database(win, connection, cursor), width = 19)
insert.grid(row = height+1, column = width-1)
win.mainloop()
if __name__ == '__main__':
database(tk.Tk())
|
Markdown
|
UTF-8
| 9,172
| 3.015625
| 3
|
[] |
no_license
|
# Sikorka
Sikorka is an Ethereum based system that allows for deployment of decentralized blockchain contracts on locations in the real world. This is achieved by a combination of hardware beacons, a mobile application and ethereum smart contracts. In the end any user can deploy a contract on a specific real world location and accept transactions only from users who are physically present there.
## Components of the Network
Proving your location to the blockchain requires that you own a mobile phone equipped with bluetooth and GPS. It also requires that someone has installed a sikorka beacon in the area. Proving your location to a blockchain contract is called Proof Of Presence. Once those requirements are in place anyone can deploy a contract at a physical location and have others interact with it.
### Proof Of Presence
Proof of Presence, abbreviated as `PoP` is the process of proving to a smart contract that you are indeed on a particular location at a specific point in time. This is achieved by utilizing a hardware beacon that can assert to smart contracts that you are indeed in a particular physical location at a certain point in time.
### Mobile Application
The Sikorka mobile app runs an ethereum light client so that it can synchronize with the ethereum network without relying on any centralized services. It allows the user to create an identity and associate it with an Ethereum account. The identity is local only to the Application, but is used by the system in various ways. Users are incentivized to have only 1 identity because they get rewarded for proper behaviour via a reputation system.
The mobile app allows for:
- Searching for nearby contracts
- Interaction with nearby contracts
- Deploying a contract
- Installing a sikorka beacon
### End Users
An end user is anyone who has the mobile application installed in his phone.
### Builders
The term `builder` is used for the people who install beacons in real world locations. A builder can but does not necessarilly need to be the same person who will deploy a contract at a real world location. Multiple contracts can be deployed in a location around a beacon.
A builder's responsibility is to obtain a beacon and set it in place on a location where it would be difficult to remove. Behind a brick, inside a wall, on a whole in a tree and so forth. Additionally they should be checking on their beacons from time to time and if something is wrong or if the beacon is lost they should deregister it from the system.
The builders get rewarded for their effort. Check the incentives section for more information. [TODO: Link].
### Contract Owners
The `contract owner` is anyone who deploys a sikorka contract on a location. In order to deploy a contract in a location the owner must himself go through the Proof Of Presence process with a beacon.
## Sikorka Smart Contracts
Following is a list of the smart contracts involved in the sikorka network.
### Registry
The sikorka registry allows you to query for contracts around a specific location. It contains a data structure mapping coordinates to contracts. It is also with this contract that newly deployed sikorka smart contracts get registered with when created.
### BasicInterface
All contracts must implement this interface to be considered sikorka contracts.
### Reputation
The reputation contract is the contracts that tracks the sikorka reputation token.
### BeaconRegistry
The sikorka beacon registry contract allows a builder to register a beacon in an exact location.
### BeaconDeed
The BeaconDeed contract is a very simple contract containing the deployment deposit for a beacon.
## Reputation
Sikorka Reputation is what helps the system grow, develop the network effect and for leaders to rise in the user communities. It also helps in weeding out malicious actors from the network. Reputation is essentially an ethereum token. You will need to use it in various parts of interacting with the network and doing so burns it. For more information take a look at the Incentives section.
You can earn it in the following ways.
### As a user
- When you interact with a contract and prove your presence via a beacon you earn `X` reputation.
- A contract owner can scan the user's phone and give him `10X` reputation only once every month. This is the most valuable form of reputation a user can earn because it's done by human verifiers.
### As a builder
- Whenever your beacon gets used for proving a user's presence you get `Y` reputation.
### As a contract owner
- Whenever users interact with your contract after having proved their presence you earn `Z` reputation.
### The development team
At least in the beginning the team can mint any amount of tokens for themselves and give it out to the first people who run the pilot program. Trust in the team is required here. Look at the Incentives section for more information. Once the network is up and running and pilot program proves succesful then this may be removed from the contract or kept only to provide reputation to people who buy beacons made by the team.
## Incentives
In this section we look at all the different actors that take the stage in the sikorka platform and analyze their incentives.
### Builders
- The builders should not lie about the location they deployed the beacon at.
- Builders should get rewarded for deploying and maintaining a beacon.
- Builders should not deploy beacons where other beacons are already deployed. A healthy network needs beacons
spread over a large area.
In order to stop builders from lying about the location of their beacon, we give to users the ability to report malicious beacons. Reporting costs at least D amount of reputation. This amount of reputation is burned both for the user and for the deployer of the beacon. The deployer of the beacon also stands to lose his ETH deposit. As soon as his beacon's reputation reaches 0 then the deposited ETH is lost for him and is distributed to the reporter's depending on the reputation they burned in order to report it.
In the happy scenario the builders should be rewarded for their efforts. This is achieved by the Proof Of Presence modifier in the Sikorka BasicInterface that all sikorka contracts must implement. If a contract uses a beacon for proof of presence a tiny amount of ether is sent to the builder of the beacon.
TODO: Should that amount be editable by the beacon's builder? What should the amount be?
(If a beacon is already deployed in a location then the deployment should not be allowed. This could be enforced in the smart contract side .. with a bit of work. Perhaps. Needs more thinking)
### Contract Owners
- The contract owners need accurate location reporting for their users as they rely on that for the contract
to operate succesfully
The users who have also deployed contracts are the contract owners. They use the beacons deployed by the builders to provide proof of presence to their end users. They pay for this service by having an amount of ETH in the contract that is used as payment each time a beacon is used.
### End users
- End users should not lie about their location when reporting malicious beacons.
- End users should use the system truthfully and not try to spoof their address
The end users are those who interact with sikorka deployed contracts. They can't lie about their location since it's determined by the proximity to the beacon, if we assume that beacons are truthfull.
They can also make sure that the builders don't lie about the location of a beacon. If they are in the exact location of a beacon and can't interact with it then they can report the beacon as explained above.
Whenever users utilize the system truthfully then they are rewarded. That means that if a user interacts with a contract's function that requires proof of presence using a physical beacon then the user also gains E reputation.
### Sikorka Development Team
- The development team needs to foster the growth and adoption of the sikorka network.
- The development team needs to have enough funds for the day to day operations, research&development, hardware costs.
The development of sikorka also needs to be funded somehow and for this reason all sikorka enabled contracts pay a very small fee `F` into the development wallet for each time they utilize the sikorka network. This fee is changeable and can be changed by the development multisig. It is in the best interests of the sikorka development team to have a healthy network and for many people to create sikorka contracts. For that reason the fee should be reasonably low and also changeable depending on the price of ETH.
The development multisig also controls the sikorka ENS domain. This is how the address of the sikorka registry, the sikorka reputation and all other contracts is determined and this is how upgrades to the contracts will happen.
The above 2 points require some trust in the development team. That is just how this system will work in the beginning. This can evolve though and users of the system with high enough reputation could be getting a vote in all network governance related matters.
|
Markdown
|
UTF-8
| 8,652
| 2.8125
| 3
|
[
"CC-BY-4.0"
] |
permissive
|
24
Microbial Symbioses
Background
Most microorganisms live together in interacting communities in the environment. These inter-microbial relationships form the base of the (and sometimes the entire) food web. Microbes can exhibit any and all of the possible relationships with other microbes. Some common relationships that we have seen (and you should know) from the lab are:
Competition: A contest between organisms for territory, a niche, or resources. Soil bacteria are often in direct competition for carbon sources (such as starch) in their environment. In this case, neither organism fully thrives – both are harmed somewhat.
Cooperation: The process of groups of microbes working or acting together for their common/mutual benefit. An example of this is quorum sensing (talked about in regulation in our lectures). Both organisms can benefit from this interaction.
Predation: An interaction where a predator (an organism that is hunting) feeds on its prey (the organism that is attacked). Predators tend to be as large or larger than their prey. An example is Paramecium consuming bacteria. Obviously, the predator benefits, but the prey…. Not so much.
Mutualism: A relationship two organisms of different in which each individual benefits from the activity of the other. This is exemplified by lichen, ruminants, and alfalfa.
Commensalism: A class of relationships between two organisms where one organism benefits without affecting the other. Many members of your microbiota are commensal – they benefit from you but not vice versa.
Amensalism: An interaction where an organism inflicts harm to another organism without any costs or benefits received by the actor. An example of this is antibiotic production by a fungus.
Parasitism: An interaction where one species, the parasite, benefits at the expense of the other, the host. Parasites tend to be smaller than their hosts. An example of a parasite is bacteriophage T4 (all viruses are considered to be obligate intracellular parasites).
In this exercise, you will be observing examples of mutualism and commensalism. You have seen examples of parasitism and amensalism in previous exercises.
Instructions
Day 1: While working in pairs, you should set up three nutrient broth tubes as follows:
· Label the tubes 1, 2, and 3 and put a symbol on each of the caps to make it easier to find them again.
· Flame a loop and let it cool. Then use the loop to add a small amount of Staphylococcus aureus (from the plate provided) to tube number 1.
· Repeat the prior step to inoculate tube number 3 with S. aureus as well.
· Using a sterile Pasteur pipette, add three drops of the Clostridium sporogenes broth culture to tubes number 2 and 3.
· Loosely cap all three tubes and incubate at 35°C.
Day 2: Observe the growth in your three tubes.
· Record your observations in your notebook.
· Gram stain the cultures from tubes 1 and 3.
· Use about 3 loopfuls of each on separate slides. Let this air dry and then heat fix.
· Record your observations in your notebook
In addition, you should observe the examples of lichen displayed in our lab. These lichen are actually communities of fungi and algae.
Finally, you will need to prepare a wet mount of termite hindgut contents.
· Put a drop of water on a microscope slide.
· Capture a termite and place it in the drop of water.
· Use a coverslip to squash the termite. You will thereby release the hindgut contents (bacteria and protozoa) for viewing.
· View using your high dry objective (you will want to reduce the brightness of the light using the iris in the substage condenser).
· Try to find ciliate protozoa and spiral-shaped bacteria. These are actually the microbes responsible for cellulose degradation in the termite.
Notebook Entry
To receive full credit for your work, your entry must contain the eight required components discussed in “Keeping a Notebook”. As a reminder, these sections are: a Table of Contents entry, title, the purpose, a procedure, your observations, your conclusions, the date, and the signatures. Take a moment to ensure that your notebook is complete and up-to-date. The most critical components are your observations and conclusions. Specific guidelines regarding your entry for this exercise are given below.
✪ Observations
• Clearly record the appearance of your broth tubes. You can draw them using the following diagrams or photograph them and tape the picture into your notebook.
• Carefully record the size, shape, arrangement, and color of the cells in tubes 1 and 3. Search around your slides and make sure that you see all types of cells present.
You may record these data in one of two ways:
1) Record the view of the ocular micrometers and bacterial cells in focus for each of the eight different samples. Make sure that you clearly label your samples.
2) Using the panels below, draw an accurate representation of each sample. Make sure that you label each sample well. Also ensure that your drawings show the correct size, shape, arrangement, and color of each cell type.
You should also include a picture or drawing of the termite hindgut contents and the lichens that you observed.
✪ Conclusions
1. Why was there no growth in tube 2?
2. What sort of relationship is illustrated in tube 3?
3. Which microbe benefitted from the relationship in tube 3?
4. How does the result in tube three relate to gingivitis (gum disease)?
5. What would happen to the termites if all its hindgut microbes were eliminated? Why?
Housekeeping
To keep our laboratory clean, safe, and organized, we ask that you adhere to some basic housekeeping protocols. Please ensure that you complete each of the following when you have finished working on this exercise for the day.
Glass waste
Dispose of your Pasteur pipettes, glass slides and coverslips in the glass waste box when you are finished for the day. Any broken glass should also be place in the glass waste box. Do not put anything sharp into the regular trash.
Bacterial cultures
We will be working with live microorganisms in this exercise. If spill the culture or otherwise contaminate yourself, you should disinfect your bench with Roccal and wash the contaminated area with plenty of soap and warm water. The cultures we are using include:
1. Staphylococcus aureus (BSL-2) This is commonly found on your skin and in your nose.
2. Clostridium sporogenes (BSL-1) This is basically Clostridium botulinum without toxins.
Return the bacterial culture when you have completed your stains.
Compound light microscope
Before returning your microscope to its respective bin, you should do the following:
1. Unplug the power cord and wrap it around the brackets on the microscope’s arm.
2. Rotate the head of the microscope so that the ocular lenses face toward the arm.
3. Clean any immersion oil off of the 100X objective lens using lens paper.
4. Rotate the objective turret so that the 4X (red striped, scan) objective is facing down.
5. Using the course focus knob, lower the microscope stage as far as it can go.
6. Carefully return your microscope to the correct cubby. Please orient the microscope such that the arm of the instrument faces out.
Contaminated materials
Dispose of your three broth tubes in the unlined silver buckets when you have completed your observations and stains. If you spill any cultures, soak the area with Roccal. Then clean up with paper towels and dispose of the mess in the lined silver buckets.
Laboratory bench
You should disinfect your lab bench at the beginning and end of each class session. Squirt a small amount (a few milliliters) of Roccal onto your bench top and wipe the surface with a paper towel. Dispose of the paper towel in our regular trash can. If you spill a microbial culture on the bench, spray the area with Roccal and allow to sit for two minutes. Then wipe the area with a paper towel and dispose of it in the silver bucket lined with the orange biohazard bag. Start doing this today.
Cell phone / camera
Before leaving the lab for the day, you should take a moment to disinfect the cellphone or camera that you used to make observations. Antimicrobial wipes are available in the lab for this purpose. Wipe all sides of your device with a single wipe and then dispose of the wipe in our regular trash can. Start doing this today too.
Hand washing
You should always wash your hands with warm water and soap for 30 seconds before leaving the lab for the day. Dispose of the paper towel that you dried you hands with in the regular trash can. You should do this today (and every day) in the lab.
|
Shell
|
UTF-8
| 2,339
| 4.0625
| 4
|
[] |
no_license
|
#!/usr/bin/env bash
#
# Credit to:
# https://github.com/alebcay/pushblast
if [[ $1 = "" ]] ; then
echo "usage: pushblast \"command_to_be_executed\""
exit 1
fi
if [ ! -d ~/.config/pushblast/lib ] ; then
mkdir -p ~/.config/pushblast/lib
fi
if [ ! -e ~/.config/pushblast/lib/pushbullet ] ; then
echo "Downloading helper file 1 of 1:"
curl -# https://raw.githubusercontent.com/Red5d/pushbullet-bash/master/pushbullet > ~/.config/pushblast/lib/pushbullet
fi
chmod +x ~/.config/pushblast/lib/pushbullet
if [ ! -e ~/.config/pushblast/pushblastrc ] ; then
touch ~/.config/pushblast/pushblastrc
echo "Welcome to PushBlast! Before I get started, I'll need a few things from you regarding your PushBullet account."
echo -e "\nPlease provide your PushBullet API key, also known as an access token. I need this to be able to push stuff: "
read API_KEY
echo -e "\nPlease provide the device name you wish to push to. Device names are case sensitive, so be careful: "
read DEV_NAME
echo -e "\nPlease name this computer. Computer names are shown on the notification so you know where a notification came from."
read COMP_NAME
echo "API_KEY=\"$API_KEY\"" >> ~/.config/pushblast/pushblastrc
echo "DEV_NAME=\"$DEV_NAME\"" >> ~/.config/pushblast/pushblastrc
echo "COMP_NAME=\"$COMP_NAME\"" >> ~/.config/pushblast/pushblastrc
echo -e "\nLooks like we're all good to go. I'll go ahead and run the command you gave."
fi
source ~/.config/pushblast/pushblastrc
if [[ $API_KEY = "" ]] ; then
echo "Invalid API key. Find your access token at https://www.pushbullet.com/account."
exit 1
fi
touch ~/.config/pushbullet
echo "API_KEY=$API_KEY" > ~/.config/pushbullet
if [[ $DEV_NAME = "" ]] ; then
echo "Invalid target device name. Find your list of devices at https://www.pushbullet.com."
exit 1
fi
if [[ $COMP_NAME = "" ]] ; then
echo "Invalid computer name. Enter a name for this computer (it does not have to be unique or in use with Pushbullet)."
exit 1
fi
(~/.config/pushblast/lib/pushbullet list | grep $DEV_NAME) >/dev/null 2>&1
if [ $? != 0 ] ; then
echo "The device $DEV_NAME does not exist or is unusable."
exit 1
fi
EXECUTE=$1
$1
EXIT=$?
~/.config/pushblast/lib/pushbullet push $DEV_NAME note "The task \"$EXECUTE\" on \"$COMP_NAME\" finished with exit code $EXIT." >/dev/null 2>&1
exit $EXIT
|
C#
|
UTF-8
| 1,955
| 2.859375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using DataLayerCommon.Addresses;
using DataLayerCommon.Phones;
using DataLayerCommon.Places;
using static CommonData.Enums.AddressEnums;
using static CommonData.Enums.PhoneEnums;
using static CommonData.Enums.PlaceEnums;
namespace DataLayerRetrieval.Places
{
public class DbPlaceDataNew : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected internal PlaceData GetNew(PlaceType placeType)
{
PlaceData data = new PlaceData();
try
{
data.Place = new PlaceBase
{
PlaceType = placeType
};
data.AddressData = new AddressData {Addresses = new List<AddressAssociation>()};
foreach (
AddressAssociation aa in
from AddressType val in Enum.GetValues(typeof (AddressType))
where (short) val != 0
select new AddressAssociation {AddressType = val})
{
data.AddressData.Addresses.Add(aa);
}
data.PhoneData = new PhoneData {Phones = new List<PhoneAssociation>()};
foreach (
PhoneAssociation pa in
from PhoneType val in Enum.GetValues(typeof (PhoneType))
where (short) val != 0
select new PhoneAssociation {PhoneType = val})
{
data.PhoneData.Phones.Add(pa);
}
}
catch (Exception ex)
{
data.Place = new PlaceBase();
}
return data;
}
protected virtual void Dispose(bool iAmBeingCalledFromDisposeAndNotFinalize)
{
}
}
}
|
Java
|
UTF-8
| 574
| 3.203125
| 3
|
[] |
no_license
|
/**
*
*/
package homework.symbol;
/*
* @author winy
* @date 2019年3月17日
*/
public enum Symbol {
I(1),
V(5),
X(10),
L(50),
C(100),
D(500),
M(1000);
private int val;
private Symbol(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public static int fromChar(char c) {
String s = c + "";
for (Symbol symbol : Symbol.values()) {
if (s.equals(symbol.name())) {
return symbol.val;
}
}
return -1;
}
}
|
Python
|
UTF-8
| 876
| 3.875
| 4
|
[
"MIT"
] |
permissive
|
# spelare name, email, latest score, high score
class Player:
def __init__(self, name, email):
self.__name = name
self.__email = email
self.__latest_score = 0
self.__high_score = 0
def set_last_score(self, score):
self.__latest_score = score
if score > self.__high_score:
self.__high_score = score
def get_email(self):
return self.__email
def get_name(self):
return self.__name
def __eq__(self, other):
return self.__name == other.__name and self.__email == other.__email
def __repr__(self):
return f"Player({self.__name}, {self.__email}, {self.__latest_score}, {self.__high_score})"
some_player = Player("Bosse", "bosse@bredsladd.se")
some_player.set_last_score(100)
some_player.set_last_score(10)
some_player.set_last_score(99)
print(f"Spelare: {some_player}")
|
Python
|
UTF-8
| 530
| 3.984375
| 4
|
[
"MIT"
] |
permissive
|
def voto(age):
from datetime import date
this_year = date.today().year
player_age=this_year-age
if (this_year-age)<16:
return f'Você tem {player_age} anos.\nVocê ainda não tem idade para votar.'
elif (this_year-age)>18:
return f'Você tem {player_age} anos. \nVocê já tem idade para votar.'
else:
return f'Você tem {player_age} anos.\nVocê tem idade para votar, porém seu voto é OPCIONAL.'
#Main program
idade = int(input('Em que ano você nasceu? '))
print(voto(idade))
|
Java
|
UTF-8
| 5,514
| 3.03125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package cn.com.lemon.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
/**
* Java reflection utility classes
* <p>
*
* @author shellpo shih
* @version 1.0
*/
public final class Reflections {
private Reflections() {
}
/**
* Method of obtaining a declaration.
*
* @param object
* @param methodName
* @param parameterTypes
* @return the declared {@code Method}
*/
public static Method method(Object object, String methodName, Class<?>... parameterTypes) {
Method method = null;
for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
method = clazz.getDeclaredMethod(methodName, parameterTypes);
return method;
} catch (Exception e) {
}
}
return null;
}
/**
* Call object methods directly, ignoring modifiers (private, protected,
* default)
*
* @param object
* @param methodName
* @param parameterTypes
* @param parameters
* @return The result {@code Object} of the execution of the method in the
* parent class.
*/
public static Object method(Object object, String methodName, Class<?>[] parameterTypes, Object[] parameters) {
// The Method object is fetched according to the object, Method name and
// corresponding Method parameters
Method method = method(object, methodName, parameterTypes);
// Inhibiting Java checking of methods, mainly for private methods
method.setAccessible(true);
try {
if (null != method) {
// The method of object is called to represent the method, whose
// parameter is parameters
return method.invoke(object, parameters);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
/**
* look up {@code Field} by field name
*
* @param object
* java {@code Object}
* @param fieldName
* field name
* @return {@code Field}
*/
public static Field field(Object object, String fieldName) {
Field field = null;
Class<?> clazz = object.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (Exception e) {
}
}
return null;
}
/**
* Java reflection gets all the attributes in the class (including the
* parent)
* <p>
* The fields not contain static or transient {@code Field}
*
* @param clazz
* {@code Class}
* @return {@code List}
*/
public static List<Field> fields(Class<?> clazz) {
return fields(clazz, true, true);
}
/**
* Java reflection gets all the attributes in the class (including the
* parent)
*
* @param clazz
* {@code Class}
* @param isStatic
* is contain static {@code Field}
* @param isTransient
* is transient static {@code Field}
* @return {@code List}
*/
public static List<Field> fields(Class<?> clazz, boolean isStatic, boolean isTransient) {
if (null == clazz) {
return null;
}
List<Field> fieldList = new LinkedList<Field>();
while (clazz != null) {
Field[] fields = clazz.getDeclaredFields();
if (null != fields && fields.length > 0) {
for (Field field : fields) {
if (isStatic && Modifier.isStatic(field.getModifiers())) {
continue;
}
if (isTransient && Modifier.isTransient(field.getModifiers())) {
continue;
}
fieldList.add(field);
}
}
// fieldList.addAll(Arrays.asList(fields));
clazz = clazz.getSuperclass();
}
return fieldList;
}
/**
* Java {@code Object} class type
*
* @param object
* @return {@code Class}
*/
public static Class<?> type(Object object) {
Class<?> classType = object.getClass();
String typeName = classType.getName();
switch (typeName) {
case "java.lang.Integer":
return Integer.TYPE;
case "java.lang.Long":
return Long.TYPE;
case "java.lang.Float":
return Float.TYPE;
case "java.lang.Double":
return Double.TYPE;
case "java.lang.Character":
return Character.TYPE;
case "java.lang.Boolean":
return Boolean.TYPE;
case "java.lang.Short":
return Short.TYPE;
case "java.lang.Byte":
return Byte.TYPE;
}
return classType;
}
/**
* Set the {@code Field} value
*
* @param object
* java {@code Object}
* @param fieldName
* {@code Field} name
* @param value
* the {@code Field} value
* @return
*/
public static void set(Object object, String fieldName, Object value) {
Field field = field(object, fieldName);
if (null != field) {
field.setAccessible(true);
try {
field.set(object, value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
/**
* Get the {@code Field} value
*
* @param object
* java {@code Object}
* @param fieldName
* {@code Field} name
* @return
*/
public static Object get(Object object, String fieldName) {
Field field = field(object, fieldName);
if (null != field) {
field.setAccessible(true);
try {
return field.get(object);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
}
|
JavaScript
|
UTF-8
| 3,265
| 2.53125
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
Copyright 2019 Adobe Inc. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
// const { stdout } = require('stdout-stderr')
const commandPath = '../../../src/commands/certificate/fingerprint'
let TheCommand
jest.isolateModules(() => {
TheCommand = require(commandPath)
})
const validCertPem = `
-----BEGIN CERTIFICATE-----
MIIDMTCCAhmgAwIBAgIHAWVCcDJVYDANBgkqhkiG9w0BAQsFADAdMRswGQYDVQQD
ExJHZW5lcmF0ZWQgS2V5IFBhaXIwHhcNMjIwNjAzMTUzMjA1WhcNMjMwNjAzMTUz
MjA1WjAdMRswGQYDVQQDExJHZW5lcmF0ZWQgS2V5IFBhaXIwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQC7vbn/WhI16mKvcYuox+NXOmlcXkieHZL2N6po
2f0Dv4WmtYNHxMbLzsP7zGeKm4DRGSs4Qwnk/NsD7KA9pILmT8aXHVfxrJhCawuz
WTUNjfp8sWGCjhOSHemN9BBo5TP4+Ht/xqE9ANG9mjHhaRUQVa8BAivDDibgC2cs
8AoA5JlDA515ShhnWFLG6wL3IObVzJIJip4chrh26r5La6l76D++LztSnDgYvfzY
J3iCdxaMh/507IVpqc5Vl4pfY5Kp9yF91Z7tD1OTyEpps9ySGiN+rHBJfvixdKUI
gLm5VkeR3hpl7g8+NJSlxo4e/9znQ45OytZHdLk/pVkEkUxXAgMBAAGjdjB0MAkG
A1UdEwQCMAAwCwYDVR0PBAQDAgL0MDsGA1UdJQQ0MDIGCCsGAQUFBwMBBggrBgEF
BQcDAgYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEFBQcDCDAdBgNVHREEFjAUghJH
ZW5lcmF0ZWQgS2V5IFBhaXIwDQYJKoZIhvcNAQELBQADggEBAGdiHZP/SA/8ejgE
1ZbRmvRJMhYz17K5KzB/3wujhRKl2OBKjnv3PVk15Pc6IHabkPKV0PtUKXPfxSci
mwj+3s2R3pRW4S6OhpNYg5/3caPGWXIVmQWJQqo1LdEnD2tpblghVRiha25QBnsi
0wk7l9ebV683A+n6u0Xn9fjFnlT+j7lG36px03z1K+dOQj0+j0yrda9SUSBCYcJj
4+PE1kwOSDRpAnb7mO5BOoSR/x67bQU5kcKcE8kVIijWmuxoyQn6LQEZzKP5LT4F
6DZssT8ZOJuWr7d+BUapoVO1D5o4CrFwYjsHss77tgybTMXQjKsPnkhns8M8RxqW
B9+DCYg=
-----END CERTIFICATE-----
`
const validCertFingerprint = '38f65e26bd3869ec3ca029cc0b3df98de29172b9'
test('exports', async () => {
expect(typeof TheCommand).toEqual('function')
})
test('description', async () => {
expect(TheCommand.description).toBeDefined()
})
test('args', async () => {
const arg = TheCommand.args[0]
expect(arg.name).toBeDefined()
})
describe('instance methods - mock forge', () => {
let CommandUnderTest, command, handleError, mockFS, mockForge
jest.isolateModules(() => {
CommandUnderTest = require(commandPath)
mockFS = require('fs-extra')
mockForge = require('node-forge')
jest.mock('node-forge')
})
beforeEach(() => {
command = new CommandUnderTest([])
handleError = jest.spyOn(command, 'error')
})
afterEach(() => {
jest.clearAllMocks()
})
test('run missing args', async () => {
expect(command.run).toBeDefined()
command.argv = []
await expect(command.run()).rejects.toThrow(/Missing 1 required arg/)
})
test('run -- input file not found', async () => {
mockFS.existsSync.mockReturnValue(false)
command.argv = ['file-not-found']
await expect(command.run()).rejects.toThrow()
expect(handleError).toHaveBeenCalledWith(expect.stringMatching(/input file does not exist/))
})
test('run with invalid file ( not a pem )', async () => {
mockFS.existsSync.mockReturnValue(true)
mockFS.readFileSync.mockReturnValue('not a pem')
mockForge.pki.certificateFromPem.mockImplementation(() => { throw new Error('Not Verified') })
command.argv = ['file']
await expect(command.run()).rejects.toThrow(/Not Verified/)
expect(handleError).toHaveBeenCalled()
})
})
describe('instance methods - real forge', () => {
let CommandUnderTest, command, handleError, mockFS
jest.isolateModules(() => {
mockFS = require('fs-extra')
jest.unmock('node-forge')
CommandUnderTest = require(commandPath)
})
beforeEach(() => {
command = new CommandUnderTest([])
handleError = jest.spyOn(command, 'error')
})
afterEach(() => {
jest.clearAllMocks()
})
test('run with valid cert pem', async () => {
mockFS.existsSync.mockReturnValue(true)
mockFS.readFileSync.mockReturnValue(Buffer.from(validCertPem))
command.argv = ['file']
await expect(command.run()).resolves.toBe(validCertFingerprint)
expect(handleError).not.toHaveBeenCalled()
})
})
|
Ruby
|
UTF-8
| 440
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
def qsort(arr)
return arr unless arr.length > 1
pivot = arr[0]
i = 0
left = []
right = []
while (i = i + 1) < arr.length
if arr[i] < pivot
left.push arr[i]
else
right.push arr[i]
end
end
left = qsort left
right = qsort right
left.push pivot
i = -1
while (i = i + 1) < right.length
left.push right[i]
end
left
end
n = 200_000
arr = []
arr.push rand until (n = n - 1).zero?
qsort arr
|
JavaScript
|
UTF-8
| 473
| 2.75
| 3
|
[] |
no_license
|
function extractMenuCategory(menuList){
var categories=Array.from(new Set(menuList.map((val)=>{
return val.category
})))
var items=categories.map((val)=>{
return menuList.filter(item=>{
return item.category===val
})
})
items.sort((item1, item2) => item1.timestamp > item2.timestamp ? 1 : -1)
// items.forEach(val=>{
// console.log(val)
// })
return items
}
export default extractMenuCategory
|
Shell
|
UTF-8
| 215
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/sh
set -o nounset
set -o errexit
STARTUP_DIR="$( cd "$( dirname "$0" )" && pwd )"
mkdir -p /data-logs/seldon-server
ln -snv /data-logs/seldon-server /apps/tomcat7/logs/
/apps/tomcat7/bin/catalina.sh run
|
Python
|
UTF-8
| 552
| 3.328125
| 3
|
[] |
no_license
|
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
x, mid = min([(abs(x), i) for (i, x) in enumerate(A)])
ans = []
ans.append(x ** 2)
i, j = mid - 1, mid + 1
inf = float('inf')
while i >= 0 or j < len(A):
left, right = A[i] if i >= 0 else inf, A[j] if j < len(A) else inf
if abs(left) <= abs(right):
ans.append(left ** 2)
i -= 1
else:
ans.append(right ** 2)
j += 1
return ans
|
JavaScript
|
UTF-8
| 3,984
| 2.5625
| 3
|
[] |
no_license
|
// npm modules
// ‾‾‾‾‾‾‾‾‾‾‾‾
// const Sql = require('./sql.js')
const inquire = require('inquirer')
const mysql = require('mysql')
const Table = require('cli-table2')
const colors = require('colors')
// global variables
// ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'sknights',
database: 'bamazon_db',
multipleStatements: true
})
// function farm
// ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
const main = ()=>{
connection.connect((err)=>{
if (err) throw err
// functions
const getAll = (func)=>{
connection.query('select * from products',(err,data)=>{
console.log('\033[2J')
if (err) throw err
let table = new Table({
head:[
colors.green("ID"),
colors.green("Product"),
colors.green("Department"),
colors.green("Price"),
colors.green("Inventory")
]
})
for (let i in data) {
table.push([
colors.white(data[i].id),
colors.white(data[i].product_name),
colors.white(data[i].department_name),
{hAlign: 'right',content: colors.white(data[i].price)},
{hAlign: 'right',content: colors.white(data[i].quantity)}
])
}
console.log(table.toString())
return func(data)
})
}
const inq = (data)=>{
let dataId = []
for (let i in data) {
dataId.push(JSON.stringify(parseInt(i)+1))
}
inquire.prompt([
{
message: 'ID of product you would like to buy:',
name: 'id',
type: 'rawlist',
choices: dataId
},
{
message: 'How many would you like?',
name: 'qty',
type: 'input'
}
]).then((x)=>{
console.log(x.id)
x.qty = parseInt(x.qty)
x.id = parseInt(x.id) - 1
let dbQty = parseInt(data[x.id].quantity)
let dbNSold = parseInt(data[x.id].num_sold)
let remaining_stock = dbQty - x.qty
let ttlSold = dbNSold + x.qty
if (remaining_stock < 0) {
// insufficient quantity
console.log('Bamazon does not have that many in stock')
} else {
let cost = parseFloat(data[x.id].price) * x.qty
let s = `You purchased ${x.qty} ${data[x.id].product_name}(s) for a total cost of ${cost}`
console.log(s)
let id = parseInt(x.id)+1
// let a = `update products set quantity = ${remaining_stock} where id = ${id}`
let a = `update products set ? where ?`
let b = [{quantity:remaining_stock,num_sold:ttlSold},{id:id}]
console.log('connect again')
connection.query(a,b,(err,data)=>{
if (err) throw err
})
}
inquire.prompt({
message: 'Go again?',
type: 'confirm',
default: true,
name: 'again'
}).then((c)=>{
if (c.again) getAll(inq)
else {
return connection.end()
}
})
})
}
getAll(inq)
})
}
main()
|
C#
|
UTF-8
| 1,115
| 2.59375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using LeanKit.API.Client.Library;
using LeanKit.API.Client.Library.TransferObjects;
namespace LeanKitQuery
{
public class ListBoardIDsQuery : ILeanKitQuery
{
public int RunQuery(ILeanKitApi client, string[] parameters, TextWriter output, TextWriter errorOutput)
{
var boards = client.GetBoards();
foreach (var board in boards)
{
if(parameters.Length > 0)
{
bool found = true;
foreach(var parameter in parameters)
{
if(!board.Title.ToLower().Contains(parameter.ToLower()))
{
found = false;
break;
}
}
if (!found)
continue;
}
output.WriteLine(board.Id + " - " + board.Title);
}
return 0;
}
}
}
|
TypeScript
|
UTF-8
| 2,002
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
import { options, LANDSCAPE, PORTRAIT, UP, DOWN, LIGHT, DARK } from '.'
const mediaQuery = (input, returnType: StringConstructor | ObjectConstructor = String) => {
let generated = returnType === String ? '' : {}
if (typeof input[0] === 'string') {
input = [input]
}
for (const value of input) {
const bp = options.breakpoints[value[0]]
const shorthand = options?.shorthands?.[value[0]]
// Handle shorthand
if (shorthand) {
if (returnType === String) {
generated += shorthand + `{ ${value[1]} }`
} else {
generated[shorthand] = value[1]
}
continue
}
// No such breakpoint, simply add
else if (!bp) {
if (returnType === String) {
generated += value[0] + `{ ${value[1]} }`
} else {
generated[value[0]] = value[1]
}
continue
}
const key = value[0]
const first = key[0]
const last = key[key.length - 1]
let query = `@media screen `
if (last === UP) {
query += `and (min-width: ${bp[0]}px) `
} else if (last === DOWN) {
query += `and (max-width: ${bp[1]}px) `
} else if (bp[0] !== true) {
query += `and (min-width: ${bp[0]}px) and (max-width: ${bp[1]}px) `
}
if (first === PORTRAIT) {
query += `and (orientation: portrait) `
} else if (first === LANDSCAPE) {
query += `and (orientation: landscape) `
} else if (first === DARK) {
query += `and (prefers-color-scheme: dark) `
} else if (first === LIGHT) {
query += `and (prefers-color-scheme: light) `
}
if (returnType === String) {
generated += query + `{ ${value[1]} }`
} else {
generated[query] = value[1]
}
}
return generated
}
export default mediaQuery
|
Java
|
UTF-8
| 3,973
| 1.78125
| 2
|
[] |
no_license
|
/*
* Copyright 2001-2007 The European Bioinformatics Institute.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.intact.dataexchange.enricher.standard;
import org.junit.Assert;
import org.junit.Test;
import psidev.psi.mi.jami.enricher.exception.EnricherException;
import psidev.psi.mi.jami.model.Annotation;
import psidev.psi.mi.jami.model.Experiment;
import psidev.psi.mi.jami.model.Publication;
import psidev.psi.mi.jami.model.Xref;
import psidev.psi.mi.jami.model.impl.DefaultExperiment;
import psidev.psi.mi.jami.model.impl.DefaultOrganism;
import psidev.psi.mi.jami.model.impl.DefaultPublication;
import psidev.psi.mi.jami.model.impl.DefaultSource;
import psidev.psi.mi.jami.utils.AnnotationUtils;
import uk.ac.ebi.intact.dataexchange.enricher.EnricherBasicTestCase;
import javax.annotation.Resource;
/**
* TODO comment this
*
* @author Bruno Aranda (baranda@ebi.ac.uk)
* @version $Id$
*/
public class ExperimentEnricherTest extends EnricherBasicTestCase {
@Resource(name = "intactExperimentEnricher")
private ExperimentEnricher enricher;
@Test
public void enrich_pub() throws EnricherException{
final String pubmedId = "15733859";
Publication publication = new DefaultPublication(pubmedId);
Experiment experiment = new DefaultExperiment(publication);
publication.setSource(new DefaultSource("ucla"));
enricher.enrich(experiment);
Assert.assertEquals("The flexible loop of Bcl-2 is required for molecular interaction with immunosuppressant FK-506 binding protein 38 (FKBP38).",
publication.getTitle());
Assert.assertEquals(3, experiment.getAnnotations().size());
Assert.assertEquals("ucla", publication.getSource().getShortName());
}
@Test
public void enrich_pub_repeatedAnnots() throws EnricherException{
final String pubmedId = "15733859";
Publication publication = new DefaultPublication(pubmedId);
Experiment experiment = new DefaultExperiment(publication);
experiment.getAnnotations().add(AnnotationUtils.createAnnotation(Annotation.PUBLICATION_YEAR, Annotation.PUBLICATION_YEAR_MI, "2005"));
enricher.enrich(experiment);
Assert.assertEquals(3, experiment.getAnnotations().size());
}
@Test
public void enrich_hostOrganism() throws EnricherException{
Experiment experiment = new DefaultExperiment(null);
experiment.setHostOrganism(new DefaultOrganism(83333));
enricher.enrich(experiment);
Assert.assertEquals("ecoli", experiment.getHostOrganism().getCommonName());
}
@Test
public void enrich_noDetectionMethod() throws EnricherException{
Experiment experiment = new DefaultExperiment(null);
experiment.setHostOrganism(new DefaultOrganism(83333));
enricher.enrich(experiment);
Assert.assertNotNull(experiment.getInteractionDetectionMethod());
Assert.assertEquals(Experiment.UNSPECIFIED_METHOD_MI, experiment.getInteractionDetectionMethod().getMIIdentifier());
}
@Test
public void enrich_wrongPubmedXrefQual() throws EnricherException{
Experiment experiment = new DefaultExperiment(new DefaultPublication("15733859"));
experiment.setHostOrganism(new DefaultOrganism(83333));
enricher.enrich(experiment);
Assert.assertEquals(Xref.PRIMARY_MI, experiment.getXrefs().iterator().next().getQualifier().getMIIdentifier());
}
}
|
C++
|
UTF-8
| 1,818
| 2.78125
| 3
|
[] |
no_license
|
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef struct _Node
{
int num, cost;
} Node;
int n, m, first, last, result = 0;
vector<vector<Node>> arr, parent;
vector<int> cnt, last_dist, visit;
void Function()
{
queue<Node> pq;
pq.push({first, 0});
last_dist[first] = 0;
while(!pq.empty()) {
int num = pq.front().num;
int cost = pq.front().cost;
int len = (int)arr[num].size();
pq.pop();
for(int i=0; i<len; i++) {
last_dist[arr[num][i].num] = max(last_dist[arr[num][i].num], cost + arr[num][i].cost);
cnt[arr[num][i].num]--;
if(cnt[arr[num][i].num] == 0) {
pq.push({arr[num][i].num, last_dist[arr[num][i].num]});
}
}
}
}
void Back()
{
queue<int> pq;
pq.push(last);
while(!pq.empty()) {
int num = pq.front();
int len = (int)parent[num].size();
pq.pop();
if(visit[num] == 1) {
continue;
}
visit[num] = 1;
for(int i=0; i<len; i++) {
if(last_dist[num] - parent[num][i].cost == last_dist[parent[num][i].num]) {
pq.push(parent[num][i].num);
result++;
}
}
}
}
int main()
{
scanf("%d %d", &n, &m);
arr.resize(n+1);
parent.resize(n+1);
cnt.assign(n+1, 0);
last_dist.assign(n+1, 0);
visit.assign(n+1, 0);
int head, tail, cost;
for(int i=0; i<m; i++) {
scanf("%d %d %d", &head, &tail, &cost);
arr[head].push_back({tail, cost});
parent[tail].push_back({head, cost});
cnt[tail]++;
}
scanf("%d %d", &first, &last);
Function();
Back();
printf("%d\n", last_dist[last]);
printf("%d\n", result);
}
|
PHP
|
UTF-8
| 3,919
| 2.609375
| 3
|
[] |
no_license
|
<?php
Core::load('CMS.Fields');
class Component_Nodus_Fields_ItemsMultilink_Type extends CMS_Fields_AbstractField implements Core_ModuleInterface
{
static $items = array();
public function items($data)
{
if (!isset($data['selector'])) {
return false;
}
$selector = trim($data['selector']);
if (!isset(self::$items[$selector])) {
$so = Component_Nodus::selector($selector);
if (!$so) {
return false;
}
$items = array();
foreach ($so->rows() as $row) {
$items[$row->id] = CMS::lang($row->title);
}
self::$items[$selector] = $items;
}
return self::$items[$selector];
}
public function form_field_name($name, $id)
{
return "nodus_ties_{$name}_{$id}";
}
public function form_fields($form, $name, $data)
{
$items = $this->items($data);
if ($items === false) {
return;
}
foreach ($items as $id => $title) {
$fname = $this->form_field_name($name, $id);
$form->checkbox($fname);
}
}
public function assign_from_object($form, $object, $name, $data)
{
$ties = $object->get_ties($name);
foreach ($ties as $id) {
$fname = $this->form_field_name($name, $id);
$form[$fname] = 1;
}
}
public function assign_to_object($form, $object, $name, $data)
{
$items = $this->items($data);
if (!$items) {
return;
}
$object->reset_ties($name);
foreach ($items as $id => $title) {
$fname = $this->form_field_name($name, $id);
if ($form[$fname]) {
$object->tie_item($name, $id);
}
}
}
public function copy_value($from, $to, $name)
{
$ties = $from->get_ties($name);
$to->reset_ties($name);
foreach ($ties as $tie)
$to->tie_item($name, $tie);
return $this;
}
}
class Component_Nodus_Fields_ItemsMultilink_Type_ValueContainer extends CMS_Fields_ValueContainer
{
protected $limit = false;
protected $ids = null;
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
/**
* @return int[]
*/
public function ids()
{
if ($this->ids !== null) {
return $this->ids;
}
$m = CMS::orm()->nodus_items->tied_ids($this->item, $this->name);
if ($this->limit) {
$m = $m->range($this->limit);
}
$this->ids = array();
foreach ($m as $row) {
$this->ids[$row->id] = $row->id;
}
return $this->ids;
}
/**
* @return Component_Nodus_DB_Item[];
*/
public function items()
{
$items = array();
foreach ($this->ids() as $id) {
$item = Component_Nodus::item($id);
if ($item) {
$items[] = $item;
}
}
return $items;
}
/**
* @return int
*/
public function count()
{
return count($this->ids());
}
/**
* @param string|bool $mode
* @param mixed $view
* @return string
*/
public function render($mode = false, $view = false)
{
if (!$mode) {
$mode = 'teaser';
}
if (!$view) {
$view = CMS::$i_view;
}
if (!$view) {
return $this->render_without_view($mode);
}
$out = '';
foreach ($this->items() as $item)
$out .= $item->render($mode, $view);
return $out;
}
public function render_without_view($tpl = false)
{
if (!is_string($tpl)) {
$tpl = 'ul';
}
if (!Core_Regexps::match_with_results('{\.phtml$}', $tpl)) {
$tpl .= '.phtml';
}
if ($tpl[0] != '.' && $tpl[0] != '/') {
$tpl = $this->type->dir() . '/' . $tpl;
}
if (is_file($tpl)) {
return CMS::render_in_page($tpl, array(
'container' => $this,
'type' => $this->type,
'item' => $this->item,
'data' => $this->data,
'name' => $this->name,
'items' => $this->items(),
)
);
}
return implode(', ', $this->ids());
}
public function set($ids)
{
$this->ids = null;
$this->item->reset_ties($this->name);
$this->item->set_ties($this->name, $ids);
return $this;
}
/**
* Механизм проверки наличие контента для рендера в контейнере
*
* @return bool
*/
public function check_empty()
{
return !$this->count();
}
}
|
Java
|
UTF-8
| 312
| 1.921875
| 2
|
[] |
no_license
|
package com.pharm.service.interfaces.manager;
import com.pharm.model.Manager;
import java.util.List;
public interface ManagerService {
List<Manager> findAll();
Manager findById(Long id);
Manager create(Manager manager);
Manager update(Manager manager);
Manager delete(Manager manager);
}
|
TypeScript
|
UTF-8
| 1,170
| 3.234375
| 3
|
[] |
no_license
|
export interface NamesAndMapAndList<P, T extends { [index: string]: P }> {
map: {
[U in keyof T]: U
};
list: P[];
names: string[];
}
export function toNamesAndMapAndList<P, T extends { [index: string]: P }>(data: T): NamesAndMapAndList<P, T> {
const map: {
[U in keyof T]: U
} = {} as any;
const list: P[] = [];
const names: string[] = [];
Object.keys(data).forEach(v => {
map[v] = v;
list.push(data[v]);
names.push(v);
});
return { map, list, names };
}
export function toNames<P, T extends { [index: string]: P }>(data: T) {
const names: string[] = [];
Object.keys(data).forEach(v => {
names.push(v);
});
return { names };
}
export function toMap<P, T extends { [index: string]: P }>(data: T) {
const map: {
[U in keyof T]: U
} = {} as any;
Object.keys(data).forEach(v => {
map[v] = v;
});
return { map };
}
export function toList<P, T extends { [index: string]: P }>(data: T): { list: P[] } {
const list: P[] = [];
Object.keys(data).forEach(v => {
list.push(data[v]);
});
return { list: list };
}
|
Markdown
|
UTF-8
| 8,256
| 2.953125
| 3
|
[
"CC-BY-4.0",
"OFL-1.1",
"MIT"
] |
permissive
|
_model: page
---
_template: page-with-toc.html
---
title: Translation Guide
---
description: Our translation files are hosted and managed on [Transifex](https://www.transifex.com). It's very easy to sign up for an account and start translation CC services into another language.
---
body:
CC applications such as CC Search and the CC License Chooser are used by
millions of users worldwide. Translating these services into the languages our
users speak and read is integral to making these services accessible to our
diverse user base.
We use Transifex to manage our translation files. It provides an intuitive UI
and many useful tools. Let's see how you can join us there and get started.
TL;DR: We have a [video version](https://www.youtube.com/watch?v=Rta2AlPww8M)
of this tutorial if you prefer that as the medium of instruction.
## For translators
* **Sign up on Transifex**
* Visit the Transifex [sign up page](https://www.transifex.com/signup/) and
fill out the form to create an account.
* You can create a new account using your email address, a username and a
password.
* Alternatively you can link an existing account from GitHub, Google or
LinkedIn to avoid having to remember another password.
* During the sign up process, you will be asked for the languages you speak.
Remember to fill it as comprehensively as possible.
<p style="text-align: center;">
<img
style="max-height: 508px; border: 1px solid #ccc;"
alt="Screenshot of the Transifex sign up page"
src="./transifex_signup.png">
</p>
* **Verify your email**
You will receive an email from Transifex on the email address you signed up.
Clicking the link in the email will verify that you used an authentic email to
sign up and enable all the features on your account.
* **Visit the CC Organisation page**
The [organisation page](https://www.transifex.com/creativecommons/public/)
contains links to all CC projects currently in translation.
<p style="text-align: center;">
<img
style="max-height: 508px; border: 1px solid #ccc;"
alt="Screenshot of the Transifex 'CC' organisation page"
src="./transifex_org_page.png">
</p>
* **Choose a project**
Choose any project from the list that you would like to translate. Click on
the project name to go to the project page.
<p style="text-align: center;">
<img
style="max-height: 508px; border: 1px solid #ccc;"
alt="Screenshot of the Transifex 'Summit website' project page"
src="./transifex_summit.png">
</p>
* **Join the team**
* You can see a list of languages that each project has been translated into.
Not all languages are visible. Click on the 'Display all languages' button
to see them all.
* If your language isn't present in the list, you can request for it by
clicking the 'Request language' button. You will have to go to the previous
step and find a different project till your language request is approved.
* If your language is present, click on the 'Join team' button to join the
team that's translating this project.
* In the modal choose your language and click the 'Join' button. You'll
receive a notification that a request has been submitted. Wait for an
administrator to add you to the team.
<p style="text-align: center;">
<img
style="border: 1px solid #ccc;"
alt="Screenshot of the Transifex 'Join project' modal"
src="./transifex_modal.png">
</p>
* **Getting around**
* You'll receive an email when your request has been accepted.
* When you log back in to Transifex, you'll see some changes in the UI.
* You'll have Creative Commons mentioned in the organisation dropdown.
* You'll see CC projects in the left sidebar.
* Click on the project of your choice from the sidebar.
<p style="text-align: center;">
<img
style="max-height: 508px; border: 1px solid #ccc;"
alt="Screenshot of the Transifex 'Summit website' member view"
src="./transifex_member_view.png">
</p>
* **Translate the strings**
* Find your language from the list of languages. Hovering over the name will
reveal a 'View resource' button.
* Click on the 'View resource' button. That should take you to the page of
that particular language. It contains the resources that you need to
translate.
* Clicking on the resource opens a modal describing the words and strings that
remain to be translated. Here onwards you have three paths for translating
the site.
- Transifex editor UI, by clicking the 'Translate' button
- Transifex live UI, by clicking the 'Live' button
- Local string translation, by clicking the download and upload buttons
<p style="text-align: center;">
<img
style="border: 1px solid #ccc;"
alt="Screenshot of the Transifex resource modal"
src="./transifex_resource_modal.png">
</p>
* * **Method 1: Translating using the Transifex editor UI**
* To do this, click on the 'Translate' button from the resource modal. You
will be taken to a list of all the strings from the website.
* Switch the language to your target language using the menu bar on the
upper side of the screen.
* Click on any string, enter the translation in the lower box and click
the 'Save Translation' button to commit the change.
* Some text has HTML tags in it. In those cases you can click on the tags in
the source text to copy them over in the translated text. You can also
drag to move them around as needed.
* Keep [these instructions](https://wiki.creativecommons.org/wiki/Translating_CC_Deeds#General_Notes_About_Translating)
in mind.
<p style="text-align: center;">
<img
style="max-height: 508px; border: 1px solid #ccc;"
alt="Screenshot of the Transifex editor UI"
src="transifex_editor_ui.png">
</p>
* * **Method 2: Translating using the Transifex live UI**
* To do this, click on the 'Live' button from the resource modal. You will
be taken to the website rendered in the Transifex page and you can edit
the text directly.
* Switch the language to your target language using the sidebar on the right
side of the screen.
* All the text is green boxes can be translated. Click on the pencil icon
that appears when you move your mouse over the green boxes.
* Enter your translated string in the lower box and press the 'Save' button
to confirm the translation.
<p style="text-align: center;">
<img
style="max-height: 508px; border: 1px solid #ccc;"
alt="Screenshot of the Transifex live UI"
src="transifex_live_ui.png">
</p>
* * **Method 3: Translating strings locally**
* To do this, you can download the JSON file that maps English strings to
their counterparts in your language by clicking the 'Download file to
translate' button.
* For the untranslated strings, both key and value will be the same.
```json
{ "Hello, World!": "Hello, World!" }
```
* Change the JSON values to the translated text.
```json
{ "Hello World": "नमस्ते, दुनिया!" }
```
* Upload the translated JSON file using the 'Upload file' button.
Your translations will go live as soon as they are approved by the admins.
## For admins
* **Approve team join requests**
* Click on the person's name to see their profile. That could help in
determining the credibility of the candidate.
* Click the 'Accept' button if you want to add the collaborator to the team.
You'll receive a notification confirming the acceptance of the translator.
<p style="text-align: center;">
<img
style="max-height: 503px; border: 1px solid #ccc;"
alt="Screenshot of the Transifex 'Join requests' page"
src="./transifex_join_request.png">
</p>
* **Review translations**
* Navigate to the resource as described for translators in the 'Translate the
strings' section.
* In the resource modal that appears, click on the 'View strings online'
button. You will be taken to the strings page.
* Click on the 'Unreviewed' tab. Approve or decline the translation as
applicable.
<p style="text-align: center;">
<img
style="max-height: 503px; border: 1px solid #ccc;"
alt="Screenshot of the Transifex 'Unreviewed translations' page"
src="./transifex_review_translation.png">
</p>
|
TypeScript
|
UTF-8
| 4,294
| 2.625
| 3
|
[] |
no_license
|
import { Router } from 'express';
import * as coffeeService from "../service/CoffeeService";
import { Coffee } from "./../model/coffee";
import {log} from "./../utils/Logger";
export const coffeeRouter = Router();
var path = require('path');
var scriptName = path.basename(__filename);
coffeeRouter.get('/', async (req, res) => {
try {
res.json(await coffeeService.getCoffeeList());
log("Coffee router - get coffee list", "get: /", "", "json file", scriptName);
} catch (e) {
log("Coffee router - get coffee list", "get: /", "", `${e.message}`, scriptName);
res.status(500).send(e.message)
}
})
coffeeRouter.get('/:id', async (req, res) => {
try {
const id = Number(req.params.id);
log("Coffee router - get coffee by id", "get: /:id", `${id}`, "json file", scriptName);
res.json(await coffeeService.getCoffeeItem(id));
} catch (e) {
log("Coffee router - get coffee by id", "get: /:id", "", `${e.message}`, scriptName);
res.status(500).send(e.message)
}
})
coffeeRouter.get('/search/:key/:word', async (req, res) => {
try {
const key = req.params.key;
const word = req.params.word;
console.log(key);
console.log(word);
res.json(await coffeeService.searchCoffeeItem(key, word));
log("Coffee router - get coffee by keyword", "get: /search/:key/:word", `Key: ${key}, Word: ${word}`, "", scriptName);
} catch (e) {
log("Coffee router - get coffee by keyword", "get: /search/:key/:word", "", `${e.message}`, scriptName);
res.status(500).send(e.message)
}
})
coffeeRouter.post('/', async (req, res) => {
let {
coffee_name,
shots_of_espresso,
container,
total_calories,
contains_milk,
price
}: {
coffee_name: string,
shots_of_espresso: number
container: string,
total_calories: number,
contains_milk: boolean,
price: number
} = req.body;
try {
let coffee: Coffee = await coffeeService.saveCoffeeItem(
new Coffee(
0,
coffee_name,
shots_of_espresso,
container,
total_calories,
contains_milk,
price));
res.status(201).json(coffee);
log("Coffee router - save coffee entry", "post: /", `${req.body}`, res.statusCode, scriptName);
} catch (e) {
log("Coffee router - save coffee entry", "post: /", "", `${e.message}`, scriptName);
res.status(500).send(e.message)
}
})
coffeeRouter.post('/:id', async (req, res) => {
let {
coffee_name,
shots_of_espresso,
container,
total_calories,
contains_milk,
price
}: {
coffee_name: string,
shots_of_espresso: number
container: string,
total_calories: number,
contains_milk: boolean,
price: number
} = req.body;
const id = Number(req.params.id);
try {
let coffee: Coffee = await coffeeService.updateCoffeeItem(id,
new Coffee(
0,
coffee_name,
shots_of_espresso,
container,
total_calories,
contains_milk,
price));
res.status(201).json(coffee);
log("Coffee router - update coffee entry", "post: /:id", `${req.body}`, res.statusCode, scriptName);
} catch (e) {
log("Coffee router - update coffee entry", "post: /:id", "", `${e.message}`, scriptName);
res.status(500).send(e.message)
}
})
coffeeRouter.delete('/:id', async (req, res) => {
try {
const id = Number(req.params.id);
const deletedItem = await coffeeService.deleteCoffeeItem(id)
res.send(`Successfully deleted ${deletedItem[0].coffee_name} with ID no ${id} in database `)
res.json(await coffeeService.deleteCoffeeItem(id));
log("Coffee router - delete coffee entry", "delete: /:id", `ID: ${id}`, res.statusCode, scriptName);
} catch (e) {
log("Coffee router - delete coffee entry", "delete: /:id", "", `${e.message}`, scriptName);
res.status(500).send(e.message)
}
})
|
Java
|
UTF-8
| 11,666
| 1.796875
| 2
|
[] |
no_license
|
package com.example.mijin.hue.Day;
/**
* Created by mijin on 2017-11-26.
*/
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.NumberPicker;
import com.example.mijin.hue.MainActivity;
import com.example.mijin.hue.R;
import com.example.mijin.hue.RequestHttpURLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by mijin on 2017-11-24.
*/
public class GroupSettingScheduleActivity extends AppCompatActivity {
DatePicker startDate, endDate;
//FrameLayout startDate, endDate;
//ClockView startTime, endTime;
NumberPicker startTime, endTime;
DatePicker start, end;
String url, project_id, id, sTime, eTime;
ContentValues values;
int t, d, m, y, t2, d2, m2, y2;
NetworkTask30 networkTask30;
SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
Intent in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_schedule);
in = getIntent();
SharedPreferences prefs = getSharedPreferences("PrefName",MODE_PRIVATE);
project_id = prefs.getString("project_id",null);
id = prefs.getString("id",null);
startDate = (DatePicker) findViewById(R.id.startDate);
endDate = (DatePicker) findViewById(R.id.endDate);
//startDate = (FrameLayout) findViewById(R.id.startDate);
//endDate = (FrameLayout) findViewById(R.id.endDate);
//start = new DatePicker(startDate,null);
//end = new DatePicker(endDate,null);
//startDate = start;
//endDate = end;
startTime = (NumberPicker) findViewById(R.id.startTime);
endTime = (NumberPicker) findViewById(R.id.endTime);
startTime.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
//t=i1;
numberPicker.setValue(i1);
}
});
endTime.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
//t2=i1;
numberPicker.setValue(i1);
}
});
startTime.setMinValue(1);
startTime.setMaxValue(24);
endTime.setMinValue(1);
endTime.setMaxValue(24);
/*
startTime = (ClockView) findViewById(R.id.startTime);
endTime = (ClockView) findViewById(R.id.endTime);
DateTime minTime = new DateTime(2014, 4, 24, 0, 0);
DateTime maxTime = new DateTime(2014, 4, 25, 0, 0);
sMinDepartTimeClockView = startTime;
startTime.setBounds(minTime, maxTime, false);
startTime.setNewCurrentTime(new DateTime(2014, 4, 24, 0, 0));
sMaxDepartTimeClockView = endTime;
endTime.setBounds(minTime, maxTime, false);
endTime.setNewCurrentTime(new DateTime(2014, 4, 25, 0, 0));
changeClockTimeForTests(DateTime.now(),false);
*/
Button save = (Button) findViewById(R.id.save);
Button cancel = (Button) findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
d = start.getDayOfMonth();
m = start.getMonth()+1;
y = start.getYear();
//t = startTime.getNewCurrentTime().getHourOfDay();
t=startTime.getValue();
sTime = y+"-"+m+"-"+d+" "+t+":00:00";
d2 = end.getDayOfMonth();
m2 = end.getMonth()+1;
y2 = end.getYear();
//t2 = endTime.getNewCurrentTime().getHourOfDay();
t2=endTime.getValue();
url = "http://uoshue.dothome.co.kr/addGroupSchedule.php?";
values = new ContentValues();
values.put("id",id);
values.put("project_id", project_id);
values.put("start",sTime);
if(y2<y){
AlertDialog.Builder builder = new AlertDialog.Builder(GroupSettingScheduleActivity.this,R.style.MyAlertDialog);
builder.setMessage("일정을 다시 확인해주세요.");
builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}else if(y2==y){
if(m2<m){
AlertDialog.Builder builder = new AlertDialog.Builder(GroupSettingScheduleActivity.this,R.style.MyAlertDialog);
builder.setMessage("일정을 다시 확인해주세요.");
builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}else if(m2==m){
if(d2<d){
AlertDialog.Builder builder = new AlertDialog.Builder(GroupSettingScheduleActivity.this,R.style.MyAlertDialog);
builder.setMessage("일정을 다시 확인해주세요.");
builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}else if(d2==d){
if(t2<=t||t2==24){
AlertDialog.Builder builder = new AlertDialog.Builder(GroupSettingScheduleActivity.this,R.style.MyAlertDialog);
builder.setMessage("일정을 다시 확인해주세요.");
builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}else{
eTime = y2 + "-" + m2 + "-" + d2 + " "+ (t2-1) +":59:59";
values.put("end",eTime);
networkTask30 = new NetworkTask30(url, values);
networkTask30.execute();
}
}else{//성공
if(t2==24) {
eTime = y2 + "-" + m2 + "-" + d2 + " " +"23:59:59";
try {
cal.setTime(dformat.parse(eTime));
cal.add(Calendar.DATE,-1);
eTime = dformat.format(cal.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}else{
eTime = y2 + "-" + m2 + "-" + d2 + " "+ (t2-1) +":59:59";
}
values.put("end",eTime);
networkTask30 = new NetworkTask30(url, values);
networkTask30.execute();
}
}else{//성공
if(t2==24) {
eTime = y2 + "-" + m2 + "-" + d2 + " " +"23:59:59";
try {
cal.setTime(dformat.parse(eTime));
cal.add(Calendar.DATE,-1);
eTime = dformat.format(cal.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}else{
eTime = y2 + "-" + m2 + "-" + d2 + " "+ (t2-1) +":59:59";
}
values.put("end",eTime);
networkTask30 = new NetworkTask30(url, values);
networkTask30.execute();
}
}else{//성공
if(t2==24) {
eTime = y2 + "-" + m2 + "-" + d2 + " " +"23:59:59";
try {
cal.setTime(dformat.parse(eTime));
cal.add(Calendar.DATE,-1);
eTime = dformat.format(cal.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}else{
eTime = y2 + "-" + m2 + "-" + d2 + " "+ (t2-1) +":59:59";
}
values.put("end",eTime);
networkTask30 = new NetworkTask30(url, values);
networkTask30.execute();
}
}
});
}
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
startDate.updateDate(year,monthOfYear,dayOfMonth);
endDate.updateDate(year,monthOfYear,dayOfMonth);
}
public class NetworkTask30 extends AsyncTask<Void, Void, String> {
private String url;
private ContentValues values;
public NetworkTask30(String url, ContentValues values) {
this.url = url;
this.values = values;
}
@Override
protected String doInBackground(Void... params) {
String result;
RequestHttpURLConnection requestHttpURLConnection = new RequestHttpURLConnection();
result = requestHttpURLConnection.request(url, values);
return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("setting","ok");
if(in!=null) intent.putExtra("date",in.getStringExtra("date"));
startActivityForResult(intent, 2);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==2&&resultCode==RESULT_OK)
finish();
}
}
|
PHP
|
UTF-8
| 283
| 2.6875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
<?php
namespace app\board\entities;
interface AdInterface
{
/**
* @return string
*/
public function getFullName();
/**
* @return int
*/
public static function type();
/**
* @return string
*/
public function getMainPhoto();
}
|
C
|
UTF-8
| 368
| 2.5625
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<string.h>
int main(){
int n,i,count=0;
scanf("%d",&n);
char str[101],S[101];
char tem,tab[256]={0};
scanf("%s",str);
for(i=0;i<n;i++){
str[i]=tolower(str[i]);
tem=str[i];
if(tab[tem]==0){
tab[tem]=1;
count++;
}
}
if(count==26)
printf("YES");
else
printf("NO");
return 0;
}
|
Java
|
UTF-8
| 291
| 2.84375
| 3
|
[] |
no_license
|
package br.com.teste.dias.semana.interno;
public class EnumInternoTeste {
public static void main(String[] args) {
EnumInterno enumInterno = new EnumInterno();
enumInterno.setDia(EnumInterno.DiaSemana.QUARTA.getValor());
System.out.println(" Dia: " + enumInterno.getDia());
}
}
|
Java
|
UTF-8
| 7,405
| 2.15625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package net.sf.webdav.methods;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.webdav.IMimeTyper;
import net.sf.webdav.ITransaction;
import net.sf.webdav.IWebdavStore;
import net.sf.webdav.StoredObject;
import net.sf.webdav.WebdavStatus;
import net.sf.webdav.locking.ResourceLocks;
import net.sf.webdav.testutil.MockTest;
import org.jmock.Expectations;
import org.junit.BeforeClass;
import org.junit.Test;
public class DoPropfindTest extends MockTest {
static IWebdavStore mockStore;
static IMimeTyper mockMimeTyper;
static HttpServletRequest mockReq;
static HttpServletResponse mockRes;
static ITransaction mockTransaction;
static PrintWriter printWriter;
static byte[] resourceContent = new byte[] { '<', 'h', 'e', 'l', 'l', 'o',
'/', '>' };
@BeforeClass
public static void setUp() throws Exception {
mockStore = _mockery.mock(IWebdavStore.class);
mockMimeTyper = _mockery.mock(IMimeTyper.class);
mockReq = _mockery.mock(HttpServletRequest.class);
mockRes = _mockery.mock(HttpServletResponse.class);
mockTransaction = _mockery.mock(ITransaction.class);
}
@Test
public void doPropFindOnDirectory() throws Exception {
final String path = "/";
_mockery.checking(new Expectations() {
{
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getHeader("Depth");
will(returnValue("infinity"));
StoredObject rootSo = initFolderStoredObject();
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(rootSo));
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getContentLength();
will(returnValue(0));
// no content, which means it is a allprop request
one(mockRes).setStatus(WebdavStatus.SC_MULTI_STATUS);
one(mockRes).setContentType("text/xml; charset=UTF-8");
one(mockRes).getWriter();
will(returnValue(printWriter));
one(mockMimeTyper).getMimeType(path);
will(returnValue("text/xml; charset=UTF-8"));
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(rootSo));
one(mockReq).getContextPath();
will(returnValue(""));
one(mockReq).getServletPath();
will(returnValue(path));
one(mockStore).getChildrenNames(mockTransaction, path);
will(returnValue(new String[] { "file1", "file2" }));
StoredObject file1So = initFileStoredObject(resourceContent);
one(mockStore).getStoredObject(mockTransaction, path + "file1");
will(returnValue(file1So));
one(mockReq).getContextPath();
will(returnValue(""));
one(mockReq).getServletPath();
will(returnValue(path));
one(mockStore)
.getChildrenNames(mockTransaction, path + "file1");
will(returnValue(new String[] {}));
StoredObject file2So = initFileStoredObject(resourceContent);
one(mockStore).getStoredObject(mockTransaction, path + "file2");
will(returnValue(file2So));
one(mockReq).getContextPath();
will(returnValue(""));
one(mockReq).getServletPath();
will(returnValue(path));
one(mockStore)
.getChildrenNames(mockTransaction, path + "file2");
will(returnValue(new String[] {}));
}
});
DoPropfind doPropfind = new DoPropfind(mockStore, new ResourceLocks(),
mockMimeTyper);
doPropfind.execute(mockTransaction, mockReq, mockRes);
_mockery.assertIsSatisfied();
}
@Test
public void doPropFindOnFile() throws Exception {
final String path = "/testFile";
_mockery.checking(new Expectations() {
{
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getHeader("Depth");
will(returnValue("0"));
StoredObject fileSo = initFolderStoredObject();
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(fileSo));
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getContentLength();
will(returnValue(0));
// no content, which means it is a allprop request
one(mockRes).setStatus(WebdavStatus.SC_MULTI_STATUS);
one(mockRes).setContentType("text/xml; charset=UTF-8");
one(mockRes).getWriter();
will(returnValue(printWriter));
one(mockMimeTyper).getMimeType(path);
will(returnValue("text/xml; charset=UTF-8"));
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(fileSo));
one(mockReq).getContextPath();
will(returnValue(""));
one(mockReq).getServletPath();
will(returnValue("/"));
}
});
DoPropfind doPropfind = new DoPropfind(mockStore, new ResourceLocks(),
mockMimeTyper);
doPropfind.execute(mockTransaction, mockReq, mockRes);
_mockery.assertIsSatisfied();
}
@Test
public void doPropFindOnNonExistingResource() throws Exception {
final String path = "/notExists";
_mockery.checking(new Expectations() {
{
one(mockReq).getAttribute("javax.servlet.include.request_uri");
will(returnValue(null));
one(mockReq).getPathInfo();
will(returnValue(path));
one(mockReq).getHeader("Depth");
will(returnValue("0"));
StoredObject notExistingSo = null;
one(mockStore).getStoredObject(mockTransaction, path);
will(returnValue(notExistingSo));
one(mockRes).setContentType("text/xml; charset=UTF-8");
one(mockReq).getRequestURI();
will(returnValue(path));
one(mockRes).sendError(WebdavStatus.SC_NOT_FOUND, path);
}
});
DoPropfind doPropfind = new DoPropfind(mockStore, new ResourceLocks(),
mockMimeTyper);
doPropfind.execute(mockTransaction, mockReq, mockRes);
_mockery.assertIsSatisfied();
}
}
|
Markdown
|
UTF-8
| 112,131
| 2.75
| 3
|
[
"CC-BY-4.0"
] |
permissive
|
---
id: EntitySelectionClass
title: EntitySelection
---
Una entity selection es un objeto que contiene una o más referencias a [entidades](ORDA/dsMapping.md#entity) pertenecientes a la misma [Dataclass](ORDA/dsMapping.md#dataclass). Una entity selection puede contener 0, 1 o X entidades de la dataclass -- donde X puede representar el número total de entidades contenidas en la dataclass.
Las selecciones de entidades pueden crearse a partir de selecciones existentes utilizando varias funciones de la clase [`DataClass` class](DataClassClass.md) tales como [`.all()`](DataClassClass.md#all) o [`.query()`](DataClassClass.md#query), o de la clase `EntityClass` misma, tal como [`.and()`](#and) o [`orderBy()`](#orderby). También puede crear entity selections vacías utilizando la función [`dataClass.newSelection()`](DataClassClass.md#newselection) o el comando [`Create new selection`](#create-new-selection).
### Resumen
| |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [<!-- INCLUDE EntitySelectionClass.index.Syntax -->](#91index93) <!-- INCLUDE EntitySelectionClass.index.Summary --> |
| [<!-- INCLUDE EntitySelectionClass.attributeName.Syntax -->](#attributename) <!-- INCLUDE EntitySelectionClass.attributeName.Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.add().Syntax -->](#add) <!-- INCLUDE #EntitySelectionClass.add().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.and().Syntax -->](#and) <!-- INCLUDE #EntitySelectionClass.and().Summary --> |
| [<!-- INCLUDE EntitySelectionClass.at().Syntax -->](#attributename) <!-- INCLUDE EntitySelectionClass.at().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.average().Syntax -->](#average) <!-- INCLUDE #EntitySelectionClass.average().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.contains().Syntax -->](#contains) <!-- INCLUDE #EntitySelectionClass.contains().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.copy().Syntax -->](#contains) <!-- INCLUDE #EntitySelectionClass.copy().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.count().Syntax -->](#count) <!-- INCLUDE #EntitySelectionClass.count().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.distinct().Syntax -->](#distinct) <!-- INCLUDE #EntitySelectionClass.distinct().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.distinctPaths().Syntax -->](#distinctPaths) <!-- INCLUDE #EntitySelectionClass.distinctPaths().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.drop().Syntax -->](#drop) <!-- INCLUDE #EntitySelectionClass.drop().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.extract().Syntax -->](#extract) <!-- INCLUDE #EntitySelectionClass.extract().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.first().Syntax -->](#first) <!-- INCLUDE #EntitySelectionClass.first().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.getDataClass().Syntax -->](#getdataclass) <!-- INCLUDE #EntitySelectionClass.getDataClass().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.getRemoteContextAttributes().Syntax -->](#getremotecontextattributes) <!-- INCLUDE #EntityClass.getRemoteContextAttributes().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.isAlterable().Syntax -->](#isalterable) <!-- INCLUDE #EntitySelectionClass.isAlterable().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.isOrdered().Syntax -->](#isordered) <!-- INCLUDE #EntitySelectionClass.isOrdered().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.last().Syntax -->](#last) <!-- INCLUDE #EntitySelectionClass.last().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.length.Syntax -->](#length) <!-- INCLUDE #EntitySelectionClass.length.Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.max().Syntax -->](#max) <!-- INCLUDE #EntitySelectionClass.max().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.min().Syntax -->](#min) <!-- INCLUDE #EntitySelectionClass.min().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.minus().Syntax -->](#minus) <!-- INCLUDE #EntitySelectionClass.minus().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.or().Syntax -->](#or) <!-- INCLUDE #EntitySelectionClass.or().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.orderBy().Syntax -->](#orderby) <!-- INCLUDE #EntitySelectionClass.orderBy().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.orderByFormula().Syntax -->](#orderbyformula) <!-- INCLUDE #EntitySelectionClass.orderByFormula().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.query().Syntax -->](#query) <!-- INCLUDE #EntitySelectionClass.query().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.queryPath.Syntax -->](#querypath) <!-- INCLUDE #EntitySelectionClass.queryPath.Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.queryPlan.Syntax -->](#queryplan) <!-- INCLUDE #EntitySelectionClass.queryPlan.Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.refresh().Syntax -->](#refresh) <!-- INCLUDE #EntitySelectionClass.refresh().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.selected().Syntax -->](#selected) <!-- INCLUDE #EntitySelectionClass.selected().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.slice().Syntax -->](#slice) <!-- INCLUDE #EntitySelectionClass.slice().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.sum().Syntax -->](#sum) <!-- INCLUDE #EntitySelectionClass.sum().Summary --> |
| [<!-- INCLUDE #EntitySelectionClass.toCollection().Syntax -->](#tocollection) <!-- INCLUDE #EntitySelectionClass.toCollection().Summary --> |
## Crear una entity selection
<!-- REF #_command_.Create entity selection.Syntax -->**Create entity selection** ( *dsTable* : Table { ; *settings* : Object } ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #_command_.Create entity selection.Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ------------------ |:--:| ------------------------------------------------------------------------------------------------------------------- |
| dsTable | Tabla | -> | Tabla de la base 4D cuya selección actual se utilizará para construir la selección de entidades |
| settings | Object | -> | Opciones de construcción: context |
| Result | 4D.EntitySelection | <- | Selección de entidades que coinciden con la clase de datos relacionada con la tabla dada|<!-- END REF --> |
#### Descripción
El comando `Create entity selection` construye y devuelve una nueva, [alterable](ORDA/entities.md#shareable-or-alterable-entity-selections) selección de entidad relacionada con la clase de datos que coincide con la tabla *dsTable* dada, según la selección actual de esta tabla.
Si la selección actual está ordenada, se crea una selección de entidades [ordenada](ORDA/dsMapping.md#ordered-or-unordered-entity-selection) (se mantiene el orden de la selección actual). Si la selección actual no está ordenada, se crea una selección de entidades no ordenada.
Si la tabla *dsTable* no está expuesto en [`ds`](API/DataStoreClass.md#ds), se devuelve un error. Este comando no puede utilizarse con un datastore remoto.
En el parámetro opcional *settings*, puede pasar un objeto que contenga la siguiente propiedad:
| Propiedad | Tipo | Descripción |
| --------- | ---- | ----------------------------------------------------------------------------------------------------------------------- |
| context | Text | Etiqueta para el [contexto de optimización](ORDA/entities.md#clientserver-optimization) aplicado a la entity selection. |
#### Ejemplo
```4d
var $employees : cs.EmployeeSelection
ALL RECORDS([Employee])
$employees:=Create entity selection([Employee])
// La entity selection $employees ahora contiene un conjunto de referencias
// en todas las entidades relacionadas con la clase de datos Employee
```
#### Ver también
[`dataClass.newSelection()`](DataClassClass.md#newselection)
## USE ENTITY SELECTION
<!-- REF #_command_.USE ENTITY SELECTION.Syntax -->**USE ENTITY SELECTION** (*entitySelection*)<!-- END REF -->
<!-- REF #_command_.USE ENTITY SELECTION.Params -->
| Parámetros | Tipo | | Descripción |
| --------------- | --------------- |:--:| ----------------------------------------------- |
| entitySelection | EntitySelection | -> | Una entity selection|<!-- END REF --> |
#### Descripción
El comando `USE ENTITY SELECTION` actualiza la selección actual de la tabla que coincide con la dataclass del parámetro *entitySelection*, según el contenido de la entity selection.
Este comando no puede utilizarse con un [datastore remoto](../ORDA/remoteDatastores.md).
> Después de una llamada a `USE ENTITY SELECTION`, el primer registro de la selección actual actualizada (si no está vacío) se convierte en el registro actual, pero no se carga en la memoria. Si necesita utilizar los valores de los campos del registro actual, utilice el comando `LOAD RECORD` después del comando `USE ENTITY SELECTION`.
#### Ejemplo
```4d
var $entitySel : Object
$entitySel:=ds.Employee.query("lastName = :1";"M@") //$entitySel está asociado a la dataclass Employee
REDUCE SELECTION([Employee];0)
USE ENTITY SELECTION($entitySel) //Se actualiza la selección actual de la tabla Employee
```
<!-- REF EntitySelectionClass.index.Desc -->
## [*index*]
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF EntitySelectionClass.index.Syntax -->***[index]*** : 4D.Entity<!-- END REF -->
#### Descripción
La notación `EntitySelection[index]` <!-- REF EntitySelectionClass.index.Summary -->le permite acceder a las entidades dentro de la selección de entidades utilizando la sintaxis estándar de la colección<!-- END REF -->: pase la posición de la entidad que desea obtener en el parámetro *index*.
Tenga en cuenta que la entidad correspondiente se vuelve a cargar desde el almacén de datos.
*index* puede ser cualquier número entre 0 y `.length`-1.
* Si *index* está fuera de rango, se devuelve un error.
* If *attributeName* kind is `storage`: `.attributeName` returns a collection of values of the same type as *attributeName*.
:::caution
`EntitySelection[index]` es una expresión no asignable, lo que significa que no puede utilizarse como referencia modificable de la entidad con los métodos como [`.lock()`](EntityClass.md#lock) o [`.save()`](EntityClass.md#save). Para trabajar con la entidad correspondiente, es necesario asignar la expresión devuelta a una expresión asignable, como una variable. Ejemplos:
```4d
$sel:=ds.Employee.all() //creación de la entity selection
//declaraciones no válidas:
$result:=$sel[0].lock() //NO funcionará
$sel[0].lastName:="Smith" //NO funcionará
$result:=$sel[0].save() //NO funcionará
//valid code:
$entity:=$sel[0] //OK
$entity.lastName:="Smith" //OK
$entity.save() //OK
```
:::
#### Ejemplo
```4d
var $employees : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
$employees:=ds.Employee.query("lastName = :1";"H@")
$employee:=$employees[2] // La tercera entidad de la selección de entidades $employees se recarga de la base de datos
```
<!-- END REF -->
<!-- REF EntitySelectionClass.attributeName.Desc -->
## .*attributeName*
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF EntitySelectionClass.attributeName.Syntax -->***.attributeName*** : Collection<br/>***.attributeName*** : 4D.EntitySelection<!-- END REF -->
#### Descripción
Todo atributo de la clase de datos puede utilizarse como propiedad de una selección de entidades para devolver <!-- REF EntitySelectionClass.attributeName.Summary -->una "proyección" de valores para el atributo en la selección de entidades<!-- END REF -->. Los valores proyectados pueden ser una colección o una nueva selección de entidades, dependiendo de [kind](DataClassAttributeClass.md#kind) (`storage` o `relation`) del atributo.
* Si el tipo de *attributeName* es `storage`: `.attributeName` devuelve una colección de valores del mismo tipo que *attributeName*.
* If *attributeName* kind is `relatedEntity`: `.attributeName` returns a new entity selection of related values of the same type as *attributeName*. Se eliminan los duplicados (se devuelve una entity selection desordenada).
* If *attributeName* kind is `relatedEntities`: `.attributeName` returns a new entity selection of related values of the same type as *attributeName*. Se eliminan los duplicados (se devuelve una entity selection desordenada).
Cuando se utiliza un atributo de relación como propiedad de una selección de entidades, el resultado es siempre otra selección de entidades, aunque sólo se devuelva una entidad. Cuando se utiliza un atributo de relación como propiedad de una selección de entidades, el resultado es siempre otra selección de entidades, aunque sólo se devuelva una entidad.
Si el atributo no existe en la selección de entidades, se devuelve un error.
#### Ejemplo 1
Proyección de valores de almacenamiento:
```4d
var $firstNames : Collection
$entitySelection:=ds.Employee.all()
$firstNames:=$entitySelection.firstName // firstName es un string
```
La colección resultante es una colección de cadenas, por ejemplo:
```4d
[
"Joanna",
"Alexandra",
"Rick"
]
```
#### Ejemplo 2
Proyección de la entidad relacionada:
```4d
var $es; $entitySelection : cs.EmployeeSelection
$entitySelection:=ds.Employee.all()
$es:=$entitySelection.employer // employer está relacionado a la dataClass Company
```
El objeto resultante es una selección de entidades de la empresa con los duplicados eliminados (si los hay).
#### Ejemplo 3
Proyección de entidades relacionadas:
```4d
var $es : cs.EmployeeSelection
$es:=ds.Employee.all().directReports // directReports está relacionado a la dataclass Employee
```
El objeto resultante es una entity selection de la dataclass Employee sin duplicados (si los hay).
<!-- END REF -->
<!-- REF EntitySelectionClass.add().Desc -->
## .add()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | --------------------------------------------- |
| v19 R7 | Soporte del parámetro *entitySelection* |
| v18 R5 | Sólo soporta las entity selections alterables |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.add().Syntax -->**.add**( *entity* : 4D.Entity ) : 4D.EntitySelection<br/>**.add**( *entitySelection* : 4D.EntitySelection ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.add().Params -->
| Parámetros | Tipo | | Descripción |
| --------------- | ------------------ |:--:| ---------------------------------------------------------------------------------------------------- |
| entity | 4D.Entity | -> | Entidad que debe añadirse a la entity selection |
| entitySelection | 4D.EntitySelection | -> | Selección de entidades que se añade a la selección de entidades original |
| Result | 4D.EntitySelection | -> | Selección de entidades incluyendo la *entity* añadida o *entitySelection*|<!-- END REF --> |
#### Descripción
La función `.add()` <!-- REF #EntitySelectionClass.add().Summary -->añade la *entity* o *entitySelection* especificada a la selección de entidades original y devuelve la selección de entidades modificada<!-- END REF -->.
> Los valores de tipo Date se convierten en valores numéricos (segundos) y se utilizan para calcular la media.
:::info warning
La entity selection debe ser *alterable*, es decir, ha sido creado, por ejemplo, por [`.newSelection()`](DataClassClass.md#newselection) o `Create entity selection`, de lo contrario `.add()` devolverá un error. Las entity selections compartibles no aceptan la adición de entidades. Para más información, consulte la sección [Entity selections compartibles o modificables ](ORDA/entities.md#shareable-or-alterable-entity-selections) section.
:::
**Añadir una entidad**
* Si la entity selection está ordenada, *entity* se añade al final de la selección. Si una referencia a la misma entidad ya pertenece a la selección de entidades, se duplica y se añade una nueva referencia.
* Si la entity selection no está ordenada, *entity* se añade en cualquier lugar de la selección, sin un orden específico.
**Añadir una selección de entidades**
* Si la entity selection está ordenada, su orden se mantiene y *entitySelection* se añade al final de la selección. Si las referencias a las mismas entidades de *entitySelection* ya pertenecen a la selección de entidades, se duplican y se añaden nuevas referencias.
* Si la selección de entidades está desordenada, se convierte en ordenada.
> Para más información, consulte la sección [Entity selections ordenada o no ordenadas](ORDA/dsMapping.md#ordered-or-unordered-entity-selection).
La entity selection modificada es devuelta por la función, de modo que las llamadas a la función pueden encadenarse.
Se produce un error si *entity* y la entity selection no están relacionadas con la misma dataclass. Si *entity* es Null, no se produce ningún error.
#### Ejemplo 1
```4d
var $employees : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
$employees:=ds.Employee.newSelection()
$employee:=ds.Employee.new()
$employee.lastName:="Smith"
$employee.save()
$employees.add($employee) //La entidad $employee se añade a la selección de entidades $employees
```
#### Ejemplo 2
Las llamadas a la función se pueden encadenar:
```4d
var $sel : cs.ProductSelection
var $p1;$p2;$p3 : cs.ProductEntity
$p1:=ds.Product.get(10)
$p2:=ds.Product.get(11)
$p3:=ds.Product.get(12)
$sel:=ds.Product.newSelection()
$sel:=$sel.add($p1).add($p2).add($p3)
```
#### Ejemplo 3
En una interfaz de usuario, tenemos dos listas. El usuario selecciona elementos de la lista1 para añadirlos a la lista2.
```4d
$sellist2:=$sellist2.add($sellist1)
```
<!-- END REF -->
<!-- REF EntitySelectionClass.and().Desc -->
## .and()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.and().Syntax -->**.and**( *entity* : 4D.Entity ) : 4D.EntitySelection<br/>**.and**( *entitySelection* : 4D.EntitySelection ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.and().Params -->
| Parámetros | Tipo | | Descripción |
| --------------- | ------------------ |:--:| ---------------------------------------------------------------------------------------------------- |
| entity | 4D.Entity | -> | Entidad a intersectar |
| entitySelection | 4D.EntitySelection | -> | Entity selection a intersectar |
| Result | 4D.EntitySelection | <- | Entity selection resultante de la intersección con el operador lógico AND|<!-- END REF --> |
#### Descripción
La función `.and()` <!-- REF #EntitySelectionClass.and().Summary -->combina la selección de la entidad con un parámetro *entity* o *entitySelection* utilizando el operador lógico AND<!-- END REF -->; devuelve una nueva selección de entidades no ordenada que contiene sólo las entidades a las que se hace referencia tanto en la selección de entidades como en el parámetro.
* Si pasa *entity* como parámetro, se combina esta entidad con la entity selection. Si la entidad pertenece a la entity selection, se devuelve una nueva entity selection que sólo contiene la entidad. En caso contrario, se devuelve una selección de entidades vacía.
* If you pass *entity* as parameter, you compare this entity with the entity selection. If the entity belongs to the entity selection, a new reference to the entity selection is returned. Otherwise, a new entity selection containing the original entity selection and the entity is returned.
> > You can compare [ordered and/or unordered entity selections](ORDA/dsMapping.md#ordered-or-unordered-entity-selection). La selección resultante es siempre desordenada.
Si la entity selection inicial o el parámetro *entitySelection* están vacíos, o si *entity* es Null, se devuelve una entity selection vacía.
Si la entity selection inicial y el parámetro no están relacionados con la misma dataclass, se produce un error.
#### Ejemplo 1
```4d
var $employees; $result : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
$employees:=ds.Employee.query("lastName = :1";"H@")
//la entity selection $employees contiene la entidad
//con la llave primaria 710 y otras entidades
//por ejemplo. "Colin Hetrick" / "Grady Harness" / "Sherlock Holmes" (primary key 710)
$employee:=ds.Employee.get(710) // Devuelve "Sherlock Holmes"
$result:=$employees.and($employee) //$result es una selección de entidades que contiene
//sólo la entidad con llave primaria 710 ("Sherlock Holmes")
```
#### Ejemplo 2
Queremos tener una selección de empleados llamados "Jones" que vivan en Nueva York:
```4d
var $sel1; $sel2; $sel3 : cs.EmployeeSelection
$sel1:=ds.Employee.query("name =:1";"Jones")
$sel2:=ds.Employee.query("city=:1";"New York")
$sel3:=$sel1.and($sel2)
```
<!-- END REF -->
<!-- REF EntitySelectionClass.at().Desc -->
## .at()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v20 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.at().Syntax -->**.at**( *index* : Integer ) : 4D.Entity <!-- END REF -->
<!-- REF #EntitySelectionClass.at().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | --------- |:--:| --------------------------------------------------- |
| index | Integer | -> | Índice de la entidad a devolver |
| Result | 4D.Entity | <- | La entidad en ese índice|<!-- END REF --> |
#### Descripción
La función `.at()` <!-- REF #EntitySelectionClass.at().Summary -->devuelve la entidad en la posición *index*, permitiendo enteros positivos y negativos<!-- END REF -->.
Si *index* es negativo (de -1 a -n con n: longitud de la selección de entidades), la entidad devuelta se basará en el orden inverso de la selección de entidades.
La función devuelve Null si *index* está más allá de los límites de selección de entidades.
#### Ejemplo
```4d
var $employees : cs.EmployeeSelection
var $emp1; $emp2 : cs.EmployeeEntity
$employees:=ds.Employee.query("lastName = :1"; "H@")
$emp1:=$employees.at(2) /3ª entidad de la selección de entidades $employees
$emp2:=$employees.at(-3) //empezando por el final, 3ª entidad
//de la selección de entidades $employees
```
<!-- END REF -->
<!-- REF EntitySelectionClass.average().Desc -->
## .average()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | ---------------------------------------------------- |
| v18 R6 | Devuelve undefined si la entity selection está vacía |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.average().Syntax -->**.average**( *attributePath* : Text ) : Real<!-- END REF -->
<!-- REF #EntitySelectionClass.average().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ---- |:--:| ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| attributePath | Text | -> | Ruta del atributo a utilizar para el cálculo |
| Result | Real | <- | Media aritmética (promedio) de los valores de las entidades para el atributo (No se define para una entity selection vacía)|<!-- END REF --> |
#### Descripción
La función `.average()` <!-- REF #EntitySelectionClass.average().Summary -->The `.average()` function<!-- END REF -->.
Pase en el parámetro *attributePath* la ruta del atributo a evaluar.
Sólo se tienen en cuenta los valores numéricos para el cálculo. Tenga en cuenta, sin embargo, que si el *attributePath* de la selección de entidades contiene tipos de valores mixtos, `.average()` tiene en cuenta todos los elementos escalares para calcular el valor medio.
> Para más información sobre propiedad compartible de entity selections, consulte la sección [Entity selections compartibles o modificables](ORDA/entities.md#shareable-or-alterable-entity-selections).
`.average()` devuelve **undefined** si la entity selection está vacía o *attributePath* no contiene valores numéricos.
Se devuelve un error si:
* *>attributePath* es un atributo relativo,
* *attributePath* designa un atributo que no existe en la dataclass de la entity selection.
#### Ejemplo
Queremos obtener una lista de empleados cuyo salario es superior al salario medio:
```4d
var $averageSalary : Real
var $moreThanAv : cs.EmployeeSelection
$averageSalary:=ds.Employee.all().average("salary")
$moreThanAv:=ds.Employee.query("salary > :1";$averageSalary)
```
<!-- END REF -->
<!-- REF EntitySelectionClass.contains().Desc -->
## .contains()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.contains().Syntax -->**.contains**( *entity* : 4D.Entity ) : Boolean<!-- END REF -->
<!-- REF #EntitySelectionClass.contains().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | --------- |:--:| ---------------------------------------------------------------------------------------------------- |
| entity | 4D.Entity | -> | Entidad a evaluar |
| Result | Boolean | <- | True si la entidad pertenece a la entity selection, de lo contrario False|<!-- END REF --> |
#### Descripción
La función `.contains()` <!-- REF #EntitySelectionClass.contains().Summary -->devuelve true si la referencia de la entidad pertenece a la selección de entidades<!-- END REF -->, y false en caso contrario.
En *entity*, especifique la entidad a buscar en la entity selection. Si la entidad es Null, la función devolverá false.
Si *entity* y la entity selection no pertenecen a la misma dataclass, se produce un error.
#### Ejemplo
```4d
var $employees : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
$employees:=ds.Employee.query("lastName=:1";"H@")
$employee:=ds.Employee.get(610)
If($employees.contains($employee))
ALERT("La entidad con llave primaria 610 tiene un apellido que empieza por H")
Else
ALERT("La entidad con llave primaria 610 no tiene un apellido que empiece por H")
End if
```
<!-- END REF -->
<!-- REF EntitySelectionClass.count().Desc -->
## .count()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.count().Syntax -->**.count**( *attributePath* : Text ) : Real<!-- END REF -->
<!-- REF #EntitySelectionClass.count().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ---- |:--:| ---------------------------------------------------------------------------------------------- |
| attributePath | Text | -> | Ruta del atributo que se utilizará para el cálculo |
| Result | Real | <- | Número de valores de *attributePath* no null en la entity selection|<!-- END REF --> |
#### Descripción
La función `.push()` <!-- REF #EntitySelectionClass.count().Summary -->The `.count()` function<!-- END REF -->.
> Sólo se tienen en cuenta los valores escalares. Los valores de tipo objeto o colección se consideran valores nulos.
Se devuelve un error si:
* *>attributePath* es un atributo relativo,
* *attributePath* no se encuentra en la clase de datos de la entity selection.
#### Ejemplo
Queremos averiguar el número total de empleados de una empresa sin contar a los que no se les ha especificado el cargo:
```4d
var $sel : cs.EmployeeSelection
var $count : Real
$sel:=ds.Employee.query("employer = :1";"Acme, Inc")
$count:=$sel.count("jobtitle")
```
<!-- END REF -->
<!-- REF EntitySelectionClass.copy().Desc -->
## .copy()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v18 R5 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.copy().Syntax -->**.copy**( { *option* : Integer } ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.copy().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ------------------ |:--:| ------------------------------------------------------- |
| option | Integer | -> | `ck shared`: devuelve una entity selection compartible |
| Result | 4D.EntitySelection | <- | Copia de la entity selection|<!-- END REF --> |
#### Descripción
La función `.copy()` <!-- REF #EntitySelectionClass.copy().Summary -->The `.copy()` function<!-- END REF -->.
> Las entidades de una colección de entidades a las que se accede por medio de \[ ] no se recargan desde la base de datos.
Por defecto, si se omite el parámetro *option*, la función devuelve una nueva entity selection alterable (incluso si la función se aplica a una entity selection compartible). Pasa la constante `ck shared` en el parámetro *option* si quiere crear una entity selection compartible.
> Esta función siempre devuelve True cuando la entity selection proviene de un datastore remoto.
#### Ejemplo
Se crea una nueva entidad vacía de selección de productos cuando se carga el formulario:
```4d
Case of
:(Form event code=On Load)
Form.products:=ds.Products.newSelection()
End case
```
A continuación, esta selección de entidades se actualiza con productos y se desea compartir los productos entre varios procesos. Se copia la selección de la entidad Form.products como compartible:
```4d
...
// La selección de entidades de Form.products se actualiza
Form.products.add(Form.selectedProduct)
Use(Storage)
If(Storage.products=Null)
Storage.products:=New shared object()
End if
Use(Storage.products)
Storage.products:=Form.products.copy(ck shared)
End use
End use
```
<!-- END REF -->
<!-- REF EntitySelectionClass.distinct().Desc -->
## .distinct()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | ---------------------------- |
| v20 | Soporte de `dk count values` |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.distinct().Syntax -->**.distinct**( *attributePath* : Text { ; *options* : Integer } ) : Collection<!-- END REF -->
<!-- REF #EntitySelectionClass.distinct().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ---------- |:--:| --------------------------------------------------------------- |
| attributePath | Text | -> | Ruta del atributo cuyos valores distintos desea obtener |
| options | Integer | -> | `dk diacritical`, `dk count values` |
| Result | Collection | <- | Colección con sólo valores distintos|<!-- END REF --> |
#### Descripción
La función `.distinct()` <!-- REF #EntitySelectionClass.distinct().Summary -->The `.distinct()` function<!-- END REF -->.
La colección devuelta se clasifica automáticamente. Los valores **Null** no se devuelven.
En el parámetro *attributePath*, pase el atributo de entidad cuyos valores distintos quiere obtener. Sólo se pueden manejar valores escalares (texto, número, booleano o fecha). Los tipos se devuelven en el siguiente orden: Si *attributePath* lleva a una propiedad de objeto que contiene valores de diferentes tipos, primero se agrupan por tipo y se ordenan después.
1. booleans
2. cadenas
3. numbers
4. dates
Se puede utilizar la notación `[]` para designar una colección cuando *attributePath* es una ruta dentro de un objeto (ver ejemplos).
En el parámetro *options*, puede pasar una o una combinación de las siguientes constantes:
| Constante | Valor | Comentario |
| ----------------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dk diacritical` | 8 | La evaluación distingue entre mayúsculas y minúsculas y diferencia los caracteres acentuados. Por defecto si se omite, se realiza una evaluación no diacrítica |
| `dk count values` | 32 | Devuelve el conteo de entidades para cada valor distinto. Cuando se pasa esta opción, `.distinct()` devuelve una colección de objetos que contienen un par de propiedades `{"value":*value*; "count":*count*}`. |
:::note
La opción `dk count values` sólo está disponible con atributos de almacenamiento de tipo booleano, cadena, número y fecha.
:::
Se devuelve un error si:
* *>attributePath* es un atributo relativo,
* *attributePath* no se encuentra en la clase de datos de la entity selection.
#### Ejemplos
Quiere obtener una colección que contenga un solo elemento por nombre de país:
```4d
var $countries : Collection
$countries:=ds.Employee.all().distinct("address.country")
//$countries[0]={"Argentina"}
//$countries[1]={"Australia"}
//$countries[2]={"Belgium"}
///...
```
`nicknames` es una colección y `extra` es un atributo de objeto:
```4d
$values:=ds.Employee.all().distinct("extra.nicknames[].first")
```
Desea obtener el número de nombres de posiciones diferentes en la empresa:
```4d
var $jobs : Collection
$jobs:=ds.Employee.all().distinct("jobName";dk count values)
//$jobs[0]={"value":"Developer";"count":17}
//$jobs[1]={"value":"Office manager";"count":5}
//$jobs[2]={"value":"Accountant";"count":2}
//...
```
<!-- END REF -->
<!-- REF EntitySelectionClass.distinctPaths().Desc -->
## .distinctPaths()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v20 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.distinctPaths().Syntax -->**.distinctPaths**( *attribute* : Text ) : Collection<!-- END REF -->
<!-- REF #EntitySelectionClass.distinctPaths().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ---------- |:--:| -------------------------------------------------------------- |
| atributo | Text | -> | Nombre del atributo del objeto cuyas rutas desea obtener |
| Result | Collection | <- | Nueva colección con rutas distintas|<!-- END REF --> |
#### Descripción
La función `.distinctPaths()` <!-- REF #EntitySelectionClass.distinctPaths().Summary -->devuelve una colección de rutas distintas encontradas en el objeto indexado *attribute* para la selección de entidades<!-- END REF -->.
Si *attribute* no es un atributo de objeto indexado, se genera un error.
Tras la llamada, el tamaño de la colección devuelta es igual al número de rutas distintas encontradas en *attribute* para la selección de entidades. Las rutas se devuelven como cadenas que incluyen atributos anidados y colecciones, por ejemplo "info.address.number" o "children[].birthdate". Las entidades con un valor null en el *attribute* no se tienen en cuenta.
#### Ejemplo
Desea obtener todas las rutas almacenadas en un atributo objeto *fullData*:
```4d
var $paths : Collection
$paths:=ds.Employee.all().distinctPaths("fullData")
//$paths[0]="age"
//$paths[1]="Children"
//$paths[2]="Children[].age"
//$paths[3]="Children[].name"
//$paths[4]="Children.length"
///...
```
:::note
*length* se añade automáticamente como ruta para las propiedades de colección anidadas.
:::
<!-- END REF -->
<!-- REF EntitySelectionClass.drop().Desc -->
## .drop()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.drop().Syntax -->**.drop**( { *mode* : Integer } ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.drop().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ------------------ |:--:| ------------------------------------------------------------------------------------------------------------------------------------------- |
| mode | Integer | -> | `dk stop dropping on first error`: detiene la ejecución del método en la primera entidad no suprimible |
| Result | 4D.EntitySelection | <- | Entity selection vacía si se ejecuta con éxito, si no entity selection que contengan las entidades no eliminables<!-- END REF --> |
#### Descripción
La función `.drop()` <!-- REF #EntitySelectionClass.drop().Summary -->elimina las entidades pertenecientes a la selección de entidades de la tabla relacionada con su clase de datos dentro del almacén de datos<!-- END REF -->. La entity selection permanece en la memoria.
> La eliminación de entidades es permanente y no se puede deshacer. Se recomienda llamar a esta acción en una transacción para tener una opción de recuperación.
Si se encuentra una entidad bloqueada durante la ejecución de `.drop()`, no se elimina. Por defecto, el método procesa todas las entidades de la selección de entidades y devuelve las entidades no eliminables en la selección de entidades. Si quiere que el método detenga la ejecución en la primera entidad no suprimible encontrada, pase la constante `dk stop dropping on first error` en el parámetro *mode*.
#### Ejemplo
Ejemplo sin la opción `dk stop dropping on first error`:
```4d
var $employees; $notDropped : cs.EmployeeSelection
$employees:=ds.Employee.query("firstName=:1";"S@")
$notDropped:=$employees.drop() // $notDropped es una entity selection que contiene todas las entidades que no suprimidas
If($notDropped.length=0) //La acción de eliminación es exitosa, todas las entidades han sido eliminadas
ALERT("You have dropped "+String($employees.length)+" employees") //La selección de entidades eliminada permanece en la memoria
Else
ALERT("Problem during drop, try later")
End if
```
Ejemplo con la opción `dk stop dropping on first error`:
```4d
var $employees; $notDropped : cs.EmployeeSelection
$employees:=ds.Employee.query("firstName=:1";"S@")
$notDropped:=$employees.drop(dk stop dropping on first error) //$notDropped es una entity selection que contiene la primera entidad no suprimida
If($notDropped.length=0) //La acción de eliminación es exitosa, todas las entidades han sido eliminadas
ALERT("You have dropped "+String($employees.length)+" employees") //La selección de entidades eliminada permanece en la memoria
Else
ALERT("Problem during drop, try later")
End if
```
<!-- END REF -->
<!-- REF EntitySelectionClass.extract().Desc -->
## .extract()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v18 R3 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.extract().Syntax --> **.extract**( *attributePath* : Text { ; *option* : Integer } ) : Collection<br/>**.extract**( *attributePath* { ; *targetPath* } { ; *...attributePathN* : Text ; *targetPathN* : Text } ) : Collection<!-- END REF -->
<!-- REF #EntitySelectionClass.extract().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ---------- |:--:| ------------------------------------------------------------------------------------------- |
| attributePath | Text | -> | Ruta del atributo cuyos valores deben ser extraídos en la nueva colección |
| targetPath | Text | -> | Ruta o nombre del atributo objetivo |
| option | Integer | -> | `ck keep null`: incluye los atributos null en la colección devuelta (ignorados por defecto) |
| Result | Collection | <- | Colección que contiene los valores extraídos|<!-- END REF --> |
#### Descripción
La función `.reduce()` <!-- REF #EntitySelectionClass.extract().Summary -->devuelve una colección que contiene *attributePath* valores extraídos de la selección de la entidad<!-- END REF -->.
*attributePath* puede referirse a:
* un atributo escalar de dataclass,
* entidad relacionada,
* entidades relacionadas.
Si *attributePath* no es válido, se devuelve una colección vacía.
Esta función acepta dos sintaxis.
**.extract( attributePath : Text { ; option : Integer } ) : Collection**
Con esta sintaxis, `.extract()` llena la colección devuelta con los valores *attributePath* de la entity selection.
Por defecto, las entidades para las que *attributePath* es *null* o indefinida se ignoran en la colección resultante. Puede pasar la constante `ck keep null` en el parámetro *option* para incluir estos valores como elementos **null** en la colección devuelta.
* Los atributos dataclass [.kind](DataClassAttributeClass.md#kind) = "relatedEntity" se extraen como una colección de entidades (se mantienen las duplicaciones).
* Los atributos dataclass con [.kind](DataClassAttributeClass.md#kind) = "relatedEntities" se extraen como una colección de entity selections.
**.extract ( attributePath ; targetPath { ; ...attributePathN ; ... targetPathN}) : Collection**
Con esta sintaxis, `.extract()` llena la colección devuelta con las propiedades *attributePath*. Cada elemento de la colección devuelta es un objeto con las propiedades *targetPath* llenadas con las propiedades *attributePath* correspondientes. Se mantienen los valores null (el parámetro *option* se ignora) con esta sintaxis.
Si se dan varios *attributePath*, debe darse un *targetPath* para cada uno. Sólo se extraen los pares válidos \[*attributePath*, *targetPath*].
* Los atributos dataclass con [.kind](DataClassAttributeClass.md#kind) = "relatedEntity" se extraen como una entidad.
* Los atributos dataclass con [.kind](DataClassAttributeClass.md#kind) = "relatedEntities" se extraen como una entity selection.
> Los valores Null se evalúan como inferiores a los otros valores.
#### Ejemplo
Dada la siguiente tabla y relación:

```4d
var $firstnames; $addresses; $mailing; $teachers : Collection
//
//
//$firstnames es una colección de cadenas
$firstnames:=ds.Teachers.all().extract("firstname")
//
//$addresses es una colección de entidades relacionadas con la dataclass Address
//Se extraen los valores null de Address
$addresses:=ds.Teachers.all().extract("address";ck keep null)
//
//
//$mailing es una colección de objetos con las propiedades "who" y "to"
//El contenido de la propiedad "who" es de tipo Cadena
//El contenido de la propiedad "to" es de tipo entity (dataclass Address)
$mailing:=ds.Teachers.all().extract("lastname";"who";"address";"to")
//
//
//$mailing es una colección de objetos con las propiedades "who" y "city"
//El contenido de la propiedad "who" es de tipo Cadena
//El contenido de la propiedad "city" es de tipo Cadena
$mailing:=ds.Teachers.all().extract("lastname";"who";"address.city";"city")
//
//$teachers es una colección de objetos con las propiedades "where" y "who"
//El contenido de la propiedad "where" es de tipo Cadena
//El contenido de la propiedad "who" es una entity selection (dataclass Teachers)
$teachers:=ds.Address.all().extract("city";"where";"teachers";"who")
//
//$teachers es una colección de entity selections
$teachers:=ds.Address.all().extract("teachers")
```
<!-- END REF -->
<!-- REF EntitySelectionClass.first().Desc -->
## .first()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.first().Syntax -->**.first()** : 4D.Entity<!-- END REF -->
<!-- REF #EntitySelectionClass.first().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | --------- |:--:| ------------------------------------------------------------------------------------------------------------------- |
| Result | 4D.Entity | <- | Referencia a la primera entidad de la entity selection (Null si la selección está vacía)|<!-- END REF --> |
#### Descripción
La función `.first()` <!-- REF #EntitySelectionClass.first().Summary -->devuelve una referencia a la entidad en la primera posición de la selección de entidades<!-- END REF -->.
El resultado de esta función es similar a:
```4d
$entity:=$entitySel[0]
```
Sin embargo, hay una diferencia entre ambas afirmaciones cuando la selección está vacía:
```4d
var $entitySel : cs.EmpSelection
var $entity : cs.EmpEntity
$entitySel:=ds.Emp.query("lastName = :1";"Nonexistentname") //ninguna entidad correspondiente
//entity selection is then empty
$entity:=$entitySel.first() //devuelve Null
$entity:=$entitySel[0] //genera un error
```
#### Ejemplo
```4d
var $entitySelection : cs.EmpSelection
var $entity : cs.EmpEntity
$entitySelection:=ds.Emp.query("salary > :1";100000)
If($entitySelection.length#0)
$entity:=$entitySelection.first()
End if
```
<!-- END REF -->
<!-- REF EntitySelectionClass.getDataClass().Desc -->
## .getDataClass()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 R5 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.getDataClass().Syntax -->**.getDataClass()** : 4D.DataClass<!-- END REF -->
<!-- REF #EntitySelectionClass.getDataClass().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ------------ |:--:| --------------------------------------------------------------------------- |
| Result | 4D.DataClass | <- | DataClass a la que pertenece la entity selection|<!-- END REF --> |
#### Descripción
La función `.getDataClass()` <!-- REF #EntitySelectionClass.getDataClass().Summary -->The `.getDataClass()` function<!-- END REF -->.
Esta función es principalmente útil en el contexto del código genérico.
#### Ejemplo
El siguiente código genérico duplica todas las entidades de la entity selection:
```4d
//método duplicate_entities
//duplicate_entities($entity_selection)
#DECLARE ( $entitySelection : 4D.EntitySelection )
var $dataClass : 4D.DataClass
var $entity; $duplicate : 4D.Entity
var $status : Object
$dataClass:=$entitySelection.getDataClass()
For each($entity;$entitySelection)
$duplicate:=$dataClass.new()
$duplicate.fromObject($entity.toObject())
$duplicate[$dataClass.getInfo().primaryKey]:=Null //restablecer la llave primaria
$status:=$duplicate.save()
End for each
```
<!-- END REF -->
<!-- REF EntitySelectionClass.getRemoteContextAttributes().Desc -->
## .getRemoteContextAttributes()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v19R5 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.getRemoteContextAttributes().Syntax -->Devuelve:<!-- END REF -->
<!-- REF #EntitySelectionClass.getRemoteContextAttributes().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ---- | -- | --------------------------------------------------------------------------------------------------------- |
| result | Text | <- | Atributos de contexto vinculados a la entity selection, separados por una coma|<!-- END REF --> |
> **Modo avanzado:** esta función está pensada para los desarrolladores que necesitan personalizar las funcionalidades por defecto de ORDA para configuraciones específicas. En la mayoría de los casos, no será necesario utilizarla.
#### Descripción
La función `.getRemoteContextAttributes()` <!-- REF #EntitySelectionClass.getRemoteContextAttributes().Summary -->devuelve información sobre el contexto de optimización utilizado por la selección de entidades<!-- END REF -->.
Si no hay [contexto de optimización](../ORDA/remoteDatastores.md#clientserver-optimization) para la entity selection, la función devuelve un texto vacío.
#### Ejemplo
```4d
var $ds : 4D.DataStoreImplementation
var $persons : cs.PersonsSelection
var $p : cs.PersonsEntity
var $info : Text
var $text : Text
$ds:=Open datastore(New object("hostname"; "www.myserver.com"); "myDS")
$persons:=$ds.Persons.all()
$text:=""
For each ($p; $persons)
$text:=$p.firstname+" lives in "+$p.address.city+" / "
End for each
$info:=$persons.getRemoteContextAttributes()
//$info = "firstname,address,address.city"
```
#### Ver también
[Entity.getRemoteContextAttributes()](./EntityClass.md#getRemoteContextAttributes)<br/>[.clearAllRemoteContexts()](./DataStoreClass.md#clearallremotecontexts)<br/>[.getRemoteContextInfo()](./DataStoreClass.md#getremotecontextinfo)<br/>[.getAllRemoteContexts()](./DataStoreClass.md#getallremotecontexts)<br/>[.setRemoteContextInfo()](./DataStoreClass.md#setremotecontextinfo)
<!-- REF EntitySelectionClass.isAlterable().Desc -->
## .isAlterable()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v18 R5 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.isAlterable().Syntax -->**.isAlterable()** : Boolean<!-- END REF -->
<!-- REF #EntitySelectionClass.isAlterable().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ------- |:--:| -------------------------------------------------------------------------------------------- |
| Result | Boolean | <- | True si la entity selection es modificable, de lo contrario False|<!-- END REF --> |
#### Descripción
La función `.isAlterable()` <!-- REF #EntitySelectionClass.isAlterable().Summary -->devuelve True si la selección de entidades es modificable<!-- END REF --> y False si la selección de la entidad no es modificable.
Para más información, consulte la sección [Entity selections compartibles o modificables](ORDA/entities.md#shareable-or-alterable-entity-selections).
#### Ejemplo
Va a mostrar `Form.products` en un [list box](FormObjects/listbox_overview.md) para que el usuario pueda añadir nuevos productos. Quiere asegurarse de que es modificable para que el usuario pueda añadir nuevos productos sin error:
```4d
If (Not(Form.products.isAlterable()))
Form.products:=Form.products.copy()
End if
...
Form.products.add(Form.product)
```
<!-- END REF -->
<!-- REF EntitySelectionClass.isOrdered().Desc -->
## .isOrdered()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.isOrdered().Syntax -->**.isOrdered()** : Boolean<!-- END REF -->
<!-- REF #EntitySelectionClass.isOrdered().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ------- |:--:| ----------------------------------------------------------------------------------------- |
| Result | Boolean | <- | True si la entity selection es ordenada, de lo contrario False|<!-- END REF --> |
#### Descripción
La función `.isOrdered()` <!-- REF #EntitySelectionClass.isOrdered().Summary -->devuelve True si la selección de entidades está ordenada<!-- END REF -->, y False si no está ordenada.
> Esta función no modifica la selección de entidades original.
Para más información, consulte [Entity selection ordenadas o desordenadas](ORDA/dsMapping.md#ordered-or-unordered-entity-selection).
#### Ejemplo
```4d
var $employees : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
var $isOrdered : Boolean
$employees:=ds.Employee.newSelection(dk keep ordered)
$employee:=ds.Employee.get(714) // Obtiene la entidad con llave primaria 714
//En una entity selection ordenada, podemos añadir la misma entidad varias veces (los duplicados se mantienen)
$employees.add($employee)
$employees.add($employee)
$employees.add($employee)
$isOrdered:=$employees.isOrdered()
If($isOrdered)
ALERT("The entity selection is ordered and contains "+String($employees.length)+" employees")
End if
```
<!-- END REF -->
<!-- REF EntitySelectionClass.last().Desc -->
## .last()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.last().Syntax -->**.last()** : 4D.Entity<!-- END REF -->
<!-- REF #EntitySelectionClass.last().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | --------- |:--:| ------------------------------------------------------------------------------------------------------------------------------------- |
| Result | 4D.Entity | <- | Referencia a la última entidad de la selección de entidades (Null si la selección de entidades está vacía)|<!-- END REF --> |
#### Descripción
La función `.last()` <!-- REF #EntitySelectionClass.last().Summary -->devuelve una referencia a la entidad en la última posición de la selección de entidades<!-- END REF -->.
El resultado de esta función es similar a:
```4d
$entity:=$entitySel[length-1]
```
Si la entity selection está vacía, la función devuelve Null.
#### Ejemplo
```4d
var $entitySelection : cs.EmpSelection
var $entity : cs.EmpEntity
$entitySelection:=ds.Emp.query("salary < :1";50000)
If($entitySelection.length#0)
$entity:=$entitySelection.last()
End if
```
<!-- END REF -->
<!-- REF EntitySelectionClass.length.Desc -->
## .length
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.length.Syntax -->**.length**: Integer<!-- END REF -->
#### Descripción
La propiedad `.length` <!-- REF #EntitySelectionClass.length.Summary -->devuelve el número de entidades en la selección de entidades<!-- END REF -->. Si la entity selection está vacía, devuelve 0.
Las entity selections siempre tienen una propiedad `.length`.
> Las entidades de una colección de entidades a las que se accede por medio de \[ ] no se recargan desde la base de datos.
#### Ejemplo
```4d
var $vSize : Integer
$vSize:=ds.Employee.query("gender = :1";"male").length
ALERT(String(vSize)+" male employees found.")
```
<!-- END REF -->
<!-- REF EntitySelectionClass.max().Desc -->
## .max()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | ---------------------------------------------------- |
| v17 | Añadidos |
| v18 R6 | Devuelve undefined si la entity selection está vacía |
</details>
<!-- REF #EntitySelectionClass.max().Syntax -->**.max**( *attributePath* : Text ) : any<!-- END REF -->
<!-- REF #EntitySelectionClass.max().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ---- | -- | ------------------------------------------------------ |
| attributePath | Text | -> | Ruta del atributo que se utilizará para el cálculo |
| Result | any | <- | Valor más alto del atributo|<!-- END REF --> |
#### Descripción
La función `.max()` <!-- REF #EntitySelectionClass.max().Summary -->devuelve el valor más alto (o máximo) entre todos los valores de *attributePath* en la selección de entidades<!-- END REF -->. En realidad devuelve el valor de la última entidad de la selección de entidades tal y como se ordenaría de forma ascendente utilizando la función [`.orderBy()`](#orderby).
Si se pasa en *attributePath* una ruta a una propiedad de objeto que contiene diferentes tipos de valores, la función `.max()` devolverá el valor máximo dentro del primer tipo escalar en el orden de la lista de tipos 4D por defecto (ver la descripción de [`.sort()`](CollectionClass.md#sort)).
`.max()` devuelve **undefined** si la entity selection está vacía o si *attributePath* no se encuentra en el atributo objeto.
Se devuelve un error si:
* *>attributePath* es un atributo relativo,
* *attributePath* designa un atributo que no existe en la dataclass de la entity selection.
#### Ejemplo
Queremos encontrar el salario más alto entre todas las empleadas:
```4d
var $sel : cs.EmpSelection
var $maxSalary : Real
$sel:=ds.Employee.query("gender = :1";"female")
$maxSalary:=$sel.max("salary")
```
<!-- END REF -->
<!-- REF EntitySelectionClass.min().Desc -->
## .min()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | ---------------------------------------------------- |
| v17 | Añadidos |
| v18 R6 | Devuelve undefined si la entity selection está vacía |
</details>
<!-- REF #EntitySelectionClass.min().Syntax -->**.min**( *attributePath* : Text ) : any<!-- END REF -->
<!-- REF #EntitySelectionClass.min().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ---- |:--:| ------------------------------------------------------ |
| attributePath | Text | -> | Ruta del atributo que se utilizará para el cálculo |
| Result | any | <- | Valor más bajo del atributo|<!-- END REF --> |
#### Descripción
La función `.min()` <!-- REF #EntitySelectionClass.min().Summary --> devuelve el valor más bajo (o mínimo) entre todos los valores de attributePath en la selección de entidades<!-- END REF -->. En realidad devuelve el valor de la primera entidad de la selección si se ordenara de forma ascendente utilizando la función [`.orderBy()`](#orderby) (excluyendo los valores **null**).
Si se pasa en *attributePath* una ruta a una propiedad objeto que contiene diferentes tipos de valores, la función `.min()` devolverá el valor mínimo dentro del primer tipo de valor escalar en el orden de la lista de tipos (ver la descripción de [`.sort()`](CollectionClass.md#sort)).
`.min()` devuelve **undefined** si la entity selection está vacía o si *attributePath* no se encuentra en el atributo objeto.
Se devuelve un error si:
* *>attributePath* es un atributo relativo,
* *attributePath* designa un atributo que no existe en la dataclass de la entity selection.
#### Ejemplo
En este ejemplo, queremos encontrar el salario más bajo entre todas las empleadas:
```4d
var $sel : cs.EmpSelection
var $minSalary : Real
$sel:=ds.Employee.query("gender = :1";"female")
$minSalary:=$sel.min("salary")
```
<!-- END REF -->
<!-- REF EntitySelectionClass.minus().Desc -->
## .minus()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | --------------------------------- |
| v19 R7 | Soporte del parámetro *keepOrder* |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.minus().Syntax -->**.minus**( *entity* : 4D.Entity { ; *keepOrder* : Integer } ) : 4D.EntitySelection<br/>**.minus**( *entitySelection* : 4D.EntitySelection { ; *keepOrder* : Integer } ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.minus().Params -->
| Parámetros | Tipo | | Descripción |
| --------------- | ------------------ |:--:| --------------------------------------------------------------------------------------------------------------------- |
| entity | 4D.Entity | -> | Entidad a sustraer |
| entitySelection | 4D.EntitySelection | -> | Entity selection a sustraer |
| keepOrder | Integer | -> | `dk keep ordered` (entero) para mantener el orden inicial en la selección de entidades resultante |
| Result | 4D.EntitySelection | <- | Nueva selección de entidades o una nueva referencia en la selección de entidades existente|<!-- END REF --> |
#### Descripción
La función `.minus()` <!-- REF #EntitySelectionClass.minus().Summary -->excluye de la selección de entidades a la que se aplica la *entidad* o las entidades de *entitySelection* y devuelve la selección de entidades resultante<!-- END REF -->.
* Si se pasa *entity* como parámetro, la función crea una nueva entity selection sin *entity* (si *entity* pertenece a la entity selection). Si *entity* no estaba incluida en la entity selection original, se devuelve una nueva referencia a la entity selection.
* Si se pasa *entitySelection* como parámetro, la función devuelve una entity selection que contiene las entidades pertenecientes a la entity selection original sin las entidades pertenecientes a *entitySelection*. > You can compare [ordered and/or unordered entity selections](ORDA/dsMapping.md#ordered-or-unordered-entity-selection).
Por defecto, si se omite el parámetro *keepOrder*, la selección de entidades resultante es desordenada. Si desea mantener el orden de la selección de entidades original (por ejemplo, si desea reutilizar la selección de entidades en una interfaz de usuario), pase la constante `dk keep ordered` en *keepOrder*. En este caso, el resultado es una selección de entidades ordenada y se mantiene el orden de la selección de entidades inicial.
:::note
Si pasa `dk keep ordered` en *keepOrder* y la *entitySelection* eliminada contiene las entidades duplicadas en la selección de entidades original, se eliminan todas las ocurrencias de los duplicados.
:::
Si la entity selection inicial o la entity selection inicial y la del parámetro *entitySelection* están vacías, se devuelve una entity selection vacía.
Si *entitySelection* está vacía o si *entity* es Null, se devuelve una nueva referencia a la entity selection original.
Si la entity selection inicial y el parámetro no están relacionados con la misma dataclass, se produce un error.
#### Ejemplo 1
```4d
var $employees; $result : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
$employees:=ds.Employee.query("lastName = :1";"H@")
// la entity selection $employees contiene la entidad con llave primaria 710 y otras entidades
// por ejemplo. "Colin Hetrick", "Grady Harness", "Sherlock Holmes" (primary key 710)
$employee:=ds.Employee.get(710) // Devuelve "Sherlock Holmes"
$result:=$employees.minus($employee) //$result contiene "Colin Hetrick", "Grady Harness"
```
#### Ejemplo 2
Queremos tener una selección de empleadas llamadas "Jones" que vivan en Nueva York :
```4d
var $sel1; $sel2; $sel3 : cs.EmployeeSelection
$sel1:=ds.Employee.query("name =:1";"Jones")
$sel2:=ds.Employee.query("city=:1";"New York")
$sel3:=$sel1.and($sel2).minus(ds.Employee.query("gender='male'"))
```
#### Ejemplo 3
En una interfaz de usuario, tenemos una lista que muestra los elementos en un orden específico. Si el usuario selecciona elementos de la lista para eliminarlos, el orden debe mantenerse al refrescar la lista:
```4d
$listsel:=$listsel.minus($selectedItems; dk keep ordered)
```
<!-- END REF -->
<!-- REF EntitySelectionClass.or().Desc -->
## .or()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.or().Syntax -->**.or**( *entity* : 4D.Entity ) : 4D.EntitySelection<br/>**.or**( *entitySelection* : 4D.EntitySelection ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.or().Params -->
| Parámetros | Tipo | | Descripción |
| --------------- | ------------------ |:--:| -------------------------------------------------------------------------------------------------------- |
| entity | 4D.Entity | -> | Entidad a intersectar |
| entitySelection | 4D.EntitySelection | -> | Entity selection a intersectar |
| Result | 4D.EntitySelection | <- | Nueva entity selection o una nueva referencia a la entity selection de origen|<!-- END REF --> |
#### Descripción
La función `.or()` <!-- REF #EntitySelectionClass.or().Summary -->combina la selección de entidades con el parámetro *entity* o *entitySelection* utilizando el operador lógico (no exclusivo) OR<!-- END REF -->; devuelve una nueva selección de entidades no ordenada que contiene todas las entidades de la selección de entidades y el parámetro.
* Si se pasa como parámetro la *entidad*, se compara esta entidad con la selección de entidades. Se devuelve una nueva selección de entidades que contiene sólo las entidades a las que se hace referencia en ambas selecciones. A new entity selection that contains only the entities that are referenced in both selections is returned.
* If the original entity selection and the *entitySelection* parameter are empty, an empty entity selection is returned. If the original entity selection is empty, a reference to *entitySelection* or an entity selection containing only *entity* is returned.
> > You can compare [ordered and/or unordered entity selections](ORDA/dsMapping.md#ordered-or-unordered-entity-selection). La selección resultante es siempre desordenada.
The returned entity selection contains the entities specified by *startFrom* and all subsequent entities up to, but not including, the entity specified by *end*. If only the *startFrom* parameter is specified, the returned entity selection contains all entities from *startFrom* to the last entity of the original entity selection.
Si *entitySelection* está vacía o si *entity* es Null, se devuelve una nueva referencia a la entity selection original.
Si la entity selection inicial y el parámetro no están relacionados con la misma dataclass, se produce un error.
#### Ejemplo 1
```4d
var $employees1; $employees2; $result : cs.EmployeeSelection
$employees1:=ds.Employee.query("lastName = :1";"H@") //Devuelve "Colin Hetrick","Grady Harness"
$employees2:=ds.Employee.query("firstName = :1";"C@") //Devuelve "Colin Hetrick", "Cath Kidston"
$result:=$employees1.or($employees2) //$result contiene "Colin Hetrick", "Grady Harness","Cath Kidston"
```
#### Ejemplo 2
```4d
var $employees; $result : cs.EmployeeSelection
var $employee : cs.EmployeeEntity
$employees:=ds.Employee.query("lastName = :1";"H@") // Devuelve "Colin Hetrick","Grady Harness", "Sherlock Holmes"
$employee:=ds.Employee.get(686) //la entidad con llave primaria 686 no pertenece a la entity selection $employees
//Coincide con la empleada "Mary Smith"
$result:=$employees.or($employee) //$result contiene "Colin Hetrick", "Grady Harness", "Sherlock Holmes", "Mary Smith"
```
<!-- END REF -->
<!-- REF EntitySelectionClass.orderBy().Desc -->
## .orderBy()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.orderBy().Syntax -->**.orderBy**( *pathString* : Text ) : 4D.EntitySelection<br/>**.orderBy**( *pathObjects* : Collection ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.orderBy().Params -->
| Parámetros | Tipo | | Descripción |
| ----------- | ------------------ |:--:| -------------------------------------------------------------------------------- |
| pathString | Text | -> | Ruta(s) de atributos e instrucciones de clasificación para la entity selection |
| pathObjects | Collection | -> | Colección de objetos criterio |
| Result | 4D.EntitySelection | <- | Nueva selección de entidades en el orden especificado|<!-- END REF --> |
#### Descripción
La función `.fill()` <!-- REF #EntitySelectionClass.orderBy().Summary -->The `.orderBy()` function<!-- END REF -->.
> * Este método no modifica la selección de entidades original.
> * Para más información sobre las selecciones de entidades ordenadas, consulte la sección [Selección de entidades ordenadas o no ordenadas](ORDA/dsMapping.md#ordered-or-unordered-entity-selection).
Debe utilizar un parámetro de criterio para definir cómo deben ordenarse las entidades. Se soportan dos parámetros diferentes:
* *pathString* (Texto): este parámetro contiene una fórmula compuesta de rutas de atributo de 1 a x y (opcionalmente) órdenes de clasificación, separados por comas. La sintaxis es:
```4d
"attributePath1 {desc or asc}, attributePath2 {desc or asc},..."
```
El orden en que se pasan los atributos determina la prioridad de ordenación de las entidades. Por defecto, los atributos se clasifican en orden ascendente. Puede definir el orden de clasificación de una propiedad en la cadena de criterios, separado de la ruta de la propiedad por un solo espacio: pase "asc" para ordenar en orden ascendente o "desc" en orden descendente.
* *pathObjects* (collection): cada elemento de la colección contiene un objeto estructurado de la siguiente manera:
```4d
{
"propertyPath": string,
"descending": boolean
}
```
Por defecto, los atributos se clasifican en orden ascendente ("descending" es false).
Puede añadir tantos objetos en la colección de criterios como sea necesario.
> Esta función sólo funciona con un datastore remoto (cliente/servidor o conexión `Open datastore`).
Si pasa una ruta de atributo inválida en *pathString* o *pathObject*, la función devuelve una selección de entidad vacía.
#### Ejemplo
```4d
// orden con fórmula
$sortedEntitySelection:=$entitySelection.orderBy("firstName asc, salary desc")
$sortedEntitySelection:=$entitySelection.orderBy("firstName")
// orden con collection con o sin órdenes de clasificación
$orderColl:=New collection
$orderColl.push(New object("propertyPath";"firstName";"descending";False))
$orderColl.push(New object("propertyPath";"salary";"descending";True))
$sortedEntitySelection:=$entitySelection.orderBy($orderColl)
$orderColl:=New collection
$orderColl.push(New object("propertyPath";"manager.lastName"))
$orderColl.push(New object("propertyPath";"salary"))
$sortedEntitySelection:=$entitySelection.orderBy($orderColl)
```
<!-- END REF -->
<!-- REF EntitySelectionClass.orderByFormula().Desc -->
## .orderByFormula()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 R6 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.orderByFormula().Syntax -->**.orderByFormula**( *formulaString* : Text { ; *sortOrder* : Integer } { ; *settings* : Object} ) : 4D.EntitySelection<br/>**.orderByFormula**( *formulaObj* : Object { ; *sortOrder* : Integer } { ; *settings* : Object} ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.orderByFormula().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ------------------ |:--:| ---------------------------------------------------------- |
| formulaString | Text | -> | Cadena formula |
| formulaObj | Object | -> | Objeto formula |
| sortOrder | Integer | -> | `dk ascending` (por defecto) o`dk descending` |
| settings | Object | -> | Parámetros de la fórmula |
| Result | 4D.EntitySelection | <- | Nueva entity selection ordenada|<!-- END REF --> |
#### Descripción
La función `.orderByFormula()` <!-- REF #EntitySelectionClass.orderByFormula().Summary -->devuelve una nueva selección ordenada de entidades<!-- END REF --> que contiene todas las entidades de la selección de entidades en el orden definido mediante los parámetros *formulaString* o *formulaObj* y, opcionalmente, *sortOrder* y *settings*.
> Las entidades de una colección de entidades a las que se accede por medio de \[ ] no se recargan desde la base de datos.
Puede utilizar un parámetro *formulaString* o un parámetro *formulaObj*:
- *formulaString*: se pasa una expresión 4D como "Year of(this.birthDate)".
- *formulaObj*: pase un objeto fórmula válido creado con el comando `Formula` o `Formula from string`.
La fórmula de *formulaString* o *formulaObj* se ejecuta para cada entidad de la entity selection y su resultado se utiliza para definir la posición de la entidad en la entity selection devuelta. El resultado debe ser de un tipo ordenable (booleano, fecha, número, texto, hora, null).
> Un resultado null es siempre el valor más pequeño.
Por defecto, si se omite el parámetro *sortOrder*, la selección de entidades resultante se clasifica en orden ascendente. Opcionalmente, puede pasar uno de los siguientes valores en el parámetro *sortOrder*:
| Constante | Valor | Comentario |
| ------------- | ----- | ------------------------------ |
| dk ascending | 0 | Orden ascendente (por defecto) |
| dk descending | 1 | Orden descendente |
Dentro de *formulaString* o *formulaObj*, la entidad procesada y, por tanto, sus atributos están disponibles a través del comando `This` (por ejemplo, `This.lastName`).
Puede pasar parámetros a la fórmula utilizando la propiedad `args/0> (objeto) del parámetro <code>settings`: la fórmula recibe el objeto `settings.args` en $1.
#### Ejemplo 1
Clasificar a los alumnos mediante una fórmula dada como texto:
```4d
var $es1; $es2 : cs.StudentsSelection
$es1:=ds.Students.query("nationality=:1";"French")
$es2:=$es1.orderByFormula("length(this.lastname)") //ascendente por defecto
$es2:=$es1.orderByFormula("length(this.lastname)";dk descending)
```
El mismo orden de clasificación pero utilizando un objeto fórmula:
```4d
var $es1; $es2 : cs.StudentsSelection
var $formula : Object
$es1:=ds.Students.query("nationality=:1";"French")
$formula:=Formula(Length(This.lastname))
$es2:=$es1.orderByFormula($formula) // ascendente por defecto
$es2:=$es1.orderByFormula($formula;dk descending)
```
#### Ejemplo 2
Una fórmula se da como un objeto fórmula con parámetros; el objeto `settings.args` se recibe como $1 en el método ***computeAverage***.
En este ejemplo, el campo objeto "marks" de la dataClass **Students** contiene las notas de los estudiantes para cada asignatura. Se utiliza un solo objeto fórmula para calcular la nota media de un alumno con diferentes coeficientes para schoolA y schoolB.
```4d
var $es1; $es2 : cs.StudentsSelection
var $formula; $schoolA; $schoolB : Object
$es1:=ds.Students.query("nationality=:1";"French")
$formula:=Formula(computeAverage($1))
$schoolA:=New object() //settings object
$schoolA.args:=New object("english";1;"math";1;"history";1) // Coeficientes para calcular una media
//Ordenar a los estudiantes según los criterios de la escuela A
$es2:=$es1.entitySelection.orderByFormula($formula;$schoolA)
$schoolB:=New object() //object settings
$schoolB.args:=New object("english";1;"math";2;"history";3) // Coeficientes para calcular un promedio
//Ordenar a los estudiantes según los criterios de la escuela B
$es2:=$es1.entitySelection.orderByFormula($formula;dk descending;$schoolB)
```
```4d
//
// método computeAverage
// -----------------------------
#DECLARE ($coefList : Object) -> $result : Integer
var $subject : Text
var $average; $sum : Integer
$average:=0
$sum:=0
For each($subject;$coefList)
$sum:=$sum+$coefList[$subject]
End for each
For each($subject;This.marks)
$average:=$average+(This.marks[$subject]*$coefList[$subject])
End for each
$result:=$average/$sum
```
<!-- END REF -->
<!-- REF EntitySelectionClass.query().Desc -->
## .query()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | ------------------------------------------ |
| v17 R6 | Soporte de los parámetros Formula |
| v17 R5 | Soporte de los marcadores para los valores |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.query().Syntax -->**.query**( *queryString* : Text { ; *...value* : any } { ; *querySettings* : Object } ) : 4D.EntitySelection <br/>**.query**( *formula* : Object { ; *querySettings* : Object } ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.query().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ------------------ |:--:| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| queryString | Text | -> | Criterios de búsqueda como cadena |
| formula | Object | -> | Criterios de búsqueda como objeto fórmula |
| value | any | -> | Valor(es) a utilizar para los marcadores de posición indexados |
| querySettings | Object | -> | Opciones de búsqueda: parameters, attributes, args, allowFormulas, context, queryPath, queryPlan |
| Result | 4D.EntitySelection | <- | Nueva selección de entidades formada por las entidades de la entity selection que cumplen los criterios de búsqueda especificados en *queryString* o*formula*|<!-- END REF --> |
#### Descripción
La función `.query()` <!-- REF #EntitySelectionClass.query().Summary -->busca entidades que cumplan los criterios de búsqueda especificados en *queryString* o *formula* y (opcionalmente) *valor*(s) entre todas las entidades de la selección de entidades<!-- END REF -->y devuelve un nuevo objeto de tipo `EntitySelection` que contiene todas las entidades encontradas. Se aplica carga diferida.
> Las entidades de una colección de entidades a las que se accede por medio de \[ ] no se recargan desde la base de datos.
Si no se encuentran entidades coincidentes, se devuelve una `EntitySelection` vacía.
Si no se encuentran entidades coincidentes, se devuelve una `EntitySelection` vacía.
> Por defecto, si se omite la declaración **order by** en *queryString*, la entity selection devuelta es [no ordenada](ORDA/dsMapping.md#ordered-or-unordered-entity-selection). Sin embargo, tenga en cuenta que, en modo Cliente/Servidor, se comporta como una selección de entidades ordenada (las entidades se añaden al final de la selección).
#### Ejemplo 1
```4d
var $entitySelectionTemp : cs.EmployeeSelection
$entitySelectionTemp:=ds.Employee.query("lastName = :1";"M@")
Form.emps:=$entitySelectionTemp.query("manager.lastName = :1";"S@")
```
#### Ejemplo 2
Para obtener información detallada sobre cómo construir una consulta utilizando los parámetros *queryString*, *value<* y *querySettings*, consulte la descripción de la función de dataClass [`.query()`](DataClassClass.md#query).
#### Ver también
Se pueden encontrar más ejemplos de búsquedas en la página [`.query()`](DataClassClass.md#query) DataClass.
<!-- END REF -->
<!-- REF EntitySelectionClass.queryPath.Desc -->
## .queryPath
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.queryPath.Syntax -->**.queryPath** : Text<!-- END REF -->
#### Descripción
La propiedad `.queryPath` <!-- REF #EntitySelectionClass.queryPath.Summary -->contiene una descripción detallada de la consulta tal y como fue realizada por 4D<!-- END REF -->. Esta propiedad está disponible para los objetos de tipo `EntitySelection` generados a través de búsquedas si la propiedad `"queryPath":true` fue pasada en el parámetro *querySettings* de la función [`.query()`](#query).
Para más información, consulte el párrafo **querySettings** en la página [`.query()`](DataClassClass.html#query) Dataclass.
<!-- END REF -->
<!-- REF EntitySelectionClass.queryPlan.Desc -->
## .queryPlan
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.queryPlan.Syntax -->**.queryPlan** : Text<!-- END REF -->
#### Descripción
La propiedad `.queryPlan` <!-- REF #EntitySelectionClass.queryPlan.Summary --> contiene una descripción detallada de la consulta justo antes de su ejecución (es decir, la consulta prevista)<!-- END REF -->. Esta propiedad está disponible para los objetos de tipo `EntitySelection` generados a través de búsquedas si la propiedad `"queryPlan":true` fue pasada en el parámetro *querySettings* de la función [`.query()`](#query).
Para más información, consulte el párrafo **querySettings** en la página [`.query()`](DataClassClass.html#query) Dataclass.
<!-- END REF -->
<!-- REF EntitySelectionClass.refresh().Desc -->
## .refresh()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v18 R3 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.refresh().Syntax -->**.refresh()**<!-- END REF -->
<!-- REF #EntitySelectionClass.refresh().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ---- |::| ------------------------------------------------------- |
| | | | No requiere ningún parámetro|<!-- END REF --> |
#### Descripción
> Esta función sólo funciona con un datastore remoto (cliente/servidor o conexión `Open datastore`).
La función `.refresh()` <!-- REF #EntitySelectionClass.refresh().Summary -->invalida inmediatamente los datos de selección de entidades en la caché ORDA local<!-- END REF --> para que la próxima vez que 4D requiera la selección de entidades, ésta se recargue de la base de datos.
Por defecto, la caché local de ORDA se invalida después de 30 segundos. En el contexto de las aplicaciones cliente/servidor que utilizan tanto ORDA como el lenguaje clásico, este método le permite asegurarse de que una aplicación remota siempre funcionará con los datos más recientes.
#### Ejemplo 1
En este ejemplo, el código clásico y el código ORDA modifican los mismos datos simultáneamente:
```4d
//En un 4D remoto
var $selection : cs.StudentsSelection
var $student : cs.StudentsEntity
$selection:=ds.Students.query("lastname=:1";"Collins")
//La primera entidad se carga en la caché de ORDA
$student:=$selection.first()
//Actualización con un 4D clásico, la caché ORDA no es consciente de si
QUERY([Students];[Students]lastname="Collins")
[Students]lastname:="Colin"
SAVE RECORD([Students])
//para obtener la última versión, hay que invalidar la caché de ORDA
$selection.refresh()
// Aunque la caché no haya caducado, la primera entidad se recarga desde el disco
$student:=$selection.first()
//$student.lastname contains "Colin"
```
#### Ejemplo 2
En este ejemplo, el código clásico y el código ORDA modifican los mismos datos simultáneamente:
```4d
// Form method: Case of
:(Form event code=On Load)
Form.students:=ds.Students.all()
End case
//
//
// On client #1, the user loads, updates, and saves the first entity
// On client #2, the user loads, updates, and saves the same entity
//
//
// On client #1:
Form.students.refresh() // Invalidates the ORDA cache for the Form.students entity selection
// The list box content is refreshed from the database with update made by client #2
```
<!-- END REF -->
<!-- REF EntitySelectionClass.selected().Desc -->
## .selected()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v19 R3 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.selected().Syntax -->**.selected**( *selectedEntities* : 4D.EntitySelection ) : Object<!-- END REF -->
<!-- REF #EntitySelectionClass.selected().Params -->
| Parámetros | Tipo | | Descripción |
| ---------------- | ------------------ |:--:| -------------------------------------------------------------------------------------------------- |
| selectedEntities | 4D.EntitySelection | -> | Selección de entidades con entidades para las cuales conocer el rango en la selección de entidades |
| Result | Object | <- | Rango(s) de entidades seleccionadas en la selección de entidades|<!-- END REF --> |
#### Descripción
La función `.selected()` <!-- REF #EntitySelectionClass.selected().Summary -->devuelve un objeto que describe la(s) posición(es) de *selectedEntities* en la selección original de entidades<!-- END REF -->.
> Las entidades de una colección de entidades a las que se accede por medio de \[ ] no se recargan desde la base de datos.
Pase en el parámetro *selectedEntities* una selección de entidades que contenga entidades de las que desee conocer la posición en la selección de entidades original. *selectedEntities* debe ser una selección de entidades que pertenezca a la misma clase de datos que la selección de entidades original, de lo contrario se produce un error 1587 - "La selección de entidades procede de una clase de datos incompatible".
#### Result
El objeto devuelto contiene las siguientes propiedades:
| Propiedad | Tipo | Descripción |
| -------------- | ---------- | ---------------------------------------- |
| ranges | Collection | Colección de objetos rango |
| ranges[].start | Integer | Índice de la primera entidad en el rango |
| ranges[].end | Integer | Índice de la última entidad en el rango |
Si una propiedad `ranges` contiene una sola entidad, `start` = `end`. El índice comienza en 0.
La función devuelve una colección vacía en la propiedad `ranges` si la selección de entidades original o la selección de entidades *selectedEntities* está vacía.
#### Ejemplo
```4d
var $invoices; $cashSel; $creditSel : cs.Invoices
var $result1; $result2 : Object
$invoices:=ds.Invoices.all()
$cashSelection:=ds.Invoices.query("payment = :1"; "Cash")
$creditSel:=ds.Invoices.query("payment IN :1"; New collection("Cash"; "Credit Card"))
$result1:=$invoices.selected($cashSelection)
$result2:=$invoices.selected($creditSel)
//$result1 = {ranges:[{start:0;end:0},{start:3;end:3},{start:6;end:6}]}
//$result2 = {ranges:[{start:0;end:1},{start:3;end:4},{start:6;end:7}]}
```
<!-- END REF -->
<!-- REF EntitySelectionClass.slice().Desc -->
## .slice()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.slice().Syntax -->**.slice**( *startFrom* : Integer { ; *end* : Integer } ) : 4D.EntitySelection<!-- END REF -->
<!-- REF #EntitySelectionClass.slice().Params -->
| Parámetros | Tipo | | Descripción |
| ---------- | ------------------ |:--:| ---------------------------------------------------------------------------------------------------- |
| startFrom | Integer | -> | Índice para iniciar la operación (incluído) |
| end | Integer | -> | Índice final (no incluido) |
| Result | 4D.EntitySelection | <- | Nueva entity selection que contiene la entidades extraídas (shallow copy)|<!-- END REF --> |
#### Descripción
La función `.slice()` <!-- REF #EntitySelectionClass.slice().Summary -->devuelve una parte de una selección de entidades en una nueva selección de entidades<!-- END REF -->, seleccionada desde el índice *startFrom* hasta el índice *end* (no se incluye*end* ) o hasta la última entidad de la selección de entidades. Este método devuelve una shallow copy (copia superficial) de la entity selection (utiliza las mismas referencias de entidades).
> Las entidades de una colección de entidades a las que se accede por medio de \[ ] no se recargan desde la base de datos.
If *startFrom* < 0, it is recalculated as *startFrom:=startFrom+length* (it is considered as the offset from the end of the entity selection). If the calculated value < 0, *startFrom* is set to 0.
* Si *startFrom* < 0, se recalcula como *startFrom:=startFrom+length*(se considera el desplazamiento desde el final de la entity selection). Si el valor calculado < 0, *startFrom* toma el valor 0.
* Si *startFrom >= length*, la función devuelve una selección de entidades vacía.
* Si *end* < 0, se recalcula como *end:=end+length*.
* If *end < startFrom* (passed or calculated values), the method does nothing.
`.sum()` devuelve 0 si la entity selection está vacía.
#### Ejemplo 1
Si la entity selection contiene entidades que se han eliminado mientras tanto, también se devuelven.
```4d
var $sel; $sliced : cs.EmployeeSelection
$sel:=ds.Employee.query("salary > :1";50000)
$sliced:=$sel.slice(0;9) //
```
#### Ejemplo 2
Assuming we have ds. Employee.all().length = 10
```4d
var $slice : cs.EmployeeSelection
$slice:=ds.Employee.all().slice(-1;-2) //intenta devolver entidades del índice 9 al 8, pero como 9 > 8, devuelve una entity selection vacía
```
<!-- END REF -->
<!-- REF EntitySelectionClass.sum().Desc -->
## .sum()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.sum().Syntax -->**.sum**( *attributePath* : Text ) : Real<!-- END REF -->
<!-- REF #EntitySelectionClass.sum().Params -->
| Parámetros | Tipo | | Descripción |
| ------------- | ---- |:--:| --------------------------------------------------------------------- |
| attributePath | Text | -> | Ruta del atributo que se utilizará para el cálculo |
| Result | Real | <- | Suma de los valores de la entity selection|<!-- END REF --> |
#### Descripción
La función `.orderByMethod()` <!-- REF #EntitySelectionClass.sum().Summary -->The `.sum()` function<!-- END REF -->.
La función `.sum()` <!-- REF #EntitySelectionClass.sum().Summary -->devuelve la suma de todos los valores de *attributePath* en la entity selection<!-- END REF -->.
La suma sólo puede hacerse en valores de tipo numérico. Si *attributePath* es una propiedad objeto, sólo se tienen en cuenta los valores numéricos para el cálculo (se ignoran otros tipos de valores). En este caso, si *attributePath* lleva a una propiedad que no existe en el objeto o no contiene ningún valor numérico, `.sum()` devuelve 0.
Se devuelve un error si:
* *attributePath<* no es un atributo numérico o un objeto,
* *>attributePath* es un atributo relativo,
* *attributePath* no se encuentra en la clase de datos de la entity selection.
#### Ejemplo
```4d
var $sel : cs.EmployeeSelection
var $sum : Real
$sel:=ds.Employee.query("salary < :1";20000)
$sum:=$sel.sum("salary")
```
<!-- END REF -->
<!-- REF EntitySelectionClass.toCollection().Desc -->
## .toCollection()
<details><summary>Histórico</summary>
| Versión | Modificaciones |
| ------- | -------------- |
| v17 | Añadidos |
</details>
<!-- REF #EntitySelectionClass.toCollection().Syntax -->**.toCollection**( { *options* : Integer { ; *begin* : Integer { ; *howMany* : Integer } } ) : *Collection*<br/>**.toCollection**( *filterString* : Text {; *options* : Integer { ; *begin* : Integer { ; *howMany* : Integer }}} ) : *Collection*<br/>**.toCollection**( *filterCol* : Collection {; *options* : Integer { ; *begin* : Integer { ; *howMany* : Integer }}} ) : *Collection*<!-- END REF -->
<!-- REF #EntitySelectionClass.toCollection().Params -->
| Parámetros | Tipo | | Descripción |
| ------------ | ---------- |:--:| -------------------------------------------------------------------------------------------------------------- |
| filterString | Text | -> | Cadena con la(s) ruta(s) de atributos de la entidad a extraer |
| filterCol | Collection | -> | Colección de rutas de atributos de entidad a extraer |
| options | Integer | -> | `dk with primary key`: adds the primary key<br/>`dk with stamp`: adds the stamp |
| begin | Integer | -> | Designa el índice inicial |
| howMany | Integer | -> | Número de entidades a extraer |
| Result | Collection | <- | Colección de objetos que contienen atributos y valores de la selección de entidades|<!-- END REF --> |
#### Descripción
La función `.toCollection()` <!-- REF #EntitySelectionClass.toCollection().Summary -->crea y devuelve una colección donde cada elemento es un objeto que contiene un conjunto de propiedades y valores <!-- END REF -->correspondientes a los nombres y valores de los atributos de la selección de entidades.
Si no se pasa ningún parámetro de filtro o si el primer parámetro contiene una cadena vacía o "*", se extraen todos los atributos. Los atributos con la propiedad [kind](DataClassAttributeClass.md#kind) como "relatedEntity" se extraen con el formulario simple: un objeto con la propiedad \_\_KEY (llave primaria). Los atributos con la propiedad kind como "relatedEntities" no se extraen.
O bien, puede designar los atributos de la entidad a extraer utilizando un parámetro de filtro. Puede utilizar uno de estos dos filtros:
* *filterString<* --una cadena con rutas de propiedades separadas por comas: "propertyPath1, propertyPath2, ...".
* *filterCol*: --una colección de cadenas que contiene la rutas de propiedades: \["propertyPath1","propertyPath2",...]
Si se especifica un filtro para un atributo de tipo `relatedEntity`:
* propertyPath = "relatedEntity" -> se extrae con una forma simple
* propertyPath = "relatedEntity.*" -> se extraen todas las propiedades
* propertyPath = "relatedEntity.propertyName1, relatedEntity.propertyName2, ..." -> sólo se extraen esas propiedades
Si se especifica un filtro para un atributo de tipo `relatedEntity`:
* propertyPath = "relatedEntities.*" -> se extraen todas las propiedades
* propertyPath = "relatedEntities.propertyName1, relatedEntities.propertyName2, ..." -> sólo se extraen esas propiedades
Si se especifica un filtro para un atributo de tipo `relatedEntities`:
:::caution Advertencia
Si utiliza otro atributo distinto de la llave primaria como atributo Uno en una relación, el valor de este atributo se escribirá en la propiedad "__KEY". Tenga en cuenta que se recomienda utilizar la llave primaria como atributo Uno en sus relaciones, especialmente cuando utilice las funciones `.toCollection()` y `.fromCollection()`.
:::
El parámetro *begin* permite indicar el índice de inicio de las entidades a extraer. Puede pasar cualquier valor entre 0 y la longitud de la entity selection -1.
El parámetro *howMany* permite especificar el número de entidades a extraer, empezando por la especificada en *begin*. Las entidades descartadas no se devuelven pero se tienen en cuenta en *howMany*. Por ejemplo, si *howMany*= 3 y hay 1 entidad descartada, sólo se extraen 2 entidades.
Si el "kind" de *attributeName* es `storage`: `.attributeName` devuelve una colección de valores del mismo tipo que *attributeName*.
Si *howMany* > longitud de la entity selection, el método devuelve (length - *begin*) objetos.
* la entity selection está vacía, o
* *begin* es mayor que la longitud de la entity selection.
#### Ejemplo 1
En todos los ejemplos de esta sección se utilizará la siguiente estructura:

Ejemplo sin parámetros de filtro ni de opciones:
```4d
var $employeesCollection : Collection
var $employees : cs.EmployeeSelection
$employeesCollection:=New collection
$employees:=ds.Employee.all()
$employeesCollection:=$employees.toCollection()
```
Ejemplo con el tipo `relatedEntity` con una forma simple:
```4d
[
{
"ID": 416,
"firstName": "Gregg",
"lastName": "Wahl",
"salary": 79100,
"birthDate": "1963-02-01T00:00:00.000Z",
"woman": false,
"managerID": 412,
"employerID": 20,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 20
},
"manager": {
"__KEY": 412
}
},
{
"ID": 417,
"firstName": "Irma",
"lastName": "Durham",
"salary": 47000,
"birthDate": "1992-06-16T00:00:00.000Z",
"woman": true,
"managerID": 412,
"employerID": 20,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 20
},
"manager": {
"__KEY": 412
}
}
]
```
#### Ejemplo 2
Devuelve:
```4d
var $employeesCollection : Collection
var $employees : cs.EmployeeSelection
$employeesCollection:=New collection
$employees:=ds.Employee.all()
$employeesCollection:=$employees.toCollection("";dk with primary key+dk with stamp)
```
Ejemplo con el tipo `relatedEntity` con una forma simple:
```4d
[
{
"__KEY": 416,
"__STAMP": 1,
"ID": 416,
"firstName": "Gregg",
"lastName": "Wahl",
"salary": 79100,
"birthDate": "1963-02-01T00:00:00.000Z",
"woman": false,
"managerID": 412,
"employerID": 20,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 20
},
"manager": {
"__KEY": 412
}
},
{
"__KEY": 417,
"__STAMP": 1,
"ID": 417,
"firstName": "Irma",
"lastName": "Durham",
"salary": 47000,
"birthDate": "1992-06-16T00:00:00.000Z",
"woman": true,
"managerID": 412,
"employerID": 20,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 20
},
"manager": {
"__KEY": 412
}
}]
```
#### Ejemplo 3
Devuelve:
```4d
var $employeesCollection; $filter : Collection
var $employees : cs.EmployeeSelection
$employeesCollection:=New collection
$filter:=New collection
$filter.push("firstName")
$filter.push("lastName")
$employees:=ds.Employee.all()
$employeesCollection:=$employees.toCollection($filter;0;0;2)
```
Ejemplo con el tipo `relatedEntity` con una forma simple:
```4d
[
{
"firstName": "Gregg",
"lastName": "Wahl"
},
{
"firstName": "Irma",
"lastName": "Durham"
}
]
```
#### Ejemplo 4
Devuelve:
```4d
var $employeesCollection : Collection
$employeesCollection:=New collection
$employeesCollection:=$employees.toCollection("firstName,lastName,employer")
```
Ejemplo con el tipo `relatedEntity` con una forma simple:
```4d
[
{
"firstName": "Gregg",
"lastName": "Wahl",
"employer": {
"__KEY": 20
}
},
{
"firstName": "Irma",
"lastName": "Durham",
"employer": {
"__KEY": 20
}
},
{
"firstName": "Lorena",
"lastName": "Boothe",
"employer": {
"__KEY": 20
}
}
]
```
#### Ejemplo 5
devuelve:
```4d
var $employeesCollection; $coll : Collection
$employeesCollection:=New collection
$coll:=New collection("firstName";"lastName")
$employeesCollection:=$employees.toCollection($coll)
```
Ejemplo con el tipo `relatedEntity` con una forma simple:
```4d
[
{
"firstName": "Joanna",
"lastName": "Cabrera"
},
{
"firstName": "Alexandra",
"lastName": "Coleman"
}
]
```
#### Ejemplo 6
Devuelve:
```4d
var $employeesCollection; $coll : Collection
$employeesCollection:=New collection
$coll:=New collection
$coll.push("firstName")
$coll.push("lastName")
$coll.push("employer.*")
$employeesCollection:=$employees.toCollection($coll)
```
Ejemplo con el tipo `relatedEntity` con una forma simple:
```4d
[
{
"firstName": "Gregg",
"lastName": "Wahl",
"employer": {
"ID": 20,
"name": "India Astral Secretary",
"creationDate": "1984-08-25T00:00:00.000Z",
"revenues": 12000000,
"extra": null
}
},
{
"firstName": "Irma",
"lastName": "Durham",
"employer": {
"ID": 20,
"name": "India Astral Secretary",
"creationDate": "1984-08-25T00:00:00.000Z",
"revenues": 12000000,
"extra": null
}
},
{
"firstName": "Lorena",
"lastName": "Boothe",
"employer": {
"ID": 20,
"name": "India Astral Secretary",
"creationDate": "1984-08-25T00:00:00.000Z",
"revenues": 12000000,
"extra": null
}
}
]
```
#### Ejemplo 7
Devuelve:
```4d
var $employeesCollection : Collection
$employeesCollection:=New collection
$employeesCollection:=$employees.toCollection("firstName, lastName, employer.name")
```
```4d
[
{
"firstName": "Gregg",
"lastName": "Wahl",
"employer": {
"name": "India Astral Secretary"
}
},
{
"firstName": "Irma",
"lastName": "Durham",
"employer": {
"name": "India Astral Secretary"
}
},
{
"firstName": "Lorena",
"lastName": "Boothe",
"employer": {
"name": "India Astral Secretary"
}
}]
```
#### Ejemplo 8
Ejemplo con la extracción de algunas las propiedades de relatedEntity:
```4d
var $employeesCollection : Collection
$employeesCollection:=New collection
$employeesCollection:=$employees.toCollection("firstName, lastName, directReports.firstName")
```
Ejemplo con el tipo `relatedEntity` con una forma simple:
```4d
[
{
"firstName": "Gregg",
"lastName": "Wahl",
"directReports": []
},
{
"firstName": "Mike",
"lastName": "Phan",
"directReports": [
{
"firstName": "Gary"
},
{
"firstName": "Sadie"
},
{
"firstName": "Christie"
}
]
},
{
"firstName": "Gary",
"lastName": "Reichert",
"directReports": [
{
"firstName": "Rex"
},
{
"firstName": "Jenny"
},
{
"firstName": "Lowell"
}
]
}]
```
#### Ejemplo 9
Devuelve:
```4d
var $employeesCollection : Collection
$employeesCollection:=New collection
$employeesCollection:=$employees.toCollection("firstName, lastName, directReports.*")
```
```4d
[
{
"firstName": "Gregg",
"lastName": "Wahl",
"directReports": []
},
{
"firstName": "Mike",
"lastName": "Phan",
"directReports": [
{
"ID": 425,
"firstName": "Gary",
"lastName": "Reichert",
"salary": 65800,
"birthDate": "1957-12-23T00:00:00.000Z",
"woman": false,
"managerID": 424,
"employerID": 21,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 21
},
"manager": {
"__KEY": 424
}
},
{
"ID": 426,
"firstName": "Sadie",
"lastName": "Gallant",
"salary": 35200,
"birthDate": "2022-01-03T00:00:00.000Z",
"woman": true,
"managerID": 424,
"employerID": 21,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 21
},
"manager": {
"__KEY": 424
}
}
]
},
{
"firstName": "Gary",
"lastName": "Reichert",
"directReports": [
{
"ID": 428,
"firstName": "Rex",
"lastName": "Chance",
"salary": 71600,
"birthDate": "1968-08-09T00:00:00.000Z",
"woman": false,
"managerID": 425,
"employerID": 21,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 21
},
"manager": {
"__KEY": 425
}
},
{
"ID": 429,
"firstName": "Jenny",
"lastName": "Parks",
"salary": 51300,
"birthDate": "1984-05-25T00:00:00.000Z",
"woman": true,
"managerID": 425,
"employerID": 21,
"photo": "[object Picture]",
"extra": null,
"employer": {
"__KEY": 21
},
"manager": {
"__KEY": 425
}
}
]
}
]
```
<!-- END REF -->
|
Java
|
UTF-8
| 857
| 2.390625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package hx.codeReviewer.lang.wm.ast;
import com.wm.lang.flow.FlowLoop;
/**
*
* @author Xiaowei Wang
* @version 1.1
*
* This class represents flow element com.wm.lang.flow.FlowLoop.
*
*/
public class ASTFlowLoop extends AbstractFlowElement {
public ASTFlowLoop(ASTPackage _package, ASTFlowRoot root,
AbstractFlowElement parentNode, FlowLoop flowLoop) {
super(_package, root, parentNode, flowLoop);
root.addLabel(this.getLabel());
}
@Override
public String getXPathNodeName() {
return "FlowLoop";
}
@Override
public Object jjtAccept(WmParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public String getInputArray() {
return ((FlowLoop) flowElement).getInArray();
}
public String getOutputArray() {
return ((FlowLoop) flowElement).getOutArray();
}
}
|
JavaScript
|
UTF-8
| 1,597
| 2.609375
| 3
|
[] |
no_license
|
import Resolver from "./Resolver";
import Route from "./Route";
export default class Router {
/**
* @param {Route[]} routes
* @param {object} options
* @returns {boolean|Route}
*/
constructor(routes = [], options = {}) {
this.setRoutes(routes);
this.setOptions(options);
}
/**
* @returns {Route[]}
*/
getRoutes() {
return this._routes;
}
/**
* @param {Route[]} routes
* @returns {*}
*/
setRoutes(routes = []) {
this._routes = routes;
return this;
}
/**
* @param {object} options
* @returns {Router}
*/
setOptions(options = {}) {
this._options = options;
return this;
}
/**
* @returns {Object}
*/
getOptions() {
return this._options;
}
/**
* @returns {boolean|Route}
*/
route() {
let result = false;
let slug = new Resolver(window.location.pathname.substr(1));
let BreakException = {};
try {
this.getRoutes().forEach(function (route, index) {
if (slug.getURL() === route.getURL()) {
result = route;
throw BreakException;
}
});
if (this.getOptions().viewOnError !== undefined && result === false) {
result = new Route('', this.getOptions().viewOnError.view, this.getOptions().viewOnError.props);
}
} catch (e) {
if (e !== BreakException) throw e;
}
return result;
}
};
|
Shell
|
UTF-8
| 716
| 3.296875
| 3
|
[] |
no_license
|
#!/bin/bash
# Realizando backup
cp /home/george/git/bentham/bin/run_tests.sh backTemp
scriptDeTestes='#!/bin/bash
i=0
files=()
CIRCLE_NODE_TOTAL=1
CIRCLE_NODE_INDEX=0
for file in $(find target/test-classes -name "*Test.class" | grep -v ConsultasSQLDBTest | sort)
do
if [ $(($i % $CIRCLE_NODE_TOTAL)) -eq $CIRCLE_NODE_INDEX ]
then
file=${file/\.class/}
file=${file/target\/test-classes\//}
files+=",$file"
fi
((i++))
done
files=${files#","}
mvn test -Dtest=ConsultasSQLDBTest -Dflyway.skip=true
DISPLAY=:1999 mvn cobertura:cobertura -Dtest="${files[@]}" -Dflyway.skip=true
returnCode=$?
exit $returnCode'
echo $scriptDeTestes > /home/george/Desenvolvimento/workspace/bentham/bin/run_tests.sh
|
Java
|
UTF-8
| 3,072
| 2.03125
| 2
|
[] |
no_license
|
package cn.springboot.model.simple;
import java.math.BigDecimal;
import java.util.Date;
public class Toilet {
private Long pkId;
private String address;
private String longitude;
private String latitude;
private Boolean checkStatus;
private String description;
private String pictureUrl;
private String label;
private Boolean fixStatus;
private Boolean deleteStatus;
private Date createTime;
private Date modifyTime;
private BigDecimal score;
private Long likeNumber;
private String publisher;
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Long getPkId() {
return pkId;
}
public void setPkId(Long pkId) {
this.pkId = pkId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public Boolean getCheckStatus() {
return checkStatus;
}
public void setCheckStatus(Boolean checkStatus) {
this.checkStatus = checkStatus;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
public String getPictureUrl() {
return pictureUrl;
}
public void setPictureUrl(String pictureUrl) {
this.pictureUrl = pictureUrl == null ? null : pictureUrl.trim();
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label == null ? null : label.trim();
}
public Boolean getFixStatus() {
return fixStatus;
}
public void setFixStatus(Boolean fixStatus) {
this.fixStatus = fixStatus;
}
public Boolean getDeleteStatus() {
return deleteStatus;
}
public void setDeleteStatus(Boolean deleteStatus) {
this.deleteStatus = deleteStatus;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
public BigDecimal getScore() {
return score;
}
public void setScore(BigDecimal score) {
this.score = score;
}
public Long getLikeNumber() {
return likeNumber;
}
public void setLikeNumber(Long likeNumber) {
this.likeNumber = likeNumber;
}
}
|
Python
|
UTF-8
| 5,950
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
'''
read_ground_trips.py
Put ground trips into the truth table for evaluation
'''
import pandas as pd
import numpy as np
def read_trips_file(filename):
df = pd.read_csv(filename, sep='\t')
df_new = df[(df['Trip Rating'] == '3') | (df['Trip Rating'] == '2')]
return df_new
def process_values(df):
df['Location'] = df['Location'].apply(rearrange)
df['Estimated Start Time'] = df['Estimated Start Time'].apply(remap_time)
df['Estimated End Time'] = df['Estimated End Time'].apply(remap_time)
return df
def remap_time(val):
if pd.isnull(val):
return val
spl = val.split(' ')
hour = 0
if spl[1] == 'PM':
hour += 12
spl2 = spl[0].split(':')
hour += int(spl2[0])
'''
minutes = str(int(60 * round(float(spl2[1])/60))).zfill(2)
if minutes == '60':
hour += 1
minutes = '00'
return str(hour) + ':' + minutes
'''
if hour >= 3 and hour <= 10:
return 'Morning'
if hour > 10 and hour < 16:
return 'Afternoon'
if hour >= 16 and hour < 20:
return 'Evening'
return 'Night'
def rearrange(val):
spl = val.split('|')
spl[0] = spl[0][:-1]
spl[1] = spl[1][1:]
spl2 = spl[0].split(',')
spl3 = spl[1].split(',')
return spl2[1] + ' ' + spl2[0] + '\t' + spl3[1] + ' ' + spl3[0]
def add_zeros(df):
df['Start Location'] = df['Start Location'].apply(location_zeroes)
df['End Location'] = df['End Location'].apply(location_zeroes)
return df
def location_zeroes(val):
spl = val.split(' ')
return spl[0] + ' ' + spl[1]
def write_trip_truth(read_file, write_file, write_times, write_modes):
df = read_trips_file(read_file)
df = process_values(df)
with open(write_file, 'w+') as wf, open(write_modes, 'w+') as wm, open(write_times, 'w+') as wt:
store = []
store1 = []
store2 = []
for index, row in df.iterrows():
if row[0] not in store:
wf.write('%s\t1\n' % row[0])
store.append(row[0])
if not pd.isnull(row[6]):
if (row[0], row[6]) not in store1:
wm.write('%s\t%s\t1\n' % (row[0], row[6]))
store1.append((row[0], row[6]))
if not pd.isnull(row[7]) and not pd.isnull(row[8]):
if (row[0], row[7], row[8]) not in store2:
wt.write('%s\t%s\t%s\t1\n' % (row[0], row[7], row[8]))
store2.append((row[0], row[7], row[8]))
def label_anchor_dataset(read_file, dataset):
df = pd.read_csv(read_file, sep='\t')
dataset_df = pd.read_csv(dataset, sep='\t', names=list('12345'))
dataset_df = dataset_df.dropna(axis=0,how='any')
indices = dataset_df.index.values
labels = pd.Series(np.zeros(dataset_df.shape[0]))
labels = labels.reindex(indices, fill_value=0)
for index, row in dataset_df.iterrows():
for ind in range(df.shape[0]):
if row[0] == df.ix[:,0][ind] or row[1] == df.ix[:,0][ind]:
labels.set_value(index, 1)
dataset_df = dataset_df.assign(Labels=labels.values)
dataset_df.to_csv(dataset, sep='\t', index=False, header=False)
def label_dataset(read_file, dataset):
df = pd.read_csv(read_file, sep='\t')
dataset_df = pd.read_csv(dataset, sep='\t', names=list('12345'))
dataset_df = dataset_df.dropna(axis=0,how='any')
indices = dataset_df.index.values
labels = pd.Series(np.zeros(dataset_df.shape[0]))
labels = labels.reindex(indices, fill_value=0)
for index, row in dataset_df.iterrows():
for ind in range(df.shape[0]):
if row[0] == df.ix[:,0][ind] and row[1] == df.ix[:,1][ind]:
labels.set_value(index, 1)
dataset_df = dataset_df.assign(Labels=labels.values)
dataset_df.to_csv(dataset, sep='\t', index=False, header=False)
def label_mode_set(read_file, dataset):
df = pd.read_csv(read_file, sep='\t')
dataset_df = pd.read_csv(dataset, sep='\t',names=list('12345'))
dataset_df = dataset_df.dropna(axis=0,how='any')
indices = dataset_df.index.values
labels = pd.Series(np.zeros(dataset_df.shape[0]))
labels = labels.reindex(indices, fill_value=0)
for index, row in dataset_df.iterrows():
for ind in range(df.shape[0]):
if row[0] == df.ix[:,0][ind] and row[1] == df.ix[:,1][ind] and row[2] == df.ix[:,2][ind]:
labels.set_value(index, 1)
dataset_df = dataset_df.assign(Labels=labels.values)
dataset_df.to_csv(dataset, sep='\t', index=False, header=False)
def label_time_set(read_file, dataset):
df = pd.read_csv(read_file, sep='\t')
dataset_df = pd.read_csv(dataset, sep='\t', names=list('12345'))
dataset_df = dataset_df.dropna(axis=0,how='any')
indices = dataset_df.index.values
labels = pd.Series(np.zeros(dataset_df.shape[0]))
labels = labels.reindex(indices, fill_value=0)
for index, row in dataset_df.iterrows():
for ind in range(df.shape[0]):
if row[0] == df.ix[:,0][ind] and row[1] == df.ix[:,1][ind] and row[2] == df.ix[:,2][ind] and row[3] == df.ix[:,3][ind]:
labels.set_value(index, 1)
dataset_df = dataset_df.assign(Labels=labels.values)
dataset_df.to_csv(dataset, sep='\t', index=False, header=False)
def write_dataset(read_files, out_dataset):
with open(out_dataset, 'w+') as out_f:
seg_map = {}
for file in read_files:
with open(file, 'r') as rf:
for line in rf:
spl = line.split('\t')
if spl[0] in seg_map:
seg_map[spl[0]].append(spl[-1][:-1])
else:
seg_map[spl[0]] = [spl[-1][:-1]]
for value in seg_map.itervalues():
concat = ""
for val in value:
concat += val + '\t'
concat = concat[:-1]
concat += '\n'
out_f.write(concat)
|
Markdown
|
UTF-8
| 6,994
| 3.203125
| 3
|
[] |
no_license
|
# 初识计算机和Java语言
## 计算机的体系结构
### 计算机的基本概念
- 计算机(Computer)俗称电脑,是现代一种用于高级计算,使用非常广泛 的设备,主要由计算机硬件和计算机软件两个部分组成。
- 计算机硬件是客观存在的各种计算机相关设备,而计算机的软件是用于 控制各种硬件设备完成各种功能。
### 常见的主要硬件
计算机硬件(Computer Hardware)主要包括:中央处理器(CPU)、内存、 硬盘、输入输出设备、主板、机箱和电源等辅助设备。
CPU
- 中央处理器(英文Central Processing Unit)
- 是计算机中最核心的部件,类似于人的大脑
- 是一台计算机运算核心和控制核心,所有运算都由CPU完成
- 其功能主要是解释计算机指令以及处理计算机软件中的数据
内存
- 是计算机中的存储部件,内存(Memory)也被称为内存储器。
- 用于暂时存放CPU中的运算数据,以及与硬盘等外部存储器交换的数据
- CPU可以直接访问内存的数据,而且效率比较高
- 容量小不能实现永久存储,一旦断电会造成数据的丢失
- 时刻记住ctrl+s快捷键进行保存
硬盘
- 是计算机中的存储部件
- 主要用于永久存放数据内容,容量大且断电不丢失
- CPU不能直接访问硬盘中数据,若希望访问则需要先加载到内存中
- 1Tb = 1024Gb
- 1Gb = 1024Mb
- 1Mb = 1024Kb
- 1Kb = 1024Byte (字节) 1Byte = 8Bit (二进制位)
输入输出设备
- 其中键盘叫做标准输入设备,显示器叫做标准输出设备。
常见的主要软件
- 计算机软件(Computer Software)可分为系统软件和应用软件,系统软件 就是操作系统,是其他软件的基础。
- 主流的操作系统有:Windows/Unix/Linux/IOS/Android。
### 计算机的体系结构
应用程序 》操作系统外壳 》操作系统内核 》硬件
## Java语言的概述
### 计算机语言的概述
语言是人与人之间进行沟通的主要表达方式。如:中国人与中国人使用 用普通话沟通。而中国人要和英国人交流,就要使用英语沟通。计算机语言是人与计算机之间交流的表达方式,该语言有很多种。
### 计算机语言的发展
- 第一代语言:机器语言。指令以二进制代码形式存在,最开始使用穿孔卡片。
- 第二代语言:汇编语言。使用助记符表示一条机器指令,如:ADD、SUB等。
- 第三代语言:高级语言。Java、C ,C++,PHP , Python,Scala等。
### Java语言的发展历史
- 1995年 Java问世。
- 1996年 Java 1.0。
- 1999年 Java 1.2发布(JAVA SE\JAVA EE\JAVA ME)。
- 2004年 Tiger 发布(JAVA5.0),Java 登录火星。
- 2011年 7月由Oracle正式发布Java7.0。
- 2014年 3月19日,Oracle公司发布Java8.0的正式版。
- 2017年 9月21日,Java9.0正式发布。
- 2018年 9月25日,Oracle官方宣布Java11正式发布。
**Java SE 桌面应用**
- Java SE(Java Platform, Standard Edition)称之为“Java平台标准版”,是 Java平台的基础。
- Java SE包含了运行Java应用所需要的基础环境和核心类库。
- Java SE还定义了基于桌面应用的基础类库,通过使用这些类库,我们可 以编写出类似于像Office那样的丰富多彩的桌面应用。
**Java EE 企业应用**
- Java EE(Java Platform,Enterprise Edition)称之为“Java平台企业版”。
- Java EE构建在Java SE基础之上,用于构建企业级应用。所谓企业级应用 是指那些为商业组织、大型企业而创建的应用系统,例如:电信的“计费 系统”、银行的“网银系统”、企业中的“客户关系管理系统”等等。
**Java ME 企业应用**
- Java ME (Java Platform,Micro Edition)称之为Java 平台微型版。
- 为机顶盒、移动电话和PDA等嵌入式消费电子设备提供的Java解决方案。 随着3G移动智能平台时代的到来,特别是以Java为核心编程语言的 Android智能平台的迅速普及,Java ME已经走向淘汰。
## 开发环境的搭建
### 开发工具的下载和安装
下载方式
- 方式一:通过官网下载 www.sun.com www.oracle.com
- 方式二:通过搜索下载 www.baidu.com www.sogou.com
安装方式
- 若下载的是安装版,则一路点击下一步安装即可;
- 若下载的是绿色版,则直接解压即可;
- 无论是安装版还是绿色版,切记安装的路径中不要有中文!
### Jdk的目录结构
- bin目录 - 该目录下主要存放JDK的各种工具命令。
- conf目录 - 该目录下主要存放jdk的相关配置文件。
- include目录 - 该目录下主要存放了一些平台的头文件。
- jmods目录 - 该目录下主要存放了JDK的各种模块。
- legal目录 - 该目录下主要存放了JDK各模块的授权文档。
- lib目录 - 该目录下主要存放了JDK工具的一些补充jar包和源代码。
### 相关的概念
- JDK - 称为Java开发工具包( Java Development Kit)。Java开发人士需 要下载和安装JDK,目前的主流版本为JDK11。
- JRE - 称之为Java SE运行时环境(Java SE Runtime Environment),提供 了运行Java应用程序所必须的软件环境等。无论是开发还是运行Java应用 都必须安装。
- javac.exe - 编译器,主要用于将高级Java源代码翻译成字节码文件。
- java.exe - 解释器,主要用于启动JVM对字节码文件进行解释并执行。
### 编写Java程序的流程
- 新建文本文档,将文件扩展名由xxx.txt修改为xxx.java;
- 使用记事本/Notepad++的方式打开文件,编写Java代码后进行保存;
- 启动dos窗口,并切换到.java文件所在的路径中;
- 使用javac xxx.java进行编译,生成xxx.class的字节码文件;
- 使用java xxx 进行解释执行,打印最终结果;
### 常见的错误
- 错误:需要class,interface或enum =>通常都是class关键字拼写错误
- 错误: 找不到符号 => 通常因为单词拼写错误或Java中不支持这样的单词
- 错误: 需要';' => 通常都是因为少写分号,加上英文版分号即可
- 错误: 非法字符: '\uff1b' => 通常是因为出现了中文标点符号,修改为英
文版即可
- 错误: 在类 PrintTest 中找不到 main 方法, 请将 main 方法定义为: => main写成了mian
### Java11新特性之简化的编译运行
- 新建文本文档,将文件扩展名由xxx.txt修改为xxx.java;
- 使用记事本/Notepad++的方式打开文件,编写Java代码后进行保存;
- 启动dos窗口,并切换到.java文件所在的路径中;
- 使用java xxx.java 进行编译运行,打印最终结果(慎用);
### 跨平台原理
Java字节码可以通过JVM翻译为具体平台能够执行的机器指令。由于Sun 定义了JVM规范,而且不同的操作系统大多提供了JVM实现,才使得相同 的一个字节码文件可以在不同的系统上运行,从而使Java赢得了“一次编 译,到处使用”的美名。
|
C#
|
UTF-8
| 790
| 3
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
using System;
using SharpRomans.Support;
namespace SharpRomans
{
public partial class NumeralOutOfRangeException : ArgumentOutOfRangeException
{
public NumeralOutOfRangeException() { }
public NumeralOutOfRangeException(string message) : base(message) { }
public NumeralOutOfRangeException(string message, Exception inner) : base(message, inner) { }
private NumeralOutOfRangeException(string paramName, string message) : base(paramName, message) { }
internal static NumeralOutOfRangeException Build(string paramName, ushort value, Range<ushort> validity)
{
string message = string.Format("Only numbers contained within {0} are allowed.\nActual value was '{1}'", validity, value);
var ex = new NumeralOutOfRangeException(paramName, message);
return ex;
}
}
}
|
PHP
|
UTF-8
| 3,981
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Boo\Persona;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
use PHPUnit_Framework_TestCase;
class VerifierTest extends PHPUnit_Framework_TestCase
{
protected $responses = [
'valid' => '{"email": "foobar@example.com", "status": "okay", "audience": "http://example.com", "expires": 1308859352261, "issuer": "example.com"}',
'invalid_json' => 'foobar',
'incorrect_audience' => '{"email": "foobar@example.com", "status": "okay", "audience": "incorrect"}',
'invalid' => '{"status":"failure","reason":"no certificates provided"}',
];
public function testThatClassCanBeConstructed()
{
$verifier = new Verifier('http://example.com');
$this->assertInstanceof(Verifier::class, $verifier);
}
/**
* @expectedException PHPUnit_Framework_Error
*/
public function testThatClassCanNotBeCosntructedWithoutAudience()
{
new Verifier;
}
public function testVerifyWithValidResponse()
{
$container = [];
$client = $this->getGuzzleClient($container, $this->responses['valid']);
$verifier = new Verifier('http://example.com', $client);
$verifier->verify('foobar');
$request = $container[0]['request'];
$body = json_decode($request->getBody());
$response = $container[0]['response'];
$this->assertSame('POST', $request->getMethod());
$this->assertSame(Verifier::ENDPOINT, (string) $request->getUri());
$this->assertSame('foobar', $body->assertion);
$this->assertSame('http://example.com', $body->audience);
$this->assertSame($this->responses['valid'], (string) $response->getBody());
}
/**
* @expectedException Boo\Persona\Exceptions\JsonException
*/
public function testVerifyWithInvalidJsonResponse()
{
$container = [];
$client = $this->getGuzzleClient($container, $this->responses['invalid_json']);
$verifier = new Verifier('http://example.com', $client);
$verifier->verify('foobar');
}
/**
* @expectedException Boo\Persona\Exceptions\PersonaException
*/
public function testVerifyWithIncorrectAudienceResponse()
{
$container = [];
$client = $this->getGuzzleClient($container, $this->responses['incorrect_audience']);
$verifier = new Verifier('http://example.com', $client);
$verifier->verify('foobar');
}
/**
* @expectedException GuzzleHttp\Exception\ServerException
*/
public function testVerifyWithServerErrorResponse()
{
$container = [];
$client = $this->getGuzzleClient($container, '', 500);
$verifier = new Verifier('http://example.com', $client);
$verifier->verify('foobar');
}
/**
* @expectedException Boo\Persona\Exceptions\PersonaException
*/
public function testVerifyWithInvalideResponse()
{
$container = [];
$client = $this->getGuzzleClient($container, $this->responses['invalid']);
$verifier = new Verifier('http://example.com', $client);
$verifier->verify('foobar');
}
public function testGetAudience()
{
$verifier = new Verifier('http://example.com');
$this->assertSame('http://example.com', $verifier->getAudience());
}
public function testGetEndpoint()
{
$verifier = new Verifier('http://example.com');
$this->assertSame(Verifier::ENDPOINT, $verifier->getEndpoint());
}
protected function getGuzzleClient(&$container, $body, $code = 200)
{
$history = Middleware::history($container);
$response = new Response($code, [], $body);
$handler = HandlerStack::create(new MockHandler([$response]));
$handler->push($history);
return new Client(['handler' => $handler]);
}
}
|
JavaScript
|
UTF-8
| 2,178
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
import { useEffect, useState } from 'react';
import { Redirect } from 'react-router-dom';
import { loadFromLocalStorage, saveToLocalStorage } from '../../utils/localStorage';
import {
Container,
Content,
Text,
SubText,
Form,
Input,
TotalText,
PlaceOrderButton,
} from './styles';
function ConfirmOrder() {
const [name, setName] = useState('');
const [cpf, setCpf] = useState('');
const [cartProducts, setCartProducts] = useState([]);
const [total, setTotal] = useState(0);
const [redirect, setRedirect] = useState(false);
function submitForm() {
const order = {
name,
cpf,
cartProducts,
total,
}
let orders = loadFromLocalStorage("orders");
if (!orders) {
orders = [];
}
orders.push(order);
saveToLocalStorage(orders, "orders");
saveToLocalStorage([], "cart");
alert("Pedido registrado");
setRedirect(true);
}
useEffect(() => {
let totalSum = 0;
let cartItems = [];
const itemsArray = loadFromLocalStorage("cart");
itemsArray.forEach(item => {
cartItems.push({ item: item.id, quantity: item.quantity });
totalSum += parseFloat(item.price) * item.quantity;
});
setCartProducts(cartItems);
setTotal(totalSum.toFixed(2));
}, [])
if (redirect) {
return <Redirect to="/orders"/>
}
return (
<>
<Container>
<Content>
<Text>Seu pedido está quase concluído</Text>
<SubText>Favor preencha os dados abaixo para concluir seu pedido</SubText>
<Form>
<Input
type="text"
placeholder="Nome completo"
onChange={(e) => setName(e.target.value)}
value={name}
/>
<Input
type="text"
placeholder="CPF"
onChange={(e) => setCpf(e.target.value)}
value={cpf}
/>
<TotalText>
Total: R$ {total}
</TotalText>
<PlaceOrderButton onClick={submitForm}>Confirmar pedido</PlaceOrderButton>
</Form>
</Content>
</Container>
</>
)
}
export default ConfirmOrder;
|
Java
|
UTF-8
| 1,456
| 1.570313
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2014. igitras.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igitras.codegen.common.java.element.file;
import com.igitras.codegen.common.FileTemplate;
import com.igitras.codegen.common.java.element.file.part.*;
/**
* Created by mason on 2014-12-01.
*/
public interface JavaFileInterface extends FileTemplate {
void addField(JavaFieldPart fieldPart);
void removeField(JavaFieldPart fieldPart);
void addAbstractMethod(JavaAbstractMethodPart abstractMethodPart);
void removeAbstractMethod(JavaAbstractMethodPart abstractMethodPart);
void addConstructor(JavaConstructorPart constructorPart);
void removeConstructor(JavaConstructorPart constructorPart);
void addMethod(JavaMethodPart methodPart);
void removeMethod(JavaMethodPart methodPart);
void addAnnotation(JavaAnnotationPart annotationPart);
void removeAnnotation(JavaAnnotationPart annotationPart);
}
|
Java
|
UTF-8
| 290
| 1.984375
| 2
|
[] |
no_license
|
package pe.edu.upc.prueba.services;
import java.util.Optional;
import pe.edu.upc.prueba.entities.Resident;
public interface ResidentService extends CrudService<Resident, Long> {
Optional<Resident> auth(String email, String password);
Optional<Integer> authToken(String token);
}
|
C++
|
UTF-8
| 6,725
| 3.53125
| 4
|
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <time.h>
#define Tam 12
using namespace std;
void Leitura();
void ordenar(int); // metodo que é chamado no switch
void bubble();
void Insert();
void Seletion();
void Count();
void CountDistr();
void Shell();
void MergeSort();
double T; //Variavel que armazena o tempo
int Sort[Tam];
int main() {
int sel;
for(int i=0; i<10;){
//Começa chamando a função leitura e preenchendo o vetor Sort[]
//Leitura();
system("cls");
cout << "\t\t\tOrdenacao de Arquivos Semestre2\n ";
cout << "\t\t\tSelecione a opcao desejada\n\n\n";
//---------------------------------------------------------
// Mostra o vetor no menu;
cout << "\t\t\tSort ={ ";
for(int i=0; i<Tam; i++){
cout << "[" << Sort[i] << "]";
}cout << " }\n\n\n";
cout << "\t\t\t*Antes de Qualquer operacao tem Que Desordenar o vetor!!\n\n";
cout << "\t\t\t1-Desordenar o vetor\n";
cout << "\t\t\t2-Bubble Sort\n";
cout << "\t\t\t3-Insertion sort\n";
cout << "\t\t\t4-Selection Sort\n";
cout << "\t\t\t5-Counting Sort\n";
cout << "\t\t\t6-Counting and distribution Sort\n";
cout << "\t\t\t7-Shell Sort\n";
cout << "\t\t\t8-Merge Sort\n";
cout << "\t\t\t0-Sair\n\n";
cout << "\t\t\tOpcao: ";
cin >> sel;
if (sel >0) {
// T = clock(); //Armazena a hora de inicio da chamada da função
ordenar(sel);// chama a função
//T = clock() - T; //Subtrai o tempo de termino do inicio e guarda na mesma
// printf("\t\t\tTempo de execucao: %Lf", T/1000);// mostra na tela o tempo de execução
// system("pause");
}
else {
i=30;
cout << "\n\t\t\t\tFim do Programa\n\n";
}
}
return 0;
}
void Leitura(){ // preenche os Numeros aleatórios no vetor para ser ordenado";
int i=0;
while (i < Tam) {
if( i % 2 == 0 ){
Sort[i] = rand() % 100;
}else{
Sort[i] = rand() % 1000;
}
i++;
}
}
void ordenar(int op) {
switch (op) {
case 1:{ Leitura(); break;}
case 2:{ bubble(); break;}
case 3:{ Insert(); break;}
case 4:{ Seletion(); break;}
case 5:{ Count(); break;}
case 6:{ CountDistr(); break;}
case 7:{ Shell(); break;}
case 8:{ MergeSort(); break;}
}
}
void bubble(){
int Aux,i;
bool troca = true;
int cont = Tam-1;
while(troca == true){
troca = false;
i=0;
while(i < cont){
if(Sort[i] > Sort[i+1]){
Aux = Sort[i+1];
Sort[i+1] = Sort[i];
Sort[i] = Aux;
troca = true;
}
i++;
}
cont--;
}
}
void Insert(){
int Aux;
int j;
int i=0;
while (i < Tam) {
Aux = Sort[i];
j=i;
while (Sort[j-1] > Aux && j >= 0) {
Sort[j] = Sort[j-1];
j--;
}
Sort[j] = Aux;
i++;
}
}
void Seletion(){
int i=0;
int Aux;
int j;
int cont;
while (i < Tam){
j=i;
cont = j;
Aux = Sort[j];
while (j < Tam){
if (Sort[cont] > Sort[j]){
cont = j;
}
j++;
}
Sort[i] = Sort[cont];
Sort[cont] = Aux;
i++;
}
}
void Count(){
int cont[Tam];
int vet[Tam];
for (int i=0; i<Tam; i++){
cont[i] = 0;
//}
//Nesta implementa��o foi preciso setar o vetor vet[]
//pois o Sort[] vai ficar com o vetor ordenado
vet[i] = Sort[i];
}
int i,j=0;
while(j<Tam){
i=j+1;
while(i<Tam){
if(vet[j] > vet[i]){
cont[j]++;
}
else{
cont[i]++;
}
i++;
}
//Saida[cont[j]] = vet[j];
//nessa implementa��o Saida[] é o Sort[]
Sort[cont[j]] = vet[j];
j++;
}
}
void CountDistr(){
// Somente para teste com menu
//------------------------------------
int vet[Tam];
for(int i=0; i<Tam; i++)
vet[i] = Sort[i];
//------------------------------------
int a=0,
maior = vet[a],
menor = vet[a];
for(int i=0; i<Tam; i++){
if(Sort[i] > maior)
maior = vet[i];
if(Sort[i] < menor)
menor = vet[i];
}
int cont[maior];
for(int i=menor; i<=maior; i++)
cont[i] = 0;
for(int i=0; i<=Tam; i++)
cont[Sort[i]]++;
for(int i=menor+1; i<=maior; i++)
cont[i] = cont[i] + cont[i-1];
//------------------------------------
// Neste caso o vetor saida foi
//Substituido por Sot[]
for(int i=0; i<Tam; i++)
Sort[cont[vet[i]]-- -1] = vet[i];
}
void Shell(){
int H[3] = {1,3,6},
i,j,k,h,aux,inicio,incremento;
for(i=2; i>=0; i--){
incremento = H[i];
inicio =0;
while(inicio < incremento){
j=inicio;
while((j+incremento) < Tam){
k = j+incremento;
aux = Sort[k];
while((k-incremento) >= 0 && aux < Sort[k-incremento]){
Sort[k] = Sort[k-incremento];
k = k-incremento;
}
Sort[k] = aux;
j=j+incremento;
}
inicio++;
}
}
}
void MergeSort(){
system("cls");
Leitura(); // caso a funçao seja chamada antes da Leitura
cout << "\t\t\tMerge Sort\n";
cout << "\t\t\tDigite 5 valores para inserir no VetorB\n";
int j=0, k=0, A=Tam, B, i, vetA[A];
bubble();
i=0;
cout << "\n\n\t\t\tvetA";
while (i<A) {
vetA[i] = Sort[i];
cout << "[" << vetA[i] << "]";
i++;
}
cout << "\n\n\t\t\tQuantos Elementos ira inserir no vetorA\n\t\t\t";
cin >> B;
cout << "\n\n\t\t\tPode inserir os valores\n\t\t\tPrecisam estar ordenado!!\n\n";
int vetB[B],
C = A+B,
vetC[C];
i=0;
while (i < B) {
cout << "\t\t\t";
cin >> vetB[i];
i++;
}
i=0;
cout << "\n\n\t\t\tvetB";
while (i<B) {
cout << "[" << vetB[i] << "]";
i++;
}
i=0;
while(i<A && j<B){
if(vetA[i] < vetB[j]){
vetC[k]=vetA[i];
i++;
}
else{
vetC[k]=vetB[j];
j++;
}
k++;
}
if(i<A){
while(i<A){
vetC[k] = vetA[i];
i++;k++;
}
}
else{
while(j<B){
vetC[k] = vetB[j];
j++;k++;
}
}
// Daqui para baixo somente é necessário para mostrar o resultado na tela
system("cls");
i=0;
cout << "\n\n\t\t\tvetA";
while (i<A) {
vetA[i] = Sort[i];
cout << "[" << vetA[i] << "]";
i++;
}
i=0;
cout << "\n\n\t\t\tvetB";
while (i<B) {
cout << "[" << vetB[i] << "]";
i++;
}
i=0;
cout << "\n\n\t\t\tvetC";
while(i<C){
cout << "[" << vetC[i] << "]";
i++;
}
cout << "\n\n\t\t\t";
system("pause");
}
|
Java
|
ISO-8859-1
| 2,103
| 3.9375
| 4
|
[
"MIT"
] |
permissive
|
import java.util.ArrayList;
import java.util.Scanner;
public class Gato extends Animal {
Scanner ler = new Scanner(System.in);
public Gato() {};
public Gato(String nome, int idade, boolean vacinado, String genero) {
setNome(nome);
setIdade(idade);
setVacinado(vacinado);
setGenero(genero);
}
ArrayList<String> nomes = new ArrayList<String>();
@Override
public void adicionar(String nome) {
nomes.add(nome);
}
@Override
public void deletar(String nome) {
if (nomes.contains(nome)) {
nomes.remove(nome);
} else {
System.out.println("\n\tNome invlido!");
}
}
@Override
public void Alterar(String nome) {
if (nomes.contains(nome)) {
System.out.print("Digite o novo nome: ");
String nome2 = ler.next();
nomes.remove(nome);
nomes.add(nome2);
} else {
System.out.println("\n\tNome no encontrado!");
}
}
@Override
public void Mostrar() {
System.out.println(nomes);
}
@Override
public void Calcular() {
System.out.println("\nQual o porte do gato?\n1)Pequeno \n2)Grande");
System.out.print("\n\t> ");
int porte = ler.nextInt();
switch (porte) {
case 1:
System.out.println("\n\tPorte Pequeno");
System.out.println("\tGatos entre 3 a 4kg > Consumir de 40g a 55g");
System.out.println("\nATENO: Se o seu pet est fora destas faixas de peso, consulte um veterinrio");
break;
case 2:
System.out.println("\n\tPorte Grande");
System.out.println("\tGatos entre 5 a 6kg > Consumir de 55g a 75g");
System.out.println("\nATENO: Se o seu pet est fora destas faixas de peso, consulte um veterinrio");
break;
default:
System.out.println("\n\tOpo invlida.");
}
}
@Override
public void mostrarGenero(String genero) {
System.out.println ("O genero do gato: " + genero);
}
@Override
public void MostrarInformacoes() {
System.out.println("O nome do gato: " + nomes);
}
public void idade(int idade) {
System.out.println("A idade do gato : " + idade);
}
public void Vacinado(String vacinado) {
System.out.println("O seu gato vacinado: " + vacinado);
}
}
|
Java
|
UTF-8
| 14,330
| 1.90625
| 2
|
[] |
no_license
|
package com.augurit.awater.dri.installRecord.rest;
import com.augurit.agcloud.common.controller.BaseController;
import com.augurit.agcloud.opus.common.domain.OpuOmOrg;
import com.augurit.agcloud.opus.common.domain.OpuOmUser;
import com.augurit.agcloud.opus.common.domain.OpuOmUserInfo;
import com.augurit.agcloud.org.rest.service.IOmOrgRestService;
import com.augurit.agcloud.org.rest.service.IOmUserInfoRestService;
import com.augurit.awater.dri.installRecord.service.IInstallRecordService;
import com.augurit.awater.dri.installRecord.web.form.InstallRecordForm;
import com.augurit.awater.dri.installRecord.web.form.OrgNameForm;
import com.augurit.awater.dri.problem_report.correct_mark.service.ICorrectMarkService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RequestMapping("/rest/app/installRecord")
@Controller
public class InstallRecordRestController extends BaseController<InstallRecordForm> {
@Autowired
private IInstallRecordService installRecordService;
@Autowired
private ICorrectMarkService correctMarkService;
@Autowired
private IOmOrgRestService omOrgRestService;
@Autowired
private IOmUserInfoRestService userInfoRestService;
/***
*保存安装信息0
* */
@RequestMapping(value = "/saveInstallInf",produces = "application/json;charset=UTF-8")
@ResponseBody
public String saveInstallInf(HttpServletRequest request, HttpServletResponse response) {
JSONObject jsonObject = new JSONObject();
String loginName = request.getParameter("login_name");
String userName = request.getParameter("user_name");
String deviceCode = request.getParameter("device_code");
OpuOmUserInfo userInfo = userInfoRestService.getOpuOmUserInfoByLoginName(loginName);
List<String> listOrgIds = omOrgRestService.listOpuOmOrgIdByUserId(userInfo.getUserId(),new String[]{"swj"});
Boolean isIn = false;
if(listOrgIds!=null && listOrgIds.size()>0){
for(String orgId :listOrgIds){
OpuOmOrg org = omOrgRestService.getOpuOmOrgIdByOrgId(orgId);
if(!org.getOrgCode().contains("PSH")){
isIn=true;
}
}
}
if(!isIn){
jsonObject.put("code", 200);
jsonObject.put("message", "当前登录不是排水户用户,无法保存");
return jsonObject.toString();
}
if ((loginName!=null && !"".equals(loginName)) || (deviceCode!=null && !"".equals(deviceCode))) {
List<InstallRecordForm> installRecordList=installRecordService.getByLnOrDc(loginName,deviceCode);
if (installRecordList!=null && installRecordList.size()>0) {
jsonObject.put("code", 200);
jsonObject.put("message", "该设备id在安装情况表中已经存在记录");
return jsonObject.toString();
}
}
if (loginName!=null && !"".equals(loginName)) {
InstallRecordForm installRecordForm=new InstallRecordForm();
installRecordForm.setLoginName(loginName);
installRecordForm.setUserName(userName);
installRecordForm.setDeviceCode(deviceCode);
installRecordForm.setInstallTime(new Date());
try {
Map<String,String> cmMap=installRecordService.getOrgForAppInstall(loginName);
if(cmMap!=null && cmMap.size()>0){
installRecordForm.setTeamOrgId(cmMap.get("teamOrgId"));
installRecordForm.setTeamOrgName(cmMap.get("teamOrgName"));
installRecordForm.setDirectOrgId(cmMap.get("directOrgId"));
installRecordForm.setDirectOrgName(cmMap.get("directOrgName"));
installRecordForm.setSuperviseOrgId(cmMap.get("superviseOrgId"));
installRecordForm.setSuperviseOrgName(cmMap.get("superviseOrgName"));
installRecordForm.setParentOrgId(cmMap.get("parentOrgId"));
installRecordForm.setParentOrgName(cmMap.get("parentOrgName"));
}
installRecordService.save(installRecordForm);
} catch (Exception e) {
jsonObject.put("code", 500);
jsonObject.put("message", "异常错误!"+e.getMessage());
e.printStackTrace();
}
jsonObject.put("data", installRecordForm);
jsonObject.put("code", 200);
jsonObject.put("message", "保存成功");
}else {
jsonObject.put("code", 500);
jsonObject.put("message", "参数异常,保存失败!");
}
return jsonObject.toString();
}
/***
*统计App安装率
* */
@RequestMapping(value = "/StatisticalApp",produces = "application/json;charset=UTF-8")
@ResponseBody
public String StatisticalApp(HttpServletRequest request){
JSONObject jsonObject = new JSONObject();
//String loginName = request.getParameter("login_name");
String orgName = request.getParameter("org_name");
String org_id = request.getParameter("org_id");
String roleType = request.getParameter("roleType");//一线还是领导
boolean ty=false;
try {
if (roleType!=null && "true".equals(roleType)) {
ty=true;
}
//区外领导部分,走这里
if (orgName!=null && (orgName.contains("市水务局"))) {//都是领导
return installRecordService.getOverUserRate(false);
}
//一线,当前只是4级结构的组织,要踢掉里面的领导用户
OpuOmOrg om=installRecordService.getOmorgByOrgName(orgName);
if (om!=null && om.getOrgId()!=null) {
org_id=om.getOrgId().toString();
}
//获取安装数
List<OrgNameForm> orgList=installRecordService.getStaticByOrgId(org_id,ty);
if (orgList==null) {//这个list存两部分,一线和领导,上面的查询是一线,如果没有值的话,就New一个去存领导层
orgList=new ArrayList<>();
}
//如果查询的全市,还要把市级别 拼接上去
if (ty && (((orgName!=null && orgName.contains("全市")))
|| orgName==null || "".equals(orgName) )) {//思路是吧,市级领导和区级领导合并
String ldJson=installRecordService.getOverUserRate(false);
if (ldJson.contains("data")) {
JSONObject ldjson = JSONObject.fromObject(ldJson);
JSONObject dataJson= JSONObject.fromObject(ldjson.getString("data"));
JSONArray childArray=JSONArray.fromObject(dataJson.getString("child_orgs"));
JSONObject childJson= JSONObject.fromObject(childArray.get(0));
OrgNameForm oruser = new OrgNameForm();
oruser.setOrg_name(childJson.getString("org_name"));
oruser.setInstall_percent(childJson.getString("install_percent"));
orgList.add(oruser);
}
}
int installs=0;
//得到该机构所有的用户,不管安装没有
List<OpuOmUser> omuserList=null;
if (org_id!=null && !"".equals(org_id)) {
omuserList=installRecordService.getUsesByOrgId(org_id,ty);
//获取当前区安装的人数
List<OpuOmUser> omUserInsList=installRecordService.getUsesByIsinstalled(true,org_id,ty);
installs=omUserInsList==null?0:omUserInsList.size();
}else {
omuserList=installRecordService.getAllUses(ty);
//获取当前市安装的总人数
List<OpuOmUser> allUserList= installRecordService.getUsesByIsinstalled(true,null,ty);
installs=allUserList==null?0:allUserList.size();
}
JSONObject jso = new JSONObject();
jso.put("total", omuserList==null?0:omuserList.size());
jso.put("install", installs);
jso.put("child_orgs", orgList);
jsonObject.put("data", jso);
jsonObject.put("code", 200);
jsonObject.put("message", "查询成功");
} catch (Exception e) {
jsonObject.put("code", 500);
jsonObject.put("message", "异常错误!"+e.getMessage());
e.printStackTrace();
}
return jsonObject.toString();
}
/**
*查询某个机构下所有已安装App的用户
*第三个接口
**/
@RequestMapping(value = "/StatisticalAppInOrg", produces = "application/json;charset=UTF-8")
@ResponseBody
public String StatisticalAppInOrg(HttpServletRequest request) {
JSONObject jsonObject = new JSONObject();
String org_id = request.getParameter("org_id");
String orgName = request.getParameter("org_name");
String roleType = request.getParameter("roleType");//一线还是领导
boolean ty = false;
if (roleType!=null && "true".equals(roleType)) {
ty=true;
}
//这里必须查询具体的机构,不允许有不存在
if(orgName!=null && !"".equals(orgName)){
try {
List<OpuOmUser> allUserInThisList = null;//该区总人数
//区外领导部分,走这里//查找市区领导
if (orgName!=null && (orgName.contains("市水务局"))) {//都是领导
allUserInThisList = installRecordService.getOverAreaUser();
}
if (allUserInThisList == null) {//非市区,走这个方法
OpuOmOrg om = installRecordService.getOmorgByOrgName(orgName);
if (om!=null && om.getOrgId()!=null) {
org_id = om.getOrgId().toString();
}
//得到该机构所有的用户,不管安装没有
allUserInThisList = installRecordService.getUsesByOrgId(org_id,ty);
}
JSONObject userJson = new JSONObject();
JSONArray appArray=new JSONArray();
if (allUserInThisList!=null && allUserInThisList.size()>0) {
userJson.put("total", allUserInThisList.size());
userJson.put("total_page", 1);
userJson.put("cur_page", 1);
List<OpuOmUser> list = allUserInThisList;
List<OpuOmUser> tempList1 = new ArrayList<>(); //存安装的人员
List<OpuOmUser> tempList2 = new ArrayList<>(); //存未安装的人员
JSONObject app = new JSONObject();
for(int i=0; i<list.size(); i++){
OpuOmUser s = list.get(i);
app.put("user_name",s.getUserName());
app.put("phone",s.getUserMobile());
app.put("org_name",s.getOrgName());
// 根据loginName判断是否安装
List<InstallRecordForm> insList = installRecordService.getByLnOrDc(s.getLoginName(), null);
if (insList!=null && insList.size()>0) {
app.put("isInstalled",true);
tempList1.add(s);
}else {
app.put("isInstalled",false);
tempList2.add(s);
}
appArray.add(app);
}
// list.clear();
// list.addAll(tempList1);
// list.addAll(tempList2);
userJson.put("users", appArray);//封装用户
}
jsonObject.put("data", userJson);
jsonObject.put("code", 200);
jsonObject.put("message", "查询成功");
}catch (Exception e) {
jsonObject.put("code", 500);
jsonObject.put("message", "异常错误!"+e.getMessage());
e.printStackTrace();
}
}else {
jsonObject.put("code", 500);
jsonObject.put("message", "参数异常,查询失败!");
}
return jsonObject.toString();
}
/**
* 获取已安装/未安装的人员详情
*
**/
@RequestMapping(value = "/StatisticalAppGetUsers",produces = "application/json;charset=UTF-8")
@ResponseBody
public String StatisticalAppGetUsers() {
JSONObject jsonObject = new JSONObject();
String isInstalled = request.getParameter("isInstalled");
String orgName = request.getParameter("org_name");
String roleType = request.getParameter("roleType");//一线还是领导
boolean ty=false;
if (roleType!=null && "true".equals(roleType)) {
ty=true;
}
if(isInstalled!=null && !"".equals(isInstalled)){
try {
List<OpuOmUser> omuserList = null;
boolean flag = false;
String oid = null;
if (orgName!=null && !"".equals(orgName)) {
OpuOmOrg om=installRecordService.getOmorgByOrgName(orgName);
if (om!=null) {
oid = om.getOrgId();
}
}
if("true".equals(isInstalled)){//查找安装用户
flag=true;
}
if (orgName!=null && orgName.contains("市水务局")) {
omuserList=installRecordService.getOverAreaUserInstalled(flag);
}else {
omuserList=installRecordService.getUsesByIsinstalled(flag,oid,ty);
}
JSONObject userJson = new JSONObject();
if (omuserList!=null && omuserList.size()>0) {
userJson.put("total", omuserList.size());
}
if (omuserList!=null && omuserList.size()>0) {
JSONArray appArray=new JSONArray();
for(OpuOmUser s:omuserList){
JSONObject app = new JSONObject();
app.put("user_name",s.getUserName());
app.put("phone",s.getUserMobile());
app.put("direc_org",s.getOrgName());
//这里识别是否安装
app.put( "isInstalled",flag);
appArray.add(app);
}
userJson.put("users", appArray);//封装用户
}
jsonObject.put("data", userJson);
jsonObject.put("code", 200);
jsonObject.put("message", "查询成功");
} catch (Exception e) {
jsonObject.put("code", 500);
jsonObject.put("message", "异常错误!"+e.getMessage());
e.printStackTrace();
}
}else {
jsonObject.put("code", 500);
jsonObject.put("message", "参数异常,查询失败!");
}
return jsonObject.toString();
}
}
|
Java
|
UTF-8
| 4,957
| 3.40625
| 3
|
[] |
no_license
|
package com.song.demo.event;
import java.util.Collection;
import java.util.EventListener;
import java.util.EventObject;
import java.util.HashSet;
import java.util.Iterator;
/**
* java事件处理机制(自定义事件)
* java中的事件机制的参与者有3种角色:
* 1.event object:事件状态对象,用于listener的相应的方法之中,作为参数,一般存在与listerner的方法之中
* 2.event source:具体的事件源,比如说,你点击一个button,那么button就是event
* source,要想使button对某些事件进行响应,你就需要注册特定的listener。
* 3.event listener:对每个明确的事件的发生,都相应地定义一个明确的Java方法。
* 这些方法都集中定义在事件监听者(EventListener)接口中,这个接口要继承 java.util.EventListener。
* 实现了事件监听者接口中一些或全部方法的类就是事件监听者。
*
* 伴随着事件的发生,相应的状态通常都封装在事件状态对象中,该对象必须继承自java.util.EventObject。
* 事件状态对象作为单参传递给应响应该事件的监听者方法中。
* 发出某种特定事件的事件源的标识是:遵从规定的设计格式为事件监听者定义注册方法,并接受对指定事件监听者接口实例的引用。
*
* 具体的对监听的事件类,当它监听到event object产生的时候,它就调用相应的方法,进行处理。
*
* 先看看jdk提供的event包: public interface EventListener:所有事件侦听器接口必须扩展的标记接口。
* public class EventObject extends Object implements Serializable 所有事件状态对象都将从其派生的根类。
* 所有 Event 在构造时都引用了对象 "source",在逻辑上认为该对象是最初发生有关 Event 的对象。
*/
public class DoorManager {
private Collection<DoorListener> listeners;
/**
* 添加事件
*
* @param listener
* DoorListener
*/
public void addDoorListener(DoorListener listener) {
if (listeners == null) {
listeners = new HashSet<DoorListener>();
}
listeners.add(listener);
}
/**
* 移除事件
*
* @param listener
* DoorListener
*/
public void removeDoorListener(DoorListener listener) {
if (listeners == null)
return;
listeners.remove(listener);
}
/**
* 触发开门事件
*/
protected void fireWorkspaceOpened() {
if (listeners == null)
return;
DoorEvent event = new DoorEvent(this, "open");
notifyListeners(event);
}
/**
* 触发关门事件
*/
protected void fireWorkspaceClosed() {
if (listeners == null)
return;
DoorEvent event = new DoorEvent(this, "close");
notifyListeners(event);
}
/**
* 通知所有的DoorListener
*/
private void notifyListeners(DoorEvent event) {
Iterator<DoorListener> iter = listeners.iterator();
while (iter.hasNext()) {
DoorListener listener = iter.next();
listener.doorEvent(event);
}
}
}
class DoorListener2 implements DoorListener {
@Override
public void doorEvent(DoorEvent event) {
if (event.getDoorState() != null && event.getDoorState().equals("open")) {
System.out.println("门2打开,同时打开走廊的灯");
} else {
System.out.println("门2关闭,同时关闭走廊的灯");
}
}
}
class DoorListener1 implements DoorListener {
@Override
public void doorEvent(DoorEvent event) {
if (event.getDoorState() != null && event.getDoorState().equals("open")) {
System.out.println("门1打开");
} else {
System.out.println("门1关闭");
}
}
}
interface DoorListener extends EventListener {
public void doorEvent(DoorEvent event);
}
class DoorEvent extends EventObject {
private static final long serialVersionUID = 6496098798146410884L;
private String doorState = "";// 表示门的状态,有“开”和“关”两种
public DoorEvent(Object source, String doorState) {
super(source);
this.doorState = doorState;
}
public void setDoorState(String doorState) {
this.doorState = doorState;
}
public String getDoorState() {
return this.doorState;
}
}
class DoorMain {
public static void main(String[] args) {
DoorManager manager = new DoorManager();
manager.addDoorListener(new DoorListener1());// 给门1增加监听器
manager.addDoorListener(new DoorListener2());// 给门2增加监听器
// 开门
manager.fireWorkspaceOpened();
System.out.println("我已经进来了");
// 关门
manager.fireWorkspaceClosed();
}
}
|
Python
|
UTF-8
| 340
| 2.515625
| 3
|
[] |
no_license
|
import cv2
image_file = "Image/study_image.jpg"
original = cv2.imread(image_file, cv2.IMREAD_COLOR)
gray = cv2.imread(image_file,cv2.IMREAD_GRAYSCALE)
unchange = cv2.imread(image_file, cv2.IMREAD_UNCHANGED)
cv2.imshow("imread_color", original)
cv2.imshow("image_gratscale", gray)
cv2.imshow("imread_unchange",unchange)
cv2.waitKey(0)
|
Python
|
UTF-8
| 387
| 3.921875
| 4
|
[] |
no_license
|
# Bar plots With Percentages
# Will use catplot() as it will be a categorical analysis.
import matplotlib.pyplot as plt
import seaborn as sns
# Use the survey_data DataFrame and sns.catplot() to create a bar plot with "Gender" on the x-axis
# and "Interested in Math" on the y-axis.
sns.catplot(data=survey_data, x='Gender', y='Interested in Math', kind='bar')
# Show plot
plt.show()
|
C
|
UTF-8
| 481
| 3.359375
| 3
|
[] |
no_license
|
#include "stack.h"
#include "tree.h"
void push(stack *s, node* x) {
s->a[s->i]= x;
(s->i)++;
}
/* the caller should check that the stack is not empty before calling pop()
*/
node* pop(stack *s) {
tree t = s->a[s->i - 1];
(s->i)--;
return t;
}
int empty(stack *s) {
return s->i == 0;
}
int full(stack *s) {
return s->i == N;
}
/* It is mandatory to call init() on a stack before calling push, pop or any other function on the stack
*/
void sinit(stack *s) {
s->i = 0;
}
|
Python
|
UTF-8
| 716
| 2.84375
| 3
|
[] |
no_license
|
import base64
import binascii
import dateutil.parser
# Decode an uplink message payload from a buffer
# From base64 payload to hex to string decoder
def decoder(payload):
messageByte = base64.b64decode(payload)
return messageByte.decode('utf-8')
# Convert bytes in hexadecimal to string
def hex_to_string(payload):
byte_to_string = binascii.hexlify(bytearray(payload))
return byte_to_string.decode('utf-8', 'strict')
# Remove header in the payload
def remove_payload_header(header, payload):
return payload[len(header):]
# Convert ISO datetime to datetime.datetime, drop millisecond value
def iso_to_datetime(dtr_str):
my_date = dateutil.parser.parse(dtr_str)
return my_date
|
Java
|
UTF-8
| 1,087
| 2.46875
| 2
|
[] |
no_license
|
package webfrontend.restful_newsticker.view;
import java.awt.BorderLayout;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import webfrontend.WebFrontend;
public class ArticleDialog extends JDialog {
private JEditorPane htmlpane;
private JScrollPane scrollpane;
public ArticleDialog()
{
setSize(600, 800);
setLayout(new BorderLayout(5, 5));
htmlpane=new JEditorPane("text/html", WebFrontend.loading);
htmlpane.setEditable(false);
scrollpane=new JScrollPane(htmlpane);
scrollpane.setAutoscrolls(false);
add(scrollpane,BorderLayout.CENTER);
}
public void setHtml(String html,String title)
{
setTitle(title);
// html=ArticleFactory.cleanSpecialTokens(html);
html=html.replaceAll("<p>", "<br><br><font face=verdana> ");
htmlpane.setText("<html><body><center><br><font face=arial size=5><b>" +
title+
"</b></font><table width=90%><tr><td align=justify valign=top><font face=verdana>"+
html+"</font></td></tr></table></body></html>");
htmlpane.setCaretPosition(0);
}
}
|
Java
|
UTF-8
| 1,257
| 2.40625
| 2
|
[] |
no_license
|
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.BookDAO;
import service.BookService;
import service.BookServiceImpl;
import vo.BookVO;
@WebServlet({ "/DeleteBookServlet", "/delete.do" })
public class DeleteBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
BookDAO dao = new BookDAO();
BookService service = new BookServiceImpl(dao);
String[] booknoList = request.getParameterValues("del");
for(String bookno:booknoList) {
try {
int i = service.deleteBook(bookno);
} catch (Exception e) {
request.setAttribute("exception", e);
getServletContext()
.getRequestDispatcher("/error.jsp")
.forward(request, response);
}
}
response.sendRedirect("list.do");
}
}
|
Python
|
UTF-8
| 556
| 4.875
| 5
|
[
"MIT"
] |
permissive
|
# comparison operators
temperature = 35
if temperature > 30:
print("It's a hot day.")
else:
print("It's not a hot day.")
# exercise - If name is less than 3 characters long
# name must be at least 3 characters
# otherwise if it's more than 50 characters long
# name can be maximum of 50 characters
# otherwise
# name looks good!
name = "John Smith"
if len(name) < 3:
print("Name must be at least 3 characters")
elif len(name) > 50:
print("Name must be a maximum of 50 characters")
else:
print("Name looks good")
print(name)
|
Java
|
UTF-8
| 1,536
| 2.203125
| 2
|
[] |
no_license
|
package mx.unam.ciencias.is.mapeobd;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author Héctor Santaella Marín
*/
@Entity
@Table (name="Usuario")
public class Usuario {
@Id@GeneratedValue(strategy =GenerationType.IDENTITY )
@Column(name="idUsuario")
private int idUsuario;
@Column (name="nickname")
private String nickname;
@Column (name="correo")
private String correo;
@Column (name="contrasena")
private String contrasena;
public int getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(int idUsuario) {
this.idUsuario = idUsuario;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public String getContrasena() {
return contrasena;
}
public void setContrasena(String contrasena) {
this.contrasena = contrasena;
}
@OneToMany(mappedBy="user")
private Set<Marcador> marcadores;
public void setMarcadores(Set<Marcador> marcadores) {
this.marcadores = marcadores;
}
public Set<Marcador> getMarcadores() {
return marcadores;
}
}
|
Markdown
|
UTF-8
| 1,516
| 3.03125
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Vert.x Concurrent
[](https://travis-ci.org/rworsnop/vertx-concurrent)
A selection of utilities from java.util.concurrent, in Vert.x-aware, non-blocking form.
See the [api docs](http://rworsnop.github.io/vertx-concurrent/apidocs/)
## Getting the library
Either grab the latest from the [releases page](https://github.com/rworsnop/vertx-beans/releases) or add a Maven dependency:
```
<dependency>
<groupId>com.github.rworsnop</groupId>
<artifactId>vertx-concurrent</artifactId>
<version>1.0.0</version>
</dependency>
```
## Examples
### Semaphore
```
Semaphore semaphore = new Semaphore(50, vertx);
semaphore.acquire(10, ()->{
// do some work
semaphore.release(10);
}));
```
```
Semaphore semaphore = new Semaphore(50, vertx);
if (semaphore.tryAcquire(10)) {
// do some work
semaphore.release(10);
}
```
```
Semaphore semaphore = new Semaphore(50, vertx);
semaphore.tryAcquire(10, 30, SECONDS, success->{
if (success){
// do some work
semaphore.release(10);
} else {
// timed out before we could acquire permits
}
});
```
```
// Don't process more than 30,000 requests in a 10-second window
Semaphore semaphore = new Semaphore(30_000, vertx);
vertx.createHttpServer().requestHandler(req->{
semaphore.acquire(()->req.response().end("Permits: " + semaphore.getAvailablePermits()));
vertx.setTimer(10_000, id->semaphore.release());
}).listen(8082);
```
|
Python
|
UTF-8
| 308
| 3.046875
| 3
|
[] |
no_license
|
D1={'a':10,'b':20,'c':30,'d':40}
D2={'c':12, 'e':15, 'f':18}
D={}
for each in D1.keys():
if each in D2:
D.setdefault(each,D1[each]+D2[each])
else:
D.setdefault(each,D1[each])
for each in D2.keys():
if each not in D:
D.setdefault(each,D2[each])
print (D)
|
Java
|
UTF-8
| 2,409
| 2.421875
| 2
|
[] |
no_license
|
package com.example.web;
import com.example.domain.model.EmployeeEntity;
import com.example.domain.model.MappingHelper;
import com.example.domain.repository.EmployeeRepository;
import com.example.domain.service.BenchmarkService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequiredArgsConstructor
public class SandboxRestController {
private final BenchmarkService benchmarkService;
private final EmployeeRepository employeeRepository;
@RequestMapping("/mybatisToMap")
public ResponseEntity<Map> mybatisToMap() {
List<MappingHelper<Integer, EmployeeEntity>> mapperList = employeeRepository.findAllByIds(Arrays.asList(1, 2));
Map<Integer, EmployeeEntity> employeeMap = MappingHelper.toMap(mapperList);
return ResponseEntity.ok().body(employeeMap);
}
@RequestMapping("/benchmark/sql/loop")
public ResponseEntity<Map> benchmarkDatabaseAccess() {
// IN句を使って1回で10,000件のレコードを取得
long beforeOneTime = System.currentTimeMillis();
benchmarkService.oneTimesDatabaseAccess();
long afterOneTime = System.currentTimeMillis();
// 10,000回のループで1件ずつレコードを取得
long beforeLoopTime = System.currentTimeMillis();
benchmarkService.tenThousandTimesDatabaseAccess();
long afterLoopTime = System.currentTimeMillis();
Map<String, Long> result = new HashMap<>();
result.put("oneTimeFirst", afterOneTime - beforeOneTime);
result.put("loopTimeFirst", afterLoopTime - beforeLoopTime);
// 同様の処理をもう1回
beforeOneTime = System.currentTimeMillis();
benchmarkService.oneTimesDatabaseAccess();
afterOneTime = System.currentTimeMillis();
beforeLoopTime = System.currentTimeMillis();
benchmarkService.tenThousandTimesDatabaseAccess();
afterLoopTime = System.currentTimeMillis();
result.put("oneTimeSecond", afterOneTime - beforeOneTime);
result.put("loopTimeSecond", afterLoopTime - beforeLoopTime);
return ResponseEntity.status(200).body(result);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.