language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C# | UTF-8 | 3,708 | 2.515625 | 3 | [] | no_license | using DataOperations.DBEntity;
using DataOperations.DBEntityManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace CSOutreach.Pages.Common
{
public partial class Signup : System.Web.UI.Page
{
public const string ROLENAME = "Student"; //setting to student when registering for first time
public const bool ISLOCKED = false;
protected void Page_Load(object sender, EventArgs e)
{
//To hide the success and error messages initially
HtmlGenericControl divsuccess = Master.FindControl("BodyContent").FindControl("divsuccess") as HtmlGenericControl;
if (divsuccess != null)
divsuccess.Style["display"] = "none";
HtmlGenericControl diverror = Master.FindControl("BodyContent").FindControl("diverror") as HtmlGenericControl;
if (diverror != null)
diverror.Style["display"] = "none";
}
/// <summary>
/// Check User Id exist or Not in database.
/// </summary>
/// <param name="userName">UserName</param>
/// <returns></returns>
[WebMethod()]
public static bool CheckUserExists(string userName)
{
try
{
PersonDBManager user = new PersonDBManager();
Person personDetails = new Person();
personDetails = user.GetUser(userName.Trim());
if (personDetails == null)
return true;
}
catch (Exception e)
{
}
return false;
}
protected void btnSubmit_ServerClick(object sender, EventArgs e)
{
PersonDBManager persondb = new PersonDBManager();
Person signup_user = new Person();
signup_user.FirstName = FirstName.Value.Trim();
signup_user.LastName = LastName.Value.Trim();
signup_user.Address = Address1.Value.Trim().Replace("'", "''") + Address2.Value.Trim().Replace("'", "''") + City.Value.Trim() + State.Value.Trim() + Zip.Value.Trim();
signup_user.ContactNumber = PhoneAreaCode.Value.Trim() + PhoneFirstPart.Value.Trim() + PhoneSecondPart.Value.Trim();
signup_user.Email = Email.Value.Trim();
signup_user.Password = Password.Value.Trim();
signup_user.Role = ROLENAME;
signup_user.IsLocked = ISLOCKED;
bool result = persondb.AddNewUserDetails(signup_user);
if (result == true)
{
HtmlGenericControl divsuccess = Master.FindControl("BodyContent").FindControl("divsuccess") as HtmlGenericControl;
if (divsuccess != null)
divsuccess.Style["display"] = "block";
}
else
{
HtmlGenericControl diverror = Master.FindControl("BodyContent").FindControl("diverror") as HtmlGenericControl;
if (diverror != null)
diverror.Style["display"] = "block";
}
ClearValues();
}
protected void ClearValues()
{
//Clear all the textboxes.
foreach (Control ctrl in Master.FindControl("BodyContent").Controls)
{
if (ctrl.GetType().Name == "HtmlInputText")
{
((HtmlInputText)ctrl).Value = string.Empty;
}
}
}
}
} |
PHP | UTF-8 | 866 | 2.84375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | <?php
include_once "config/database.php";
include_once "objects/product.php";
$db_conn = new Database();
$product = new Product($db_conn->getConnection());
$product_read = $product->read();
//var_dump($product_read->fetchAll());
//
while ($row = $product_read->fetch(PDO::FETCH_ASSOC)) {
// extract row
// this will make $row['name'] to
// just $name only
extract($row);
/** @var TYPE_NAME $id */
/** @var TYPE_NAME $name */
/** @var TYPE_NAME $description */
/** @var TYPE_NAME $price */
/** @var TYPE_NAME $category_id */
/** @var TYPE_NAME $category_name */
/** @var TYPE_NAME $created */
$product_item = array(
"id" => $id,
"name" => $name,
"description" => html_entity_decode($description),
"price" => $price,
"category_id" => $category_id,
"category_name" => $category_name,
"created" => $created
);
} |
Python | UTF-8 | 3,245 | 4.3125 | 4 | [] | no_license | # Demonstrates various list methods
from collections import deque
from functools import reduce
import bisect
# List names are plural by convention
# Lists are considered mutable objects, thus when var = list is used, the list
# is passed by reference instead of by value. As a result, any changes to list
# will affect var.
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple']
# Size of list
print(len(fruits))
print(fruits.count('apple'))
# If you just need to know if a value is in a list, use: value in list
print(fruits.index('apple'))
# Find an instance of apple starting at index 2
print(fruits.index('apple', 2))
# slice() works on lists as it does strings
print('slice:', fruits[slice(0, 10, 2)])
# Demonstrates copy and reverse functions
# The significance of copy() is that the value remains unchanged when the
# original variable is modified.
fruits2 = fruits.copy()
# It is also possible to reverse the list without altering the original using
# list(reversed(fruits))
fruits2.reverse()
print('reverse:', fruits2)
fruits.append('grape')
# extend is like append, but for lists. It returns None. If you wish to return
# the combined lists instead, use result = list1 + list2
fruits.extend(['mango', 'papaya'])
print('append:', fruits)
# Of note is the face remove only removes the first matching element.
fruits.remove('apple')
print('remove:', fruits)
fruits.sort()
print('sort:', fruits)
# Demonstrates sorting using a function as key.
# Alternatively, use key=lambda x: x[-1].
def last_letter(x):
return x[-1]
fruits.sort(key=last_letter)
print('sort by last letter:', fruits)
# Demonstrates chcking for elements in a list
e = 'apple'
if e in fruits:
print(f'{e} is in fruits')
# Checking for multiple elements
e = ['apple', 'orange']
if all(x in fruits for x in e):
print(f'{e} is in fruits')
# list.pop(index=None) removes last entry and returns it.
# If index is given it removes the correspending list element.
# Can be used with append to make a stack.
print(fruits.pop(2))
print('pop:', fruits)
# Demonstrates use of bisect module to replace a deleted key from a list.
fruits_numbered = list(enumerate(fruits))
key = 2
del fruits_numbered[key]
bisect.insort(fruits_numbered, (key, 'guava'))
print(fruits_numbered)
# Deletes list.
fruits.clear()
print()
# Imports a type of list where append and pop functions can be applied to the
# beginning.
enemies = deque(['Orc', 'Goblin', 'Catapult'])
enemies.appendleft('Slime')
print('append:', enemies)
print('You struck down the ' + enemies.popleft() + '.')
print('You struck down the ' + enemies.popleft() + '.')
print('Enemies left:', enemies)
print()
# Demonstrates mathematical operations between number lists
nums = [1, 2, 3]
nums2 = [3, 2, 1]
result = []
for e, e2 in zip(nums, nums2):
result.append(e - e2)
print('subtraction between lists:')
print(result)
print()
# Demonstrates 2d list.
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
# Note how indexing works on a 2d list.
print(grid[2])
# Demonstrates looping through 2d list using a nested loop.
for row in grid:
print(row)
print('Sum:', sum(row))
for element in row:
mavg = reduce(lambda x, y: (x + y)/2, row)
print('Mavg:', mavg)
print()
|
Markdown | UTF-8 | 7,043 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | ---
parent: Conventions
---
# Action menus
## Kebab and resource Actions menus
- A resource's Actions menu is accessible from a number of places, such as:
1. List view kebab
2. Details page actions dropdown
3. Topology side panel
4. Topology right-click action on a resource
- By default, submenus will open to the right of the main menu. In cases where there is no space to the right, they can open to the left.
**List view kebab**

**Details page actions dropdown**

**Topology side panel**

**Topology right click action on a resource**

- Actions dropdowns are styled as primary blue dropdowns.
- Exceptions are acceptable in cases where a different action(s) has been identified as the view's primary action. In these cases, the primary action(s) is usually pulled out of the dropdown and is styled as a primary button or dropdown to the left of the Actions dropdown, which will thus have secondary styling (e.g., Secrets details pages).
## Organization of Actions menu items
**Basic action menus**
<img src="../images/action-menus-1.png" alt="Action menus order" width="294"/>
The majority of resource action menus will be a basic action menu. These menus have "universal" actions and the `Delete {resource_type}` action separated by a horizontal divider.
**Complex action menus**
Some resource action menus will have more actions than those included in the basic action menu. The following documentation uses a Deployment as an example, but the logic to each section should be applied to any other complex action menu.
<img src="../images/action-menus-2.png" alt="Action menus order" width="1239"/>
Action menus are separated into multiple sections. The ordering of sections and actions in the menu should adhere to the following pattern:
1. **Resource specific actions**
* This section includes both standalone actions and flyout actions with submenus (see below for submenu guidance). Standalone actions are listed first, ordered alphabetically by default. Next, flyouts are listed, also alphabetically by default.
* Exceptions are acceptable in the cases where an action may be dynamic (e.g., `Pause rollouts` becomes `Resume rollouts`, but the action should not move from its original position).
2. **"Universal" actions**
* These actions are available for every resource in the console. These are listed in the following order:
1. `Edit labels`
2. `Edit annotations`
3. `Edit {resource_type}`
3. **Delete resource action**
* The last section of each Actions menu has the `Delete {resource_type}` action.
4. **Submenus**
* In this example, the resource has two or more actions that are Edit actions, and are thus put into an Edit submenu.
* Resources may have multiple submenus.
* The default logic for ordering these actions is alphabetical.
* If multiple actions relate directly to one topic, they can go in their own submenu. For example, dynamic actions relating to HorizontalPodAutoscalers will be listed in an "Autoscale" submenu.
* If the resource doesn't yet have a HorizontalPodAutoscaler, the only action in the submenu will be `Add HorizontalPodAutoscaler`. If one exists already, the Add action will be replaced by `Edit HorizontalPodAutoscaler` and `Delete HorizontalPodAutoscaler`. (In the future, VerticalPodAutoscalers may be added to this submenu, with the same dynamic actions used for HPAs – Add, Edit, and Delete.)
<img src="../images/action-menus-3.png" alt="Action menus order" width="329"/>
5. **Additional Edit action**
* In cases where a resource was created via an import flow, they may have an additional Edit action.
* The Edit action is listed below the default `Edit {resource_type}` action.
* The Edit action name will reflect the import flow used to create the resource. The following are the possible Edit labels for this action:
* `Edit JAR import`
* `Edit Git import`
* `Edit Container import`
Naming of actions:
- Actions for resources do not need to include the resource’s name they affect, unless many resource types can be affected in the actions menu (e.g. taking action on HorizontalPodAutoscalers from Deployment action menu).
- Create, Edit, Delete are the exceptions in that they always include the full name of the resource they affect.
- Action labels should follow the [capitalization convention](http://openshift.github.io/openshift-origin-design/conventions/documentation/capitalization.html).
---
## Bulk Actions Menu
- This is a convention that hasn’t yet been implemented in the console. [Learn more here](http://openshift.github.io/openshift-origin-design/designs/administrator/future-openshift/bulk-actions/)
- List views of resources may support multi-select and a bulk “Actions” menu.

Actions in the menu should follow the following pattern:
- Unique bulk actions to that resource should appear above default bulk resource actions
- Add Labels (when present)
- Add Annotations (when present)
- Delete [Resource Name(s)]
---
## Hiding and disabling actions
The following convention describes when to hide or disable an action in the console and provides examples for each scenario. Note that while these guidelines should be the default behavior, exceptions may be made where necessary.
1. If an action isn’t recommended or encouraged, but the action technically can be performed, **use a modal** to ask the user “Are you sure?” and explain the potential consequences rather than hide or disable the action.
* Example: *A user wants to start maintenance on a master node*
2. If an action isn’t available because a user doesn’t have the correct RBAC, **disable** those actions.
* Example: *A user with view-only privileges looks at a Pod’s details page and the options within the Actions dropdown are disabled*
3. If an action isn’t available because the user needs to do something else in the UI first, **disable** the action with a tooltip explaining what they need to do to enable the action. This aids in discoverability of actions within the console.
* Example: *A user can’t perform bulk actions until they select resources in the list*
4. If an action is dependent on a condition or status in the console, **disable** the action with a tooltip explaining why the action currently is unavailable.
* Example: *A user cannot view past logs because this container hasn’t restarted*
5. If an action cannot be taken because of a product / K8s constraint or rule, **hide** the action.
* Example: *A user can’t delete a Red Hat template or remove an Environment variable from a managed resource*
* Exception: *Environment variables themselves should be shown but disabled, so that users can see a read-only view of the related variables*
|
JavaScript | UTF-8 | 958 | 3.046875 | 3 | [] | no_license | 'use strict';
(function () {
// Variables
var coatColors = ['rgb(101, 137, 164)', 'rgb(241, 43, 107)', 'rgb(146, 100, 161)', 'rgb(56, 159, 117)', 'rgb(215, 210, 55)', 'rgb(0, 0, 0)'];
var eyesColors = ['black', 'red', 'blue', 'yellow', 'green'];
var fireballColors = ['#ee4830', '#30a8ee', '#5ce6c0', '#e848d5', '#e6e848'];
// Customize wizard
var setCustomFill = function (element, color) {
element.style.fill = color;
};
var setCustomBg = function (element, color) {
element.style.backgroundColor = color;
};
var wizardCoat = document.querySelector('.setup-wizard .wizard-coat');
var wizardEyes = document.querySelector('.setup-wizard .wizard-eyes');
var fireball = document.querySelector('.setup-fireball-wrap');
window.colorizeElement(wizardCoat, coatColors, setCustomFill);
window.colorizeElement(wizardEyes, eyesColors, setCustomFill);
window.colorizeElement(fireball, fireballColors, setCustomBg);
})();
|
Ruby | UTF-8 | 3,170 | 3.203125 | 3 | [
"MIT"
] | permissive | Foo::bar
::Bar
puts ::Foo::Bar
foo[bar]
foo[*bar]
foo[* bar]
foo[]
foo["bar"]
foo[:bar]
foo[bar] = 1
()
;
yield
yield foo
yield foo, bar
not foo
foo and bar
foo or bar
a or b and c
defined? foo
defined? Foo.bar
defined?(foo)
defined?($foo)
defined?(@foo)
defined?(@äö)
x = y
x = *args
FALSE = "false"
TRUE = "true"
NIL = "nil"
x, y = [1, 2]
x, * = [1, 2]
x, *args = [1, 2]
x, y = *foo
self.foo, self.bar = target.a?, target.b
(x, y) = foo
(a, b, c = 1)
foo = 1, 2
x, y = foo, bar
a, (b, c), d, (e, (f, g)) = foo
x = foo a, b
x = foo a, :b => 1, :c => 2
x += y
x -= y
x *= y
x **= y
x /= y
puts "/hi"
x ||= y
x &&= y
x &= y
x |= y
x %= y
x >>= y
x <<= y
x ^= y
a ? b : c
a ? b
: c
true ?")":"c"
foo ? true: false
foo ? return: false
a..b
a...b
a || b
a && b
a == b
a != b
a =~ b
a !~ b
a < b
a <= b
a > b
a >= b
a | b
a ^ b
a & b
a >> b
a << b
a + b
a * b
2+2*2
-a
foo -a, bar
foo(-a, bar)
foo-a
@ivar-1
a ** b
!a
foo
foo()
print "hello"
print("hello")
foo a,
b, c
foo(a, b,)
foo(bar(a),)
foo.bar
foo.bar()
foo.bar "hi"
foo.bar "hi", 2
foo.bar("hi")
foo.bar("hi", 2)
foo[bar].()
foo.(1, 2)
a.() {}
a.(b: c) do
d
end
foo.[]()
foo&.bar
foo(:a => true)
foo([] => 1)
foo(bar => 1)
foo :a => true, :c => 1
foo(a: true)
foo a: true
foo B: true
foo(if: true)
foo alias: true
foo and: true
foo begin: true
foo break: true
foo case: true
foo class: true
foo def: true
foo defined: true
foo do: true
foo else: true
foo elsif: true
foo end: true
foo ensure: true
foo false: true
foo for: true
foo if: true
foo in: true
foo module: true
foo next: true
foo nil: true
foo not: true
foo or: true
foo redo: true
foo rescue: true
foo retry: true
foo return: true
foo self: true
foo super: true
foo then: true
foo true: true
foo undef: true
foo unless: true
foo until: true
foo when: true
foo while: true
foo yield: true
foo (b), a
foo(&:sort)
foo(&bar)
foo(&bar, 1)
foo &bar
foo &bar, 1
foo(*bar)
foo *bar
foo *%w{ .. lib }
foo *(bar.baz)
foo :bar, -> (a) { 1 }
foo :bar, -> (a) { where(:c => b) }
foo :bar, -> (a) { 1 } do
end
foo(*bar)
foo(*[bar, baz].quoz)
foo(x, *bar)
foo(*bar.baz)
foo(**baz)
include D::E.f
Foo
.bar
.baz
Foo \
.bar
foo do |i|
foo
end
foo do
|i| i
end
foo do; end
foo(a) do |i|
foo
end
foo.bar a do |i|
foo
end
foo(a) do |name: i, *args|
end
foo { |i| foo }
foo items.any? { |i| i > 0 }
foo(bar, baz) { quux }
foo { |; i, j| }
request.GET
-> (d, *f, (x, y)) {}
def foo(d, *f, (x, y))
end
def foo d, *f, (x, y)
end
foo do |a, (c, d, *f, (x, y)), *e|
end
foo []
foo [1]
foo[1]
lambda {}
lambda { foo }
lambda(&block) { foo }
lambda(&lambda{})
lambda { |foo| 1 }
lambda { |a, b, c|
1
2
}
lambda { |a, b,|
1
}
lambda { |a, b=nil|
1
}
lambda { |a, b: nil|
1
}
lambda do |foo|
1
end
proc = Proc.new
lambda = lambda {}
proc = proc {}
foo \
a, b
"abc \
de"
foo \
"abc"
10 / 5
h/w
"#{foo}"
Time.at(timestamp/1000)
"#{timestamp}"
foo /bar/
foo
/ bar/
Foo / "bar"
"/edit"
/ a
b/
|
C | UTF-8 | 555 | 3.109375 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
void __gen_params(char *str, int n, int curpos, int l , int r) {
if(curpos == 2*n) {
str[curpos] = '\0';
printf("%s\n",str);
return;
}
if(l < n) {
str[curpos] = '(';
__gen_params(str, n , curpos+1, l+1, r);
}
if(r < l) {
str[curpos] = ')';
__gen_params(str, n , curpos+1, l, r+1);
}
}
void gen_params(char *str, int n){
__gen_params(str, n , 0, 0, 0 );
}
main() {
int n = 4;
char *str = (char *)malloc(sizeof(char)*(2*n+1));
memset(str, 0X00, 2*n +1);
gen_params(str,n);
}
|
Markdown | UTF-8 | 7,348 | 2.828125 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | ---
title: "Data Transformations with LINQ (C#) | Microsoft Docs"
ms.custom: ""
ms.date: "2015-07-20"
ms.prod: .net
ms.reviewer: ""
ms.suite: ""
ms.technology:
- "devlang-csharp"
ms.topic: "article"
dev_langs:
- "CSharp"
helpviewer_keywords:
- "LINQ [C#], data transformations"
- "source elements [LINQ in C#]"
- "joining multiple inputs [LINQ in C#]"
- "multiple outputs for one output sequence [LINQ in C#]"
- "subset of source elements [LINQ in C#]"
- "data sources [LINQ in C#], data transformations"
- "data transformations [LINQ in C#]"
ms.assetid: 674eae9e-bc72-4a88-aed3-802b45b25811
caps.latest.revision: 17
author: "BillWagner"
ms.author: "wiwagn"
translation.priority.ht:
- "de-de"
- "es-es"
- "fr-fr"
- "it-it"
- "ja-jp"
- "ko-kr"
- "ru-ru"
- "zh-cn"
- "zh-tw"
translation.priority.mt:
- "cs-cz"
- "pl-pl"
- "pt-br"
- "tr-tr"
---
# Data Transformations with LINQ (C#)
[!INCLUDE[vbteclinqext](../../../../csharp/getting-started/includes/vbteclinqext_md.md)] is not only about retrieving data. It is also a powerful tool for transforming data. By using a [!INCLUDE[vbteclinq](../../../../csharp/includes/vbteclinq_md.md)] query, you can use a source sequence as input and modify it in many ways to create a new output sequence. You can modify the sequence itself without modifying the elements themselves by sorting and grouping. But perhaps the most powerful feature of [!INCLUDE[vbteclinq](../../../../csharp/includes/vbteclinq_md.md)] queries is the ability to create new types. This is accomplished in the [select](../../../../csharp/language-reference/keywords/select-clause.md) clause. For example, you can perform the following tasks:
- Merge multiple input sequences into a single output sequence that has a new type.
- Create output sequences whose elements consist of only one or several properties of each element in the source sequence.
- Create output sequences whose elements consist of the results of operations performed on the source data.
- Create output sequences in a different format. For example, you can transform data from SQL rows or text files into XML.
These are just several examples. Of course, these transformations can be combined in various ways in the same query. Furthermore, the output sequence of one query can be used as the input sequence for a new query.
## Joining Multiple Inputs into One Output Sequence
You can use a [!INCLUDE[vbteclinq](../../../../csharp/includes/vbteclinq_md.md)] query to create an output sequence that contains elements from more than one input sequence. The following example shows how to combine two in-memory data structures, but the same principles can be applied to combine data from XML or SQL or DataSet sources. Assume the following two class types:
[!code-cs[CsLINQGettingStarted#7](../../../../csharp/programming-guide/concepts/linq/codesnippet/CSharp/data-transformations-with-linq_1.cs)]
The following example shows the query:
[!code-cs[CSLinqGettingStarted#8](../../../../csharp/programming-guide/concepts/linq/codesnippet/CSharp/data-transformations-with-linq_2.cs)]
For more information, see [join clause](../../../../csharp/language-reference/keywords/join-clause.md) and [select clause](../../../../csharp/language-reference/keywords/select-clause.md).
## Selecting a Subset of each Source Element
There are two primary ways to select a subset of each element in the source sequence:
1. To select just one member of the source element, use the dot operation. In the following example, assume that a `Customer` object contains several public properties including a string named `City`. When executed, this query will produce an output sequence of strings.
```
var query = from cust in Customers
select cust.City;
```
2. To create elements that contain more than one property from the source element, you can use an object initializer with either a named object or an anonymous type. The following example shows the use of an anonymous type to encapsulate two properties from each `Customer` element:
```
var query = from cust in Customer
select new {Name = cust.Name, City = cust.City};
```
For more information, see [Object and Collection Initializers](../../../../csharp/programming-guide/classes-and-structs/object-and-collection-initializers.md) and [Anonymous Types](../../../../csharp/programming-guide/classes-and-structs/anonymous-types.md).
## Transforming in-Memory Objects into XML
[!INCLUDE[vbteclinq](../../../../csharp/includes/vbteclinq_md.md)] queries make it easy to transform data between in-memory data structures, SQL databases, [!INCLUDE[vstecado](../../../../csharp/programming-guide/concepts/linq/includes/vstecado_md.md)] Datasets and XML streams or documents. The following example transforms objects in an in-memory data structure into XML elements.
[!code-cs[CsLINQGettingStarted#9](../../../../csharp/programming-guide/concepts/linq/codesnippet/CSharp/data-transformations-with-linq_3.cs)]
The code produces the following XML output:
```
< Root>
<student>
<First>Svetlana</First>
<Last>Omelchenko</Last>
<Scores>97,92,81,60</Scores>
</student>
<student>
<First>Claire</First>
<Last>O'Donnell</Last>
<Scores>75,84,91,39</Scores>
</student>
<student>
<First>Sven</First>
<Last>Mortensen</Last>
<Scores>88,94,65,91</Scores>
</student>
</Root>
```
For more information, see [Creating XML Trees in C# (LINQ to XML)](../../../../csharp/programming-guide/concepts/linq/creating-xml-trees-linq-to-xml-2.md).
## Performing Operations on Source Elements
An output sequence might not contain any elements or element properties from the source sequence. The output might instead be a sequence of values that is computed by using the source elements as input arguments. The following simple query, when it is executed, outputs a sequence of strings whose values represent a calculation based on the source sequence of elements of type `double`.
> [!NOTE]
> Calling methods in query expressions is not supported if the query will be translated into some other domain. For example, you cannot call an ordinary C# method in [!INCLUDE[vbtecdlinq](../../../../csharp/includes/vbtecdlinq_md.md)] because SQL Server has no context for it. However, you can map stored procedures to methods and call those. For more information, see [Stored Procedures](../../../../framework/data/adonet/sql/linq/stored-procedures.md).
[!code-cs[CsLINQGettingStarted#10](../../../../csharp/programming-guide/concepts/linq/codesnippet/CSharp/data-transformations-with-linq_4.cs)]
## See Also
[Language-Integrated Query (LINQ) (C#)](../../../../csharp/programming-guide/concepts/linq/index.md)
[LINQ to SQL](https://msdn.microsoft.com/library/bb386976)
[LINQ to DataSet](../../../../framework/data/adonet/linq-to-dataset.md)
[LINQ to XML (C#)](../../../../csharp/programming-guide/concepts/linq/linq-to-xml.md)
[LINQ Query Expressions](../../../../csharp/programming-guide/linq-query-expressions/index.md)
[select clause](../../../../csharp/language-reference/keywords/select-clause.md) |
Java | UTF-8 | 5,065 | 2.328125 | 2 | [] | no_license | package com.example.konrad.trainingtracker;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import com.example.konrad.trainingtracker.datastore.TrainingDBAdapter;
import com.example.konrad.trainingtracker.fragments.TrainingInfoFragment;
import com.example.konrad.trainingtracker.model.Duration;
import com.example.konrad.trainingtracker.model.Training;
public class TrainingDetailsActivity extends ActionBarActivity {
public final static String INTENT_ARGUMENT_ID = "t_id";
public final static String INTENT_ARGUMENT_PARENT_ACTIVITY = "parent_activity";
public final static String INTENT_VALUE_MAIN_ACTIVITY = "MainActivity";
public final static String INTENT_VALUE_LIST_ACTIVITY = "ListActivity";
private TrainingDBAdapter database;
private String parentActivity;
private long trainingId;
private Training training;
private Duration duration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_training_details);
parentActivity = getIntent().getStringExtra(INTENT_ARGUMENT_PARENT_ACTIVITY);
trainingId = getIntent().getLongExtra(INTENT_ARGUMENT_ID, 0);
}
@Override
protected void onResume() {
super.onResume();
database = new TrainingDBAdapter(this);
training = database.getTraining(trainingId);
duration = new Duration(training.getDuration());
initializeTrainingInfoFragment();
}
private void initializeTrainingInfoFragment() {
TrainingInfoFragment trainingInfoFragment = (TrainingInfoFragment) getFragmentManager().findFragmentById(R.id.training_info);
trainingInfoFragment.setTraining(training);
trainingInfoFragment.setDuration(duration);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_training_details, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(TrainingDetailsActivity.this, SettingsActivity.class);
startActivity(intent);
return true;
}else if(id == R.id.action_delete){
showConfirmationAlert();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && INTENT_VALUE_MAIN_ACTIVITY.equals(parentActivity)) {
Intent intent = new Intent(TrainingDetailsActivity.this, MainActivity.class);
startActivity(intent);
finish();
return true;
}else if(keyCode == KeyEvent.KEYCODE_BACK && INTENT_VALUE_LIST_ACTIVITY.equals(parentActivity)){
Intent intent = new Intent(TrainingDetailsActivity.this, TrainingListActivity.class);
startActivity(intent);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void showConfirmationAlert() {
AlertDialog alertDialog = new AlertDialog.Builder(TrainingDetailsActivity.this).create();
alertDialog.setTitle(getString(R.string.confirmation));
alertDialog.setMessage(getString(R.string.wantDelete));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
deleteTraining();
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void deleteTraining(){
database.deleteTraining(trainingId);
Intent intent;
if(INTENT_VALUE_MAIN_ACTIVITY.equals(parentActivity)){
intent = new Intent(TrainingDetailsActivity.this, MainActivity.class);
}else {
intent = new Intent(TrainingDetailsActivity.this, TrainingListActivity.class);
}
startActivity(intent);
finish();
}
}
|
JavaScript | UTF-8 | 1,863 | 3.21875 | 3 | [] | no_license | import { useState, useEffect, useRef } from "react";
import styles from "./Clock.module.css";
export default function Clock() {
const [time, setTime] = useState(() => new Date());
const intervalId = useRef(null);
useEffect(() => {
intervalId.current = setInterval(() => {
console.log("Это интервал каждые 2000ms " + Date.now());
setTime(new Date());
}, 2000);
return () => {
console.log("Это функция очистки перед следующим вызовом useEffect");
stop();
};
}, []);
const stop = () => {
clearInterval(intervalId.current);
};
return (
<div className={styles.container}>
<p className={styles.clockface}>
Текущее время: {time.toLocaleTimeString()}
</p>
<button type="button" onClick={stop}>
Остановить
</button>
</div>
);
}
// class OldClock extends Component {
// state = {
// time: new Date(),
// };
// intervalId = null;
// componentDidMount() {
// this.intervalId = setInterval(() => {
// console.log('Это интервал каждые 1000ms ' + Date.now());
// this.setState({ time: new Date() });
// }, 1000);
// }
// componentWillUnmount() {
// console.log('Эот метод вызывается перед размонтированием компонента');
// this.stop();
// }
// stop = () => {
// clearInterval(this.intervalId);
// };
// render() {
// return (
// <div className={styles.container}>
// <p className={styles.clockface}>
// Текущее время: {this.state.time.toLocaleTimeString()}
// </p>
// <button type="button" onClick={this.stop}>
// Остановить
// </button>
// </div>
// );
// }
// }
|
Java | UTF-8 | 4,739 | 3.078125 | 3 | [] | no_license | package tk.simplaysgames.messenger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by SimPlaysGames on 18.11.2016.
*/
public class Server extends JFrame{
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
//Constructor
public Server() {
super("Sim's Instant Messenger");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.SOUTH);
chatWindow = new JTextArea();
chatWindow.setEditable(false)
add(new JScrollPane(chatWindow));
setSize(300, 150);
setVisible(true);
}
//Set up and run the server
public void startRunning(){
try{
server = new ServerSocket(6789, 100);
while(true){
try{
waitForConnection();
setupStreams();
whileChatting();
}
catch(EOFException eofExceptopn){
showMessage("\n Server ended the connection!");
}
finally {
closeConnection();
}
}
}
catch (IOException ioExceptione){
ioExceptione.printStackTrace();
}
}
//Wait for connection, then display connection information
private void waitForConnection()throws IOException{
showMessage("Waiting for someone to connect...\n");
connection = server.accept();
showMessage(" You are now connected!");
}
//Get stream to send and recieve data
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n The streams are setup! \n");
}
//During the conversation
private void whileChatting() throws IOException {
String message = " You are now connected! ";
sendMessage(message);
ableToType(true);
do {
try {
message = (String) input.readObject();
showMessage("\n" + message);
} catch (ClassNotFoundException classNotFoundException) {
showMessage("\n Oops, Something weird happened! Please try again");
}
}
while (!message.equals("CLIENT - END"));
closeConnection();
}
//Close streams and sockets when done
private void closeConnection(){
showMessage("\n Closing connections... \n");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}
catch (IOException ioException){
ioException.printStackTrace();
}
}
//Send a message to client
private void sendMessage(String message){
try{
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER - " + message);
}
catch (IOException ioException){
chatWindow.append("\n ERROR: Message could not be sent!");
}
}
//Updates the chat window (Shows the message)
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
@Override
public void run() {
chatWindow.append(text);
}
}
);
}
//Change the permission to type (let them, or disallow them)
private void ableToType (final boolean bool){
SwingUtilities.invokeLater(
new Runnable(){
@Override
public void run() {
userText.setEditable(bool);
}
}
);
}
}
|
Python | UTF-8 | 3,700 | 3.296875 | 3 | [] | no_license | def getnumber(self):
#This function will be used to get the number of goals we want to reach at the end
rospy.init_node('listener', anonymous=True) #we create our code
while self.number < 1: #we don't want a number of goals less than 1 so we
#create a loop to obtain a positive integer
try:
self.number = int(raw_input('Enter the number of wanted waypoints: '))
#we check if the number is an integer
if self.number < 1: #if the number is less than one
rospy.loginfo("Not a positive number") #we ask a positive number
except ValueError: #if the input is not an integer
rospy.loginfo("Not a positive number") #we ask a positive number
rospy.loginfo("Now you can enter your different waypoints") #we display that we can register our way points
self.index = 0 #we reset our index
while self.index < self.number: we want to it until we got the good number of goals
rospy.Subscriber('/move_base/goal', MoveBaseActionGoal, self.callback) #we subscribe to the goal node,
rospy.spin() #used to let only one instruction pass, this will wait another instruction
def callback(self, msg): #this function will be used each time we create a new nav goal
if self.over == 0: #if we hadn't finish the program
new_move = actionlib.SimpleActionClient("move_base", MoveBaseAction) #"new_move" will be a variable containting an action, here a MoveBaseAction to move the robot
new_move.wait_for_server() #we are waiting the robot server
new_move.cancel_all_goals() #we cancel every goals to avoid a movement of the robot
self.goal = msg #goal (a MoveBaseGoal) become the new goal we entered
self.add_markers(self.goal) #with the goal we add a new markers on this position
if self,index == 0: #if this is the first move we allow it to not be compared
def callback(self,msg): #this function will be used each time we create a new nav goal
if self.over == 0: #if we hadn't finished the program
new_move = actionlib.SimpleActionClient("move_base", MoveBaseAction) #"new_move" will be variable containing an action, here a MoveBaseAction to move the robot
new_move.wait_for_server() #we are waiting the robot server
new_move.cancel_all_goals() #We cancel every goals to avoid a movement of the robot
self.goal = msg #goal (a MoveBaseGoal) become the new goal we entered
self.add_markers(self.goal) #with the goal we add a new markers on this position
if self.index == 0: #if this is the first move we allow it not be compared
self.WaypointsLists = self.WayPointsLists.append(self.goal)
#We add the new goal to the goals list
self.index = self.index +1
#we increment the index
if self.WayPointLists[self.index-1] !=self.goal:
#we compare the new goal to the last one to avoid some useless move
self.WaypointsLists = self.WayPointsLists.append(self.goal)
#We add the new goal to the goals list
self.index = self.index +1
#we increment the index
if self.index >= self.number and not rospy.is_shutdown():
#if the index is equal or greater than the number of goals
rospy.loginfo("Procurement finished") #we entered all the goals
self.over = 1
self.recurrence() #we call the function to reach goals
|
JavaScript | UTF-8 | 682 | 4.21875 | 4 | [] | no_license | //function should return true or false if string is a palindrome
function isPalindrome(str) {
str = str.toLowerCase();
for (var i = 0; i < str.length; i++) {
if (str[i] === "!" || str[i] === "," || str[i] === "?" || str[i] === " ") {
str = str.replace(str[i], "");
i--;
}
};
for (var i = 0; i < Math.floor(str.length / 2); i++) {
if (str[i] !== str[str.length - 1 - i]) {
return false;
}
}
return true;
}
console.log(isPalindrome("Star Rats!")); // true
console.log(isPalindrome("palindrome")); // false
console.log(isPalindrome("I madam, I made radio! So I dared! Am I mad?? Am I?!"));
|
Java | UTF-8 | 836 | 3.484375 | 3 | [] | no_license | package gui.observer;
import java.util.ArrayList;
/**
* Klasa koja sadrzi listu observera koji ce biti
* odrzavani klasom Observable.
*
* @author Vanja Paunovic
*
*/
public class ObserverList {
private ArrayList<MainObserver> observers;
public ObserverList() {
observers = new ArrayList<>();
}
/**
* Salje poruku svim registrovanim observerima.
*
* @param notification
* obavestenje o odlaznim porukama
* @param obj
* pomocni objekat koji se salje sa porukom
*/
public void notifyObservers(NotificationObserver notification, Object obj) {
for (MainObserver obs : observers)
obs.update(notification, obj);
}
/**
* Registruje novi observer.
*
* @param observer
* novi observer koji ce biti dodat
*/
public void addObserver(MainObserver observer) {
observers.add(observer);
}
} |
JavaScript | UTF-8 | 648 | 3.296875 | 3 | [
"MIT"
] | permissive | function solution(a, b) {
var temp = 0;
var result = b
.split('')
.map(val => {
if (val === 'U') {
temp = temp + 1
} else {
temp = temp - 1
}
return temp;
})
.reduce((acc, val, i, arr) => {
acc = (arr[i - 1] && arr[i - 1] < 0 && val === 0) ? (acc + 1) : acc;
console.log(acc, val, arr[i - 1])
return acc;
}, 0);
console.log(b);
return result;
};
var a = 9
var b = 'UDDDUDUU';
console.log('RESULT : ',
solution(a, b)
);
function toArray(str) {
return str.split(' ')
}; |
Java | UTF-8 | 1,998 | 2.875 | 3 | [] | no_license | package com.mdoa.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
public class JSONUtil{
/**
* json字符串转List的
* @param json
* @param clazz
* @return
*/
public static <T> List<T> jsonToList(String jsonString){
Gson gson = new Gson();
List<T> list = gson.fromJson(jsonString, new TypeToken<List<T>>(){}.getType());
return list;
}
public static <T> List<T> jsonToList(String jsonString, Class<T[]> clazz){
Gson gson = new Gson();
T[] array = gson.fromJson(jsonString, clazz);
return Arrays.asList(array);
}
public static List<ExcelModel> jsonToExcelModelList(String jsonString){
//创建Gson对象
Gson gson = new Gson();
//创建JsonParser
JsonParser parser = new JsonParser();
System.out.println(jsonString);
//通过JsonParser可以把json字符串解析成一个JsonElement对象
JsonElement jsonElement = parser.parse(jsonString);
//把JsonElement对象转换成JsonObject
JsonObject jsonObject = null;
if(jsonElement.isJsonObject()){
jsonObject = jsonElement.getAsJsonObject();
}
//把JsonElement转换成JsonArray
JsonArray jsonArray = null;
if(jsonElement.isJsonArray()){
jsonArray = jsonElement.getAsJsonArray();
}
//遍历JsonArray对象
Iterator<JsonElement> iterator = jsonArray.iterator();
List<ExcelModel> excelModels = new ArrayList<>();
while(iterator.hasNext()){
JsonElement element = iterator.next();
//JsonElement转换为ExcelModel对象
ExcelModel excelModel= gson.fromJson(element, ExcelModel.class);
excelModels.add(excelModel);
}
return excelModels;
}
}
|
Python | UTF-8 | 383 | 3.46875 | 3 | [] | no_license | # this program is used to safe open file
def safeopen(path):
try:
f = open(path, 'r')
return f
except IOError:
return None
def printf(f):
for line in f:
print line,
input_file = raw_input("input file name:")
f = safeopen(input_file)
if f is not None:
printf(f)
f.close()
else:
print("file:%s is not exist" % (input_file))
|
C | UTF-8 | 1,084 | 3.671875 | 4 | [] | no_license | /*
** EPITECH PROJECT, 2018
** my_put_nbr.c
** File description:
** my_put_nbr
*/
#include <unistd.h>
#include "../../../include/my.h"
void print_nbr(void)
{
my_putchar('-');
my_putchar('2');
my_putchar('1');
my_putchar('4');
my_putchar('7');
my_putchar('4');
my_putchar('8');
my_putchar('3');
my_putchar('6');
my_putchar('4');
my_putchar('8');
}
int my_put_nbr(int nb)
{
int output = 0;
if (nb == -2147483648) {
print_nbr();
return (nb);
}
if (nb < 0) {
nb = -nb;
my_putchar('-');
output = output + 1;
}
if (nb > 9)
output = output + my_put_nbr(nb / 10);
my_putchar(nb % 10 + 48);
return (output);
}
int my_put_nbru(unsigned int nb)
{
unsigned int output = 0;
if (nb == -2147483648) {
print_nbr();
return (nb);
}
if (nb < 0) {
nb = -nb;
my_putchar('-');
output = output + 1;
}
if (nb > 9)
output = output + my_put_nbru(nb / 10);
my_putchar(nb % 10 + 48);
return (output);
} |
Java | UTF-8 | 1,510 | 2.09375 | 2 | [
"BSD-3-Clause"
] | permissive | package de.wiosense.webauthn.util.database;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;
import java.util.List;
import de.wiosense.webauthn.models.PublicKeyCredentialSource;
@Dao
public abstract class CredentialDao {
@Query("SELECT * FROM credentials")
public abstract List<PublicKeyCredentialSource> getAll();
@Query("SELECT * FROM credentials")
public abstract LiveData<List<PublicKeyCredentialSource>> getAllLive();
@Query("SELECT * FROM credentials WHERE rpId = :rpId")
public abstract List<PublicKeyCredentialSource> getAllByRpId(String rpId);
@Query("SELECT * FROM credentials WHERE id = :id LIMIT 1")
public abstract PublicKeyCredentialSource getById(byte[] id);
@Insert
public abstract void insert(PublicKeyCredentialSource credential);
@Delete
public abstract void delete(PublicKeyCredentialSource credential);
@Update
public abstract void update(PublicKeyCredentialSource credential);
@Query("SELECT keyUseCounter FROM credentials WHERE roomUid = :uid LIMIT 1")
public abstract int getUseCounter(int uid);
@Transaction
public int incrementUseCounter(PublicKeyCredentialSource credential) {
int useCounter = getUseCounter(credential.roomUid);
credential.keyUseCounter++;
update(credential);
return useCounter;
}
}
|
JavaScript | UTF-8 | 600 | 3.609375 | 4 | [] | no_license | function queryAb(str) {
if (!str || str.length < 2) {
return -1;
}
let i = 0;
while(i < str.length - 1) {
let curChar = str[i]
let nextChar = str[i + 1]
if (curChar === 'a') {
if (nextChar === 'b') {
return i;
} else {
i++;
continue;
}
} else {
if (nextChar === 'a') {
i++;
} else {
i += 2;
}
continue;
}
}
return -1;
}
console.log(queryAb("I'm b dog!!!ab"));
|
Java | UTF-8 | 1,405 | 2.078125 | 2 | [] | no_license | package com.sys.controller;
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 com.sys.model.DataGridResult;
import com.sys.model.Player;
import com.sys.model.PlayerBych;
import com.sys.service.PlayerServiceBych;
@Controller
public class PlayerControleerBych {
@Autowired
private PlayerServiceBych playerService;
@RequestMapping(value="getPlayerById")
@ResponseBody
public DataGridResult getPlayerById(String id){
int i=1;
System.out.println("现在执行到controller23123-----------");
//int TeamID=Integer.parseInt(id);
return playerService.getPlayerById(i);
}
@RequestMapping(value="getPlayerByPID")
@ResponseBody
public Player getPlayerByPID(String jplayer_id){
//jplayer_id="19";
System.out.println("现在打印id"+jplayer_id);
int player_id=Integer.parseInt(jplayer_id);
return playerService.getPlayerByPID(player_id);
}
@RequestMapping(value="updatePlayerByPID")
@ResponseBody
public int updatetPlayerByPID(String jplayer_id,String jplayer_first){
//jplayer_id="19";
//jplayer_first="19";
int player_id=Integer.parseInt(jplayer_id);
int player_first=Integer.parseInt(jplayer_first);
return playerService.updatePlayerByPID(player_id, player_first);
}
}
|
Python | UTF-8 | 929 | 2.65625 | 3 | [] | no_license | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtQuick import QQuickView
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle("Qt Combo Demo")
widget= QWidget()
layout = QVBoxLayout()
view = QQuickView()
container = QWidget.createWindowContainer(view, self)
container.setMinimumSize(200, 200)
container.setMaximumSize(200, 200)
view.setSource(QUrl("view.qml"))
label = QLabel("Hello World")
label.setAlignment(Qt.AlignCenter)
layout.addWidget(label)
layout.addWidget(container)
widget.setLayout(layout)
self.setCentralWidget(widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec()) |
C++ | UTF-8 | 1,603 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "renderer.h"
#include "shaders.h"
namespace gui
{
/*************************************************
** Basic Gui Renderer
*************************************************/
GuiRenderer::GuiRenderer(gl::Renderer glRenderer, gl::ShaderCreator shaderCreator, gl::IRenderer::Viewport viewport)
: glRenderer(glRenderer)
{
glRenderer->setViewport(viewport);
gui::ShaderTemplate guiShaderTemplate;
font::ShaderTemplate fontShaderTemplate;
guiShader = shaderCreator->createShader(guiShaderTemplate.guiShader_vert, guiShaderTemplate.guiShader_frag);
textShader = shaderCreator->createShader(fontShaderTemplate.textShader_vert, fontShaderTemplate.textShader_frag);
gml::Mat4d projection = gml::Mat4d::orthographic(0.0, (float)viewport.width, (float)viewport.height, 0.0, 0.1, 100.0);
guiShader->setUniform("projection", projection);
guiShader->setUniform("texture", 0);
textShader->setUniform("projection", projection);
//clearColor = gml::Vec4<float>(1, 1, 1, 1);
}
void GuiRenderer::render()
{
//prepareRenderTarget();
glRenderer->enableBlending();
glRenderer->useShader(guiShader);
glRenderer->bindTexture(guiTexture);
for (unsigned int i = 0; i < widgets.size(); ++i)
{
glRenderer->draw(widgets[i]);
}
glRenderer->useShader(textShader);
for (unsigned int i = 0; i < text.size(); ++i)
{
glRenderer->bindTexture(text[i]->getTexture(), 0);
glRenderer->draw(text[i]->getDrawable());
}
glRenderer->disableBlending();
//renderToScreen();
}
void GuiRenderer::setTexture(gl::Texture2D texture)
{
guiTexture = texture;
}
}
|
Markdown | UTF-8 | 1,110 | 2.609375 | 3 | [] | no_license | Developing-Data-Products-Assignment
===================================
Coursera Course: Developing Data Products
Assignment Submission Files
- [ui.R](https://github.com/proshanta/DevelopingDataProductsAssignment/blob/master/ui.R)
- [server.R](https://github.com/proshanta/DevelopingDataProductsAssignment/blob/master/server.R)
- [README.md](https://github.com/proshanta/DevelopingDataProductsAssignment/blob/master/README.md)
Instructions
1. Clone the code using 'git clone https://github.com/proshanta/DevelopingDataProductsAssignment.git YOURDIRECTORY'
2. Load your RStudio
3. Set your working directory to YOURDIRECTORY using setwd("YOURDIRECTORY")
4. Load the Shiny library using library(shiny)
5. Load the XML library using library(XML)
6. Run the application using runApp()
7. You will see the application in a browser. Follow the instructions to use the application.
Dependencies
1. Shiny library
2. XML library
More Information
The application is deployed on ShinyApps.io at [https://proshanta.shinyapps.io/DataProductAssignment](https://proshanta.shinyapps.io/DataProductAssignment).
|
Python | UTF-8 | 3,598 | 2.828125 | 3 | [] | no_license |
##########################
### Imports
##########################
## Standard Library
import os
## External Libraries
import joblib
import numpy as np
import pandas as pd
from langcodes import Language
## Local
from ..util.logging import initialize_logger
##########################
### Helpers
##########################
## Logging
logger = initialize_logger()
## Language Names
def get_language_name(chars):
"""
"""
name = Language.get(chars).language_name()
return name
##########################
### Class
##########################
class RedditRecommender(object):
"""
"""
def __init__(self,
collaborative_filtering_path,
language_distribution_path=None,
min_support=10):
"""
"""
## Class Attributes
self._cf_path = collaborative_filtering_path
self._min_support = min_support
## Initialize Class
self._initialize_collaborative_filtering(collaborative_filtering_path)
self._initialize_language_distribution(language_distribution_path)
def __repr__(self):
"""
"""
desc = f"RedditRecommender(name={self._cf_path})"
return desc
def _initialize_collaborative_filtering(self,
path):
"""
"""
logger.info("Loading Collaborative Filtering Model")
if not os.path.exists(path):
raise FileNotFoundError("Collaborative Filtering model not found")
self.cf = joblib.load(path)
def _initialize_language_distribution(self,
path):
"""
"""
logger.info("Loading Subreddit Language Details")
if path is None:
self._language_dist = None
return
if not os.path.exists(path):
raise FileNotFoundError("Language Distribution not found")
self._language_dist = pd.read_csv(path, index_col=0)
## Update Columns
self._language_dist.rename(columns=dict((x, get_language_name(x)) for x in self._language_dist.columns),
inplace=True)
## Filtering
self._language_dist = self._language_dist.loc[self._language_dist.sum(axis=1) >= self._min_support].copy()
## Concentration
self._language_conc = self._language_dist.apply(lambda row: row / sum(row), axis=1)
def show_available_languages(self):
"""
"""
languages = self._language_dist.columns.tolist()
return languages
def get_top_concentrations(self,
language,
k_top=20):
"""
"""
top_concentrations = self._language_conc[language].sort_values(ascending=False).head(k_top)
return top_concentrations
def recommend(self,
user_history,
languages=[],
k_top=100,
**kwargs
):
"""
"""
## Get Recommendations Based on Posting History
cf_rec = self.cf.recommend(user_history, k_top=len(self.cf._items), **kwargs)
cf_rec.set_index("item", inplace=True)
## Merge Language Distribution
for language in languages:
cf_rec[language] = self._language_conc[language]
cf_rec = cf_rec.fillna(0)
## Get K Top
cf_rec = cf_rec.head(k_top)
cf_rec = cf_rec.rename(columns = {"score":"Recommendation Score"})
return cf_rec |
Python | UTF-8 | 8,225 | 2.953125 | 3 | [] | no_license | #%%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
data = pd.read_csv('data/tick-levelII/bu1912 (6).csv', header=None)
#%%
plt.plot(data[4])
plt.show()
#%%
#思路:当价格达到一段时间内的最大值或者最小值,且做空、做空方,即卖方或买方前三档的挂单量明显大于对手方
#加减仓数手数,成交价格,开平仓,最新成交价, 总仓位,PNL
vol_all = np.full([data.shape[0], 6], np.nan)
vol_all[:, 2] = 0
vol_all[:, 5] = 0
def judge_price():
pass
def send_order(vol_all, tick, vol_num, price, is_open):
if not is_open:
vol_all[tick:, 5] += (price-vol_all[tick, 3]) * vol_all[tick, 4]
vol_all[tick, 0] = vol_num
vol_all[tick, 1] = price
vol_all[tick:, 2] = is_open
vol_all[tick:, 3] = price
vol_all[tick:, 4] = vol_num
for i in range(data.shape[0]):
if i < 1000:
continue
last_price_array = data.loc[i-1000:i, 4].values
last_sell_vol = data.loc[i-20:i+1, 15:18].values #取前三列
last_buy_vol = data.loc[i-20:i+1, 25:28] .values # 取前三列
is_open = vol_all[i, 2]
his_sell = np.mean(last_sell_vol[:-5, :])
now_sell = np.mean(last_sell_vol[-5:, :])
his_buy = np.mean(last_buy_vol[:-5, :])
now_buy = np.mean(last_buy_vol[-5:, :])
if not is_open:
if (last_price_array[-1] >= np.max(last_price_array[:-1]) and
last_price_array[-1] > np.min(last_price_array[:-1]+20)):
if now_sell > now_buy * 2:
price = data.loc[i + 1, 20] #买一价卖出
send_order(vol_all, i, -1, price, 1)
print(i, '卖开')
if (last_price_array[-1] <= np.min(last_price_array[:-1]) and
last_price_array[-1] < np.max(last_price_array[:-1]-20)):
if now_buy > now_sell * 2:
price = data.loc[i + 1, 10] #卖一价买入
send_order(vol_all, i, 1, price, 1)
print(i, '买开')
else:
open_price = vol_all[i, 3]
vol = vol_all[i, 4]
if vol > 0:#买入持仓
if last_price_array[-1]-open_price >= 10:#止盈
price = data.loc[i + 1, 20] # 买一价卖出
send_order(vol_all, i, -1, price, 0)
print(i, '买开止盈')
if last_price_array[-1]-open_price <= -6:#止损
price = data.loc[i + 1, 20] # 买一价卖出
send_order(vol_all, i, -1, price, 0)
print(i, '买开止损')
elif vol < 0:#卖出持仓
if last_price_array[-1]-open_price <= -10:#止盈
price = data.loc[i + 1, 10] # 卖一价买入
send_order(vol_all, i, 1, price, 0)
print(i, '卖开止盈')
if last_price_array[-1]-open_price >= 6:#止损
price = data.loc[i + 1, 10] # 卖一价买入
send_order(vol_all, i, 1, price, 0)
print(i, '卖开止损')
#%%
plt.figure()
plt.plot(vol_all[:, 5])
plt.show()
#%%
'''
def cc(num):
return num*(num-1)*(num-2)/6
def unique(arr):
all = []
for a in arr:
if a not in all:
all.append(a)
return all
def countTriplets(arr, n, r):
cnt = 0
if r == 1:
item = unique(arr)
print(item)
for i in item:
num = arr.count(i)
cnt += cc(num)
elif r != 1:
for i in range(n):
a = arr[i]
for j in range(i+1,n):
b = arr[j]
if b != a*r:
continue
for k in range(j+1,n):
c = arr[k]
if c != b*r:
continue
else:
print('cnt',a,b,c)
cnt += 1
return cnt
#%%
# !/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'interpolate' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER_ARRAY instances
# 3. FLOAT_ARRAY price
#
def pop_laps(instances, price):
false = []
for i, p in enumerate(price):
if p <= 0:
false.append(i)
for i in range(len(false)):
f = false[len(false) - i - 1]
instances.pop(f)
price.pop(f)
def double_sort(instances, price):
instances2 = instances.copy()
instances.sort()
p = []
for ins in instances:
p.append(price[instances2.index(ins)])
price = p
def judge_index(instances, n):
i = 0
for i, instance in enumerate(instances):
if n < instances[0]:
return 0, -1
if n == instance:
return i, None
elif i < len(instances) - 1 and n > instance and n < instances[i + 1]:
return i, i
return i, None
def inter_cal(a, b, c, d, e):
return (e - a) * (c - d) / (a - b) + c
def reg_format(a):
reg = '%.2f' % round(a, 2)
if reg[-1] == 0:
return reg[:-1]
else:
return reg
def interpolate(n, instances, price):
# Write your code here
pop_laps(instances, price)
double_sort(instances, price)
l = len(instances)
if l == 1:
return reg_format(price[0])
i, j = judge_index(instances, n)
if j is None:
if i < len(instances) - 1:
return reg_format(price[i])
else:
return reg_format(inter_cal(instances[l - 2], instances[l - 1], price[l - 2], price[l - 1], n) + 10e-5)
elif j == -1:
return reg_format(inter_cal(instances[0], instances[1], price[0], price[1], n) + 10e-5)
else:
return reg_format(inter_cal(instances[j], instances[j + 1], price[j], price[j + 1], n) + 10e-5)
n = 2
ins = [10, 25, 50, 100, 500]
pr = [0.0, 0.0, 0.0, 0.0, 54.25]
interpolate(n, ins, pr)
#%%
import copy
def build_matrix(n, n_1, matrix, max_sum):
a = [0] * n
b = list()
c = list()
for i in range(n):
b.append(a)
for i in range(n):
c.append(b)
c[0] = matrix
for item in matrix:
for it in item:
if it > max_sum:
return 0
for k in range(1,n):
tmp = copy.deepcopy(b)
for i in range(k, n):
tmp_1 = copy.deepcopy(a)
for j in range(k, n):
w = c[k-1][i-1][j-1] + sum(c[0][i][j-k:j+1]) + sum([item[j] for item in c[0][i-k:i+1]]) - c[0][i][j]
tmp_1[j] = w
tmp[i] = tmp_1
mark = 1
for item in tmp:
for ite in item:
if ite > max_sum:
mark = 0
if mark == 0:
return k
c[k] = tmp
return n
if __name__ == '__main__':
matrix = [[1,2,3,4,1],
[5,6,7,8,1],
[9,10,11,12,1],
[13,14,15,16,1],
[13,14,15,16,1]]
n = 4
print(build_matrix(n,n,matrix,150))
#%%
import copy
def build_matrix(n, n_1, matrix, max_sum):
a = [0] * n
b = list()
c = list()
for i in range(n):
b.append(a)
for i in range(n):
c.append(b)
c[0] = matrix
for item in matrix:
for it in item:
if it > max_sum:
return 0
for k in range(1,n):
tmp = copy.deepcopy(b)
for i in range(k, n):
tmp_1 = [0] * n
for j in range(k, n):
w = c[k-1][i-1][j-1] + sum(c[0][i][j-k:j+1]) + sum([item[j] for item in c[0][i-k:i+1]]) - c[0][i][j]
if w > max_sum:
return k
tmp_1[j] = w
tmp[i] = tmp_1
c[k] = tmp
return n
def largestSubgrid(grid, maxSum):
# Write your code here
n = len(grid)
m = build_matrix(n, n, grid, maxSum)
return m
'''
|
Java | UTF-8 | 6,311 | 2.8125 | 3 | [] | no_license | package kr.gov.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import kr.gov.dto.Product;
public class ProductRepository {
private ArrayList<Product> listOfProducts = new ArrayList<>();
//ProductRepository 인스턴스를 하나만 공유하게끔 싱글톤 패턴 이용
private static ProductRepository instance = new ProductRepository();
//DB 접속에 필요한 멤버
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
private static String url = "jdbc:mysql://localhost:3306/webstoredb?serverTimezone=UTC";
private static String user = "root";
private static String password = "0217";
//ProductRepository 인스턴스를 리턴하는 getter 메서드
public static ProductRepository getInstance() {
return instance;
}
public ProductRepository() {
//DB 연동전 임시데이터로 활용
// Product phone = new Product("P1234", "iPhone 12 Pro Max", 1490000);
// phone.setDescription("6.7-inch, 2778*1284-pixel, OLED Super Retina XDR display, cameras");
// phone.setCategory("Smart Phone");
// phone.setManufacturer("Apple");
// phone.setUnitPrice(1490000);
// phone.setCondition("New");
// phone.setNumberOfStock(7000);
// phone.setFilename("iphone-12-pro-max-gold-hero.jpg");
//
// Product notebook = new Product("P1235", "LG 울트라 기어", 1930000);
// notebook.setDescription("15-inch, 1920*1080-pixel, IPS LED display, 10세대 인텔 코어 i7-10510U 프로세서");
// notebook.setCategory("Notebook");
// notebook.setManufacturer("LG");
// notebook.setUnitPrice(1930000);
// notebook.setCondition("Refurblished");
// notebook.setNumberOfStock(5000);
// notebook.setFilename("usp_0103.jpg");;
//
// Product tablet = new Product("P1236", "갤럭시 탭 S7+", 1149500);
// tablet.setDescription("12-inch, 2800*1752-pixel, Super AMOLED display, Octa-Core 프로세서");
// tablet.setCategory("Tablet");
// tablet.setManufacturer("Samsung");
// tablet.setUnitPrice(1149500);
// tablet.setCondition("Old");
// tablet.setNumberOfStock(3000);
// tablet.setFilename("b008b623-6fe8-4191-82bd-d988db87e6e6.jpg");
//
// listOfProducts.add(phone);
// listOfProducts.add(notebook);
// listOfProducts.add(tablet);
}
//모든 상품 정보를 넘겨주는 getter 메서드
public ArrayList<Product> getAllProducts() {
String sql = "select * from product";
try {
conn = getConnection(); //커넥션 얻기
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(); //DB에 저장되어 있는 상품 모두 가져와 ResultSet에 담음.
while(rs.next()) {
Product product = new Product(); //빈 객체인 product에 각각 db에서 가져온 값을 저장
product.setProductId(rs.getString("productId"));
product.setPname(rs.getString("pname"));
product.setUnitPrice(rs.getInt("unitPrice"));
product.setDescription(rs.getString("description"));
product.setManufacturer(rs.getString("manufacturer"));
product.setCategory(rs.getString("category"));
product.setNumberOfStock(rs.getLong("numberOfStock"));
product.setCondition(rs.getString("conditions"));
product.setFilename(rs.getString("filename"));
listOfProducts.add(product); //ArrayLsit 컬렉션에 product 객체 추가
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
System.out.println("DB 연동 해제");
} catch (Exception e2) {
e2.printStackTrace();
}
}
return listOfProducts; // 각 객체가 저장되어 ArrayList 리턴함.
}
//DB 접속(Connection 객체 리턴하는 메서드)
public Connection getConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver"); //드라이버명
conn = DriverManager.getConnection(url, user, password); //DB연결 객체 얻음
System.out.println("DB 연동 완료");
} catch (Exception e) {
System.out.println("DB 연동 실패");
e.printStackTrace();
}
return conn;
}
//listOfProducts에 저장된 모든 상품 목록을 조회해서 상품아이디와 일치하는 상품을 리턴하는 메서드
public Product getProductById(String productId) {
Product productById = new Product();
String sql = "select * from product where productId = ?";
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, productId);
rs = pstmt.executeQuery(); //인자값으로 넘어온 productId 값에 해당하는 상품을 ResultSet객체에 하나만 저장됨.
if(!rs.next()) {
return null; //일치하는 상품없는 상태임
}
//인자값으로 넘어온 productId값이 있다면
if(rs.next()) {
productById.setProductId(rs.getString("productId"));
productById.setPname(rs.getString("pname"));
productById.setUnitPrice(rs.getInt("unitPrice"));
productById.setDescription(rs.getString("description"));
productById.setManufacturer(rs.getString("manufacturer"));
productById.setCategory(rs.getString("category"));
productById.setNumberOfStock(rs.getLong("numberOfStock"));
productById.setCondition(rs.getString("conditions"));
productById.setFilename(rs.getString("filename"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
System.out.println("DB 연동 해제");
} catch (Exception e2) {
e2.printStackTrace();
}
}
// for(int i = 0; i < listOfProducts.size(); i++) {
// Product product = listOfProducts.get(i);
//
// if(productId != null && product.getProductId() != null &&
// product.getProductId().equals(productId)) {
// productById = product;
// break;
// }
//
// }
return productById;
}
//상품을 추가하는 메서드
public void addProduct(Product product) {
listOfProducts.add(product);
}
}
|
Markdown | UTF-8 | 2,650 | 2.859375 | 3 | [] | no_license | # insertPluginFunctionNameHere Noteplan Plugin
[You will delete this text and replace it with a readme about your plugin -- not ever seen by users, but good for people looking at your code. Before you delete though, you should know:]
You do not need all of this scaffolding for a basic NP plugin. As the instructions state [Creating Plugins](https://help.noteplan.co/article/65-commandbar-plugins), you can create a plugin with just two files: `plugin.json` and `script.js`. Please read that whole page before proceeding here.
However, for more complex plugins, you may find that it's easier to write code in multiple files, incorporating code (helper functions, etc.) written (and *TESTED*) previously by others. You also may want type checking (e.g. [Flow.io](https://flow.io)) to help validate the code you write. If either of those is interesting to you, you're in the right place. Before going any further, make sure you follow the development environment [setup instructions](https://github.com/NotePlan/plugins).
Clone/download the entire plugins repository from github.
Then create a copy of this skeleton folder. Give your skeleton folder copy a name (e.g. your githubUsername.pluginOrCollectionOfCommandsName). Some examples that exist today:
- jgclark.NoteHelpers
- dwertheimer.DateAutomations
Do a global find/replace in your folder for `insertPluginFunctionNameHere` for the function name of your plugin's JS entry point (it will be listed in the plugin.json). And change the filename `insertPluginFunctionNameHere.js` to match.
Open up a terminal folder and change directory to the plugins repository root. Run the command `npm run autowatch` which will keep looking for changes to plugin files and will re-compile when Javascript changes are made. It will also transpile ES6 and ES7 code down to ES5 which will run on virtually all Macs, and will copy the file to your plugins folder, so you can immediately test in Noteplan.
Keep in mind that you can code/test without updating the plugin version # in plugin.json, but when you push the code to the repository (or create a PR), you should update the version number so that other peoples' Noteplan apps will know that there's a newer version.
Further to that point, you can use your plugin locally, or you can use `git` to create a Pull Request to get it included in the Noteplan/plugins repository and potentially available for all users through the Preferences > Plugins tab.
That's it. Happy coding!
Hat-tip to @eduard, @nmn & @jgclark, who made all this fancy cool stuff.
Best,
@dwertheimer
## Configuration
Notes about how to configure your plugin (if required)
|
Java | UTF-8 | 1,685 | 3.109375 | 3 | [] | no_license | import java.io.*;
import java.util.*;
public class J {
public static Map<Character, Integer> v;
public static Map<Integer, Character> vInv;
public static void main(String [] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
initV();
int n = Integer.parseInt(f.readLine());
for (int i = 0; i < n; i++) {
String s = f.readLine();
StringTokenizer st = new StringTokenizer(s);
if (st.nextToken().equals("e")) {
System.out.println(encrypt(s.substring(2)));
}
else {
System.out.println(decrypt(s.substring(2)));
}
}
}
public static String encrypt(String s) {
StringBuilder t = new StringBuilder();
int[] vals = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
vals[i] = v.get(s.charAt(i));
if (i > 0)
vals[i] += vals[i-1];
vals[i] %= 27;
t.append(vInv.get(vals[i]));
}
return t.toString();
}
public static String decrypt(String s) {
StringBuilder t = new StringBuilder();
int[] vals = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
vals[i] = v.get(s.charAt(i));
if (i > 0) {
int x = (vals[i] - vals[i-1] + 27) % 27;
t.append(vInv.get(x));
}
else {
t.append(vInv.get(vals[i]));
}
}
return t.toString();
}
public static void initV() {
v = new HashMap<>();
vInv = new HashMap<>();
v.put(' ', 0);
vInv.put(0, ' ');
for (int i = (int)'a'; i <= (int)'z'; i++) {
v.put((char)i, i - 'a' + 1);
vInv.put(i - 'a' + 1, (char)i);
}
// System.out.println(v.keySet());
}
} |
Python | UTF-8 | 737 | 4.25 | 4 | [] | no_license | class Animal():
def walk(self):
print("걷는다")
def eat(self):
print("먹는다")
class Human(Animal):
def wave(self):
print("손을 흔든다")
class Dog(Animal):
def wave(self):
print("꼬리를 흔든다")
person = Human()
person.walk()
person.eat()
person.wave()
dog = Dog()
dog.walk()
dog.eat()
dog.wave()
# 실습
class Car():
def run(self):
print("차가 달립니다.")
# 아래에서 Car를 상속받는 Truck이라는 클래스를 만들고, load라는 메소드를 만들어 보세요.
class Truck(Car):
def load(self):
print("짐을 실었습니다.")
# load메소드에서는 "짐을 실었습니다."라고 출력하면 됩니다.
|
Ruby | UTF-8 | 304 | 2.53125 | 3 | [] | no_license | require "character_count"
describe "#character_count" do
specify do
expect(character_count(["a", "bc", "def"])).to eq(6)
end
it "calls itself" do
expect(self).to receive(:character_count)
.at_least(:twice)
.and_call_original
character_count(["a", "bc", "def"])
end
end
|
Java | UTF-8 | 4,367 | 2.171875 | 2 | [] | no_license | package steps.Qapter;
import cases.TestBase;
import com.aventstack.extentreports.Status;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import pageobjects.processstep.DamageCapturingPO;
import steps.DamageCapturing;
import java.util.List;
import java.util.Map;
import static utils.webdrivers.WebDriverFactory.getDriver;
public class RepairPanel extends TestBase {
private DamageCapturingPO damageCapturingPO;
private WebDriverWait wait;
private ZoneAndLayout zoneAndLayout;
public RepairPanel() {
damageCapturingPO = (DamageCapturingPO)context.getBean("DamageCapturingPO");
damageCapturingPO.setWebDriver(getDriver());
wait = new WebDriverWait(getDriver(), 10);
zoneAndLayout = new ZoneAndLayout();
}
public void selectPosition(String zone, String position, String positionName) {
zoneAndLayout.openZone(zone);
zoneAndLayout.clickPosition(position, true);
Assert.assertEquals(damageCapturingPO.getRPPartDescription(), positionName);
testCase.get().log(Status.PASS, "Repair panel of " + positionName + " is opened");
}
public void openRepairPanel(String zone1, String position1, String positionName1, String position2){
selectPosition(zone1, position1, positionName1);
DamageCapturing damageCapturing = new DamageCapturing();
if(isMobileDevice())
damageCapturing.useCameraPermission();
testCase.get().log(Status.PASS, "Repair panel is opened with the right position");
zoneAndLayout.clickPosition(position2, true);
damageCapturingPO.waitForQapterLoading();
}
public void closeRepiarPanel(String zone, String position){
zoneAndLayout.openZone(zone);
zoneAndLayout.clickPosition(position, true);
DamageCapturing damageCapturing = new DamageCapturing();
if(isMobileDevice())
damageCapturing.useCameraPermission();
damageCapturingPO.clickOutOfRepairPanel();
}
public void uploadPhotoFromRepairPanel(String zone, String position, String positionName, String filePath, boolean repairNeeded) {
damageCapturingPO.navigationVehicle();
selectPosition(zone, position, positionName);
if (repairNeeded) {
//Replace part
damageCapturingPO.clickRPReplaceWithOEMPart();
testCase.get().log(Status.INFO, "Replace a part");
}
damageCapturingPO.uploadPhotosOnRepairPanel(filePath);
testCase.get().log(Status.PASS, "Photo is uploaded from repair panel");
}
public void verifyPartCompositionData(String zone, String position, String positionName, String currency, Boolean withExtraPart) {
damageCapturingPO.navigationVehicle();
selectPosition(zone, position, positionName);
damageCapturingPO.clickRPReplaceWithOEMPart();
testCase.get().log(Status.INFO, "Replace a part");
damageCapturingPO.clickReplaceMutations();
testCase.get().log(Status.PASS, "Open replace mutation option successfully");
damageCapturingPO.clickPartsComposition();
testCase.get().log(Status.PASS, "Switch to parts composition view successfully");
Assert.assertEquals(damageCapturingPO.getMainPartName(), positionName);
testCase.get().log(Status.PASS, "Main part " + positionName + " is displayed");
if (withExtraPart) {
Assert.assertTrue(damageCapturingPO.isExtraPartDisplayed());
testCase.get().log(Status.PASS, "Extra Part is displayed");
Assert.assertTrue(damageCapturingPO.isAllExtraPartSelected());
testCase.get().log(Status.PASS, "All extra parts are selected");
}
Assert.assertTrue(isWorkCompositionWithWuAndPrice(currency));
testCase.get().log(Status.PASS, "All parts under work composition have WU and price value");
}
private boolean isWorkCompositionWithWuAndPrice(String currency) {
Map<String, List> workCompositionData = damageCapturingPO.getWorkCompositionData();
for (Map.Entry<String, List> entry : workCompositionData.entrySet()) {
if (!(entry.getValue().get(0).toString().matches("\\d+") && entry.getValue().get(1).toString().matches(currency + "\\d+.\\d+"))) {
return false;
}
}
return true;
}
}
|
Java | UTF-8 | 6,399 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package com.diguits.domainmodeldesigner.template.models;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
public class TemplateDefModel extends TemplateProjectItemDefModel {
public TemplateDefModel() {
super();
// For the time being it is just needed two apply class name
applyClassNameProperty().addListener((v, o, n) -> {
if(n==null || n.isEmpty())
getClassNamesToApplyOver().clear();
else if (getClassNamesToApplyOver().size() < 1)
getClassNamesToApplyOver().add(getApplyClassName());
else if (!getClassNamesToApplyOver().get(0).equals(getApplyClassName()))
getClassNamesToApplyOver().set(0, getApplyClassName());
});
applyClassName1Property().addListener((v, o, n) -> {
if((n==null || n.isEmpty()) && getClassNamesToApplyOver().size() > 1)
getClassNamesToApplyOver().remove(1);
else if (getClassNamesToApplyOver().size() < 1)
getClassNamesToApplyOver().add(getApplyClassName());
if (getClassNamesToApplyOver().size() < 2)
getClassNamesToApplyOver().add(getApplyClassName1());
else if (!getClassNamesToApplyOver().get(1).equals(getApplyClassName1()))
getClassNamesToApplyOver().set(1, getApplyClassName1());
});
getClassNamesToApplyOver().addListener(new ListChangeListener<String>() {
@Override
public void onChanged(javafx.collections.ListChangeListener.Change<? extends String> c) {
if (c.next()) {
if (c.getAddedSize() > 0 || c.getRemovedSize() > 0) {
if (getClassNamesToApplyOver().size() > 0)
setApplyClassName(getClassNamesToApplyOver().get(0));
if (getClassNamesToApplyOver().size() > 1)
setApplyClassName1(getClassNamesToApplyOver().get(1));
}
}
}
});
}
private StringProperty outputFileNameExpression;
private ListProperty<String> classNamesToApplyOver;
private StringProperty path;
private StringProperty source;
private StringProperty applyClassName;
private StringProperty applyClassName1;
private ListProperty<TemplateParameterDefModel> parameters;
public String getPath() {
if (path != null)
return path.get();
return "";
}
public void setPath(String path) {
if (this.path != null || path == null || !path.equals("")) {
pathProperty().set(path);
}
}
public StringProperty pathProperty() {
if (path == null) {
path = new SimpleStringProperty(this, "path", "");
}
return path;
}
public String getOutputFileNameExpression() {
if (outputFileNameExpression != null)
return outputFileNameExpression.get();
return "";
}
public void setOutputFileNameExpression(String outputFileNameExpression) {
if (this.outputFileNameExpression != null || outputFileNameExpression == null
|| !outputFileNameExpression.equals("")) {
outputFileNameExpressionProperty().set(outputFileNameExpression);
}
}
public StringProperty outputFileNameExpressionProperty() {
if (outputFileNameExpression == null) {
outputFileNameExpression = new SimpleStringProperty(this, "outputFileNameExpression", "");
}
return outputFileNameExpression;
}
public ObservableList<String> getClassNamesToApplyOver() {
return classNamesToApplyOverProperty().get();
}
public void setClassNamesToApplyOver(ObservableList<String> classNamesToApplyOver) {
if (this.classNamesToApplyOver != null || classNamesToApplyOver != null) {
classNamesToApplyOverProperty().set(classNamesToApplyOver);
}
}
public ListProperty<String> classNamesToApplyOverProperty() {
if (classNamesToApplyOver == null) {
classNamesToApplyOver = new SimpleListProperty<String>(this, "classNamesToApplyOver", null);
classNamesToApplyOver.set(FXCollections.observableArrayList());
}
return classNamesToApplyOver;
}
public String getSource() {
if (source != null)
return source.get();
return "";
}
public void setSource(String source) {
if (this.source != null || source == null || !source.equals("")) {
sourceProperty().set(source);
}
}
public StringProperty sourceProperty() {
if (source == null) {
source = new SimpleStringProperty(this, "source", "");
}
return source;
}
public String getApplyClassName() {
if (applyClassName != null)
return applyClassName.get();
return "";
}
public void setApplyClassName(String applyClassName) {
if (this.applyClassName != null || applyClassName == null || !applyClassName.equals("")) {
applyClassNameProperty().set(applyClassName);
}
}
public StringProperty applyClassNameProperty() {
if (applyClassName == null) {
applyClassName = new SimpleStringProperty(this, "applyClassName", "");
}
return applyClassName;
}
public String getApplyClassName1() {
if (applyClassName1 != null)
return applyClassName1.get();
return "";
}
public void setApplyClassName1(String applyClassName1) {
if (this.applyClassName1 != null || applyClassName1 == null || !applyClassName1.equals("")) {
applyClassName1Property().set(applyClassName1);
}
}
public StringProperty applyClassName1Property() {
if (applyClassName1 == null) {
applyClassName1 = new SimpleStringProperty(this, "applyClassName1", "");
}
return applyClassName1;
}
public ObservableList<TemplateParameterDefModel> getParameters() {
return parametersProperty().get();
}
public void setParameters(ObservableList<TemplateParameterDefModel> templateParameters) {
if (this.parameters != null || templateParameters != null) {
parametersProperty().set(templateParameters);
}
}
public TemplateGroupDefModel getGroupOwner() {
if (owner != null)
return (TemplateGroupDefModel) owner.get();
return null;
}
public void setGroupOwner(TemplateGroupDefModel owner) {
if (this.owner != null || owner != null) {
ownerProperty().set(owner);
}
}
public TemplateProjectDefModel getProject() {
if (getGroupOwner() != null)
return getGroupOwner().getProjectOwner();
return null;
}
public ListProperty<TemplateParameterDefModel> parametersProperty() {
if (parameters == null) {
parameters = new SimpleListProperty<TemplateParameterDefModel>(this, "templateParameters", null);
parameters.set(FXCollections.observableArrayList());
}
return parameters;
}
}
|
Python | UTF-8 | 1,189 | 2.90625 | 3 | [] | no_license | import websockets
import asyncio
import json
class Connection:
def __init__(self):
self.url = "ws://127.0.0.1:7890"
self.player = {}
self.connect()
def getPlayer(self):
return self.player
def connect(self):
async def listen(self):
async with websockets.connect(self.url) as ws:
while True:
# this will receive any incoming message
msg = await ws.recv()
print(msg)
# this will send something
await ws.send("response")
# make the connection
asyncio.get_event_loop().run_until_complete(self.listen())
# this is returning the Player Instance
self.player = json.loads("this will need to be the player instance")
def send(self, data):
try:
# send current player location to server
self.client.send(json.dumps("this will need to be player instance"))
# return the other players location to client
return json.loads("this will need to be opponent instance")
except socket.error as e:
print(e)
|
Markdown | UTF-8 | 791 | 2.953125 | 3 | [] | no_license | # 파라미터를 받는 방법들
## 파라미터로 전달
```java
@GetMapping(value= "vie")
public String vie(int no) {
// no 로 바로 접근
...
}
```
- @RequestParam을 사용하면 해당 파라미터 값이 없을때 해당 로직을 실행하지 않고 400err를 발생시킨다.
```java
@GetMapping(value= "vie")
public String vie(@RequestParam(value="cha_no") int no) {
// no 로 바로 접근
...
}
```
## httpServletRequest.getParameter()
```java
@GetMapping(value= "vie")
public String vie(HttpServletRequest request) {
String cha_no = request.getParameter("no"); //string으로 받을 수 있기 때문에 경우에 따라 형변환이 필요하다.
...
}
```
|
C++ | UTF-8 | 1,084 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_CONNECTION_COLLECTION_H_
#define SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_CONNECTION_COLLECTION_H_
#include <cstdint>
#include <map>
#include <string>
namespace flutter {
/// Maintains a current integer assigned to a name (connections).
class ConnectionCollection {
public:
typedef int64_t Connection;
static const Connection kInvalidConnection = 0;
Connection AquireConnection(const std::string& name);
///\returns the name of the channel when cleanup is successful, otherwise
/// the empty string.
std::string CleanupConnection(Connection connection);
static bool IsValidConnection(Connection connection);
static Connection MakeErrorConnection(int errCode);
private:
std::map<std::string, Connection> connections_;
Connection counter_ = 0;
};
} // namespace flutter
#endif // SHELL_PLATFORM_IOS_FRAMEWORK_SOURCE_CONNECTION_COLLECTION_H_
|
JavaScript | UTF-8 | 3,701 | 2.6875 | 3 | [] | no_license | import React, {useState, useEffect} from "react";
import Trailer from "./page2/Trailer";
import informationIcon from "../../assets/informationIcon.gif"
function Header({apiKey, apiUrl, totalPagesCount, moviesDataLength, poster_prefixURL, setSuffix, setmovieCateogry, broken_path, setMovie, movie, toggleHeaderInfo, setToggleHeaderInfo, togglePage2, setTogglePage2}){
// const [movie, setMovie]= useState([])
const [movieID, setMovieID] = useState("tv/popular")
const [genresList, setGenresList] = useState([])
const randomMovieIndex = Math.floor(Math.random() * moviesDataLength)
const headerPageNumber =`&page=${Math.floor(Math.random() * totalPagesCount)}`
const alternatingLink = typeof movieID === "string"?
`${apiUrl}${movieID}?api_key=${apiKey}${headerPageNumber}`:`${apiUrl}tv/${movieID}?api_key=${apiKey}`
const genreLI = genresList.map(listItem =>
<li key={listItem.name}
className="headerGenresLI"
onClick={()=> {
setSuffix(`&with_genres=${listItem.id}`)
setmovieCateogry("Genres")
setTogglePage2(false)
}
}>
{listItem.name}
</li>)
useEffect(()=>{
fetch(alternatingLink)
.then(res => res.json())
.then(randomMovieArray => handlePageLoad(randomMovieArray))
// eslint-disable-next-line react-hooks/exhaustive-deps
},[movieID])
function handlePageLoad(randomMovieArray ){
// console.log(randomMovieArray.results)
if((movieID === "popular" || movieID ==="tv/popular") && randomMovieArray.results !== undefined){
setMovie(randomMovieArray.results[randomMovieIndex])
setMovieID(randomMovieArray.results[randomMovieIndex].id)
}else if (typeof movieID === "number" ){
setMovie(randomMovieArray)
setGenresList([...randomMovieArray.genres])
}
}
return(
<>
<div className="headerBannerContainer">
<img className={toggleHeaderInfo? "headerDisplayInfoSmall" : "headerDisplayInfoBig"} src={informationIcon} alt="headerDisplayInfoIcon" onClick={()=> setToggleHeaderInfo(toggleHeaderInfo => !toggleHeaderInfo)}/>
<img className="headerBannerBackground" src={movie.backdrop_path === null ? broken_path :`https://www.themoviedb.org/t/p/w640_and_h360_multi_faces/${movie.backdrop_path}`} alt={movie.name}></img>
</div>
<div className={toggleHeaderInfo? "headerImageContainer" : "hidden"}>
<div id="movie-details">
<h1>{movie.name}
<span style={{fontSize:"22px"}}> ({(movie.length !== 0 && movie !== null && movie !== undefined) ? movie.first_air_date.slice(0,4) : null }) </span>
</h1>
<em>{movie.vote_average}/10⭐</em>
<p>{movie.overview}</p>
<div>Genres: <span><ul className="headerGenresUL">{genreLI}</ul></span></div>
</div>
<img id="headerImage" src={movie.backdrop_path === null ? broken_path : `${poster_prefixURL}${movie.poster_path}`} alt={movie.name}></img>
</div>
<Trailer movie={movie} togglePage2={togglePage2}/>
</>
)
}
export default Header
//const realseYear = movie.first_air_date.slice(0,4)
//const link = `${apiUrl}${movieID}?api_key=${apiKey}${typeof movieID !== 'number'?headerPageNumber : "" }}`
// fetch(`${apiUrl}${movieID}?api_key=${apiKey}${typeof movieID !== 'number'? headerPageNumber : "" }}`) |
PHP | UTF-8 | 3,846 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Match;
use App\Team;
use App\Standing;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class MatchController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$matches = Match::all();
$teams = Team::all();
$matches_without_results = Match::where('host_team_result', '=', NULL)
->where('guest_team_result','=', NULL)->get();
return view('index')
->with(['matches'=> $matches])
->with(['teams' => $teams])
->with(['matches_without_results' => $matches_without_results]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
private function validate_match_request(Request $request){
if ($request->host_team == $request->guest_team)
{
return '0';
}else {
return '1';
}
}
public function store(Request $request)
{
$validate = $this->validate_match_request($request);
if ($validate == '1')
{
$match = new Match();
$match->host_team_id = $request->host_team;
$match->guest_team_id = $request->guest_team;
$match->match_date = $request->date;
$match->save();
return response()->json(['success' => 'Match saved']);
} else {
return response()->json(['error' => 'Mistake']);
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$match = Match::where('id', $request->match_id)->first();
$match->host_team_result = $request->host_goals;
$match->guest_team_result = $request->guest_goals;
// //update host team standings
$host_team_standings = Standing::where('team_id', $match->host_team_id)->first();
$host_team_standings->gp += 1;
//
// //update guest team standings
$guest_team_standings = Standing::where('team_id', $match->guest_team_id)->first();
$guest_team_standings->gp += 1;
// //update win results
if ($request->host_goals > $request->guest_goals) {
$host_team_standings->w += 1;
$host_team_standings->pts += 3;
$guest_team_standings->l += 1;
$guest_team_standings->pts += 1;
} else if ($request->host_goals < $request->guest_goals)
{
$host_team_standings->l += 1;
$host_team_standings->pts += 1;
$guest_team_standings->w += 1;
$guest_team_standings->pts += 3;
} else if ($request->host_goals == $request->guest_goals)
{
$host_team_standings->d += 1;
$guest_team_standings->d += 1;
}
$host_team_standings->save();
$guest_team_standings->save();
$match->save();
return response()->json(['success'=> "Results updated"]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
|
Markdown | UTF-8 | 12,273 | 3.34375 | 3 | [] | no_license | # **SQL**
## **Reporting**
Some ways to handle data:
- Ordering (e.g. sort products alphabetically or by price, movies by year, articles by date, sorting contacts)
- Limiting (e.g. retrieve lastest articles, paging through archive)
- Manipulating Text (e.g. standarizing output: lowercase emails, uppercase last names)
- Aggregation (e.g. count values, sum values, maximum number, minimum number)
- Date (e.g. search using today's date, date calculations)
## **Ordering**
Ordering by a single column criteria:
SELECT * FROM <table name> ORDER BY <column> [ASC|DESC];
ASC is used to order results in ascending order. DESC is used to order results in descending order.
Examples:
SELECT * FROM books ORDER BY title ASC;
SELECT * FROM products WHERE name = "Sonic T-Shirt" ORDER BY stock_count DESC;
SELECT * FROM users ORDER BY signed_up_on DESC;
SELECT * FROM countries ORDER BY population DESC;
Ordering by multiple column criteria:
SELECT * FROM <table name> ORDER BY <column> [ASC|DESC],
<column 2> [ASC|DESC],
...,
<column n> [ASC|DESC];
SELECT * FROM customs ORDER BY first_name ASC, last_name ASC
Ordering is prioritized left to right.
Examples:
SELECT * FROM books ORDER BY genre ASC,
title ASC;
SELECT * FROM books ORDER BY genre ASC,
year_published DESC;
SELECT * FROM users ORDER BY last_name ASC,
first_name ASC;
## **Limiting**
Databases can store massive amounts of data, and often you don't want to bring back all of the results. It's slow and it affects the performance for other users. In most cases you only want a certain subset of the rows.
SQLite, PostgreSQL and MySQL: To limit the number of results returned, use the LIMIT keyword.
SELECT <columns> FROM <table> LIMIT <# of rows>;
MS SQL: To limit the number of results returned, use the TOP keyword.
SELECT TOP <# of rows> <columns> FROM <table>;
Oracle: To limit the number of results returned, use the ROWNUM keyword in a WHERE clause.
SELECT <columns> FROM <table> WHERE ROWNUM <= <# of rows>;
Limiting just by the top set of results is a fine thing, but let's say you wanted to generate a multi page report. Having a blog archive or listing search results in batches of 50 is where you want paging.
SQLite, PostgreSQL and MySQL: To page through results you can either use the OFFSET keyword in conjunction with the LIMIT keyword or just with LIMIT alone.
SELECT <columns> FROM <table> LIMIT <# of rows> OFFSET <skipped rows>;
SELECT <columns> FROM <table> LIMIT <skipped rows>, <# of rows>;
MS SQL and Oracle: To page through results you can either use the OFFSET keyword in conjunction with the FETCH keyword. Cannot be used with TOP.
SELECT <columns> FROM <table> OFFSET <skipped rows> ROWS FETCH NEXT <# of rows> ROWS ONLY;
SELECT * FROM phone_book ORDER BY last_name ASC, first_name ASC LIMIT 20 OFFSET 60;
Example #1:
- Obtain the actor records between the 701st and 720th records using only LIMIT and OFFSET
- N.B Due to actors being removed from the database the 701st row has the id of 702
SELECT * FROM actors ORDER BY id LIMIT 20 OFFSET 699;
Example #2:
- Obtain the actor records between the 701st and 720th records using only LIMIT and OFFSET
- N.B Due to actors being removed from the database the 701st row has the id of 702
SELECT * FROM actors ORDER BY id LIMIT 20 OFFSET 699;
Example #3:
- Sort all reviews by username
SELECT * FROM reviews ORDER BY username ASC;
Example #4:
- Order movies with the most recent movies appearing at the top
SELECT * FROM movies ORDER BY year_released DESC;
## **Functions**
Keywords: Commands issued to a database. The data presented in queries is unaltered.
Operators: Performs comparisons and simple manipulation
Functions: Presents data differently through more complex manipulation
A function looks like:
<function name>(<value or column>)
Example:
UPPER("Andrew Chalkley")
## **Adding Text Columns Together**
SQLite, PostgreSQL and Oracle
Use the concatenation operator ||.
SELECT <value or column> || <value or column> || <value or column> FROM <table>;
MS SQL
Use the concatenation operator +.
SELECT <value or column> + <value or column> + <value or column> FROM <table>;
MySQL, Postgres and MS SQL
Use the CONCAT() function.
SELECT CONCAT(<value or column>, <value or column>, <value or column>) FROM <table>;
Example with space:
SELECT first_name || " " || last_name AS "Full Name", email AS "Email", phone AS "Phone" FROM customers ORDER BY last_name
NOTE: In SQL there's a difference between using single quotes (') and double quotes ("). Single quotes should be used for String literals (e.g. 'lbs'), and double quotes should be used for identifiers like column aliases (e.g. "Max Weight"):
SELECT maximum_weight || 'lbs' AS "Max Weight" FROM ELEVATOR_DATA;
## **Finding the Length of Text**
To obtain the length of a value or column use the LENGTH() function.
SELECT LENGTH(<value or column>) FROM <tables>;
SELECT LENGTH(<column>) AS <alias> FROM <table>;
SELECT <columns> FROM <table> WHERE LENGTH(<column>) <operator> <value>;
Example:
SELECT username, LENGTH(username) AS length FROM customers;
SELECT username, LENGTH(username) AS length FROM customers ORDER BY length DESC LIMIT 1;
## **Changing the Case of Text Columns
Use the UPPER() function to uppercase text.
SELECT UPPER(<value or column>) FROM <table>;
Use the LOWER() function to lowercase text.
SELECT LOWER(<value or column>) FROM <table>;
Example:
SELECT LOWER(title) AS lower_case_title, UPPER(author) AS upper_case_author FROM books;
## **Creating Excerpts From Text**
To create smaller strings from larger piece of text you can use the SUBSTR() funciton or the substring function.
SELECT SUBSTR(<value or column>, <start>, <length>) FROM <table>;
Example:
SELECT name, SUBSTR(description, 1 50) || "..." AS short_description, price FROM products;
## **Replacing Portions of Text**
To replace piece of strings of text in a larger body of text you can use the REPLACE() function.
SELECT REPLACE(<original value or column>, <target string>, <replacement string>) FROM <table>;
SELECT street, city, FROM addresses WHERE REPLACE(state, "California", "CA") = "CA";
SELECT street, city, REPLACE(state, "California", "CA") zip FROM addresses WHERE REPLACE(state, "California", "CA") = "CA";
## **Counting Results**
To count rows you can use the COUNT() function.
SELECT COUNT(*) FROM <table>;
To count unique entries use the DISTINCT keyword too:
SELECT COUNT(DISTINCT <column>) FROM <table>;
Example:
SELECT COUNT(*) FROM customers ORDER BY id DESC LIMIT 1;
SELECT COUNT(*) FROM customers WHERE first_name = "Andrew";
SELECT COUNT(DISTINCT category) FROM products;
SELECT COUNT(*) AS scifi_book_count FROM books WHERE genre = "Science Fiction";
## **Counting Groups of Rows**
Basic SQL syntax:
SELECT <column> FROM <table> GROUP BY <column>;
To count aggregated rows with common values use the GROUP BY keywords:
SELECT COUNT(<column>) FROM <table> GROUP BY <column
Examples:
SELECT genre, count(*) as genre_count FROM books GROUP BY genre;
## **Grand Total**
Basic SQL syntax:
SELECT SUM(<column>) FROM <table> GROUP BY <another column>;
SELECT SUM(<numeric column) FROM <table>;
SELECT SUM(<numeric column) AS <alias> FROM <table>
GROUP BY <another column>
HAVING <alias> <operator> <value>;
Examples:
SELECT SUM(cost) AS total_spend, user_id FROM orders GROUP BY user_id ORDER BY total_spend DESC LIMIT 1;
## **Averages**
To get the average value of a numeric column use the AVG() function.
SELECT AVG(<numeric column>) FROM <table>;
SELECT AVG(<numeric column>) FROM <table> GROUP BY <other column>;
Examples:
SELECT AVG(rating) AS average_rating FROM reviews WHERE movie_id = "6";
## **Min / Max**
To get the maximum value of a numeric column use the MAX() function.
SELECT MAX(<numeric column>) FROM <table>;
SELECT MAX(<numeric column>) FROM <table> GROUP BY <other column>;
To get the minimum value of a numeric column use the MIN() function.
SELECT MIN(<numeric column>) FROM <table>;
SELECT MIN(<numeric column>) FROM <table> GROUP BY <other
Examples:
SELECT AVG(cost) AS average, MAX(cost) AS Maximum, MIN(cost) AS Minimum, user_id FROM orders GROUP BY user_id;
## **Mathematical Numeric Types**
Mathematical Operators
* Multiply
/ Divide
+ Add
- Subtract
SELECT <numeric column> <mathematical operator> <numeric value> FROM <table>;
Examples:
SELECT name, ROUND(price * 1.06, 2) AS "Price in Florida" FROM products;
SELECT name, ROUND(price / 1.4, 2) AS price_gbp FROM products;
git
## **Other Random Examples**
- Find the actor with the longest name
SELECT name, LENGTH(name) AS length FROM actors ORDER BY length DESC LIMIT 1;
- Add the username after the review. e.g. "That was a really cool movie - chalkers"
SELECT review || " - " || username AS combined FROM reviews;
- Uppercase all movie titles
SELECT UPPER(title) FROM movies;
- In all of the reviews, replace the text "public relations" with "PR"
SELECT REPLACE(review, "public relations", "PR") FROM reviews;
- From the actors, truncate names greater than 10 charactor with ... e.g. William Wo...
SELECT name, SUBSTR(name, 1, 10) || "..." AS short_description FROM actors;
- Count number in a specific genre:
SELECT COUNT(genre) FROM movies WHERE genre = "Musical";
- Average rating:
SELECT AVG(rating) FROM reviews WHERE username = "chalkers";
- Sorting movie IDs by average rating:
SELECT movie_id, AVG(rating) FROM reviews GROUP BY movie_id;
## **Date and Time Functions**
One of the powerful features in SQL is writing queries based on today's date and time. Here are some variations based on different types:
SQLite
To get the current date use: DATE("now")
To get the current time use: TIME("now")
To get the current date time: DATETIME("NOW")
MS SQL
To get the current date use: CONVERT(date, GETDATE())
To get the current time use: CONVERT(time, GETDATE())
To get the current date time: GETDATE()
MySQL
To get the current date use: CURDATE()
To get the current time use: CURTIME()
To get the current date time: NOW()
Oracle and PostgreSQL
To get the current date use: CURRENT_DATE
To get the current time use: CURRENT_TIME
To get the current date time: `CURRENT_TIMESTAMP
Example:
SELECT * FROM orders WHERE status = "placed" AND ordered_on = DATE("now");
SELECT COUNT(*) AS "shipped_today" FROM orders WHERE status = "shipped" AND ordered_on = DATE("now");
## **Calculating Dates**
Calculating dates are great for generating reports and dashboards that are dynamic in nature.
Examples:
SELECT COUNT(*) FROM orders WHERE ordered_on BETWEEN DATE("now", "-7 days") AND DATE("now, "-1 day");
SELECT COUNT(*) FROM orders WHERE ordered_on BETWEEN DATE("now", "-7 days", "-7 days") AND DATE("now, "-1 day", "-7 days");
SELECT COUNT(status) AS ordered_yesterday_and_shipped FROM orders WHERE status = "shipped" AND ordered_on = DATE("now", "-1 day");
## **Formatting Dates For Reporting**
Examples:
SELECT *, STRFTIME("%d/%m/%Y", ordered_on) AS UK_date FROM orders;
SELECT title, STRFTIME("%m/%Y", date_released) AS month_year_released FROM movies;
STRFTIME("%d-%m", "now")
STRFTIME("%m-%Y", "2016-12-19 09:10:55")
STRFTIME("%Y", "2016-12-19 09:10:55", "+1 year")
SELECT * FROM loans WHERE return_by = DATE("now", "-1 day"); |
Markdown | UTF-8 | 1,015 | 3.046875 | 3 | [] | no_license | # Watercooler Gossip: Dream or Nightmare?
**Advanced** level
### Chinese Text
开辟鸿蒙,谁为情种?都只为风月情浓。奈何天,伤怀日,寂寥时,试遣愚衷。因此上演出这悲金悼玉的“红楼梦”。
### Pinyin and Translation
|说人|句子|
|----|----|
||开辟鸿蒙,谁为情种?都只为风月情浓。奈何天,伤怀日,寂寥时,试遣愚衷。因此上演出这悲金悼玉的“红楼梦”。<blockquote><br /></blockquote>|
### Vocab
|汉子|拼音|英文|词类|
|----|----|----|----|
|丫鬟|yāhuan|serving girl|noun|
|风波|fēngbō|scandal|noun|
|弱柳扶风|ruòliǔfúfēng|unable to walk steadily|idiom|
|铜钱头|tóngqiántóu|an ugly Chinese hairstyle|noun|
|伏笔|fúbǐ|portent|noun|
|册子|cèzi|bound volumes|noun|
|红楼梦|hónglóumèng|Dream of the Red Chamber|noun|
|贾宝玉|jiǎbǎoyù|Jia Baoyu|name|
|薛宝钗|xuēbǎochāi|Xue Baochai|name|
|林黛玉|líndàiyù|Lin Daiyu|name|
|史湘云|shǐxiāngyún|Shi Xiangyun|name| |
JavaScript | UTF-8 | 1,184 | 3 | 3 | [] | no_license | let http = require('http');
// http基于tcp
// let server = http.createServer(function(req,res){
// });
let server = http.createServer();
// 监听的方法和上面的方法等效;
server.on('connection', function (req, res) {
console.log('connection')
});
server.on('close', function (req, res) {
});
server.on('error', function (req, res) {
});
// curl 发http请求
// 模拟客户端创建连接 curl http://www.baidu.com -v -v显示内容
// curl -v -d 'a=1' http://localhost:8080/abc?a=1#123
server.on('request', function (req, res) {
// req 请求 可读流
// res 响应 可写流
let method = req.method;//POST
let httpVersion = req.httpVersion;//1.1
let url = req.url;///abc?a=1
let header = req.headers;//名字都小写的;
// console.log(method, httpVersion, url, header)
let buffers = [];
// 如果没有请求体是不会触发data事件;
req.on('data', function (data) {
buffers.push(data);
});
req.on('end', function () {
let result = Buffer.concat(buffers);
// socket.write socket.end
res.write("hello ");
res.end("wrold");
})
});
server.listen(8080); |
Python | UTF-8 | 8,862 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | # -*- python -*-
import requests
from . import writer
from . import reader
from . import metadata
from . import graphite
from . import deleter
class KairosDBConnection(object):
"""
:type server: str
:param server: the host to connect to that is running KairosDB
:type port: str
:param port: the port, as a string, that the KairosDB instance is running on
:type ssl: bool
:param ssl: Whether or not to use ssl for this connection.
"""
def __init__(self, server='localhost', port='8080', ssl=False, user=None, passw=None):
"""
:type server: str
:param server: the host to connect to that is running KairosDB
:type port: str
:param port: the port, as a string, that the KairosDB instance is running on
:type ssl: bool
:param ssl: Whether or not to use ssl for this connection.
"""
self.ssl = ssl
self.server = server
self.port = port
self.user = user
self.passw = passw
# We shouldn't have to worry about efficient re-use of connections, pooling, etc. See:
# http://docs.python-requests.org/en/latest/user/advanced/#keep-alive
self._generate_urls()
metadata.get_server_version(self) # XXX check for failure to connect
def _generate_urls(self):
"""This method creates the URL each time a read or write operation is performed.
By its nature, it allows the schema (http/https) to be changed e.g. if it's desired for testing.
"""
if self.ssl is True:
self.schema = "https"
else:
self.schema = "http"
self.read_url = "{0}://{1}:{2}/api/v1/datapoints/query".format(self.schema, self.server, self.port)
self.read_tag_url = "{0}://{1}:{2}/api/v1/datapoints/query/tags".format(self.schema, self.server, self.port)
self.write_url = "{0}://{1}:{2}/api/v1/datapoints".format(self.schema, self.server, self.port)
self.delete_dps_url = "{0}://{1}:{2}/api/v1/datapoints/delete".format(self.schema, self.server, self.port)
self.delete_metric_url = "{0}://{1}:{2}/api/v1/metric/".format(self.schema, self.server, self.port)
def write_one_metric(self, name, timestamp, value, tags):
"""
:type name: str
:param name: the name of the metric being written
:type timestamp: float
:param timestamp: the number of seconds since the epoch, as a float. Per the return value of time.time()
:type value: float
:param value: The value of the metric to be recorded
:type tags: dict
:param tags: A dictionary of key : value strings that are the tags that will be recorded with this metric.
:rtype: requests.response
:return: a requests.response object with the results of the write
This is the API for writing a single metric, making it
easier in simple cases. This method is inefficient for large
batches, and write_metrics() should be used instead in these cases.
"""
return writer.write_one_metric(self, name, timestamp, value, tags)
def write_metrics(self, metric_list):
"""
:type tags: list
:param tags: list of dictionaries of metrics, including name, timestamp, value, and tags to be written
:rtype: requests.response
:return: a requests.response object with the results of the write
"""
return writer.write_metrics_list(self, metric_list)
def read_relative(self, metric_names_list, start_time, end_time=None,
query_modifying_function=None, only_read_tags=False, tags=None):
"""
:type metric_names_list: list
:param metric_names_list: list of metric names to be queried
:type start_time: list
:param start_time: The start time for this read request as a pair of values. The first element
is a number, the second element is a string specifying the unit of time, e.g. "days", "seconds", "hours", etc.
:type end_time: list
:param end_time: The end time for this read request as a pair of values. The first element
is a number, the second element is a string specifying the unit of time, e.g. "days", "seconds", "hours", etc.
:type query_modifying_function: function
:param query_modifying_function: A function that accepts one argument: the query being created. It can be used
to arbitrarily modify the contents of the request. Intended for applying modifications to aggregators and
grouping and caching when appropriate values for these are discovered.
:type only_read_tags: bool
:param only_read_tags: Whether the query will be for tags or for tags and data. Default is both.
:type tags: dict
:param tags: Contains tags which will be added to the query. If only_read_tags=True, will filter the results to
those that have specified tags.
:rtype: requests.response
:return: a requests.response object with the results of the write
Read values for the requested metrics using a relative start time, and optionally a relative end time (or don't use
an end time, which means "now")
"""
return reader.read_relative(self, metric_names_list, start_time, end_time,
query_modifying_function=query_modifying_function,
only_read_tags=only_read_tags, tags=tags)
def read_absolute(self, metric_names_list, start_time, end_time=None,
query_modifying_function=None, only_read_tags=False, tags=None):
"""
:type metric_names_list: list
:param metric_names_list: list of metric names to be queried
:type start_time: float
:param start_time: The start time for this read request as seconds since the epoch (per python's time.time())
:type end_time: float
:param end_time: The end time for this read request as seconds since the epoch (per python's time.time())
:type query_modifying_function: function
:param query_modifying_function: A function that accepts one argument: the query being created. It can be used
to arbitrarily modify the contents of the request. Intended for applying modifications to aggregators and
grouping and caching when appropriate values for these are discovered.
:type only_read_tags: bool
:param only_read_tags: Whether the query will be for tags or for tags and data. Default is both.
:type tags: dict
:param tags: Contains tags which will be added to the query. If only_read_tags=True, will filter the results to
those that have specified tags.
:rtype: requests.response
:return: a requests.response object with the results of the write
Read values for the requested metrics using an absolute start time, and optionally an absolute end time (or don't use
an end time, which means time.time())
"""
return reader.read_absolute(self, metric_names_list, start_time, end_time,
query_modifying_function=query_modifying_function,
only_read_tags=only_read_tags, tags=tags)
def delete_datapoints(self, metric_names_list, start_time, end_time=None, tags=None):
"""
:type metric_names_list: list
:param metric_names_list: list of metric names to be queried.
:type start_time: float
:param start_time: The start time for this read request as seconds since the epoch (per python's time.time())
:type end_time: float
:param end_time: The end time for this read request as seconds since the epoch (per python's time.time())
:type only_read_tags: bool
:param only_read_tags: Whether the query will be for tags or for tags and data. Default is both.
:type tags: dict
:param tags: Tags to be searched in metrics. Allows to filter the results to only metric which contain specified
tags in case only_read_tags=True.
Performs the query made from specified parameters and deletes all data points returned by the query.
Aggregators and groupers have no effect on which data points are deleted.
Note: Works for the Cassandra and H2 data store only.
"""
return deleter.delete_datapoints(self, metric_names_list, start_time,
end_time, tags=tags)
def delete_metrics(self, metric_names_list):
"""
:type metric_names_list: list
:param metric_names_list: list of metric names to be deleted.
"""
return deleter.delete_metrics(self, metric_names_list)
|
Ruby | UTF-8 | 12,679 | 3.171875 | 3 | [
"MIT"
] | permissive | require 'pp'
module RbbCode
module CharCodes
CR_CODE = 13
LF_CODE = 10
L_BRACK_CODE = 91
R_BRACK_CODE = 93
SLASH_CODE = 47
LOWER_A_CODE = 97
LOWER_Z_CODE = 122
UPPER_A_CODE = 65
UPPER_Z_CODE = 90
end
class Node
def << (child)
@children << child
end
attr_accessor :children
def initialize(parent)
@parent = parent
@children = []
end
attr_accessor :parent
end
class RootNode < Node
def initialize
@children = []
end
end
class TextNode < Node
undef_method '<<'.to_sym
undef_method :children
def initialize(parent, text)
@parent = parent
@text = text
end
attr_accessor :text
def to_bb_code
@text
end
end
class TagNode < Node
def self.from_opening_bb_code(parent, bb_code)
if equal_index = bb_code.index('=')
tag_name = bb_code[1, equal_index - 1]
value = bb_code[(equal_index + 1)..-2]
else
tag_name = bb_code[1..-2]
value = nil
end
new(parent, tag_name, value)
end
def initialize(parent, tag_name, value = nil)
super(parent)
@tag_name = tag_name.downcase
@value = value
@preformatted = false
end
def inner_bb_code
@children.inject('') do |output, child|
output << child.to_bb_code
end
end
def preformat!
@preformatted = true
end
def preformatted?
@preformatted
end
def to_bb_code
if @value.nil?
output = "[#{@tag_name}]"
else
output = "[#{@tag_name}=#{@value}]"
end
output << inner_bb_code << "[/#{@tag_name}]"
end
attr_reader :tag_name
attr_reader :value
end
class TreeMaker
include CharCodes
def initialize(schema)
@schema = schema
end
def make_tree(str)
delete_junk_breaks!(
delete_invalid_empty_tags!(
parse_str(str)
)
)
end
protected
def ancestor_list(parent)
ancestors = []
while parent.is_a?(TagNode)
ancestors << parent.tag_name
parent = parent.parent
end
ancestors
end
def break_type(break_str)
if break_str.length > 2
:paragraph
elsif break_str.length == 1
:line_break
elsif break_str == "\r\n"
:line_break
else
:paragraph
end
end
# Delete empty paragraphs and line breaks at the end of block-level elements
def delete_junk_breaks!(node)
node.children.reject! do |child|
if child.is_a?(TagNode) and !node.is_a?(RootNode)
if !child.children.empty?
delete_junk_breaks!(child)
false
elsif child.tag_name == @schema.paragraph_tag_name
# It's an empty paragraph tag
true
elsif @schema.block_level?(node.tag_name) and child.tag_name == @schema.line_break_tag_name and node.children.last == child
# It's a line break a the end of the block-level element
true
else
false
end
else
false
end
end
node
end
# The schema defines some tags that may not be empty. This method removes any such empty tags from the tree.
def delete_invalid_empty_tags!(node)
node.children.reject! do |child|
if child.is_a?(TagNode)
if child.children.empty? and !@schema.tag_may_be_empty?(child.tag_name)
true
else
delete_invalid_empty_tags!(child)
false
end
end
end
node
end
def parse_str(str)
tree = RootNode.new
# Initially, we open a paragraph tag. If it turns out that the first thing we encounter
# is a block-level element, no problem: we'll be calling promote_block_level_elements
# later anyway.
current_parent = TagNode.new(tree, @schema.paragraph_tag_name)
tree << current_parent
current_token = ''
current_token_type = :unknown
current_opened = 0
# It may seem naive to use each_byte. What about Unicode? So long as we're using UTF-8, none of the
# BB Code control characters will appear as part of multibyte characters, because UTF-8 doesn't allow
# the range 0x00-0x7F in multibyte chars. As for the multibyte characters themselves, yes, they will
# be temporarily split up as we append bytes onto the text nodes. But as of yet, I haven't found
# a way that this could cause a problem. The bytes always come back together again. (It would be a problem
# if we tried to count the characters for some reason, but we don't do that.)
str.each_byte do |char_code|
char = char_code.chr
case current_token_type
when :unknown
case char
when '['
current_token_type = :possible_tag
current_token << char
current_opened += 1
when "\r", "\n"
current_token_type = :break
current_token << char
else
if current_parent.is_a?(RootNode)
new_paragraph_tag = TagNode.new(current_parent, @schema.paragraph_tag_name)
current_parent << new_paragraph_tag
current_parent = new_paragraph_tag
end
current_token_type = :text
current_token << char
end
when :text
case char
when "["
if @schema.text_valid_in_context?(*ancestor_list(current_parent))
current_parent << TextNode.new(current_parent, current_token)
end
current_token = '['
current_token_type = :possible_tag
current_opened += 1
when "\r", "\n"
if @schema.text_valid_in_context?(*ancestor_list(current_parent))
current_parent << TextNode.new(current_parent, current_token)
end
current_token = char
current_token_type = :break
else
current_token << char
end
when :break
if char_code == CR_CODE or char_code == LF_CODE
current_token << char
else
if break_type(current_token) == :paragraph
while current_parent.is_a?(TagNode) and !@schema.block_level?(current_parent.tag_name) and current_parent.tag_name != @schema.paragraph_tag_name
current_parent = current_parent.parent
end
# The current parent might be a paragraph tag, in which case we should move up one more level.
# Otherwise, it might be a block-level element or a root node, in which case we should not move up.
if current_parent.is_a?(TagNode) and current_parent.tag_name == @schema.paragraph_tag_name
current_parent = current_parent.parent
end
# Regardless of whether the current parent is a block-level element, we need to open a new paragraph.
new_paragraph_node = TagNode.new(current_parent, @schema.paragraph_tag_name)
current_parent << new_paragraph_node
current_parent = new_paragraph_node
else # line break
prev_sibling = current_parent.children.last
if prev_sibling.is_a?(TagNode) and @schema.block_level?(prev_sibling.tag_name)
# Although the input only contains a single newline, we should
# interpret is as the start of a new paragraph, because the last
# thing we encountered was a block-level element.
new_paragraph_node = TagNode.new(current_parent, @schema.paragraph_tag_name)
current_parent << new_paragraph_node
current_parent = new_paragraph_node
elsif @schema.tag(@schema.line_break_tag_name).valid_in_context?(*ancestor_list(current_parent))
current_parent << TagNode.new(current_parent, @schema.line_break_tag_name)
end
end
if char == '['
current_token = '['
current_token_type = :possible_tag
current_opened += 1
else
current_token = char
current_token_type = :text
end
end
when :possible_tag
case char
when '['
current_parent << TextNode.new(current_parent, '[')
current_opened += 1
# No need to reset current_token or current_token_type, because now we're in a new possible tag
when '/'
current_token_type = :closing_tag
current_token << '/'
else
if tag_name_char?(char_code)
current_token_type = :opening_tag
current_token << char
else
current_token_type = :text
current_token << char
end
end
when :opening_tag
if tag_name_char?(char_code) or char == '='
current_token << char
elsif char == '['
current_opened += 1
current_token << char
elsif char == ']'
current_opened -= 1
current_token << ']'
if current_opened <= 0
tag_node = TagNode.from_opening_bb_code(current_parent, current_token)
if @schema.block_level?(tag_node.tag_name) and current_parent.tag_name == @schema.paragraph_tag_name
# If there is a line break before this, it's superfluous and should be deleted
prev_sibling = current_parent.children.last
if prev_sibling.is_a?(TagNode) and prev_sibling.tag_name == @schema.line_break_tag_name
current_parent.children.pop
end
# Promote a block-level element
current_parent = current_parent.parent
tag_node.parent = current_parent
current_parent << tag_node
current_parent = tag_node
# If all of this results in empty paragraph tags, no worries: they will be deleted later.
elsif tag_node.tag_name == current_parent.tag_name and @schema.close_twins?(tag_node.tag_name)
# The current tag and the tag we're now opening are of the same type, and this kind of tag auto-closes its twins
# (E.g. * tags in the default config.)
current_parent.parent << tag_node
current_parent = tag_node
elsif @schema.tag(tag_node.tag_name).valid_in_context?(*ancestor_list(current_parent))
current_parent << tag_node
current_parent = tag_node
end # else, don't do anything--the tag is invalid and will be ignored
if @schema.preformatted?(current_parent.tag_name)
current_token_type = :preformatted
current_parent.preformat!
else
current_token_type = :unknown
end
current_token = ''
end
elsif char == "\r" or char == "\n"
current_parent << TextNode.new(current_parent, current_token)
current_token = char
current_token_type = :break
elsif current_token.include?('=')
current_token << char
else
current_token_type = :text
current_token << char
end
when :closing_tag
if tag_name_char?(char_code)
current_token << char
elsif char == ']'
original_parent = current_parent
while current_parent.is_a?(TagNode) and current_parent.tag_name != current_token[2..-1].downcase
current_parent = current_parent.parent
end
if current_parent.is_a?(TagNode)
if !current_parent.parent.is_a?(RootNode)
current_parent = current_parent.parent
else
new = TagNode.new(current_parent.parent, @schema.paragraph_tag_name)
current_parent.parent << new
current_parent = new
end
else # current_parent is a RootNode
# we made it to the top of the tree, and never found the tag to close
# so we'll just ignore the closing tag altogether
current_parent = original_parent
end
current_token_type = :unknown
current_token = ''
current_opened -= 1
elsif char == "\r" or char == "\n"
current_parent << TextNode.new(current_parent, current_token)
current_token = char
current_token_type = :break
else
current_token_type = :text
current_token << char
end
when :preformatted
if char == '['
current_parent << TextNode.new(current_parent, current_token)
current_token_type = :possible_preformatted_end
current_token = '['
else
current_token << char
end
when :possible_preformatted_end
current_token << char
if current_token == "[/#{current_parent.tag_name}]" # Did we just see the closing tag for this preformatted element?
current_parent = current_parent.parent
current_token_type = :unknown
current_token = ''
elsif char == ']' # We're at the end of this opening/closing tag, and it's not the closing tag for the preformatted element
current_parent << TextNode.new(current_parent, current_token)
current_token_type = :preformatted
current_token = ''
end
else
raise "Unknown token type in state machine: #{current_token_type}"
end
end
# Handle whatever's left in the current token
if current_token_type != :break and !current_token.empty?
current_parent << TextNode.new(current_parent, current_token)
end
tree
end
def tag_name_char?(char_code)
(LOWER_A_CODE..LOWER_Z_CODE).include?(char_code) or (UPPER_A_CODE..UPPER_Z_CODE).include?(char_code) or char_code.chr == '*'
end
end
end
|
Ruby | UTF-8 | 1,214 | 2.953125 | 3 | [] | no_license | # Open and Read file
File.open("wordlist", "r") do |file|
file.each do |line|
puts line
end
end
File.open("wordlist", "r") do |file|
file.each_line do |line|
puts line
end
end
File.open("wordlist", "r") do |file|
while line = file.gets
puts line
end
end
File.open("wordlist", "r") do |file|
file.each_byte.with_index do |ch, index|
puts ch.chr
end
end
IO.foreach('wordlist') {|line| puts line}
# Open and Writing to files
File.open('wordlist', 'w') do |file|
file.puts 'pataha'
file << 'chido'
end
puts File.read('wordlist')
STDOUT << File.read('wordlist')
require 'stringio'
ip = StringIO.new("now is\nthe time\n")
op = StringIO.new("", "w")
ip.each_line {|line| op.puts line.reverse}
STDOUT << op.string
# Taking to Networks
# Low-Level
require 'net/http'
http = Net::HTTP.new('vnexpress.net', 80)
response = http.get('/')
puts response.message
if response.message == "OK"
puts response.body.scan(/<img alt=".*?" src="(.*?)"/m)
end
# High-Level
require 'open-uri'
open('https://google.com.vn') do |f|
puts f.read.scan(/<a href=".*?"/m)
end
# Parsing HTML
require 'open-uri'
require 'nokogiri'
doc = Nokogiri::HTML(open('https://google.com.vn'))
puts doc.css("a") |
Java | UTF-8 | 260 | 1.640625 | 2 | [] | no_license | package com.nespot2.springrestsample.item.repository;
import com.nespot2.springrestsample.item.domain.ItemDetail;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ItemDetailRepository extends JpaRepository<ItemDetail, Long> {
}
|
C++ | UTF-8 | 729 | 2.875 | 3 | [] | no_license | #include "Numeros_Complexos_Polares.h"
#include <cmath>
Numeros_Complexos_Polares::Numeros_Complexos_Polares(Numeros_Complexos um_numero_complexo)
{
this->Set_Real(um_numero_complexo.Get_Real());
this->Set_Imaginario(um_numero_complexo.Get_Imaginario());
Conformar_Numero();
}
void Numeros_Complexos_Polares::Conformar_Numero()
{
this->angulo = 57.2958*atan(this->Get_Imaginario()/this->Get_Real());
this->modulo = sqrt((pow(this->Get_Real(),2)+pow(this->Get_Imaginario(),2)));
}
double Numeros_Complexos_Polares::Get_Modulo() const
{
return this->modulo;
}
double Numeros_Complexos_Polares::Get_Angulo() const
{
return this->angulo;
}
Numeros_Complexos_Polares::~Numeros_Complexos_Polares()
{}
|
Python | UTF-8 | 12,449 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | import numpy as np
import keras.backend as T
from keras.metrics import categorical_accuracy, mean_squared_error
from ellipse_fit import get_ellipse_kaggle_par
def lr_function(e, lrs):
for i in xrange(e, -1, -1):
if i in lrs:
return lrs[i]
def kaggle_MultiRotMergeLayer_output(x, num_views=2):
# TODO: stop using mb_size argument! needed for events mod batch_size!=0!
# build check?
input_shape = T.shape(x)
input_ = x
mb_size = input_shape[0] / 4 / num_views
# split out the 4* dimension
input_r = input_.reshape((4 * num_views, mb_size, T.prod(input_shape[1:])))
def output_shape(lx): return (
lx[0] // 4 // num_views, (lx[1] * lx[2] * lx[3] * 4 * num_views))
return input_r.transpose(1, 0, 2).reshape(output_shape(input_shape))
# TODO anyway to get 'num_views' when used as output_shape function? ->
# use a lambda function? use functools.partial would work too
def kaggle_MultiRotMergeLayer_output_shape(input_shape, num_views=2):
# #size = T.prod(input_shape[1:]) * (4 * num_views)
size = (input_shape[1] * input_shape[2] * input_shape[3]) * (4 * num_views)
return (input_shape[0] // 4 // num_views, size)
def kaggle_input(x, part_size=45, n_input_var=2, include_flip=False, random_flip=False):
parts = []
for i in range(0, n_input_var):
input_ = x[i]
ps = part_size # shortcut
if include_flip:
input_representations = [input_, input_[
:, :, :, ::-1]] # regular and flipped
elif random_flip:
input_representations = [input_] if np.random.binomial(1, 0.5) else [
input_[:, :, :, ::-1]]
else:
input_representations = [input_] # just regular
for input_rep in input_representations:
part0 = input_rep[:, :, :ps, :ps] # 0 degrees
part1 = input_rep[:, :, :ps, :-ps - 1:-
1].dimshuffle(0, 1, 3, 2) # 90 degrees
part2 = input_rep[:, :, :-ps - 1:-1, :-ps - 1:-1] # 180 degrees
part3 = input_rep[:, :, :-ps - 1:-1,
:ps].dimshuffle(0, 1, 3, 2) # 270 degrees
parts.extend([part0, part1, part2, part3])
return T.concatenate(parts, axis=0)
# unfortunately keras2 does not support dicts as output for metrics anymore...
def kaggle_sliced_accuracy(y_true, y_pred, slice_weights=[1.] * 11):
question_slices = [slice(0, 3), slice(3, 5), slice(5, 7), slice(7, 9), slice(9, 13), slice(13, 15),
slice(15, 18), slice(18, 25), slice(25, 28), slice(28, 31), slice(31, 37)]
accuracy_slices = [categorical_accuracy(
y_true[:, question_slices[i]], y_pred[:, question_slices[i]]) * slice_weights[i] for i in range(len(question_slices))]
accuracy_slices = T.cast(accuracy_slices, 'float32')
return {'sliced_accuracy_mean': T.mean(accuracy_slices), 'sliced_accuracy_std': T.std(accuracy_slices)}
def sliced_accuracy_mean(y_true, y_pred, slice_weights=[1.] * 11):
return kaggle_sliced_accuracy(y_true, y_pred, slice_weights)['sliced_accuracy_mean']
def sliced_accuracy_std(y_true, y_pred, slice_weights=[1.] * 11):
return kaggle_sliced_accuracy(y_true, y_pred, slice_weights)['sliced_accuracy_std']
def rmse(y_true, y_pred):
return T.sqrt(mean_squared_error(y_true, y_pred))
# in keras 2 weights cant be set directly on layer creation. constant
# initilizer are now available. orth_style will need custom initilizer
def dense_weight_init_values(n_inputs, n_outputs, nb_feature=None, w_std=0.001, b_init_val=0.01, orth_style=False):
if type(n_inputs) != tuple and type(n_inputs) == int:
n_inputs = (n_inputs,)
if type(n_outputs) != tuple and type(n_outputs) == int:
n_outputs = (n_outputs,)
W_shape = n_inputs + n_outputs
if nb_feature:
W_shape = (nb_feature,) + W_shape
n_outputs = (nb_feature,) + n_outputs
weights = (np.random.randn(*W_shape).astype(np.float32) * w_std,
np.ones(n_outputs).astype(np.float32) * b_init_val)
if orth_style:
if len(n_inputs) != 1 or len(n_inputs) != 1:
raise ValueError(
'For orthagonal matrixes in weight init the numer of input and output dimension must be one')
if nb_feature:
weights = (weights[0] + np.repeat(
[np.eye(n_inputs[0], n_outputs[0],
dtype=np.float32) - w_std / 2], nb_feature, 0),
weights[1])
else:
weights = (weights[0] + np.eye(n_inputs[0], n_outputs[0],
dtype=np.float32) - w_std / 2,
weights[1])
return weights
# TODO categorised and LL loss not updated
def OptimisedDivGalaxyOutput(x, mb_size=None, normalised=True, categorised=False):
input_layer = x
if not mb_size:
mb_size = input_layer.shape[0]
params = []
bias_params = []
question_slices = [slice(0, 3), slice(3, 5), slice(5, 7), slice(7, 9), slice(9, 13), slice(13, 15),
slice(15, 18), slice(18, 25), slice(25, 28), slice(28, 31), slice(31, 37)]
normalisation_mask = T.variable(
generate_normalisation_mask(question_slices))
# self.scaling_mask = theano.shared(self.generate_scaling_mask())
# sequence of scaling steps to be undertaken.
# First element is a slice indicating the values to be scaled. Second element is an index indicating the scale factor.
# these have to happen IN ORDER else it doesn't work correctly.
scaling_sequence = [
(slice(3, 5), 1), # I: rescale Q2 by A1.2
(slice(5, 13), 4), # II: rescale Q3, Q4, Q5 by A2.2
(slice(15, 18), 0), # III: rescale Q7 by A1.1
(slice(18, 25), 13), # IV: rescale Q8 by A6.1
(slice(25, 28), 3), # V: rescale Q9 by A2.1
(slice(28, 37), 7), # VI: rescale Q10, Q11 by A4.1
]
if normalised:
return predictions(input_layer, normalisation_mask, categorised, mb_size, scaling_sequence)
else:
return predictions_no_normalisation(input_layer)
def predictions(input_layer, normalisation_mask, categorised, mb_size, scaling_sequence, *args, **kwargs):
return weighted_answer_probabilities(input_layer, normalisation_mask, categorised, mb_size, scaling_sequence, *args, **kwargs)
def predictions_no_normalisation(input_layer, *args, **kwargs):
"""
Predict without normalisation. This can be used for the first few chunks to find good parameters.
"""
return T.clip(input_layer, 0, 1) # clip on both sides here, any predictions over 1.0 are going to get normalised away anyway.
def generate_normalisation_mask(question_slices):
"""
when the clipped input is multiplied by the normalisation mask, the normalisation denominators are generated.
So then we can just divide the input by the normalisation constants (elementwise).
"""
mask = np.zeros((37, 37), dtype='float32')
for s in question_slices:
mask[s, s] = 1.0
return mask
'''
def error(self, normalisation=True, *args, **kwargs):
if normalisation:
predictions = self.predictions(*args, **kwargs)
else:
predictions = self.predictions_no_normalisation(*args, **kwargs)
error = T.mean((predictions - self.target_var) ** 2)
return error
'''
def weighted_answer_probabilities(input_layer, normalisation_mask, categorised, mb_size, scaling_sequence, *args, **kwargs):
probs = answer_probabilities(
input_layer, normalisation_mask, categorised, mb_size, *args, **kwargs)
# go through the rescaling sequence in order (6 steps)
output = []
output.append(probs[:, 0:3])
if not categorised:
#prob_scale = T.ones(T.shape(probs))
for probs_slice, scale_idx in scaling_sequence:
#probs = T.set_subtensor(probs[:, probs_slice], probs[:, probs_slice] * probs[:, scale_idx].dimshuffle(0, 'x'))
output.append(probs[:, probs_slice] *
probs[:, scale_idx].dimshuffle(0, 'x'))
if probs_slice == slice(5, 13):
output.append(probs[:, 13:15])
#T.batch_set_value(probs[:, probs_slice], probs[:, probs_slice] * probs[:, scale_idx].dimshuffle(0, 'x'))
output = T.concatenate(output)
else:
output = probs
return output
def answer_probabilities(x, normalisation_mask, categorised, mb_size, *args, **kwargs):
"""
normalise the answer groups for each question.
"""
input_ = T.reshape(x, (mb_size, 37)) # not needed but keep as saveguard
input_clipped = T.maximum(input_, 0)
# small constant to prevent division by 0
normalisation_denoms = T.dot(input_clipped, normalisation_mask) + 1e-7
input_normalised = input_clipped / normalisation_denoms
'''
if categorised:
output=[]
for k in xrange(0,mb_size):
input_q = [
input_normalised[k][0:3], # 1.1 - 1.3,
input_normalised[k][3:5], # 2.1 - 2.2
input_normalised[k][5:7], # 3.1 - 3.2
input_normalised[k][7:9], # 4.1 - 4.2
input_normalised[k][9:13], # 5.1 - 5.4
input_normalised[k][13:15], # 6.1 - 6.2
input_normalised[k][15:18], # 7.1 - 7.3
input_normalised[k][18:25], # 8.1 - 8.7
input_normalised[k][25:28], # 9.1 - 9.3
input_normalised[k][28:31], # 10.1 - 10.3
input_normalised[k][31:37], # 11.1 - 11.6
]
z_v=[]
for i in xrange(0,len(input_q)):
z=1.
z = z * (1.-T.greater(input_q[0][2],0.6))
if i==1: z = z * T.greater(input_q[0][1],0.6)
if i==2: z = z * T.greater(input_q[1][1],0.6)
if i==3: z = z * T.greater(input_q[1][1],0.6)
if i==4: z = z * T.greater(input_q[1][1],0.6)
if i==6: z = z * T.greater(input_q[0][0],0.6)
if i==9: z = z * T.greater(input_q[4][0],0.6)
if i==10: z = z * T.greater(input_q[4][0],0.6)
for j in xrange(0,len(input_q)):
z_v.append(z)
output.append(T.dot(input_normalised[k],z))
#print output
return output
#input_normaised = sum(input_q,[]) #flattens lists of lists
#input_normalised[0:3]=input_q[0]
#input_normalised[3:5]=input_q[1]
#input_normalised[5:7]=input_q[2]
#input_normalised[7:9]=input_q[3]
#input_normalised[9:13]=input_q[4]
#input_normalised[13:15]=input_q[5]
#input_normalised[15:18]=input_q[6]
#input_normalised[18:25]=input_q[7]
#input_normalised[25:28]=input_q[8]
#input_normalised[28:31]=input_q[9]
#input_normalised[31:37]=input_q[10]
'''
return input_normalised
# return [input_normalised[:, s] for s in self.question_slices]
'''
#not original, not in use
def sqrtError(self, normalisation=True, *args, **kwargs):
return T.sqrt(self.error(normalisation=True, *args, **kwargs))
#not original
def error_weighted(self,weight, normalisation=True, *args, **kwargs):
if normalisation:
predictions = self.predictions(*args, **kwargs)
else:
predictions = self.predictions_no_normalisation(*args, **kwargs)
error = T.mean(((predictions - self.target_var)*weight) ** 2)
return error
#not original
#not quadratic like the error!
def ll_error(self, normalisation=True, *args, **kwargs):
if normalisation:
predictions = self.predictions(*args, **kwargs)
else:
predictions = self.predictions_no_normalisation(*args, **kwargs)
error = logloss(self.target_var,predictions)
return error
'''
def input_generator(train_gen):
for chunk in train_gen:
if not chunk:
print 'WARNING: data input generator yielded ' + str(chunk)
+ ', something went wrong'
chunk_data, chunk_length = chunk
y_chunk = chunk_data.pop() # last element is labels.
xs_chunk = chunk_data
# need to transpose the chunks to move the 'channels' dimension up
xs_chunk = [x_chunk.transpose(0, 3, 1, 2) for x_chunk in xs_chunk]
l0_input_var = xs_chunk[0]
l0_45_input_var = xs_chunk[1]
l6_target_var = y_chunk
yield ([l0_input_var, l0_45_input_var], l6_target_var)
def ellipse_par_gen(train_gen):
for img, target in input_generator(train_gen):
yield (np.array(map(lambda x: x, get_ellipse_kaggle_par(img[0])) if len(
np.shape(img[0])) >= 4 else get_ellipse_kaggle_par(img[0])),
target)
|
Java | UTF-8 | 3,499 | 3.15625 | 3 | [] | no_license | package automail;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
/** This class represents the input properties of the simulation. */
public class Properties {
private Integer seed = null;
private int maxFloor;
private double deliveryPenalty;
private int lastDeliveryTime;
private int mailToCreate;
private String robotType1;
private String robotType2;
/**
* Reads in a given .Properties file.
* @param path to the .Properties class.
*/
public Properties(String path) {
// Use a stream to capture all configuration lines and parse them into values
try (Stream<String> stream = Files.lines(Paths.get(path))) {
stream.filter(line -> !line.startsWith("#"))
.forEach(this::load);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method loads our values in depending on the specified value in the line.
* @param line A given line with a value in the class.
*/
private void load(String line) {
String argument = line.substring(0, line.indexOf("="));
switch (argument) {
case "Seed":
// If we have no seed, return 0
if (parseValue(line).equals(" ")) {
this.seed = 0;
} else {
this.seed = Integer.parseInt(parseValue(line));
}
break;
case "Number_of_Floors":
this.maxFloor = Integer.parseInt(parseValue(line));
break;
case "Delivery_Penalty":
this.deliveryPenalty = Double.parseDouble(parseValue(line));
break;
case "Last_Delivery_Time":
this.lastDeliveryTime = Integer.parseInt(parseValue(line));
break;
case "Mail_to_Create":
this.mailToCreate = Integer.parseInt(parseValue(line));
break;
case "Robot_Type_1":
this.robotType1 = parseValue(line);
break;
case "Robot_Type_2":
this.robotType2 = parseValue(line);
break;
}
}
/**
* This simply returns a string of the value of a variable in the .properties file.
* @param line String containing the parameter to be configured
* @return The value defined in the line.
*/
private String parseValue(String line) {
return line.substring(line.lastIndexOf("=") + 1);
}
public Integer getSeed() {
return this.seed;
}
public int getMaxFloor() {
return this.maxFloor;
}
public double getDeliveryPenalty() {
return this.deliveryPenalty;
}
public int getLastDeliveryTime() {
return this.lastDeliveryTime;
}
public int getMailToCreate() {
return this.mailToCreate;
}
public String getRobotType1() {
return this.robotType1;
}
public String getRobotType2() {
return this.robotType2;
}
}
|
Go | UTF-8 | 2,535 | 2.609375 | 3 | [
"MIT"
] | permissive | package webhook_test
import (
"testing"
"github.com/manyminds/api2go/jsonapi"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/smartcontractkit/chainlink/core/services/job"
"github.com/smartcontractkit/chainlink/core/services/webhook"
)
func TestValidateWebJobSpec(t *testing.T) {
var tt = []struct {
name string
toml string
assertion func(t *testing.T, spec job.Job, err error)
}{
{
name: "valid spec",
toml: `
type = "webhook"
schemaVersion = 1
jobID = "0EEC7E1D-D0D2-476C-A1A8-72DFB6633F46"
observationSource = """
ds [type=http method=GET url="https://chain.link/ETH-USD"];
ds_parse [type=jsonparse path="data,price"];
ds -> ds_parse;
"""
`,
assertion: func(t *testing.T, s job.Job, err error) {
require.NoError(t, err)
require.NotNil(t, s.WebhookSpec)
b, err := jsonapi.Marshal(s.WebhookSpec)
require.NoError(t, err)
var r job.WebhookSpec
err = jsonapi.Unmarshal(b, &r)
require.NoError(t, err)
require.Equal(t, "0eec7e1dd0d2476ca1a872dfb6633f46", r.OnChainJobSpecID.String())
},
},
{
name: "invalid job name",
toml: `
type = "webhookjob"
schemaVersion = 1
jobID = "0EEC7E1D-D0D2-476C-A1A8-72DFB6633F46"
observationSource = """
ds [type=http method=GET url="https://chain.link/ETH-USD"];
ds_parse [type=jsonparse path="data,price"];
ds_multiply [type=multiply times=100];
ds -> ds_parse -> ds_multiply;
"""
`,
assertion: func(t *testing.T, s job.Job, err error) {
require.Error(t, err)
assert.Equal(t, "unsupported type webhookjob", err.Error())
},
},
{
name: "missing jobID",
toml: `
type = "webhookjob"
schemaVersion = 1
observationSource = """
ds [type=http method=GET url="https://chain.link/ETH-USD"];
ds_parse [type=jsonparse path="data,price"];
ds_multiply [type=multiply times=100];
ds -> ds_parse -> ds_multiply;
"""
`,
assertion: func(t *testing.T, s job.Job, err error) {
require.Error(t, err)
require.Equal(t, webhook.ErrMissingJobID, errors.Cause(err))
},
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
s, err := webhook.ValidateWebhookSpec(tc.toml)
tc.assertion(t, s, err)
})
}
}
|
Java | UTF-8 | 5,675 | 2.453125 | 2 | [] | no_license | package com.bb.db;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.bb.ui.GwcInfo;
import com.bb.util.Constants;
import com.bb.util.Tool;
/**
* sqlite数据库类
* @author Administrator
*
*/
public class DbControl {
private static final String CREATE_TABLE_NOTE = "create table if not exists gwc ( id integer primary key autoincrement, "
+ "food_name text not null , price text not null , count text not null, seat text not null ,order_date text not null ,user_id text not null,tel text not null );" ;
private static final String DATABASE_NAME = "b_food";
private static final String TABLE_NAME = "gwc" ;
private SQLiteDatabase db;
public DbControl(Context ctx) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
// db.execSQL(" drop table " + TABLE_NAME );
db.execSQL(CREATE_TABLE_NOTE);
int test = db.getVersion();
Log.i( "===db version===", String.valueOf( test ) );
db.close();
}
/**
* 新增
* @param ctx
* @param note
* @return
*/
public boolean addGwc( Context ctx , String food_name , String seat , float price ,int count ,String tel ) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
ContentValues values = new ContentValues();
// food_name , seat , order_date
values.put("food_name", food_name);
values.put("seat", seat);
values.put("count", String.valueOf(count));
values.put("price", String.valueOf(price) ) ;
values.put("order_date", Tool.getNowTime() );
values.put("user_id", Constants.userId );
values.put("tel", tel);
boolean returnValue = db.insert(TABLE_NAME, null, values) > 0;
db.close();
return (returnValue);
}
public boolean updateGwc( Context ctx , long id,String count ) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
ContentValues values = new ContentValues();
// food_name , seat , order_date
values.put("count", count);
boolean returnValue = db.update(TABLE_NAME, values,"id=" + id ,null) >0;
db.close();
return (returnValue);
}
/**
* 删除
* @param ctx
* @param note
* @return
*/
public boolean deleteGwc( Context ctx , long id ) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
boolean returnValue = false;
int result = 0;
result = db.delete(TABLE_NAME, "id=" + id , null);
db.close();
if (result == 1){
returnValue = true;
}
return returnValue;
}
public boolean deleteAllGwc( Context ctx ) {
db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
boolean returnValue = false;
int result = 0;
result = db.delete(TABLE_NAME, null , null);
db.close();
if (result == 1){
returnValue = true;
}
return returnValue;
}
/**
*
* 获取所有购物车
* @param ctx
* @return
*
*/
public List<GwcInfo> getAllGwc( Context ctx ){
db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
List<GwcInfo> list = new ArrayList<GwcInfo>();
// food_name , seat , order_date
Cursor c = db.query(TABLE_NAME, new String[] { "id", "food_name" , "seat" ,"order_date","price" ,"count","tel"}, null, null,null,null, "seat");
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; i++) {
GwcInfo object = new GwcInfo() ;
object.setId( c.getInt(0) );
object.setFood_name( c.getString(1) );
object.setSeat( c.getString(2) );
//object.setSeat_id( c.getString(3) );
object.setOrder_date( c.getString(3) );
object.setPrice( c.getString(4) );
object.setCount( c.getString(5) );
object.setTel( c.getString(6) );
list.add(i, object) ;
c.moveToNext();
}
c.close();
db.close();
return list ;
}
public List<GwcInfo> getGwc( Context ctx ){
db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
List<GwcInfo> list = new ArrayList<GwcInfo>();
// food_name , seat , order_date
Cursor c = db.query(TABLE_NAME, new String[] { "id", "food_name" , "seat" ,"order_date","price" ,"count","tel"}, "user_id=?", new String []{Constants.userId},null,null, "seat");
int numRows = c.getCount();
c.moveToFirst();
for (int i = 0; i < numRows; i++) {
GwcInfo object = new GwcInfo() ;
object.setId( c.getInt(0) );
object.setFood_name( c.getString(1) );
object.setSeat( c.getString(2) );
//object.setSeat_id( c.getString(3) );
object.setOrder_date( c.getString(3) );
object.setPrice( c.getString(4) );
object.setCount( c.getString(5) );
object.setTel( c.getString(6) );
list.add(i, object) ;
c.moveToNext();
}
c.close();
db.close();
return list ;
}
public GwcInfo getoneGwc( Context ctx,long Id ){
db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
List<GwcInfo> list = new ArrayList<GwcInfo>();
GwcInfo object = new GwcInfo();
Cursor cursor = db.query(true, TABLE_NAME, new String[] { "id", "food_name" , "seat" ,"order_date","price" ,"count","tel"},
"id"+ "="+Id, null, null, null, null, null);
if(cursor.moveToFirst()){
// GwcInfo object = new GwcInfo();
object.setId( cursor.getInt(0));
object.setFood_name( cursor.getString(1)) ;
object.setSeat( cursor.getString(2) );
object.setOrder_date( cursor.getString(3) );
object.setPrice( String.valueOf( cursor.getFloat(4) ) );
object.setCount( String.valueOf( cursor.getFloat(5) ) );
object.setTel( cursor.getString(6) );
}
return object;
}
}
|
Python | UTF-8 | 1,177 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | import cryptanalib as ca
import feathermodules
def single_byte_xor_attack(ciphertexts):
options = dict(feathermodules.current_options)
results = []
print '[+] Running single-byte XOR brute force attack...'
try:
num_answers = int(options['number_of_answers'])
except:
return '[*] Could not interpret number_of_answers option as a number.'
if num_answers > 256:
return '[*] Bad option value for number_of_answers.'
for ciphertext in ciphertexts:
results.append(ca.break_single_byte_xor(ciphertext, num_answers=num_answers))
print 'Best candidate decryptions:\n' + '-'*40 + '\n'
output = []
for result in results:
print '\n'.join(['%r (score: %f)' % (candidate_decryption[0],candidate_decryption[1][0]) for candidate_decryption in result])
print '\n'
output.append([x[0] for x in result])
return output
feathermodules.module_list['single_byte_xor'] = {
'attack_function':single_byte_xor_attack,
'type':'stream',
'keywords':['individually_low_entropy'],
'description':'A brute force attack against single-byte XOR encrypted ciphertext.',
'options':{
'number_of_answers': '3'
}
}
|
Java | UTF-8 | 3,795 | 2.34375 | 2 | [] | no_license | package com.ceribit.android.lazynotes;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.ceribit.android.lazynotes.database.Note;
import com.ceribit.android.lazynotes.database.NotePresenter;
import java.util.ArrayList;
public class NoteRecyclerViewFragment extends Fragment {
private static NoteRecyclerViewAdapter mAdapter;
private Note mSavedInstanceNote;
private boolean mSavedInstanceExist;
/* Testing */
private static String LOG_TAG = NoteRecyclerViewFragment.class.getSimpleName();
public void restoreSelectedNote(Note note, boolean shouldStart){
mSavedInstanceNote = note;
mSavedInstanceExist = shouldStart;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.e(LOG_TAG, "RecyclerView fragment created");
View rootView = inflater.inflate(R.layout.note_recycler_view_layout, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.note_recycler_view);
// Retreieve all notes from the database
ArrayList<Note> notesList = NotePresenter.getAllNotes(getContext());
// If the Add-FAB is pressed, create a new note
FloatingActionButton floatingActionButton = rootView.findViewById(R.id.fab_add_note);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fragmentManager =
((MainActivity) getContext()).getSupportFragmentManager();
if (fragmentManager != null) {
NoteFragment noteFragment = new NoteFragment();
fragmentManager.beginTransaction()
.replace(R.id.main_container, noteFragment)
.addToBackStack(null)
.commit();
}
}
});
// Set up the adapter
mAdapter = new NoteRecyclerViewAdapter(getContext(), notesList);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
recyclerView.setAdapter(mAdapter);
// Reinstantiate existing NoteFragment
if (mSavedInstanceExist) {
FragmentManager fragmentManager =
((MainActivity) getContext()).getSupportFragmentManager();
if (fragmentManager != null && mSavedInstanceNote.getTitle() != null) {
NoteFragment noteFragment = new NoteFragment();
noteFragment.setArguments(NoteRecyclerViewAdapter
.createNoteBundle(mSavedInstanceNote));
fragmentManager.beginTransaction()
.setCustomAnimations(R.anim.do_nothing, R.anim.do_nothing,
R.anim.zoom_enter, R.anim.zoom_exit)
.replace(R.id.main_container, noteFragment)
.addToBackStack(null)
.commit();
}
mSavedInstanceExist = false;
}
// Return recycler view
return rootView;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(LOG_TAG,"RecyclerFragment deleted");
}
}
|
Java | UTF-8 | 690 | 2.203125 | 2 | [
"MIT"
] | permissive | package br.com.fatecmogidascruzes.config.captcha;
import java.util.HashMap;
import java.util.Map;
public class ReCaptchaUtil {
public static final Map<String, String> RECAPTCHA_ERROR_CODE = new HashMap<>();
static {
RECAPTCHA_ERROR_CODE.put("missing-input-secret", "The secret parameter is missing");
RECAPTCHA_ERROR_CODE.put("invalid-input-secret", "The secret parameter is invalid or malformed");
RECAPTCHA_ERROR_CODE.put("missing-input-response", "The response parameter is missing");
RECAPTCHA_ERROR_CODE.put("invalid-input-response", "The response parameter is invalid or malformed");
RECAPTCHA_ERROR_CODE.put("bad-request", "The request is invalid or malformed");
}
} |
Markdown | UTF-8 | 4,832 | 3.234375 | 3 | [] | no_license | ---
title: Overview
---
The XCaliber Gaming Platform API uses [OAuth 2](https://tools.ietf.org/html/rfc6749) for authentication and it implements some extensions to it for some advanced scenarios.
## What is OAuth 2?
OAuth 2 is an authorization framework that enables applications to obtain access to user accounts on an HTTP service such as XCaliber Gaming Platform API. It works by delegating user authentication to the service that hosts the user account, and authorizing the application to access the user account.
## OAuth Roles
OAuth defines [four roles](https://tools.ietf.org/html/rfc6749#section-1.1):
* [Resource owner](#resource-owner) (the user)
* [Resource server](#resource-authorization-server) (this API)
* [Authorization server](#resource-authorization-server) (this API)
* [Client](#client) (the application)
### Resource owner
The OAuth 2 spec refers to the user as the "resource owner". The resource owner is the person who is giving access to their account. The resources in this case can be data (bonuses, transactions, game sessions), services (claiming a bonus, creating a transaction), or any other resource requiring access restrictions.
### Resource / authorization server
The resource server hosts the protected user accounts, and the authorization server verifies the identity of the *user* then issues access tokens to the *application*.
From an application developer's point of view, XCaliber's API fulfills both the resource and authorization server roles.
### Client
The client is the application that is attempting to access the user's resources. Before the client can access the user's account, it needs to obtain permission. The client will obtain permission by either directing the user to a login form, or by asserting permission directly with the authorization server without interaction by the user.
## Abstract flow
Now that you have an idea of what the OAuth roles are, let's look at a diagram of how they generally interact with each other:
```adoc
+-------------+ +------------------+
│ │ --- 1. Authorization request --> │ User │
│ │ <-- 2. Authorization grant ----- │ (Resource owner) │
│ │ +------------------+
│ │
│ Application │ +------------------+---+
│ (Client) │ --- 3. Authorization grant ----> │ Authorization │ │
│ │ <-- 4. Access token ------------ │ server │ A │
│ │ +------------------+ P │
│ │ --- 5. Access token -----------> │ Resource │ I │
│ │ <-- 6. Protected resource ------ │ server │ │
+-------------+ +------------------+---+
```
1. The *application* requests authorization to access service resources from the *user*.
2. If the *user* authorized the request, the *application* receives an authorization grant.
3. The *application* requests an access token from the *authorization server* (API) by presenting authentication of its own identity, and the authorization grant.
4. If the application identity is authenticated and the authorization grant is valid, the *authorization server* (API) issues an access token to the application. Authorization is complete.
5. The *application* requests the resource from the *resource server* (API) and presents the access token for authentication.
6. If the access token is valid, the *resource server* (API) serves the resource to the *application*.
The actual flow of this process will differ depending on the authorization grant type in use, but this is the general idea.
## Application registration
Before using OAuth with your application, the application must be registered with the service. This is done by XCaliber when the brand is configured in our platform.
### Client ID
Once the application is registered, the service will issue 'client credentials' in the form of a *client identifier*. The Client ID is a publicly exposed string that is used by the service API to identify the application. In our API the Client ID is the brand code.
## Authorization grant
In the [abstract flow](#abstract-flow) above, the first four steps cover obtaining an authorization grant and access token. The authorization grant type depends on the method used by the application to request authorization, and the grant types supported by our API:
* [Password](authentication/grants.md#password): for normal logins.
* [Activation code](authentication/grants.md#activation-code): for activating user accounts and granting access immediately.
* [Refresh token](authentication/grants.md#refresh-token): for refreshing an access token.
|
JavaScript | UTF-8 | 1,234 | 3.703125 | 4 | [] | no_license | var cand1 = 0;
var cand2 = 0;
var votN = 0;
var votB = 0;
perCand1 = 0;
perCand2 = 0;
perBranco = 0;
perNulo = 0;
var soma = 0;
function votar() {
var voto = parseInt(document.getElementById('numero').value)
switch (voto) {
case 1:
cand1 = cand1 + 1;
alert("Você votou no candidato 1");
break;
case 2:
cand2 = cand2 + 1;
alert("Você votou no candidato 2");
break;
case 3:
votN = votN + 1;
alert("Você votou Nulo");
break;
case 4:
votB = votB + 1;
alert("Você votou em Branco");
break;
}
soma = cand1 + cand2 + votB + votN;
}
function totalVotos() {
let lista = document.getElementById('result');
let ul = "<ul>"
perCand1 = (cand1 / soma) * 100;
ul = ul + `<li>Votos do candidato 1: ${perCand1}%</li>`
perCand2 = (cand2 / soma) * 100;
ul += `<li>Votos do candidato 2: ${perCand2}%</li>`
perBranco = (votB / soma) * 100;
ul += `<li>Voto em branco: ${perBranco}%</li>`
perNulo = (votN / soma) * 100;
ul += `<li>Votos nulo: ${perNulo}%</li>`
ul += "</ul>"
lista.innerHTML = ul;
} |
JavaScript | UTF-8 | 2,625 | 3.203125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | const shuffle = require('../../../../src/common/utils/shuffle');
describe('shuffle', () => {
test('Should return a shuffle array (same size, different order)', async () => {
// arrange
const tArray = [1,2,3,4,5,6,7,8,9];
// act
const result = shuffle(tArray);
// assert
expect(result).toHaveLength(tArray.length);
expect(result).not.toEqual(tArray);
});
test('Should return a shuffle array for array of size 1', async () => {
// arrange
const tArray = [1];
// act
const result = shuffle(tArray);
// assert
expect(result).toHaveLength(tArray.length);
expect(result).toEqual(tArray);
});
test('Should return a shuffle array for array of size 0', async () => {
// arrange
const tArray = [];
// act
const result = shuffle(tArray);
// assert
expect(result).toHaveLength(tArray.length);
expect(result).toEqual(tArray);
});
test('Should return a shuffle only from a starting point', async () => {
// arrange
const tArray = [1,2,3,4,5,6,7,8,9];
// act
const result = shuffle(tArray, 2);
// assert
expect(result).toHaveLength(tArray.length);
expect(result).not.toEqual(tArray);
const fixedOrigin = [...tArray].splice(0, 2);
const shuffledOrigin = [...tArray].splice(2);
const fixedResult= [...result].splice(0, 2);
const shuffledResult = [...result].splice(2);
expect(fixedResult).toHaveLength(fixedOrigin.length);
expect(fixedResult).toEqual(fixedOrigin);
expect(shuffledResult).toHaveLength(shuffledOrigin.length);
expect(shuffledResult).not.toEqual(shuffledOrigin);
});
test('Should return a shuffle only from a starting point to and end point', async () => {
// arrange
const tArray = [1,2,3,4,5,6,7,8,9];
// act
const result = shuffle(tArray, 2, 4);
// assert
expect(result).toHaveLength(tArray.length);
expect(result).not.toEqual(tArray);
const fixedStartOrigin = [...tArray].splice(0, 2);
const fixedEndOrigin = [...tArray].splice(4);
const shuffledOrigin = [...tArray].splice(2, 4);
const fixedStartResult= [...result].splice(0, 2);
const fixedEndResult = [...tArray].splice(4);
const shuffledResult = [...result].splice(2, 4);
expect(fixedStartResult).toHaveLength(fixedStartOrigin.length);
expect(fixedStartResult).toEqual(fixedStartOrigin);
expect(fixedEndResult).toHaveLength(fixedEndOrigin.length);
expect(fixedEndResult).toEqual(fixedEndOrigin);
expect(shuffledResult).toHaveLength(shuffledOrigin.length);
expect(shuffledResult).not.toEqual(shuffledOrigin);
});
}); |
Markdown | UTF-8 | 942 | 2.8125 | 3 | [
"MIT"
] | permissive | # Adversarial Attack on Multimodal Fusion Systems
## Experiment plan 1 Baseline Attack-FGSM
### 1. Description
Simply modify the inputs based on backpropagation using FGSM in the trained model. The FGSM attacking method is given by the following formula

Where $\epsilon$ is the step size for the gradient ascent.
### 2. Realization Plan
- After the model has been trained for enough epochs, we backpropagate the gradient to the input data in all modalities.
- Then we add FGSM purturbation to each sample and find the attack results. We try diffent $\epsilon$ settings and observe how the results change.
- Consider attack each modality only and all 3
- The final results will show here.
- Open a new branch named attack to do so
### 3. Experiment Record
* Nov. 6th 00:30 Finish plan writing
* Nov. 9th 23:20 Finish attacker coding
* Nov. 11th 15:20 Finish attacker debugging and the first attack experiment
|
C++ | UTF-8 | 612 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | #ifndef __NET_SOCKET_H__
#define __NET_SOCKET_H__
#include <string>
using namespace std;
namespace net {
class PacketHead{
unsigned long dataLen;
char *data;
};
class Socket {
public:
Socket();
Socket(int sockfd);
~Socket();
void listen(int port);
void startAccept();
bool connect(string hostname, int port);
void disconnect();
void send(const void *data, int len);
void recv();
protected:
protected:
string _hostname;
int _port;
int _sockfd;
};
}
#endif |
JavaScript | UTF-8 | 166 | 2.875 | 3 | [] | no_license | function validTime(time) {
let hours = time.split(':')[0]
let minutes = time.split(':')[1]
return hours < 24 && minutes < 60
}
console.log(validTime("13:58")) |
JavaScript | UTF-8 | 1,741 | 2.546875 | 3 | [
"MIT"
] | permissive | import Audius from './audius';
import AbstractHTML5AudioPlayer from './abstract_html5_audio_player';
export default class AudiusStreamPlayer extends AbstractHTML5AudioPlayer {
constructor(song, options = {}) {
super();
this.disposed = false;
this.player = document.createElement('audio');
if (options.autoPlay === undefined) options.autoPlay = true;
Audius.getSong(song.originalId)
.then(songUrl => this.startPlayer(songUrl, song, options));
}
startPlayer(songUrl, song, options) {
this.player.setAttribute('class', 'html5audio');
this.player.setAttribute('src', songUrl);
if (song.inLibrary) {
this.player.setAttribute('src', `/offlineaudio/${song.originalId}?src=${encodeURIComponent(songUrl)}`);
} else {
this.player.setAttribute('src', songUrl);
}
if (options.volume) {
this.player.volume = options.volume;
}
if (options.autoPlay) {
this.player.setAttribute('autoplay', 'true');
}
document.body.appendChild(this.player);
this.player.onloadeddata = () => {
if (this.disposed) {
return;
}
if (options.currentTime) {
this.player.currentTime = options.currentTime;
}
if (options.autoPlay) {
try {
this.player.play();
} catch (_) {
// no-op
}
}
}
this.player.onended = AudiusStreamPlayer.endHandler;
this.player.onpause = () => AudiusStreamPlayer.playstateChangeHandler(false);
this.player.onplaying = () => AudiusStreamPlayer.playstateChangeHandler(true);
}
static injectHandlers(playstateChange, onEnded) {
AudiusStreamPlayer.playstateChangeHandler = playstateChange;
AudiusStreamPlayer.endHandler = onEnded;
}
}
|
Python | UTF-8 | 189 | 3.8125 | 4 | [] | no_license | def IsPointInSquare(x,y):
if (x**2+y**2)**0.5 <=(2)**0.5:
return 'Yes'
else:
return 'No'
x = float(input())
y = float(input())
print(IsPointInSquare(x,y))
|
Ruby | UTF-8 | 118 | 2.9375 | 3 | [] | no_license | puts "Comme tu t'apples? "
prenom = gets.chomp
puts "et ton nom? "
nom = gets.chomp
puts "salut #{ prenom } #{ nom }"
|
Rust | UTF-8 | 1,497 | 2.96875 | 3 | [
"BSD-2-Clause"
] | permissive | use crate::math::{Point, Vector};
use na::{RealField, Unit};
/// Kernel functions for performing approximations within the PBF/SPH methods.
pub trait Kernel: Send + Sync {
/// Evaluates the kernel for the given scalar `r` and the reference support length `h`.
fn scalar_apply<N: RealField>(r: N, h: N) -> N;
/// Evaluates the kernel derivative for the given scalar `r` and the reference support length `h`.
fn scalar_apply_diff<N: RealField>(r: N, h: N) -> N;
/// Evaluate the kernel for the given vector.
fn apply<N: RealField>(v: Vector<N>, h: N) -> N {
Self::scalar_apply(v.norm(), h)
}
/// Differential wrt. the coordinates of `v`.
fn apply_diff<N: RealField>(v: Vector<N>, h: N) -> Vector<N> {
if let Some((dir, norm)) = Unit::try_new_and_get(v, N::default_epsilon()) {
*dir * Self::scalar_apply_diff(norm, h)
} else {
Vector::zeros()
}
}
/// Evaluate the kernel for the vector equal to `p1 - p2`.
fn points_apply<N: RealField>(p1: &Point<N>, p2: &Point<N>, h: N) -> N {
Self::apply(p1 - p2, h)
}
/// Differential wrt. the coordinates of `p1`.
fn points_apply_diff1<N: RealField>(p1: &Point<N>, p2: &Point<N>, h: N) -> Vector<N> {
Self::apply_diff(p1 - p2, h)
}
/// Differential wrt. the coordinates of `p2`.
fn points_apply_diff2<N: RealField>(p1: &Point<N>, p2: &Point<N>, h: N) -> Vector<N> {
-Self::apply_diff(p1 - p2, h)
}
}
|
Rust | UTF-8 | 2,217 | 2.828125 | 3 | [
"MIT"
] | permissive | // some code taken and adapted from RLS and cargo
#[derive(Debug, Default, Clone)]
pub struct Version {
pub major: u8,
pub minor: u8,
pub patch: u16,
pub dash_pre: String,
pub code_name: Option<String>,
pub commit_describe: Option<String>,
pub commit_date: Option<String>,
}
impl Version {
pub fn short(&self) -> String {
format!(
"{}.{}.{}{}",
self.major, self.minor, self.patch, self.dash_pre
)
}
pub fn long(&self) -> String {
self.to_string()
}
pub fn is_pre(&self) -> bool {
self.dash_pre != ""
}
pub fn is_dirty(&self) -> bool {
if let Some(describe) = &self.commit_describe {
describe.ends_with("-dirty")
} else {
false
}
}
}
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}.{}.{}{}",
self.major, self.minor, self.patch, self.dash_pre
)?;
let extra_parts: Vec<_> = self
.code_name
.iter()
.chain(self.commit_describe.iter())
.chain(self.commit_date.iter())
.map(String::as_str)
.collect();
if !extra_parts.is_empty() {
write!(f, " ({})", extra_parts.as_slice().join(" "))?;
}
Ok(())
}
}
pub fn get_commit_describe() -> Option<String> {
std::process::Command::new("git")
.args(&[
"describe",
"--dirty",
"--always",
"--match",
"__EXCLUDE__",
"--abbrev=7",
])
.output()
.ok()
.and_then(|r| {
String::from_utf8(r.stdout)
.ok()
.map(|s| s.trim().to_string())
})
}
pub fn get_commit_date() -> Option<String> {
std::process::Command::new("git")
.env("TZ", "UTC")
.args(&["log", "-1", "--date=short-local", "--pretty=format:%cd"])
.output()
.ok()
.and_then(|r| {
String::from_utf8(r.stdout)
.ok()
.map(|s| s.trim().to_string())
})
}
|
Markdown | UTF-8 | 1,268 | 2.875 | 3 | [] | no_license | # The ROS2 OpenCV Camera Package
This is a ROS2 package with a publisher node that uses OpenCV to
publish raw images from a camera onto a topic called `image_raw`.
Since the package is based on OpenCV, any camera that's supported
in OpenCV can be used with this package. And because this package publishes raw camera images, it can be used as the foundation for all computer vision related aspects of your robotics project.
Features :
- publishing of raw camera images
- configurable camera id (you can specify which camera to publish from)
- image viewer subscriber for visualizing the published images
## Topics
- /image_raw - topic for raw image data published as `sensor_msgs.msg import Image`
## Publishers
- image_publisher - publishes raw camera images. `ros2 run opencv_camera image_publisher`
## Subscribers
- image_viewer - subscribes to `/image_raw` and shows the received image frames. `ros2 run opencv_camera image_viewer`
# Installation
- clone this repository into your ROS2 workspace
- cd into the `src` folder of your workspance
- run `colcon build`
- source `setup.bash` and `local_setup.bash`
# Dependencies
This package depends on OpenCV so if that's not already installed on your system, run `pip install opencv-python` to install it.
|
PHP | UTF-8 | 1,463 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateResultsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('results', function (Blueprint $table) {
$table->increments('result_id')->unsigned();
$table->boolean('disqualified')->nullable();
$table->integer('result_time');
$table->integer('result_athlete')->unsigned();
$table->integer('result_competition')->unsigned();
$table->integer('result_distance')->unsigned();
$table->integer('result_sport')->unsigned();
$table->integer('result_multisport')->unsigned()->nullable();
$table->foreign('result_athlete')->references('id')->on('users');
$table->foreign('result_competition')->references('comp_id')->on('competitions');
$table->foreign('result_distance')->references('distance_id')->on('distances');
$table->foreign('result_sport')->references('sport_id')->on('sports');
$table->foreign('result_multisport')->references('sport_id')->on('sports');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('results');
}
}
|
Java | UTF-8 | 2,462 | 1.828125 | 2 | [
"Apache-2.0"
] | permissive | package io.sitoolkit.cv.core.app.crud;
import io.sitoolkit.cv.core.app.functionmodel.FunctionModelService;
import io.sitoolkit.cv.core.domain.classdef.ClassDef;
import io.sitoolkit.cv.core.domain.crud.CrudMatrix;
import io.sitoolkit.cv.core.domain.crud.CrudProcessor;
import io.sitoolkit.cv.core.domain.crud.SqlPerMethod;
import io.sitoolkit.cv.core.domain.project.ProjectManager;
import io.sitoolkit.cv.core.infra.util.JsonUtils;
import java.io.File;
import java.util.List;
import java.util.Optional;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequiredArgsConstructor
public class CrudService {
@NonNull FunctionModelService functionModelService;
@NonNull private CrudProcessor processor;
@NonNull ProjectManager projectManager;
public Optional<CrudMatrix> loadMatrix() {
if (!projectManager.getCurrentProject().existsWorkDir()) {
return Optional.empty();
}
Optional<CrudMatrix> crudMatrixOpt =
JsonUtils.file2obj(projectManager.getCurrentProject().getCrudPath(), CrudMatrix.class);
if (!crudMatrixOpt.isPresent()) {
return generateMatrix();
}
CrudMatrix crudMatrix = crudMatrixOpt.get();
File sqlLogFile = projectManager.getCurrentProject().getSqlLogPath().toFile();
if (!sqlLogFile.exists() || crudMatrix.getSqlLogLastModified() == sqlLogFile.lastModified()) {
return crudMatrixOpt;
}
return generateMatrix();
}
public Optional<CrudMatrix> generateMatrix() {
Optional<List<SqlPerMethod>> sqlPerMethodList = projectManager.getSqlLog();
if (!sqlPerMethodList.isPresent()) {
log.warn("SQL log file not found. If you need a CRUD matrix, please run analyze-sql first.");
return Optional.empty();
}
CrudMatrix methodCrud = processor.buildMatrix(sqlPerMethodList.get());
List<ClassDef> entryPointClasses = functionModelService.getAllEntryPointClasses();
CrudMatrix entryPointCrud = processor.adjustAxis(entryPointClasses, methodCrud);
long lastModified = projectManager.getCurrentProject().getSqlLogPath().toFile().lastModified();
entryPointCrud.setSqlLogLastModified(lastModified);
JsonUtils.obj2file(entryPointCrud, projectManager.getCurrentProject().getCrudPath());
return Optional.of(entryPointCrud);
}
public void analyzeSql() {
projectManager.generateSqlLog();
}
}
|
Markdown | UTF-8 | 1,790 | 2.734375 | 3 | [] | no_license | # Article L264-1
L'exécution de tous travaux qui seraient de nature à compromettre la sécurité du réservoir souterrain ou à troubler son
exploitation est réglementée ou interdite par l'autorité administrative, même à l'égard du propriétaire des terrains, à
l'intérieur du périmètre de stockage et d'un périmètre de protection institué par l'acte accordant la concession. Cet acte
fixe, pour chacun de ces périmètres, la profondeur qu'aucun travail ne peut dépasser sans une autorisation préalable de
l'autorité administrative.
Des servitudes d'utilité publique sont instituées autour des ouvrages nécessaires à l'exploitation d'un stockage souterrain
dans les conditions prévues aux I, II et III de l'article L. 515-8, aux premier, deuxième et troisième alinéas de l'article
L. 515-9, aux articles L. 515-10 et L. 515-11 et au III de l'article L. 515-37 du code de l'environnement. Ces servitudes et
leurs périmètres sont arrêtés par l'autorité administrative.
Les actes de mutation de propriété des biens fonciers et immobiliers mentionnent explicitement, le cas échéant, les
servitudes instituées en application de l'article L. 112-1 du code de l'urbanisme et de la présente section.
**Liens relatifs à cet article**
_Codifié par_:
- Ordonnance n°2011-91 du 20 janvier 2011 - art. Annexe
_Modifié par_:
- ORDONNANCE n°2015-1174 du 23 septembre 2015 - art. 9
_Cite_:
- Code de l'urbanisme - art. L112-1 (VT)
- Code de l'environnement - art. L515-10 (VD)
- Code de l'environnement - art. L515-37
- Code de l'environnement - art. L515-8
- Code de l'environnement - art. L515-9
_Cité par_:
- Code de l'urbanisme - art. (VD)
- Code de l'urbanisme - art. L111-1-5 (VT)
- Code de l'urbanisme - art. L112-2 (VD)
|
Python | UTF-8 | 4,233 | 2.734375 | 3 | [] | no_license | from Queue import Queue
import wave
import math
import numpy as np
import struct
from itertools import izip
import operator
flatten = lambda l: [item for sublist in l for item in sublist]
def getChannel (data, ch):
pairs = zip(data[::2], data[1::2])
ret = []
ret.append(flatten(pairs[0::2]))
ret.append(flatten(pairs[1::2]))
return ''.join(ret[ch])
class SampleSlot :
def __init__(self, filename):
self.CMD_SELSLICE = 0
self.CMD_NSLICES = 1
wav = wave.open (filename, 'rb')
self.len = wav.getnframes()
self.data = getChannel (wav.readframes(self.len/2), 0)
self.sampwidth = wav.getsampwidth()
self.nchannels = wav.getnchannels()
self.rate = wav.getframerate()
self.queue = Queue()
self.spec = 0
self.specs = []
self.fftsize = 128
self.nFFT = self.len / self.fftsize
self.analyze()
wav.close()
self.currentSlice = 0
self.__setSlices(16)
self.__selectSlice(0)
self.index = self.start
self.running = True
self.p0 = 0
self.p1 = 0
def analyze (self):
scale = [2/65535.0]*self.fftsize
offset = [-1]*self.fftsize
window = []
for i in range (0, self.fftsize):
v = math.sin(i*2*math.pi/self.fftsize-math.pi/2)*0.5+0.5
window.append(v)
self.ss = 0
sz = self.fftsize*2
nspecs = int(math.floor(self.len/sz))
self.slices = []
for i in range (0, nspecs):
y = struct.unpack("%dH"%self.fftsize,self.data[i*sz:(i+1)*sz])
y = map(operator.mul, scale, y)
y = map(operator.add, offset, y)
y = map(operator.mul, window, y)
self.slices.append(y)
Y = np.fft.fft(self.slices[i])
self.specs.append(Y)
#print(self.slices[0][0:10])
def __selectSlice (self, slice):
self.currentSlice = slice
self.start = slice*self.sliceLen
self.stop = (slice+1)*self.sliceLen
self.index = self.start
def selectSlice (self, slice):
self.queue.put([self.CMD_SELSLICE, slice])
def __setSlices (self, nSlices):
self.nSlices = nSlices
self.sliceLen = self.len / self.nSlices
self.__selectSlice(self.currentSlice)
def setSlices (self, nSlices):
self.queue.put([self.CMD_NSLICES, nSlices])
def getFrameFFT (self, frame_count):
'''
if (self.queue.empty() == False):
cmd = self.queue.get()
if (cmd[0]==self.CMD_SELSLICE):
self.__selectSlice(cmd[1])
elif (cmd[0]==self.CMD_NSLICES):
self.__setSlices(cmd[1])
self.p1 = self.p0 + 4*frame_count
dat = self.data [self.p0:self.p1]
self.p0 += 4*frame_count
dat = np.fft.ifft(self.specs[self.spec])
self.spec += 1
print(self.spec)
'''
ind = int(math.floor(self.ss))
t = self.ss-ind
self.ss = (self.ss+1)%(len(self.specs)-1)
spec0 = self.specs[ind]
spec1 = self.specs[ind+1]
'''
_spec0 = map(operator.mul,spec0,[t]*len(spec0))
_spec1 = map(operator.mul,spec1,[1-t]*len(spec1))
_spec = map(operator.add, _spec0, _spec1)
'''
_spec = []
for i in range (0,128):
v = (1-t)*spec0[i]+t*spec1[i]
_spec.append (v)
dat = np.fft.ifft (_spec)
dat = map(operator.add, dat, [1]*len(dat))
dat = map(operator.mul, dat, [32668]*len(dat))
#print(dat[0:10])
#dat = np.fft.ifft (spec0)
return struct.pack ("%dH"%len(dat), *dat)
def getFrame (self, frame_count):
'''
if (self.queue.empty() == False):
cmd = self.queue.get()
if (cmd[0]==self.CMD_SELSLICE):
self.__selectSlice(cmd[1])
elif (cmd[0]==self.CMD_NSLICES):
self.__setSlices(cmd[1])
'''
self.p0 = self.index*2
self.p1 = (self.index+frame_count)*2
self.index += frame_count
# stereo to mono
return self.data[self.p0:self.p1]
|
Markdown | UTF-8 | 6,921 | 2.8125 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: "Visual Studio Live: DC"
---

This year I decided to try to attend my first software development conference, and it ended up being [Visual Studio Live](http://vslive.com/) in Washington DC. The conference just concluded yesterday, and now that I'm back after a full day of travel and haven't entirely passed out yet, I wanted to put some impressions down for anyone else considering going to one of their future events.<!--more-->
I wasn't sure what to expect going to a .NET-centric conference. The crowd probably had a higher average age than you'd find at, say, a Ruby on Rails conference, but there was still a wide variety of ages and skill-levels present. It was predominantly male, and at a guess I'd say there the attendees were about 10% female. It was nice to see some female presenters.
The presenters almost always seemed to have a firm grasp on their topic. Many of them have classes on [PluralSight](http://www.pluralsight.com/), and in some cases their material was a condensed version of a longer PluralSight course. I didn't mind this even though I have a PS account, since many of those courses are a major time commitment and this gave me an opportunity to get an overview and see if the topic was even worth my time. There were the occasional tech problems that are bound to pop up at a conference, though hopefully the microphone problems can get ironed out for future events.
Some of the sessions I attended and got the most out of:
* [SignalR](http://www.asp.net/signalr) from [Rachel Appel](http://rachelappel.com/): A library created by Microsoft that allows for a persistant connection over HTTP, using Websockets if the client supports it but falling back to server side events or long-polling if necessary. It certainly looks impressive and I want to play around with it on my own. My concerns are how it resource intensive it becomes with a lot of users. Support for load-balancing via backplaning was mentioned, though I've only seen mention of support for a few storage mechanisms such as Redis. The demo was really well done and would have even allowed for audience participation if it weren't for the hotel WiFi being so intermittent.
* TDD (Test-Driven Development) vs TED (Test-Eventually Development) from [Ben Hoelting](http://www.benhblog.com/): Both are definitely preferable to TND (Test-Never Development). Most of this I had already heard about, but I did learn about [Code Katas](http://osherove.com/tdd-kata-1/), a daily exercise to teach TDD principles and keep up unit testing skills. I may try to introduce this at work as a group exercise, to foster discussion and increase our knowledge. I doubt we'll be switching to a TDD approach anytime soon, but getting better code coverage with tests would get us some nice gains in code stability.
* JavaScript for C# programmers by [Phil Japikse](http://about.me/skimedic): This really opened my eyes to the... interesting... language that is JavaScript. I've mostly played in the shallow end of client-side that is jQuery, so seeing some of the quirks of JavaScript was highly educational. Phil had a very engaging style, even though he said he had received feedback from prior sessions about being "too negative".
* Scrum and TFS from [Richard Hundhausen](https://twitter.com/rhundhausen): My team may be moving to a more Scrummish software development process soon, and even though that may not be using TFS, it was still worthwhile to get an overview of Scrum and the heart of what advantages it brought. The key benefit is getting your software in front of the customer sooner, and since whatever you show them is almost guaranteed to be not what they want (despite what they told you), you might as well do it sooner than later and make things better. Also good to hear about the pitfalls that many companies encounter when trying to implement Scrum, which in the majority of cases seems to be that they put all the right-sounding Scrum nouns in place (sprints, Scrummaster, daily Scrum, etc.) but aren't actually doing the verbs (maintaining a backlog, grooming the backlog, etc.). Richard also mentioned [the Scrum Guides website](http://www.scrumguides.org/) that I will certainly be checking out.
* New features in C# 6.0 from [Mark Michaelis](http://intellitect.com/mark-michaelis/): A lot of cool stuff, and a little bit of heartbreak in the form of features that were once planned but cut due to a lack of time to fully implement. C# 6.0 is nothing groundbreaking, just a lot of syntactical sugar that should make for cleaner code in a lot of cases. The null conditional will reduce null checks that often take up many lines, though I hope we can refrain from reducing methods to a single unintelligible line. Mark really seemed to know his stuff and pointed out how the [open sourcing of the .NET compiler](https://roslyn.codeplex.com/) really means that it's much more possible now to influence the design of future C# features.

The monuments tour Wednesday night was also fun, led by a funny and informative guide. We weren't able to stop in any one spot for long, so I definitely want to go back to DC and do the touristy thing. The conference venue was fine, and the area of DC worked out well with some good restaurants nearby.
Should you go to Visual Studio Live? I'd say the topics skewed towards beginner level to mid-level developer. Many were overviews of the technology, though there were some intermediate "best practices" type presentations. I'd say look at the sessions list, see if there are topics you've wanting to dig into or more specific talks on the areas that you work with. If you're already a senior software engineer and want to explore and evaluate an individual technology or technique, devoting some time to diving into a related book or a PluralSight course may be more useful. I can't speak to the all-day workshops conducted on the first day since I skipped those.
I am glad that there were dedicated networking sessions, both the lunches and after the talks concluded on the first day. I was able to meet other .NET developers from around the country doing a lot of different types of work.
Some of the impressions I heard from my fellow attendees were that they should try to have fewer but more defined "tracks" where the first day has an intro talk, then the second and third day has more advanced-level presentations. This may be difficult with the varied interests of the attendees, but that might present an opportunity to focus each VS Live event on different topics such as "Web", "Sharepoint", "Databases", and so on.
Overall I was happy with the conference. Nothing totally shook up the way I'll be writing software, but I was able to learn a lot of new things that I'll be able to take back to my team and make our product better.
|
Shell | UTF-8 | 1,595 | 3.328125 | 3 | [
"MIT"
] | permissive | # This script runs the (potentially parallel) algorithm to generate a 3D mesh and 1D fiber meshes for the biceps muscle.
# Input is a representation of the biceps surface which is already given in the input directory.
# Output is a *.bin file that contains the points of the fibers.
# parameters for this script
use_neumann_bc=false # (false,true) set to false to use Dirichlet BC (which is better)
improve_mesh=true # (false,true) if the Laplacian smoothing and fixing of invalid quadrilaterals should be enabled
method=splines # (splines,stl) which input to use, either splines = use "biceps_splines.stl" or stl = use "biceps.surface.pickle"
refinement=1 # (0,1,2,...) how often to refine the mesh for the Laplace problem, 1=twice as many elements per direction, 2=4x as many elements per direction
nproc=1 # (1,8,64,...) number of processes, should be 8^i
m=2 # (0,1,2,...) parameter m of fine grid fibers, a higher value means more fibers, use "compute_sizes.py" to get an estimate
# clear output directory
rm -rf out
# run program with MPI
mpirun -n $nproc --oversubscribe ./generate ../settings_generate.py \
--input_filename_or_splines_or_stl $method \
--refinement_factor $refinement \
--improve_mesh $improve_mesh \
--use_neumann_bc $use_neumann_bc \
-m $m
# run mesh_evaluate_quality on created files
for file in `ls -rt *.bin | head -n 2`; do
echo ""
mesh_evaluate_quality.py $file
done
# rename output directory
mv out out_${method}_${refinement}_${improve_mesh}_${use_neumann_bc}_m${m}
|
C++ | UTF-8 | 405 | 3.34375 | 3 | [] | no_license | #include<stdio.h>
int strlen(const char* str){
int i=0;
while(str[i]!='\0')
i++;
return i;
}
void sub(char *dest,char *src,char ch){
int length=strlen(src);
int j=0;
for (int i = 0; i <= length; i++)
{
if(src[i]!=ch){
dest[j]=src[i];
j++;
}
else{
dest[j]=' ';
j++;
}
}
}
int main(){
char *src="Hello,I'm,Yuchul";
char dest[128];
sub(dest,src,',');
printf("%s\n",dest);
} |
TypeScript | UTF-8 | 3,331 | 2.59375 | 3 | [
"MIT"
] | permissive | /**
* Copyright (c) 2018 Bitbloq (BQ)
*
* License: MIT
*
* long description for the file
*
* @summary short description for the file
* @author David García <https://github.com/empoalp>, Alberto Valero <https://github.com/avalero>
*
* Created at : 2018-11-16 17:30:44
* Last modified : 2019-01-31 10:37:34
*/
import { isEqual } from "lodash";
import Object3D from "./Object3D";
import * as THREE from "three";
import ObjectsCommon from "./ObjectsCommon";
import {
IPrimitiveObjectJSON,
IViewOptions,
OperationsArray
} from "./Interfaces";
export default class PrimitiveObject extends Object3D {
protected parameters: object;
constructor(viewOptions: IViewOptions, operations: OperationsArray) {
super(viewOptions, operations);
}
public toJSON(): IPrimitiveObjectJSON {
const json: IPrimitiveObjectJSON = {
...super.toJSON(),
parameters: this.parameters
};
return json;
}
/**
* For primitive objects. Cube, Cylinder, etc.
* For CompoundObjects find function in CompoundObjects Class
*/
public updateFromJSON(
object: IPrimitiveObjectJSON,
fromParent: boolean = false
) {
if (this.id !== object.id) {
throw new Error("Object id does not match with JSON id");
}
const vO = {
...ObjectsCommon.createViewOptions(),
...object.viewOptions
};
this.setParameters(object.parameters);
this.setOperations(object.operations);
this.setViewOptions(vO);
if (
this.meshUpdateRequired ||
this.pendingOperation ||
this.viewOptionsUpdateRequired
) {
// if has no parent, update mesh, else update through parent
const obj: ObjectsCommon | undefined = this.getParent();
if (obj && !fromParent) {
obj.updateFromJSON(obj.toJSON());
} else {
this.meshPromise = this.computeMeshAsync();
}
}
}
public async computeMeshAsync(): Promise<THREE.Mesh> {
this.meshPromise = new Promise(async (resolve, reject) => {
try {
if (this.meshUpdateRequired) {
const geometry: THREE.Geometry = this.getGeometry();
this.mesh = new THREE.Mesh(geometry);
this.meshUpdateRequired = false;
this.applyViewOptions();
await this.applyOperationsAsync();
}
if (this.pendingOperation) {
await this.applyOperationsAsync();
}
if (this.viewOptionsUpdateRequired) {
this.applyViewOptions();
}
resolve(this.mesh);
} catch (e) {
reject(e);
throw new Error(`Cannot compute Mesh: ${e}`);
}
});
return this.meshPromise as Promise<THREE.Mesh>;
}
protected computeMesh(): void {
try {
const geometry: THREE.Geometry = this.getGeometry();
this.mesh = new THREE.Mesh(geometry);
this.applyOperations();
this.applyViewOptions();
this.setMesh(this.mesh);
} catch (e) {
throw new Error(`Cannot compute Mesh: ${e}`);
}
}
protected setParameters(parameters: object): void {
if (!this.parameters) {
this.parameters = { ...parameters };
this.meshUpdateRequired = true;
return;
}
if (!isEqual(parameters, this.parameters)) {
this.parameters = { ...parameters };
this.meshUpdateRequired = true;
return;
}
}
}
|
Python | UTF-8 | 540 | 2.640625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | import pandas as pd
import matplotlib.pyplot as plt
from mpldatacursor import datacursor
csv_GAN=pd.read_csv('Loss_G_GAN.csv')
csv_L1=pd.read_csv('Loss_G_L1.csv')
fig, ax = plt.subplots()
lines = ax.plot(csv_GAN.columns.astype(int),csv_GAN.get_values().reshape(len(csv_GAN.columns),), '*-')
datacursor(lines)
plt.grid()
plt.title('GAN Loss')
plt.show()
# plt.figure()
# plt.stem(csv_L1.columns.astype(int),csv_L1.get_values().reshape(len(csv_GAN.columns),), '*-')
# plt.grid()
# plt.title('L1 Loss')
#
# plt.show() |
Java | UTF-8 | 2,006 | 1.898438 | 2 | [] | no_license | package com.xiaodou.server.mapi.domain;
public class OfficialInfo {
private String realName;
private String gender;
private String phoneNum;
private String admissionCardCode;
private String identificationCardCode;
private String majorCode;
private String majorName;
private String courseCode;
private String courseName;
private String merchant;
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIdentificationCardCode() {
return identificationCardCode;
}
public void setIdentificationCardCode(String identificationCardCode) {
this.identificationCardCode = identificationCardCode;
}
public String getAdmissionCardCode() {
return admissionCardCode;
}
public void setAdmissionCardCode(String admissionCardCode) {
this.admissionCardCode = admissionCardCode;
}
public String getMajorCode() {
return majorCode;
}
public void setMajorCode(String majorCode) {
this.majorCode = majorCode;
}
public String getMajorName() {
return majorName;
}
public void setMajorName(String majorName) {
this.majorName = majorName;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
}
|
PHP | UTF-8 | 999 | 2.671875 | 3 | [] | no_license | <?php namespace BCD\Forms;
use Laracasts\Validation\FormValidator;
class RegisterGroupForm extends FormValidator {
/**
* Validation rules for registering a participant
*
* @var array
*/
protected $rules = [
'registration_type' => 'required',
'first_name_1' => 'required|max:60|min:2',
'middle_name_1' => 'required|max:60|min:2',
'last_name_1' => 'required|max:60|min:2',
'birthdate_1' => 'required|date',
'sex_1' => 'required',
'race_shirt_size_1' => 'required|max:5|min:1',
'first_name_2' => 'required|max:60|min:2',
'middle_name_2' => 'required|max:60|min:2',
'last_name_2' => 'required|max:60|min:2',
'birthdate_2' => 'required|date',
'sex_2' => 'required',
'race_shirt_size_2' => 'required|max:5|min:1',
'first_name_3' => 'required|max:60|min:2',
'middle_name_3' => 'required|max:60|min:2',
'last_name_3' => 'required|max:60|min:2',
'birthdate_3' => 'required|date',
'sex_3' => 'required',
'race_shirt_size_3' => 'required|max:5|min:1'
];
} |
Java | UTF-8 | 1,607 | 3.6875 | 4 | [] | no_license | package com.leetcode.challenges.march;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DollEnvelopes {
public int maxEnvelopes(int[][] envelopes) {
// l'entrée c'est un matrice de n lignes et 2 colonnes
// je calcule la surface d'un envelope
// je déclare un objet de type enveloppe qui a pour attributs son height et width ainsi son surface
// j'initialise une liste des objets envelope et je la trie suivant le surface de l'objet
// je parcours cette liste et je verifie la condition de height et width et j'incrémente un compteur
if (envelopes == null || envelopes.length == 0) {
return 0;
}
if (envelopes.length == 1) {
return 1;
}
List<Envelope> tmpEnvelopes = new ArrayList<>();
for (int i = 0; i < envelopes.length; i++) {
Envelope env = new Envelope();
int j = 0;
while (j < 2) {
if (j == 0) {
env.width = envelopes[i][j];
} else if (j == 1) {
env.height = envelopes[i][j];
}
j++;
}
env.surface = env.height * env.width;
tmpEnvelopes.add(env);
}
Collections.sort(tmpEnvelopes);
int count = 1;
Envelope firstEnv = tmpEnvelopes.get(0);
for (int i = 1; i < tmpEnvelopes.size(); i++) {
if (firstEnv.height < tmpEnvelopes.get(i).height && firstEnv.width < tmpEnvelopes.get(i).width) {
count++;
firstEnv = tmpEnvelopes.get(i);
}
}
return count;
}
}
class Envelope implements Comparable<Envelope> {
int height;
int width;
int surface;
@Override
public int compareTo(Envelope otherEnv) {
return Integer.compare(this.surface, otherEnv.surface);
}
}
|
C++ | UTF-8 | 997 | 3.125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
template<typename T>
class Graph{
map<T,vector<T>> adjList;
public:
void addEdge(T x, T y){
adjList[x].push_back(y);
adjList[y].push_back(x);
}
void dfsHelper(T src,map<T,bool> &visited){
cout<<src<<" ";
visited[src] = true;
for(auto child: adjList[src]){
if(!visited[child]){
dfsHelper(child,visited);
}
}
}
void dfs(){
map<T,bool> visited;
for(auto edge : adjList){
T node = edge.first;
visited[node] = false;
}
int cnt = 0;
for(auto edge: adjList){
T node = edge.first;
if(!visited[node]){
cout<<"Connected component "<<cnt<<" "<<endl;
dfsHelper(node,visited);
cnt++;
cout<<endl;
}
}
}
};
int main(){
Graph<int> g;
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,3);
g.addEdge(1,4);
g.addEdge(2,5);
g.addEdge(5,6);
g.addEdge(5,7);
g.addEdge(8,9);
g.addEdge(8,10);
g.addEdge(9,10);
g.addEdge(11,12);
g.dfs();
}
|
C++ | UTF-8 | 4,443 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef PQTABLE_PQ_TABLE_H
#define PQTABLE_PQ_TABLE_H
// PQTable
// Y. Matsui, T. Yamasaki, and K. Aizawa, "PQTable: Non-exhaustive Fast Search for
// Product-quantized Codes using Hash Tables", arXiv 2017
//
// Usage:
// vector<vector<float>> train_vecs = /* set vec */
// vector<vector<float>> base_vecs = /* set vec */
// vector<vector<float>> query_vecs = /* set vec */
//
// int M = 4; /* The number of sub-vector */
// pqtable::PQ pq(pqtable::PQ::Learn(train_vecs, M)); // Train product quantizer
// pqtable::UcharVecs codes = pq.Encode(base_vecs); // Encode vectors
//
// /* PQTable is instantiated with the codewords and the PQ-codes. */
// /* The best "T" is selected automaticallly. If T=1, the sinle-PQTable is
// /* created. Otherwise, multi-PQTable is created.
// pqtable::PQTable tbl(pq.GetCodewords(), codes);
//
// /* Neareset neighbor search for 0-th query vector. */
// /* score.first is the nearest-id. score.second is the distance between */
// /* the 0-th query and the nearest-id-th base vec. */
// pair<int, float> score = tbl.Query(query_vecs[0]);
//
// /* Or, you can do top-k search */
// /* scores[0] is the nearest result, and scores[1] is the second nearest result. */
// int top_k = 3;
// vector<pair<int, float>> scores = tbl.Query(query_vecs[0], top_k);
#include <opencv2/opencv.hpp>
#include <unordered_map>
#include "pq.h"
#include "code_to_key.h"
#include "pq_key_generator.h"
#include "sparse_hashtable/sparse_hashtable.h"
#include "sparse_hashtable/helper_sht.h"
namespace pqtable {
class I_PQTable // interface. abstract basic class.
{
public:
virtual ~I_PQTable() {}
virtual std::pair<int, float> Query(const std::vector<float> &query) = 0; // for top-1 search
virtual std::vector<std::pair<int, float> > Query(const std::vector<float> &query, int top_k) = 0; // for top-k search
virtual void Write(std::string dir_path) = 0;
};
class PQSingleTable: public I_PQTable
{
public:
PQSingleTable(const std::vector<PQ::Array> &codewords,
const UcharVecs &pq_codes);
PQSingleTable(std::string dir_path); // Read from saved files (a dir contains files)
// Querying function.
std::pair<int, float> Query(const std::vector<float> &query); // fot top-1
std::vector<std::pair<int, float> > Query(const std::vector<float> &query, int top_k); // for top-k
// IO
void Write(std::string dir_path);
private:
PQSingleTable();
PQ m_PQ;
// Table
SparseHashtable m_sHashTable;
};
class PQMultiTable: public I_PQTable
{
public:
PQMultiTable(const std::vector<PQ::Array> &codewords,
const UcharVecs &pq_codes,
int T);
PQMultiTable(std::string dir_path);
std::pair<int, float> Query(const std::vector<float> &query);
std::vector<std::pair<int, float> > Query(const std::vector<float> &query, int top_k);
// IO
void Write(std::string dir_path);
static int OptimalT(int B, int N) {
return std::pow(2, std::round(std::log2(B / std::log2(N))));
}
private:
PQMultiTable();
int m_T;
std::vector<std::vector<PQ::Array> > m_codewordsEach; // [t][m][ks][ds]
std::vector<SparseHashtable> m_sHashTableEach; // [t]
PQ m_PQ;
UcharVecs m_codes; // PQ code itself
// Helper function. Divide codewords into codewords_each
void DivideCodewords(const std::vector<PQ::Array> &codewords,
int T,
std::vector<std::vector<PQ::Array> > *codewords_each);
};
// Proxy class. This class can automatically select the best table from singletable of multitable
class PQTable{
public:
PQTable(const std::vector<PQ::Array> &codewords,
const UcharVecs &pq_codes,
int T = -1); // If T == -1, then the best T is automatically selected
PQTable(std::string dir_path); // Read from the saved dir
~PQTable();
std::pair<int, float> Query(const std::vector<float> &query);
std::vector<std::pair<int, float> > Query(const std::vector<float> &query, int top_k);
// IO
void Write(std::string dir_path);
private:
PQTable(); // Default construct is prohibited
PQTable(const PQTable &); // In current implementation, copy is prohibited
const PQTable &operator =(const PQTable &); // In current implementation, copy is prohibited
I_PQTable *m_table;
};
}
#endif // PQTABLE_PQ_TABLE_H
|
C# | UTF-8 | 1,732 | 2.59375 | 3 | [
"MIT"
] | permissive | using System;
using System.Linq;
using System.Linq.Expressions;
namespace Atlassian.Jira.Linq
{
public class JiraQueryProvider : IQueryProvider
{
private readonly IJqlExpressionVisitor _translator;
private readonly IIssueService _issues;
public JiraQueryProvider(IJqlExpressionVisitor translator, IIssueService issues)
{
_translator = translator;
_issues = issues;
}
public IQueryable<T> CreateQuery<T>(Expression expression)
{
return new JiraQueryable<T>(this, expression);
}
public IQueryable CreateQuery(Expression expression)
{
throw new NotImplementedException();
}
public T Execute<T>(Expression expression)
{
bool isEnumerable = (typeof(T).Name == "IEnumerable`1");
return (T)this.Execute(expression, isEnumerable);
}
public object Execute(Expression expression)
{
return Execute(expression, true);
}
private object Execute(Expression expression, bool isEnumerable)
{
var jql = _translator.Process(expression);
var temp = _issues.GetIssuesFromJqlAsync(jql.Expression, jql.NumberOfResults, jql.SkipResults ?? 0).Result;
IQueryable<Issue> issues = temp.AsQueryable();
if (isEnumerable)
{
return issues;
}
else
{
var treeCopier = new ExpressionTreeModifier(issues);
Expression newExpressionTree = treeCopier.Visit(expression);
return issues.Provider.Execute(newExpressionTree);
}
}
}
}
|
Python | UTF-8 | 3,181 | 3.953125 | 4 | [] | no_license | import numpy
'''
Experiment performed 10000 times
'''
x = numpy.zeros((10000,2))
y = numpy.zeros((10000,3))
z = numpy.zeros((10000,5))
'''
Convert this problem from 2-D to 1-D representation
Each point in 2-D mapped to a line segment 0 to 2*pi
Random selections of points from the circumference
'''
for i in range(10000):
x[i] = numpy.random.uniform(0,2*numpy.pi,2)
y[i] = numpy.random.uniform(0,2*numpy.pi,3)
z[i] = numpy.random.uniform(0,2*numpy.pi,5)
'''
Store number of successful experiments
'''
count_2_yes = 0
count_3_yes = 0
count_5_yes = 0
'''
For n=2
Strategy used
Distance between 2 points should be less than pi
'''
for i in range(10000):
if (max(x[i]) - min (x[i]) <= numpy.pi) or 2*numpy.pi - max(x[i]) + min(x[i]) <= numpy.pi:
count_2_yes+=1
'''
For n=3
Strategy used
1. Make a semicircle with each point as a starting point
2. Identify the endpoints of the semicircle with that point
3. Check if other points lie within these end points
4. If atleast 1 point satisfies Step 2 and 3, then semicircle is possible
containing all points
'''
for i in range(10000):
valid_semi_circle = False
for j in range(3):
end_point = []
count = 0
if y[i][j] <= numpy.pi:
end_point.append(y[i][j] + numpy.pi)
else:
end_point.append(2*numpy.pi)
end_point.append(y[i][j] - numpy.pi)
for k in range(3):
if len(end_point) == 1:
if y[i][k] >= y[i][j] and y[i][k] <= end_point[0]:
count+=1
else:
if (y[i][k] >= y[i][j] and y[i][k] <= end_point[0]) or (y[i][k] >=0 and y[i][k] <= end_point[1]):
count+=1
if count == 3:
valid_semi_circle = True
if valid_semi_circle:
count_3_yes+=1
'''
For n=5
Strategy used
1. Make a semicircle with each point as a starting point
2. Identify the endpoints of the semicircle with that point
3. Check if other points lie within these end points
4. If atleast 1 point satisfies Step 2 and 3, then semicircle is possible
containing all points
'''
for i in range(10000):
valid_semi_circle = False
for j in range(5):
end_point = []
count = 0
if z[i][j] <= numpy.pi:
end_point.append(z[i][j] + numpy.pi)
else:
end_point.append(2*numpy.pi)
end_point.append(z[i][j] - numpy.pi)
for k in range(5):
if len(end_point) == 1:
if z[i][k] >= z[i][j] and z[i][k] <= end_point[0]:
count+=1
else:
if (z[i][k] >= z[i][j] and z[i][k] <= end_point[0]) or (z[i][k] >=0 and z[i][k] <= end_point[1]):
count+=1
if count == 5:
valid_semi_circle = True
if valid_semi_circle:
count_5_yes+=1
print("Probability for 2 points in a semi-circle", count_2_yes/10000)
print("Probability for 3 points in a semi-circle", count_3_yes/10000)
print("Probability for 5 points in a semi-circle", count_5_yes/10000)
|
Markdown | UTF-8 | 3,372 | 2.625 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: Access from Container Instances
description: Learn how to provide access to images in your private container registry from Azure Container Instances by using an Azure Active Directory service principal.
ms.topic: article
ms.custom: devx-track-azurecli
author: tejaswikolli-web
ms.author: tejaswikolli
ms.date: 10/11/2022
---
# Authenticate with Azure Container Registry from Azure Container Instances
You can use an Azure Active Directory (Azure AD) service principal to provide access to your private container registries in Azure Container Registry.
In this article, you learn to create and configure an Azure AD service principal with *pull* permissions to your registry. Then, you start a container in Azure Container Instances (ACI) that pulls its image from your private registry, using the service principal for authentication.
## When to use a service principal
You should use a service principal for authentication from ACI in **headless scenarios**, such as in applications or services that create container instances in an automated or otherwise unattended manner.
For example, if you have an automated script that runs nightly and creates a [task-based container instance](../container-instances/container-instances-restart-policy.md) to process some data, it can use a service principal with pull-only permissions to authenticate to the registry. You can then rotate the service principal's credentials or revoke its access completely without affecting other services and applications.
Service principals should also be used when the registry [admin user](container-registry-authentication.md#admin-account) is disabled.
[!INCLUDE [container-registry-service-principal](../../includes/container-registry-service-principal.md)]
## Authenticate using the service principal
To launch a container in Azure Container Instances using a service principal, specify its ID for `--registry-username`, and its password for `--registry-password`.
```azurecli-interactive
az container create \
--resource-group myResourceGroup \
--name mycontainer \
--image mycontainerregistry.azurecr.io/myimage:v1 \
--registry-login-server mycontainerregistry.azurecr.io \
--registry-username <service-principal-ID> \
--registry-password <service-principal-password>
```
>[!Note]
> We recommend running the commands in the most recent version of the Azure Cloud Shell. Set `export MSYS_NO_PATHCONV=1` for running on-perm bash environment.
## Sample scripts
You can find the preceding sample scripts for Azure CLI on GitHub, as well versions for Azure PowerShell:
* [Azure CLI][acr-scripts-cli]
* [Azure PowerShell][acr-scripts-psh]
## Next steps
The following articles contain additional details on working with service principals and ACR:
* [Azure Container Registry authentication with service principals](container-registry-auth-service-principal.md)
* [Authenticate with Azure Container Registry from Azure Kubernetes Service (AKS)](../aks/cluster-container-registry-integration.md)
<!-- IMAGES -->
<!-- LINKS - External -->
[acr-scripts-cli]: https://github.com/Azure/azure-docs-cli-python-samples/tree/master/container-registry/create-registry/create-registry-service-principal-assign-role.sh
[acr-scripts-psh]: https://github.com/Azure/azure-docs-powershell-samples/tree/master/container-registry
<!-- LINKS - Internal -->
|
Swift | UTF-8 | 433 | 3.03125 | 3 | [] | no_license |
import Foundation
import SDWebImage
extension UIImageView {
enum UseType {
case assist
}
func nc_typeImage(url: String, type: UseType = .assist) {
nc_imageSet(url: url, placeImage: nil)
}
func nc_imageSet(url: String,placeImage: UIImage? = nil) {
let rurl = URL(string: url)
self.sd_setImage(with: rurl, placeholderImage: placeImage)
}
}
|
Swift | UTF-8 | 4,033 | 2.65625 | 3 | [
"MIT"
] | permissive | //
// NextLevel+Foundation.swift
// NextLevel (http://github.com/NextLevel/)
//
// Copyright (c) 2016-present patrick piemonte (http://patrickpiemonte.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import AVFoundation
// MARK: - Comparable
extension Comparable {
public func clamped(to limits: ClosedRange<Self>) -> Self {
min(max(self, limits.lowerBound), limits.upperBound)
}
}
// MARK: - Data
extension Data {
/// Outputs a `Data` object with the desired metadata dictionary
///
/// - Parameter metadata: metadata dictionary to be added
/// - Returns: JPEG formatted image data
public func jpegData(withMetadataDictionary metadata: [String: Any]) -> Data? {
var imageDataWithMetadata: Data?
if let source = CGImageSourceCreateWithData(self as CFData, nil),
let sourceType = CGImageSourceGetType(source) {
let mutableData = NSMutableData()
if let destination = CGImageDestinationCreateWithData(mutableData, sourceType, 1, nil) {
CGImageDestinationAddImageFromSource(destination, source, 0, metadata as CFDictionary?)
let success = CGImageDestinationFinalize(destination)
if success == true {
imageDataWithMetadata = mutableData as Data
} else {
print("could not finalize image with metadata")
}
}
}
return imageDataWithMetadata
}
}
// MARK: - Date
extension Date {
static let dateFormatter: DateFormatter = iso8601DateFormatter()
fileprivate static func iso8601DateFormatter() -> DateFormatter {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
return formatter
}
// http://nshipster.com/nsformatter/
// http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
public func iso8601() -> String {
Date.iso8601DateFormatter().string(from: self)
}
}
// MARK: - FileManager
extension FileManager {
/// Returns the available user designated storage space in bytes.
///
/// - Returns: Number of available bytes in storage.
public class func availableStorageSpaceInBytes() -> UInt64 {
do {
if let lastPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last {
let attributes = try FileManager.default.attributesOfFileSystem(forPath: lastPath)
if let freeSize = attributes[FileAttributeKey.systemFreeSize] as? UInt64 {
return freeSize
}
}
} catch {
print("could not determine user attributes of file system")
return 0
}
return 0
}
}
|
C++ | UTF-8 | 702 | 3.546875 | 4 | [] | no_license | class Solution{
public:
// arr: input array
// num: size of array
//Function to find maximum circular subarray sum.
int circularSubarraySum(int arr[], int num){
int max = arr[0];
int max_1 = arr[0];
int first_ele_pos = 0;
for (int i = 1; i < 2 * (num - 1); i++) {
int index = (i > num - 1) ? i % num : i;
if (first_ele_pos == index) {
index = first_ele_pos + 1;
index = (index > num - 1) ? index % num : index;
i = index;
max_1 = arr[index];
first_ele_pos = index;
continue;
}
if (max_1 > 0)
max_1 += arr[index];
else {
max_1 = arr[index];
first_ele_pos = index;
}
if (max_1 > max)
max = max_1;
}
return max;
}
};
|
Java | UTF-8 | 462 | 1.664063 | 2 | [] | no_license | package org.robins.io.pubnub.api.domain;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Integration {
@SerializedName("type")
@Expose
public String type;
@SerializedName("source")
@Expose
public String source;
@SerializedName("channel")
@Expose
public String channel;
@SerializedName("channel_id")
@Expose
public String channelId;
} |
Python | UTF-8 | 2,257 | 2.5625 | 3 | [] | no_license | import os
import sys
import pandas as pd
ope = os.path.exists
opj = os.path.join
def read_and_format(path, source):
print(f"processing {path} {source}")
t = pd.read_csv(path, sep="\t", index_col="recordingmbid")
all_tags = []
genre_columns = [c for c in t.columns if "genre" in c]
for ts in zip(*[t[key] for key in genre_columns]):
all_tags.append([g.split("---")[-1] for g in ts if isinstance(g, str)])
t[source] = all_tags
for key in genre_columns:
del t[key]
return t
if __name__ == "__main__":
acoustic_brainz_dir = sys.argv[1]
assert ope(opj(acoustic_brainz_dir, "recordingmbid2artistmbid.tsv"))
sources = ["discogs", "lastfm", "tagtraum"]
files = []
tables = []
for t in sources:
files.append((opj(acoustic_brainz_dir, f"ab_mediaeval_train_{t}.tsv"), t))
files.append((opj(acoustic_brainz_dir, f"ab_mediaeval_val_{t}.tsv"), t))
for f in files:
assert ope(f[0])
artist_mapping = pd.read_csv(opj(acoustic_brainz_dir, "recordingmbid2artistmbid.tsv"), sep="\t",
index_col="recordingmbid")
table_per_source = {}
for f in files:
table = read_and_format(*f)
if f[1] not in table_per_source:
table_per_source[f[1]] = table
else:
table_per_source[f[1]] = pd.concat([table_per_source[f[1]], table])
all_tables = list(table_per_source.values())
final = all_tables[0]
for t in all_tables[1:]:
print(t.columns)
final = final.join(t, lsuffix="_left", rsuffix="_right", how="outer")
print(final.columns)
final["releasegroupmbid"] = final["releasegroupmbid_left"]
final["releasegroupmbid"][final["releasegroupmbid"].isnull()] = final["releasegroupmbid_right"]
del final["releasegroupmbid_left"]
del final["releasegroupmbid_right"]
nb = len(final)
final = final.join(artist_mapping, how="inner")
rem = len(final)
if rem < nb:
print("WARNING: some recordingmbids haven't been matched to an artistmbid")
final = final[["releasegroupmbid", "artistmbid", "discogs", "lastfm", "tagtraum"]]
final.to_csv(opj(acoustic_brainz_dir, "translation_dataset_all.tsv"), sep="\t")
|
Java | UTF-8 | 147,432 | 1.5 | 2 | [] | no_license | package gov.noaa.nws.ncep.viz.resourceManager.ui.createRbd;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EventObject;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnViewerEditor;
import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent;
import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerEditor;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PlatformUI;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.viz.core.VizApp;
import com.raytheon.uf.viz.core.drawables.AbstractRenderableDisplay;
import com.raytheon.uf.viz.core.drawables.ResourcePair;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.rsc.AbstractResourceData;
import com.raytheon.uf.viz.core.rsc.ResourceList;
import com.raytheon.uf.viz.core.rsc.ResourceProperties;
import com.raytheon.uf.viz.core.rsc.capabilities.Capabilities;
import com.raytheon.viz.ui.UiPlugin;
import com.raytheon.viz.ui.editor.AbstractEditor;
import gov.noaa.nws.ncep.viz.common.area.AreaMenus.AreaMenuItem;
import gov.noaa.nws.ncep.viz.common.area.AreaName;
import gov.noaa.nws.ncep.viz.common.area.AreaName.AreaSource;
import gov.noaa.nws.ncep.viz.common.area.IGridGeometryProvider.ZoomLevelStrings;
import gov.noaa.nws.ncep.viz.common.area.PredefinedArea;
import gov.noaa.nws.ncep.viz.common.customprojection.GempakProjectionValuesUtil;
import gov.noaa.nws.ncep.viz.common.display.INcPaneID;
import gov.noaa.nws.ncep.viz.common.display.INcPaneLayout;
import gov.noaa.nws.ncep.viz.common.display.NcDisplayName;
import gov.noaa.nws.ncep.viz.common.display.NcDisplayType;
import gov.noaa.nws.ncep.viz.common.ui.color.ColorButtonSelector;
import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor;
import gov.noaa.nws.ncep.viz.resourceManager.timeline.GraphTimelineControl;
import gov.noaa.nws.ncep.viz.resourceManager.timeline.TimelineControl;
import gov.noaa.nws.ncep.viz.resourceManager.timeline.TimelineControl.IDominantResourceChangedListener;
import gov.noaa.nws.ncep.viz.resourceManager.timeline.cache.TimeSettingsCacheManager;
import gov.noaa.nws.ncep.viz.resourceManager.ui.createRbd.ResourceSelectionControl.IResourceSelectedListener;
import gov.noaa.nws.ncep.viz.resources.AbstractNatlCntrsRequestableResourceData;
import gov.noaa.nws.ncep.viz.resources.INatlCntrsResourceData;
import gov.noaa.nws.ncep.viz.resources.attributes.EditResourceAttrsDialogFactory;
import gov.noaa.nws.ncep.viz.resources.groupresource.GroupResourceData;
import gov.noaa.nws.ncep.viz.resources.manager.AbstractRBD;
import gov.noaa.nws.ncep.viz.resources.manager.AreaMenuTree;
import gov.noaa.nws.ncep.viz.resources.manager.AttributeSet;
import gov.noaa.nws.ncep.viz.resources.manager.NcMapRBD;
import gov.noaa.nws.ncep.viz.resources.manager.ResourceBndlLoader;
import gov.noaa.nws.ncep.viz.resources.manager.ResourceDefinition;
import gov.noaa.nws.ncep.viz.resources.manager.ResourceDefnsMngr;
import gov.noaa.nws.ncep.viz.resources.manager.ResourceFactory;
import gov.noaa.nws.ncep.viz.resources.manager.ResourceFactory.ResourceSelection;
import gov.noaa.nws.ncep.viz.resources.manager.ResourceName;
import gov.noaa.nws.ncep.viz.resources.manager.RscBundleDisplayMngr;
import gov.noaa.nws.ncep.viz.resources.manager.SpfsManager;
import gov.noaa.nws.ncep.viz.resources.time_match.NCTimeMatcher;
import gov.noaa.nws.ncep.viz.ui.display.NatlCntrsEditor;
import gov.noaa.nws.ncep.viz.ui.display.NcDisplayMngr;
import gov.noaa.nws.ncep.viz.ui.display.NcEditorUtil;
import gov.noaa.nws.ncep.viz.ui.display.NcPaneID;
import gov.noaa.nws.ncep.viz.ui.display.NcPaneLayout;
/**
* Creates the Resource Manager's Data Selection dialog.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 01/26/10 #226 Greg Hull Broke out and refactored from ResourceMngrDialog
* 04/27/10 #245 Greg Hull Added Apply Button
* 06/13/10 #273 Greg Hull RscBndlTemplate->ResourceSelection, use ResourceName
* 07/14/10 #273 Greg Hull remove Select Overlay list (now in ResourceSelection)
* 07/21/10 #273 Greg Hull add un-implemented Up/Down/OnOff buttons
* 08/18/10 #273 Greg Hull implement Clear RBD button
* 08/23/10 #303 Greg Hull changes from workshop
* 09/01/10 #307 Greg Hull implement auto update
* 01/25/11 Greg Hull fix autoImport of current Display, autoImport
* of reprojected SAT area,
* 02/11/11 #408 Greg Hull Move Clear to Clear Pane; Add Load&Close btn
* 02/22/11 #408 Greg Hull allow for use by EditRbdDialog
* 06/07/11 #445 Xilin Guo Data Manager Performance Improvements
* 07/11/11 Greg Hull Rm code supporting 'Save All to SPF' capability.
* 08/20/11 #450 Greg Hull Use new SpfsManager
* 10/22/11 #467 Greg Hull Add Modify button
* 11/03/11 #??? B. Hebbard Add "Save Source Timestamp As:" Constant / Latest
* 02/15/2012 627 Archana Updated the call to addRbd() to accept
* a NCMapEditor object as one of the arguments
* 04/26/2012 #766 Quan Zhou Modified rscSelDlg listener for double click w. existing rsc--close the dlg.
* 04/03/2012 #765 S. Gurung Modified method importRBD to change the display when a RBD is imported
* 05/17/2012 #791 Quan Zhou Added getDefaultRbdRsc() to get name and rsc from original defaultRbd.xml
* Modified LoadRBD to check if default editor is empty, then replace it.
* findCloseEmptyEdotor() is ready but not used now.
* 06/18/2012 #624 Greg Hull set size correctly when initially importing mult-pane
* 06/18/2012 #713 Greg Hull clone the RbdBundl when importing
* 06/20/2012 #647 Greg Hull dont call selectDominantResource() after importRbd.
* 06/20/2012 S. Gurung Fix for TTR# 539 (Auto-update checkbox gets reset to OFF)
* 06/21/2012 #646 Greg Hull import full PredefinedArea instead of just the name.
* 06/28/2012 #824 Greg Hull update the importRbdCombo in the ActivateListener.
* 08/01/2012 #836 Greg Hull check for paneLayout when using empty editor
* 08/02/2012 #568 Greg Hull Clear Rbd -> Reset Rbd. get the Default RBD
* 11/16/2012 #630 Greg Hull Allow selection of resource-defined areas.
* 12/02/2012 #630 Greg Hull add zoomLevel combo
* 01/24/2013 #972 Greg Hull add NcDisplayType to support NonMap and solar based RBDs
* 05/24/2013 #862 Greg Hull get areas from menus file and change combo to a cascading menu
* 06/03/2013 #1001 Greg Hull allow multiple Remove/TurnOff of resources
* 10/22/2013 #1043 Greg Hull setSelectedResource() if rsc sel dlg is already up.
* 11/25/2013 #1079 Greg Hull adjust size/font of area toolbar based on the text
* 05/07/2014 TTR991 D. Sushon if a different NCP editor is selected, the CreateRDB tab should now adjust.
* 05/29/2014 #1131 qzhou Added NcDisplayType
* Modified creating new timelineControl in const and updateGUI
* 08/14/2014 ? B. Yin Added power legend (resource group) support.
* 09/092014 ? B. Yin Fixed NumPad enter issue and the "ResetToDefault" issue for groups.
* 07/28/2014 R4079 sgurung Fixed the issue related to CreateRbd dialog size (bigger than usual).
* Also, added code to set geosync to true for graphs.
* 11/12/2015 R8829 B. Yin Implemented up/down arrows to move a resource in list.
* 01/14/2016 R14896 J. Huber Repair Replace Resource button which was broken during cleanup of
* previous change.
* 01/01/2016 R14142 RCReynolds Reformatted Mcidas resource string
* 01/25/2016 R14142 RCReynolds Moved mcidas related sting construction out to ResourceDefinition
* 02/16/2016 R15244 bkowal Cleaned up warnings.
* 04/05/2016 R15715 dgilling Refactored out PopupEditAttrsDialog and associated methods.
* 06/20/2016 R8878 J. Lopez Changed createAvailAreaMenuItems() to use AreaMenuTree
* Auto selects the new group when creating a new resource group
* Renamed variables to be CamelCase
* 08/25/2016 R15518 Jeff Beck Added check for isDisposed() before calling refresh() in editResourceData()
* 10/20/2016 R17365 K.Bugenhagen Added call to SpfsManager method to remember
* selected spf group/name and RBD
* name in between calls to save RBD dialogue.
* Cleanup.
* 11/14/2016 R17362 Jeff Beck Added functionality to remove user defined resources from the dominant resource combo
* when clicking the "X" on the GUI.
* </pre>
*
* @author ghull
* @version 1
*/
public class CreateRbdControl extends Composite implements IPartListener2 {
private ResourceSelectionDialog rscSelDlg = null;
private RscBundleDisplayMngr rbdMngr;
private Shell shell;
private SashForm sashForm = null;
private Group rbdGroup = null;
private Text rbdNameText = null;
private Label rbdNameLabel = null;
private Combo dispTypeCombo = null;
private Label dispTypeLabel = null;
private Button selectResourceButton = null;
private Button multiPaneToggle = null;
private Button autoUpdateButton = null;
private Button geoSyncPanesToggle = null;
private Group selectedResourceGroup = null;
private ListViewer selectedResourceViewer = null;
private TableViewer groupListViewer;
private Text nameTxt;
private Button delGrpBtn;
private Composite grpColorComp;
private ColorButtonSelector grpColorBtn;
private Button grpMoveUpBtn;
private Button grpMoveDownBtn;
private int curGrp = -1;
private Button replaceResourceButton = null;
private Button editResourceButton = null;
private Button deleteResourceButton = null;
private Button disableResourceButton = null;
private Button moveResourceUpButton = null;
private Button moveResourceDownButton = null;
private ToolItem areaToolItem;
private AreaMenuItem seldAreaMenuItem = null;
// dispose if new Font created
private Font areaFont = null;
private Group geoAreaGroup = null;
private MenuManager areaMenuMngr = null;
// only one of these visible at a time
private Composite geoAreaInfoComp = null;
// depending on if a satellite area is selected
private Composite resourceAreaOptsComp = null;
// view-only projection and map center info
private Text projInfoText = null;
// view-only projection and map center info
private Text mapCenterText = null;
private Button fitToScreenButton = null;
private Button sizeOfImageButton = null;
private Button customAreaButton = null;
private Group paneLayoutGroup = null;
private Group groupGrp = null;
private Button paneSelectionButtons[][] = null;
private Button importPaneButton = null;
private Button loadPaneButton = null;
private Button clearPaneButton = null;
private Label importLabel = null;
private Combo importRbdCombo = null;
private Button loadRbdButton = null;
private Button loadAndCloseButton = null;
private Button saveRbdButton = null;
private Button clearRbdButton = null;
// when part of the 'Edit Rbd' dialog these will replace the Clear, Save,
// and Load buttons
private Button cancelEditButton = null;
private Button okEditButton = null;
// set on OK when this is an 'Edit Rbd' dialog
private AbstractRBD<?> editedRbd = null;
// used to initialize the Save Dialog
private String savedSpfGroup = null;
private String savedSpfName = null;
private String savedRbdName;
private Point initDlgSize = new Point(750, 860);
private int multiPaneDlgWidth = 950;
private TimelineControl timelineControl = null;
private final String ImportFromSPF = "From SPF...";
private Group timelineGroup;
private int grpColor = 1;
// NCP group rendering order
static private int NCP_GROUP_RENDERING_ORDER = 500;
private static Map<String, String> gempakProjMap = GempakProjectionValuesUtil
.initializeProjectionNameMap();
private static String ungrpStr = "Static";
private static final transient IUFStatusHandler statusHandler = UFStatus
.getHandler(CreateRbdControl.class);
// the rbdMngr will be used to set the gui so it should either be
// initialized/cleared or set with the initial RBD.
public CreateRbdControl(Composite parent, RscBundleDisplayMngr mngr)
throws VizException {
super(parent, SWT.NONE);
shell = parent.getShell();
rbdMngr = mngr;
rscSelDlg = new ResourceSelectionDialog(shell);
Composite top_comp = this;
top_comp.setLayout(new GridLayout(1, true));
sashForm = new SashForm(top_comp, SWT.VERTICAL);
GridData gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.horizontalAlignment = SWT.FILL;
gd.verticalAlignment = SWT.FILL;
sashForm.setLayoutData(gd);
sashForm.setSashWidth(10);
rbdGroup = new Group(sashForm, SWT.SHADOW_NONE);
rbdGroup.setText("Resource Bundle Display");
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.horizontalAlignment = SWT.FILL;
gd.verticalAlignment = SWT.FILL;
rbdGroup.setLayoutData(gd);
rbdGroup.setLayout(new FormLayout());
createRBDGroup();
timelineGroup = new Group(sashForm, SWT.SHADOW_NONE);
timelineGroup.setText("Select Timeline");
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.horizontalAlignment = SWT.FILL;
gd.verticalAlignment = SWT.FILL;
timelineGroup.setLayoutData(gd);
timelineGroup.setLayout(new GridLayout());
if (mngr.getRbdType().equals(NcDisplayType.GRAPH_DISPLAY)) {
timelineControl = new GraphTimelineControl(timelineGroup);
} else {
timelineControl = new TimelineControl(timelineGroup);
}
timelineControl.addDominantResourceChangedListener(
new IDominantResourceChangedListener() {
@Override
public void dominantResourceChanged(
AbstractNatlCntrsRequestableResourceData newDomRsc) {
if (newDomRsc == null) {
autoUpdateButton
.setSelection(rbdMngr.isAutoUpdate());
autoUpdateButton.setEnabled(false);
} else if (newDomRsc.isAutoUpdateable()) {
autoUpdateButton.setEnabled(true);
autoUpdateButton.setSelection(true);
if (rbdMngr.getRbdType()
.equals(NcDisplayType.GRAPH_DISPLAY)) {
geoSyncPanesToggle.setSelection(true);
rbdMngr.syncPanesToArea();
}
} else {
autoUpdateButton.setSelection(false);
autoUpdateButton.setEnabled(false);
}
}
});
timelineControl.setTimeMatcher(new NCTimeMatcher());
Composite loadSaveComp = new Composite(top_comp, SWT.NONE);
gd = new GridData();
gd.minimumHeight = 40;
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
gd.horizontalAlignment = SWT.FILL;
gd.verticalAlignment = SWT.FILL;
loadSaveComp.setLayoutData(gd);
loadSaveComp.setLayout(new FormLayout());
clearRbdButton = new Button(loadSaveComp, SWT.PUSH);
clearRbdButton.setText(" Reset To Default ");
FormData fd = new FormData();
fd.width = 130;
fd.top = new FormAttachment(0, 7);
fd.left = new FormAttachment(17, -65);
clearRbdButton.setLayoutData(fd);
saveRbdButton = new Button(loadSaveComp, SWT.PUSH);
saveRbdButton.setText(" Save RBD ");
fd = new FormData();
fd.width = 100;
fd.top = new FormAttachment(0, 7);
fd.left = new FormAttachment(40, -50);
saveRbdButton.setLayoutData(fd);
loadRbdButton = new Button(loadSaveComp, SWT.PUSH);
loadRbdButton.setText("Load RBD");
fd = new FormData();
fd.width = 100;
fd.top = new FormAttachment(0, 7);
fd.left = new FormAttachment(63, -50);
loadRbdButton.setLayoutData(fd);
loadAndCloseButton = new Button(loadSaveComp, SWT.PUSH);
loadAndCloseButton.setText("Load And Close");
fd = new FormData();
fd.width = 120;
fd.top = new FormAttachment(0, 7);
fd.left = new FormAttachment(83, -50);
loadAndCloseButton.setLayoutData(fd);
cancelEditButton = new Button(loadSaveComp, SWT.PUSH);
cancelEditButton.setText(" Cancel ");
fd = new FormData();
fd.width = 80;
fd.top = new FormAttachment(0, 7);
fd.right = new FormAttachment(45, 0);
cancelEditButton.setLayoutData(fd);
okEditButton = new Button(loadSaveComp, SWT.PUSH);
okEditButton.setText(" Ok ");
fd = new FormData();
fd.width = 80;
fd.top = new FormAttachment(0, 7);
fd.left = new FormAttachment(55, 0);
okEditButton.setLayoutData(fd);
// only visible if configureForEditRbd is called
cancelEditButton.setVisible(false);
okEditButton.setVisible(false);
sashForm.setWeights(new int[] { 50, 35 });
// set up the content providers for the ListViewers
setContentProviders();
addSelectionListeners();
initWidgets();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.addPartListener(this);
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage()
.removePartListener(CreateRbdControl.this);
// now mark for disposal
CreateRbdControl.this.dispose();
} catch (NullPointerException npe) {
// do nothing if already disposed, another thread already
// swept it up..
}
}
});
}
// create all the widgets in the Resource Bundle Definition (bottom) section
// of the sashForm.
private void createRBDGroup() {
importRbdCombo = new Combo(rbdGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
FormData form_data = new FormData();
form_data.left = new FormAttachment(0, 15);
form_data.top = new FormAttachment(0, 30);
form_data.right = new FormAttachment(24, 0);
importRbdCombo.setLayoutData(form_data);
importRbdCombo.setEnabled(true);
importLabel = new Label(rbdGroup, SWT.None);
importLabel.setText("Import");
form_data = new FormData();
form_data.left = new FormAttachment(importRbdCombo, 0, SWT.LEFT);
form_data.bottom = new FormAttachment(importRbdCombo, -3, SWT.TOP);
importLabel.setLayoutData(form_data);
rbdNameText = new Text(rbdGroup, SWT.SINGLE | SWT.BORDER);
form_data = new FormData(200, 20);
form_data.left = new FormAttachment(importRbdCombo, 25, SWT.RIGHT);
form_data.top = new FormAttachment(importRbdCombo, 0, SWT.TOP);
rbdNameText.setLayoutData(form_data);
rbdNameLabel = new Label(rbdGroup, SWT.None);
rbdNameLabel.setText("RBD Name");
form_data = new FormData();
form_data.width = 180;
form_data.left = new FormAttachment(rbdNameText, 0, SWT.LEFT);
form_data.bottom = new FormAttachment(rbdNameText, -3, SWT.TOP);
rbdNameLabel.setLayoutData(form_data);
dispTypeCombo = new Combo(rbdGroup, SWT.DROP_DOWN | SWT.READ_ONLY);
form_data = new FormData(120, 20);
form_data.left = new FormAttachment(importRbdCombo, 0, SWT.LEFT);
form_data.top = new FormAttachment(importRbdCombo, 45, SWT.BOTTOM);
dispTypeCombo.setLayoutData(form_data);
dispTypeCombo.setEnabled(true);
dispTypeCombo
.setItems(new String[] { NcDisplayType.NMAP_DISPLAY.getName(),
NcDisplayType.NTRANS_DISPLAY.getName(),
NcDisplayType.SOLAR_DISPLAY.getName(),
NcDisplayType.GRAPH_DISPLAY.getName() });
dispTypeLabel = new Label(rbdGroup, SWT.None);
dispTypeLabel.setText("RBD Type");
form_data = new FormData();
form_data.left = new FormAttachment(dispTypeCombo, 0, SWT.LEFT);
form_data.bottom = new FormAttachment(dispTypeCombo, -3, SWT.TOP);
dispTypeLabel.setLayoutData(form_data);
multiPaneToggle = new Button(rbdGroup, SWT.CHECK);
multiPaneToggle.setText("Multi-Pane");
form_data = new FormData();
form_data.top = new FormAttachment(rbdNameText, -10, SWT.TOP);
form_data.left = new FormAttachment(rbdNameText, 15, SWT.RIGHT);
multiPaneToggle.setLayoutData(form_data);
autoUpdateButton = new Button(rbdGroup, SWT.CHECK);
form_data = new FormData();
autoUpdateButton.setText("Auto Update");
form_data.top = new FormAttachment(multiPaneToggle, 10, SWT.BOTTOM);
form_data.left = new FormAttachment(multiPaneToggle, 0, SWT.LEFT);
autoUpdateButton.setLayoutData(form_data);
autoUpdateButton.setEnabled(false);
geoSyncPanesToggle = new Button(rbdGroup, SWT.CHECK);
form_data = new FormData();
geoSyncPanesToggle.setText("Geo-Sync Panes");
form_data.top = new FormAttachment(autoUpdateButton, 10, SWT.BOTTOM);
form_data.left = new FormAttachment(autoUpdateButton, 0, SWT.LEFT);
geoSyncPanesToggle.setLayoutData(form_data);
createAreaGroup();
// create all the widgets used to show and edit the Selected Resources
selectedResourceGroup = createSeldRscsGroup();
createPaneLayoutGroup();
createGroupGrp();
}
private void createAreaGroup() {
geoAreaGroup = new Group(rbdGroup, SWT.SHADOW_NONE);
geoAreaGroup.setText("Area");
geoAreaGroup.setLayout(new FormLayout());
FormData form_data = new FormData();
form_data.top = new FormAttachment(dispTypeCombo, 25, SWT.BOTTOM);
// room for the Load and Save buttons
form_data.bottom = new FormAttachment(100, 0);
form_data.left = new FormAttachment(0, 10);
form_data.right = new FormAttachment(24, 0);
geoAreaGroup.setLayoutData(form_data);
ToolBar areaTBar = new ToolBar(geoAreaGroup,
SWT.SHADOW_OUT | SWT.HORIZONTAL | SWT.RIGHT | SWT.WRAP);
form_data = new FormData();
form_data.left = new FormAttachment(0, 10);
form_data.top = new FormAttachment(0, 15);
form_data.right = new FormAttachment(100, -10);
form_data.height = 30;
areaTBar.setLayoutData(form_data);
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
if (areaFont != null) {
areaFont.dispose();
}
}
});
areaToolItem = new ToolItem(areaTBar, SWT.DROP_DOWN);
areaMenuMngr = new MenuManager("CreateRbdControl");
areaMenuMngr.setRemoveAllWhenShown(true);
final Menu areaCtxMenu = areaMenuMngr.createContextMenu(shell);
areaCtxMenu.setVisible(false);
geoAreaGroup.setMenu(areaCtxMenu);
areaMenuMngr.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager amngr) {
AreaMenuTree areaMenu = rbdMngr.getAvailAreaMenuItems();
createAvailAreaMenuItems(amngr, areaMenu);
}
});
// Main toolbar button clicked: show the areas popup menu at
// the location of the toolbar so it appears like a combo
// dropdown. This will also trigger the menu manager to create
// the menu items for the available areas.
areaToolItem.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
ToolItem ti = ((ToolItem) event.widget);
Rectangle bounds = ti.getBounds();
Point point = ti.getParent().toDisplay(bounds.x,
bounds.y + bounds.height);
areaCtxMenu.setLocation(point);
areaCtxMenu.setVisible(true);
}
});
// 2 Composites. 1 for when a predefined area is selected which will
// show the projection and map center. And 1 for when a satellite
// resource is select which will let the user select either FitToScreen
// or SizeOfImage
geoAreaInfoComp = new Composite(geoAreaGroup, SWT.NONE);
geoAreaInfoComp.setLayout(new FormLayout());
resourceAreaOptsComp = new Composite(geoAreaGroup, SWT.NONE);
resourceAreaOptsComp.setLayout(new GridLayout(1, true));
geoAreaInfoComp.setVisible(true);
resourceAreaOptsComp.setVisible(false);
form_data = new FormData();
form_data.left = new FormAttachment(0, 10);
form_data.top = new FormAttachment(areaTBar, 15, SWT.BOTTOM);
form_data.right = new FormAttachment(100, -10);
// both overlap each other since only one visible at a time
geoAreaInfoComp.setLayoutData(form_data);
form_data.top = new FormAttachment(areaTBar, 30, SWT.BOTTOM);
resourceAreaOptsComp.setLayoutData(form_data);
fitToScreenButton = new Button(resourceAreaOptsComp, SWT.RADIO);
fitToScreenButton.setText("Fit To Screen");
sizeOfImageButton = new Button(resourceAreaOptsComp, SWT.RADIO);
sizeOfImageButton.setText("Size Of Image");
// radio behavior
fitToScreenButton.setSelection(true);
sizeOfImageButton.setSelection(false);
Label proj_lbl = new Label(geoAreaInfoComp, SWT.None);
proj_lbl.setText("Projection");
form_data = new FormData();
form_data.left = new FormAttachment(0, 0);
form_data.top = new FormAttachment(0, 0);
form_data.right = new FormAttachment(100, 0);
proj_lbl.setLayoutData(form_data);
projInfoText = new Text(geoAreaInfoComp,
SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
form_data = new FormData();
form_data.left = new FormAttachment(0, 0);
form_data.top = new FormAttachment(proj_lbl, 2, SWT.BOTTOM);
form_data.right = new FormAttachment(100, 0);
projInfoText.setLayoutData(form_data);
projInfoText.setText("");
// indicate Read-only
projInfoText.setBackground(rbdGroup.getBackground());
Label map_center_lbl = new Label(geoAreaInfoComp, SWT.None);
map_center_lbl.setText("Map Center");
form_data = new FormData();
form_data.left = new FormAttachment(0, 0);
form_data.top = new FormAttachment(projInfoText, 15, SWT.BOTTOM);
form_data.right = new FormAttachment(100, 0);
map_center_lbl.setLayoutData(form_data);
mapCenterText = new Text(geoAreaInfoComp,
SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
form_data = new FormData();
form_data.left = new FormAttachment(0, 0);
form_data.top = new FormAttachment(map_center_lbl, 2, SWT.BOTTOM);
form_data.right = new FormAttachment(100, 0);
mapCenterText.setLayoutData(form_data);
mapCenterText.setText(" ");
// indicate Read-only
mapCenterText.setBackground(rbdGroup.getBackground());
// TODO : move this to be a Tool from main menu to create and name
// predefined areas and move this button to be an option under the
// predefined areas list
customAreaButton = new Button(geoAreaGroup, SWT.PUSH);
form_data = new FormData();
form_data.left = new FormAttachment(0, 40);
form_data.right = new FormAttachment(100, -40);
form_data.bottom = new FormAttachment(100, -15);
customAreaButton.setLayoutData(form_data);
customAreaButton.setText(" Custom ... ");
// not implemented
customAreaButton.setEnabled(false);
customAreaButton.setVisible(false);
}
// create the Selected Resources List, the Edit, Delete and Clear buttons
private Group createSeldRscsGroup() {
Group seld_rscs_grp = new Group(rbdGroup, SWT.SHADOW_NONE);
seld_rscs_grp.setText("Selected Resources");
seld_rscs_grp.setLayout(new FormLayout());
FormData form_data = new FormData();
form_data.top = new FormAttachment(autoUpdateButton, 15, SWT.BOTTOM);
form_data.left = new FormAttachment(geoAreaGroup, 10, SWT.RIGHT);
form_data.right = new FormAttachment(100, -300);
form_data.bottom = new FormAttachment(100, 0);
seld_rscs_grp.setLayoutData(form_data);
// This is multi-select to make Deleting resources easier.
selectedResourceViewer = new ListViewer(seld_rscs_grp,
SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
form_data = new FormData();
form_data.top = new FormAttachment(0, 5);
form_data.left = new FormAttachment(0, 5);
form_data.right = new FormAttachment(100, -95);// -110 ); //80, 0 );
form_data.bottom = new FormAttachment(100, -47);
selectedResourceViewer.getList().setLayoutData(form_data);
//
editResourceButton = new Button(seld_rscs_grp, SWT.PUSH);
editResourceButton.setText(" Edit ...");
form_data = new FormData();
form_data.width = 90;
form_data.bottom = new FormAttachment(100, -10);
form_data.left = new FormAttachment(40, 20);
editResourceButton.setLayoutData(form_data);
editResourceButton.setEnabled(false);
selectResourceButton = new Button(seld_rscs_grp, SWT.PUSH);
selectResourceButton.setText(" New ... ");
form_data = new FormData();
form_data.width = 90;
form_data.bottom = new FormAttachment(100, -10);
form_data.right = new FormAttachment(40, -20);
selectResourceButton.setLayoutData(form_data);
replaceResourceButton = new Button(seld_rscs_grp, SWT.PUSH);
replaceResourceButton.setText(" Replace ...");
form_data = new FormData();
form_data.width = 90;
form_data.bottom = new FormAttachment(100, -10);
form_data.left = new FormAttachment(editResourceButton, 30, SWT.RIGHT);
replaceResourceButton.setLayoutData(form_data);
replaceResourceButton.setEnabled(false);
replaceResourceButton.setVisible(false);
deleteResourceButton = new Button(seld_rscs_grp, SWT.PUSH);
deleteResourceButton.setText("Remove");
form_data = new FormData();
form_data.width = 75;
form_data.top = new FormAttachment(10, -10);
form_data.right = new FormAttachment(100, -10);
deleteResourceButton.setLayoutData(form_data);
deleteResourceButton.setEnabled(false);
disableResourceButton = new Button(seld_rscs_grp, SWT.TOGGLE);
disableResourceButton.setText("Turn Off");
form_data = new FormData();
form_data.width = 75;
form_data.right = new FormAttachment(100, -10);
form_data.top = new FormAttachment(30, -10);
disableResourceButton.setLayoutData(form_data);
moveResourceDownButton = new Button(seld_rscs_grp,
SWT.ARROW | SWT.DOWN);
moveResourceDownButton.setToolTipText("Move Down");
form_data = new FormData();
form_data.width = 35;
form_data.top = new FormAttachment(50, -10);
form_data.right = new FormAttachment(100, -10);
moveResourceDownButton.setLayoutData(form_data);
moveResourceDownButton.setEnabled(false);
moveResourceDownButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
StructuredSelection groups = ((StructuredSelection) groupListViewer
.getSelection());
ResourceSelection grpSelected = (ResourceSelection) groups
.getFirstElement();
StructuredSelection resources = ((StructuredSelection) selectedResourceViewer
.getSelection());
ResourceSelection resSelected = (ResourceSelection) resources
.getFirstElement();
if (resSelected != null && grpSelected != null) {
if (groupListViewer.getTable().getSelection()[0].getText()
.equalsIgnoreCase(ungrpStr)) {
rbdMngr.moveDownResource(resSelected, null);
selectedResourceViewer
.setInput(rbdMngr.getUngroupedResources());
selectedResourceViewer.refresh();
selectedResourceViewer.setSelection(resources);
} else {
rbdMngr.moveDownResource(resSelected,
(GroupResourceData) grpSelected
.getResourceData());
selectedResourceViewer.setInput(
rbdMngr.getResourcesInGroup(groupListViewer
.getTable().getSelection().length == 0
? null
: groupListViewer.getTable()
.getSelection()[0]
.getText()));
int ii = 0;
for (ResourceSelection rs : rbdMngr.getResourcesInGroup(
groupListViewer.getTable().getSelection()[0]
.getText())) {
if (rs.getResourcePair() == resSelected
.getResourcePair()) {
selectedResourceViewer.getList().select(ii);
break;
}
ii++;
}
}
}
}
});
moveResourceUpButton = new Button(seld_rscs_grp, SWT.ARROW | SWT.UP);
moveResourceUpButton.setToolTipText("Move Up");
form_data = new FormData();
form_data.width = 35;
form_data.top = new FormAttachment(moveResourceDownButton, 0, SWT.TOP);
form_data.left = new FormAttachment(disableResourceButton, 0, SWT.LEFT);
moveResourceUpButton.setLayoutData(form_data);
moveResourceUpButton.setEnabled(false);
moveResourceUpButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
StructuredSelection groups = ((StructuredSelection) groupListViewer
.getSelection());
ResourceSelection grpSelected = (ResourceSelection) groups
.getFirstElement();
StructuredSelection resources = ((StructuredSelection) selectedResourceViewer
.getSelection());
ResourceSelection resSelected = (ResourceSelection) resources
.getFirstElement();
if (resSelected != null && grpSelected != null) {
if (groupListViewer.getTable().getSelection()[0].getText()
.equalsIgnoreCase(ungrpStr)) {
rbdMngr.moveUpResource(resSelected, null);
selectedResourceViewer
.setInput(rbdMngr.getUngroupedResources());
selectedResourceViewer.refresh();
selectedResourceViewer.setSelection(resources);
} else {
rbdMngr.moveUpResource(resSelected,
(GroupResourceData) grpSelected
.getResourceData());
selectedResourceViewer.setInput(
rbdMngr.getResourcesInGroup(groupListViewer
.getTable().getSelection().length == 0
? null
: groupListViewer.getTable()
.getSelection()[0]
.getText()));
selectedResourceViewer.refresh();
int ii = 0;
for (ResourceSelection rs : rbdMngr.getResourcesInGroup(
groupListViewer.getTable().getSelection()[0]
.getText())) {
if (rs.getResourcePair() == resSelected
.getResourcePair()) {
selectedResourceViewer.getList().select(ii);
break;
}
ii++;
}
}
}
}
});
Button edit_span_btn = new Button(seld_rscs_grp, SWT.PUSH);
edit_span_btn.setText(" Bin ... ");
form_data = new FormData();
form_data.width = 75;
form_data.top = new FormAttachment(70, -10);
form_data.right = new FormAttachment(100, -10);
edit_span_btn.setLayoutData(form_data);
edit_span_btn.setEnabled(false);
return seld_rscs_grp;
}
private void createGroupGrp() {
groupGrp = new Group(rbdGroup, SWT.SHADOW_NONE);
groupGrp.setText("Resource Group");
FormData fd = new FormData();
fd.left = new FormAttachment(selectedResourceGroup, 10, SWT.RIGHT);
fd.top = new FormAttachment(0, 3);
fd.right = new FormAttachment(100, 0);
fd.bottom = new FormAttachment(100, 0);
groupGrp.setLayoutData(fd);
groupGrp.setLayout(new FormLayout());
Label nameLbl = new Label(groupGrp, SWT.NONE);
nameLbl.setText("Name:");
fd = new FormData();
fd.left = new FormAttachment(0, 5);
fd.top = new FormAttachment(0, 5);
nameLbl.setLayoutData(fd);
nameTxt = new Text(groupGrp, SWT.SINGLE | SWT.BORDER);
fd = new FormData(200, 20);
fd.left = new FormAttachment(nameLbl, 5, SWT.RIGHT);
fd.right = new FormAttachment(100, -40);
fd.top = new FormAttachment(nameLbl, -5, SWT.TOP);
nameTxt.setLayoutData(fd);
nameTxt.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent ke) {
Text txt = (Text) ke.widget;
if ((ke.keyCode == SWT.CR || ke.keyCode == SWT.KEYPAD_CR)
&& !txt.getText().isEmpty()) {
if (txt.getText().equalsIgnoreCase(ungrpStr)) {
curGrp = -1;
selectUngroupedGrp();
selectedResourceViewer
.setInput(rbdMngr.getUngroupedResources());
setGroupButtons();
return;
}
int ii = 0;
for (ResourceSelection rsel : rbdMngr.getGroupResources()) {
if (rsel.getResourceData() instanceof GroupResourceData) {
if (((GroupResourceData) rsel.getResourceData())
.getGroupName()
.equalsIgnoreCase(txt.getText())) {
groupListViewer.getTable().setSelection(ii);
curGrp = groupListViewer.getTable()
.getSelectionIndex();
selectedResourceViewer.setInput(rbdMngr
.getResourcesInGroup(groupListViewer
.getTable()
.getSelection().length == 0
? null
: groupListViewer
.getTable()
.getSelection()[0]
.getText()));
setGroupButtons();
return;
}
}
ii++;
}
addResourceGroup(txt.getText());
setGroupButtons();
txt.setText("");
}
}
});
groupListViewer = new TableViewer(groupGrp, SWT.SINGLE | SWT.V_SCROLL
| SWT.H_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
fd = new FormData();
fd.top = new FormAttachment(nameLbl, 15, SWT.BOTTOM);
fd.bottom = new FormAttachment(100, -5);
fd.left = new FormAttachment(0, 5);
fd.right = new FormAttachment(100, -40);
groupListViewer.getTable().setLayoutData(fd);
groupListViewer.setContentProvider(new IStructuredContentProvider() {
@Override
public Object[] getElements(Object inputElement) {
// Add "Ungrouped" group
ResourcePair group = new ResourcePair();
GroupResourceData grd = new GroupResourceData(ungrpStr, 0,
grpColorBtn.getColorValue());
group.setResourceData(grd);
ResourceSelection ungrouped = null;
try {
ungrouped = ResourceFactory.createResource(group);
} catch (VizException e) {
}
ResourceSelection[] groups = (ResourceSelection[]) inputElement;
ResourceSelection[] groups1;
if (ungrouped != null) {
if (groups != null) {
List<ResourceSelection> list = new ArrayList<>(Arrays
.asList(groups));
list.add(0, ungrouped);
groups1 = list
.toArray(new ResourceSelection[list.size()]);
} else {
groups1 = new ResourceSelection[] { ungrouped };
}
} else {
groups1 = groups;
}
return groups1;
}
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput,
Object newInput) {
}
});
groupListViewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
ResourceSelection rscSel = (ResourceSelection) element;
if (rscSel.getResourceData() instanceof GroupResourceData) {
return ((GroupResourceData) rscSel.getResourceData())
.getGroupName();
} else {
return "No Group Name";
}
}
});
// enable/disable the Edit/Delete/Clear buttons...
groupListViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
}
});
groupListViewer.getTable().addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
curGrp = groupListViewer.getTable().getSelectionIndex();
if (groupListViewer.getTable().getSelection()[0].getText()
.equalsIgnoreCase(ungrpStr)) {
curGrp = -1;
selectedResourceViewer
.setInput(rbdMngr.getUngroupedResources());
} else {
selectedResourceViewer.setInput(
rbdMngr.getResourcesInGroup(groupListViewer
.getTable().getSelection().length == 0
? null
: groupListViewer.getTable()
.getSelection()[0]
.getText()));
}
setGroupButtons();
}
});
groupListViewer.setColumnProperties(new String[] { "Group Name" });
groupListViewer.setCellModifier(new ICellModifier() {
@Override
public boolean canModify(Object element, String property) {
// TODO Auto-generated method stub
return true;
}
@Override
public Object getValue(Object element, String property) {
ResourceSelection sel = (ResourceSelection) element;
return ((GroupResourceData) sel.getResourceData())
.getGroupName();
}
@Override
public void modify(Object element, String property, Object value) {
if (value != null && !((String) value).isEmpty()) {
ResourceSelection sel = (ResourceSelection) ((TableItem) element)
.getData();
((GroupResourceData) sel.getResourceData())
.setGroupName((String) value);
groupListViewer.refresh();
}
}
});
groupListViewer.setCellEditors(new CellEditor[] {
new TextCellEditor(groupListViewer.getTable()) });
ColumnViewerEditorActivationStrategy activationSupport = new ColumnViewerEditorActivationStrategy(
groupListViewer) {
@Override
protected boolean isEditorActivationEvent(
// Enable editor only with mouse double click
ColumnViewerEditorActivationEvent event) {
if (event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION) {
EventObject source = event.sourceEvent;
if (source instanceof MouseEvent
&& ((MouseEvent) source).button == 3) {
return false;
}
if (((GroupResourceData) ((ResourceSelection) ((org.eclipse.jface.viewers.ViewerCell) event
.getSource()).getElement()).getResourcePair()
.getResourceData()).getGroupName()
.equalsIgnoreCase(ungrpStr)) {
return false;
}
return true;
}
return false;
}
};
TableViewerEditor.create(groupListViewer, activationSupport,
ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL
| ColumnViewerEditor.KEYBOARD_ACTIVATION);
groupListViewer.addDoubleClickListener(new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
TableViewer tv = (TableViewer) event.getSource();
tv.setSelection(event.getSelection());
selectedResourceViewer.setInput(rbdMngr.getResourcesInGroup(
groupListViewer.getTable().getSelection().length == 0
? null
: groupListViewer.getTable().getSelection()[0]
.getText()));
curGrp = groupListViewer.getTable().getSelectionIndex();
if (groupListViewer.getTable().getSelection()[0].getText()
.equalsIgnoreCase(ungrpStr)) {
selectUngroupedGrp();
selectedResourceViewer
.setInput(rbdMngr.getUngroupedResources());
curGrp = -1;
}
setGroupButtons();
}
});
groupListViewer.getTable().addListener(SWT.MouseUp, new Listener() {
@Override
public void handleEvent(Event event) {
org.eclipse.swt.widgets.Table grpList = (org.eclipse.swt.widgets.Table) event.widget;
if (grpList.getItemCount() > 0) {
if (event.y > grpList.getItemCount()
* grpList.getItemHeight()) {
grpList.deselectAll();
curGrp = -1;
selectUngroupedGrp();
selectedResourceViewer
.setInput(rbdMngr.getUngroupedResources());
setGroupButtons();
nameTxt.setText("");
}
}
}
});
grpMoveUpBtn = new Button(groupGrp, SWT.ARROW | SWT.UP);
grpMoveUpBtn.setToolTipText("Move Up");
fd = new FormData();
fd.width = 30;
fd.top = new FormAttachment(50, -70);
fd.left = new FormAttachment(groupListViewer.getTable(), 5, SWT.RIGHT);
grpMoveUpBtn.setLayoutData(fd);
grpMoveUpBtn.setEnabled(true);
grpMoveUpBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
StructuredSelection isel = ((StructuredSelection) groupListViewer
.getSelection());
ResourceSelection sel = (ResourceSelection) isel
.getFirstElement();
if (sel != null) {
rbdMngr.moveUpGrp(sel.getResourcePair());
groupListViewer.setInput(rbdMngr.getGroupResources());
groupListViewer.refresh();
groupListViewer.setSelection(isel);
curGrp = groupListViewer.getTable().getSelectionIndex();
setGroupButtons();
}
}
});
grpMoveDownBtn = new Button(groupGrp, SWT.ARROW | SWT.DOWN);
grpMoveDownBtn.setToolTipText("Move Down");
fd = new FormData();
fd.width = 30;
fd.top = new FormAttachment(grpMoveUpBtn, 10, SWT.BOTTOM);
fd.left = new FormAttachment(groupListViewer.getTable(), 5, SWT.RIGHT);
grpMoveDownBtn.setLayoutData(fd);
grpMoveDownBtn.setEnabled(true);
grpMoveDownBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
StructuredSelection isel = ((StructuredSelection) groupListViewer
.getSelection());
ResourceSelection sel = (ResourceSelection) isel
.getFirstElement();
if (sel != null) {
rbdMngr.moveDownGrp(sel.getResourcePair());
groupListViewer.setInput(rbdMngr.getGroupResources());
groupListViewer.setSelection(isel);
groupListViewer.refresh();
curGrp = groupListViewer.getTable().getSelectionIndex();
setGroupButtons();
}
}
});
delGrpBtn = new Button(groupGrp, SWT.PUSH);
delGrpBtn.setText("X");
delGrpBtn.setToolTipText("Remove");
fd = new FormData();
fd.width = 30;
fd.top = new FormAttachment(grpMoveDownBtn, 10, SWT.BOTTOM);
fd.left = new FormAttachment(groupListViewer.getTable(), 5, SWT.RIGHT);
delGrpBtn.setLayoutData(fd);
delGrpBtn.setEnabled(true);
delGrpBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
ResourceSelection sel = (ResourceSelection) ((StructuredSelection) groupListViewer
.getSelection()).getFirstElement();
if (sel != null) {
removeUserDefinedResourceGroup(sel);
groupListViewer.setInput(rbdMngr.getGroupResources());
groupListViewer.refresh();
selectUngroupedGrp();
selectedResourceViewer
.setInput(rbdMngr.getUngroupedResources());
setGroupButtons();
curGrp = -1;
}
}
});
grpColorComp = new Composite(groupGrp, SWT.NONE);
grpColorComp.setLayout(new FormLayout());
grpColorComp.setToolTipText("Legend Color");
grpColorBtn = new ColorButtonSelector(grpColorComp, 28, 22);
grpColorBtn.setColorValue(GempakColor.convertToRGB(1));
fd = new FormData();
fd.width = 30;
fd.top = new FormAttachment(delGrpBtn, 10, SWT.BOTTOM);
fd.left = new FormAttachment(groupListViewer.getTable(), 6, SWT.RIGHT);
grpColorComp.setLayoutData(fd);
grpColorComp.pack();
grpColorBtn.addListener(new IPropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
ResourceSelection sel = getGroupResourceSelection();
if (sel != null) {
((GroupResourceData) sel.getResourceData())
.setLegendColor(grpColorBtn.getColorValue());
}
}
});
groupListViewer.setInput(rbdMngr.getGroupResources());
groupListViewer.refresh(true);
selectUngroupedGrp();
setGroupButtons();
groupGrp.pack();
groupGrp.setVisible(true);
}
private void createPaneLayoutGroup() {
paneLayoutGroup = new Group(rbdGroup, SWT.SHADOW_NONE);
paneLayoutGroup.setText("Pane Layout");
paneLayoutGroup.setLayout(new FormLayout());
FormData fd = new FormData();
fd.left = new FormAttachment(selectedResourceGroup, 10, SWT.RIGHT);
fd.top = new FormAttachment(0, 3);
fd.right = new FormAttachment(100, 0);
fd.bottom = new FormAttachment(100, 0);
paneLayoutGroup.setLayoutData(fd);
Composite num_rows_cols_comp = new Composite(paneLayoutGroup, SWT.NONE);
GridLayout gl = new GridLayout(rbdMngr.getMaxPaneLayout().getColumns(),
false);
num_rows_cols_comp.setLayout(gl);
fd = new FormData();
fd.left = new FormAttachment(0, 100);
fd.top = new FormAttachment(0, 3);
fd.right = new FormAttachment(100, -10);
num_rows_cols_comp.setLayoutData(fd);
Button num_rows_btns[] = new Button[rbdMngr.getMaxPaneLayout()
.getRows()];
Button num_cols_btns[] = new Button[rbdMngr.getMaxPaneLayout()
.getColumns()];
for (int r = 0; r < rbdMngr.getMaxPaneLayout().getRows(); r++) {
num_rows_btns[r] = new Button(num_rows_cols_comp, SWT.PUSH);
num_rows_btns[r].setText(Integer.toString(r + 1));
num_rows_btns[r].setSize(20, 20);
num_rows_btns[r].setData(new Integer(r + 1));
num_rows_btns[r].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectPane(
rbdMngr.setPaneLayout(
new NcPaneLayout(
(Integer) e.widget.getData(),
((NcPaneLayout) rbdMngr
.getPaneLayout())
.getColumns())));
updatePaneLayout();
}
});
}
GridData gd = new GridData();
gd.widthHint = 50;
gd.grabExcessHorizontalSpace = true;
for (int c = 0; c < rbdMngr.getMaxPaneLayout().getColumns(); c++) {
num_cols_btns[c] = new Button(num_rows_cols_comp, SWT.PUSH);
num_cols_btns[c].setText(Integer.toString(c + 1));
num_cols_btns[c].setData(new Integer(c + 1));
num_cols_btns[c].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectPane(
rbdMngr.setPaneLayout(
new NcPaneLayout(
((NcPaneLayout) rbdMngr
.getPaneLayout()).getRows(),
(Integer) e.widget.getData())));
updatePaneLayout();
}
});
}
Label num_rows_lbl = new Label(paneLayoutGroup, SWT.NONE);
num_rows_lbl.setText("Rows:");
fd = new FormData();
fd.right = new FormAttachment(num_rows_cols_comp, -5, SWT.LEFT);
fd.top = new FormAttachment(num_rows_cols_comp, 10, SWT.TOP);
num_rows_lbl.setLayoutData(fd);
Label num_cols_lbl = new Label(paneLayoutGroup, SWT.NONE);
num_cols_lbl.setText("Columns:");
fd = new FormData();
fd.right = new FormAttachment(num_rows_cols_comp, -5, SWT.LEFT);
fd.top = new FormAttachment(num_rows_lbl, 15, SWT.BOTTOM);
num_cols_lbl.setLayoutData(fd);
Label sel_pane_lbl = new Label(paneLayoutGroup, SWT.NONE);
sel_pane_lbl.setText("Select Pane");
fd = new FormData();
fd.left = new FormAttachment(0, 5);
fd.top = new FormAttachment(num_rows_cols_comp, 2, SWT.BOTTOM);
sel_pane_lbl.setLayoutData(fd);
Label sep = new Label(paneLayoutGroup, SWT.SEPARATOR | SWT.HORIZONTAL);
fd = new FormData();
fd.left = new FormAttachment(sel_pane_lbl, 5, SWT.RIGHT);
fd.right = new FormAttachment(100, 0);
fd.top = new FormAttachment(num_rows_cols_comp, 11, SWT.BOTTOM);
sep.setLayoutData(fd);
Composite pane_sel_comp = new Composite(paneLayoutGroup, SWT.NONE);
pane_sel_comp.setLayout(
new GridLayout(rbdMngr.getMaxPaneLayout().getColumns(), true));
fd = new FormData();
fd.left = new FormAttachment(0, 25);
fd.top = new FormAttachment(sep, 12);
fd.bottom = new FormAttachment(100, -45);
fd.right = new FormAttachment(100, -15);
pane_sel_comp.setLayoutData(fd);
paneSelectionButtons = new Button[rbdMngr.getMaxPaneLayout()
.getRows()][rbdMngr.getMaxPaneLayout().getColumns()];
int numPanes = rbdMngr.getMaxPaneLayout().getNumberOfPanes();
for (
int p = 0; p < numPanes; p++)
{
NcPaneID pid = (NcPaneID) rbdMngr.getMaxPaneLayout()
.createPaneId(p);
int r = pid.getRow();
int c = pid.getColumn();
paneSelectionButtons[r][c] = new Button(pane_sel_comp, SWT.TOGGLE);
paneSelectionButtons[r][c].setText(pid.toString());
paneSelectionButtons[r][c].setData(pid);
paneSelectionButtons[r][c]
.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
NcPaneID seldPane = (NcPaneID) e.widget.getData();
selectPane(seldPane);
}
});
paneSelectionButtons[r][c].setSelection((r == 0 && c == 0));
}
importPaneButton = new Button(paneLayoutGroup, SWT.PUSH);
fd = new FormData();
fd.top = new FormAttachment(pane_sel_comp, 10, SWT.BOTTOM);
fd.left = new FormAttachment(50, -120);
importPaneButton.setLayoutData(fd);
importPaneButton.setText("Import...");
importPaneButton.setEnabled(true);
loadPaneButton = new Button(paneLayoutGroup, SWT.PUSH);
fd = new FormData();
fd.top = new FormAttachment(importPaneButton, 0, SWT.TOP);
fd.left = new FormAttachment(50, -38);
loadPaneButton.setLayoutData(fd);
loadPaneButton.setText(" Re-Load ");
clearPaneButton = new Button(paneLayoutGroup, SWT.PUSH);
clearPaneButton.setText(" Clear ");
fd = new FormData();
fd.top = new FormAttachment(importPaneButton, 0, SWT.TOP);
fd.left = new FormAttachment(50, 50);
clearPaneButton.setLayoutData(fd);
paneLayoutGroup.setVisible(false);
}
private void setContentProviders() {
selectedResourceViewer
.setContentProvider(new IStructuredContentProvider() {
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput,
Object newInput) {
}
@Override
public Object[] getElements(Object inputElement) {
return ((ResourceSelection[]) inputElement);
}
});
// get the full path of the attr file and then remove .prm extension
// and the prefix path up to the cat directory.
selectedResourceViewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
ResourceSelection rscSel = (ResourceSelection) element;
return rscSel.getRscLabel();
}
});
updateSelectedResourcesView(true);
// enable/disable the Edit/Delete/Clear buttons...
selectedResourceViewer
.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
updateSelectedResourcesView(false);
}
});
selectedResourceViewer.getList().addListener(SWT.MouseDoubleClick,
new Listener() {
@Override
public void handleEvent(Event event) {
editResourceData();
}
});
}
// add all of the listeners for widgets on this dialog
void addSelectionListeners() {
dispTypeCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
NcDisplayType selDispType = NcDisplayType
.getDisplayType(dispTypeCombo.getText());
if (rbdMngr.getRbdType() != selDispType) {
if (rbdMngr.isRbdModified()) {
MessageDialog confirmDlg = new MessageDialog(shell,
"Confirm", null,
"This RBD has been modified.\n\n"
+ "Do you want to clear the current RBD selections?",
MessageDialog.QUESTION,
new String[] { "Yes", "No" }, 0);
confirmDlg.open();
if (confirmDlg.getReturnCode() != MessageDialog.OK) {
return;
}
}
try {
rbdMngr.setRbdType(selDispType);
AbstractRBD<?> dfltRbd = AbstractRBD
.getDefaultRBD(rbdMngr.getRbdType());
rbdMngr.initFromRbdBundle(dfltRbd);
} catch (VizException ve) {
MessageDialog errDlg = new MessageDialog(shell, "Error",
null, ve.getMessage(), MessageDialog.ERROR,
new String[] { "OK" }, 0);
errDlg.open();
rbdMngr.init(rbdMngr.getRbdType());
}
updateGUI();
}
}
});
selectResourceButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
StructuredSelection sel_elems = (StructuredSelection) selectedResourceViewer
.getSelection();
List<ResourceSelection> seldRscsList = sel_elems.toList();
int numSeldRscs = selectedResourceViewer.getList()
.getSelectionCount();
Boolean isBaseLevelRscSeld = false;
// the initially selected resource is the first non-baselevel
// rsc
ResourceName initRscName = null;
for (ResourceSelection rscSel : seldRscsList) {
isBaseLevelRscSeld |= rscSel.isBaseLevelResource();
if (initRscName == null && !rscSel.isBaseLevelResource()) {
initRscName = rscSel.getResourceName();
}
}
// the replace button is enabled if there is only 1 resource
// selected and it is not the base resource
if (rscSelDlg.isOpen()) {
if (initRscName != null) {
rscSelDlg.setSelectedResource(initRscName);
}
} else {
// Replace button is visible replace enabled
rscSelDlg.open(true,
(numSeldRscs == 1 && !isBaseLevelRscSeld),
initRscName, multiPaneToggle.getSelection(),
rbdMngr.getRbdType(),
SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MODELESS);
}
}
});
// may be invisible, if implementing the Replace on the Select Resource
// Dialog
replaceResourceButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!rscSelDlg.isOpen()) {
StructuredSelection sel_elems = (StructuredSelection) selectedResourceViewer
.getSelection();
ResourceSelection rscSel = (ResourceSelection) sel_elems
.getFirstElement();
// Replace button is visible
rscSelDlg.open(true, (rscSel != null ? true : false),
rscSel.getResourceName(),
multiPaneToggle.getSelection(),
rbdMngr.getRbdType(), SWT.DIALOG_TRIM | SWT.RESIZE
| SWT.APPLICATION_MODAL);
}
}
});
rscSelDlg.addResourceSelectionListener(new IResourceSelectedListener() {
@Override
public void resourceSelected(ResourceName rscName, boolean replace,
boolean addAllPanes, boolean done) {
try {
ResourceSelection rbt = ResourceFactory
.createResource(rscName);
rbdMngr.getSelectedArea();
// if replacing existing resources, get the selected
// resources (For now just replace the 1st if more than one
// selected.)
if (replace) {
StructuredSelection sel_elems = (StructuredSelection) selectedResourceViewer
.getSelection();
ResourceSelection rscSel = (ResourceSelection) sel_elems
.getFirstElement();
StructuredSelection grp = (StructuredSelection) groupListViewer
.getSelection();
ResourceSelection sel = (ResourceSelection) grp
.getFirstElement();
// If the group resource functionality exists (which it
// does in all cases currently) sel will have a value.
// If in the future it is removed in some places, use
// the standard replace method.
if (sel != null) {
// If we are in the Static group, just replace the
// resource(s) as normal. If we are in a group
// resource follow the group resource replace method
if (((GroupResourceData) sel.getResourcePair()
.getResourceData()).getGroupName()
.equalsIgnoreCase(ungrpStr)) {
sel = null;
rbdMngr.replaceSelectedResource(rscSel, rbt);
} else {
((GroupResourceData) sel.getResourceData())
.replaceResourcePair(
rscSel.getResourcePair(),
rbt.getResourcePair());
selectedResourceViewer.setInput(rbdMngr
.getResourcesInGroup(groupListViewer
.getTable()
.getSelection().length == 0
? null
: groupListViewer
.getTable()
.getSelection()[0]
.getText()));
selectedResourceViewer.refresh(true);
}
} else {
rbdMngr.replaceSelectedResource(rscSel, rbt);
}
// remove this from the list of available dominant
// resources.
if (rscSel
.getResourceData() instanceof AbstractNatlCntrsRequestableResourceData) {
timelineControl.removeAvailDomResource(
(AbstractNatlCntrsRequestableResourceData) rscSel
.getResourceData());
}
// if replacing a resource which is set to provide the
// geographic area check to see if the current area has
// been reset to the default because it was not
// available
updateAreaGUI();
} else {
if (addAllPanes) {
if (!rbdMngr.addSelectedResourceToAllPanes(rbt)) {
if (done) {
rscSelDlg.close();
}
return;
}
} else {
StructuredSelection grp = (StructuredSelection) groupListViewer
.getSelection();
ResourceSelection sel = (ResourceSelection) grp
.getFirstElement();
if (sel != null && ((GroupResourceData) sel
.getResourcePair().getResourceData())
.getGroupName()
.equalsIgnoreCase(ungrpStr)) {
sel = null;
}
if (!rbdMngr.addSelectedResource(rbt, sel)) {
if (sel != null) {
selectedResourceViewer.setInput(rbdMngr
.getResourcesInGroup(groupListViewer
.getTable()
.getSelection().length == 0
? null
: groupListViewer
.getTable()
.getSelection()[0]
.getText()));
selectedResourceViewer.refresh(true);
}
if (done) {
rscSelDlg.close();
}
return;
}
}
}
// add the new resource to the timeline as a possible
// dominant resource
if (rbt.getResourceData() instanceof AbstractNatlCntrsRequestableResourceData) {
timelineControl.addAvailDomResource(
(AbstractNatlCntrsRequestableResourceData) rbt
.getResourceData());
// if there is not a dominant resource selected then
// select this one
if (timelineControl.getDominantResource() == null) {
timelineControl
.setDominantResource(
(AbstractNatlCntrsRequestableResourceData) rbt
.getResourceData(),
replace);
}
}
} catch (VizException e) {
statusHandler.handle(Priority.PROBLEM,
"Error Adding Resource to List: " + e.getMessage());
MessageDialog errDlg = new MessageDialog(shell, "Error",
null,
"Error Creating Resource:" + rscName.toString()
+ "\n\n" + e.getMessage(),
MessageDialog.ERROR, new String[] { "OK" }, 0);
errDlg.open();
}
updateSelectedResourcesView(true);
if (done) {
rscSelDlg.close();
}
}
});
sizeOfImageButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
rbdMngr.setZoomLevel((sizeOfImageButton.getSelection()
? ZoomLevelStrings.SizeOfImage.toString()
: ZoomLevelStrings.FitToScreen.toString()));
}
});
fitToScreenButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
rbdMngr.setZoomLevel((fitToScreenButton.getSelection()
? ZoomLevelStrings.FitToScreen.toString()
: ZoomLevelStrings.SizeOfImage.toString()));
}
});
// TODO: if single pane and there are resources selected
// in other panes then should we prompt the user on whether
// to clear them? We can ignore them if Loading/Saving a
// single pane, but if they reset multi-pane then should the
// resources in other panes still be selected.
multiPaneToggle.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
rbdMngr.setMultiPane(multiPaneToggle.getSelection());
updateGUIforMultipane(multiPaneToggle.getSelection());
if (multiPaneToggle.getSelection()) {
updatePaneLayout();
} else {
selectPane(new NcPaneID());
}
if (rscSelDlg != null && rscSelDlg.isOpen()) {
rscSelDlg.setMultiPaneEnabled(
multiPaneToggle.getSelection());
}
}
});
// if syncing the panes
geoSyncPanesToggle.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
if (geoSyncPanesToggle.getSelection()) {
MessageDialog confirmDlg = new MessageDialog(shell,
"Confirm Geo-Sync Panes", null,
"This will set the Area for all panes to the currently\n"
+ "selected Area: "
+ rbdMngr.getSelectedArea()
.getProviderName()
+ "\n\n" + "Continue?",
MessageDialog.QUESTION,
new String[] { "Yes", "No" }, 0);
confirmDlg.open();
if (confirmDlg.getReturnCode() != MessageDialog.OK) {
geoSyncPanesToggle.setSelection(false);
return;
}
rbdMngr.syncPanesToArea();
} else {
rbdMngr.setGeoSyncPanes(false);
}
}
});
customAreaButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
}
});
// only 1 should be selected or this button should be greyed out
editResourceButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
editResourceData();
}
});
deleteResourceButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
StructuredSelection sel_elems = (StructuredSelection) selectedResourceViewer
.getSelection();
Iterator<?> itr = sel_elems.iterator();
// note: the base may be selected if there are multi selected
// with others.
while (itr.hasNext()) {
ResourceSelection rscSel = (ResourceSelection) itr.next();
if (!rscSel.isBaseLevelResource()) {
removeSelectedResource(rscSel);
}
}
updateSelectedResourcesView(true);
updateAreaGUI();
}
});
disableResourceButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
StructuredSelection sel_elems = (StructuredSelection) selectedResourceViewer
.getSelection();
Iterator<?> itr = sel_elems.iterator();
while (itr.hasNext()) {
ResourceSelection rscSel = (ResourceSelection) itr.next();
rscSel.setIsVisible(!disableResourceButton.getSelection());
}
selectedResourceViewer.refresh(true);
updateSelectedResourcesView(false);
}
});
clearPaneButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
clearSeldResources();
}
});
clearRbdButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
clearRBD();
}
});
loadRbdButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
loadRBD(false);
}
});
loadAndCloseButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
loadRBD(true);
}
});
loadPaneButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
loadPane();
}
});
saveRbdButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
saveRBD(false);
}
});
importRbdCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
importRBD(importRbdCombo.getText());
}
});
// TODO : Currently we can't detect if the user clicks on the import
// combo and then clicks on the currently selected
// item which means the users can't re-import the current selection (or
// import another from an spf.) The following may
// allow a hackish work around later.... (I tried virtually every
// listener and these where the only ones to trigger.)
// ....update...with new Eclipse this seems to be working; ie.
// triggering a selection when
// combo is clicked on but selection isn't changed.
importRbdCombo.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
}
});
importRbdCombo.addListener(SWT.MouseDown, new Listener() { // and
// SWT.MouseUp
@Override
public void handleEvent(Event event) {
}
});
importRbdCombo.addListener(SWT.Activate, new Listener() {
@Override
public void handleEvent(Event event) {
updateImportCombo();
}
});
importRbdCombo.addListener(SWT.Deactivate, new Listener() {
@Override
public void handleEvent(Event event) {
}
});
importPaneButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
SelectRbdsDialog impDlg = new SelectRbdsDialog(shell,
"Import Pane", true, false, true);
if (!impDlg.open()) {
return;
}
AbstractRBD<?> impRbd = impDlg.getSelectedRBD();
if (impRbd != null) {
impRbd.resolveLatestCycleTimes();
try {
importPane(impRbd, impRbd.getSelectedPaneId());
} catch (VizException e) {
MessageDialog errDlg = new MessageDialog(shell, "Error",
null,
"Error Importing Rbd, " + impRbd.getRbdName()
+ ".\n" + e.getMessage(),
MessageDialog.ERROR, new String[] { "OK" }, 0);
errDlg.open();
}
}
}
});
}
// import the current editor or initialize the widgets.
public void initWidgets() {
rbdNameText.setText("");
updateAreaGUI();// should be the default area
shell.setSize(initDlgSize);
updateGUIforMultipane(rbdMngr.isMultiPane());
timelineControl.clearTimeline();
}
// if this is called from the Edit Rbd Dialog (from the LoadRbd tab), then
// remove widgets that don't apply. (ie, import, Save, and Load)
public void configureForEditRbd() {
importLabel.setVisible(false);
importRbdCombo.setVisible(false);
clearRbdButton.setVisible(false);
saveRbdButton.setVisible(false);
loadPaneButton.setVisible(false);
loadRbdButton.setVisible(false);
loadAndCloseButton.setVisible(false);
cancelEditButton.setVisible(true);
okEditButton.setVisible(true);
cancelEditButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
editedRbd = null;
shell.dispose();
}
});
// dispose and leave the edited RBD in
okEditButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent ev) {
createEditedRbd();
shell.dispose();
}
});
FormData fd = (FormData) rbdNameText.getLayoutData();
fd.left = new FormAttachment(20, 0);
rbdNameText.setLayoutData(fd);
timelineControl.getParent().setVisible(false);
sashForm.setWeights(new int[] { 10, 1 });
shell.setSize(shell.getSize().x - 100, 350);
shell.pack(true);
}
public void updateImportCombo() {
// check for possible new Displays that may be imported.
NcDisplayName seldImport = NcDisplayName
.parseNcDisplayNameString(importRbdCombo.getText());
importRbdCombo.removeAll();
for (AbstractEditor ncDisplay : NcDisplayMngr.getAllNcDisplays()) {
NcDisplayName displayName = NcEditorUtil.getDisplayName(ncDisplay);
importRbdCombo.add(displayName.toString());
// if this was selected before, select it again
if (seldImport == null || seldImport.equals(displayName)) {
importRbdCombo.select(importRbdCombo.getItemCount() - 1);
}
}
// if the previous selection wasn't found then select 'from SPF'
importRbdCombo.add(ImportFromSPF);
if (importRbdCombo.getSelectionIndex() == -1) {
importRbdCombo.select(importRbdCombo.getItemCount() - 1);
}
}
// Note: if the text set for the ToolItem doesn't fit on the size of the
// item then it will become blank and unselectable. Need to make sure this
// doesn't happen so create a multi-line text string for the tool item and
// make sure it is wide and high enough to hold the string.
//
public void setAreaTextOnMenuItem(AreaName areaName) {
seldAreaMenuItem = new AreaMenuItem(areaName);
// based on the starting width of the dialog and current attachments,
// the ToolItem has a width of 136. This will display up to 13
// characters.
//
// current width and height
Point toolBarSize = areaToolItem.getParent().getSize();
if (toolBarSize.x == 0) { // gui not initialized yet
return;
}
int maxChars = toolBarSize.x * 13 / 136;
// normal font
int fontSize = 10;
boolean truncated = false;
// string that will be used to set the menuItem
String menuText = seldAreaMenuItem.getMenuName();
// if greater than 13 then we will have to figure out how to make it fit
if (menuText.length() > maxChars) {
// if its close then just change the font size
if (menuText.length() <= maxChars + 1) {
fontSize = 8;
} else if (menuText.length() <= maxChars + 2) {
fontSize = 7;
} else if (menuText.length() <= maxChars + 3) {
fontSize = 7;
}
// if this is a Display-defined area then just truncate it since the
// display id should be enough to let the user know what the area is
else if (areaName.getSource() == AreaSource.DISPLAY_AREA) {
fontSize = 8;
menuText = menuText.substring(0, maxChars + 3);
truncated = true;
}
else if (areaName.getSource().isImagedBased()) {
// if a Mcidas or Gini satellite then the name is the satellite
// name and area or sector name
// separated with '/'
// in this case we can leave off the satelliteName
int sepIndx = menuText.indexOf(File.separator);
if (sepIndx == -1) {
statusHandler.handle(Priority.INFO,
"Expecting '/' in satellite defined area???? ");
menuText = menuText.substring(0, maxChars);
truncated = true;
} else {
String satName = menuText.substring(0, sepIndx);
String area = menuText.substring(sepIndx + 1);
// if the areaName is close then change the font size
if (area.length() > maxChars) {
if (area.length() <= maxChars + 1) {
fontSize = 8;
} else if (area.length() <= maxChars + 2) {
fontSize = 7;
} else if (area.length() <= maxChars + 3) {
fontSize = 7;
// else have to truncate
} else {
fontSize = 7;
area = area.substring(0, maxChars + 3);
truncated = true;
}
}
if (satName.length() > maxChars + 10 - fontSize) {
satName = satName.substring(0,
maxChars + 10 - fontSize);
truncated = true;
}
menuText = satName + "\n" + area;
}
} else {
fontSize = 8;
menuText = menuText.substring(0, maxChars + 1);
truncated = true;
}
}
// change the font and set the text (don't dispose the original font).
Font curFont = areaToolItem.getParent().getFont();
FontData[] fd = curFont.getFontData();
if (fd[0].getHeight() != fontSize) {
fd[0].setHeight(fontSize);
Device dev = curFont.getDevice();
if (areaFont != null) {
areaFont.dispose();
}
areaFont = new Font(dev, fd);
areaToolItem.getParent().setFont(areaFont);
}
int tbHght = (menuText.indexOf("\n") > 0 ? 47 : 30);
if (tbHght != toolBarSize.y) {
toolBarSize.y = (menuText.indexOf("\n") > 0 ? 47 : 30);
// without this the size will revert back when the dialog is resized
// for multi-pane
FormData formData = (FormData) areaToolItem.getParent()
.getLayoutData();
formData.height = tbHght;
areaToolItem.getParent().getLayoutData();
areaToolItem.getParent().getParent().layout(true);
}
areaToolItem.setText(menuText);
// if truncated then show the menuname in the tooltips
areaToolItem.setToolTipText(
truncated ? seldAreaMenuItem.getMenuName() : "");
}
// set the area and update the proj/center field
public void updateAreaGUI() {
PredefinedArea area = rbdMngr.getSelectedArea();
setAreaTextOnMenuItem(
new AreaName(area.getSource(), area.getAreaName()));
geoAreaInfoComp.setVisible(false);
resourceAreaOptsComp.setVisible(false);
if (area.getSource().isImagedBased()) {
resourceAreaOptsComp.setVisible(true);
if (area.getZoomLevel()
.equals(ZoomLevelStrings.FitToScreen.toString())) {
fitToScreenButton.setSelection(true);
sizeOfImageButton.setSelection(false);
} else if (area.getZoomLevel()
.equals(ZoomLevelStrings.SizeOfImage.toString())) {
fitToScreenButton.setSelection(false);
sizeOfImageButton.setSelection(true);
} else {
area.setZoomLevel("1.0");
fitToScreenButton.setSelection(true);
sizeOfImageButton.setSelection(false);
}
} else {
geoAreaInfoComp.setVisible(true);
String projStr = rbdMngr.getSelectedArea().getGridGeometry()
.getCoordinateReferenceSystem().getName().toString();
projInfoText.setText(projStr);
projInfoText.setToolTipText(projStr);
// use the GEMPAK name if possible.
for (String gemProj : gempakProjMap.keySet()) {
if (gempakProjMap.get(gemProj).equals(projStr)) {
projInfoText.setText(gemProj.toUpperCase());
break;
}
}
if (area.getMapCenter() != null) {
Integer lat = (int) (area.getMapCenter()[1] * 1000.0);
Integer lon = (int) (area.getMapCenter()[0] * 1000.0);
mapCenterText.setText(Double.toString((double) lat / 1000.0)
+ "/" + Double.toString((double) lon / 1000.0));
} else {
mapCenterText.setText("N/A");
}
}
}
private class SelectAreaAction extends Action {
private AreaMenuItem ami;
public SelectAreaAction(AreaMenuItem a) {
super(a.getMenuName());
ami = a;
}
@Override
public void run() {
try {
rbdMngr.setSelectedAreaName(
new AreaName(AreaSource.getAreaSource(ami.getSource()),
ami.getAreaName()));
updateAreaGUI();
} catch (VizException e) {
MessageDialog errDlg = new MessageDialog(
NcDisplayMngr.getCaveShell(), "Error", null,
e.getMessage(), MessageDialog.ERROR,
new String[] { "OK" }, 0);
errDlg.open();
}
}
}
/**
* Recursive method to create MenuManager from a Tree
*
* @param IMenuManager
*
* @param AreaMenuTree
*/
public void createAvailAreaMenuItems(IMenuManager areaMenuMngr,
AreaMenuTree areaMenu) {
for (AreaMenuTree areaSubMenu : areaMenu.getSubMenu()) {
// Base case: if there aren't any sub-menus add the AreaMenuItem to
// the menu
if (!areaSubMenu.hasSubMenu()) {
areaMenuMngr.add(
new SelectAreaAction(areaSubMenu.getAreaMenuItem()));
}
// If there's a sub-menu, create a IMenuManager recursively call
// createAvailAreaMenuItems with the subMenuManager and areaSubMenu
if (areaSubMenu.hasSubMenu()) {
String subMenuName = areaSubMenu.getMenuName();
IMenuManager subMenuManager = new MenuManager(subMenuName,
areaMenuMngr.getId() + "." + subMenuName);
areaMenuMngr.add(subMenuManager);
createAvailAreaMenuItems(subMenuManager, areaSubMenu);
}
}
}
// called when the user switches to this tab in the ResourceManagerDialog or
// when the EditRbd Dialog initializes
public void updateDialog() {
updateImportCombo();
// If the gui has not been set with the current rbdMngr then do it now.
updateGUI();
// updateGUI triggers the spinner which ends up calling
// rbdMngr.setPaneLayout(), so we need to reset this here.
rbdMngr.setRbdModified(false);
}
// set widgets based on rbdMngr
public void updateGUI() {
// update the display type combo
for (int i = 0; i < dispTypeCombo.getItemCount(); i++) {
NcDisplayType dType = NcDisplayType
.getDisplayType(dispTypeCombo.getItems()[i]);
if (dType.equals(rbdMngr.getRbdType())) {
dispTypeCombo.select(i);
}
}
if (dispTypeCombo.getSelectionIndex() == -1) {
dispTypeCombo.select(0);
}
rbdNameText.setText(rbdMngr.getRbdName());
rbdNameText.setSelection(0, rbdMngr.getRbdName().length());
rbdNameText.setFocus();
importRbdCombo.deselectAll();
for (int i = 0; i < importRbdCombo.getItemCount(); i++) {
String importRbdName = importRbdCombo.getItems()[i];
importRbdName = NcDisplayName
.parseNcDisplayNameString(importRbdName).getName();
if (importRbdName.equals(rbdMngr.getRbdName())) {
importRbdCombo.select(i);
break;
}
}
TimeSettingsCacheManager.getInstance()
.updateCacheLookupKey(rbdMngr.getRbdName());
if (importRbdCombo.getSelectionIndex() == -1) {
importRbdCombo.select(importRbdCombo.getItemCount() - 1);
}
updateAreaGUI();
// create new GraphTimelineControl if loading a Graph Display
timelineControl.dispose();
if (rbdMngr.getRbdType().equals(NcDisplayType.GRAPH_DISPLAY)) {
timelineControl = new GraphTimelineControl(timelineGroup);
} else {
timelineControl = new TimelineControl(timelineGroup);
}
timelineControl.addDominantResourceChangedListener(
new IDominantResourceChangedListener() {
@Override
public void dominantResourceChanged(
AbstractNatlCntrsRequestableResourceData newDomRsc) {
if (newDomRsc == null) {
autoUpdateButton
.setSelection(rbdMngr.isAutoUpdate());
autoUpdateButton.setEnabled(false);
} else if (newDomRsc.isAutoUpdateable()) {
autoUpdateButton.setEnabled(true);
autoUpdateButton.setSelection(true);
if (rbdMngr.getRbdType()
.equals(NcDisplayType.GRAPH_DISPLAY)) {
geoSyncPanesToggle.setSelection(true);
rbdMngr.syncPanesToArea();
}
} else {
autoUpdateButton.setSelection(false);
autoUpdateButton.setEnabled(false);
}
}
});
timelineGroup.pack();
shell.pack();
shell.setSize(initDlgSize);
geoSyncPanesToggle.setSelection(rbdMngr.isGeoSyncPanes());
multiPaneToggle.setSelection(rbdMngr.isMultiPane());
updateGUIforMultipane(rbdMngr.isMultiPane());
// set the pane sel buttons based on the combos also sets the rbdMngr's
// layout
if (rbdMngr.isMultiPane()) {
updatePaneLayout();
}
selectPane(rbdMngr.getSelectedPaneId());
INcPaneLayout paneLayout = rbdMngr.getPaneLayout();
// set the list of available resources for the timeline
for (int paneIndx = 0; paneIndx < paneLayout
.getNumberOfPanes(); paneIndx++) {
for (ResourceSelection rscSel : rbdMngr
.getRscsForPane(paneLayout.createPaneId(paneIndx))) {
if (rscSel.getResourceData() instanceof GroupResourceData) {
for (ResourcePair pair : ((GroupResourceData) rscSel
.getResourceData()).getResourceList()) {
if (pair.getResourceData() instanceof AbstractNatlCntrsRequestableResourceData) {
timelineControl.addAvailDomResource(
(AbstractNatlCntrsRequestableResourceData) pair
.getResourceData());
}
}
} else if (rscSel
.getResourceData() instanceof AbstractNatlCntrsRequestableResourceData) {
timelineControl.addAvailDomResource(
(AbstractNatlCntrsRequestableResourceData) rscSel
.getResourceData());
}
}
}
NCTimeMatcher timeMatcher = rbdMngr.getInitialTimeMatcher();
timelineControl.setTimeMatcher(timeMatcher);
if (timeMatcher.getDominantResource() != null
&& timeMatcher.getDominantResource().isAutoUpdateable()) {
autoUpdateButton.setEnabled(true);
autoUpdateButton.setSelection(rbdMngr.isAutoUpdate());
} else {
autoUpdateButton.setSelection(false);
autoUpdateButton.setEnabled(false);
}
}
// TODO : we could have the pane buttons indicate whether
// there are resources selected for them by changing the foreground color to
// yellow or green...
private void updatePaneLayout() {
int colCnt = ((NcPaneLayout) rbdMngr.getPaneLayout()).getColumns();
int rowCnt = ((NcPaneLayout) rbdMngr.getPaneLayout()).getRows();
for (int r = 0; r < rbdMngr.getMaxPaneLayout().getRows(); r++) {
for (int c = 0; c < rbdMngr.getMaxPaneLayout().getColumns(); c++) {
paneSelectionButtons[r][c].setVisible(r < rowCnt && c < colCnt);
}
}
}
// update the GUI with the selections (area/list of rscs) for the selected
// pane
private void selectPane(INcPaneID pane) {
NcPaneID seldPane = (NcPaneID) pane;
rbdMngr.setSelectedPaneId(seldPane);
if (rbdMngr.isMultiPane()) {
selectedResourceGroup.setText(
"Selected Resources for Pane " + seldPane.toString());
} else {
selectedResourceGroup.setText("Selected Resources");
}
// implement radio behavior
for (int r = 0; r < rbdMngr.getMaxPaneLayout().getRows(); r++) {
for (int c = 0; c < rbdMngr.getMaxPaneLayout().getColumns(); c++) {
paneSelectionButtons[r][c].setSelection(
(r == seldPane.getRow() && c == seldPane.getColumn()));
}
}
updateAreaGUI();
updateSelectedResourcesView(true);
}
public void removeSelectedResource(ResourceSelection rscSel) {
if (groupListViewer.getSelection() == null
|| groupListViewer.getSelection().isEmpty()
|| groupListViewer.getTable().getSelection()[0].getText()
.equalsIgnoreCase(ungrpStr)) {
rbdMngr.removeSelectedResource(rscSel);
} else { // remove from group
((GroupResourceData) getGroupResourceSelection().getResourceData())
.getResourceList().remove(rscSel.getResourcePair());
}
// remove this from the list of available dominant resources.
if (rscSel.getResourceData() instanceof AbstractNatlCntrsRequestableResourceData) {
timelineControl
.removeAvailDomResource((AbstractNatlCntrsRequestableResourceData) rscSel
.getResourceData());
}
}
/**
* Removes a User Defined Resource Group. Removes resources from the
* list of dominant resources. Removes resources from the dominant resource combo.
* If there are no resources left in any group, it will also remove the timeline.
*
* @param rscSel
* the user defined group to remove
*/
private void removeUserDefinedResourceGroup(ResourceSelection rscSel) {
AbstractResourceData data = null;
// Remove resources from the resource list
rbdMngr.removeSelectedResource(rscSel);
// Remove resources from the dominant resource combo and remove the
// timeline if no resources are left in any user group or the static group
ResourceList groupResourceList = ((GroupResourceData) rscSel
.getResourceData()).getResourceList();
for (int i = 0; i < groupResourceList.size(); i++) {
data = groupResourceList.get(i).getResourceData();
if (data instanceof AbstractNatlCntrsRequestableResourceData) {
timelineControl.removeAvailDomResource(
(AbstractNatlCntrsRequestableResourceData) data);
}
}
}
// Listener callback for the Edit Resource button and dbl click on the list
public void editResourceData() {
StructuredSelection sel_elems = (StructuredSelection) selectedResourceViewer
.getSelection();
ResourceSelection rscSel = (ResourceSelection) sel_elems
.getFirstElement();
if (rscSel == null) {
statusHandler.handle(Priority.INFO, "no resource is selected");
return;
}
Capabilities capObj = new Capabilities();
ResourcePair rp = rscSel.getResourcePair();
// getLoadProperties() is not null safe but getCapabilities() is, thus
// only one check is needed.
if (rp.getLoadProperties() != null) {
capObj = rp.getLoadProperties().getCapabilities();
}
INatlCntrsResourceData rscData = rscSel.getResourceData();
if (rscData == null) {
statusHandler.handle(Priority.INFO,
"seld resource is not a INatlCntrsResource");
return;
}
EditResourceAttrsDialogFactory factory = new EditResourceAttrsDialogFactory();
try {
ResourceDefnsMngr rscDefnsMngr = ResourceDefnsMngr.getInstance();
ResourceDefinition rscDefn = rscDefnsMngr.getResourceDefinition(
rscData.getResourceName().getRscType());
AttributeSet attSet = rscDefnsMngr
.getAttrSet(rscSel.getResourceName());
rscDefn.setAttributeSet(attSet);
String displayName = rscSel.getResourceName().toString()
.split("/")[2];
displayName = rscDefn.getRscGroupDisplayName(displayName);
String updatedAttrSetName = rscDefn.getRscAttributeDisplayName("");
// add on aliased attribute name
// simply change the popup title
if (!updatedAttrSetName.isEmpty()) {
displayName += " " + updatedAttrSetName;
factory.setTitle(displayName);
}
} catch (VizException e) {
statusHandler.handle(Priority.PROBLEM, e.getMessage());
}
factory.setShell(shell).setResourceData(rscData).setCapabilities(capObj)
.setApplyBtn(false);
if (factory.construct()) {
rbdMngr.setRbdModified(true);
}
// display modified (edited) name
if (!selectedResourceViewer.getControl().isDisposed()) {
selectedResourceViewer.refresh(true);
}
}
public void clearSeldResources() {
// remove the requestable resources from the timeline
for (ResourceSelection rbt : rbdMngr.getSelectedRscs()) {
if (rbt.getResourceData() instanceof AbstractNatlCntrsRequestableResourceData) {
timelineControl.removeAvailDomResource(
(AbstractNatlCntrsRequestableResourceData) rbt
.getResourceData());
}
}
rbdMngr.removeAllSelectedResources();
// TODO : should this reset the rbd to not modified if single pane? No
// since the num panes and/or the area could have changed. clearRbd will
// reset the modified flag
updateSelectedResourcesView(true);
}
// reset all panes. This includes 'hidden' panes which may have resources
// selected but are hidden because the user has changed to a smaller layout.
public void clearRBD() {
// TODO : ? reset the predefined area to the default???
if (rbdMngr.isMultiPane()) {
MessageDialog confirmDlg = new MessageDialog(shell, "Confirm", null,
"The will remove all resources selections\n"
+ "from all panes in this RBD. \n\n"
+ "Are you sure you want to do this?",
MessageDialog.QUESTION, new String[] { "Yes", "No" }, 0);
confirmDlg.open();
if (confirmDlg.getReturnCode() != MessageDialog.OK) {
return;
}
}
NcDisplayType curDispType = rbdMngr.getRbdType();
try {
AbstractRBD<?> dfltRbd = NcMapRBD.getDefaultRBD(curDispType);
rbdMngr.initFromRbdBundle(dfltRbd);
} catch (VizException e) {
MessageDialog errDlg = new MessageDialog(shell, "Error", null,
e.getMessage(), MessageDialog.ERROR, new String[] { "OK" },
0);
errDlg.open();
rbdMngr.init(curDispType);
}
TimeSettingsCacheManager.getInstance().reset();
updateGUI();
curGrp = -1;
groupListViewer.setInput(rbdMngr.getGroupResources());
selectedResourceViewer.setInput(rbdMngr.getUngroupedResources());
selectedResourceViewer.refresh();
setGroupButtons();
}
// reset the ListViewer's input and update all of the buttons
// TODO; get the currently selected resources and reselect them.
private void updateSelectedResourcesView(boolean updateList) {
if (updateList) {
StructuredSelection orig_sel_elems = (StructuredSelection) selectedResourceViewer
.getSelection();
List<?> origSeldRscsList = orig_sel_elems.toList();
if (groupListViewer.getSelection().isEmpty()
|| groupListViewer.getTable().getSelection()[0].getText()
.equalsIgnoreCase(ungrpStr)) {
selectedResourceViewer
.setInput(rbdMngr.getUngroupedResources());
} else {
selectedResourceViewer.setInput(rbdMngr.getResourcesInGroup(
groupListViewer.getTable().getSelection().length == 0
? null
: groupListViewer.getTable().getSelection()[0]
.getText()));
}
selectedResourceViewer.refresh(true);
List<ResourceSelection> newSeldRscsList = new ArrayList<>();
// create a new list of selected elements
for (Object object : origSeldRscsList) {
ResourceSelection rscSel = (ResourceSelection) object;
for (int r = 0; r < selectedResourceViewer.getList()
.getItemCount(); r++) {
if (rscSel == selectedResourceViewer.getElementAt(r)) {
newSeldRscsList.add(rscSel);
break;
}
}
}
selectedResourceViewer.setSelection(
new StructuredSelection(newSeldRscsList.toArray()), true);
}
int numSeldRscs = selectedResourceViewer.getList().getSelectionCount();
int numRscs = selectedResourceViewer.getList().getItemCount();
// the Clear button is enabled if there are more than 1 resources in the
// list.
clearPaneButton.setEnabled(numRscs > 1);
// the edit button is enabled iff there is only one selected resource.
editResourceButton.setEnabled(numSeldRscs == 1);
StructuredSelection sel_elems = (StructuredSelection) selectedResourceViewer
.getSelection();
List<ResourceSelection> seldRscsList = sel_elems.toList();
// Can't delete, replace or turn off the base overlay.
Boolean isBaseLevelRscSeld = false;
Boolean allRscsAreVisible = true;
for (ResourceSelection rscSel : seldRscsList) {
isBaseLevelRscSeld |= rscSel.isBaseLevelResource();
allRscsAreVisible &= rscSel.isVisible();
}
boolean firstSelected = false;
boolean lastSelected = false;
if (numSeldRscs == 1) {
firstSelected = (seldRscsList.get(0) == selectedResourceViewer
.getElementAt(0));
lastSelected = (seldRscsList.get(0) == selectedResourceViewer
.getElementAt(numRscs - 1));
}
// the replace button is enabled if there is only 1 resource selected
// and it is not the base resource
rscSelDlg.setReplaceEnabled((numSeldRscs == 1 && !isBaseLevelRscSeld));
// the delete button is only disabled if there is one the one base
// resource selected.
deleteResourceButton.setEnabled(
numSeldRscs > 1 || (numSeldRscs == 1 && !isBaseLevelRscSeld));
// the disable_rsc_btn is always enabled.
disableResourceButton.setEnabled((numSeldRscs > 0));
moveResourceDownButton.setEnabled((numSeldRscs == 1) && !lastSelected);
moveResourceUpButton.setEnabled((numSeldRscs == 1) && !firstSelected);
if (allRscsAreVisible) {
disableResourceButton.setSelection(false);
disableResourceButton.setText("Turn Off");
} else {
disableResourceButton.setSelection(true);
disableResourceButton.setText("Turn On");
}
}
// This will load the currently configured RBD (all panes) into
// a new editor or the active editor if the name matches the current
// name of the RBD
public void loadRBD(boolean close) {
String rbdName = rbdNameText.getText().trim();
if (rbdName == null || rbdName.isEmpty()) {
rbdName = "Preview";
}
// Since rbdLoader uses the same resources in the rbdBundle to load in
// the editor, we will need to make a copy here so that future edits are
// not immediately reflected in the loaded display. The easiest way to
// do this is to marshal and then unmarshal the rbd.
try {
rbdMngr.setGeoSyncPanes(geoSyncPanesToggle.getSelection());
rbdMngr.setAutoUpdate(autoUpdateButton.getSelection());
AbstractRBD<?> rbdBndl = rbdMngr.createRbdBundle(rbdName,
timelineControl.getTimeMatcher());
rbdBndl = AbstractRBD.clone(rbdBndl);
rbdBndl.resolveDominantResource();
ResourceBndlLoader rbdLoader = null;
rbdLoader = new ResourceBndlLoader("RBD Previewer");
// TODO : Allow the user to define preferences such as
// whether to prompt when re-loading into an existing editor,
// whether to look for an empty editor first before re-loading an
// exising one...
//
// Determine which Display Editor to use.
//
// 1-check if the name of the active editor is the same as the RBD
// and if so, re-load into this editor.
// 2-if the RBD was imported then look specifically for this display
// ID.
// 3-if no rbd name was given it will be called "Preview" and look
// for an existing "Preview" editor.
// 4-
// First look for a preview editor and if not found then check if
// the active editor name matches that of the current rbd name
// (Note: don't look for an editor matching the rbd name because it
// is possible to have the same named display for a different RBD.)
// If the active editor doesn't match then load into a new display
// editor
AbstractEditor editor = null;
// 1-if the active editor matches this rbdName, use the active
// editor
// Don't attempt to find an editor based just on the display name
// since they may not be unique without the display id.
if (editor == null) {
editor = NcDisplayMngr.getActiveNatlCntrsEditor();
if (!NcEditorUtil.getDisplayName(editor).getName()
.equals(rbdName)) {
editor = null;
}
// if they changed the layout then we should be able to modify
// the layout of the current
// / display but for now just punt and get a new editor.
else if (NcEditorUtil.getPaneLayout(editor)
.compare(rbdBndl.getPaneLayout()) != 0) {
statusHandler.handle(Priority.INFO,
"Creating new Editor because the paneLayout differs.");
editor = null;
}
}
// 2- look for an available editor that has not been modified.
// This is usually the initial 'default' editor but could be one
// that has been
// cleared/wiped, or one from the New Display menu.
if (editor == null) {
editor = NcDisplayMngr
.findUnmodifiedDisplayToLoad(rbdBndl.getDisplayType());
if (editor != null && NcEditorUtil.getPaneLayout(editor)
.compare(rbdBndl.getPaneLayout()) != 0) {
statusHandler.handle(Priority.INFO,
"Creating new Editor because the paneLayout differs.");
editor = null;
}
}
// 3- if the rbd was imported from a display and the name was not
// changed get this display and attempt to use it.
if (editor == null) {
NcDisplayName importDisplayName = NcDisplayName
.parseNcDisplayNameString(importRbdCombo.getText());
if (importDisplayName.getName().equals(rbdName)) {
// get by ID since the rbd name doesn't have to be unique
editor = NcDisplayMngr.findDisplayByID(
rbdBndl.getDisplayType(), importDisplayName);
if (editor != null && NcEditorUtil.getPaneLayout(editor)
.compare(rbdBndl.getPaneLayout()) != 0) {
editor = null;
}
}
}
// 4-reuse if it is a Preview editor.
if (editor == null && rbdName.equals("Preview")) {
editor = NcDisplayMngr
.findDisplayByName(rbdBndl.getDisplayType(), rbdName);
if (editor != null && NcEditorUtil.getPaneLayout(editor)
.compare(rbdBndl.getPaneLayout()) != 0) {
editor = null;
}
}
// 5-Create a new one.
// Note that it is possible for a display name matching the RBD name
// to not be reused if the display is not active. This is because
// the names may not be unique and so we can't determine which
// unless it was specifically imported into the Manager and even in
// this case they may not want to re-load it.
if (editor == null) {
editor = NcDisplayMngr.createNatlCntrsEditor(
rbdBndl.getDisplayType(), rbdName,
rbdBndl.getPaneLayout());
}
if (editor == null) {
throw new VizException(
"Unable to create a display to load the RBD.");
}
NcDisplayMngr.bringToTop(editor);
// Assign hot keys to group resources. Set visible for the selected
// group.
ResourceSelection rsel = getGroupResourceSelection();
for (AbstractRenderableDisplay rendDisp : rbdBndl.getDisplays()) {
int funKey = 1;
for (ResourcePair rp : rendDisp.getDescriptor()
.getResourceList()) {
if (rp.getResourceData() instanceof GroupResourceData) {
GroupResourceData grd = (GroupResourceData) rp
.getResourceData();
grd.setFuncKeyNum(funKey);
funKey++;
// If nothing selected, turn on all groups.
rp.getProperties().setVisible(true);
if (rsel != null
&& !((GroupResourceData) rsel.getResourcePair()
.getResourceData()).getGroupName()
.equals(grd.getGroupName())) {
rp.getProperties().setVisible(false);
}
}
}
}
rbdLoader.addRBD(rbdBndl, editor);
VizApp.runSync(rbdLoader);
// They aren't going to like this if there is an error loading....
// update the "Import RBD" list once a new RBD is loaded.
// after the rbdLoader starts, if the close flag is false, update
// the import_rbd_combo.
if (close) {
shell.dispose();
} else {
importRbdCombo.add(editor.getPartName());
importRbdCombo.setText(editor.getPartName());
rbdMngr.setRbdModified(false);
importRBD(editor.getPartName());
}
} catch (VizException e) {
final String msg = e.getMessage();
VizApp.runSync(new Runnable() {
@Override
public void run() {
Status status = new Status(Status.ERROR, UiPlugin.PLUGIN_ID,
0, msg, null);
ErrorDialog.openError(Display.getCurrent().getActiveShell(),
"ERROR", "Error.", status);
}
});
}
}
// After Loading an RBD the user may 're-load' a modified Pane. Currently
// the number of panes has to be the same as previously displayed.
public void loadPane() {
String rbdName = rbdNameText.getText();
if (rbdName == null || rbdName.isEmpty()) {
rbdName = "Preview";
}
// Since rbdLoader uses the same resources in the rbdBundle to load in
// the editor, we will need to make a copy here so that future edits are
// not immediately reflected in the loaded display. The easiest way to
// do this is to marshal and then unmarshall the rbd.
try {
rbdMngr.setGeoSyncPanes(geoSyncPanesToggle.getSelection());
rbdMngr.setAutoUpdate(autoUpdateButton.getSelection());
// TODO : check timeline compatibility with other panes...
AbstractRBD<?> rbdBndl = rbdMngr.createRbdBundle(rbdName,
timelineControl.getTimeMatcher());
rbdBndl = AbstractRBD.clone(rbdBndl);
ResourceBndlLoader rbdLoader = null;
rbdLoader = new ResourceBndlLoader("RBD Previewer");
rbdLoader.setLoadSelectedPaneOnly();
// Get the Display Editor to use. If the active editor doesn't
// match the name of the RBD then prompt the user.
AbstractEditor editor = NcDisplayMngr.getActiveNatlCntrsEditor();
// Check that the selected pane is within the layout of the Display
if (editor == null) {
throw new VizException("Error retrieving the Active Display??");
}
String activeEditorName = NcEditorUtil.getDisplayName(editor)
.getName();
if (!activeEditorName.equals(rbdName)) {
MessageDialog confirmDlg = new MessageDialog(shell,
"Confirm Load Pane", null,
"You will first need to Load the RBD before\n"
+ "re-loading a pane. \n\n"
+ "Do you want to load the currently defined RBD?",
MessageDialog.QUESTION, new String[] { "Yes", "No" },
0);
confirmDlg.open();
if (confirmDlg.getReturnCode() == MessageDialog.OK) {
loadRBD(false);
}
return;
}
// TODO : We could make this smarter by adjusting the display...
if (!NcEditorUtil.getPaneLayout(editor)
.equals(rbdBndl.getPaneLayout())) {
MessageDialog msgDlg = new MessageDialog(shell, "Load Pane",
null,
"The pane layout of the display doesn't match the currently selected\n"
+ "RBD pane layout. You will first need to Load the RBD before\n"
+ "changing the number of panes.",
MessageDialog.INFORMATION, new String[] { "OK" }, 0);
msgDlg.open();
return;
}
rbdLoader.addRBD(rbdBndl, editor);
VizApp.runSync(rbdLoader);
} catch (VizException e) {
final String msg = e.getMessage();
VizApp.runSync(new Runnable() {
@Override
public void run() {
Status status = new Status(Status.ERROR, UiPlugin.PLUGIN_ID,
0, msg, null);
ErrorDialog.openError(Display.getCurrent().getActiveShell(),
"ERROR", "Error.", status);
}
});
}
}
public void importRBD(String seldDisplayName) {
AbstractRBD<?> impRbd;
if (seldDisplayName.equals(ImportFromSPF)) {
SelectRbdsDialog impDlg = new SelectRbdsDialog(shell, "Import RBD",
false, false, false);
if (!impDlg.open()) {
return;
}
impRbd = impDlg.getSelectedRBD();
impRbd.resolveLatestCycleTimes();
} else {
// get NcMapRBD from selected display
AbstractEditor seldEditor = NcDisplayMngr.findDisplayByID(
NcDisplayName.parseNcDisplayNameString(seldDisplayName));
if (seldEditor == null) {
statusHandler.handle(Priority.PROBLEM,
"Unable to load Display :"
+ seldDisplayName.toString());
return;
}
try {
impRbd = AbstractRBD.createRbdFromEditor(seldEditor);
impRbd = AbstractRBD.clone(impRbd);
} catch (VizException e) {
MessageDialog errDlg = new MessageDialog(shell, "Error", null,
"Error Importing Rbd from Display, "
+ seldDisplayName.toString() + ".\n"
+ e.getMessage(),
MessageDialog.ERROR, new String[] { "OK" }, 0);
errDlg.open();
return;
}
}
// if any selections have been made then popup a confirmation msg
if (rbdMngr.isRbdModified()) {
MessageDialog confirmDlg = new MessageDialog(shell, "Confirm", null,
"You are about to replace the entire contents of this dialog. There is no 'undo'.\n\n"
+ "Do you want to continue the import and clear the current RBD selections?",
MessageDialog.QUESTION, new String[] { "Yes", "No" }, 0);
confirmDlg.open();
if (confirmDlg.getReturnCode() != MessageDialog.OK) {
return;
}
}
NcDisplayType curDispType = rbdMngr.getRbdType();
try {
rbdMngr.initFromRbdBundle(impRbd);
groupListViewer.setInput(rbdMngr.getGroupResources());
// the new group is always added at the top.
if (curGrp != -1) {
groupListViewer.getTable().setSelection(curGrp);
groupListViewer.refresh();
} else {
this.selectUngroupedGrp();
}
} catch (VizException e) {
rbdMngr.init(curDispType);
MessageDialog errDlg = new MessageDialog(shell, "Error", null,
"Error Importing RBD:" + impRbd.getRbdName() + "\n\n"
+ e.getMessage(),
MessageDialog.ERROR, new String[] { "OK" }, 0);
errDlg.open();
}
updateGUI();
// updateGUI triggers the spinner which ends up calling
// rbdMngr.setPaneLayout(), so we need to reset this here.
rbdMngr.setRbdModified(false);
}
// import just the given pane in the rbdBndl into the dialog's currently
// selected pane. Note: paneID is not the currently selected pane id when
// we are importing just a single pane.
public void importPane(AbstractRBD<?> rbdBndl, INcPaneID paneId)
throws VizException {
if (rbdBndl.getDisplayType() != rbdMngr.getRbdType()) {
throw new VizException("Can't import a non-matching display type.");
}
clearSeldResources();
rbdMngr.setPaneData(rbdBndl.getDisplayPane(paneId));
for (ResourceSelection rscSel : rbdMngr
.getRscsForPane(rbdMngr.getSelectedPaneId())) {
if (rscSel
.getResourceData() instanceof AbstractNatlCntrsRequestableResourceData) {
timelineControl.addAvailDomResource(
(AbstractNatlCntrsRequestableResourceData) rscSel
.getResourceData());
}
}
timelineControl.setTimeMatcher(rbdBndl.getTimeMatcher());
updateAreaGUI();
updateSelectedResourcesView(true);
}
private void updateGUIforMultipane(boolean isMultiPane) {
FormData fd = new FormData();
geoSyncPanesToggle.setVisible(isMultiPane);
paneLayoutGroup.setVisible(isMultiPane);
if (isMultiPane) {
groupGrp.setVisible(false);
fd.left = new FormAttachment(geoAreaGroup, 10, SWT.RIGHT);
fd.top = new FormAttachment(geoSyncPanesToggle, 10, SWT.BOTTOM);
fd.bottom = new FormAttachment(geoAreaGroup, 0, SWT.BOTTOM);
fd.right = new FormAttachment(100, -300);
selectedResourceGroup.setLayoutData(fd);
shell.setSize(new Point(multiPaneDlgWidth, shell.getSize().y));
} else {
groupGrp.setVisible(true);
fd.left = new FormAttachment(geoAreaGroup, 10, SWT.RIGHT);
fd.top = new FormAttachment(autoUpdateButton, 5, SWT.BOTTOM);
fd.right = new FormAttachment(100, -10);
fd.bottom = new FormAttachment(geoAreaGroup, 0, SWT.BOTTOM);
shell.setSize(new Point(multiPaneDlgWidth - 10, shell.getSize().y));
}
// the area name may be truncated based on a shorter toolbar widget
// reset it now that it is wider.
PredefinedArea area = rbdMngr.getSelectedArea();
setAreaTextOnMenuItem(
new AreaName(area.getSource(), area.getAreaName()));
}
public void saveRBD(boolean new_pane) {
try {
NCTimeMatcher timeMatcher = timelineControl.getTimeMatcher();
boolean saveRefTime = !timeMatcher.isCurrentRefTime();
boolean saveTimeAsConstant = false; // TODO -- how should this be
// set???
SpfsManager spfsMgr = SpfsManager.getInstance();
savedSpfGroup = spfsMgr.getLatestSpfGroup();
savedSpfName = spfsMgr.getLatestSpfName();
savedRbdName = spfsMgr.getLatestRbdName();
// get the filename to save to.
SaveRbdDialog saveDlg = new SaveRbdDialog(shell, savedSpfGroup,
savedSpfName, savedRbdName, saveRefTime, saveTimeAsConstant);
if ((Boolean) saveDlg.open() == false) {
return;
}
savedSpfGroup = saveDlg.getSeldSpfGroup();
savedSpfName = saveDlg.getSeldSpfName();
savedRbdName = saveDlg.getSeldRbdName();
saveRefTime = saveDlg.getSaveRefTime();
saveTimeAsConstant = saveDlg.getSaveTimeAsConstant();
// Set the name to the name that was actually used to save the RBD.
rbdNameText.setText(savedRbdName);
rbdMngr.setGeoSyncPanes(geoSyncPanesToggle.getSelection());
rbdMngr.setAutoUpdate(autoUpdateButton.getSelection());
AbstractRBD<?> rbdBndl = rbdMngr.createRbdBundle(savedRbdName,
timeMatcher);
spfsMgr.saveRbdToSpf(savedSpfGroup, savedSpfName, rbdBndl,
saveRefTime, saveTimeAsConstant);
VizApp.runSync(new Runnable() {
@Override
public void run() {
String msg = null;
msg = new String(
"Resource Bundle Display " + rbdNameText.getText()
+ " Saved to SPF " + savedSpfGroup
+ File.separator + savedSpfName + ".");
MessageBox mb = new MessageBox(shell, SWT.OK);
mb.setText("RBD Saved");
mb.setMessage(msg);
mb.open();
rbdMngr.setRbdModified(false);
}
});
} catch (VizException e) {
final String msg = e.getMessage();
VizApp.runSync(new Runnable() {
@Override
public void run() {
Status status = new Status(Status.ERROR, UiPlugin.PLUGIN_ID,
0, msg, null);
ErrorDialog.openError(Display.getCurrent().getActiveShell(),
"ERROR", "Error.", status);
}
});
}
}
// if Editing then save the current rbd to an AbstractRBD<?>
private void createEditedRbd() {
try {
NCTimeMatcher timeMatcher = timelineControl.getTimeMatcher();
if (!rbdNameText.getText().isEmpty()) {
rbdMngr.setRbdName(rbdNameText.getText());
}
rbdMngr.setGeoSyncPanes(geoSyncPanesToggle.getSelection());
rbdMngr.setAutoUpdate(autoUpdateButton.getSelection());
editedRbd = rbdMngr.createRbdBundle(rbdMngr.getRbdName(),
timeMatcher);
editedRbd.setIsEdited(rbdMngr.isRbdModified());
} catch (VizException e) {
editedRbd = null;
final String msg = e.getMessage();
VizApp.runSync(new Runnable() {
@Override
public void run() {
Status status = new Status(Status.ERROR, UiPlugin.PLUGIN_ID,
0, msg, null);
ErrorDialog.openError(Display.getCurrent().getActiveShell(),
"ERROR", "Error.", status);
}
});
}
}
public AbstractRBD<?> getEditedRbd() {
return editedRbd;
}
@Override
public void partBroughtToTop(IWorkbenchPartReference partRef) {
// In this method, if the CreateRbdControl object is not disposed and
// the part that is brought to top is an instance of NatlCntrsEditor,
// loop through item strings in import_rbd_combo and find the item which
// is identical to the title string of the NatlCntrsEditor. Set that
// item as selected for import_rbd_combo and call importRBD() for that
// item to update RBD contents.
AbstractEditor seldEditor = NcDisplayMngr.findDisplayByID(
NcDisplayName.parseNcDisplayNameString(partRef.getPartName()));
if ((false == this.isDisposed())
&& seldEditor instanceof NatlCntrsEditor) {
for (String item : importRbdCombo.getItems()) {
if (item.equalsIgnoreCase(seldEditor.getPartName())) {
try {
importRBD(item);
} catch (NullPointerException npe) {
// null DataTime can cause a panic here but is not an
// erroneous situation
}
}
}
}
}
private void addResourceGroup(String name) {
ResourcePair group = new ResourcePair();
// group always at bottom
group.setProperties(new ResourceProperties());
group.getProperties().setRenderingOrder(NCP_GROUP_RENDERING_ORDER);
// Add group, the default hot key is F1 and will be re-assigned at
// the time all groups are loaded.
grpColorBtn.setColorValue(GempakColor.convertToRGB(grpColor++));
GroupResourceData grd = new GroupResourceData(name, 1,
grpColorBtn.getColorValue());
group.setResourceData(grd);
try {
ResourceSelection sel = ResourceFactory.createResource(group);
rbdMngr.addSelectedResource(sel, false);
groupListViewer.setInput(rbdMngr.getGroupResources());
// the new group is always added at the top.
groupListViewer.getTable().setSelection(1);
curGrp = 0;
groupListViewer.refresh();
selectedResourceViewer.setInput(null);
selectedResourceViewer.refresh();
} catch (VizException e) {
}
}
private void setGroupButtons() {
if (groupListViewer.getTable().getSelectionCount() <= 0
|| groupListViewer.getTable().getSelection()[0].getText()
.equalsIgnoreCase(ungrpStr)) {
grpMoveUpBtn.setEnabled(false);
grpMoveDownBtn.setEnabled(false);
grpColorComp.setEnabled(false);
delGrpBtn.setEnabled(false);
} else if (groupListViewer.getTable().getItemCount() == 1) {
grpMoveUpBtn.setEnabled(false);
grpMoveDownBtn.setEnabled(false);
grpColorComp.setEnabled(true);
delGrpBtn.setEnabled(true);
} else {
int idx = groupListViewer.getTable().getSelectionIndex();
if (idx == 1) {
grpMoveUpBtn.setEnabled(false);
grpMoveDownBtn.setEnabled(true);
grpColorComp.setEnabled(true);
delGrpBtn.setEnabled(true);
}
if (idx == groupListViewer.getTable().getItemCount() - 1) {
grpMoveUpBtn.setEnabled(true);
grpMoveDownBtn.setEnabled(false);
grpColorComp.setEnabled(true);
delGrpBtn.setEnabled(true);
}
if (idx != 1
&& idx != groupListViewer.getTable().getItemCount() - 1) {
grpMoveUpBtn.setEnabled(true);
grpMoveDownBtn.setEnabled(true);
grpColorComp.setEnabled(true);
delGrpBtn.setEnabled(true);
}
}
// set the color button
ResourceSelection sel = getGroupResourceSelection();
if (sel != null) {
grpColorBtn.setColorValue(sel.getResourceData().getLegendColor());
}
}
private ResourceSelection getGroupResourceSelection() {
StructuredSelection isel = ((StructuredSelection) groupListViewer
.getSelection());
return (ResourceSelection) isel.getFirstElement();
}
private void selectUngroupedGrp() {
groupListViewer.getTable()
.setSelection(groupListViewer.getTable().getItemCount() - 1);
}
@Override
public void partActivated(IWorkbenchPartReference partRef) {
// Auto-generated method stub
}
@Override
public void partClosed(IWorkbenchPartReference partRef) {
// Auto-generated method stub
}
@Override
public void partDeactivated(IWorkbenchPartReference partRef) {
// Auto-generated method stub
}
@Override
public void partOpened(IWorkbenchPartReference partRef) {
// Auto-generated method stub
}
@Override
public void partHidden(IWorkbenchPartReference partRef) {
// Auto-generated method stub
}
@Override
public void partVisible(IWorkbenchPartReference partRef) {
// Auto-generated method stub
}
@Override
public void partInputChanged(IWorkbenchPartReference partRef) {
// Auto-generated method stub
}
}
|
Python | UTF-8 | 3,228 | 3.0625 | 3 | [] | no_license | import pygame
from pygame import locals as const
from constantes import *
class Selectors:
def __init__(self, ecran):
self.ecran = ecran
self.list = {}
def add(self, valName, values, pos):
self.list[valName] = Selector(self.ecran,valName,values,pos,SELECTOR_SIZE)
def collide(self,pos):
isCollide = False
for selector in self.list.values() :
isCollide |= selector.collide(pos)
return isCollide
def render(self):
for selector in self.list.values() :
selector.render()
class Selector:
def __init__(self, ecran, valName, values, pos, size):
self.ecran = ecran
self.values = values
self.pos = pos
self.size = size
self.valName = valName
self.selectedIndex = 0
self.previous = Arrow(self,0)
self.next = Arrow(self,1)
self.disp = Display(self)
# Vérifie si on a cliqué sur une des fléches
def collide(self,pos):
return self.previous.collide(pos) or self.next.collide(pos)
def render(self):
self.previous.render()
self.next.render()
self.disp.render()
def get_selected(self):
return self.values[self.selectedIndex]
class Display:
def __init__(self,selector):
self.selector = selector
def render(self):
font = pygame.font.SysFont(None,SELECTOR_TEXT_SIZE)
text = font.render(self.selector.valName.capitalize(), 1, (255,255,255))
self.selector.ecran.blit(text, (self.selector.pos[0] - text.get_width()/2, self.selector.pos[1] - text.get_height()/2))
class Arrow:
def __init__(self,selector,typeArrow):
self.selector = selector
self.type = typeArrow
self.image = pygame.image.load(ARROW_TEXTURE)
self.image = pygame.transform.scale(self.image,ARROW_SIZE)
self.hitbox = self.image.get_rect()
# Flèche de gauche (Previous)
if self.type == 0 :
self.image = pygame.transform.rotate(self.image, 180) # On la fait tourner à 180
self.hitbox.midleft = [self.selector.pos[0] - self.selector.size[0]//2, self.selector.pos[1]]
else:
self.hitbox.midright = [self.selector.pos[0] + self.selector.size[0]//2, self.selector.pos[1]]
self.pos = self.hitbox.topleft
# Vérifie si on a cliqué dessus
def collide(self,pos):
isCollide = self.hitbox.collidepoint(pos)
maxval = len(self.selector.values) - 1
if isCollide :
# Flèche de gauche (Previous)
if self.type == 0 :
if self.selector.selectedIndex <= 0 :
self.selector.selectedIndex = maxval
else :
self.selector.selectedIndex -= 1
# Flèche de droite (Next)
else:
if self.selector.selectedIndex >= maxval:
self.selector.selectedIndex = 0
else :
self.selector.selectedIndex += 1
return isCollide
def render(self):
self.selector.ecran.blit(self.image, self.pos)
# pygame.draw.rect(self.selector.ecran,GREEN,self.hitbox,1) |
Java | UTF-8 | 1,109 | 2.21875 | 2 | [] | no_license | package trong.lixco.com.jpa.entities;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import trong.lixco.com.jpa.entity.AbstractEntity;
@Entity
@Table(name = "skill")
public class Skill extends AbstractEntity {
private String name;
private String description;
private String file_document;// file tài liệu
private String file_video;
@OneToOne
private Course course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFile_document() {
return file_document;
}
public void setFile_document(String file_document) {
this.file_document = file_document;
}
public String getFile_video() {
return file_video;
}
public void setFile_video(String file_video) {
this.file_video = file_video;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
C++ | GB18030 | 1,214 | 2.625 | 3 | [] | no_license | #pragma once
#include "TGXML.h"
#include "GString.h"
typedef Cactus::vector<Cactus::String>::type StringVector;
COMMONUTIL_API extern StringVector split( const Cactus::String& str, const Cactus::String& delims = "\t\n ", unsigned int maxSplits = 0);
/*
XMLConfigReaderڶȡXMLãݴXMLPATHROOTµĽڵ㿪ʼңڣ
<root>
<net>
<port>9800</port>
<ip>127.0.0.1</ip>
</root>
ӦXMLPATHΪ
"net/port"
"net/ip"
עrootDzҪдģõXMLʽֻҪһROOTڵ㡣ȡʱ£
XMLConfigReader config;
config.Load("xxx.xml");
int port = config.GetInt("net/port");
вͬͬĽڵ㣬ʱֻҵһַϵĽڵ㡣
*/
class COMMONUTIL_API XMLConfigReader
{
public:
XMLConfigReader(void);
~XMLConfigReader(void);
bool Load(const Cactus::String& xmlFile);
Cactus::String GetString(const Cactus::String& xmlPath);
bool GetBool(const Cactus::String& xmlPath);
float GetFloat(const Cactus::String& xmlPath);
int GetInt(const Cactus::String& xmlPath);
protected:
Cactus::GXMLDoc _doc;
Cactus::GXMLElement _root;
};
|
C++ | UTF-8 | 2,770 | 2.890625 | 3 | [] | no_license | #include <functional>
#include <bits/stdc++.h>
using namespace std;
class ThreadPool{
private:
int size;
atomic<int> disponibles;
condition_variable cv;
mutex mtx,qmtx;
queue<function<void(void)>> tareas;
void waitforwork(){
}
public:
ThreadPool(int _size){
puts("voy a crear");
size=_size;
disponibles=size;
for(int i=0;i<size;i++){
puts("creo");
thread t(
[this]{
puts("owo");
while(1){
//puts("alo");
unique_lock<mutex> tlock(this->mtx);
cv.wait(tlock); //hace tuto
//muere aqui
//puts("asdasd");
qmtx.lock();
//saco tarea;
auto tarea = tareas.front();
tareas.pop();
qmtx.unlock();
disponibles--;
//HACER TAREA
tarea();
qmtx.lock();
while(disponibles==0 && !tareas.empty()){ //mientras todas estan ocupadas y hay tareas
qmtx.unlock();
auto tarea = tareas.front();
tareas.pop(); //trato de hacer mientras quedan
qmtx.lock();
}
qmtx.unlock();
disponibles++; //si no queda nada estoy libre
}
}
);
t.detach();
}
}
template<
typename funcion,
typename ... argumentos,
typename MRtrn=typename std::result_of<funcion(argumentos...)>::type>
auto encolar(
funcion && func,
argumentos && ...args) -> std::packaged_task<MRtrn(void)> {
auto aux = std::bind(std::forward<funcion>(func),
std::forward<argumentos>(args)... );
qmtx.lock();
tareas.push(aux);
qmtx.unlock();
cv.notify_one();
return std::packaged_task<MRtrn(void)>(aux);
}
template<
typename funcion,
typename ... argumentos,
typename MRtrn=typename std::result_of<funcion(argumentos...)>::type>
auto spawn(
funcion && func,
argumentos && ...args) -> std::packaged_task<MRtrn(void)> {
auto aux = std::bind(std::forward<funcion>(func),
std::forward<argumentos>(args)... );
if(disponibles>0){
qmtx.lock();
tareas.push(aux);
qmtx.unlock();
cv.notify_one();
return std::packaged_task<MRtrn(void)>(aux);
}else{
aux();
return std::packaged_task<MRtrn(void)>(aux);
}
}
};
int main(){
vector<int> v;
int tam = 25;
for(int i=0;i<tam;i++){
v.push_back(i);
}
random_shuffle(v.begin(), v.end());
cout<<"vector a usar"<<endl;
for(int i=0;i<tam;i++){
cout<<v[i]<<" ";
}
cout<<endl;
ThreadPool tp(5);
vector<packaged_task<int()> > res;
for(int i=0;i<5;i++){
res.push_back(
tp.encolar([i,tam,v]{
cout<<"aloalo"<<endl;
int mini = v[i];
for(int j=1;j<tam/5;j++){
mini = min(v[i+j],mini);
}
return mini;
})
);
}
puts("kk");
int rmini = res[0].get_future().get();
puts("asdas");
for(int i=1;i<res.size();i++){
rmini = min(res[i].get_future().get(),rmini);
}
cout<<"minimo es: "<<rmini<<endl;
return 0;
}
|
C# | UTF-8 | 1,649 | 3.546875 | 4 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
using System.Numerics;
namespace ShapeConsole
{
public class Circle : Shape2D
{
private Vector2 circleCenter;
private float circleArea;
private float circleCircumference;
private float circleRadius;
public Circle(Vector2 center, float radius)
{
//center of the circle
this.circleCenter = center;
// A = pi x r2
this.circleArea = (float)Math.PI * (radius * radius);
//set the radius
this.circleRadius = radius;
}
public override Vector3 Center
{
get
{
return new Vector3(circleCenter, 0.0f);
}
}
public override float Area
{
get
{
return circleArea;
}
}
public override float Circumference
{
//circumference of the circle (omkrets)
get
{
//calculate circumference according to the formula
//Ocirkel=2πr=πd
return ((this.circleRadius * 2) * (float)Math.PI);
}
}
public float Radius
{
get
{
return circleRadius;
}
}
public override string ToString()
{
return "circle @(" + Center.X.ToString("0.0#") + " , " + Center.Y.ToString("0.0#") + "): r = " + Radius.ToString("0.0#");
}
}
}
|
Go | UTF-8 | 1,194 | 2.84375 | 3 | [] | no_license | package middleware_test
import (
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/gorilla/mux"
"github.com/maanijou/imageservice/middleware"
"github.com/maanijou/imageservice/monitoring"
)
var sm *mux.Router
func TestMain(m *testing.M) {
route, err := setup()
sm = route
if err != nil {
teardown()
os.Exit(-1)
return
}
code := m.Run()
teardown()
os.Exit(code)
}
func setup() (*mux.Router, error) {
log.Println("Setup middleware test")
os.Chdir("..")
sm := mux.NewRouter().StrictSlash(true) // ignoring trailing slash
sm = sm.PathPrefix("/api/v1/").Subrouter()
sm.Use(middleware.CorsMiddleware)
sm.Use(middleware.LoggingMiddleware)
monitoring.SetupMonitoring(sm)
return sm, nil
}
func teardown() {
log.Println("cleanup middleware test")
}
func TestCORS(t *testing.T) {
req, err := http.NewRequest(
"GET",
"/api/v1/health/",
nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.Handler(sm)
handler.ServeHTTP(rr, req)
if rr.HeaderMap.Get("Access-Control-Allow-Origin") != "*" {
t.Errorf(
"Error in allow origin expected '*', got %v",
rr.HeaderMap.Get("Access-Control-Allow-Origin"),
)
}
}
|
Java | UTF-8 | 4,261 | 3.078125 | 3 | [
"Apache-2.0"
] | permissive | package org.neuroph.imgrec.filter.impl;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import org.neuroph.imgrec.ImageUtilities;
import org.neuroph.imgrec.filter.ImageFilter;
/**
* Otsu binarize filter serves to dynamically determine the threshold based on
* the whole image and for later binarization on black (0) and white (255) pixels.
* In determining threshold a image histogram is created in way that the value of
* each pixel of image affects on the histogram appearance. Then, depending upon
* the look of the histogram threshold counts and based on that, the real image
* which is binarized is made.The image before this filter MUST be GRAYSCALE and
* at the end image will contain only two colors - black and white.
*
* threshold - could be trainable
*
* Reference to: http://zerocool.is-a-geek.net/?p=376
* http://www.labbookpages.co.uk/software/imgProc/otsuThreshold.html
*
* @author Mihailo Stupar
*/
public class OtsuBinarizeFilter implements ImageFilter<BufferedImage>, Serializable {
private transient BufferedImage originalImage;
private transient BufferedImage filteredImage;
private static final int BLACK_PIXEL = 0;
private static final int WHITE_PIXEL = 255;
@Override
public BufferedImage apply(BufferedImage image) {
this.originalImage = image;
int width = originalImage.getWidth();
int height = originalImage.getHeight();
filteredImage = new BufferedImage(width, height, originalImage.getType());
int [] histogram = imageHistogram(originalImage);
int totalNumberOfpixels = width * height;
int threshold = calculateThreshold(histogram, totalNumberOfpixels); // ovo moze biti adaptivni parametar - adaptivna konvoluciona binarizacija
int alpha, gray, newColor;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
final Color col = new Color(originalImage.getRGB(x, y));
gray = col.getRed();
alpha = col.getAlpha();
if (gray > threshold)
newColor = WHITE_PIXEL;
else
newColor = BLACK_PIXEL;
newColor = ImageUtilities.argbToColor(alpha, newColor, newColor, newColor);
filteredImage.setRGB(x, y, newColor);
}
}
return filteredImage;
}
/**
* Creates image histogram for the given image.
*
* @param image
* @return
*/
private int[] imageHistogram(BufferedImage image) {
int[] histogram = new int[256];
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
// ovde bi bilo bolje da ne instanciram ovoliko objekata... nego nek atransformacija: (getRGB() >> 16) & 0xFF to se radi u getRed()
int gray = (image.getRGB(x, y) >> 16) & 0xFF; // ovo je getRed() samo crveni kanal jer se pretpostavlja da je prethodno prosla kroz grayscale filter pa su sva tri kaala ista
histogram[gray]++; // za svaku nijansu sive povecaj odgovarajucu poziciju za 1
}
}
return histogram;
}
private int calculateThreshold(int[] histogram, int total) {
float sum = 0;
for (int i = 0; i < 256; i++) {
sum += i * histogram[i];
}
float sumB = 0;
int wB = 0;
int wF = 0;
float varMax = 0;
int threshold = 0;
for (int i = 0; i < 256; i++) {
wB += histogram[i];
if (wB == 0) {
continue;
}
wF = total - wB;
if (wF == 0) {
break;
}
sumB += (float) (i * histogram[i]);
float mB = sumB / wB;
float mF = (sum - sumB) / wF;
float varBetween = (float) wB * (float) wF * (mB - mF) * (mB - mF);
if (varBetween > varMax) {
varMax = varBetween;
threshold = i;
}
}
return threshold;
}
@Override
public String toString() {
return "Otsu Binarize Filter";
}
} |
Markdown | UTF-8 | 1,032 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | 3、修改Activity中的代码,内容如下:
```
LinearLayout mLinearLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLinearLayout = new LinearLayout(this);
ImageView i = new ImageView(this);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mLinearLayout.addView(i);
setContentView(mLinearLayout);
Resources res = getResources();
TransitionDrawable transition = (TransitionDrawable) res
.getDrawable(R.drawable.expand_collapse);
i.setImageDrawable(transition);
transition.startTransition(10000);
}
```
4、如果修改的没有错误,运行程序,结果显示如下:
初始图片

过渡中的图片

最后的图片

屏幕上动画显示的是:从图片image_expand.png过渡到image_collapse.png,也就是我们在expand_collapse.xml中定义的一个transition动画。看完这个例子,你对Drawable的理解是否又深入些? |
JavaScript | UTF-8 | 248 | 2.921875 | 3 | [] | no_license | document.write('<h1>Please Don\'t Do This</h1>');
document.write('<p><span class="code">document.write</span> is naughty,\n');
document.write('and should be avoided at all costs.</p>');
document.write('<p>Today\'s date is ' + new Date() + '.</p>'); |
Markdown | UTF-8 | 265 | 3.140625 | 3 | [
"ISC"
] | permissive | *
===
### Description
Multiplies two numbers.
### Input
Takes two numerical arguments.
### Output
Returns the product as a numerical result.
### Example
\* 3 4
output
12
### Exceptions
If the arguments are not numerical, an exception is thrown.
|
C++ | UTF-8 | 1,086 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <limits>
#include <cmath>
#include <iomanip>
#include <functional>
#include <random>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using ll = long long;
int main()
{
// 整数の入力
ll N;
cin >> N;
vector<ll> counts(N);
vector<ll> a(N);
for (size_t i = 0; i < N; i++)
{
cin >> a[i];
counts[a[i]]++;
}
sort(a.begin(),a.end());
ll min_a = a[0];
ll max_a = a[N-1];
if (min_a < (max_a+1)/2){
cout << "Impossible" << endl;
return 0;
}
if (max_a % 2 == 0 && counts[min_a] != 1){
cout << "Impossible" << endl;
return 0;
}
if (max_a % 2 == 1 && counts[min_a] != 2){
cout << "Impossible" << endl;
return 0;
}
for(int i = min_a + 1;i <= max_a;i++){
if (counts[i] < 2){
cout << "Impossible" << endl;
return 0;
}
}
cout << "Possible" << endl;
return 0;
} |
JavaScript | UTF-8 | 772 | 3.0625 | 3 | [] | no_license | const quote = document.querySelector(".quote");
const author = document.querySelector(".author");
const new_quote = document.querySelector(".new_quote");
const twit = document.querySelector(".twit");
const random = "https://random-quote-generator.herokuapp.com/api/quotes/random";
const twitter = "https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=";
const getRandomQuote = () => {
return fetch(random)
.then(x => x.json())
}
const renderQuote = x => {
quote.innerText = x.quote
author.innerText = x.author
}
new_quote.addEventListener('click', async el => {
const nextQuote = await getRandomQuote()
renderQuote(nextQuote)
})
twit.addEventListener('click', () => {
window.open(twitter + quote.innerText)
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.