language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 1,799 | 2.75 | 3 |
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CheckUntil : MonoBehaviour {
private int CheckedTime = 0;
private float DelaySecond = 2f;
private int TimeoutMinits = 5;
private int CheckingTime;
public static bool isGetResult = false;
public void SetCheckingTime(float delaySecond, int timeoutMinits)
{
DelaySecond = delaySecond;
TimeoutMinits = timeoutMinits;
}
/// <summary>
/// Process CallBack Function
/// </summary>
public void CheckUntilGetResult(float delay, int timeoutMinits, Func<bool> checkAction, Action whenLoaded,Action whenTimeout)
{
CheckedTime = 0;
CheckingTime = (TimeoutMinits * 60 * 60) / (int)(DelaySecond * 10);
StartCoroutine(Check(checkAction,whenLoaded, whenTimeout));
}
IEnumerator Check(Func<bool> checkAction, Action whenLoaded,Action whenTimeout)
{
print("Checking...(" + CheckedTime + "/" + CheckingTime + ")");
yield return new WaitForSeconds(DelaySecond);
isGetResult = checkAction();
if (isGetResult) // Someone Joined
{
print(" -> Stop it");
Loading.stopLoading();
whenLoaded();
//StartGame
yield break;
}
else //Noone Join
{
CheckedTime++;
print(" -> Not Stop");
if (CheckingTime <= CheckedTime)
{
//print("Time Out");
//ShowTimeout
whenTimeout();
isGetResult = true;
yield break;
}
//Rechecking
StartCoroutine(Check(checkAction, whenLoaded, whenTimeout));
}
}
}
|
C++
|
UTF-8
| 6,336 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
// Copyright (c) 2016 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/**
* \file boost/process/group.hpp
*
* Defines a group process class.
* For additional information see the platform specific implementations:
*
* - [windows - job object](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684161.aspx)
* - [posix - process group](http://pubs.opengroup.org/onlinepubs/009695399/functions/setpgid.html)
*
*/
#ifndef BOOST_PROCESS_GROUP_HPP
#define BOOST_PROCESS_GROUP_HPP
#include <boost/process/detail/config.hpp>
#include <boost/process/child.hpp>
#include <chrono>
#include <memory>
#include <boost/none.hpp>
#include <atomic>
#if defined(BOOST_POSIX_API)
#include <boost/process/detail/posix/group_handle.hpp>
#include <boost/process/detail/posix/group_ref.hpp>
#include <boost/process/detail/posix/wait_group.hpp>
#elif defined(BOOST_WINDOWS_API)
#include <boost/process/detail/windows/group_handle.hpp>
#include <boost/process/detail/windows/group_ref.hpp>
#include <boost/process/detail/windows/wait_group.hpp>
#endif
namespace boost
{
namespace process
{
namespace detail
{
struct group_builder;
}
/**
* Represents a process group.
*
* Groups are movable but non-copyable. The destructor
* automatically closes handles to the group process.
*
* The group will have the same interface as std::thread.
*
* \note If the destructor is called without a previous detach or wait, the group will be terminated.
*
* \attention If a default-constructed group is used before being used in a process launch, the behaviour is undefined.
*
* \attention Waiting for groups is currently broken on windows and will most likely result in a dead-lock.
*/
class group
{
::boost::process::detail::api::group_handle _group_handle;
bool _attached = true;
public:
typedef ::boost::process::detail::api::group_handle group_handle;
///Native representation of the handle.
typedef group_handle::handle_t native_handle_t;
explicit group(group_handle &&ch) : _group_handle(std::move(ch)) {}
///Construct the group from a native_handle
explicit group(native_handle_t & handle) : _group_handle(handle) {};
group(const group&) = delete;
///Move constructor
group(group && lhs)
: _group_handle(std::move(lhs._group_handle)),
_attached (lhs._attached)
{
lhs._attached = false;
}
///Default constructor
group() = default;
group& operator=(const group&) = delete;
///Move assign
group& operator=(group && lhs)
{
_group_handle= std::move(lhs._group_handle);
_attached = lhs._attached;
return *this;
};
///Detach the group
void detach()
{
_attached = false;
}
/** Join the child. This just calls wait, but that way the naming is similar to std::thread */
void join()
{
wait();
}
/** Check if the child is joinable. */
bool joinable()
{
return _attached;
}
/** Destructor
*
* \note If the destructor is called without a previous detach or wait, the group will be terminated.
*
*/
~group()
{
std::error_code ec;
if ( _attached && valid())
terminate(ec);
}
///Obtain the native handle of the group.
native_handle_t native_handle() const
{
return _group_handle.handle();
}
///Wait for the process group to exit.
void wait()
{
boost::process::detail::api::wait(_group_handle);
}
///\overload void wait()
void wait(std::error_code & ec) noexcept
{
boost::process::detail::api::wait(_group_handle, ec);
}
/** Wait for the process group to exit for period of time.
* \return True if all child processes exited while waiting.*/
template< class Rep, class Period >
bool wait_for (const std::chrono::duration<Rep, Period>& rel_time)
{
return boost::process::detail::api::wait_for(_group_handle, rel_time);
}
/** \overload bool wait_for(const std::chrono::duration<Rep, Period>& timeout_time ) */
template< class Rep, class Period >
bool wait_for (const std::chrono::duration<Rep, Period>& rel_time, std::error_code & ec) noexcept
{
return boost::process::detail::api::wait_for(_group_handle, rel_time, ec);
}
/** Wait for the process group to exit until a point in time.
* \return True if all child processes exited while waiting.*/
template< class Clock, class Duration >
bool wait_until(const std::chrono::time_point<Clock, Duration>& timeout_time )
{
return boost::process::detail::api::wait_until(_group_handle, timeout_time);
}
/** \overload bool wait_until(const std::chrono::time_point<Clock, Duration>& timeout_time ) */
template< class Clock, class Duration >
bool wait_until(const std::chrono::time_point<Clock, Duration>& timeout_time, std::error_code & ec) noexcept
{
return boost::process::detail::api::wait_until(_group_handle, timeout_time, ec);
}
///Check if the group has a valid handle.
bool valid() const
{
return _group_handle.valid();
}
///Convenience to call valid.
explicit operator bool() const
{
return valid();
}
///Terminate the process group, i.e. all processes in the group
void terminate()
{
::boost::process::detail::api::terminate(_group_handle);
}
///\overload void terminate()
void terminate(std::error_code & ec) noexcept
{
::boost::process::detail::api::terminate(_group_handle, ec);
}
///Assign a child process to the group
void add(const child &c)
{
_group_handle.add(c.native_handle());
}
///\overload void assign(const child & c)
void add(const child &c, std::error_code & ec) noexcept
{
_group_handle.add(c.native_handle(), ec);
}
///Check if the child process is in the group
bool has(const child &c)
{
return _group_handle.has(c.native_handle());
}
///\overload bool has(const child &)
bool has(const child &c, std::error_code & ec) noexcept
{
return _group_handle.has(c.native_handle(), ec);
}
friend struct detail::group_builder;
};
namespace detail
{
struct group_tag;
struct group_builder
{
group * group_p;
void operator()(group & grp)
{
this->group_p = &grp;
};
typedef api::group_ref result_type;
api::group_ref get_initializer()
{
return api::group_ref (group_p->_group_handle);
};
};
template<>
struct initializer_tag<group>
{
typedef group_tag type;
};
template<>
struct initializer_builder<group_tag>
{
typedef group_builder type;
};
}
}
}
#endif
|
Python
|
UTF-8
| 106 | 3.109375 | 3 |
[] |
no_license
|
names=['马成超','张自豪','袁玉华','白明睿']
for i in names:
print('%s:你好么'%i)
|
C#
|
UTF-8
| 3,192 | 3.234375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ex2
{
class DrunkenNumbers
{
static void Main(string[] args)
{
double numberOfTours = double.Parse(Console.ReadLine());
long mitkoBeers = 0;
long vladoBeers = 0;
for (int i = 0; i < numberOfTours; i++)
{
List<int> beersInTour = new List<int>();
long currTourr = long.Parse(Console.ReadLine());
long currTour = Math.Abs(currTourr);
string beers = currTour + "";
if (beers.Length % 2 == 0)
{
for (int j = 0; j < beers.Length / 2; j++)
{
if (beers[j] != '-')
{
beersInTour.Add(Convert.ToInt32(beers[j] + " "));
}
}
foreach (var beer in beersInTour)
{
mitkoBeers += beer;
}
beersInTour.Clear();
for (int j = beers.Length - 1; j >= beers.Length / 2; j--)
{
if (beers[j] != '-')
{
beersInTour.Add(Convert.ToInt32(beers[j] + " "));
}
}
foreach (var beer in beersInTour)
{
vladoBeers += beer;
}
beersInTour.Clear();
}
if (beers.Length % 2 == 1)
{
for (int j = 0; j < (beers.Length / 2) + 1; j++)
{
if (beers[j] != '-')
{
beersInTour.Add(Convert.ToInt32(beers[j] + ""));
}
}
foreach (var beer in beersInTour)
{
mitkoBeers += beer;
}
beersInTour.Clear();
for (int j = beers.Length - 1; j >= (beers.Length / 2); j--)
{
if (beers[j] != '-')
{
beersInTour.Add(Convert.ToInt32(beers[j] + ""));
}
}
foreach (var beer in beersInTour)
{
vladoBeers += beer;
}
beersInTour.Clear();
}
}
if ((mitkoBeers - vladoBeers) > 0)
{
Console.WriteLine("M {0}", mitkoBeers - vladoBeers);
}
if ((mitkoBeers - vladoBeers) < 0)
{
Console.WriteLine("V {0}", vladoBeers - mitkoBeers);
}
if ((mitkoBeers - vladoBeers) == 0)
{
Console.WriteLine("No {0}", vladoBeers + mitkoBeers);
}
}
}
}
|
Java
|
UTF-8
| 1,390 | 2.59375 | 3 |
[] |
no_license
|
package kr.ac.kopo.account.user.ui;
import kr.ac.kopo.account.user.vo.UserVO;
public class SignUpUI extends BaseUI{
@Override
public void execute() throws Exception {
System.out.println("=================================================================");
System.out.println("\t\t\t회원가입");
System.out.println("=================================================================");
String id = scanStr("\t사용하실 id를 입력하세요.\t: ");
while(!userService.idCheck(id)) {
System.out.println("\tID가 이미 존재합니다. ");
id = scanStr("\t사용하실 id를 입력하세요.\t: ");
}
String pwd = scanStr("\t사용하실 비밀번호를 입력하세요.\t: ");
String name = scanStr("\t사용자 명을 입력하세요.\t: ");
String phoneNumber = scanStr("\t핸드폰 번호를 입력하세요.\t: ");
int age = scanInt("\t사용자 나이를 입력하세요.\t: ");
//////////////////////////////////////////////////
// 사용자 회원 가입 (User db 에 insert)
UserVO newUser = new UserVO();
newUser.setId(id);
newUser.setPassword(pwd);
newUser.setName(name);
newUser.setPhoneNumber(phoneNumber);
newUser.setAge(age);
userService.insertUser(newUser);
//////////////////////////////////////////////////
System.out.println("\t\t회원가입을 완료하였습니다.\n");
Thread.sleep(1000);
}
}
|
JavaScript
|
UTF-8
| 5,151 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
const implementations = {
c: {
name: "C",
repo: "cdtp",
},
cpp: {
name: "C++",
repo: "cppdtp",
},
cs: {
name: "C#",
repo: "CSDTP",
},
java: {
name: "Java",
repo: "JDTP",
},
ts: {
name: "JavaScript/TypeScript",
repo: "dtp.js",
},
py: {
name: "Python",
repo: "dtppy",
},
go: {
name: "Go",
repo: "godtp",
},
rs: {
name: "Rust",
repo: "rustdtp",
},
};
const implementationExamples = {};
function updateComparison(element, selected) {
const sideIndex = element.id.includes("left") ? 0 : 1;
const implServer =
document.getElementsByClassName("impl-server")[0].children[sideIndex];
const implClient =
document.getElementsByClassName("impl-client")[0].children[sideIndex];
const exampleServer = implServer.getElementsByTagName("code")[0];
const exampleClient = implClient.getElementsByTagName("code")[0];
const serverHeader = implServer.getElementsByTagName("h3")[0];
const clientHeader = implClient.getElementsByTagName("h3")[0];
const selectedName = implementations[selected].name;
const serverCode = implementationExamples[selected].server
.replaceAll("<", "<")
.replaceAll(">", ">");
const clientCode = implementationExamples[selected].client
.replaceAll("<", "<")
.replaceAll(">", ">");
exampleServer.classList = "";
exampleServer.classList.add("hljs", `language-${selected}`);
exampleServer.innerHTML = serverCode;
exampleClient.classList = "";
exampleClient.classList.add("hljs", `language-${selected}`);
exampleClient.innerHTML = clientCode;
serverHeader.innerText = `${selectedName} server`;
clientHeader.innerText = `${selectedName} client`;
hljs.highlightAll();
}
async function populateExamples() {
const examples = await Promise.all(
Object.keys(implementations).map(async (impl) => {
const repoName = implementations[impl].repo;
const exampleReadme = await fetch(
`https://raw.githubusercontent.com/WKHAllen/${repoName}/main/README.md`
);
const readmeText = await exampleReadme.text();
if (
readmeText.includes("## Creating a server") &&
readmeText.includes("## Creating a client")
) {
const serverSection = readmeText.split("## Creating a server")[1];
const serverExampleWithLanguage = serverSection.split("```")[1];
const serverExample = serverExampleWithLanguage
.slice(serverExampleWithLanguage.indexOf("\n"))
.trim();
const clientSection = readmeText.split("## Creating a client")[1];
const clientExampleWithLanguage = clientSection.split("```")[1];
const clientExample = clientExampleWithLanguage
.slice(clientExampleWithLanguage.indexOf("\n"))
.trim();
return {
language: impl,
server: serverExample,
client: clientExample,
};
} else {
return null;
}
})
);
for (const example of examples) {
if (example !== null) {
implementationExamples[example.language] = {
server: example.server,
client: example.client,
};
}
}
const implCompareLeft = document.getElementById("impl-compare-left");
const implCompareRight = document.getElementById("impl-compare-right");
for (const impl of Object.keys(implementationExamples)) {
const implOptionLeft = document.createElement("option");
implOptionLeft.setAttribute("value", impl);
implOptionLeft.innerText = implementations[impl].name;
const implOptionRight = document.createElement("option");
implOptionRight.setAttribute("value", impl);
implOptionRight.innerText = implementations[impl].name;
implCompareLeft.appendChild(implOptionLeft);
implCompareRight.appendChild(implOptionRight);
}
const leftSelectionIndex = Math.floor(
Math.random() * Object.keys(implementationExamples).length
);
let rightSelectionIndex = leftSelectionIndex;
while (rightSelectionIndex === leftSelectionIndex) {
rightSelectionIndex = Math.floor(
Math.random() * Object.keys(implementationExamples).length
);
}
const leftSelection = Object.keys(implementationExamples)[leftSelectionIndex];
const rightSelection = Object.keys(implementationExamples)[
rightSelectionIndex
];
implCompareLeft.value = leftSelection;
implCompareRight.value = rightSelection;
updateComparison(implCompareLeft, leftSelection);
updateComparison(implCompareRight, rightSelection);
}
function showImplementationIndices() {
const table = document.getElementsByClassName("impl-table")[0];
const rows = table.getElementsByTagName("tr");
const indexHeading = document.createElement("th");
indexHeading.innerText = "#";
rows[0].insertBefore(indexHeading, rows[0].firstChild);
for (let i = 1; i < rows.length; i++) {
const indexData = document.createElement("td");
indexData.innerText = rows[i].rowIndex;
rows[i].insertBefore(indexData, rows[i].firstChild);
}
}
window.addEventListener("load", async () => {
await populateExamples();
showImplementationIndices();
hljs.highlightAll();
});
|
C
|
UTF-8
| 3,229 | 3.375 | 3 |
[] |
no_license
|
#include "treap.h"
node* init_node(int val) {
node* new_node = (node*)malloc(sizeof(node));
if (!new_node)
return NULL;
new_node->left = new_node->right = NULL;
new_node->val = val;
new_node->prior = rand();
new_node->count = 1;
return new_node;
}
int get_count(node* p) {
return p ? p->count : 0;
}
void update_count(node* p) {
if (p)
p->count = get_count(p->left) + get_count(p->right) + 1;
}
node* merge(node* l, node* r) {
node* res = NULL;
if (!l)
res = r;
else if (!r)
res = l;
else if (l->prior > r->prior) {
l->right = merge(l->right, r);
res = l;
}
else {
r->left = merge(l, r->left);
res = r;
}
update_count(res);
return res;
}
//[0..n]->[0..key-1] + [key..pos];
// add's default value is 0
void split(int key, node* root, node** l, node** r, int add) {
if (!root) {
*l = *r = NULL;
return;
}
int cur_key = get_count(root->left) + add;
if (key <= cur_key) {
split(key, root->left, l, &(root->left), add);
*r = root;
}
else {
split(key, root->right, &(root->right), r, add + 1 + get_count(root->left));
*l = root;
}
update_count(root);
}
void insert(int val, int pos, node** root) {
node* new_node = init_node(val);
node* head = NULL;
node* tail = NULL;
if (pos < 0 || !new_node)
return;
split(pos, *root, &head, &tail, DEFAULT_ADD_VAL);
*root = merge(merge(head, new_node), tail);
}
void print(node* root) {
if (!root)
return;
print(root->left);
printf("%d ", root->val);
print(root->right);
}
int del(int pos, node** root) {
int res = NOTHING_DELETED;
node* pos_elem = NULL;
node* head = NULL;
node* tail = NULL;
node* new_tail = NULL;
if (pos < 0)
return res;
split(pos, *root, &head, &tail, DEFAULT_ADD_VAL);
split(1, tail, &pos_elem, &new_tail, DEFAULT_ADD_VAL);
if (pos_elem) {
res = SOMETHING_DELETED;
free(pos_elem);
}
*root = merge(head, new_tail);
return res;
}
void free_tree(node* root) {
if (root) {
free_tree((root)->left);
free_tree((root)->right);
free(root);
root = NULL;
}
}
void check(int val, node* root, bool* contains) {
if (root) {
if (root->val == val)
*contains = true;
check(val, root->left, contains);
check(val, root->right, contains);
}
}
void find(int val, node* root, node** result) {
if (root && !(*result)) { // !result not to call function if node's already found earlier
if (root->val == val) {
*result = root;
}
find(val, root->left, result);
find(val, root->right, result);
}
}
void del_val(int val, node** root, bool* deleted) {
if (*root && !(*deleted)) {
if ((*root)->val == val) {
node* l = (*root)->left;
node* r = (*root)->right;
free(*root);
*root = merge(l, r);
*deleted = true;
return;
}
del_val(val, &((*root)->left),deleted);
del_val(val, &((*root)->right),deleted);
}
}
//void del_val(int val, node** root) {
//
//
// if (*root && (*root)->val == val) {
// node* l = (*root)->left;
// node* r = (*root)->right;
// free(*root);
// *root = merge(l, r);
// return;
// }
//
//
// node* del_node = NULL;
// find(val, *root, &del_node);
// if (del_node) {
// node* l = (del_node)->left;
// node* r = (del_node)->right;
// free(del_node);
// del_node = merge(l, r);
// }
//}
|
C
|
UTF-8
| 3,056 | 2.90625 | 3 |
[] |
no_license
|
#include "my_http_server.h"
// @ Taskes SSID and wrapps it in html from.
static char *form_wrapper(char *ssid_name) {
char res[400];
bzero(res, 400);
sprintf(res, "<form enctype=\"text/plain\" action=\"/\" method=\"post\">\
<p>%s <input name=\"%s\" value=\"\" type=\"text\" size=\"40\" placeholder=\"password\">\
<input type=\"submit\">\
</p>\
</form>", ssid_name, ssid_name);
char *result = mx_string_copy(res);
return result;
}
/* @Handles http get request URL: /
* 1. Scans all available wifi networks.
* 2. Froms html response, where there are forms
* for selecting wifi ssid and entering password.
* 3. Sends response.
*/
esp_err_t get_handler(httpd_req_t *req) {
char response[20000];
bzero(response, 20000);
printf("scanning wifi_networks...\n");
char **avaliable_networks = scan_wifi_networks();
printf("scanning end\n");
// response formation.
char *wrapped_str;
int index = 0;
for (int i = 0; avaliable_networks[i]; ++i) {
wrapped_str = form_wrapper(avaliable_networks[i]);
for (int j = 0; wrapped_str[j]; ++j) {
response[index] = wrapped_str[j];
index++;
}
free(wrapped_str);
}
// sending response.
httpd_resp_send(req, response, HTTPD_RESP_USE_STRLEN);
// freeing memmory.
for (int i = 0; avaliable_networks[i]; ++i) {free(avaliable_networks[i]);}
free(avaliable_networks);
return ESP_OK;
}
/* @ Received data, user entered to connect to wifi.
* Received data structure:
* wifi_ssid=wifi_password
*
*/
esp_err_t post_handler(httpd_req_t *req) {
char content[800];
bzero(content, 800);
size_t recv_size = sizeof(content);
int ret = httpd_req_recv(req, content, recv_size);
if (ret <= 0) {
if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
httpd_resp_send_408(req);
}
return ESP_FAIL;
}
char *wifi_ssid = strtok(content, "=");
char *wifi_pass = strtok(NULL , "\r");
int status = connect_to_wifi(wifi_ssid, wifi_pass);
char *msg = "OK. Device is connected to wifi";
if (status == -1) {
msg = "Connection failed. Some error occured(Maybe password is wrong). Try again.";
}
httpd_resp_send(req, msg, strlen(msg));
vTaskDelay(50);
esp_restart();
return ESP_OK;
}
httpd_uri_t uri_get = {
.uri = "/",
.method = HTTP_GET,
.handler = get_handler,
.user_ctx = NULL
};
httpd_uri_t uri_post = {
.uri = "/",
.method = HTTP_POST,
.handler = post_handler,
.user_ctx = NULL
};
// Initialize simple http server.
httpd_handle_t http_server_init() {
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.stack_size = 180000;
httpd_handle_t server = NULL;
if (httpd_start(&server, &config) == ESP_OK) {
httpd_register_uri_handler(server, &uri_get);
httpd_register_uri_handler(server, &uri_post);
}
return server;
}
|
Markdown
|
UTF-8
| 1,051 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
<a name="dbk_configure"></a>
## dbk_configure
```python
dbk_configure(name, profile)
```
For example, if the BUILD file contains:
```python
dbk_configure(
name = "cfg"
profile = "DEFAULT",
)
```
<table class="table table-condensed table-bordered table-params">
<colgroup>
<col class="col-param" />
<col class="param-description" />
</colgroup>
<thead>
<tr>
<th colspan="2">Attributes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>name</code></td>
<td>
<code>Name, required</code>
<p>A unique name for this rule.</p>
</td>
</tr>
<tr>
<td><code>profile</code></td>
<td>
<code>String, required</code>
<p>The name of the profile defined when set up authentication with databricks.</p>
<p>This value is defined when <a href="/README.md#databricks_authentication">Set Up Authentication.</a></p>
<p><code>profile = "DEFAULT"</code></p>
<p>This field supports stamp variables.</p>
</td>
</tr>
</tbody>
</table>
|
Java
|
UTF-8
| 2,564 | 2.796875 | 3 |
[] |
no_license
|
package fiabilitate;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class GeneratePredicate {
private static ScriptEngineManager factory = new ScriptEngineManager();
private static ScriptEngine engine = factory.getEngineByName("JavaScript");
public static void main(String[] args) throws ScriptException {
String[] variablesList = {"a", "b", "c", "d"};
String expression = "(a ∨ b) ∧ (c ∨ d)";
evaluateExpresionPossibilities(variablesList, expression, variablesList.length);
System.out.println();
variablesList = new String[]{"a", "b", "c"};
expression = "(¬a ∧ ¬b) ∨ (a ∧ ¬c) ∨ (¬a ∧ c)";
evaluateExpresionPossibilities(variablesList, expression, variablesList.length);
System.out.println();
variablesList = new String[]{"a", "b", "c", "d"};
expression = "a ∨ b ∨ (c ∧ d)";
evaluateExpresionPossibilities(variablesList, expression, variablesList.length);
System.out.println();
variablesList = new String[]{"a", "b", "c"};
expression = "(a ∧ b) ∨ (b ∧ c) ∨ (a ∧ c)";
evaluateExpresionPossibilities(variablesList, expression, variablesList.length);
}
private static void evaluateExpresionPossibilities(String[] variablesList, String expression, int n) throws ScriptException {
System.out.println(expression);
for (int i = 0; i < Math.pow(2, n); i++) {
String combination = generateCombination(i, n);
evaluateExpression(expression, variablesList, combination);
}
}
public static void evaluateExpression(String expression, String[] variablesList, String combination) throws ScriptException {
for (int variableIndex = 0; variableIndex < variablesList.length; variableIndex++) {
String variable = combination.charAt(variableIndex) == '0' ? "false" : "true";
expression = expression.replace(variablesList[variableIndex], variable);
}
expression = expression.replace("∧", "&&");
expression = expression.replace("∨", "||");
expression = expression.replace("¬", "!");
System.out.println(expression + " = " + engine.eval(expression));
}
public static String generateCombination(int i, int n) {
String bin = Integer.toBinaryString(i);
while (bin.length() < n)
bin = "0" + bin;
// System.out.println(bin);
return bin;
}
}
|
Java
|
UTF-8
| 105 | 1.789063 | 2 |
[
"MIT"
] |
permissive
|
package TP3;
class InvalidKeyException extends Exception {
public InvalidKeyException() {
}
}
|
JavaScript
|
UTF-8
| 2,887 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import React, { Component } from 'react';
import * as d3 from 'd3';
import PropTypes from 'prop-types';
// Utils
import {
COLOR_BLACK, COLOR_BLUE_DARK, COLOR_CYAN_DARK, COLOR_RED_DARK,
} from '../../../utils/constants';
class PostTimeline extends Component {
componentDidMount() {
const { numberOfPosts } = this.props;
const listOfPosts = document.getElementById('list-of-posts');
const colors = {
red: COLOR_RED_DARK,
cyan: COLOR_CYAN_DARK,
blue: COLOR_BLUE_DARK,
black: COLOR_BLACK,
};
const timelineWrapper = document.getElementById('timeline-wrapper');
if (timelineWrapper) {
const postMarginBottom = window.getComputedStyle(listOfPosts.children[0]).marginBottom;
const timelineHeight = parseInt(window.getComputedStyle((listOfPosts)).height, 0) - parseInt(postMarginBottom, 0);
const timelineWrapperStyles = window.getComputedStyle(timelineWrapper);
const timelineWidth = parseInt(timelineWrapperStyles.width, 0)
- parseInt(timelineWrapperStyles.paddingLeft, 0)
- parseInt(timelineWrapperStyles.paddingRight, 0);
const timelineVector = d3.select('#timeline')
.append('svg')
.attr('height', timelineHeight)
.attr('width', timelineWidth);
// Base line
const lineGenerator = d3.line();
const points = [
[timelineWidth / 2, 0],
[timelineWidth / 2, timelineHeight],
];
const baseLine = lineGenerator(points);
timelineVector
.append('path')
.attr('d', baseLine)
.attr('fill', 'none')
.attr('stroke-width', 1)
.attr('stroke', colors.black);
const smallCircleRadius = 5;
const bigCircleRadius = 6;
// Append the last circles
timelineVector
.append('circle')
.attr('cx', points[1][0])
.attr('cy', points[1][1] - bigCircleRadius)
.attr('r', bigCircleRadius)
.attr('fill', colors.black);
let postDotOffset = 0;
// Append circles for each post
for (let count = 0; count < numberOfPosts; count += 1) {
timelineVector
.append('circle')
.attr('cx', points[0][0])
.attr('cy', points[0][1] + postDotOffset + smallCircleRadius)
.attr('r', smallCircleRadius)
.attr('fill', () => {
const keys = Object.keys(colors);
keys.splice(keys.indexOf('black'), 1);
return colors[keys[count % 3]];
});
// Height of nth post
const postHeight = window.getComputedStyle(listOfPosts.children[count]).height;
postDotOffset += parseInt(postHeight, 0) + parseInt(postMarginBottom, 0);
}
}
}
render() {
return (
<div id="timeline" />
);
}
}
PostTimeline.propTypes = {
numberOfPosts: PropTypes.number.isRequired,
};
export default PostTimeline;
|
Python
|
UTF-8
| 4,110 | 2.84375 | 3 |
[
"ISC"
] |
permissive
|
import logging
from typing import Collection, Dict, List, Optional, Sequence
import wx
from wx.lib.mixins.listctrl import ColumnSorterMixin
logger = logging.getLogger(__name__)
class AdvancedListCtrl(wx.ListCtrl, ColumnSorterMixin):
# wx.LC_SORT_* breaks idtopos
def __init__(self, *args, **kwargs):
wx.ListCtrl.__init__(self, *args, **kwargs)
self.columns = 0
self._init()
ColumnSorterMixin.__init__(self, 0)
# self.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnDeleteItem)
# self.Bind(wx.EVT_LIST_INSERT_ITEM, self.OnInsertItem)
def _init(self):
self.rows = 0
self.itemDataMap = {}
self.insertcount = 0
self.idtopos = {}
def GetListCtrl(self) -> "AdvancedListCtrl":
return self
def ClearAll(self, clear_columns: bool = True) -> None:
if clear_columns:
wx.ListCtrl.ClearAll(self)
self.columns = 0
else:
wx.ListCtrl.DeleteAllItems(self)
self._init()
def Setup(self, columns: Collection[str]) -> None:
self.columns = len(columns)
self.SetColumnCount(self.columns)
for i, col in enumerate(columns):
self.InsertColumn(i, col)
def Append(self, items: Sequence[str]) -> None:
if len(items) != self.columns:
raise ValueError("Length of items doesn't match available columns")
pos = self.InsertItem(self.rows, items[0])
assert pos == self.rows
# logger.debug("Appending Item on rows->pos: {}->{}".format(self.rows, pos))
self.rows += 1
self.SetItemData(pos, self.insertcount)
self.itemDataMap[self.insertcount] = items
"""for id, pos in self.idtopos.items():
if pos >= event.Index:
self.idtopos[id] = pos + 1"""
self.idtopos[self.insertcount] = pos
self.insertcount += 1
for col in range(1, self.columns):
self.SetItem(pos, col, items[col])
return self.insertcount - 1
def Edit(self, pos: int, items: Dict[int, str]):
"""items is dict with col as key and string als value"""
for col, val in items.items():
self.SetItem(pos, col, val)
def GetSelections(self) -> List[int]:
indexes = []
pos = self.GetFirstSelected()
while pos != -1:
indexes.append(pos)
pos = self.GetNextSelected(pos)
return indexes
def DeleteSelectedItems(self) -> List[int]:
# might be faster with autoarrange (listbox only??) off, no reversed -> autoarrange on
indexes = self.GetSelections()
for index in reversed(indexes):
self.DeleteItem(index)
self.rows -= 1
id = self.GetItemData(index)
del self.itemDataMap[id]
del self.idtopos[id]
return indexes
def Get(self, pos: int = 0) -> str:
if pos < 0:
return self.GetItem(self.GetItemCount() + 1 + pos).GetText()
else:
return self.GetItem(pos).GetText()
def IDtoPos(self, id: int) -> int:
return self.idtopos[id]
def Delete(self, pos: int = 0) -> Optional[str]:
if pos < 0:
index = self.GetItemCount() + 1 + pos
else:
index = pos
if self.GetItemCount() > pos:
item = self.GetItem(index)
ret = item.GetText()
id = self.GetItemData(index)
del self.itemDataMap[id]
del self.idtopos[id]
self.rows -= 1
self.DeleteItem(index)
return ret
else:
return None
class AdvancedItemContainerMixin:
def DeleteSelectedItems(self) -> List[int]:
# might be faster with autoarrange of, no reversed -> autoarrange on
indexes = self.GetSelections()
for index in reversed(indexes):
self.Delete(index)
return indexes
class AdvancedListBox(wx.ListBox, AdvancedItemContainerMixin):
def __init__(self, *args, **kwargs) -> None:
wx.ListBox.__init__(self, *args, **kwargs)
|
PHP
|
UTF-8
| 1,880 | 2.578125 | 3 |
[] |
no_license
|
<?php
// mengambil ID
$id = $_GET['id'];
$query = mysqli_query($koneksi, "SELECT kode_merk,nama_merk FROM merk WHERE kode_merk='$id'");
$data = mysqli_fetch_array($query);
//Proses Update Data Hak akses
if (isset($_POST['update'])) {
$kode_merk = $_POST['kode_merk'];
$nama_merk = ucfirst($_POST['nama_merk']);
$update = mysqli_query($koneksi, "UPDATE merk SET nama_merk='$nama_merk' WHERE kode_merk='$kode_merk'");
if ($update) {
echo "<script>alert('Data Berhasil Terupdate'); window.location = 'gudang.php?halaman=v_merkBarang'</script>";
} else {
echo "<script>alert('Terjadi Kesalahan Input Database'); window.location = 'gudang.php?halaman=edit_merkBarang&id=" . $id . "'</script>";
}
}
?>
<div class="form-element-list">
<div class="basic-tb-hd">
<h2>Form Edit Merk Barang</h2>
</div>
<form action="" method="post">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<label for="">Nama Merk Barang</label>
<div class="form-group">
<div class="nk-int-st">
<input type="hidden" name="kode_merk" class="form-control" readonly=""
value="<?= $data['kode_merk'] ?>">
<input type="text" name="nama_merk" class="form-control" placeholder="Isi form nama Merk barang"
required="" maxlength="20" oninvalid="this.setCustomValidity('Nama Merk Wajib Diisi')"
oninput="setCustomValidity('')" value="<?= $data['nama_merk'] ?>">
</div>
</div>
</div>
</div>
<button type="submit" name="update" class="btn btn-primary">Update</button>
<a href="gudang.php?halaman=v_merkBarang" class="btn btn-danger">Kembali</a>
</form>
</div>
|
C
|
UTF-8
| 3,067 | 3.203125 | 3 |
[] |
no_license
|
/************
Instructions To run this code:
Run ./server from bash Before running client
************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <time.h>
double power(double,double);
struct my_msgbuf {
long mtype;
char mtext[100];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
char buffer[30];
time_t timer;
struct tm* tm_info;
time(&timer);
tm_info = localtime(&timer);
/*Date and Time Generation*/
strftime(buffer, 30, "%Y-%m-%d %H:%M:%S:", tm_info);
/*Opening A file In Append Mode*/
FILE *fp = fopen("result.txt","a");
fprintf(fp,"%s \n",buffer);
fclose(fp);
/*Creating Unique Key same for both clinet and server*/
if ((key = ftok("server.c", 'S')) == -1) {
perror("ftok");
exit(1);
}
/*Connecting To the queue*/
if ((msqid = msgget(key, 0644)) == -1) {
perror("msgget");
exit(1);
}
printf("server: ready to receive command\n");
int i,j,k,var,opr;
double op[2];
for(;;) {
for(i=1;i<=10;i++)
{
/*Receving Message from the message queue*/
var=msgrcv(msqid, &buf, sizeof(buf.mtext),i, IPC_NOWAIT);
j=0,k=0,op[0]=0,op[1]=0;
char *ins = buf.mtext,opr;
/*Getting the the required operands
in op[0] and op[1] and operator opr*/
while(*(ins+j)!='\0'&&var!=-1)
{
if(*(ins+j)==' '){j++;}
else if(*(ins+j)=='e'){op[k]=2.71828;k++;j++;}
else
{
if(47<*(ins+j)&&*(ins+j)<58)
{
while(47<*(ins+j)&&*(ins+j)<58)
{
op[k] = op[k]*10 + *(ins+j)-48;
j++;
}
k++;
}
else
{
opr = *(ins+j);
j++;
}
}
}
if (var!= -1)
{
/*Computing the Result*/
if(opr == '+') op[0]=op[0]+op[1];
else if(opr == '-') op[0]=op[0]-op[1];
else if(opr == '*') op[0]=op[0]*op[1];
else if(opr == '^') op[0]=power(op[0],op[1]);
else op[0]=0;
/*Writing to the file as well ass scree*/
printf("Server: Client %d \"%s\" = %f Written To file\n",i,buf.mtext,op[0]);
fp = fopen("result.txt","a");
fprintf(fp,"Client %d: \"%s\" = %f\n",i,buf.mtext,op[0]);
fclose(fp);
}
}
}
return 0;
}
/*Efficinet way to calculate power*/
double power(double x,double y)
{
double res=1;
while(y>0)
{
if((int)y%2!=0) res = res * x;
x = x*x;
y=y/2;
}
return res;
}
|
Python
|
UTF-8
| 267 | 3.640625 | 4 |
[] |
no_license
|
n=int(input("Enter a number : "))
def num(n):
s=0
while(n>0):
r=n%10
s=s+r**2
n=n//10
return (s)
def Canada(n):
s1=0
for i in range(1,n+1):
if n%i==0:
s1+=i
if (s1-1-n)==num(n):
return True
else:
return False
print(Canada(n))
|
PHP
|
UTF-8
| 3,220 | 2.546875 | 3 |
[] |
no_license
|
<?php
require_once ("../classes/Question.php");
require_once ("../classes/Answer.php");
require_once ("../db/QuizDbUtil.php");
session_start();
if (!isset($_SESSION['username'])) {
header('location:login.php');
}
$db=new QuizDbUtil("config1.ini");
$que=new Question();
$ans=new Answer();
?>
<?php
include("header.php");
?>
<div class="questions">
<div class="cards" >
<h2>Welcome <?php echo 1;echo $_SESSION['username']?> to quiz </h2>
<br>
</div>
<center>
<form action="results.php" method="post">
<?php
//$arrays=array();
$arrays=getQuestions();
/*$arrays=array(
array("qid","name","ansid","111t", "1","121","24","24","24","24"),
array("ase1","2","22","222t", "2","122","24","24","24","24"),
array("ase2","3","33s","333t", "33s","123","24","24","24","24"),
array("ase3","4","44s","444t", "444t","124","24","24","24","24"),
array("ase4","5","55s","555t", "5","125","24","24","24","24"),
array("ase5","6","66s","666t", "66s","126","24","24","24","24"),
array("ase6","7","77s","777t", "7","127","24","24","24","24"),
array("ase7","8","88s","888t", "8","128","24","24","24","24"),
array("ase8","9","99s","999t", "99s","129","24","24","24","24"),
array("ase9","10","100s","t", "t","120","24","24","24","24"),
);*/
for ($j=0; $j<10; $j++) {
echo '<h4>'.$arrays[$j][1].'</h4>';
/*$q="select * from answer where ans_id=: $k";
$querry=mysql_query($q);
while ($rows=mysql_fetch_array($querry)) {*/
# code...
# code...
//echo '';
//for ($k=1; $k <=3; $k++) {
?>
<div class="cards">
<div class="body">
<<<<<<< HEAD
<input type="radio" id="num[]" name="quizc[<?php echo($arrays[$j][2]);?>]" value="<?php echo($ans->getAnswers($ansid));?>">
=======
<input type="radio" id="num[<?php echo($arrays[$j][5]);?>]" name="quizc[<?php echo($arrays[$j][4]);?>]" value="<?php echo($arrays[$j][$i]);?>">
>>>>>>> 0b86a4da4cdb4020c61f8dccaa57412f90482685
<?php
/*num($array[$j][0])*/
/*$arrays[$j][4]*/
echo $ans->getAnswers($ansid);
//}
echo '</div>';
echo '</div>';
}
?>
<input type="submit" name="submit" value="Submit">
</form>
</center>
</div>
<!--
<fieldset>
<legend>What is your JavaScript library of choice?</legend>
<form action="<?php //echo $editFormAction; ?>" id="form1" name="form1" method="POST">
<label>
<input type="radio" name="Poll" value="mootools" id="Poll_0" />
Mootools
</label>
<label>
<input type="radio" name="Poll" value="prototype" id="Poll_1" />
Prototype
</label>
<label>
<input type="radio" name="Poll" value="jquery" id="Poll_2" />
jQuery
</label>
<label>
<input type="radio" name="Poll" value="spry" id="Poll_3" />
Spry
</label>
<label>
<input type="radio" name="Poll" value="other" id="Poll_4" />
Other
</label>
<input type="submit" name="submit" id="submit" value="Vote" />
<input type="hidden" name="id" value="form1" />
<input type="hidden" name="MM_insert" value="form1" />
</form>
</fieldset>
-->
</body>
</html>
|
Python
|
UTF-8
| 11,349 | 2.5625 | 3 |
[] |
no_license
|
from InspectorG.utils import SliceBbox, ImgViewer, SaveDict, LoadDict
import collections as clct
from tqdm import tqdm
import random
import numpy as np
import cv2
import os
class FeatureGenerator:
def __init__ (self, imgdict, task_name, aug = None, feature_dir = 'InspectorG/DICT'):
"""
Args:
imgdict: Image data path dictionary {Product ID : (PATH, Label)}
task_name: The task name that you want to save
aug: Augmentation method ex) GAN or policy
feature_dir: Directory of feature dictionaries
"""
self.IMGDICT = imgdict
self.TASK = task_name if aug == None else task_name+'-'+aug
self.PAT_DICT = self.make_patdict(self.TASK)
self.FEATURE_DIR = feature_dir
self.aug = aug
self.set_featuredict()
def set_featuredict (self):
"""
Set existed feature dictionaries or make new dictionary.
"""
if self.TASK+'.featuredict' in os.listdir(self.FEATURE_DIR):
self.featuredict = LoadDict(self.TASK, 'featuredict')
else:
self.featuredict = dict()
def make_patdict (self, dtype):
"""
Make pattern dictionary using saved pattern images.
Args:
dtype: Defect type
"""
root = 'InspectorG/PATTERN/'+dtype
res = dict()
for file in os.listdir(root):
fname = file.split('.')
if fname[-1] == 'png' or fname[-1] == 'jpg':
res[fname[0]] = os.path.join(root, file)
return res
def fg_function (self, fname, pattern):
"""
Feature Generation Function using cv2.matchTemplate
Args:
fname: The directory of the image file
pattern: The directory of the pattern image
"""
img = cv2.imread(fname)
pattern_img = cv2.imread(pattern)
method = eval('cv2.TM_CCOEFF_NORMED')
result = cv2.matchTemplate(img, pattern_img, method)
min_val,max_val,min_loc, max_loc = cv2.minMaxLoc(result)
y, x = np.shape(pattern_img)[:2]
if abs(max_val) > abs(min_val):
return abs(max_val), (max_loc[0], max_loc[1], max_loc[0]+x, max_loc[1]+y)
else:
return abs(min_val), (min_loc[0], min_loc[1], min_loc[0]+x, min_loc[1]+y)
def GenFeature(self, save = True, print_log = False):
"""
Generate features of the unlabeled images using fg_function().
Args:
save: If True, the generated features will be saved
"""
if len(self.PAT_DICT) == 0:
print("There is no PATTERN")
return
feature_dict = clct.defaultdict(dict)
print('Generate Features ...')
for patname, patdir in tqdm(self.PAT_DICT.items()):
ex_pat = lambda a : a[list(a.keys())[0]].keys()
if len(self.featuredict) != 0:
pat_list = ex_pat(self.featuredict)
else:
pat_list = []
if patname not in pat_list:
for pid, (imgdir, label) in self.IMGDICT.items():
res = self.fg_function(imgdir, patdir)
feature_dict[pid][patname] = res
else:
if print_log:
print('%s -> Already Generated' % patname)
if len(self.featuredict) != 0 and len(dict(feature_dict)) != 0:
self.featuredict = combine_featuredict(self.featuredict, dict(feature_dict))
elif len(self.featuredict) == 0:
self.featuredict = dict(feature_dict)
if save:
SaveDict(self.featuredict, self.TASK, 'featuredict')
def LoadPatDict (self):
"""
Load pattern dictionary.
"""
if self.aug is not None:
new_patdict = dict()
for patname, patdir in self.PAT_DICT.items():
new_patdict[patname+'-'+self.aug] = patdir
return new_patdict
else:
return self.PAT_DICT
def LoadFeatureDict(self, wo_bbox = True):
"""
Load feature dictionary.
Args:
wo_bbox: If True, bounding box coordinates are included
"""
new_featuredict = dict()
if len(self.featuredict) != 0:
for pid, value in self.featuredict.items():
tmp = value
if self.aug is not None:
tmp = patname_update(tmp, self.aug)
if wo_bbox:
tmp = without_bbox(tmp)
new_featuredict[pid] = tmp
return new_featuredict
class FeatureManager:
def __init__(self, task_name, f_org, f_gan = None, f_policy = None):
"""
Args:
task_name: The task name that you want to save
f_org: FeatureGenerator instance with original pattern
f_gan: FeatureGenerator instance with GAN-based augmented pattern
f_policy: FeatureGenerator instance with policy-based augmented pattern
"""
self.TASK = task_name
self.f_org = f_org
self.f_gan = f_gan
self.f_policy = f_policy
self.check_task_name()
self.load_featuredicts()
def check_task_name (self):
"""
Check if the task name is matched with input FeatureGenerator instance.
"""
try:
if self.TASK != self.f_org.TASK:
raise Exception('FeatureE instance is different from Task name')
elif self.f_gan is not None and self.TASK+'-GAN' != self.f_gan.TASK:
raise Exception('FeatureE-GAN instance is different from Task name')
elif self.f_policy is not None and self.TASK+'-policy' != self.f_policy.TASK:
raise Exception('FeatureE-policy instance is different from Task name')
except Exception as e:
print('Error : ', e)
def load_featuredicts (self):
"""
Load feature dictionary from FeatureGenerator instance.
"""
def tmp_f(a):
if a is None:
return None
b = a.LoadFeatureDict()
return b if len(b) != 0 else None
self.pd_org = tmp_f(self.f_org)
self.pd_gan = tmp_f(self.f_gan)
self.pd_policy = tmp_f(self.f_policy)
self.IMGDICT = self.f_org.IMGDICT
def integrate_featuredict (self, mode):
"""
Integrate feature dictionaries (GAN, policy)
Args:
mode: experiment mode
"""
full_dict = dict()
for pid in self.pd_org.keys():
tmp_org = self.pd_org[pid]
if mode == 'gan':
full_dict[pid] = dict(tmp_org, **self.pd_gan[pid])
if mode == 'policy':
full_dict[pid] = dict(tmp_org, **self.pd_policy[pid])
if mode == 'all':
full_dict[pid] = dict(tmp_org, **self.pd_policy[pid], **self.pd_gan[pid])
elif mode == 'org':
full_dict[pid] = tmp_org
return full_dict
def integrate_patdict (self, mode, dev_dict, pat_num):
"""
Integrate pattern dictionaries (GAN, policy)
Args:
mode: experiment mode
dev_dict: development set dictionary
pat_num: the number of pattern
"""
print('== PATTENRNS ==')
org_patdict = filter_patdict(self.f_org.LoadPatDict(), dev_dict)
print_str = 'ORG : %s' % len(org_patdict)
if self.pd_gan is not None:
if mode == 'gan' or mode == 'all':
aug_patdict_gan = dict_sampling(self.f_gan.LoadPatDict(), pat_num)
else:
aug_patdict_gan = dict()
print_str += ', GAN : %s' % len(aug_patdict_gan)
if self.pd_policy is not None:
if mode == 'policy' or mode == 'all':
aug_patdict_policy = dict_sampling(self.f_policy.LoadPatDict(), pat_num)
else:
aug_patdict_policy = dict()
print_str += ', Policy : %s' % len(aug_patdict_policy)
print(print_str)
if mode == 'gan':
aug_patdict = aug_patdict_gan
elif mode == 'policy':
aug_patdict = aug_patdict_policy
elif mode == 'all':
aug_patdict =dict(aug_patdict_gan, **aug_patdict_policy)
elif mode == 'org':
aug_patdict = dict()
return dict(org_patdict, **aug_patdict)
def MakeMatrix (self, mode, dev_dict, pat_num = None):
"""
Make feature matrix, which is input of the Labeler, by integrating whole feature dictionaries.
Args:
mode: experiment mode
dev_dict: development set dictionary
pat_num: the number of pattern
"""
try:
if self.pd_gan is None and (mode == 'gan' or mode == 'all'):
raise Exception('"mode" is not matched with input PrimEs')
if self.pd_policy is None and (mode == 'policy' or mode == 'all'):
raise Exception('"mode" is not matched with input PrimEs')
except Exception as e:
print('Error : ', e)
print('MODE : %s\n' % mode)
i_featuredict = self.integrate_featuredict(mode)
i_patdict = self.integrate_patdict(mode, dev_dict, pat_num)
self.i_featuredict = i_featuredict
i_patlist = i_patdict.keys()
print('\nMake Training Data ...')
X_tr, Y_tr, X_te, Y_te = [], [], [], []
for pid, labels in i_featuredict.items():
tmp = [labels[pat] for pat in i_patlist]
if pid in dev_dict:
X_tr.append(tmp)
Y_tr.append(self.IMGDICT[pid][1])
else:
X_te.append(tmp)
Y_te.append(self.IMGDICT[pid][1])
X_tr, Y_tr = np.array(X_tr), np.array(Y_tr)
X_te, Y_te = np.array(X_te), np.array(Y_te)
print('Train : %s, %s, Test : %s, %s' % (np.shape(X_tr), np.shape(Y_tr), np.shape(X_te), np.shape(Y_te)))
return X_tr, Y_tr, X_te, Y_te
"""
Simple functions used in this file.
"""
def combine_featuredict(p1, p2):
for key, value in p1.items():
p1[key] = dict(value, **p2[key])
return p1
def without_bbox(featuredict):
return {key : value[0] for key, value in featuredict.items()}
def patname_update(dic, name):
return {key+'-'+name : value for key, value in dic.items()}
def filter_patdict(patdic, devdict):
tmp = dict()
for pid, label in devdict.items():
if label == 1:
for k, v in patdic.items():
if pid in k:
tmp[k] = v
return tmp
def dict_sampling(dic, n):
if n == None:
n = len(dic.keys())
n_keys = random.sample(dic.keys(), n)
return {k : dic[k] for k in n_keys}
|
JavaScript
|
UTF-8
| 6,092 | 2.828125 | 3 |
[] |
no_license
|
/*
Copyright The Infusion copyright holders
See the AUTHORS.md file at the top-level directory of this distribution and at
https://github.com/fluid-project/infusion/raw/main/AUTHORS.md.
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/main/Infusion-LICENSE.txt
*/
(function ($, fluid) {
"use strict";
/*******************************************************************************
* fluid.textNodeParser
*
* Parses out the text nodes from a DOM element and its descendants
*******************************************************************************/
fluid.defaults("fluid.textNodeParser", {
gradeNames: ["fluid.component"],
events: {
onParsedTextNode: null,
afterParse: null
},
invokers: {
parse: {
funcName: "fluid.textNodeParser.parse",
args: ["{that}", "{arguments}.0", "{arguments}.1", "{that}.events.afterParse.fire"]
},
hasTextToRead: "fluid.textNodeParser.hasTextToRead",
getLang: "fluid.textNodeParser.getLang"
}
});
/**
* Checks if a string contains non-whitespace characters.
* inspired by https://stackoverflow.com/a/2031143
*
* @param {String} str - the String to test
*
* @return {Boolean} - `true` if a word, `false` otherwise.
*/
fluid.textNodeParser.hasGlyph = function (str) {
return fluid.isValue(str) && /\S/.test(str);
};
/**
* Determines if there is text in an element that should be read.
* Will return false in the following conditions:
* - elm is falsey (undefined, null, etc.)
* - elm's offsetParent is falsey, unless elm is the `body` element
* - elm has no text or only whitespace
* - elm or an ancestor has "aria-hidden=true", unless the `acceptAriaHidden` parameter is set
*
* NOTE: Text added by pseudo elements (e.g. :before, :after) are not considered.
* NOTE: This method is not supported in IE 11 because innerText returns the text for some hidden elements,
* that is inconsistent with modern browsers.
*
* @param {jQuery|DomElement} elm - either a DOM node or a jQuery element
* @param {Boolean} acceptAriaHidden - if set, will return `true` even if the `elm` or one of its ancestors has
* `aria-hidden="true"`.
*
* @return {Boolean} - returns true if there is rendered text within the element and false otherwise.
* (See conditions in description above)
*/
fluid.textNodeParser.hasTextToRead = function (elm, acceptAriaHidden) {
elm = fluid.unwrap(elm);
return elm &&
(elm.tagName.toLowerCase() === "body" || elm.offsetParent) &&
fluid.textNodeParser.hasGlyph(elm.innerText) &&
(acceptAriaHidden || !$(elm).closest("[aria-hidden=\"true\"]").length);
};
/**
* Uses jQuery's `closest` method to find the closest element with a lang attribute, and returns the value.
*
* @param {jQuery|DomElement} elm - either a DOM node or a jQuery element
*
* @return {String|undefined} - a valid BCP 47 language code if found, otherwise undefined.
*/
fluid.textNodeParser.getLang = function (elm) {
return $(elm).closest("[lang]").attr("lang");
};
/**
* The parsed information of text node, including: the node itself, its specified language, and its index within its
* parent.
*
* @typedef {Object} TextNodeData
* @property {DomNode} node - The current child node being parsed
* @property {Integer} childIndex - The index of the child node being parsed relative to its parent
* @property {String} lang - a valid BCP 47 language code
*/
/**
* Recursively parses a DOM element and it's sub elements and fires the `onParsedTextNode` event for each text node
* found. The event is fired with the text node, language and index of the text node in the list of its parent's
* child nodes..
*
* Note: elements that return `false` from `that.hasTextToRead` are ignored.
*
* @param {fluid.textNodeParser} that - an instance of the component
* @param {jQuery|DomElement} elm - the DOM node to parse
* @param {String} lang - a valid BCP 47 language code.
* @param {Event} afterParseEvent - the event to fire after parsing has completed.
*
* @return {TextNodeData[]} the array of parsed elements. Only text nodes for elements that have passed the
* `that.hasTextToRead` check will be included.
*/
fluid.textNodeParser.parse = function (that, elm, lang, afterParseEvent) {
elm = fluid.unwrap(elm);
var parsed = [];
if (that.hasTextToRead(elm)) {
var childNodes = elm.childNodes;
var elementLang = elm.getAttribute("lang") || lang || that.getLang(elm);
// This funny iteration is a fix for FLUID-6435 on IE11
Array.prototype.forEach.call(childNodes, function (childNode, childIndex) {
if (childNode.nodeType === Node.TEXT_NODE) {
var textNodeData = {
node: childNode,
lang: elementLang,
childIndex: childIndex
};
parsed.push(textNodeData);
that.events.onParsedTextNode.fire(textNodeData);
} else if (childNode.nodeType === Node.ELEMENT_NODE) {
parsed = parsed.concat(fluid.textNodeParser.parse(that, childNode, elementLang));
}
});
}
if (afterParseEvent) {
afterParseEvent(that, parsed);
}
return parsed;
};
})(jQuery, fluid_3_0_0);
|
Java
|
UTF-8
| 1,601 | 2.46875 | 2 |
[] |
no_license
|
package com.zfz.recommendation;
import org.springframework.data.relational.core.sql.In;
import java.io.*;
public class FileTool {
private static String fileName = "D:\\web\\user.csv";
private static String tmpFileName = "D:\\web\\tmp.csv";
public boolean append(Integer userId, Integer book_id, Double rate) {
try {
FileWriter fileWriter = new FileWriter(fileName,true);
fileWriter.write("\n");
String tmp = userId.toString() + "," + book_id.toString() + "," + rate.toString();
fileWriter.write(tmp);
fileWriter.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public boolean updateRate(Integer userId, Integer bookId, Double newRate) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tmpFileName));
String line = null;
while ((line = bufferedReader.readLine()) != null){
String item[] = line.split(",");
if(Integer.getInteger(item[0]) == userId && Integer.getInteger(item[1]) == bookId){
String tmp = item[0] + "," + item[1] + "," + newRate.toString() + "\n";
bufferedWriter.write(tmp);
}else
bufferedWriter.write(line+"\n");
}
bufferedWriter.close();
bufferedReader.close();
return true;
}
}
|
Python
|
UTF-8
| 2,127 | 3.125 | 3 |
[] |
no_license
|
# coding: utf-8
# # Python Example for recording and playing back the quanitzed version of recording.
# <br/>
# #### Import relevant modules.
# In[1]:
"""
Using Pyaudio, record sound from the audio device and plot, for 8 seconds, and display it live in a Window.
Usage example: python pyrecplotanimation.py test.wav
Gerald Schuller, October 2014
"""
get_ipython().magic('matplotlib inline')
import numpy as np
import matplotlib.pyplot as plt
import pyaudio
import struct
# <h4>Define the varaiables.</h4>
# In[2]:
CHUNK = 5000 #Blocksize
WIDTH = 2 #2 bytes per sample
CHANNELS = 1 #2
RATE = 32000 #Sampling Rate in Hz
RECORD_SECONDS = 8
# <h4>Initialize the sound card.</h4>
# In[3]:
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(WIDTH),
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
#input_device_index=10,
frames_per_buffer=CHUNK)
# #### Starts recording and plays back the quantized version of the recording.
# In[4]:
print("* recording")
#Loop for the blocks:
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
#Reading from audio input stream into data with block length "CHUNK":
data = stream.read(CHUNK)
#Convert from stream of bytes to a list of short integers (2 bytes here) in "samples":
#shorts = (struct.unpack( "128h", data ))
shorts = (struct.unpack( 'h' * CHUNK, data ));
samples=np.array(list(shorts),dtype=float);
#start block-wise signal processing:
#Quantization, for a signal between -32000 to +32000:
q=5000;
#Mid Tread quantization:
#indices=np.round(samples/q)
#de-quantization:
#samples=indices*q;
#Mid -Rise quantizer:
indices=np.floor(samples/q)
#de-quantization:
samples=indices*q+q/2;
#end signal processing
#converting from short integers to a stream of bytes in "data":
data=struct.pack('h' * len(samples), *samples);
#Writing data back to audio output stream:
stream.write(data, CHUNK)
print("* done")
stream.stop_stream()
stream.close()
p.terminate()
|
Markdown
|
UTF-8
| 11,215 | 3.5 | 4 |
[] |
no_license
|
# Problem Set: Exception Handling
## Directions
Complete all questions below.
## Practice
<!-- Question 1 -->
<!-- prettier-ignore-start -->
### !challenge
* type: code-snippet
* language: python3.6
* id: XwJz6l
* title: Exception Handling
### !question
Given these tests, provide the function body that will make them pass. Assume that the only invalid, claimed code school name is `"Ada Developers Academy"`.
```python
def test_valid_name():
result = claim_unreserved_code_school_name("Some Code School")
assert result is True
def test_invalid_name():
with pytest.raises(ValueError):
claim_unreserved_code_school_name("Ada Developers Academy")
```
### !end-question
### !placeholder
```python
def claim_unreserved_code_school_name(name):
pass
```
### !end-placeholder
### !tests
```python
import unittest
from main import *
class TestChallenge(unittest.TestCase):
def test_valid_name(self):
result = claim_unreserved_code_school_name("Some Code School")
self.assertTrue(result)
def test_invalid_name(self):
with self.assertRaises(ValueError):
claim_unreserved_code_school_name("Ada Developers Academy")
```
### !end-tests
### !explanation
An example of a working implementation:
```python
def claim_unreserved_code_school_name(name):
if name == "Ada Developers Academy":
raise ValueError
return True
```
### !end-explanation
### !end-challenge
<!-- prettier-ignore-end -->
<!-- Question 2 -->
<!-- prettier-ignore-start -->
### !challenge
* type: code-snippet
* language: python3.6
* id: SkMsOl
* title: Exception Handling
### !question
Given these tests, provide the function body that will make them pass. Assume that any phone number that is a string is valid.
Hint: The function `type(phone_num)` will return `str` if `phone_num` is a string.
```python
def test_valid_phone_nums_return_true():
phone_num = "777-888-9999"
is_valid = is_phone_num_valid(phone_num)
assert is_valid
def test_invalid_phone_nums_raise_error():
phone_num = 777-888-9999
with pytest.raises(ValueError):
is_valid = is_phone_num_valid(phone_num)
```
### !end-question
### !placeholder
```python
def is_phone_num_valid(phone_num):
pass
```
### !end-placeholder
### !tests
```python
import unittest
from main import *
class TestChallenge(unittest.TestCase):
def test_valid_phone_nums_return_true(self):
phone_num = "777-888-9999"
is_valid = is_phone_num_valid(phone_num)
self.assertTrue(is_valid)
def test_invalid_phone_nums_raise_error(self):
phone_num = 777-888-9999
with self.assertRaises(ValueError):
is_phone_num_valid(phone_num)
```
### !end-tests
### !explanation
An example of a working implementation:
```python
def is_phone_num_valid(phone_num):
if type(phone_num) is not str:
raise ValueError
return True
```
### !end-explanation
### !end-challenge
<!-- prettier-ignore-end -->
<!-- Question 3 -->
<!-- prettier-ignore-start -->
### !challenge
* type: code-snippet
* language: python3.6
* id: VLwvhu
* title: Exception Handling
### !question
Given these tests, refactor this function to make them pass. Use `try ... except` syntax.
- If no error is raised, return `cost_per_person`
- If a `ZeroDivisionError` is raised, catch it, and return `0`
```python
def test_split_cost_evenly():
cost = split_cost_evenly(100, 4, .5)
assert cost == pytest.approx(37.5)
def test_caught_zerodivisionerror_returns_zero():
cost = split_cost_evenly(100, 0, .5)
assert cost == 0
```
### !end-question
### !placeholder
```python
def split_cost_evenly(total_cost, num_of_people, tip_percentage):
cost_with_tip = total_cost * (1 + tip_percentage)
cost_per_person = cost_with_tip / num_of_people
return cost_per_person
```
### !end-placeholder
### !tests
```python
import unittest
from main import *
class TestChallenge(unittest.TestCase):
def test_split_cost_evenly(self):
cost = split_cost_evenly(100, 4, .5)
self.assertAlmostEqual(cost, 37.5)
def test_caught_zerodivisionerror_returns_zero(self):
cost = split_cost_evenly(100, 0, .5)
self.assertEqual(cost, 0)
```
### !end-tests
### !explanation
An example of a working implementation:
```python
def split_cost_evenly(total_cost, num_of_people, tip_percentage):
try:
cost_with_tip = total_cost * (1 + tip_percentage)
cost_per_person = cost_with_tip / num_of_people
return cost_per_person
except ZeroDivisionError:
return 0
```
### !end-explanation
### !end-challenge
<!-- prettier-ignore-end -->
<!-- Question 4 -->
<!-- prettier-ignore-start -->
### !challenge
* type: code-snippet
* language: python3.6
* id: j9kUX9
* title: Exception Handling
### !question
Given these tests, refactor **_only_** the **`get_celebration_treat`** function to make them pass. Use `try ... except` syntax.
In `get_celebration_treat`...
- If no error is raised, then `get_celebration_treat` returns `"celebration {thirteenth_donut}!"`, where `thirteenth_donut` is the result of `grab_thirteenth_donut()`
- If an `IndexError` is raised because of accessing something missing in `donuts`, then `get_celebration_treat` returns `"no donut :("`
```python
def test_get_celebration_treat():
bakers_dozen = [
"glazed donut", "old-fashioned", "jelly donut", "bear claw", "classic donut with pink frosting and sprinkles on top", "donut hole", "another glazed donut", "yet another glazed donut?", "cruller", "maple donut", "powdered sugar donut", "doughnut", "thirteenth donut"
]
# Run this assert as part of the "Arrange" step to ensure we're set up correctly
assert len(bakers_dozen) == 13
thirteenth_donut = get_celebration_treat(bakers_dozen)
assert thirteenth_donut == "celebration thirteenth donut!"
def test_no_celebration_treat():
empty_donut_box = []
# Run this assert as part of the "Arrange" step to ensure we're set up correctly
assert len(empty_donut_box) != 13
no_donut = get_celebration_treat(empty_donut_box)
assert no_donut == "no donut :("
def test_dont_grab_thirteenth_donut():
# This test is for checking that grab_thirteenth_donut raises the error
empty_donut_box = []
with pytest.raises(IndexError):
grab_thirteenth_donut(empty_donut_box)
```
### !end-question
### !placeholder
```python
def grab_thirteenth_donut(donuts):
return donuts[12]
def get_celebration_treat(treats):
thirteenth_donut = grab_thirteenth_donut(treats)
return f"celebration {thirteenth_donut}!"
```
### !end-placeholder
### !tests
```python
import unittest
from main import *
class TestChallenge(unittest.TestCase):
def test_get_celebration_treat(self):
bakers_dozen = [
"glazed donut", "old-fashioned", "jelly donut", "bear claw", "classic donut with pink frosting and sprinkles on top", "donut hole", "another glazed donut", "yet another glazed donut?", "cruller", "maple donut", "powdered sugar donut", "doughnut", "thirteenth donut"
]
self.assertEqual(len(bakers_dozen), 13)
thirteenth_donut = get_celebration_treat(bakers_dozen)
self.assertEqual(thirteenth_donut, "celebration thirteenth donut!")
def test_no_celebration_treat(self):
empty_donut_box = []
self.assertNotEqual(len(empty_donut_box), 13)
no_donut = get_celebration_treat(empty_donut_box)
self.assertEqual(no_donut, "no donut :(")
def test_dont_grab_thirteenth_donut(self):
# This test is for checking that grab_thirteenth_donut raises the error
empty_donut_box = []
with self.assertRaises(IndexError):
grab_thirteenth_donut(empty_donut_box)
```
### !end-tests
### !explanation
An example of a working implementation:
```python
def get_celebration_treat(treats):
try:
thirteenth_donut = grab_thirteenth_donut(treats)
return f"celebration {thirteenth_donut}!"
except IndexError:
return "no donut :("
```
### !end-explanation
### !end-challenge
<!-- prettier-ignore-end -->
<!-- Question 5 -->
<!-- prettier-ignore-start -->
### !challenge
* type: code-snippet
* language: python3.6
* id: UlAHwy
* title: Exception Handling
### !question
Given these tests, refactor **_only_** the **`prepare_meal`** function to make them pass. Use `try ... except` syntax.
In `prepare_meal`...
- If no error is raised, then `food` should be the result of `make_breakfast(pantry)`
- If a `KeyError` is raised because of accessing something missing in `pantry`, then `food` should be `"nothing"`
```python
def test_makes_breakfast_on_a_plate():
pantry = {
"waffles": "blueberry waffles",
"juice": "orange juice"
}
breakfast = prepare_meal("breakfast", pantry)
assert breakfast == "blueberry waffles and orange juice on a plate!"
def test_missing_pantry_items_gets_nothing_on_a_plate():
empty_pantry = {}
missing_breakfast = prepare_meal("breakfast", empty_pantry)
assert missing_breakfast == "nothing on a plate!"
def test_make_breakfast_with_empty_pantry():
# This test is for checking that make_breakfast raises the error
empty_pantry = {}
with pytest.raises(KeyError):
make_breakfast(empty_pantry)
```
### !end-question
### !placeholder
```python
def make_breakfast(pantry):
breakfast = f"{pantry['waffles']} and {pantry['juice']}"
return breakfast
def serve_food(food):
return food + " on a plate!"
def prepare_meal(meal_type, pantry):
if meal_type == "breakfast":
food = make_breakfast(pantry)
meal = serve_food(food)
return meal
```
### !end-placeholder
### !tests
```python
import unittest
from main import *
class TestChallenge(unittest.TestCase):
def test_makes_breakfast_on_a_plate(self):
pantry = {
"waffles": "blueberry waffles",
"juice": "orange juice"
}
breakfast = prepare_meal("breakfast", pantry)
self.assertEqual(
breakfast, "blueberry waffles and orange juice on a plate!")
def test_missing_pantry_items_gets_nothing_on_a_plate(self):
empty_pantry = {}
missing_breakfast = prepare_meal("breakfast", empty_pantry)
self.assertEqual(
missing_breakfast, "nothing on a plate!")
def test_make_breakfast_with_empty_pantry(self):
# This test is for checking that make_breakfast raises the error
empty_pantry = {}
with self.assertRaises(KeyError):
make_breakfast(empty_pantry)
```
### !end-tests
### !hint
Try putting the line `food = make_breakfast(pantry)` inside the try-clause. If a `KeyError` is caught, then assign `food` to `"nothing"`.
### !end-hint
### !explanation
An example of a working implementation:
```python
def prepare_meal(meal_type, pantry):
if meal_type == "breakfast":
try:
food = make_breakfast(pantry)
except KeyError:
food = "nothing"
meal = serve_food(food)
return meal
```
It's completely valid to have more code inside the try-clause.
### !end-explanation
### !end-challenge
<!-- prettier-ignore-end -->
|
C
|
UTF-8
| 2,039 | 2.875 | 3 |
[
"Apache-2.0"
] |
permissive
|
/**
* This example shows the loopback feature on I2S.
* Incoming data on RX are sent back on TX. Received data will not be stored in
* memory.
*/
#include "pmsis.h"
#include "bsp/bsp.h"
#define NB_CHANNELS ( 4 )
#define NB_ACTIVE_CHANNELS ( 4 )
static struct pi_device i2s;
static int test_entry()
{
int32_t errors = 0;
printf("Entering main controller\n");
// The configuration given when the driver is opened, is the global one
// which applies to all channels like the number of channels, sampling rate
// and so on.
struct pi_i2s_conf i2s_conf = {0};
pi_i2s_conf_init(&i2s_conf);
i2s_conf.frame_clk_freq = 44100;
i2s_conf.itf = 0;
i2s_conf.word_size = 32;
i2s_conf.channels = NB_CHANNELS;
i2s_conf.options = PI_I2S_OPT_TDM | PI_I2S_OPT_FULL_DUPLEX;
pi_open_from_conf(&i2s, &i2s_conf);
errors = pi_i2s_open(&i2s);
if (errors)
{
printf("Error opening i2s_%d : %lx\n", errors, i2s_conf.itf);
return -1;
}
// Now that the global configuration is given, configure each channel
// independently.
for (uint8_t i=0; i<(uint8_t) NB_ACTIVE_CHANNELS; i++)
{
// Enabled TX for slot i with pingpong buffers
i2s_conf.channel_id = i;
i2s_conf.options = PI_I2S_OPT_IS_TX | PI_I2S_OPT_ENABLED | PI_I2S_OPT_LOOPBACK;
pi_i2s_ioctl(&i2s, PI_I2S_IOCTL_CONF_SET, &i2s_conf);
}
printf("Start receiving and sending...\n");
// Start sampling.
// Starting from there, the driver will alternate between the 2 pingpong
// buffers for each channel.
if (pi_i2s_ioctl(&i2s, PI_I2S_IOCTL_START, NULL))
{
return -2;
}
while (1);
// Sampling is done, close everything
pi_i2s_ioctl(&i2s, PI_I2S_IOCTL_STOP, NULL);
pi_i2s_close(&i2s);
return errors;
}
void test_kickoff(void *arg)
{
int ret = test_entry();
pmsis_exit(ret);
}
int main()
{
printf("PMSIS I2S TDM RX TX loopback example\n");
return pmsis_kickoff((void *) test_kickoff);
}
|
Shell
|
UTF-8
| 709 | 3.5625 | 4 |
[] |
no_license
|
#!/bin/sh
yaml() {
docker run --rm -i -v "${PWD}":/workdir mikefarah/yq yq "$@"
}
parse_image() {
service_name=$1
service_version=$(cat "$service_name/package.json" | jq .version --raw-output)
printf "docker.pkg.github.com/czarsimon/webca/$service_name:$service_version"
}
update_image() {
service_name=$1
image_name=$(parse_image $service_name)
yaml write --inplace "k8s/application/$service_name/deployment.yml" spec.template.spec.containers[0].image $image_name
}
services=("api-server" "web-app")
for service in "${services[@]}"
do
update_image $service
image_name=$(parse_image $service_name)
echo "Updated image for service $service. image = $image_name"
done
|
Markdown
|
UTF-8
| 1,554 | 2.765625 | 3 |
[] |
no_license
|
---
title: undefined reference to sem and stdout
date: 2019-06-05 00:00:00
cover: /img/Tux.svg
categories:
- Dev-Code
tags:
- Linux
- signal
- stdout
- gcc
---
# 一个系统信号量相关函数的问题,一个stdout相关的问题
## 未定义的引用:sem函数(`Undefined Reference to Sem_*`)
GCC没有默认地支持C的API中的信号函数例如`sem_init` `sem_post` `sem_wait` (这很常见,GCC总是不会默认帮你加载所需的链接库)
直接`gcc`带有这些函数的代码,想都不用想,肯定会报
> undefined reference to sem
的错误
解决这个问题需要给gcc带一个`-pthread`参数
-------------------------
## 标准输出stdout缓冲区flush的问题
在我设置的打印提示信息(`fprintf(stderr, "info")`)出现之前程序就段错误了,之前以为是打印的句子之前出现了错误,但是后来得证问题出在提示信息之后的语句中;
那为什么以前不出提示信息呢?
这个问题是打印错误信息的语句没有考虑到C缓冲区的问题,事实上C输出缓冲区只会在里面有`\n`,EOF,`fflush(stdout)`,还有程序执行完毕的时候才会把缓冲区里面的内容打印出来,所以如果提示信息里面没有`\n`或者什么能清空缓冲区的东西,那么提示信息就会一直屯着,直到程序觉得可以输出了,那么如果在这之间程序出了问题,提示信息就永远不会打印出来,进而也会导致对出错位置判断失误
Knighthana
2019年06月05日 于西电
|
Markdown
|
UTF-8
| 2,282 | 2.921875 | 3 |
[] |
no_license
|
---
title: New Version Coming Soon
date: '2015-04-30'
layout: post
excerpt_separator: "noexcerpt"
permalink: /blog/new-version-coming-soon/
tags:
- HappyFunTimes
dsq_thread_id: '3724924797'
---
I've been trying forever to ship a Unity3D plugin. After seeing [Uniduino](http://www.uniduino.com/) though and working with the art/design students at UCLA I felt like I needed
to do a lot more work before shipping it. Lots of docs, videos, etc... Still
not done but
<!-- more -->
I was going to try to push it today and .... my mac broke. Sigh....
Anyway, hopefully I can push out a new App soon and get the plugin out as
well.
The latest plugin does a few things the old one didn't
One it handles the name system a little better. The old manual way still works
but otherwise `NetPlayer.Name` will always hold the current user's name. If you want to know if it changed
add an event listener to `NetPlayer.OnNameChanged`
Another is the plugin will now launch HappyFunTimes if it's not already
running. Similarly if it can't launch it it will direct you to install it.
Hopefully that will make it easier for non−techies to get started
Also added a `PlayerConnector` script. Most of the examples use the `PlayerSpawner` script which spawns a prefab anytime a player connects. This allows many
players to play. 10, 20, 30 is not uncommon.
The `PlayerConnector` script on the other hand helps you to connect players to `GameObject`s already in your scene. That fits the use case that many users have that just
want to use the phone for input but don't want to support lots of players, just
the 1 − 4 they have already in their scene.
The `PlayerConnector` also has the option to let a disconnected player reconnect. You can set how
many seconds they have until their player is given to someone else waiting to
play. You can also swap players. So let's say you have a 3 player game and 5
people connect. 3 play the game, when one dies you can tell HappyFunTimes to
swap out that person for one of the other players waiting to play. You can use
a similar feature boot out all players at the end of round and take the next
set of waiting players.
Hopefully you'll find those features useful.... once I get access to a machine
I can code on (current at an internet cafe)
|
Shell
|
UTF-8
| 3,237 | 3.515625 | 4 |
[] |
no_license
|
#!/bin/bash
# dibuat : bayu imbang, 7 Feb 2012
# =================================
# objective : membuat key-file
if [ $# -lt 2 ];then
echo "bil_make_key_file.sh <input DIR> <output file>"
echo "==========================================="
exit
fi
wmocode=/usr/people/imbangla/didah/official/sta_id.txt
database=didah
echo -n "Are you going to retrieve ID stations data ? (y/n)"
read hasil
if [ $hasil == "y" ] || [ $hasil == "Y" ];then
echo "updating stations..............."
mysql -udiddba -pQhL40K -hbwdb04 $database --skip-column-names -e"select concat(sta_id,',',name,',',wmocode,',',lat) from stations where coun_id='id'" > $wmocode
fi
indir=$1
outfil=$2
if [ -e $outfil ];then
rm $outfil
fi
maxserid=$(mysql -udiddba -pQhL40K -hbwdb04 $database --skip-column-names -e"select max(ser_id) from series;")
serid=$maxserid
echo -e "WMOcode\tName\tSta_id\tLat\trr\thu\tpp\tss\ttg\ttx\ttn\tfg\tdd\tfx" >> $outfil
#ls ./data.* > fake.tmp
#ls $indir/data*.txt | awk -F. '{print $2}' | uniq -c > key.tmp
ls $indir/data*.txt > key.tmp1
cat key.tmp1 | while read LINE; do basename $LINE; done | awk -F. '{print $2}' | uniq -c > key.tmp
#for FILE in $indir/*tn*.txt
echo "Creating key file ................."
cat key.tmp | while read FILE
do
#FILE=$(basename "$FILE")
wmo=`echo $FILE | awk '{print $2}'`
echo $wmo
#export WMO=$wmo
brs=`awk -F, -v VAR=$wmo '$3==VAR {print}' $wmocode`
if [ $? -ne 0 ]
then
echo "station $wmo can't be found."
exit
fi
name=`echo $brs | awk -F, '{print $2}'`
staid=`echo $brs | awk -F, '{print $1}'`
stalat=`echo $brs | awk -F, '{print $4}'`
tmp=${#stalat}
if [ $tmp -gt 6 ];then
stalat=-9999
else
stalat=`echo "scale=1; $stalat/3600" | bc -l`
fi
# rr
cekfl=$indir/data.$wmo.rr.txt
if [ -e $cekfl ];then
let serid="$serid+1"
rr=$serid
else
rr=///
fi
# hu
cekfl=$indir/data.$wmo.hu.txt
if [ -e $cekfl ];then
let serid="$serid+1"
hu=$serid
else
hu=///
fi
# pp
cekfl=$indir/data.$wmo.pp.txt
if [ -e $cekfl ];then
let serid="$serid+1"
pp=$serid
else
pp=///
fi
# ss
cekfl=$indir/data.$wmo.ss.txt
if [ -e $cekfl ];then
let serid="$serid+1"
ss=$serid
else
ss=///
fi
# tg
cekfl=$indir/data.$wmo.tg.txt
if [ -e $cekfl ];then
let serid="$serid+1"
tg=$serid
else
tg=///
fi
# tx
cekfl=$indir/data.$wmo.tx.txt
if [ -e $cekfl ];then
let serid="$serid+1"
tx=$serid
else
tx=///
fi
# tn
cekfl=$indir/data.$wmo.tn.txt
if [ -e $cekfl ];then
let serid="$serid+1"
tn=$serid
else
tn=///
fi
# fg
cekfl=$indir/data.$wmo.fg.txt
if [ -e $cekfl ];then
let serid="$serid+1"
fg=$serid
else
fg=///
fi
# dd
cekfl=$indir/data.$wmo.dd.txt
if [ -e $cekfl ];then
let serid="$serid+1"
dd=$serid
else
dd=///
fi
# fx
cekfl=$indir/data.$wmo.fx.txt
if [ -e $cekfl ];then
let serid="$serid+1"
fx=$serid
else
fx=///
fi
printf "%s\t%s\t%s\t%s\t" "$wmo" "$name" "$staid" "$stalat" >> $outfil
printf "%s\t%s\t%s\t%s\t" $rr $hu $pp $ss >> $outfil
printf "%s\t%s\t%s\t%s\t%s\t%s\n" $tg $tx $tn $fg $dd $fx >> $outfil
#printf "%-8s %-8s %-8s\n" "$wmo" "$staid" "$stalat" >> $outfil
#echo $wmo $name $staid
done
|
Python
|
UTF-8
| 1,479 | 3.15625 | 3 |
[] |
no_license
|
# import Presentation class
# from pptx library
from pptx import Presentation
from pathlib import Path
from os.path import isfile, join
import os
from alive_progress import alive_bar
from tkinter import Tk
from tkinter.filedialog import askdirectory
# Method to get content from slides
def getPowerpointContent(path):
ppt = Presentation(path)
content = ""
for slide in ppt.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
content += shape.text
# print(shape.text)
#
return content
# creating an object
# powerpoint_directory = "C:/Users/mitow/Desktop/source/GRACE HYMNS/"
powerpoint_directory = askdirectory(title="Select Folder source of PPT")
global_path = Path(powerpoint_directory)
file_type = input("What file type are you converting (pptx or ppt)?")
file_list = [str(pp) for pp in global_path.glob("*." + file_type)]
print(type(file_list))
corpus = [str(f) for f in os.listdir(powerpoint_directory) if not f.startswith('.') and isfile(join(powerpoint_directory, f))]
with alive_bar(len(corpus)) as bar:
for filename in corpus:
print(filename)
path = powerpoint_directory + "/" + filename
print(path)
file_content = getPowerpointContent(path)
f = open(powerpoint_directory + "/output/" + filename.split(".")[0] + ".txt", "w+", encoding="utf-8")
f.write(str(file_content))
f.close()
bar()
print("Done")
|
JavaScript
|
UTF-8
| 151 | 3.1875 | 3 |
[] |
no_license
|
let x = 14;
if (x > 10) {
//Tosihaara
console.log("x = yli kymmenen");
}
else {
//Epätosihaara
console.log("x = kymmenen tai alle");
}
|
Java
|
UTF-8
| 6,210 | 2.453125 | 2 |
[] |
no_license
|
package controller;
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import model.Employee;
import org.bson.Document;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
public class MainStageController {
public TextField usernameTextField;
public TextField passwordTextField;
public Button loginBtn;
public TextField passwordField;
public CheckBox checkbox;
private Stage primaryStage;
private Scene scene;
private HashMap<Integer, Employee> employeeCollection = new HashMap<>();
private MongoClient mc = new MongoClient();
private MongoDatabase database = mc.getDatabase("Restaurants");
private MongoCollection<Document> collection = database.getCollection("Employees");
private MongoClient mongoC = new MongoClient(new ServerAddress("Localhost", 27017));
private DB db = mongoC.getDB("Restaurants");
private DBCollection employeesCollection = db.getCollection("Employees");
private HashMap<Integer, Employee> adminMap = new HashMap<>();
private MongoCollection<Document> adminCollection = database.getCollection("Administrators");
private DBCollection adminDbCollection = db.getCollection("Administrators");
private CurrentSession currentSession = new CurrentSession();
public void setPrimaryStage(Stage primaryStage, Scene scene) {
this.primaryStage = primaryStage;
this.scene = scene;
employeeCollection = fillEmpCollection();
adminMap = fillAdminCollection();
passwordTextField.setManaged(false);
passwordTextField.setVisible(false);
passwordField.managedProperty().bind(checkbox.selectedProperty());
passwordField.visibleProperty().bind(checkbox.selectedProperty());
passwordTextField.managedProperty().bind(checkbox.selectedProperty().not());
passwordTextField.visibleProperty().bind(checkbox.selectedProperty().not());
passwordTextField.textProperty().bindBidirectional(passwordField.textProperty());
}
public void login() throws IOException {
Employee employee;
if (usernameTextField.getText().startsWith("3")) {
int id = 0;
try {
id = Integer.parseInt(usernameTextField.getText());
} catch (NumberFormatException ex) {
showAlertInvalidInput();
}
employee = adminMap.get(id);
if (employee != null) {
if (passwordTextField.getText().equals(employee.getPassword())) {
currentSession.setAdmin(true);
currentSession.setLoggedIn(employee);
FXMLLoader loader = new FXMLLoader(getClass().getResource("../AdminView.fxml"));
BorderPane root = loader.load();
AdminController adminController = loader.getController();
Scene adminScene = new Scene(root, 600, 600);
adminController.setPrimaryStage(primaryStage, adminScene, this, employeeCollection, currentSession);
primaryStage.setMaxWidth(600);
primaryStage.setMaxHeight(600);
primaryStage.setScene(adminScene);
} else {
showAlertInvalidInput();
}
}
} else {
int id = 0;
try {
id = Integer.parseInt(usernameTextField.getText());
} catch (NumberFormatException ex) {
showAlertInvalidInput();
}
employee = employeeCollection.get(id);
if (employee != null) {
if (passwordTextField.getText().equals(employee.getPassword())) {
currentSession.setAdmin(false);
currentSession.setLoggedIn(employee);
FXMLLoader loader = new FXMLLoader(getClass().getResource("../POSScene.fxml"));
BorderPane root = loader.load();
POSController posController = loader.getController();
Scene posScene = new Scene(root, 600, 600);
posController.setPrimaryStage(primaryStage, scene, this, employeeCollection, currentSession);
primaryStage.setMaxWidth(600);
primaryStage.setMaxHeight(600);
primaryStage.setScene(posScene);
} else {
showAlertInvalidInput();
}
}
}
}
private void showAlertInvalidInput() {
Alert alert = new Alert(Alert.AlertType.ERROR, "Invalid ID/Password, please try again.", ButtonType.OK);
alert.setTitle("Invalid Input");
alert.show();
}
private HashMap<Integer, Employee> fillEmpCollection() {
return generateHashMap(employeesCollection);
}
private HashMap<Integer, Employee> generateHashMap(DBCollection collection) {
HashMap<Integer, Employee> data = new HashMap<>();
List<DBObject> dbObjects;
DBCursor cursor = collection.find();
dbObjects = cursor.toArray();
Employee employee;
for (DBObject dbObject : dbObjects) {
employee = getEmployee(dbObject);
data.put(Integer.parseInt(employee.getId()), employee);
}
return data;
}
static Employee getEmployee(DBObject dbObject) {
Employee employee;
employee = new Employee();
employee.setName(dbObject.get("name").toString());
employee.setPassword(dbObject.get("password").toString());
employee.setOccupation(dbObject.get("occupation").toString());
employee.setWeeklyHours(dbObject.get("weeklyHours").toString());
employee.setId(dbObject.get("employeeID").toString());
employee.setHourlyPay(dbObject.get("hourlyPay").toString());
return employee;
}
private HashMap<Integer, Employee> fillAdminCollection() {
return generateHashMap(adminDbCollection);
}
}
|
Java
|
UTF-8
| 1,219 | 2.515625 | 3 |
[] |
no_license
|
package ftn.is.util.xmlAdapters;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import ftn.is.model.Odsek;
import ftn.is.util.CustomTManager;
public class XmlAdapterOdsek extends XmlAdapter<XmlAdapterOdsek.AdaptedOdsek, Odsek>{
private CustomTManager utx;
public XmlAdapterOdsek(){
}
public XmlAdapterOdsek(CustomTManager utx){
this.utx = utx;
}
@XmlType(name="odsek")
public static class AdaptedOdsek {
public int odsekId;
public String naziv;
public AdaptedOdsek(){}
public AdaptedOdsek(Odsek ods){
odsekId = ods.getOdsekId();
naziv = ods.getNaziv();
}
public Odsek getOdsek(CustomTManager utx){
Odsek tmp = new Odsek();
tmp.setNaziv(naziv);
tmp.setOdsekId(odsekId);
tmp.setPredmeti(null);
//Posto je Id postavljen mora merge, persist daje exception
utx.save(tmp);
return tmp;
}
}
@Override
public AdaptedOdsek marshal(Odsek v) throws Exception {
return new AdaptedOdsek(v);
}
@Override
public Odsek unmarshal(AdaptedOdsek v) throws Exception {
return v.getOdsek(utx);
}
}
|
Java
|
UTF-8
| 836 | 3.0625 | 3 |
[] |
no_license
|
public class Solution {
public int minCost(int[] stones) {
// Write your solution here.
int len = stones.length;
int[][] cost = new int[len][len];//cost[i][j] is the min cost to merge stones from index i to j including i and j.
int[][] weight = new int[len][len];//weight[i][j] is the total weight of stones from index i to j including i and j.
for (int i = 0; i < len; i++) {
for (int j = i; j >= 0; j--) {
if (i == j) {
cost[j][i] = 0;
weight[j][i] = stones[i];
} else {
weight[j][i] = weight[j][i - 1] + stones[i];
cost[j][i] = Integer.MAX_VALUE;
for (int k = j; k < i; k++) {
cost[j][i] = Math.min(cost[j][i], cost[j][k] + cost[k + 1][i] + weight[j][i]);
}
}
}
}
return cost[0][len - 1];
}
}
|
Shell
|
UTF-8
| 644 | 3.828125 | 4 |
[] |
no_license
|
if [ $# -ne 2 ]
then
echo "ERROR: La ejecución del programa es: ./ejercicio2.sh <nombre_fichero.txt> <numero_segundos>"
exit 1
fi
if [ ! -f $1 ];
then
echo "$1 no es un fichero"
exit 1
fi
if [ $2 -lt 1 ];
then
echo "El número de segundos debe ser mayor o igual que 1"
exit 1
fi
for x in $(cat $1)
do
ping -c 1 -w $2 $x > leido.txt
#$? : se usa para almacenar el resultado del últ comando ejecutado
if [ ! $? -eq 0 ];
then
echo "La IP $x no respondió tras $2 segundos"
else
cat leido.txt | sed -n -r -e '1,1d' -e '3,$d' -e 's/^.* from (.*)\:.* time\=(.*) ms/ La IP \1 respondió en \2 milisegundos/gp'
fi
done | sort -k 5
|
Java
|
UTF-8
| 1,536 | 2.5625 | 3 |
[] |
no_license
|
package com.samsung.idajavaclient;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.minlog.Log;
import java.io.IOException;
import java.util.Scanner;
public class idaClient {
public static Client client;
public static Scanner scanner;
public idaClient() {
scanner = new Scanner(System.in);
client = new Client();
registerPackets();
networkListener nl = new networkListener();
nl.init(client);
client.addListener(nl);
client.start();
try {
Log.info("Enter IP\n");
client.connect(60000,scanner.nextLine(), 5555);
client.connect(100000,"127.0.0.1", 5555);
} catch (IOException e) {
e.printStackTrace();
client.stop();
}
}
private void registerPackets() {
Kryo kryo = client.getKryo();
kryo.register(packet.PacketLoginRequest.class);
kryo.register(packet.PacketLoginAnswer.class);
kryo.register(packet.PacketMessage.class);
}
public static void main(String[] args) {
new idaClient();
Log.set(Log.LEVEL_DEBUG);
while(client.isConnected()) {
if(idaClient.scanner.hasNext() ) {
packet.PacketMessage npacket = new packet.PacketMessage();
npacket.msg = idaClient.scanner.nextLine();
client.sendTCP(npacket);
Log.info("Enter another message");
}
}
}
}
|
Python
|
UTF-8
| 12,111 | 2.78125 | 3 |
[
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"Zlib",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"BSD-3-Clause",
"OpenSSL",
"MIT"
] |
permissive
|
#!/usr/bin/env python
#
# Copyright (c) 2009, 2010, Henry Precheur <henry@precheur.org>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
'''Formats dates according to the :RFC:`3339`.
Report bugs and feature requests on Sourcehut_
Source availabe on this Mercurial repository: https://hg.sr.ht/~henryprecheur/rfc3339
.. _Sourcehut: https://todo.sr.ht/~henryprecheur/rfc3339
'''
__author__ = 'Henry Precheur <henry@precheur.org>'
__license__ = 'ISCL'
__version__ = '6.2'
__all__ = ('rfc3339', )
from datetime import (
datetime,
date,
timedelta,
tzinfo,
)
import time
import unittest
def _timezone(utc_offset):
'''
Return a string representing the timezone offset.
>>> _timezone(0)
'+00:00'
>>> _timezone(3600)
'+01:00'
>>> _timezone(-28800)
'-08:00'
>>> _timezone(-8 * 60 * 60)
'-08:00'
>>> _timezone(-30 * 60)
'-00:30'
'''
# Python's division uses floor(), not round() like in other languages:
# -1 / 2 == -1 and not -1 / 2 == 0
# That's why we use abs(utc_offset).
hours = abs(utc_offset) // 3600
minutes = abs(utc_offset) % 3600 // 60
sign = (utc_offset < 0 and '-') or '+'
return '%c%02d:%02d' % (sign, hours, minutes)
def _timedelta_to_seconds(td):
'''
>>> _timedelta_to_seconds(timedelta(hours=3))
10800
>>> _timedelta_to_seconds(timedelta(hours=3, minutes=15))
11700
>>> _timedelta_to_seconds(timedelta(hours=-8))
-28800
'''
return int((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)
def _utc_offset(timestamp, use_system_timezone):
'''
Return the UTC offset of `timestamp`. If `timestamp` does not have any `tzinfo`, use
the timezone informations stored locally on the system.
>>> if time.localtime().tm_isdst:
... system_timezone = -time.altzone
... else:
... system_timezone = -time.timezone
>>> _utc_offset(datetime.now(), True) == system_timezone
True
>>> _utc_offset(datetime.now(), False)
0
'''
if (isinstance(timestamp, datetime) and
timestamp.tzinfo is not None):
return _timedelta_to_seconds(timestamp.utcoffset())
elif use_system_timezone:
if timestamp.year < 1970:
# We use 1972 because 1970 doesn't have a leap day (feb 29)
t = time.mktime(timestamp.replace(year=1972).timetuple())
else:
t = time.mktime(timestamp.timetuple())
if time.localtime(t).tm_isdst: # pragma: no cover
return -time.altzone
else:
return -time.timezone
else:
return 0
def _string(d, timezone):
return ('%04d-%02d-%02dT%02d:%02d:%02d%s' %
(d.year, d.month, d.day, d.hour, d.minute, d.second, timezone))
def _string_milliseconds(d, timezone):
return ('%04d-%02d-%02dT%02d:%02d:%02d.%03d%s' %
(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond / 1000, timezone))
def _string_microseconds(d, timezone):
return ('%04d-%02d-%02dT%02d:%02d:%02d.%06d%s' %
(d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, timezone))
def _format(timestamp, string_format, utc, use_system_timezone):
# Try to convert timestamp to datetime
try:
if use_system_timezone:
timestamp = datetime.fromtimestamp(timestamp)
else:
timestamp = datetime.utcfromtimestamp(timestamp)
except TypeError:
pass
if not isinstance(timestamp, date):
raise TypeError('Expected timestamp or date object. Got %r.' %
type(timestamp))
if not isinstance(timestamp, datetime):
timestamp = datetime(*timestamp.timetuple()[:3])
utc_offset = _utc_offset(timestamp, use_system_timezone)
if utc:
# local time -> utc
return string_format(timestamp - timedelta(seconds=utc_offset), 'Z')
else:
return string_format(timestamp , _timezone(utc_offset))
def format_millisecond(timestamp, utc=False, use_system_timezone=True):
'''
Same as `rfc3339.format` but with the millisecond fraction after the seconds.
'''
return _format(timestamp, _string_milliseconds, utc, use_system_timezone)
def format_microsecond(timestamp, utc=False, use_system_timezone=True):
'''
Same as `rfc3339.format` but with the microsecond fraction after the seconds.
'''
return _format(timestamp, _string_microseconds, utc, use_system_timezone)
def format(timestamp, utc=False, use_system_timezone=True):
'''
Return a string formatted according to the :RFC:`3339`. If called with
`utc=True`, it normalizes `timestamp` to the UTC date. If `timestamp` does
not have any timezone information, uses the local timezone::
>>> d = datetime(2008, 4, 2, 20)
>>> rfc3339(d, utc=True, use_system_timezone=False)
'2008-04-02T20:00:00Z'
>>> rfc3339(d) # doctest: +ELLIPSIS
'2008-04-02T20:00:00...'
If called with `use_system_timezone=False` don't use the local timezone if
`timestamp` does not have timezone informations and consider the offset to UTC
to be zero::
>>> rfc3339(d, use_system_timezone=False)
'2008-04-02T20:00:00+00:00'
`timestamp` must be a `datetime`, `date` or a timestamp as
returned by `time.time()`::
>>> rfc3339(0, utc=True, use_system_timezone=False)
'1970-01-01T00:00:00Z'
>>> rfc3339(date(2008, 9, 6), utc=True,
... use_system_timezone=False)
'2008-09-06T00:00:00Z'
>>> rfc3339(date(2008, 9, 6),
... use_system_timezone=False)
'2008-09-06T00:00:00+00:00'
>>> rfc3339('foo bar') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: Expected timestamp or date object. Got <... 'str'>.
For dates before January 1st 1970, the timezones will be the ones used in
1970. It might not be accurate, but on most sytem there is no timezone
information before 1970.
'''
return _format(timestamp, _string, utc, use_system_timezone)
# FIXME deprecated
rfc3339 = format
class LocalTimeTestCase(unittest.TestCase):
'''
Test the use of the timezone saved locally. Since it is hard to test using
doctest.
'''
def setUp(self):
local_utcoffset = _utc_offset(datetime.now(),
use_system_timezone=True)
self.local_utcoffset = timedelta(seconds=local_utcoffset)
self.local_timezone = _timezone(local_utcoffset)
def test_datetime(self):
d = datetime.now()
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
def test_datetime_timezone(self):
class FixedNoDst(tzinfo):
'A timezone info with fixed offset, not DST'
def utcoffset(self, dt):
return timedelta(hours=2, minutes=30)
def dst(self, dt):
return None
fixed_no_dst = FixedNoDst()
class Fixed(FixedNoDst):
'A timezone info with DST'
def utcoffset(self, dt):
return timedelta(hours=3, minutes=15)
def dst(self, dt):
return timedelta(hours=3, minutes=15)
fixed = Fixed()
d = datetime.now().replace(tzinfo=fixed_no_dst)
timezone = _timezone(_timedelta_to_seconds(fixed_no_dst.\
utcoffset(None)))
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + timezone)
d = datetime.now().replace(tzinfo=fixed)
timezone = _timezone(_timedelta_to_seconds(fixed.dst(None)))
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + timezone)
def test_datetime_utc(self):
d = datetime.now()
d_utc = d - self.local_utcoffset
self.assertEqual(rfc3339(d, utc=True),
d_utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
def test_date(self):
d = date.today()
self.assertEqual(rfc3339(d),
d.strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
def test_date_utc(self):
d = date.today()
# Convert `date` to `datetime`, since `date` ignores seconds and hours
# in timedeltas:
# >>> date(2008, 9, 7) + timedelta(hours=23)
# date(2008, 9, 7)
d_utc = datetime(*d.timetuple()[:3]) - self.local_utcoffset
self.assertEqual(rfc3339(d, utc=True),
d_utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
def test_timestamp(self):
d = time.time()
self.assertEqual(
rfc3339(d),
datetime.fromtimestamp(d).
strftime('%Y-%m-%dT%H:%M:%S') + self.local_timezone)
def test_timestamp_utc(self):
d = time.time()
# utc -> local timezone
d_utc = datetime.utcfromtimestamp(d) + self.local_utcoffset
self.assertEqual(rfc3339(d),
(d_utc.strftime('%Y-%m-%dT%H:%M:%S') +
self.local_timezone))
def test_before_1970(self):
d = date(1885, 1, 4)
self.assertTrue(rfc3339(d).startswith('1885-01-04T00:00:00'))
self.assertEqual(rfc3339(d, utc=True, use_system_timezone=False),
'1885-01-04T00:00:00Z')
def test_1920(self):
d = date(1920, 2, 29)
x = rfc3339(d, utc=False, use_system_timezone=True)
self.assertTrue(x.startswith('1920-02-29T00:00:00'))
# If these tests start failing it probably means there was a policy change
# for the Pacific time zone.
# See http://en.wikipedia.org/wiki/Pacific_Time_Zone.
if 'PST' in time.tzname:
def testPDTChange(self):
'''Test Daylight saving change'''
# PDT switch happens at 2AM on March 14, 2010
# 1:59AM PST
self.assertEqual(rfc3339(datetime(2010, 3, 14, 1, 59)),
'2010-03-14T01:59:00-08:00')
# 3AM PDT
self.assertEqual(rfc3339(datetime(2010, 3, 14, 3, 0)),
'2010-03-14T03:00:00-07:00')
def testPSTChange(self):
'''Test Standard time change'''
# PST switch happens at 2AM on November 6, 2010
# 0:59AM PDT
self.assertEqual(rfc3339(datetime(2010, 11, 7, 0, 59)),
'2010-11-07T00:59:00-07:00')
# 1:00AM PST
# There's no way to have 1:00AM PST without a proper tzinfo
self.assertEqual(rfc3339(datetime(2010, 11, 7, 1, 0)),
'2010-11-07T01:00:00-07:00')
def test_millisecond(self):
x = datetime(2018, 9, 20, 13, 11, 21, 123000)
self.assertEqual(
format_millisecond(
datetime(2018, 9, 20, 13, 11, 21, 123000),
utc=True,
use_system_timezone=False),
'2018-09-20T13:11:21.123Z')
def test_microsecond(self):
x = datetime(2018, 9, 20, 13, 11, 21, 12345)
self.assertEqual(
format_microsecond(
datetime(2018, 9, 20, 13, 11, 21, 12345),
utc=True,
use_system_timezone=False),
'2018-09-20T13:11:21.012345Z')
if __name__ == '__main__': # pragma: no cover
import doctest
doctest.testmod()
unittest.main()
|
Java
|
UTF-8
| 641 | 2.84375 | 3 |
[] |
no_license
|
package clasesAbstractas_Empleados;
public class Administrativo extends Empleado {
private int horasExtra;
public Administrativo (int codigo, String nombre,int sueldo,Empresa enlace,int hExtra){
super(codigo,nombre,sueldo,enlace);
horasExtra=hExtra;
enlace.incrementarNumEmpleados();
}
public Administrativo() {
this(0,null,0,null,0);
}
public float calcularSueldoMensual(){
final int PRECIO_HORA=30;
float sueldoMes=sueldo_fijo+(horasExtra*PRECIO_HORA);
enlace.calcularGastoEmpresa(sueldoMes);
return sueldoMes;
}
public String toString(){
return super.toString()+ " horas Extra: " +horasExtra;
}
}
|
Ruby
|
UTF-8
| 1,395 | 3.609375 | 4 |
[] |
no_license
|
require "komaba/array"
def make_array(height, width)
a = Array.new(height)
for row in 0..width-1
a[row] = Array.new(width)
end
a
end
def put_initialize_cells(a)
for row in 0..a.size-1
for col in 0..a[row].size-1
a[row][col] = rand(2) # 0 or 1
end
end
end
def count(board, row, col)
height = board.size
width = board[0].size
r = 0
r = r + board[(row-1) % height][(col-1) % width]
r = r + board[(row-1) % height][col]
r = r + board[(row-1) % height][(col+1) % width]
r = r + board[row][(col-1) % width]
r = r + board[row][(col+1) % width]
r = r + board[(row+1) % height][(col-1) % width]
r = r + board[(row+1) % height][col]
r = r + board[(row+1) % height][(col+1) % width]
r
end
def alive(now, lives)
if lives <= 1
0
elsif lives == 2
now
elsif lives == 3
1
else
0
end
end
def copy_array(dst, src)
for row in 0..src.size-1
for col in 0..src[row].size-1
dst[row][col] = src[row][col]
end
end
end
width = 50
height = 50
board = make_array(height, width)
next_board = make_array(height, width)
put_initialize_cells(board)
puts "Press Ctrl+C to exit."
while true
show(board)
checkpoint_a()
for row in 0..height-1
for col in 0..width-1
lives = count(board, row, col)
next_board[row][col] = alive(board[row][col], lives)
end
end
copy_array(board, next_board)
end
|
Shell
|
UTF-8
| 357 | 3.71875 | 4 |
[] |
no_license
|
#!/usr/bin/env bash
function _usage {
echo "usage: $0 <1st search term> <2nd search term>...<nth search term> "
}
# check that we have a couple of params.
if [ $# = 0 ]; then
_usage
fi
# loop over inputs
command="grep --line-number --recursive --color=auto --exclude=*.{pyc,png,jpg} "
for arg in $*; do
command="$command -e $arg "
done
$command
|
Markdown
|
UTF-8
| 886 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
# redis-scan
Scan redis keys with pattern and do something to them, Aliyun redis cluster is supported.
## install
```
npm i shimo-redis-scan
```
## usage
```javascript
const RedisScan = require('shimo-redis-scan')
const Ioredis = require('ioredis')
// All keys is optional
const task = new RedisScan({
// pattern
pattern: 'key:*',
// redis client
redis: new Ioredis(),
// scan count per time
size: 1000,
// handler function which return promise
handler: function ({ key, index, stop, clusterIndex }) {
console.log('current index:', index)
if (index > 10000) {
stop()
}
},
// aliyun redis cluster
aliyun: false
})
task.start().then(() => process.exit(0))
```
## notes
1. You need to make your own catch-error logic
2. Your node.js version must support async function
3. Cluster mode is only enabled in Aliyun redis cluster
## License
MIT
|
Java
|
UTF-8
| 2,446 | 2.921875 | 3 |
[] |
no_license
|
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
import java.util.stream.Collectors;
import java.io.*;
public class Main
{
static List<int[]> prev;
static List<int[]> seats;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
prev = new ArrayList<int[]>();
String curr = "";
while ((curr = in.readLine()) != null) {
int[] line = new int[curr.length()];
for (int i = 0; i < curr.length(); i++) {
switch (curr.charAt(i)) {
case 'L': line[i] = 1; break;
case '.': line[i] = 0; break;
case '#': line[i] = 2;
}
}
prev.add(line);
}
int[] ans = iterate();
while (ans[0] != 0) ans = iterate();
System.out.println(ans[1]);
}
public static int[] iterate() {
seats = new ArrayList<int[]>();
for (int[] list : prev) seats.add(list.clone());
int[] ret = {0, 0};
for (int i = 0; i < seats.size(); i++) {
for (int j = 0; j < seats.get(i).length; j++) {
if (prev.get(i)[j] == 0) { //floor
continue;
} else { //seat
int adj = 0;
for (int k = i - 1; k <= i + 1; k++) {
for (int l = j - 1; l <= j + 1; l++) {
if (k == i && l == j) continue;
try {
if (prev.get(k)[l] == 2) //occupied
adj++;
} catch (Exception e) {}
}
}
if (prev.get(i)[j] == 1 && adj == 0) {
seats.get(i)[j]++;
ret[0]++;
ret[1]++;
} else if (prev.get(i)[j] == 2 && adj >= 4) {
seats.get(i)[j]--;
ret[0]++;
} else if (prev.get(i)[j] == 2) ret[1]++;
}
}
}
prev = new ArrayList<int[]>();
for (int[] list : seats) prev.add(list.clone());
seats.clear();
return ret;
}
}
|
JavaScript
|
UTF-8
| 3,323 | 2.578125 | 3 |
[] |
no_license
|
import 'bootstrap/dist/css/bootstrap.min.css';
import React, {useState} from "react";
import "./Task.css"
const Task = (props) => {
let empl, cr
try {
empl = props.users.find(x => x.id === props.item.employeeid.toString()).login
cr = props.users.find(x => x.id === props.item.creatorid.toString()).login
} catch {
empl = 'empl'
cr = 'cr'
}
let d1 = new Date(props.item.datestart).toLocaleDateString();
let d2 = new Date(props.item.dateend).toLocaleDateString();
let d3;
if (props.item.dateupdate !== null)
d3 = new Date(props.item.dateupdate).toLocaleDateString();
else
d3 = d1
let color = Date.parse(props.item.dateend) < Date.now() ?
(props.item.status === 3 ? "text-green" :
"text-danger") : "text-dark"
const pr = [
{id: 1, name: 'Низкий'},
{id: 2, name: 'Средний'},
{id: 3, name: 'Высокий'}
]
const st = [
{id: 1, name: 'Приступить к выполнению'},
{id: 2, name: 'Закончить выполнение'},
{id: 3, name: 'Отменить'}
]
const states = [
{id: 1, name: 'К выполнению'},
{id: 2, name: 'Выполняется'},
{id: 3, name: 'Выполнена'},
{id: 4, name: 'Отменена'}
]
function onStatusClick() {
let body = props.item
//body.dateupdate = new Date()
body.status = props.item.status + 1
props.onStatusClick({data: body, isCancel: false})
}
const [info, setInfo] = useState(false)
return (
<div className="main">
<div className="task">
<div className="i1">
<div className="p0">
<h4 className={color}>{props.item.title}</h4>
</div>
<h5 className="p1">Ответственный: {empl}</h5>
<p className="p2">Дата Окончания: {d2}</p>
<p className="p3">Приоритет: {pr[props.item.priority - 1].name}</p>
<p className="p4">Статус: {states[props.item.status - 1].name}</p>
</div>
<div className="i2">.
{props.item.status < 3 && !props.isEditable &&
<button type="submit" className="btn btn-info"
onClick={onStatusClick}>{st[props.item.status - 1].name}</button>}
{props.isEditable && <button type="submit" className="btn btn-info"
onClick={() => props.onClick({body: props.item})}>Изменить</button>}
</div>
</div>
<div>
<button type="submit" className="btn binfo"
onClick={() => setInfo(!info)}>
</button>
</div>
{info &&
<div className="task">
<h5>Описание:</h5>
<p>{props.item.text}</p>
<p>Дата создания: {d1}</p>
<p>Дата обновления: {d3}</p>
<p>Создатель: {cr}</p>
</div>}
</div>
)
}
export default Task;
|
Java
|
UTF-8
| 213 | 1.5625 | 2 |
[] |
no_license
|
package com.mototown.dao;
import org.springframework.data.repository.CrudRepository;
import com.mototown.models.Vehicle;
public interface MotoTownRepository extends CrudRepository<Vehicle, Long> {
}
|
Swift
|
UTF-8
| 1,792 | 2.765625 | 3 |
[] |
no_license
|
//
// PetsDataSource.swift
// Pet Finder
//
// Created by 张嘉夫 on 2017/6/9.
// Copyright © 2017年 张嘉夫. All rights reserved.
//
import UIKit
import Pets
import MobileCoreServices
class PetsDataSource: NSObject, UITableViewDataSource {
var pets: [Pet]
init(pets: [Pet]) {
self.pets = pets
super.init()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PetCell", for: indexPath)
let pet = pets[indexPath.row]
cell.imageView?.image = pet.image
cell.imageView?.layer.masksToBounds = true
cell.imageView?.layer.cornerRadius = 5
cell.detailTextLabel?.text = pets[indexPath.row].type
cell.textLabel?.text = pets[indexPath.row].name
return cell
}
func moveItem(at sourceIndex: Int, to destinationIndex: Int) {
guard sourceIndex != destinationIndex else { return }
let pet = pets[sourceIndex]
pets.remove(at: sourceIndex)
pets.insert(pet, at: destinationIndex)
}
func addPet(_ newPet: Pet, at index: Int) {
pets.insert(newPet, at: index)
}
func dragItems(for indexPath: IndexPath) -> [UIDragItem] {
let pet = pets[indexPath.row]
let itemProvider = NSItemProvider()
itemProvider.registerDataRepresentation(forTypeIdentifier: kUTTypeUTF8PlainText as String, visibility: .all, loadHandler: { completion in
let data = pet.name.data(using: .utf8)
completion(data, nil)
return nil
})
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = pet
return [dragItem]
}
}
|
C++
|
UTF-8
| 1,822 | 3.609375 | 4 |
[] |
no_license
|
//Hamiltonian Cycle --- Backtracking
#include<iostream>
#define V 5
using namespace std;
bool isSafe(bool graph[V][V],int path[V],int pos,int p){
int i;
if(graph[pos][path[p-1]] == 0 ){
return false;
}
for(i=0;i<p;i++){
if(path[i]==pos)
return false;
}
return true;
}
bool hamCycleUtil(bool graph[V][V],int path[V],int v){
int i;
if(v == V){
cout<<"v";
if(graph[path[0]][path[v-1]] ==1)
return true;
else
return false;
}
for(i=1;i<V;i++){
if(isSafe(graph,path,i,v)){
path[v] = i;
if(hamCycleUtil(graph,path,v+1))
return true;
path[v] = -1;
}
}
return false;
}
void printSol(int path[V]){
int i;
for(i=0;i<V;i++){
cout<<path[i]<<" ";
}
cout<<path[0];
}
void hamCycle(bool graph[V][V]){
int i,path[V];
for(i=0;i<V;i++){
path[i] = -1;
}
path[0] = 0;
if(hamCycleUtil(graph,path,1)){
printSol(path);
}
else {
cout<<"False"<<"\n";
}
}
int main(){
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
bool graph1[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};
// Print the solution
hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
bool graph2[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};
// Print the solution
hamCycle(graph2);
return 0;
}
|
Rust
|
UTF-8
| 507 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
use crate::pattern::Pattern;
#[derive(Debug, PartialEq)]
pub struct Bind<'a, T> {
pub name: &'static str,
pub help: Option<&'static str>,
pub required: bool,
pub patterns: Vec<Pattern<'a>>,
pub takes_parameter: bool,
pub kind: T,
}
impl<'a, T> Bind<'a, T>
where
T: Copy,
{
pub fn matches(&self, s: &str) -> bool {
for pattern in &self.patterns {
if pattern.matches(s) {
return true;
}
}
return false;
}
}
|
JavaScript
|
UTF-8
| 5,355 | 3 | 3 |
[] |
no_license
|
const $listaContainer = $('.container-lista');
const urlPokemon = "https://pokeapi.co/api/v2/pokemon"
let offset = 0;
let limite = 807;
let id = 1 + offset;
pokemonData = {};
function cargarListaPokemon() {
fetch(urlPokemon + '?offsset=' + offset + "&limit=" + limite)
.then(res => res.json())
.then(pokemon => {
pokemon.results.forEach((element) => {
const $listaNombrePokemon = $('<a href="#" id="' + id + '" class="text-capitalize list-group-item list-group-item-action bg-light elemento-lista-pokemon">Cargando...</a>');
$listaContainer.append($listaNombrePokemon);
$listaNombrePokemon.text(element.name);
id++;
})
})
.catch(error => console.error("Hubo un error: ", error));
};
function obtenerInfoDelPokemonSeleccionado(id) {
const pokemonInfo = {
id: null,
nombre: "",
descripcion: "",
habilidades: [],
altura: null,
peso: null,
tipos: [],
foto: ""
};
fetch(urlPokemon + '/' + id)
.then(res => res.json())
.then(pokemon => {
pokemonInfo.id = pokemon.id;
pokemonInfo.nombre = pokemon.name;
pokemon.abilities.forEach(habilidad => {
pokemonInfo.habilidades.push(habilidad.ability.name);
});
pokemonInfo.altura = pokemon.height * 10; //Según la documentación altura está expresada en decímetros. La paso a centímetros.
pokemonInfo.peso = pokemon.weight / 10; //Se pasa el peso de hectogramos a kilogramos.
pokemon.types.forEach(tipo => {
pokemonInfo.tipos.push(tipo.type.name);
});
pokemonInfo.foto = pokemon.sprites.front_default;
return fetch("https://pokeapi.co/api/v2/pokemon-species/" + id)
.then(res => res.json())
.then(pokemonSpecies => {
pokemonSpecies.flavor_text_entries.some(flavor => {
if (flavor.language.name === "es") {
return pokemonInfo.descripcion = flavor.flavor_text;
}
})
mostrarPokemonSeleccionado(pokemonInfo);
})
})
.catch(error => console.error("Hubo un error: ", error));
};
function mostrarPokemonSeleccionado(pokemonSeleccionado) {
const containerPokemon = $('<div id="container-pokemon" class="card mx-auto mt-5"></div>'),
nombrePokemon = $('<h2 id="nombre-pokemon" class="card-title pt-3 text-capitalize text-center">Cargando...</h2>'),
containerBadgeTipoPokemon = $('<div id="container-badge-tipo-pokemon" class="container"></div>'),
fotoPokemon = $('<img id="foto-pokemon" src="./src/img/loading.gif" class="card-img-top" alt="">'),
containerPesoAlturaDescripcion = $('<div id="container-descripcion-peso-altura" class="card-body"></div>'),
containerPesoAltura = $('<div id="container-peso-altura" class="row"></div>'),
pesoPokemon = $('<div id="pesoPokemon" class="text-center pt-3 col-6 border-top">Cargando...</div>'),
alturaPokemon = $('<div id="alturaPokemon" class="col-6 pt-3 border-top text-center">Cargando...</div>'),
descripcionPokemon = $('<p id="descripcion" class="card-text mt-3">Cargando...</p>');
if ($("#container-pokemon")) {
$("#container-pokemon").remove();
};
$('#container-principal').append(containerPokemon);
containerPokemon.append(nombrePokemon);
nombrePokemon.text(pokemonSeleccionado.nombre);
containerPokemon.append(containerBadgeTipoPokemon);
for (let i = 0; i < pokemonSeleccionado.tipos.length; i++) {
containerBadgeTipoPokemon.append($('<span class="badge pb-1 ' + pokemonSeleccionado.tipos[i] + '">' + pokemonSeleccionado.tipos[i] + '</span>'));
}
containerPokemon.append(fotoPokemon);
fotoPokemon.attr("src", pokemonSeleccionado.foto);
containerPokemon.append(containerPesoAlturaDescripcion);
containerPesoAlturaDescripcion.append(containerPesoAltura);
containerPesoAltura.append(pesoPokemon);
pesoPokemon.html("<strong>Peso:</strong> " + pokemonSeleccionado.peso + " kg");
containerPesoAltura.append(alturaPokemon);
alturaPokemon.html("<strong>Altura:</strong> " + pokemonSeleccionado.altura + " cm");
containerPesoAlturaDescripcion.append($("<hr/>"));
containerPesoAlturaDescripcion.append(descripcionPokemon);
descripcionPokemon.text(pokemonSeleccionado.descripcion);
}
cargarListaPokemon();
const $listaPokemon = document.querySelector('.container-lista');
$listaPokemon.onclick = function (e) {
if (e.target.classList.contains("elemento-lista-pokemon")) {
obtenerInfoDelPokemonSeleccionado(e.target.id);
};
};
$("#buscar").on("keyup", function () {
if (this.value.length > 0) {
$listaContainer.each(function () {
$(this).children().hide().filter(function () {
return $(this).text().toLowerCase().lastIndexOf($("#buscar").val().toLowerCase(), 0) == 0;
}).show();
});
}
else {
$(".container-lista").show();
}
});
$("#menu-toggle").click(function (e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
|
Shell
|
UTF-8
| 1,162 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
fix () {
ionice -c 3 \
nice -n 19 \
ffmpeg -i "$MFPATH"/"$NAME"."$EXT" -copyts -map 0 -c copy -f mpegts "$MFPATH"/"$NAME".tmp_"$EXT" && \
mv -f "$MFPATH"/"$NAME".tmp_"$EXT" "$MFPATH"/"$NAME"."$EXT"
}
skip () {
INI_FILE="/config/comskip/comskip.ini"
if [ ! -f $INI_FILE ]; then
INI_FILE="/usr/bin/comskip_cfg"
fi
# ionice -c 3 nice -n 19 comskip --threads=4 --ini=$INI_FILE "$MFPATH"/"$NAME"."$EXT"
ionice -c 3 nice -n 19 comskip --ini=$INI_FILE "$MFPATH"/"$NAME"."$EXT"
echo "$MFPATH"/"$NAME"."$EXT"
ffprobe -i "$MFPATH"/"$NAME"."$EXT"
cat "$MFPATH"/"$NAME".edl
notify $MQTT_HOST $MQTT_USER $MQTT_PASS "$MFPATH"/"$NAME"."$EXT"
}
usage () {
echo "$0 option file"
echo "options: fix skip clean fix_skip"
exit 1
}
clean () {
ls -1 "$MFPATH"/"$NAME".*
rm -rf "$MFPATH"/"$NAME".*
}
process () {
case "$1" in
"fix")
fix
;;
"skip")
skip
;;
"clean")
clean
;;
"fix_skip")
fix
skip
;;
*)
usage
;;
esac
}
if [ "$#" != "2" ]; then
usage
fi
MFPATH=$(dirname "$2")
s=$(basename "$2")
NAME=${s%.*}
EXT=${s##*.}
process "$@"
|
Swift
|
UTF-8
| 4,961 | 2.53125 | 3 |
[] |
no_license
|
//
// ImageViewController.swift
// Dog breeds
//
// Created by Александр Осипов on 01.08.2020.
// Copyright © 2020 Александр Осипов. All rights reserved.
//
import UIKit
class ImageViewController: UIViewController {
@IBOutlet weak var imageCollectionView: UICollectionView!
@IBOutlet weak var imageNavigationItem: UINavigationItem!
@IBOutlet weak var mainActivityIndicatorView: UIActivityIndicatorView!
var routing = Routing()
var breedString: String?
var subbreedString: String?
var breedRequestStr = ""
var arrayImagesURL: [String] = []
var arrayImagesURLRealm: [BreedImageRealm]?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
routing.delegateImage = self
mainActivityIndicatorView.isHidden = false
mainActivityIndicatorView.startAnimating()
imageNavigationItem.title = breedRequestStr
if let breedString = breedString, let subbreedString = subbreedString {
breedRequestStr = "\(breedString)/\(subbreedString)"
imageNavigationItem.title = "\(breedString) \(subbreedString)"
} else if let breedString = breedString {
breedRequestStr = breedString
imageNavigationItem.title = breedString
}
if let arrayImagesURLRealm = arrayImagesURLRealm {
arrayImagesURL.removeAll()
for url in arrayImagesURLRealm {
if !url.isInvalidated {
arrayImagesURL.append(url.imageURL)
}
}
} else {
routing.getImage(type: .imageBreed(breedRequestStr))
}
}
@IBAction func shareButton(_ sender: UIBarButtonItem) {
let myActionSheet = UIAlertController(title: "Share photo", message: "", preferredStyle: UIAlertController.Style.actionSheet)
let shareAction = UIAlertAction(title: "Share", style: UIAlertAction.Style.default) { (action) in
print("Share action button tapped")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) { (action) in
print("Cancel action button tapped")
}
myActionSheet.addAction(shareAction)
myActionSheet.addAction(cancelAction)
present(myActionSheet, animated: true, completion: nil)
}
}
extension ImageViewController: PresentImageProtocol {
func presentImage(response: FetchType<Image>) {
switch response {
case .success(let track):
arrayImagesURL = track.message
DispatchQueue.main.async {
self.imageCollectionView.reloadData()
self.mainActivityIndicatorView.stopAnimating()
}
case .failure(let error):
print(error)
DispatchQueue.main.async {
self.errorAlert(with: error)
}
}
}
func errorAlert(with title: String) {
let alertController = UIAlertController(title: title, message: "Повторите попытку.", preferredStyle: .alert)
let closeAction = UIAlertAction(title: "Закрыть", style: .cancel, handler: { [weak self] (_ action: UIAlertAction) -> Void in
guard let self = self else { return }
self.dismiss(animated: true, completion: nil)
})
let tryAgainAction = UIAlertAction(title: "Повторить", style: .default) { [weak self] (_) in
guard let self = self else { return }
self.routing.getImage(type: .imageBreed(self.breedRequestStr))
}
alertController.addAction(tryAgainAction)
alertController.addAction(closeAction)
present(alertController, animated: true)
}
}
extension ImageViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayImagesURL.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCollectionViewCell
let track = self.arrayImagesURL[indexPath.row]
cell.breed = breedString
cell.subbreed = subbreedString
cell.imageURL = track
return cell
}
// MARK: - CollectionViewFlowLayoutDelegate
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let w = collectionView.bounds.width
let h = collectionView.bounds.height
return CGSize(width: w, height: h)
}
}
|
Swift
|
UTF-8
| 2,996 | 2.734375 | 3 |
[] |
no_license
|
import RxSwift
import RxSwiftExt
import Firebase
import Himotoki
import Library
extension Firebase {
struct Post: PostType {
let id: PostID
let prompt: String
let author: UserID
static func fromFirebase(ref: DataSnapshot) -> Post? {
guard let json = ref.value as? [String: Any] else { return nil }
return fromFirebase(json: ["uid": ref.key as Any] + json)
}
static func fromFirebase(json: [String: Any]) -> Post? {
return try? Post.decodeValue(json)
}
}
}
extension Firebase.Post: Himotoki.Decodable {
static func decode(_ e: Extractor) throws -> Firebase.Post { //swiftlint:disable:this variable_name
return try Firebase.Post(
id: e <| "uid",
prompt: e <| "prompt",
author: e <| "authorId"
)
}
// doesnt include the id, since we never want to upload that. The ID is simply the location
func encoded() -> [String: Any] {
return [
"prompt": prompt,
"authorId": author
]
}
}
extension Firebase.Provider {
func fetchPost(withId id: PostID) -> Observable<Firebase.Post?> {
return ref
.child("posts")
.child(id)
.rx.observeEventOnce()
.map(Firebase.Post.fromFirebase)
}
func fetchPosts() -> Observable<[Firebase.Post]> {
return ref
.child("posts")
.queryOrdered(byChild: "date")
.rx.observeEventOnce()
.map { arrayOfPostsRef in
return arrayOfPostsRef.children.map { snapshot in
guard let postSnapshot = snapshot as? DataSnapshot else { fatalError("rethink this :/") }
return Firebase.Post.fromFirebase(ref: postSnapshot)!
}
}
}
func createPost(prompt: String, by userId: UserID) -> Observable<Firebase.Post> {
/**
/// This idea comes from https://github.com/firebase/quickstart-ios/blob/f0c4be06f9bfe73a4a90116b19ee8f500c24f4c1/database/DatabaseExampleSwift/NewPostViewController.swift#L68
/// Create new post at
/// /user-posts/$userid/$postid and at
/// /posts/$postid simultaneously
///
/// /user-posts/$userid/$postid so we can find posts for you & your followers
/// /posts/$postid so we can find everyone's recent & popular posts
*/
let postId = ref.child("posts").childByAutoId().key as PostID
let post = Firebase.Post(id: postId, prompt: prompt, author: userId)
let globalScopedPost = ref
.child("posts")
.child(postId)
.rx.setValue(post.encoded())
let userScopedPost = ref
.child("user-posts")
.child(userId)
.child(postId)
.rx.setValue(post.encoded() as AnyObject)
return Observable.zip(globalScopedPost, userScopedPost) { _, _ in post }
}
}
|
C++
|
UTF-8
| 4,848 | 3.078125 | 3 |
[] |
no_license
|
//
// Copyright 2015 Yangbin Lin. All Rights Reserved.
//
// Author: yblin@jmu.edu.cn (Yangbin Lin)
//
// This file is part of the Code Library.
//
#ifndef VISUALIZATION_PLOT_AXIS_H_
#define VISUALIZATION_PLOT_AXIS_H_
#include <algorithm>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <string>
#include "codelibrary/base/format.h"
#include "codelibrary/visualization/terminal/terminal.h"
namespace cl {
namespace plot {
/**
* Axis for Plot.
*/
class Axis {
public:
/**
* Construct a axis by given range and maximal number of ticks.
* Note that, the data range not necessarily the same as the axis range.
*
* Parameters:
* min - the expected minimal value of axis.
* max - the expected maximal value of axis.
* max_ticks - the expected maximal number of ticks on the axis.
*/
Axis(double min = 0.0, double max = 1.0, int max_ticks = 10) {
Reset(min, max, max_ticks);
}
/**
* Reset this axis.
*/
void Reset(double min, double max, int max_ticks = 10) {
assert(min <= max);
assert(max_ticks > 0);
ChooseInterval(min, max, max_ticks);
GenerateTicks(min, max);
}
/**
* Return the minimum value of tick on the axis.
*/
double min() const {
return ticks_.front();
}
/**
* Return the maximal value of tick on the axis.
*/
double max() const {
return ticks_.back();
}
/**
* Return the length of axis.
*/
double length() const {
return max() - min();
}
/**
* Return the interval between two neighbor ticks.
*/
double interval() const {
return interval_;
}
/**
* Manually set an interval.
*/
void SetInterval(double interval) {
assert(interval > 0.0);
assert(length() < INT_MAX * interval &&
"The given interval can not be too small");
interval_ = interval;
GenerateTicks(min(), max());
}
/**
* Return the tick values.
*/
const Array<double>& ticks() const {
return ticks_;
}
/**
* Return the tick labels.
*/
const Array<std::string>& tick_labels() const {
return tick_labels_;
}
/**
* Reverse the direction of axis.
*/
void Reverse() {
is_increasing_ ^= 1;
}
/**
* Return true if the axis value is increasing.
*/
bool is_increasing() const {
return is_increasing_;
}
private:
/**
* Automatically choose a usable ticking interval.
*/
void ChooseInterval(double min, double max, int max_ticks) {
// Order of magnitude of argument.
double length = max - min;
if (length == 0.0) length = 1.0;
double power = std::pow(10.0, std::floor(std::log10(length)));
// Approximate number of decades, we expect that 1 <= xnorm <= 10.
double xnorm = length / power;
xnorm = Clamp(xnorm, 1.0, 10.0);
// Approximate number of ticks per decade.
double n_ticks = max_ticks / xnorm;
if (n_ticks > 20.0) {
interval_ = 0.05; // e.g. 0, 0.05, 0.10, ...
} else if (n_ticks > 10.0) {
interval_ = 0.1; // e.g. 0, 0.1, 0.2, ...
} else if (n_ticks > 5.0) {
interval_ = 0.2; // e.g. 0, 0.2, 0.4, ...
} else if (n_ticks > 2.0) {
interval_ = 0.5; // e.g. 0, 0.5, 1, ...
} else if (n_ticks > 1.0) {
interval_ = 1.0; // e.g. 0, 1, 2, ...
} else if (n_ticks > 0.5) {
interval_ = 2.0; // e.g. 0, 2, 4, ...
} else {
interval_ = std::ceil(xnorm);
}
interval_ *= power;
}
/**
* Generate tick values and labels.
*/
void GenerateTicks(double min, double max) {
int start = static_cast<int>(std::floor(min / interval_));
int end = static_cast<int>(std::ceil(max / interval_));
assert(start <= end);
ticks_.clear();
for (int i = start; i <= end; ++i) {
double x = i * interval_;
ticks_.push_back(x);
}
if (ticks_.size() == 1) {
ticks_.push_back((end + 1) * interval_);
}
// Generate tick labels.
tick_labels_.clear();
for (double x : ticks_) {
tick_labels_.push_back(fmt::format("{:g}", x));
}
}
// The interval between two neighbor ticks.
double interval_ = 0.0;
// Position of ticks.
Array<double> ticks_;
// Labels for every tick.
Array<std::string> tick_labels_;
// True if the values are increasing.
bool is_increasing_ = true;
};
} // namespace plot
} // namespace cl
#endif // VISUALIZATION_PLOT_AXIS_H_
|
Java
|
UTF-8
| 1,593 | 2.203125 | 2 |
[] |
no_license
|
package com.test.controller;
import com.test.model.Picture;
import com.test.service.LoginService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.time.LocalDateTime;
import java.util.List;
@Controller
@RequestMapping("/cabinet*")
@PreAuthorize("hasRole('CUSTOMER')")
public class CabinetController {
private final LoginService loginService;
public CabinetController(LoginService loginService) {
this.loginService = loginService;
}
/*@RequestMapping(method = RequestMethod.GET)
public List<Customer> getUsers() {
List<Customer> result = new ArrayList<>();
customerRepository.findAll().forEach(result::add);
return result;
}*/
@RequestMapping(method = RequestMethod.GET)
@Secured("hasRole('')")
public String showCabinet(Model model) {
model.addAttribute("now", LocalDateTime.now()); //todo delete this line
if (loginService.ensureCustomer()) {
return "tl/cabinet";
} else {
return "redirect:tl/main?error=NotCustomer";
}
}
@RequestMapping(method = RequestMethod.POST)
public String addPictures(@ModelAttribute("pictureList") List<Picture> pictures, Model model) {
//todo maybe need in checking errors here
model.addAttribute("info", "pictures uploaded");
return "tl/cabinet";
}
}
|
Python
|
UTF-8
| 1,293 | 4.53125 | 5 |
[] |
no_license
|
#demonstrate math operations in python
#initialize some variables
x = 2
xx = 2.5
y = 4
yy = 4.5
yyy = 5.1
print yy/xx #quotient
print yy//xx #floored quotient - lower integer bound; type takes on the types of input
#take x to the power of y
powY = pow(y,x)
powY_ = y**x
print powY, powY_
#remainder of yy/x
print yy%x
dataList = (x, xx, y, yy)
#recall that slicing or subsetting is not inclusive:
print dataList[1:3] #does not include the value of yy and returns 2 items
import math
#exponent and logs
print math.exp(xx)
print math.log(xx)
#as in C++, we can do some operations on a variable without calling it
#this will perform the operation on the incoming value of the variable and return
#a final value in the same variable
val1 = 5
val2 = 3
val1 += 2
print val1
#and, or, not logical operations
print (val1 > val2)
print (val1 > 10 and val1 < 12)
print (val1 == 7 or val2 == 2)
print not(val1 == 7 or val2 == 2) #not reverses result of operation
#in and not in are used to query presence in sequence
print (2.57 in dataList)
print (2.5 in dataList)
#is and is not are used to compare objects (not contents)
dataList2 = dataList
dataList3 = (x, xx, y, yy)
print dataList2 is dataList #same objects - returns True
print dataList3 is dataList #same contents - returns False
|
JavaScript
|
UTF-8
| 527 | 4.65625 | 5 |
[] |
no_license
|
/*
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
*/
function isPrime(number){
if(number%2==0)
return false;
var sqrt = Math.floor(Math.sqrt(number));
for(var i=3;i<=sqrt;i+=2){
if(number%i==0)
return false;
}
return true;
}
var primes = [2];
var num = 3;
while(primes.length <10001){
if(isPrime(num)){
primes.push(num);
}
num+=2;
}
console.log('10001th prime: ' + primes[primes.length-1]);
|
TypeScript
|
UTF-8
| 5,588 | 2.875 | 3 |
[
"Apache-2.0"
] |
permissive
|
import { IRoundTile, TileValue, TileSetGroup } from "../../models/tile";
import _ from "lodash";
import { TileStatus } from "../../models/tileStatus";
export const GetPossibleChow = (
boardActiveTile: IRoundTile,
playerActiveTiles: IRoundTile[]
): Array<IRoundTile[]> => {
let chowTilesOptions: Array<IRoundTile[]> = [];
let sameTypeChowTiles = playerActiveTiles.filter(
(t) =>
t.tile.tileType === boardActiveTile.tile.tileType &&
t.tile.tileValue !== boardActiveTile.tile.tileValue
);
// If the board active tile is one
if (boardActiveTile.tile.tileValue === TileValue.One) {
const tileTwo = sameTypeChowTiles?.find(
(t) => t.tile.tileValue === TileValue.Two
);
const tileThree = sameTypeChowTiles?.find(
(t) => t.tile.tileValue === TileValue.Three
);
if (tileTwo && tileThree) {
let twoThreeArray: IRoundTile[] = [tileTwo, tileThree];
chowTilesOptions.push(twoThreeArray);
}
// If the board active tile is nine
} else if (boardActiveTile.tile.tileValue === TileValue.Nine) {
const tileSeven = sameTypeChowTiles?.find(
(t) => t.tile.tileValue === TileValue.Seven
);
const tileEight = sameTypeChowTiles?.find(
(t) => t.tile.tileValue === TileValue.Eight
);
if (tileSeven && tileEight) {
let sevenEightArray: IRoundTile[] = [tileSeven, tileEight];
chowTilesOptions.push(sevenEightArray);
}
// if not one or nine
} else {
let possibleTiles = sameTypeChowTiles?.filter(
(t) =>
t.tile.tileValue === boardActiveTile!.tile.tileValue - 2 ||
t.tile.tileValue === boardActiveTile!.tile.tileValue + 2 ||
t.tile.tileValue === boardActiveTile!.tile.tileValue + 1 ||
t.tile.tileValue === boardActiveTile!.tile.tileValue - 1
);
if (possibleTiles && possibleTiles.length > 1) {
//remove dups
possibleTiles = _.uniqWith(
possibleTiles,
(a, b) =>
a.tile.tileType === b.tile.tileType &&
a.tile.tileValue === b.tile.tileValue
);
//now we try to get possible tiles to chow
for (var i = 0; i < possibleTiles.length; i++) {
let t = possibleTiles[i];
let testChowTiles: IRoundTile[] = [];
testChowTiles.push(t);
testChowTiles.push(boardActiveTile!);
testChowTiles.sort((a, b) => a!.tile.tileValue - b!.tile.tileValue);
let probableTile;
if ((t.tile.tileValue + boardActiveTile!.tile.tileValue) % 2 !== 0) {
//then these two tiles is connected
probableTile = possibleTiles.find(
(t) => t.tile.tileValue === testChowTiles[1].tile.tileValue + 1
);
} else {
//then these two tiles is not connected
probableTile = possibleTiles.find(
(t) => t.tile.tileValue === testChowTiles[0].tile.tileValue + 1
);
}
if (probableTile) {
chowTilesOptions.push(
[probableTile, t].sort(
(a, b) => a!.tile.tileValue - b!.tile.tileValue
)
);
}
}
}
}
//remove dups
chowTilesOptions = _.uniqWith(chowTilesOptions, (a, b) => {
let foundDups = true;
var firsta = _.find(b, function (t) {
return t.tile.tileValue === a[0].tile.tileValue;
});
var seconda = _.find(b, function (t) {
return t.tile.tileValue === a[1].tile.tileValue;
});
if (!firsta || !seconda) foundDups = false;
return foundDups;
});
return chowTilesOptions;
};
export const GetPossibleKong = (
isPlayerTurn: boolean,
playerTiles: IRoundTile[],
boardActiveTile: IRoundTile
): IRoundTile[] => {
const mainPlayerAliveTiles = _.filter(
playerTiles,
(t) => t.status === TileStatus.UserActive || t.status === TileStatus.UserJustPicked
);
let validTileForKongs: IRoundTile[] = [];
var kongTiles = _.chain(playerTiles)
.groupBy((asd) => `${asd.tile.tileType}-${asd.tile.tileValue}`)
.filter((asd) => asd.length > 2)
.value();
_.forEach(kongTiles, function (ts) {
//if player has 3 same tiles and not in graveyard, they can kong matching board active tile anytime even if its not their turn
if (ts.length === 3) {
let userActive = _.filter(
ts,
(t) => t.status !== TileStatus.UserGraveyard
);
if (
userActive.length === 3 &&
boardActiveTile &&
userActive[0].tile.tileType === boardActiveTile.tile.tileType &&
userActive[0].tile.tileValue === boardActiveTile.tile.tileValue
)
validTileForKongs.push(boardActiveTile);
}
if (ts.length === 4 && isPlayerTurn) {
//if its player's turn
//if player has 3 same tiles that's ponged, player can kong only from their active and just picked tile
let pongedTile = _.filter(
ts,
(t) => t.tileSetGroup === TileSetGroup.Pong
);
if (pongedTile.length === 3) {
//check if user active tile
let tileIsAlive = _.filter(
mainPlayerAliveTiles,
(t) =>
t.tile.tileValue === pongedTile[0].tile.tileValue &&
t.tile.tileType === pongedTile[0].tile.tileType
);
if (tileIsAlive.length > 0) validTileForKongs.push(tileIsAlive[0]);
}
//if tile is not in graveyard, then player can kong when its his turn
let allTileAlive = _.filter(
ts,
(t) => t.status !== TileStatus.UserGraveyard
);
if (allTileAlive.length === 4) validTileForKongs.push(allTileAlive[0]);
}
});
return validTileForKongs;
};
|
TypeScript
|
UTF-8
| 1,596 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
import { WritableStreamBuffer } from 'stream-buffers'
import { OutPacketBase } from 'packets/out/packet'
import { PacketId } from 'packets/definitions'
import { PacketString } from 'packets/packetstring'
import { ExtendedSocket } from 'extendedsocket'
/**
* sends out the result of a login attempt
* Structure:
* [base packet]
* [userId - 4 bytes]
* [loginName - the length of the str + 1 byte]
* [userName - the length of the str + 1 byte]
* [unk00 - 1 byte]
* [serverUdpPort - 2 bytes]
* @class OutUserStartPacket
*/
export class OutUserStartPacket extends OutPacketBase {
private userId: number
private loginName: PacketString
private userName: PacketString
private unk00: number
private holepunchPort: number
constructor(userId: number, loginName: string, userName: string,
holepunchPort: number, socket: ExtendedSocket) {
super(socket, PacketId.UserStart)
this.userId = userId
this.loginName = new PacketString(loginName)
this.userName = new PacketString(userName)
this.unk00 = 1
this.holepunchPort = holepunchPort
}
/**
* builds the packet with data provided by us
*/
public build(): Buffer {
this.outStream = new WritableStreamBuffer(
{ initialSize: 20, incrementAmount: 4 })
this.buildHeader()
this.writeUInt32(this.userId)
this.writeString(this.loginName)
this.writeString(this.userName)
this.writeUInt8(this.unk00)
this.writeUInt16(this.holepunchPort)
return this.getData()
}
}
|
Java
|
UTF-8
| 830 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
package com.brentonbostick.capsloc.world.sprites;
import static com.brentonbostick.capsloc.CapslocApplication.APP;
import com.brentonbostick.capsloc.Resource;
import com.brentonbostick.capsloc.ui.Image;
import com.brentonbostick.capsloc.ui.paint.RenderingContext;
public abstract class Sheet {
Resource res;
Image img;
public void load() throws Exception {
img = APP.platform.readImage(res);
}
public void paint(RenderingContext ctxt, Sprite s, int dx1, int dy1, int dx2, int dy2) {
ctxt.paintImage(img, dx1, dy1, dx2, dy2, s.xStart(), s.yStart(), s.xEnd(), s.yEnd());
}
public void paint(RenderingContext ctxt, Sprite s, double origX, double origY, double dx1, double dy1, double dx2, double dy2) {
ctxt.paintImage(img, origX, origY, dx1, dy1, dx2, dy2, s.xStart(), s.yStart(), s.xEnd(), s.yEnd());
}
}
|
PHP
|
UTF-8
| 3,591 | 2.640625 | 3 |
[] |
no_license
|
<?php
/**
* TechDivision\WebSocketContainer\Application
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
*/
namespace TechDivision\WebSocketContainer;
use Guzzle\Http\Message\RequestInterface;
use TechDivision\ApplicationServer\AbstractApplication;
use TechDivision\WebSocketContainer\HandlerManager;
use TechDivision\WebSocketContainer\Service\Locator\HandlerLocator;
use TechDivision\ApplicationServer\Configuration;
use TechDivision\ApplicationServer\Vhost;
/**
* The application instance holds all information about the deployed application
* and provides a reference to the web socket manager and the initial context.
*
* @package TechDivision\WebSocketContainer
* @copyright Copyright (c) 2010 <info@techdivision.com> - TechDivision GmbH
* @license http://opensource.org/licenses/osl-3.0.php
* Open Software License (OSL 3.0)
* @author Tim Wagner <tw@techdivision.com>
*/
class Application extends AbstractApplication
{
/**
* The handler manager.
*
* @var \TechDivision\WebSocketContainer\HandlerManager
*/
protected $handlerManager;
/**
* Has been automatically invoked by the container after the application
* instance has been created.
*
* @return \TechDivision\WebSocketContainer\Application The connected application
*/
public function connect()
{
// also initialize the vhost configuration
parent::connect();
// initialize the class loader with the additional folders
set_include_path(get_include_path() . PATH_SEPARATOR . $this->getWebappPath());
set_include_path(get_include_path() . PATH_SEPARATOR . $this->getWebappPath() . DIRECTORY_SEPARATOR . 'WEB-INF' . DIRECTORY_SEPARATOR . 'classes');
set_include_path(get_include_path() . PATH_SEPARATOR . $this->getWebappPath() . DIRECTORY_SEPARATOR . 'WEB-INF' . DIRECTORY_SEPARATOR . 'lib');
// initialize the handler manager instance
$handlerManager = $this->newInstance('TechDivision\WebSocketContainer\HandlerManager', array(
$this
));
$handlerManager->initialize();
// set the handler manager
$this->setHandlerManager($handlerManager);
// return the instance itself
return $this;
}
/**
* Sets the applications handler manager instance.
*
* @param \TechDivision\WebSocketContainer\HandlerManager $handlerManager
* The handler manager instance
* @return \TechDivision\WebSocketContainer\Application The application instance
*/
public function setHandlerManager(HandlerManager $handlerManager)
{
$this->handlerManager = $handlerManager;
return $this;
}
/**
* Return the handler manager instance.
*
* @return \TechDivision\WebSocketContainer\HandlerManager The handler manager instance
*/
public function getHandlerManager()
{
return $this->handlerManager;
}
/**
* Locates the handler for the passed request.
*
* @param \Guzzle\Http\Message\RequestInterface $request
* @return \Ratchet\MessageComponentInterface
*/
public function locate(RequestInterface $request)
{
$className = 'TechDivision\WebSocketContainer\Service\Locator\HandlerLocator';
$handlerLocator = $this->newInstance($className, array(
$this->getHandlerManager()
));
return $handlerLocator->locate($request);
}
}
|
Swift
|
UTF-8
| 738 | 3.078125 | 3 |
[] |
no_license
|
//
// Goal.swift
// uReadLiteracy
//
// Created by Duy Le 2 on 11/24/18.
// Copyright © 2018 AdaptConsulting. All rights reserved.
//
import Foundation
class GoalModel{
let name:String
var progress:Int!
let date:Date
init(name:String,date:Date){
self.name = name
self.date = date
progress = 0
}
init(name:String,progress:Int,date:Date){
self.name = name
self.progress = progress
self.date = date
}
func getDescription()->String{
return "\(name)"
}
func getDescriptionWithProgress()->String{
return "\(name): \(Int(progress))%"
}
func isCompleted()->Bool{
return progress == 100
}
}
|
Shell
|
UTF-8
| 3,769 | 3.15625 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
#!/bin/sh
#v10.0.3
globalconf="${workdir}/cbsd.conf";
CBSDMODULE="build"
MYARG=""
MYOPTARG="ver arch target_arch maxjobs clean name basename ccache notify stable emulator"
MYDESC="Build kernel from sources"
set -e
. ${globalconf}
set +e
. ${subr}
init $*
over="${ver}"
oarch="${arch}"
[ -z "${NICE}" ] && NICE="0"
. ${buildconf}
. ${distccacheconf}
. ${mailconf}
readconf buildworld.conf
. ${system}
. ${workdir}/universe.subr
. ${workdir}/emulator.subr
readconf srcup.conf
init_distcc
init_notify
init_target_arch
init_srcdir
init_supported_arch
[ -z "${emulator}" ] && emulator="jail"
init_usermode_emul
if [ "${ccache}" = "1" ]; then
ccache_prefix="cbsd buildworld ${ver} ${arch} ${target_arch} ${basename}"
ccache_dir="/var/cache/ccache"
init_ccache_dir
export CCACHE_DIR=${ccache_realdir}
if ! ccache_check; then
ccache=0
fi
else
ccache=0
fi
init_basedir
if [ ! -d "${BASE_DIR}" -o ! -f "${BASE_DIR}/bin/sh" ]; then
${ECHO} "${MAGENTA}FreeBSD base on ${GREEN}${BASE_DIR}${MAGENTA} is missing${NORMAL}"
${ECHO} "${MAGENTA}Use ${GREEN}cbsd world${MAGENTA} to compile from the source${NORMAL}"
${ECHO} "${GREEN}cbsd repo action=get sources=base${MAGENTA} to obtain it from repository.${NORMAL}"
exit 1
fi
init_make_flags
LOCKFILE=${ftmpdir}/$( /sbin/md5 -qs ${MAKEOBJDIRPREFIX} ).lock
[ -z "${name}" ] && name="GENERIC"
kernel_conf="${platform}-kernel-${name}-${arch}-${ver}"
if [ -f "${etcdir}/${kernel_conf}" ]; then
kernel_conf_path="${etcdir}/${kernel_conf}"
else
kernel_conf_path="${etcdir}/defaults/${kernel_conf}"
fi
[ ! -f "${kernel_conf_path}" ] && err 1 "${MAGENTA}No such config ${kernel_conf_path} in: ${GREEN}${etcdir}${NORMAL}"
## preparing chroot
TMPDST="${basejaildir}/tempbase.$$"
/bin/mkdir -p ${TMPDST}
[ $notify -eq 1 ] && BLDLOG="${tmpdir}/build.$$.log"
case "${platform}" in
"DragonFly")
DESTCONF="${SRC_DIR}/sys/config/${name}.CBSD"
;;
*)
DESTCONF="${SRC_DIR}/sys/${arch}/conf/${name}.CBSD"
;;
esac
makelock $LOCKFILE "/bin/rm -f ${DESTCONF} && /sbin/umount -f ${TMPDST}${MAKEOBJDIRPREFIX} && /sbin/umount -f ${TMPDST}/dev && /sbin/umount -f ${TMPDST}/usr/src && ${CHFLAGS_CMD} -R noschg ${TMPDST} && /bin/rm -rf ${TMPDST} && /bin/rm -f ${BLDLOG}"
baserw=1
populate_cdir ${BASE_DIR} ${TMPDST}
cp ${kernel_conf_path} ${DESTCONF}
# place for rewrite to mountbase from system.subr
mkdir -p ${TMPDST}/usr/src
${MOUNT_NULL_CMD} -o ro ${SRC_DIR} ${TMPDST}/usr/src
mkdir -p ${MAKEOBJDIRPREFIX} ${TMPDST}${MAKEOBJDIRPREFIX}
mkdir -p ${TMPDST}${etcdir}
[ -f "${__MAKE_CONF}" ] && cp ${__MAKE_CONF} ${TMPDST}${etcdir}
[ -f "${SRCCONF}" ] && cp ${SRCCONF} ${TMPDST}${etcdir}
${MOUNT_NULL_CMD} ${MAKEOBJDIRPREFIX} ${TMPDST}${MAKEOBJDIRPREFIX}
mount -t devfs devfs ${TMPDST}/dev
#
DT_START=$( date +%s )
if [ $notify -eq 1 ]; then
[ -z "$TAILSTRING" ] && TAILSTRING=50
script ${BLDLOG} /usr/bin/nice -n ${NICE} /usr/sbin/chroot ${TMPDST} /usr/bin/make $NUMJOBS -C /usr/src buildkernel KERNCONF=${name}.CBSD ${NOCLEANUP} TARGET=${arch} TARGET_ARCH="${target_arch}"
res=$?
else
/usr/sbin/chroot ${TMPDST} /usr/bin/nice -n ${NICE} /usr/bin/make $NUMJOBS -C /usr/src buildkernel KERNCONF=${name}.CBSD ${NOCLEANUP} TARGET=${arch} TARGET_ARCH="${target_arch}"
res=$?
fi
DT_END=$( date +%s )
init_scm_and_version
if [ $res -ne 0 ]; then
[ $notify -eq 1 ] && send_notification -s "[CBSD ${nodename}] buildkernel ${name} $basename $ver $arch ${target_arch} r${svnrev} failed." -b "`tail -n${TAILSTRING} ${BLDLOG}`"
exit 1
fi
if [ $res -eq 0 -a $notify -eq 1 ]; then
cat > ${BLDLOG} << EOF
Start time: `date -r ${DT_START}`
End time: `date -r ${DT_END}`
EOF
send_notification -s "[CBSD ${nodename}] buildkernel ${name} $basename $ver $arch ${target_arch} r${svnrev} complete." -f ${BLDLOG}
return 0
fi
|
C#
|
UTF-8
| 974 | 3.84375 | 4 |
[] |
no_license
|
//8. Write a program that extracts from a given text all sentences containing given word.
// Example: The word is "in".
using System;
class ExtractSentencesByWord
{
static void Main()
{
string text = "We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight."+
" So we are drinking all the day. We will move out of it in 5 days. In August I am having holidays";
string[] sentences = text.Split('.');
string key = "in".ToLower();
for (int i = 0; i < sentences.Length; i++)
{
string temporary = sentences[i].ToLower();
string[] words = temporary.Split(' ', ',', ';', '-', ':');
for (int j = 0; j < words.Length; j++)
{
if (words[j] ==key)
{
Console.WriteLine(sentences[i].Trim() + ".");
break;
}
}
}
}
}
|
Markdown
|
UTF-8
| 1,462 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "[新闻]Win 7 重新变成头号桌面系统"
excerpt: "Win 10 算个毛!Win 7 是王道!"
categories: [新闻]
comments: true
---
# [新闻]Win 7 重新变成头号桌面系统 微软迫不得已把重心偏向 Win 7
<i class="icon-pencil"></i> 通讯员:SYY
---
大家猴久不见~
可忧君又来了(话说这还是第一次好吗~)
我先来问大家一个问题~
你用什么系统?
我猜大部分奥友都是 Windows 7 吧
原因很简单——稳定!
而近日,微软迫不得已把重心偏向 Win 7
Why?
GOGOGO!
---
> 在调查中显示,即使微软出了Win 10 和 Win 8 ,但是大部分用户仍会选择Win 7!

> 根据最新公布的数据,Windows7系统的市场份额从41.69%(2月)上升至43.44%(4月),而与此同时Windows10系统的市场份额从34.62%下降至33.83%。整体上在过去的3月份Windows10市场份额下降了0.79%,而Windows7增长了1.75%。
> 这对于微软激进的 Win 10 升级推广来说可能是个坏消息,虽然Win 7 系统要在2020年1月停止支持,但是用户并没有太大的“压迫感”,因为这没有必要急着升级至最新系统。假设微软没有理由说服用户升级系统的话,到了2020年,很有可能会进入Windows XP 的时代。

|
C#
|
UTF-8
| 758 | 2.984375 | 3 |
[] |
no_license
|
using System;
namespace MIE.Dto
{
public class ReservationCount : IComparable<ReservationCount>
{
public int TimeId { get; set; }
public string StartTime { get; set; }
public string Date { get; set; }
public int Count { get; set; }
private DateTime dateTime;
public ReservationCount(DateTime dateTime, int count, int timeId)
{
this.dateTime = dateTime;
this.StartTime = dateTime.ToLongTimeString();
this.Date = dateTime.ToShortDateString();
this.Count = count;
this.TimeId = timeId;
}
public int CompareTo(ReservationCount rhs)
{
return dateTime.CompareTo(rhs.dateTime);
}
}
}
|
C++
|
UTF-8
| 2,335 | 2.78125 | 3 |
[] |
no_license
|
#include "shader.h"
int Shader::load() {
char vertShaderPath[strlen(resourcePath) + 5];
char fragShaderPath[strlen(resourcePath) + 5];
strcpy(vertShaderPath, resourcePath);
strcpy(fragShaderPath, resourcePath);
strcat(vertShaderPath, ".vert");
strcat(fragShaderPath, ".frag");
std::ifstream vertShaderFile(vertShaderPath), fragShaderFile(fragShaderPath);
std::string vertexString(
(std::istreambuf_iterator<char>(vertShaderFile)),
(std::istreambuf_iterator<char>())
);
std::string fragmentString(
(std::istreambuf_iterator<char>(fragShaderFile)),
(std::istreambuf_iterator<char>())
);
const char* vertexSource = vertexString.c_str();
const char* fragmentSource = fragmentString.c_str();
int success;
char infoLog[512];
GLuint vertex, fragment;
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vertexSource, NULL);
glCompileShader(vertex);
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if(!success) {
glGetShaderInfoLog(vertex, 512, NULL, infoLog);
LOG_ERROR("Vertex shader failed to compile: %s", infoLog);
} else {
LOG_DEBUG("Vertex shader successfully compiled");
}
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fragmentSource, NULL);
glCompileShader(fragment);
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if(!success) {
glGetShaderInfoLog(fragment, 512, NULL, infoLog);
LOG_ERROR("Fragment shader failed to compile: %s", infoLog);
} else {
LOG_DEBUG("Fragment shader successfully compiled");
}
program = glCreateProgram();
glAttachShader(program, vertex);
glAttachShader(program, fragment);
glBindFragDataLocation(program, 0, "outColor");
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &success);
if(!success) {
glGetShaderInfoLog(program, 512, NULL, infoLog);
LOG_ERROR("Shader program failed to link: %s", infoLog);
} else {
LOG_DEBUG("Shader program successfully linked");
}
glDetachShader(program, vertex);
glDetachShader(program, fragment);
glDeleteShader(vertex);
glDeleteShader(fragment);
LOG_DEBUG("Shader loaded: %s, %s", vertShaderPath, fragShaderPath);
return 0;
}
void Shader::unload() {
LOG_DEBUG("Shader unloaded: %s", resourcePath);
}
GLuint Shader::getUniformLocation(const char* uniform) {
return glGetUniformLocation(program, uniform);
}
|
C++
|
UTF-8
| 280 | 3.125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include <iostream>
#include "fibonacci.cpp"
int main()
{
auto max = 15;
auto number = 0;
while (number <= max)
{
std::cout << "fibonacci of " << number << ": " << fibonacci(number)
<< std::endl;
number++;
}
return 0;
}
|
Java
|
UTF-8
| 3,556 | 2.265625 | 2 |
[
"Apache-2.0",
"GPL-2.0-only"
] |
permissive
|
/*
* Copyright (C) 2012 Brendan Robert (BLuRry) brendan.robert@gmail.com.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package jace.tracker;
import jace.apple2e.MOS65C02;
import jace.core.Card;
import jace.core.Computer;
import jace.core.Motherboard;
import jace.hardware.CardExt80Col;
import jace.hardware.CardMockingboard;
import java.util.Optional;
/**
*
* @author Brendan Robert (BLuRry) brendan.robert@gmail.com
*/
public class PlaybackEngine extends Computer {
Computer dummyComputer = new Computer() {
@Override
public void coldStart() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void warmStart() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
protected void doPause() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
protected void doResume() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getName() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getShortName() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
};
Motherboard motherboard = new Motherboard(dummyComputer, null);
CardMockingboard mockingboard = new CardMockingboard(dummyComputer);
public PlaybackEngine() {
setMemory(new CardExt80Col(dummyComputer));
setCpu(new MOS65C02(dummyComputer));
getMemory().addCard(mockingboard, 5);
}
@Override
public void coldStart() {
for (Optional<Card> c : getMemory().getAllCards()) {
c.ifPresent(Card::reset);
}
}
@Override
public void warmStart() {
for (Optional<Card> c : getMemory().getAllCards()) {
c.ifPresent(Card::reset);
}
}
@Override
public boolean isRunning() {
return motherboard.isRunning();
}
@Override
protected void doPause() {
motherboard.suspend();
}
@Override
protected void doResume() {
motherboard.resume();
}
@Override
public String getName() {
return "Playback Computer";
}
@Override
public String getShortName() {
return "Computer";
}
@Override
public void reconfigure() {
// do nothing
}
}
|
Python
|
UTF-8
| 434 | 3.9375 | 4 |
[] |
no_license
|
# pizza_slices.py
# Calculates the maximum number of pizza slices to divide a pizza into,
# so that the minimum area per slice is maintained.
# Robert Morales (0849639)
# Fall 2012
# Oct 2, 2012
from math import pi
MIN_SLICE_AREA = 56
def main():
radius = float(input("Enter the radius of the pizza: "))
area = pi * radius**2
max_slices = int(area / MIN_SLICE_AREA)
print("Maximum number of slices:", max_slices)
main()
|
Markdown
|
UTF-8
| 3,419 | 2.828125 | 3 |
[] |
no_license
|
---
layout: post
title: "Develop and Evaluate Large Deep Learning Models with Keras on AWS"
date: 2016-11-13
categories: ['Setup & Environment']
---
Large deep learning models require a lot of compute time to run. You can run them on your CPU but it can take hours or days to get a result. If you have access to a GPU on your desktop, you can drastically speed up the training time of your deep learning models.
In this post, you will discover how you can get access to GPUs to speed up the training of your deep learning models by using the Amazon Web Service (AWS) infrastructure. For less than a dollar per hour and often a lot cheaper you can use this service from your workstation or laptop.
### OS - Ubuntu
I highly recommend sticking with latest version of Ubuntu Linux as OS for Neural Networks with Keras. I ran into lot of issues with Red Hat when pushing limits of MultiThreaded and Multiprocess programs.
### EC2 Instance Types
- **Compute Optimized:** Type: c3.8xlarge. vCPU: 32. Memory: 60GB
- **GPU Instances:** Type: g2.2xlarge. vCPU: 8. Memory: 15GB
As of this writing, Google Cloud Platform does not offer on-demand GPU instances. So Amazon is only reliable viable option. Unfortunately, on AWS not everybody has access by default to launch GPU instances. You may have to put in a request with AWS customer support to get access. If you don't have the access, AWS console will prompt you to fill in a form when you try to launch a GPU instance.
### Software Installation
1. Install Anaconda per instructions [here](https://docs.continuum.io/anaconda/install#linux-install)
2. Installation instructions for [Theano](http://deeplearning.net/software/theano/install_ubuntu.html#install-ubuntu)
3. Installation instructions for [TensorFlow](https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html#anaconda-installation)
### Configure Theano
Update your configuration of Theano (the Keras backend) to always use the GPU.
```
vi ~/.theanorc
```
Copy and paste the following configuration and save the file:
```
[global]
device = gpu
floatX = float32
optimizer_including = cudnn
allow_gc = False
[lib]
cnmem=.95
```
### Configure TensorFlow
TensorFlow will automatically switch to using GPU if it detects one provided all the appropriate NVIDIA cuda drivers are correctly installed. There is nothing to configure.
### Docker installation
For Tensorflow I highly recommend using Docker images. It will save a lot of time in setup. Since you are paying for instances per minute, I like not to waste time in setup. This benefit is more evident when using Tensorflow with GPU. Docker based installation instructions are [here](https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html#docker-installation).
### Running Jupyter remotely
By default the notebook server only listens on the localhost/127.0.0.1 network interface. If you want to connect to the notebook from another computers, or over the internet, you need to configure the notebook server to listen on all network interfaces and not open the browser. You will often also want to disable the automatic launching of the web browser.
```
jupyter notebook --ip=* --no-browser
```
### Docker cleanup
Delete all containers
```
docker rm $(docker ps -a -q)
```
Delete all images
```
docker rmi $(docker images -q)
```
Next: [Deep Learning on Apache Spark](/notes/2016/11/20/deep-learning-on-apache-spark)
|
Markdown
|
UTF-8
| 1,912 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
---
prev: false
next: false
---
# Contributing
Our website is powered by Vue and VuePress - which opens up a couple of different routes for contribution. One is contributing in the form of pure content; the other is contributing to the Vue components themselves. We'll outline those two processes below.
## Updating or adding new content
VuePress makes updating and adding new content reasonably straightforward. If you're looking to improve a page, each page has a built-in link that takes you right to the MD file editor on GitHub. If you want to create a new page that gets a bit more complex but we'll outline that process down below.
### Updating content
First, make sure you have a GitHub account. If you don't and would like to contribute, please reach out to Brian via email or slack.
- Visit a page on the website.
- Scroll all the way down the page, you should see a "Help Us Improve This Page" link. Click that.
- You may need to sign in to GitHub here.
- You should see GitHub's built-in file editor. We use Markdown for all of our pages - if you're unfamiliar with Markdown syntax check out [this handy guide](https://www.google.com/search?client=safari&rls=en&q=github+markdown&ie=UTF-8&oe=UTF-8)
- Make your edits. Have fun here! Add copy, emojis, etc. We'll review it.
- Scroll down to the "Commit changes" section - add a proper title and description, and then select "Create a new branch for this commit and start a pull request."
- Fire off your pull request, we'll review it and work with you if any updates need to be made.
- Thanks for contributing!
## Updating or adding Vue components
VuePress handles components just like a typical Vue installation - except it bundles them in a different place. To find our components, you'll need to visit `pdxdevs.org/docs/.vuepress/components/` - that's where you'll find them.
We suggest pulling this repo down and working on it locally.
|
Java
|
UTF-8
| 676 | 1.835938 | 2 |
[] |
no_license
|
package com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.math.analysis;
import com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.math.FunctionEvaluationException;
class ComposableFunction$31
extends ComposableFunction
{
ComposableFunction$31(ComposableFunction paramComposableFunction, UnivariateRealFunction paramUnivariateRealFunction) {}
public double value(double x)
throws FunctionEvaluationException
{
return this$0.value(x) + val$f.value(x);
}
}
/* Location:
* Qualified Name: com.amazon.ws.emr.hadoop.fs.shaded.org.apache.commons.math.analysis.ComposableFunction.31
* Java Class Version: 5 (49.0)
* JD-Core Version: 0.7.1
*/
|
Java
|
UHC
| 361 | 3.015625 | 3 |
[] |
no_license
|
package com.orange.datatype;
public class LongTest {
public static void main(String[] args) {
long bigNumber = 100000000000L; // 1õ
long bigNumber2 = 100000000000L;// ڿ 'L' ־ݴϴ. int ū̱ ڿ L δ
System.out.println(bigNumber);
System.out.println(bigNumber2);
}
}
|
Java
|
UTF-8
| 3,374 | 3.15625 | 3 |
[] |
no_license
|
package GenericLibrary;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
public class ExcelUtility {
/**
* Desc - This returns a handle of the Excelsheet
* @param fileName - Path and the file we need to excess (File)
* @param sheetName - Sheet name of the file (String)
* @return - XSSFSheet handle
* @throws Exception
*/
public static XSSFSheet GetSheetHandle(File fileName, String sheetName) throws Exception
{
try
{
FileInputStream mcExcelFileHndl = new FileInputStream(fileName);
@SuppressWarnings("resource")
XSSFWorkbook mcWorkbookHndl = new XSSFWorkbook(mcExcelFileHndl);
XSSFSheet mcSheet = mcWorkbookHndl.getSheet(sheetName);
return mcSheet;
}
catch(Exception e)
{
System.out.println("Exception caught in "+ e);
return null;
}
}
/**
* Desc - Returns the number of rows present in the excelsheet
* @param sheetHandle - Sheet handle of the excel file of which we need to find the count (XSSFSheet handle)
* @return - the count in Integer
*/
public static Integer getRowCount(XSSFSheet sheetHandle)
{
Integer rowCount = null;
rowCount = sheetHandle.getLastRowNum();
return rowCount;
}
public static Integer getStartingExcecutionRowOfMC(XSSFSheet sheetHandle) throws Exception
{
int rowNo = 0;
try
{
int mcRowCount,mcRowCounter;
int newRow = sheetHandle.getPhysicalNumberOfRows();
// System.out.println("physrical no of rows are"+ newRow);
mcRowCount = ExcelUtility.getRowCount(sheetHandle);
System.out.println("physrical no of rows are"+ mcRowCount);
Boolean bStartPosFound, bYPosFound = false;
// check the path file name and start looping it
for(mcRowCounter=1;mcRowCounter<mcRowCount+1;mcRowCounter++)
{
XSSFRow eachRow = null;
XSSFCell cellValueYPos, cellValueStartPos = null;
eachRow = sheetHandle.getRow(mcRowCounter);
cellValueYPos = eachRow.getCell(5);
cellValueStartPos = eachRow.getCell(6);
//System.out.println("cell value of Y at row no.-"+mcRowCounter+"value is-"+cellValueYPos.toString()+"- and the other start-"+cellValueStartPos.toString() );
if(cellValueYPos.toString().equalsIgnoreCase("Y") && cellValueStartPos.toString().equalsIgnoreCase("START"))
{
System.out.println("inside FIRST if");
bStartPosFound = true; // global variable
bYPosFound = true; // global variable
System.out.println("Yahoo here we start");
int rowToStart = mcRowCounter;
System.out.println("row to start the count is-"+rowToStart);
rowNo = rowToStart;
return rowToStart;
// here we start with the row
// put these variables in the global list of variables
}
else
{
// We can still be specific with error message by having 2 if conditions 1 for Y and other for START
System.out.println("start point not found");
}
}
}
catch(Exception e)
{
System.out.println("Exception Found in finding the file "+ e);
return null;
}
return rowNo;
}
}
|
Python
|
UTF-8
| 406 | 3.828125 | 4 |
[] |
no_license
|
def cipher(characters):
a = []
for character in characters:
if character.islower():
ascii = ord(character)
a.append(chr(219 - ascii))
else:
a.append(character)
return ''.join(a)
a = "Hoge Fuga PiYo"
encryption = cipher(a)
decryption = cipher(encryption)
print("original: ", a)
print("encryption: ", encryption)
print("decryption: ", decryption)
|
JavaScript
|
UTF-8
| 2,353 | 2.53125 | 3 |
[] |
no_license
|
import React, { useState, useRef } from "react";
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons"; // ES Module "as" syntax: ;
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
export function Login(props) {
const pInput = useRef();
const [pText, setPText] = useState("");
const [invalid, setInvalid] = useState("no-show");
const [toggled, setToggled] = useState(false);
const { setValidated } = props;
const handleToggle = () => {
setToggled(!toggled);
let pType = pInput.current.type;
if (pType === "text") {
pInput.current.type = "password";
} else {
console.log("password");
pInput.current.type = "text";
}
console.log(pType);
};
const handleSubmit = (e) => {
e.preventDefault();
if (pText === process.env.REACT_APP_PASSWORD) {
window.localStorage.setItem(process.env.REACT_APP_PASSWORD, true);
return setValidated(true);
}
setInvalid("invalid");
setTimeout(() => {
setInvalid("no-show");
setPText("");
}, 3000);
};
return (
<div className="container vh-100 w-100 d-flex justify-content-center align-items-center">
<form
onSubmit={(e) => handleSubmit(e)}
className="card rounded d-flex justify-content-evenly align-items-start p-3"
style={{ width: "50%", height: "200px" }}
noValidate
>
<div className="form-group w-100">
<label htmlFor="password">Password</label>
<div className="position-relative">
<input
type="password"
id="password"
ref={pInput}
className={`form-control form-control ${invalid}`}
required
aria-label="Password to enter site"
value={pText}
onChange={(e) => {
setPText(e.target.value);
}}
/>
<FontAwesomeIcon
icon={toggled ? faEyeSlash : faEye}
className="position-absolute"
onClick={() => {
handleToggle();
}}
/>
</div>
<div className={`${invalid}`}>Incorrect Password</div>
</div>
<button type="submit" className="btn btn-primary ">
Submit
</button>
</form>
</div>
);
}
|
Python
|
UTF-8
| 132 | 3.328125 | 3 |
[] |
no_license
|
a=input("Enter first no:")
b=input("Enter second no:")
sum=int(a)+int(b)
print("Sum is:",sum)
|
C++
|
UTF-8
| 332 | 3.171875 | 3 |
[
"CC-BY-3.0"
] |
permissive
|
int inPin = 7; // pushbutton connected to digital pin 7
int val = 0; // variable to store the read value
void setup() {
Serial.begin(9600);
pinMode(inPin, INPUT); // sets the digital pin 7 as input
}
void loop() {
val = digitalRead(inPin); // read the input pin
Serial.print(val);
Serial.print("\n");
}
|
Markdown
|
UTF-8
| 1,707 | 2.796875 | 3 |
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
---
title: Delete nodes for VMware Solutions (AVS) - Azure
description: Learn how to delete nodes from your VMWare with AVS deployment
author: sharaths-cs
ms.author: dikamath
ms.date: 08/05/2019
ms.topic: article
ms.service: azure-vmware-cloudsimple
ms.reviewer: cynthn
manager: dikamath
---
# Delete nodes from Azure VMware Solution by AVS
AVS nodes are metered once they are created. Nodes must be deleted to stop metering of the nodes. You delete the nodes that are not used from Azure portal.
## Before you begin
A node can be deleted only under following conditions:
* An AVS Private Cloud created with the nodes is deleted. To delete an AVS Private Cloud, see [Delete an Azure VMware Solution by AVS Private Cloud](delete-private-cloud.md).
* The node has been removed from the AVS Private Cloud by shrinking the AVS Private Cloud. To shrink an AVS Private Cloud, see [Shrink Azure VMware Solution by AVS Private Cloud](shrink-private-cloud.md).
## Sign in to Azure
Sign in to the Azure portal at [https://portal.azure.com](https://portal.azure.com).
## Delete AVS node
1. Select **All services**.
2. Search for **AVS Nodes**.

3. Select **AVS Nodes**.
4. Select nodes that don't belong to an AVS Private Cloud to delete. **AVS PRIVATE CLOUD NAME** column shows the AVS Private Cloud name to which a node belongs to. If a node is not used by an AVS Private Cloud, the value will be empty.

> [!NOTE]
> Only nodes which are not a part of the AVS Private Cloud can be deleted.
## Next steps
* Learn about [AVS Private Cloud](cloudsimple-private-cloud.md)
|
Java
|
UTF-8
| 1,832 | 3.984375 | 4 |
[] |
no_license
|
package com.danleinbach.game.design.entities;
import java.awt.*;
import java.util.Observable;
/**
* Game Entity is an object representing the players and elements in a game.
* The object handels its own updateing and drawing. It also extends observable
* so it can notify its observers of any changes in its state.
*
* @param <E> - This is the return type of its update methods, sometimes an entity
* doesn't need to return anything, other times it does.
* @author Daniel
*/
public abstract class GameEntity<E> extends Observable {
/**
* This is the width of the area that the entity can be drawn in
*/
protected int drawWidth;
/**
* This is the height of the area that the entity can be drawn in
*/
protected int drawHeight;
/**
* Construct a new game entity with two parameters. This
* is so the entitiy knows its bounds.
*
* @param pWidth - Width of the game area
* @param pHeight - Height of the game area
*/
public GameEntity(int pWidth, int pHeight) {
super();
this.drawWidth = pWidth;
this.drawHeight = pHeight;
}
/**
* Standard update for the entity. This should be called to perform routine
* updates to the object.
*
* @return A value appropriate to the entity
*/
public abstract E update();
/**
* Draw the entity.<br/>
* With the given graphics object draw itself and add it to the
* rest of the elements.
*
* @param g - Graphics object that holds all objects to be drawn.
*/
public abstract void draw(Graphics2D g);
/**
* Update the entity at a given location. This can be interpreted many ways,
* so it is left up to the implementor.
*
* @param x - the x location on the game panel
* @param y - the y location on the game panel
* @return A value appropriate to the entity
*/
public abstract E update(int x, int y);
}
|
SQL
|
UTF-8
| 34,429 | 2.875 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 3.4.5
-- http://www.phpmyadmin.net
--
-- Servidor: localhost
-- Tiempo de generación: 14-12-2014 a las 18:44:44
-- Versión del servidor: 5.5.16
-- Versión de PHP: 5.3.8
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de datos: `horario`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem1`
--
CREATE TABLE IF NOT EXISTS `afectsem1` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(2) NOT NULL,
`L2` int(2) NOT NULL,
`L3` int(2) NOT NULL,
`L4` int(2) NOT NULL,
`L5` int(2) NOT NULL,
`L6` int(2) NOT NULL,
`M1` int(2) NOT NULL,
`M2` int(2) NOT NULL,
`M3` int(2) NOT NULL,
`M4` int(2) NOT NULL,
`M5` int(2) NOT NULL,
`M6` int(2) NOT NULL,
`MI1` int(2) NOT NULL,
`MI2` int(2) NOT NULL,
`MI3` int(2) NOT NULL,
`MI4` int(2) NOT NULL,
`MI5` int(2) NOT NULL,
`MI6` int(2) NOT NULL,
`J1` int(2) NOT NULL,
`J2` int(2) NOT NULL,
`J3` int(2) NOT NULL,
`J4` int(2) NOT NULL,
`J5` int(2) NOT NULL,
`J6` int(2) NOT NULL,
`V1` int(2) NOT NULL,
`V2` int(2) NOT NULL,
`V3` int(2) NOT NULL,
`V4` int(2) NOT NULL,
`V5` int(2) NOT NULL,
`V6` int(2) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem2`
--
CREATE TABLE IF NOT EXISTS `afectsem2` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem3`
--
CREATE TABLE IF NOT EXISTS `afectsem3` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem4`
--
CREATE TABLE IF NOT EXISTS `afectsem4` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem5`
--
CREATE TABLE IF NOT EXISTS `afectsem5` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem6`
--
CREATE TABLE IF NOT EXISTS `afectsem6` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem7`
--
CREATE TABLE IF NOT EXISTS `afectsem7` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem8`
--
CREATE TABLE IF NOT EXISTS `afectsem8` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem9`
--
CREATE TABLE IF NOT EXISTS `afectsem9` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem10`
--
CREATE TABLE IF NOT EXISTS `afectsem10` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem11`
--
CREATE TABLE IF NOT EXISTS `afectsem11` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem12`
--
CREATE TABLE IF NOT EXISTS `afectsem12` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem13`
--
CREATE TABLE IF NOT EXISTS `afectsem13` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem14`
--
CREATE TABLE IF NOT EXISTS `afectsem14` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem15`
--
CREATE TABLE IF NOT EXISTS `afectsem15` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem16`
--
CREATE TABLE IF NOT EXISTS `afectsem16` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `afectsem17`
--
CREATE TABLE IF NOT EXISTS `afectsem17` (
`nombreProf` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreProf`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `asignatura`
--
CREATE TABLE IF NOT EXISTS `asignatura` (
`nombre` varchar(20) NOT NULL,
`carrera` varchar(20) NOT NULL,
`ano` int(1) NOT NULL,
`abrev` varchar(5) NOT NULL,
`cantHC` int(3) NOT NULL,
`s11` varchar(2) DEFAULT NULL,
`s21` varchar(2) DEFAULT NULL,
`s31` varchar(2) DEFAULT NULL,
`s41` varchar(2) DEFAULT NULL,
`s51` varchar(2) DEFAULT NULL,
`s61` varchar(2) DEFAULT NULL,
`s71` varchar(2) DEFAULT NULL,
`s81` varchar(2) DEFAULT NULL,
`s91` varchar(2) DEFAULT NULL,
`s101` varchar(2) DEFAULT NULL,
`s111` varchar(2) DEFAULT NULL,
`s121` varchar(2) DEFAULT NULL,
`s131` varchar(2) DEFAULT NULL,
`s141` varchar(2) DEFAULT NULL,
`s151` varchar(2) DEFAULT NULL,
`s161` varchar(2) DEFAULT NULL,
`s171` varchar(2) DEFAULT NULL,
`s12` varchar(2) DEFAULT NULL,
`s22` varchar(2) DEFAULT NULL,
`s32` varchar(2) DEFAULT NULL,
`s42` varchar(2) DEFAULT NULL,
`s52` varchar(2) DEFAULT NULL,
`s62` varchar(2) DEFAULT NULL,
`s72` varchar(2) DEFAULT NULL,
`s82` varchar(2) DEFAULT NULL,
`s92` varchar(2) DEFAULT NULL,
`s102` varchar(2) DEFAULT NULL,
`s112` varchar(2) DEFAULT NULL,
`s122` varchar(2) DEFAULT NULL,
`s132` varchar(2) DEFAULT NULL,
`s142` varchar(2) DEFAULT NULL,
`s152` varchar(2) DEFAULT NULL,
`s162` varchar(2) DEFAULT NULL,
`s172` varchar(2) DEFAULT NULL,
`s13` varchar(2) DEFAULT NULL,
`s23` varchar(2) DEFAULT NULL,
`s33` varchar(2) DEFAULT NULL,
`s43` varchar(2) DEFAULT NULL,
`s53` varchar(2) DEFAULT NULL,
`s63` varchar(2) DEFAULT NULL,
`s73` varchar(2) DEFAULT NULL,
`s83` varchar(2) DEFAULT NULL,
`s93` varchar(2) DEFAULT NULL,
`s103` varchar(2) DEFAULT NULL,
`s113` varchar(2) DEFAULT NULL,
`s123` varchar(2) DEFAULT NULL,
`s133` varchar(2) DEFAULT NULL,
`s143` varchar(2) DEFAULT NULL,
`s153` varchar(2) DEFAULT NULL,
`s163` varchar(2) DEFAULT NULL,
`s173` varchar(2) DEFAULT NULL,
`s14` varchar(2) DEFAULT NULL,
`s24` varchar(2) DEFAULT NULL,
`s34` varchar(2) DEFAULT NULL,
`s44` varchar(2) DEFAULT NULL,
`s54` varchar(2) DEFAULT NULL,
`s64` varchar(2) DEFAULT NULL,
`s74` varchar(2) DEFAULT NULL,
`s84` varchar(2) DEFAULT NULL,
`s94` varchar(2) DEFAULT NULL,
`s104` varchar(2) DEFAULT NULL,
`s114` varchar(2) DEFAULT NULL,
`s124` varchar(2) DEFAULT NULL,
`s134` varchar(2) DEFAULT NULL,
`s144` varchar(2) DEFAULT NULL,
`s154` varchar(2) DEFAULT NULL,
`s164` varchar(2) DEFAULT NULL,
`s174` varchar(2) DEFAULT NULL,
PRIMARY KEY (`nombre`,`carrera`,`ano`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem1`
--
CREATE TABLE IF NOT EXISTS `labsem1` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem2`
--
CREATE TABLE IF NOT EXISTS `labsem2` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem3`
--
CREATE TABLE IF NOT EXISTS `labsem3` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem4`
--
CREATE TABLE IF NOT EXISTS `labsem4` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`L5` int(11) NOT NULL,
`L6` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`M4` int(11) NOT NULL,
`M5` int(11) NOT NULL,
`M6` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`MI4` int(11) NOT NULL,
`MI5` int(11) NOT NULL,
`MI6` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`J4` int(11) NOT NULL,
`J5` int(11) NOT NULL,
`J6` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
`V4` int(11) NOT NULL,
`V5` int(11) NOT NULL,
`V6` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem5`
--
CREATE TABLE IF NOT EXISTS `labsem5` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem6`
--
CREATE TABLE IF NOT EXISTS `labsem6` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem7`
--
CREATE TABLE IF NOT EXISTS `labsem7` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem8`
--
CREATE TABLE IF NOT EXISTS `labsem8` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem9`
--
CREATE TABLE IF NOT EXISTS `labsem9` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem10`
--
CREATE TABLE IF NOT EXISTS `labsem10` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem11`
--
CREATE TABLE IF NOT EXISTS `labsem11` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem12`
--
CREATE TABLE IF NOT EXISTS `labsem12` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem13`
--
CREATE TABLE IF NOT EXISTS `labsem13` (
`nombreAsignatura` int(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L4` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem14`
--
CREATE TABLE IF NOT EXISTS `labsem14` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem15`
--
CREATE TABLE IF NOT EXISTS `labsem15` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem16`
--
CREATE TABLE IF NOT EXISTS `labsem16` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `labsem17`
--
CREATE TABLE IF NOT EXISTS `labsem17` (
`nombreAsignatura` varchar(50) NOT NULL,
`L1` int(11) NOT NULL,
`L2` int(11) NOT NULL,
`L3` int(11) NOT NULL,
`M1` int(11) NOT NULL,
`M2` int(11) NOT NULL,
`M3` int(11) NOT NULL,
`MI1` int(11) NOT NULL,
`MI2` int(11) NOT NULL,
`MI3` int(11) NOT NULL,
`J1` int(11) NOT NULL,
`J2` int(11) NOT NULL,
`J3` int(11) NOT NULL,
`V1` int(11) NOT NULL,
`V2` int(11) NOT NULL,
`V3` int(11) NOT NULL,
PRIMARY KEY (`nombreAsignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `profesor`
--
CREATE TABLE IF NOT EXISTS `profesor` (
`Nombre` varchar(20) NOT NULL,
`Apellidos` varchar(50) NOT NULL,
`Asignatura` varchar(20) NOT NULL,
`imparteC` varchar(4) NOT NULL,
`imparteCp` varchar(4) NOT NULL,
`CatDocente` varchar(20) NOT NULL,
`Correo` varchar(30) NOT NULL,
`Telefono` int(14) DEFAULT NULL,
`Departamento` varchar(20) NOT NULL,
PRIMARY KEY (`Nombre`,`Apellidos`,`Asignatura`),
KEY `Asignatura` (`Asignatura`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `usuario`
--
CREATE TABLE IF NOT EXISTS `usuario` (
`user` varchar(20) NOT NULL,
`password` varchar(20) CHARACTER SET ascii NOT NULL,
`type` binary(1) NOT NULL,
PRIMARY KEY (`user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `usuario`
--
INSERT INTO `usuario` (`user`, `password`, `type`) VALUES
('lmcastillo', 'ok', '0'),
('nparada', 'yo', '0');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
PHP
|
UTF-8
| 1,922 | 2.65625 | 3 |
[] |
no_license
|
<?php
//Connect to mysql
$connection = new mysqli('localhost', 'root', '');
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS change_org";
if ($connection->query($sql) === TRUE) {
} else {
echo "Error creating database: " . $connection->error;
}
// Connect to database
$connection = new mysqli('localhost', 'root', '', 'change_org');
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS users (
uid int NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password TEXT NOT NULL,
first_name VARCHAR(50) NOT NULL ,
last_name VARCHAR(50) NOT NULL
)";
if ($connection->query($sql) === TRUE) {
} else {
echo "Error creating table: " . $connection->error;
}
// sql to create tables
$sql = "CREATE TABLE IF NOT EXISTS posts (
pid int NOT NULL AUTO_INCREMENT PRIMARY KEY,
uid VARCHAR(100),
title TEXT,
goal FLOAT,
problem LONGTEXT,
img TEXT,
base VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
recipient TEXT,
deleted boolean DEFAULT false
)";
if ($connection->query($sql) === TRUE) {
} else {
echo "Error creating table: " . $connection->error;
}
$sql = "CREATE TABLE IF NOT EXISTS donation (
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
pid VARCHAR(100),
amount FLOAT,
name VARCHAR(100),
billing TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";
if ($connection->query($sql) === TRUE) {
} else {
echo "Error creating table: " . $connection->error;
}
$pw = password_hash('admin', PASSWORD_DEFAULT);
$sql="INSERT IGNORE INTO users (username, password, first_name, last_name)
VALUES ('admin','$pw', 'Anonymous', 'Admin')";
if ($connection->query($sql) === TRUE) {
} else {
echo "Error creating table: " . $connection->error;
}
|
C
|
UTF-8
| 4,252 | 3.46875 | 3 |
[
"Unlicense"
] |
permissive
|
#include "buffer.h"
#include <string.h>
#include <assert.h>
#include <talloc.h>
struct buffer {
bool fast_prepend;
size_t item_size;
size_t alloc_len;
char *front_addr;
char *back_addr;
void *ptr;
};
struct buffer *buffer_new(size_t item_size,
size_t init_capacity,
bool fast_prepend) {
struct buffer *buffer = NULL;
assert(item_size > 0);
assert(init_capacity > 0);
if ((buffer = malloc(sizeof(struct buffer))) == NULL) {
return NULL;
}
if (buffer_init(buffer, item_size, init_capacity, fast_prepend) == NULL) {
free(buffer);
return NULL;
}
return buffer;
}
struct buffer *buffer_init(struct buffer *buffer,
size_t item_size,
size_t init_capacity,
bool fast_prepend) {
assert(item_size > 0);
assert(init_capacity > 0);
if ((buffer->ptr = malloc(item_size * init_capacity)) == NULL) {
return NULL;
}
buffer->fast_prepend = fast_prepend;
buffer->item_size = item_size;
buffer->alloc_len = init_capacity;
if (fast_prepend) {
buffer->front_addr = buffer->back_addr =
(char *) buffer->ptr + (init_capacity / 2) * item_size;
} else {
buffer->front_index = buffer->back_index = 0;
}
return buffer;
}
void buffer_free(struct buffer *buffer, DtorFunc *destructor) {
char *ptr = buffer_get(buffer, 0);
for (size_t i = 0; i < (const size_t) buffer_length(buffer); i++) {
if (destructor) {
destructor(ptr);
}
ptr += buffer->element_size;
}
free(buffer->ptr);
free(buffer);
}
void *buffer_get(struct buffer *buffer, size_t index) {
if (index >= buffer_length(buffer)) {
return NULL;
} else {
return (char *) buffer->ptr +
((buffer->front_index + index) * buffer->element_size);
}
}
void buffer_set(struct buffer *buffer, size_t index, void *element) {
memcpy(buffer_get(buffer, index), element, buffer->element_size);
}
void buffer_insert(struct buffer *buffer, size_t index, void *element);
bool buffer_remove(struct buffer *buffer, size_t index, DtorFunc *destructor) {
void *addr = NULL, *next_addr = NULL;
size_t real_index = buffer->front_index + index;
assert(real_index <= buffer->back_index);
if ((addr = buffer_get(buffer, index)) == NULL) {
return false;
}
if (destructor) {
destructor(addr);
}
if ((next_addr = buffer_get(buffer, index + 1)) == NULL) {
return false;
}
if (real_index == 0) {
buffer->front_index++;
} else if (real_index == buffer->back_index) {
buffer->back_index--;
} else {
memmove(addr, next_addr, (char *) buffer->ptr +
(buffer->back_index * buffer->element_size) - (char *) next_addr);
buffer->back_index--;
}
return true;
}
size_t buffer_length(struct buffer *buffer) {
return (buffer->back_index - buffer->front_index) / buffer->element_size;
}
/* struct buffer *buffer_new(int initial_len, size_t element_size) { */
/* struct buffer *buf = NULL; */
/* */
/* assert(initial_len > 0); */
/* assert(element_size > 0); */
/* */
/* if ((buf = malloc(sizeof(struct buffer))) == NULL) { */
/* return NULL; */
/* } */
/* */
/* if ((buf->ptr = malloc(initial_len * element_size)) == NULL) { */
/* free(buf); */
/* return NULL; */
/* } */
/* */
/* buf->allocated_len = initial_len; */
/* buf->element_size = element_size; */
/* buf->len = 0; */
/* */
/* return buf; */
/* } */
/* */
/* struct buffer *buffer_append(struct buffer *buf, void *element) { */
/* void *new_ptr = NULL; */
/* char *buf_ptr = NULL; */
/* */
/* assert(buf != NULL); */
/* assert(buf->ptr != NULL); */
/* assert(element != NULL); */
/* */
/* if (buf->len == buf->allocated_len) { */
/* if ((new_ptr = realloc */
/* (buf->ptr, buf->allocated_len * buf->element_size * 2)) == NULL) { */
/* return NULL; */
/* } else { */
/* buf->ptr = new_ptr; */
/* buf->allocated_len *= 2; */
/* } */
/* } */
/* */
/* buf_ptr = buf->ptr; */
/* memcpy(buf_ptr + (buf->len * buf->element_size / sizeof(char)), */
/* element, buf->element_size); */
/* buf->len++; */
/* */
/* return buf; */
/* } */
|
C
|
UTF-8
| 811 | 3.65625 | 4 |
[] |
no_license
|
#include <stddef.h>
#include "memcpy.h"
/**
* Copy a memory area.
*
* <p>The memcpy function copies n bytes from memory area pointed to
* by src (source area) to memory area pointed to by dest (destination
* area). The memory areas may not overlap.
*
* @param dest destination area
* @param src source area
* @param n number of bytes to copy
* @returns a pointer to the destination area
*/
void *memcpy(void *dest, const void *src, size_t n)
{
if (n == 0)
return dest;
if (src == NULL || dest == NULL)
return NULL;
const char *s = src;
char *d = dest;
long i = 0;
// HERE
while (i < n) {
d[i] = s[i];
i++;
}
return dest;
}
/*
100/80 = 1.25
Program speedup by 1.25x.
1536/56 = 27.43
Internet access speedup by 27.43x.
*/
|
PHP
|
UTF-8
| 3,005 | 2.84375 | 3 |
[] |
no_license
|
<?php
/**
* 大转盘、刮刮乐等抽奖,抽中之后奖品从奖池删除,绝对概率,数量递减;
*/
//定义一个奖品数组,id为几等奖,prize为奖品名称,v为中奖概率,
//下面例子中sun(v)=100,所以平板电脑的中奖概率就是1%;
$prize_arr = array(
'0' => array('id'=>1,'prize'=>'平板电脑','v'=>1,'num'=>1),
'1' => array('id'=>2,'prize'=>'数码相机','v'=>5,'num'=>2),
'2' => array('id'=>3,'prize'=>'音箱设备','v'=>10,'num'=>5),
'3' => array('id'=>4,'prize'=>'4G优盘','v'=>12,'num'=>10),
'4' => array('id'=>5,'prize'=>'10Q币','v'=>22,'num'=>20),
'5' => array('id'=>6,'prize'=>'下次没准就能中哦','v'=>50),
);
//将奖品的数组放入redis中;
$redis = new Redis();
$redis->connect('192.168.1.202',6379);
$redis->auth('youderedis202');
$redis->lPush('prize',json_encode($prize_arr,true));
$arr = $redis->lRange('prize',0,-1);
/**
* 从$prize_arr中随机出来一条记录;
* 因为没中奖也在$prize_arr之中,所以函数每次总会返回一个结果的,要么中奖,要么就是id=>6
* @param $proArr :中奖概率的数组
* array(
1=>1,
2=>5,
3=>10,
4=>12,
5=>22,
6=>50
)
* @return int|string 中了几等奖
*/
function get_rand($prize_arr) {
//$proArr :中奖概率的数组
/*形如array(
1=>1,
2=>5,
3=>10,
4=>12,
5=>22,
6=>50
)*/
foreach ($prize_arr as $key => $val) {
$proArr[$val['id']] = $val['v'];
}
$result = '';
//概率数组的总概率精度
$proSum = array_sum($proArr);
//概率数组循环
//例:第一个循环是1=>1,若$randNum是10,大于1,$proSum减去1,继续循环。
foreach ($proArr as $key => $proCur) {
$randNum = mt_rand(1, $proSum);//在1~100随机一个数字
if ($randNum <= $proCur) {
$result = $key;
break;
} else {
$proSum -= $proCur;
}
}
unset ($proArr);
return $result;
}
/**
* 抽奖的函数,每次调用,中奖后奖池内的奖品就会从redis里删除;
* @param $prize_arr :奖品数组
* @return mixed
*/
function lotto()
{
$redis = new Redis();
$redis->connect('192.168.1.202',6379);
$redis->auth('youderedis202');
$prize_arr = $redis->lGet('prize',0);
$prize_arr = json_decode($prize_arr,true);
$rid = get_rand($prize_arr); //根据概率获取奖项id
if ($rid != 6) {
$prize_arr[$rid-1]['num']-=1;
if ($prize_arr[$rid-1]['num']==0) {
unset($prize_arr[$rid-1]);//将中奖项从数组中剔除,剩下未中奖项
$redis->lSet('prize',0,json_encode($prize_arr));
}
$redis->lSet('prize',0,json_encode($prize_arr));
$prize = $prize_arr[$rid-1]['prize'];
echo '恭喜您获得'.$prize;
}else{
echo '未中奖';
}
}
lotto();
|
Markdown
|
UTF-8
| 8,205 | 2.953125 | 3 |
[] |
no_license
|
---
title: Ionic Angular | FusionCharts
description: This article outlines the steps to create your chart in ionic framework with Angular.
heading: Ionic Angular
---
FusionCharts is a JavaScript charting library that allows you to create interactive charts, gauges, maps, and dashboards in JavaScript. Ionic is an open source framework used for developing mobile applications. It provides tools and services for building Mobile UI with a native look and feel. Ionic framework needs native wrapper to be able to run on mobile devices. We have built a simple and lightweight Angular component, which provides bindings for FusionCharts in Ionic Framework. The `angular-fusioncharts` component allows you to easily add rich and interactive charts to any Ionic Framework Project.
On this page, we'll see how to install FusionCharts and render a chart using the `angular-fusioncharts` component in Ionic Framework.
## Prerequisite
You need to have Ionic installed before proceeding any further. If not, you can follow the steps below.
Ionic requires both `Node.js` and `NPM` to be installed in your machine. You can check it by running the following commands in the terminal:
```shell
node -v
npm -v
```
To get Node.js (if not installed), you can go to the [official website](https://nodejs.org/en/) and get it. Enter the following command to install ionic.
```shell
$ npm install -g ionic
```
Now that Ionic is installed, let's set up an **Ionic** project. Follow the steps mentioned below:
```shell
$ ionic start myApp tabs --type angular
$ cd myApp
```
Start the development server by the entering the following command:
```shell
$ ionic serve
```
Now, open [http://localhost:8100](http://localhost:8100) to see your Ionic app.
## Installing and Including Dependencies
Install `angular-fusioncharts` and fusioncharts modules by the following command:
```shell
$ npm install fusioncharts angular-fusioncharts
```
After the installation, enter the following command to create an angular component to use fusioncharts. It will create a new folder named as `chart` inside `MyApp` directory.
```shell
$ ionic generate component chart
```
Create a new file called `**chart.module.ts` in the **chart** folder and add the consolidated code shown below to this file. Import all the required dependencies in `@NgModule` to get started.
```javascript
// chart.module.ts
import { NgModule } from "@angular/core";
// Import angular-fusioncharts
import { FusionChartsModule } from "angular-fusioncharts";
// Import FusionCharts library
import * as FusionCharts from "fusioncharts";
// Load FusionCharts Individual Charts
import * as Charts from "fusioncharts/fusioncharts.charts";
import * as FusionTheme from "fusioncharts/themes/fusioncharts.theme.fusion";
import { ChartComponent } from "./chart.component";
FusionChartsModule.fcRoot(FusionCharts, Charts, FusionTheme);
@NgModule({
declarations: [ChartComponent],
imports: [
FusionChartsModule // Include in imports
],
exports: [ChartComponent]
})
export class ChartModule {}
```
Open the `tab1.module.ts` file present inside the **tab1** folder and add the following code to it. The tab module will now import `**ChartModule**`.
```javascript
// tab1.module.ts
import { IonicModule } from "@ionic/angular";
import { RouterModule } from "@angular/router";
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { Tab1Page } from "./tab1.page";
import { ChartModule } from "../chart/chart.module";
@NgModule({
imports: [
IonicModule,
CommonModule,
FormsModule,
ChartModule,
RouterModule.forChild([{ path: "", component: Tab1Page }])
],
declarations: [Tab1Page]
})
export class Tab1PageModule {}
```
## Preparing the Data
Let's create a chart showing the "Countries With Most Oil Reserves". The data of the oil reserves present in various countries is shown in tabular form below.
| Country | No. of Oil Reserves |
| --------- | ------------------- |
| Venezuela | 290K |
| Saudi | 260K |
| Canada | 180K |
| Iran | 140K |
| Russia | 115K |
| UAE | 100K |
| US | 30K |
| China | 30K |
Since we are plotting a single dataset, let us create a column 2D chart with `countries` as data labels along X-axis and `No. of oil reserves` as data values along Y-axis. Let us prepare the data for a single-series chart.
FusionCharts accepts the data in **JSON** format. So the above data in the tabular form will take the structure given below:
```javascript
const chartData = [
{ label: "Venezuela", value: "290" },
{ label: "Saudi", value: "260" },
{ label: "Canada", value: "180" },
{ label: "Iran", value: "140" },
{ label: "Russia", value: "115" },
{ label: "UAE", value: "100" },
{ label: "US", value: "30" },
{ label: "China", value: "30" }
];
```
## Configure Your Chart
Now that the data is ready, let's work on the styling, positioning and giving your chart a context. Now, we add the chart attributes in the `chart.component.ts` file.
```javascript
const chartConfigs = {
caption: "Countries With Most Oil Reserves [2017-18]", //caption of the chart
subCaption: "In MMbbl = One Million barrels", //sub-caption of the chart
xAxisName: "Country", //x-axis name of the chart
yAxisName: "Reserves (MMbbl)", //y-axis name of the chart
numberSuffix: "K",
theme: "fusion" //applying a theme for the chart
};
```
Define the height, width, type attributes of the chart using the `fusioncharts` component in `chart.component.html` file. Refer to the code given below.
```html
<p>
chart works!
</p>
<fusioncharts
width="600"
height="350"
type="Column2D"
dataFormat="JSON"
[dataSource]="dataSource"
></fusioncharts>
```
The `type` attribute in the `chartConfigs` object signifies the type of chart being rendered. Have a look at different chart types with their aliases [here](/dev/chart-guide/list-of-charts).
## Render Your Chart
Now, get ready to render your first chart by following the steps below:
The `chartData` and the `chartConfigs` objects created above will now go into the `chart.component.ts` file. Its consolidated code is shown below:
```javascript
// chart.component.ts
import { Component, OnInit } from "@angular/core";
@Component({
selector: "chart-container",
templateUrl: "chart.component.html",
styleUrls: ["chart.component.scss"]
})
export class ChartComponent implements OnInit {
dataSource: object;
constructor() {
const chartData = [
{ label: "Venezuela", value: "290" },
{ label: "Saudi", value: "260" },
{ label: "Canada", value: "180" },
{ label: "Iran", value: "140" },
{ label: "Russia", value: "115" },
{ label: "UAE", value: "100" },
{ label: "US", value: "30" },
{ label: "China", value: "30" }
];
const chartConfigs = {
caption: "Countries With Most Oil Reserves [2017-18]",
subCaption: "In MMbbl = One Million barrels",
xAxisName: "Country",
yAxisName: "Reserves (MMbbl)",
numberSuffix: "K",
theme: "fusion"
};
this.dataSource = {
chart: chartConfigs,
data: chartData
};
}
ngOnInit() {}
}
```
Define the chart-container component in the tab1.page.html file present in the tab1 folder. Refer to the code below:
```html
<ion-header>
<ion-toolbar>
<ion-title>
Tab One
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<chart-container></chart-container>
</ion-content>
```
## See Your Chart
With all the code in place and the development server running, open [http://localhost:8100](http://localhost:8100) and you'll be able to see the chart, as shown below.
{% embed_chart getting-started-your-first-chart.js %}
If you are getting a JavaScript error on your page, check your browser console for the exact error and fix it accordingly. If you're unable to solve it, click [here](mailto:support@fusioncharts.com) to get in touch with our support team.
That's it! Your first chart using `angular-fusioncharts` in Ionic Framework is ready
|
Shell
|
UTF-8
| 288 | 2.765625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
#!/bin/bash
COMMITMESSAGE=$(git log --pretty=%s | head -1 | grep -G "^\[maven-release-plugin\] prepare for next development iteration$")
if [ -z "$COMMITMESSAGE" ]; then
git checkout develop
mvn release:prepare -B -Dskiptests
mvn release:perform --settings deploy-settings.xml
fi
|
JavaScript
|
UTF-8
| 3,109 | 4.5 | 4 |
[] |
no_license
|
/* ARRAYS - en lista med ett eller flera värden */
// names = []
// var names = []
// let names = []
//const names = []
// const name = "Albin"
// name = "Åberg" //detta funkar inte att göra så här.
// const names = ["Albin"]
// names[0] = "Albin" // detta fungerar
// const person = { firstName: "Albin"}
// person.firstName = "Albin" //detta fungerar
// console.log(names)
// console.log(person.firstName)
// const names = ["Albin","Åberg","Björn","Anders"]
// console.log(names)
// console.log(names.length)
// console.log(names.indexOf("Albin"))
//const multiarray = ["text", 12, true]
//const people = [
// { firstName: "Albin", age: 19, status: true },
// { firstName: "Åberg", age: 70, status: false },
// { firstName: "Marcus", age: 17, status: true },
//]
//const numberarray = [1,2,3,4,5]
// console.log(objarray[1])
// console.log(multiarray[1])
// console.log(numberarray[1])
// people.forEach(function(value, index) {
// console.log(value.firstName, index)
// })
//let names = ['Albin','Manfred Olle','Hellman']
//.unshift() - lägg till i början av en array
// names.unshift('zoar)
//.shift() - ta bort första värdet i en array
// names.shift()
//.push() - lägg till i slutet av en array
// names.push('zoar')
//.pop() - ta bort sista värdet i en array
// names.pop()
//.sort() - sorterar arrayen i A-Z ordning
// names.sort()
// .reverse() - vänder på hela arrayn.
// names.reverse()
//nestlad array - .sort().reverse() etc.
// names.push('Zoar')
// names.sort().reverse()
//delete - tar bort ett värde från en specifik position
//delete names[1]
//splice() - tar bort/lägg till ett värde från en specifik position
// names.splice(2,0, "Marcus") //lägger till
// names.splice(1, 1) //tar bort
//indexOf() - hitta ett specifikt index att ett värde
// names.indexOf('Björn')
//console.log(names.indexOf('Björn'))
// exmpel på att ta bort A
// let index = names.indexOf('Björn')
// delete names[index]
//.length - hur många värden innehåller arrayen
//console.log(names.length)
// .forEach() - loopar igenom hela arrayen
//names.forEach(function(name, index) {
// console.log(index, name)
//})
// med arrow-functions (lambda functions/lambda expression)
//names.forEach(function(name,index) {
// console.log(index, name)
//})
//names.forEach(function(name) {
// console.log(name)
// })
//names.forEach(function (name) {
// console.log(name)})
// for loop - det gamla sättet att loopa igenom en array
//for (var i=0; i < names.length; i++) {
// console.log(names[i]);
//}
// .map
//let people = [
// { firstName: "Albin", lastName: "Hellman"},
// { firstName: "Marcus", lastName: "Hellman"},
// { firstName: "Björn", lastName: "Hellman"},
// { firstName: "Anna", lastName: "Allansson"},
//]
//let firstNames = people.map(function(person) {
// return person.firstName
//})
//console.log(firstnames)
//.filter
//let specificpeople = people.filter(function(person) {
// return person.lastName == "Hellman"
//})
//console.log(specificpeople)
//.reduce
|
C#
|
UTF-8
| 52,064 | 2.78125 | 3 |
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
namespace System.Drawing.ClassicGraphicsExamples3CS
{
/// <summary>
/// Summary description for Form1.
/// </summary>
class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.Size = new System.Drawing.Size(300, 300);
this.Text = "Form1";
}
#endregion
// Snippet for: M:System.Drawing.Graphics.FillRectangle(System.Drawing.Brush,System.Drawing.Rectangle)
// <snippet111>
private void FillRectangleRectangle(PaintEventArgs e)
{
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create rectangle.
Rectangle rect = new Rectangle(0, 0, 200, 200);
// Fill rectangle to screen.
e.Graphics.FillRectangle(blueBrush, rect);
}
// </snippet111>
// Snippet for: M:System.Drawing.Graphics.FillRectangle(System.Drawing.Brush,System.Drawing.RectangleF)
// <snippet112>
private void FillRectangleRectangleF(PaintEventArgs e)
{
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create rectangle.
RectangleF rect = new RectangleF(0.0F, 0.0F, 200.0F, 200.0F);
// Fill rectangle to screen.
e.Graphics.FillRectangle(blueBrush, rect);
}
// </snippet112>
// Snippet for: M:System.Drawing.Graphics.FillRectangle(System.Drawing.Brush,System.Int32,System.Int32,System.Int32,System.Int32)
// <snippet113>
private void FillRectangleInt(PaintEventArgs e)
{
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create location and size of rectangle.
int x = 0;
int y = 0;
int width = 200;
int height = 200;
// Fill rectangle to screen.
e.Graphics.FillRectangle(blueBrush, x, y, width, height);
}
// </snippet113>
// Snippet for: M:System.Drawing.Graphics.FillRectangle(System.Drawing.Brush,System.Single,System.Single,System.Single,System.Single)
// <snippet114>
private void FillRectangleFloat(PaintEventArgs e)
{
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create location and size of rectangle.
float x = 0.0F;
float y = 0.0F;
float width = 200.0F;
float height = 200.0F;
// Fill rectangle to screen.
e.Graphics.FillRectangle(blueBrush, x, y, width, height);
}
// </snippet114>
// Snippet for: M:System.Drawing.Graphics.FillRectangles(System.Drawing.Brush,System.Drawing.Rectangle[])
// <snippet115>
private void FillRectanglesRectangle(PaintEventArgs e)
{
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create array of rectangles.
Rectangle[] rects = { new Rectangle(0, 0, 100, 200), new Rectangle(100, 200, 250, 50), new Rectangle(300, 0, 50, 100) };
// Fill rectangles to screen.
e.Graphics.FillRectangles(blueBrush, rects);
}
// </snippet115>
// Snippet for: M:System.Drawing.Graphics.FillRectangles(System.Drawing.Brush,System.Drawing.RectangleF[])
// <snippet116>
private void FillRectanglesRectangleF(PaintEventArgs e)
{
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create array of rectangles.
RectangleF[] rects = { new RectangleF(0.0F, 0.0F, 100.0F, 200.0F), new RectangleF(100.0F, 200.0F, 250.0F, 50.0F), new RectangleF(300.0F, 0.0F, 50.0F, 100.0F) };
// Fill rectangles to screen.
e.Graphics.FillRectangles(blueBrush, rects);
}
// </snippet116>
// Snippet for: M:System.Drawing.Graphics.FillRegion(System.Drawing.Brush,System.Drawing.Region)
// <snippet117>
private void FillRegionRectangle(PaintEventArgs e)
{
// Create solid brush.
SolidBrush blueBrush = new SolidBrush(Color.Blue);
// Create rectangle for region.
Rectangle fillRect = new Rectangle(100, 100, 200, 200);
// Create region for fill.
Region fillRegion = new Region(fillRect);
// Fill region to screen.
e.Graphics.FillRegion(blueBrush, fillRegion);
}
// </snippet117>
// Snippet for: M:System.Drawing.Graphics.FromHdc(System.IntPtr)
// <snippet118>
private void FromHdcHdc(PaintEventArgs e)
{
// Get handle to device context.
IntPtr hdc = e.Graphics.GetHdc();
// Create new graphics object using handle to device context.
Graphics newGraphics = Graphics.FromHdc(hdc);
// Draw rectangle to screen.
newGraphics.DrawRectangle(new Pen(Color.Red, 3), 0, 0, 200, 100);
// Release handle to device context and dispose of the // Graphics object
e.Graphics.ReleaseHdc(hdc);
newGraphics.Dispose();
}
// </snippet118>
// Snippet for: M:System.Drawing.Graphics.FromHwnd(System.IntPtr)
// <snippet119>
private void FromHwndHwnd(PaintEventArgs e)
{
// Get handle to form.
IntPtr hwnd = this.Handle;
// Create new graphics object using handle to window.
Graphics newGraphics = Graphics.FromHwnd(hwnd);
// Draw rectangle to screen.
newGraphics.DrawRectangle(new Pen(Color.Red, 3), 0, 0, 200, 100);
// Dispose of new graphics.
newGraphics.Dispose();
}
// </snippet119>
// Snippet for: M:System.Drawing.Graphics.FromImage(System.Drawing.Image)
// <snippet120>
private void FromImageImage(PaintEventArgs e)
{
// Create image.
Image imageFile = Image.FromFile("SampImag.jpg");
// Create graphics object for alteration.
Graphics newGraphics = Graphics.FromImage(imageFile);
// Alter image.
newGraphics.FillRectangle(new SolidBrush(Color.Black), 100, 50, 100, 100);
// Draw image to screen.
e.Graphics.DrawImage(imageFile, new PointF(0.0F, 0.0F));
// Dispose of graphics object.
newGraphics.Dispose();
}
// </snippet120>
// Snippet for: M:System.Drawing.Graphics.GetHalftonePalette
// <snippet121>
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern IntPtr SelectPalette(
IntPtr hdc,
IntPtr htPalette,
bool bForceBackground);
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern int RealizePalette(IntPtr hdc);
private void GetHalftonePaletteVoid(PaintEventArgs e)
{
// Create and draw image.
Image imageFile = Image.FromFile("SampImag.jpg");
e.Graphics.DrawImage(imageFile, new Point(0, 0));
// Get handle to device context.
IntPtr hdc = e.Graphics.GetHdc();
// Get handle to halftone palette.
IntPtr htPalette = Graphics.GetHalftonePalette();
// Select and realize new palette.
SelectPalette(hdc, htPalette, true);
RealizePalette(hdc);
// Create new graphics object.
Graphics newGraphics = Graphics.FromHdc(hdc);
// Draw image with new palette.
newGraphics.DrawImage(imageFile, 300, 0);
// Release handle to device context.
e.Graphics.ReleaseHdc(hdc);
}
// </snippet121>
// Snippet for: M:System.Drawing.Graphics.GetHdc
// <snippet122>
public class GDI
{
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
internal static extern bool Rectangle(
IntPtr hdc,
int ulCornerX, int ulCornerY,
int lrCornerX, int lrCornerY);
}
private void GetHdcForGDI1(PaintEventArgs e)
{
// Create pen.
Pen redPen = new Pen(Color.Red, 1);
// Draw rectangle with GDI+.
e.Graphics.DrawRectangle(redPen, 10, 10, 100, 50);
// Get handle to device context.
IntPtr hdc = e.Graphics.GetHdc();
// Draw rectangle with GDI using default pen.
GDI.Rectangle(hdc, 10, 70, 110, 120);
// Release handle to device context.
e.Graphics.ReleaseHdc(hdc);
}
// </snippet122>
// Snippet for: M:System.Drawing.Graphics.GetNearestColor(System.Drawing.Color)
// <snippet123>
private void GetNearestColorColor(PaintEventArgs e)
{
// Create solid brush with arbitrary color.
Color arbColor = Color.FromArgb(255, 165, 63, 136);
SolidBrush arbBrush = new SolidBrush(arbColor);
// Fill ellipse on screen.
e.Graphics.FillEllipse(arbBrush, 0, 0, 200, 100);
// Get nearest color.
Color realColor = e.Graphics.GetNearestColor(arbColor);
SolidBrush realBrush = new SolidBrush(realColor);
// Fill ellipse on screen.
e.Graphics.FillEllipse(realBrush, 0, 100, 200, 100);
}
// </snippet123>
// Snippet for: M:System.Drawing.Graphics.IntersectClip(System.Drawing.Rectangle)
// <snippet124>
private void IntersectClipRectangle(PaintEventArgs e)
{
// Set clipping region.
Rectangle clipRect = new Rectangle(0, 0, 200, 200);
e.Graphics.SetClip(clipRect);
// Update clipping region to intersection of
// existing region with specified rectangle.
Rectangle intersectRect = new Rectangle(100, 100, 200, 200);
e.Graphics.IntersectClip(intersectRect);
// Fill rectangle to demonstrate effective clipping region.
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 500, 500);
// Reset clipping region to infinite.
e.Graphics.ResetClip();
// Draw clipRect and intersectRect to screen.
e.Graphics.DrawRectangle(new Pen(Color.Black), clipRect);
e.Graphics.DrawRectangle(new Pen(Color.Red), intersectRect);
}
// </snippet124>
// Snippet for: M:System.Drawing.Graphics.IntersectClip(System.Drawing.RectangleF)
// <snippet125>
private void IntersectClipRectangleF1(PaintEventArgs e)
{
// Set clipping region.
Rectangle clipRect = new Rectangle(0, 0, 200, 200);
e.Graphics.SetClip(clipRect);
// Update clipping region to intersection of
// existing region with specified rectangle.
RectangleF intersectRectF = new RectangleF(100.0F, 100.0F, 200.0F, 200.0F);
e.Graphics.IntersectClip(intersectRectF);
// Fill rectangle to demonstrate effective clipping region.
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 500, 500);
// Reset clipping region to infinite.
e.Graphics.ResetClip();
// Draw clipRect and intersectRect to screen.
e.Graphics.DrawRectangle(new Pen(Color.Black), clipRect);
e.Graphics.DrawRectangle(new Pen(Color.Red), Rectangle.Round(intersectRectF));
}
// </snippet125>
// Snippet for: M:System.Drawing.Graphics.IntersectClip(System.Drawing.Region)
// <snippet126>
private void IntersectClipRegion(PaintEventArgs e)
{
// Set clipping region.
Rectangle clipRect = new Rectangle(0, 0, 200, 200);
Region clipRegion = new Region(clipRect);
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Update clipping region to intersection of
// existing region with specified rectangle.
Rectangle intersectRect = new Rectangle(100, 100, 200, 200);
Region intersectRegion = new Region(intersectRect);
e.Graphics.IntersectClip(intersectRegion);
// Fill rectangle to demonstrate effective clipping region.
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 500, 500);
// Reset clipping region to infinite.
e.Graphics.ResetClip();
// Draw clipRect and intersectRect to screen.
e.Graphics.DrawRectangle(new Pen(Color.Black), clipRect);
e.Graphics.DrawRectangle(new Pen(Color.Red), intersectRect);
}
// </snippet126>
// Snippet for: M:System.Drawing.Graphics.IsVisible(System.Drawing.Point)
// <snippet127>
private void IsVisiblePoint(PaintEventArgs e)
{
// Set clip region.
Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Set up coordinates of points.
int x1 = 100;
int y1 = 100;
int x2 = 200;
int y2 = 200;
Point point1 = new Point(x1, y1);
Point point2 = new Point(x2, y2);
// If point is visible, fill ellipse that represents it.
if (e.Graphics.IsVisible(point1))
{
e.Graphics.FillEllipse(new SolidBrush(Color.Red), x1, y1, 10, 10);
}
if (e.Graphics.IsVisible(point2))
{
e.Graphics.FillEllipse(new SolidBrush(Color.Blue), x2, y2, 10, 10);
}
}
// </snippet127>
// Snippet for: M:System.Drawing.Graphics.IsVisible(System.Drawing.PointF)
// <snippet128>
private void IsVisiblePointF(PaintEventArgs e)
{
// Set clip region.
Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Set up coordinates of points.
float x1 = 100.0F;
float y1 = 100.0F;
float x2 = 200.0F;
float y2 = 200.0F;
PointF point1 = new PointF(x1, y1);
PointF point2 = new PointF(x2, y2);
// If point is visible, fill ellipse that represents it.
if (e.Graphics.IsVisible(point1))
{
e.Graphics.FillEllipse(new SolidBrush(Color.Red), x1, y1, 10.0F, 10.0F);
}
if (e.Graphics.IsVisible(point2))
{
e.Graphics.FillEllipse(new SolidBrush(Color.Blue), x2, y2, 10.0F, 10.0F);
}
}
// </snippet128>
// Snippet for: M:System.Drawing.Graphics.IsVisible(System.Drawing.Rectangle)
// <snippet129>
private void IsVisibleRectangle(PaintEventArgs e)
{
// Set clip region.
Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Set up coordinates of rectangles.
Rectangle rect1 = new Rectangle(100, 100, 20, 20);
Rectangle rect2 = new Rectangle(200, 200, 20, 20);
// If rectangle is visible, fill it.
if (e.Graphics.IsVisible(rect1))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red), rect1);
}
if (e.Graphics.IsVisible(rect2))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), rect2);
}
}
// </snippet129>
// Snippet for: M:System.Drawing.Graphics.IsVisible(System.Drawing.RectangleF)
// <snippet130>
private void IsVisibleRectangleF(PaintEventArgs e)
{
// Set clip region.
Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Set up coordinates of rectangles.
RectangleF rect1 = new RectangleF(100.0F, 100.0F, 20.0F, 20.0F);
RectangleF rect2 = new RectangleF(200.0F, 200.0F, 20.0F, 20.0F);
// If rectangle is visible, fill it.
if (e.Graphics.IsVisible(rect1))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red), rect1);
}
if (e.Graphics.IsVisible(rect2))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), rect2);
}
}
// </snippet130>
// Snippet for: M:System.Drawing.Graphics.IsVisible(System.Int32,System.Int32)
// <snippet131>
private void IsVisibleInt(PaintEventArgs e)
{
// Set clip region.
Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Set up coordinates of points.
int x1 = 100;
int y1 = 100;
int x2 = 200;
int y2 = 200;
// If point is visible, fill ellipse that represents it.
if (e.Graphics.IsVisible(x1, y1))
{
e.Graphics.FillEllipse(new SolidBrush(Color.Red), x1, y1, 10, 10);
}
if (e.Graphics.IsVisible(x2, y2))
{
e.Graphics.FillEllipse(new SolidBrush(Color.Blue), x2, y2, 10, 10);
}
}
// </snippet131>
// Snippet for: M:System.Drawing.Graphics.IsVisible(System.Int32,System.Int32,System.Int32,System.Int32)
// <snippet132>
private void IsVisible4Int(PaintEventArgs e)
{
// Set clip region.
Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Set up coordinates of rectangles.
int x1 = 100;
int y1 = 100;
int width1 = 20;
int height1 = 20;
int x2 = 200;
int y2 = 200;
int width2 = 20;
int height2 = 20;
// If rectangle is visible, fill it.
if (e.Graphics.IsVisible(x1, y1, width1, height1))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red), x1, y1, width1, height1);
}
if (e.Graphics.IsVisible(x2, y2, width2, height2))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), x2, y2, width2, height2);
}
}
// </snippet132>
// Snippet for: M:System.Drawing.Graphics.IsVisible(System.Single,System.Single)
// <snippet133>
private void IsVisibleFloat(PaintEventArgs e)
{
// Set clip region.
Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Set up coordinates of points.
float x1 = 100.0F;
float y1 = 100.0F;
float x2 = 200.0F;
float y2 = 200.0F;
// If point is visible, fill ellipse that represents it.
if (e.Graphics.IsVisible(x1, y1))
{
e.Graphics.FillEllipse(new SolidBrush(Color.Red), x1, y1, 10.0F, 10.0F);
}
if (e.Graphics.IsVisible(x2, y2))
{
e.Graphics.FillEllipse(new SolidBrush(Color.Blue), x2, y2, 10.0F, 10.0F);
}
}
// </snippet133>
// Snippet for: M:System.Drawing.Graphics.IsVisible(System.Single,System.Single,System.Single,System.Single)
// <snippet134>
private void IsVisible4Float(PaintEventArgs e)
{
// Set clip region.
Region clipRegion = new Region(new Rectangle(50, 50, 100, 100));
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Set up coordinates of rectangles.
float x1 = 100.0F;
float y1 = 100.0F;
float width1 = 20.0F;
float height1 = 20.0F;
float x2 = 200.0F;
float y2 = 200.0F;
float width2 = 20.0F;
float height2 = 20.0F;
// If rectangle is visible, fill it.
if (e.Graphics.IsVisible(x1, y1, width1, height1))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red), x1, y1, width1, height1);
}
if (e.Graphics.IsVisible(x2, y2, width2, height2))
{
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), x2, y2, width2, height2);
}
}
// </snippet134>
// Snippet for: M:System.Drawing.Graphics.MeasureCharacterRanges(System.String,System.Drawing.Font,System.Drawing.RectangleF,System.Drawing.StringFormat)
// <snippet135>
private void MeasureCharacterRangesRegions(PaintEventArgs e)
{
// Set up string.
string measureString = "First and Second ranges";
Font stringFont = new Font("Times New Roman", 16.0F);
// Set character ranges to "First" and "Second".
CharacterRange[] characterRanges = { new CharacterRange(0, 5), new CharacterRange(10, 6) };
// Create rectangle for layout.
float x = 50.0F;
float y = 50.0F;
float width = 35.0F;
float height = 200.0F;
RectangleF layoutRect = new RectangleF(x, y, width, height);
// Set string format.
StringFormat stringFormat = new StringFormat();
stringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
stringFormat.SetMeasurableCharacterRanges(characterRanges);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, x, y, stringFormat);
// Measure two ranges in string.
Region[] stringRegions = e.Graphics.MeasureCharacterRanges(measureString,
stringFont, layoutRect, stringFormat);
// Draw rectangle for first measured range.
RectangleF measureRect1 = stringRegions[0].GetBounds(e.Graphics);
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), Rectangle.Round(measureRect1));
// Draw rectangle for second measured range.
RectangleF measureRect2 = stringRegions[1].GetBounds(e.Graphics);
e.Graphics.DrawRectangle(new Pen(Color.Blue, 1), Rectangle.Round(measureRect2));
}
// </snippet135>
// Snippet for: M:System.Drawing.Graphics.MeasureString(System.String,System.Drawing.Font)
// <snippet136>
private void MeasureStringMin(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
// </snippet136>
// Snippet for: M:System.Drawing.Graphics.MeasureString(System.String,System.Drawing.Font,System.Drawing.PointF,System.Drawing.StringFormat)
// <snippet137>
private void MeasureStringPointFFormat(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Set point for upper-left corner of string.
float x = 50.0F;
float y = 50.0F;
PointF ulCorner = new PointF(x, y);
// Set string format.
StringFormat newStringFormat = new StringFormat();
newStringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, ulCorner, newStringFormat);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), x, y, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, ulCorner, newStringFormat);
}
// </snippet137>
// Snippet for: M:System.Drawing.Graphics.MeasureString(System.String,System.Drawing.Font,System.Drawing.SizeF)
// <snippet138>
private void MeasureStringSizeF(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Set maximum layout size.
SizeF layoutSize = new SizeF(200.0F, 50.0F);
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, layoutSize);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
// </snippet138>
// Snippet for: M:System.Drawing.Graphics.MeasureString(System.String,System.Drawing.Font,System.Drawing.SizeF,System.Drawing.StringFormat)
// <snippet139>
private void MeasureStringSizeFFormat(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Set maximum layout size.
SizeF layoutSize = new SizeF(100.0F, 200.0F);
// Set string format.
StringFormat newStringFormat = new StringFormat();
newStringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, layoutSize, newStringFormat);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0), newStringFormat);
}
// </snippet139>
// Snippet for: M:System.Drawing.Graphics.MeasureString(System.String,System.Drawing.Font,System.Drawing.SizeF,System.Drawing.StringFormat,System.Int32@,System.Int32@)
// <snippet140>
private void MeasureStringSizeFFormatInts(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Set maximum layout size.
SizeF layoutSize = new SizeF(100.0F, 200.0F);
// Set string format.
StringFormat newStringFormat = new StringFormat();
newStringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
// Measure string.
int charactersFitted;
int linesFilled;
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, layoutSize, newStringFormat, out charactersFitted, out linesFilled);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0), newStringFormat);
// Draw output parameters to screen.
string outString = "chars " + charactersFitted + ", lines " + linesFilled;
e.Graphics.DrawString(outString, stringFont, Brushes.Black, new PointF(100, 0));
}
// </snippet140>
// Snippet for: M:System.Drawing.Graphics.MeasureString(System.String,System.Drawing.Font,System.Int32)
// <snippet141>
private void MeasureStringWidth(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Set maximum width of string.
int stringWidth = 200;
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, stringWidth);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));
}
// </snippet141>
// Snippet for: M:System.Drawing.Graphics.MeasureString(System.String,System.Drawing.Font,System.Int32,System.Drawing.StringFormat)
// <snippet142>
private void MeasureStringWidthFormat(PaintEventArgs e)
{
// Set up string.
string measureString = "Measure String";
Font stringFont = new Font("Arial", 16);
// Set maximum width of string.
int stringWidth = 100;
// Set string format.
StringFormat newStringFormat = new StringFormat();
newStringFormat.FormatFlags = StringFormatFlags.DirectionVertical;
// Measure string.
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(measureString, stringFont, stringWidth, newStringFormat);
// Draw rectangle representing size of string.
e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
// Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0), newStringFormat);
}
// </snippet142>
// Snippet for: M:System.Drawing.Graphics.MultiplyTransform(System.Drawing.Drawing2D.Matrix)
// <snippet143>
private void MultiplyTransformMatrix(PaintEventArgs e)
{
// Create transform matrix.
Matrix transformMatrix = new Matrix();
// Translate matrix, prepending translation vector.
transformMatrix.Translate(200.0F, 100.0F);
// Rotate transformation matrix of graphics object,
// prepending rotation matrix.
e.Graphics.RotateTransform(30.0F);
// Multiply (prepend to) transformation matrix of
// graphics object to translate graphics transformation.
e.Graphics.MultiplyTransform(transformMatrix);
// Draw rotated, translated ellipse.
e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), -80, -40, 160, 80);
}
// </snippet143>
// Snippet for: M:System.Drawing.Graphics.MultiplyTransform(System.Drawing.Drawing2D.Matrix,System.Drawing.Drawing2D.MatrixOrder)
// <snippet144>
private void MultiplyTransformMatrixOrder(PaintEventArgs e)
{
// Create transform matrix.
Matrix transformMatrix = new Matrix();
// Translate matrix, prepending translation vector.
transformMatrix.Translate(200.0F, 100.0F);
// Rotate transformation matrix of graphics object,
// prepending rotation matrix.
e.Graphics.RotateTransform(30.0F);
// Multiply (append to) transformation matrix of
// graphics object to translate graphics transformation.
e.Graphics.MultiplyTransform(transformMatrix, MatrixOrder.Append);
// Draw rotated, translated ellipse.
e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), -80, -40, 160, 80);
}
// </snippet144>
// Snippet for: M:System.Drawing.Graphics.ReleaseHdc(System.IntPtr)
// <snippet145>
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern bool Rectangle2(
IntPtr hdc,
int ulCornerX, int ulCornerY,
int lrCornerX, int lrCornerY);
private void GetHdcForGDI2(PaintEventArgs e)
{
// Create pen.
Pen redPen = new Pen(Color.Red, 1);
// Draw rectangle with GDI+.
e.Graphics.DrawRectangle(redPen, 10, 10, 100, 50);
// Get handle to device context.
IntPtr hdc = e.Graphics.GetHdc();
// Draw rectangle with GDI using default pen.
Rectangle2(hdc, 10, 70, 110, 120);
// Release handle to device context.
e.Graphics.ReleaseHdc(hdc);
}
// </snippet145>
// Snippet for: M:System.Drawing.Graphics.ResetClip
// <snippet146>
private void IntersectClipRectangleF2(PaintEventArgs e)
{
// Set clipping region.
Rectangle clipRect = new Rectangle(0, 0, 200, 200);
e.Graphics.SetClip(clipRect);
// Update clipping region to intersection of
// existing region with specified rectangle.
RectangleF intersectRectF = new RectangleF(100.0F, 100.0F, 200.0F, 200.0F);
e.Graphics.IntersectClip(intersectRectF);
// Fill rectangle to demonstrate effective clipping region.
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 500, 500);
// Reset clipping region to infinite.
e.Graphics.ResetClip();
// Draw clipRect and intersectRect to screen.
e.Graphics.DrawRectangle(new Pen(Color.Black), clipRect);
e.Graphics.DrawRectangle(new Pen(Color.Red), Rectangle.Round(intersectRectF));
}
// </snippet146>
// Snippet for: M:System.Drawing.Graphics.ResetTransform
// <snippet147>
private void SaveRestore1(PaintEventArgs e)
{
// Translate transformation matrix.
e.Graphics.TranslateTransform(100, 0);
// Save translated graphics state.
GraphicsState transState = e.Graphics.Save();
// Reset transformation matrix to identity and fill rectangle.
e.Graphics.ResetTransform();
e.Graphics.FillRectangle(new SolidBrush(Color.Red), 0, 0, 100, 100);
// Restore graphics state to translated state and fill second
// rectangle.
e.Graphics.Restore(transState);
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 100, 100);
}
// </snippet147>
// Snippet for: M:System.Drawing.Graphics.Restore(System.Drawing.Drawing2D.GraphicsState)
// <snippet148>
private void SaveRestore2(PaintEventArgs e)
{
// Translate transformation matrix.
e.Graphics.TranslateTransform(100, 0);
// Save translated graphics state.
GraphicsState transState = e.Graphics.Save();
// Reset transformation matrix to identity and fill rectangle.
e.Graphics.ResetTransform();
e.Graphics.FillRectangle(new SolidBrush(Color.Red), 0, 0, 100, 100);
// Restore graphics state to translated state and fill second
// rectangle.
e.Graphics.Restore(transState);
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 100, 100);
}
// </snippet148>
// Snippet for: M:System.Drawing.Graphics.RotateTransform(System.Single)
// <snippet149>
private void RotateTransformAngle(PaintEventArgs e)
{
// Set world transform of graphics object to translate.
e.Graphics.TranslateTransform(100.0F, 0.0F);
// Then to rotate, prepending rotation matrix.
e.Graphics.RotateTransform(30.0F);
// Draw rotated, translated ellipse to screen.
e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), 0, 0, 200, 80);
}
// </snippet149>
// Snippet for: M:System.Drawing.Graphics.RotateTransform(System.Single,System.Drawing.Drawing2D.MatrixOrder)
// <snippet150>
private void RotateTransformAngleMatrixOrder(PaintEventArgs e)
{
// Set world transform of graphics object to translate.
e.Graphics.TranslateTransform(100.0F, 0.0F);
// Then to rotate, appending rotation matrix.
e.Graphics.RotateTransform(30.0F, MatrixOrder.Append);
// Draw translated, rotated ellipse to screen.
e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), 0, 0, 200, 80);
}
// </snippet150>
// Snippet for: M:System.Drawing.Graphics.Save
// <snippet151>
private void SaveRestore3(PaintEventArgs e)
{
// Translate transformation matrix.
e.Graphics.TranslateTransform(100, 0);
// Save translated graphics state.
GraphicsState transState = e.Graphics.Save();
// Reset transformation matrix to identity and fill rectangle.
e.Graphics.ResetTransform();
e.Graphics.FillRectangle(new SolidBrush(Color.Red), 0, 0, 100, 100);
// Restore graphics state to translated state and fill second
// rectangle.
e.Graphics.Restore(transState);
e.Graphics.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 100, 100);
}
// </snippet151>
// Snippet for: M:System.Drawing.Graphics.ScaleTransform(System.Single,System.Single)
// <snippet152>
private void ScaleTransformFloat(PaintEventArgs e)
{
// Set world transform of graphics object to rotate.
e.Graphics.RotateTransform(30.0F);
// Then to scale, prepending to world transform.
e.Graphics.ScaleTransform(3.0F, 1.0F);
// Draw scaled, rotated rectangle to screen.
e.Graphics.DrawRectangle(new Pen(Color.Blue, 3), 50, 0, 100, 40);
}
// </snippet152>
// Snippet for: M:System.Drawing.Graphics.ScaleTransform(System.Single,System.Single,System.Drawing.Drawing2D.MatrixOrder)
// <snippet153>
private void ScaleTransformFloatMatrixOrder(PaintEventArgs e)
{
// Set world transform of graphics object to rotate.
e.Graphics.RotateTransform(30.0F);
// Then to scale, appending to world transform.
e.Graphics.ScaleTransform(3.0F, 1.0F, MatrixOrder.Append);
// Draw rotated, scaled rectangle to screen.
e.Graphics.DrawRectangle(new Pen(Color.Blue, 3), 50, 0, 100, 40);
}
// </snippet153>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.Drawing2D.GraphicsPath)
// <snippet154>
private void SetClipPath(PaintEventArgs e)
{
// Create graphics path.
GraphicsPath clipPath = new GraphicsPath();
clipPath.AddEllipse(0, 0, 200, 100);
// Set clipping region to path.
e.Graphics.SetClip(clipPath);
// Fill rectangle to demonstrate clipping region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet154>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.Drawing2D.GraphicsPath,System.Drawing.Drawing2D.CombineMode)
// <snippet155>
private void SetClipPathCombine(PaintEventArgs e)
{
// Create graphics path.
GraphicsPath clipPath = new GraphicsPath();
clipPath.AddEllipse(0, 0, 200, 100);
// Set clipping region to path.
e.Graphics.SetClip(clipPath, CombineMode.Replace);
// Fill rectangle to demonstrate clipping region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet155>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.Graphics)
// <snippet156>
private void SetClipGraphics(PaintEventArgs e)
{
// Create temporary graphics object and set its clipping region.
Graphics newGraphics = this.CreateGraphics();
newGraphics.SetClip(new Rectangle(0, 0, 100, 100));
// Update clipping region of graphics to clipping region of new
// graphics.
e.Graphics.SetClip(newGraphics);
// Fill rectangle to demonstrate clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
// Release new graphics.
newGraphics.Dispose();
}
// </snippet156>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.Graphics,System.Drawing.Drawing2D.CombineMode)
// <snippet157>
private void SetClipGraphicsCombine(PaintEventArgs e)
{
// Create temporary graphics object and set its clipping region.
Graphics newGraphics = this.CreateGraphics();
newGraphics.SetClip(new Rectangle(0, 0, 100, 100));
// Update clipping region of graphics to clipping region of new
// graphics.
e.Graphics.SetClip(newGraphics, CombineMode.Replace);
// Fill rectangle to demonstrate clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
// Release new graphics.
newGraphics.Dispose();
}
// </snippet157>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.Rectangle)
// <snippet158>
private void SetClipRectangle(PaintEventArgs e)
{
// Create rectangle for clipping region.
Rectangle clipRect = new Rectangle(0, 0, 100, 100);
// Set clipping region of graphics to rectangle.
e.Graphics.SetClip(clipRect);
// Fill rectangle to demonstrate clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet158>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.Rectangle,System.Drawing.Drawing2D.CombineMode)
// <snippet159>
private void SetClipRectangleCombine(PaintEventArgs e)
{
// Create rectangle for clipping region.
Rectangle clipRect = new Rectangle(0, 0, 100, 100);
// Set clipping region of graphics to rectangle.
e.Graphics.SetClip(clipRect, CombineMode.Replace);
// Fill rectangle to demonstrate clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet159>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.RectangleF)
// <snippet160>
private void SetClipRectangleF(PaintEventArgs e)
{
// Create rectangle for clipping region.
RectangleF clipRect = new RectangleF(0.0F, 0.0F, 100.0F, 100.0F);
// Set clipping region of graphics to rectangle.
e.Graphics.SetClip(clipRect);
// Fill rectangle to demonstrate clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet160>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.RectangleF,System.Drawing.Drawing2D.CombineMode)
// <snippet161>
private void SetClipRectangleFCombine(PaintEventArgs e)
{
// Create rectangle for clipping region.
RectangleF clipRect = new RectangleF(0.0F, 0.0F, 100.0F, 100.0F);
// Set clipping region of graphics to rectangle.
e.Graphics.SetClip(clipRect, CombineMode.Replace);
// Fill rectangle to demonstrate clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet161>
// Snippet for: M:System.Drawing.Graphics.SetClip(System.Drawing.Region,System.Drawing.Drawing2D.CombineMode)
// <snippet162>
private void SetClipRegionCombine(PaintEventArgs e)
{
// Create region for clipping.
Region clipRegion = new Region(new Rectangle(0, 0, 100, 100));
// Set clipping region of graphics to region.
e.Graphics.SetClip(clipRegion, CombineMode.Replace);
// Fill rectangle to demonstrate clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet162>
// Snippet for: M:System.Drawing.Graphics.TransformPoints(System.Drawing.Drawing2D.CoordinateSpace,System.Drawing.Drawing2D.CoordinateSpace,System.Drawing.Point[])
// <snippet163>
private void TransformPointsPoint(PaintEventArgs e)
{
// Create array of two points.
Point[] points = { new Point(0, 0), new Point(100, 50) };
// Draw line connecting two untransformed points.
e.Graphics.DrawLine(new Pen(Color.Blue, 3), points[0], points[1]);
// Set world transformation of Graphics object to translate.
e.Graphics.TranslateTransform(40, 30);
// Transform points in array from world to page coordinates.
e.Graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.World, points);
// Reset world transformation.
e.Graphics.ResetTransform();
// Draw line that connects transformed points.
e.Graphics.DrawLine(new Pen(Color.Red, 3), points[0], points[1]);
}
// </snippet163>
// Snippet for: M:System.Drawing.Graphics.TransformPoints(System.Drawing.Drawing2D.CoordinateSpace,System.Drawing.Drawing2D.CoordinateSpace,System.Drawing.PointF[])
// <snippet164>
private void TransformPointsPointF(PaintEventArgs e)
{
// Create array of two points.
PointF[] points = { new PointF(0.0F, 0.0F), new PointF(100.0F, 50.0F) };
// Draw line connecting two untransformed points.
e.Graphics.DrawLine(new Pen(Color.Blue, 3), points[0], points[1]);
// Set world transformation of Graphics object to translate.
e.Graphics.TranslateTransform(40.0F, 30.0F);
// Transform points in array from world to page coordinates.
e.Graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.World, points);
// Reset world transformation.
e.Graphics.ResetTransform();
// Draw line that connects transformed points.
e.Graphics.DrawLine(new Pen(Color.Red, 3), points[0], points[1]);
}
// </snippet164>
// Snippet for: M:System.Drawing.Graphics.TranslateClip(System.Int32,System.Int32)
// <snippet165>
private void TranslateClipInt(PaintEventArgs e)
{
// Create rectangle for clipping region.
Rectangle clipRect = new Rectangle(0, 0, 100, 100);
// Set clipping region of graphics to rectangle.
e.Graphics.SetClip(clipRect);
// Translate clipping region.
int dx = 50;
int dy = 50;
e.Graphics.TranslateClip(dx, dy);
// Fill rectangle to demonstrate translated clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet165>
// Snippet for: M:System.Drawing.Graphics.TranslateClip(System.Single,System.Single)
// <snippet166>
private void TranslateClipFloat(PaintEventArgs e)
{
// Create rectangle for clipping region.
RectangleF clipRect = new RectangleF(0.0F, 0.0F, 100.0F, 100.0F);
// Set clipping region of graphics to rectangle.
e.Graphics.SetClip(clipRect);
// Translate clipping region.
float dx = 50.0F;
float dy = 50.0F;
e.Graphics.TranslateClip(dx, dy);
// Fill rectangle to demonstrate translated clip region.
e.Graphics.FillRectangle(new SolidBrush(Color.Black), 0, 0, 500, 300);
}
// </snippet166>
// Snippet for: M:System.Drawing.Graphics.TranslateTransform(System.Single,System.Single)
// <snippet167>
private void TranslateTransformAngle(PaintEventArgs e)
{
// Set world transform of graphics object to rotate.
e.Graphics.RotateTransform(30.0F);
// Then to translate, prepending to world transform.
e.Graphics.TranslateTransform(100.0F, 0.0F);
// Draw translated, rotated ellipse to screen.
e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), 0, 0, 200, 80);
}
// </snippet167>
// Snippet for: M:System.Drawing.Graphics.TranslateTransform(System.Single,System.Single,System.Drawing.Drawing2D.MatrixOrder)
// <snippet168>
private void TranslateTransformAngleMatrixOrder(PaintEventArgs e)
{
// Set world transform of graphics object to rotate.
e.Graphics.RotateTransform(30.0F);
// Then to translate, appending to world transform.
e.Graphics.TranslateTransform(100.0F, 0.0F, MatrixOrder.Append);
// Draw rotated, translated ellipse to screen.
e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), 0, 0, 200, 80);
}
// </snippet168>
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
}
}
|
Python
|
UTF-8
| 8,107 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
# -*- mode: python; coding: utf-8 -*-
# Copyright 2012-2014 Peter Williams <peter@newton.cx> and collaborators.
# Licensed under the MIT License.
"""pwkit.contours - Tracing contours in functions and data.
Uses my own homebrew algorithm. So far, it's only tested on extremely
well-behaved functions, so probably doesn't cope well with poorly-behaved
ones.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__all__ = str ('analytic_2d').split ()
import numpy as np
from . import PKError
def analytic_2d (f, df, x0, y0,
maxiters=5000,
defeta=0.05,
netastep=12,
vtol1=1e-3,
vtol2=1e-8,
maxnewt=20,
dorder=7,
goright=False):
"""Sample a contour in a 2D analytic function. Arguments:
f
A function, mapping (x, y) -> z.
df
The partial derivative: df (x, y) -> [dz/dx, dz/dy]. If None,
the derivative of f is approximated numerically with
scipy.derivative.
x0
Initial x value. Should be of "typical" size for the problem;
avoid 0.
y0
Initial y value. Should be of "typical" size for the problem;
avoid 0.
Optional arguments:
maxiters
Maximum number of points to create. Default 5000.
defeta
Initially offset by distances of defeta*[df/dx, df/dy]
Default 0.05.
netastep
Number of steps between defeta and the machine resolution
in which we test eta values for goodness. (OMG FIXME doc).
Default 12.
vtol1
Tolerance for constancy in the value of the function in the
initial offset step. The value is only allowed to vary by
``f(x0,y0) * vtol1``. Default 1e-3.
vtol2
Tolerance for constancy in the value of the function in the
along the contour. The value is only allowed to vary by
``f(x0,y0) * vtol2``. Default 1e-8.
maxnewt
Maximum number of Newton's method steps to take when
attempting to hone in on the desired function value. Default 20.
dorder
Number of function evaluations to perform when evaluating
the derivative of f numerically. Must be an odd integer greater
than 1. Default 7.
goright
If True, trace the contour rightward (as looking uphill),
rather than leftward (the default).
"""
# Coerce argument types.
if not callable (f):
raise ValueError ('f')
if df is not None and not callable (df):
raise ValueError ('df')
x0 = float (x0)
if x0 == 0.:
raise ValueError ('x0')
y0 = float (y0)
if y0 == 0.:
raise ValueError ('y0')
maxiters = int (maxiters)
if maxiters < 3:
raise ValueError ('maxiters')
defeta = float (defeta)
if defeta <= 0:
raise ValueError ('defeta')
netastep = int (netastep)
if netastep < 2:
raise ValueError ('netastep')
vtol1 = float (vtol1)
if vtol1 <= 0:
raise ValueError ('vtol1')
vtol2 = float (vtol2)
if vtol2 >= vtol1:
raise ValueError ('vtol2')
maxnewt = int (maxnewt)
if maxnewt < 1:
raise ValueError ('maxnewt')
# What value are we contouring?
v = f (x0, y0)
# If no derivative is given, use a numerical approximation.
if df is None:
derivx = abs (x0 * 0.025)
derivy = abs (y0 * 0.025)
from scipy import derivative
if dorder == 2:
# simple derivative
def df (x1, y1):
z0 = f (x1, y1)
dx = max (abs (x1) * 1e-5, 1e-8)
dy = max (abs (y1) * 1e-5, 1e-8)
dzdx = (f (x1 + dx, y1) - z0) / dx
dzdy = (f (x1, y1 + dy) - z0) / dy
return [dzdx, dzdy]
else:
def df (x1, y1):
dx = derivative (lambda x: f (x, y1), x1, derivx, order=dorder)
dy = derivative (lambda y: f (x1, y), y1, derivy, order=dorder)
return [dx, dy]
# Init eta progression.
rez = np.finfo (np.double).resolution
if rez > defeta:
raise PKError ('defeta below resolution!')
eta_scale = np.exp ((np.log (rez) - np.log (defeta)) / netastep)
# Init data storage
n = 1
pts = np.empty ((maxiters, 2))
pts[0] = (x0, y0)
x = x0
y = y0
# Quitflag: 0 if first iteration
# 1 if inited but not yet ok to quit (definition of this below)
# 2 if ok to quit
# initquad: 0 if x > 0, y > 0
# 1 if x < 0, y > 0
# 2 if x < 0, y < 0
# 3 if x > 0, y < 0
# We invert these senses in the in-loop test to make comparison easy.
quitflag = 0
initquad = -1
# Start finding contours.
while n < maxiters:
dfdx, dfdy = df (x, y)
# If we're booting up, remember the quadrant that df/dx points in.
# Once we've rotated around to the other direction, it is safe to quit
# once we return close to the original point, since we must have
# completed a circle.
if quitflag == 0:
if dfdx > 0:
if dfdy > 0:
initquad = 0
else:
initquad = 3
else:
if dfdy > 0:
initquad = 1
else:
initquad = 2
quitflag = 1
elif quitflag == 1:
if dfdx > 0:
if dfdy > 0:
curquad = 2
else:
curquad = 1
else:
if dfdy > 0:
curquad = 3
else:
curquad = 0
if curquad == initquad:
quitflag = 2
# We will move perpendicular to [df/dx, df/dy], rotating to the left
# (arbitrarily) from that direction. We need to figure out how far we
# can safely move in this direction.
if goright:
dx = dfdy * defeta
dy = -dfdx * defeta
else:
dx = -dfdy * defeta
dy = dfdx * defeta
i = 0
while i < netastep:
nx = x + dx
ny = y + dy
nv = f (nx, ny)
# Is the value of the function sufficently close to what
# we're aiming for?
if abs (nv / v - 1) < vtol1:
break
# No. Try a smaller dx/dy.
dx *= eta_scale
dy *= eta_scale
i += 1
else:
# Failed to find a sufficiently small eta (did not break out of
# loop)
raise PKError ('failed to find sufficiently small eta: xy %g,%g; '
'dv %g; df %g,%g; dxy %g,%g; defeta %g; eta_scale '
'%g' % (x, y, nv - v, dfdx, dfdy, dx, dy, defeta,
eta_scale))
# Now compute a new [df/dx, df/dy], and move along it, finding our way
# back to the desired value, 'v'. Newton's method should suffice. This
# loop usually exits after one iteration.
i = 0
while i < maxnewt:
dfdx, dfdy = df (nx, ny)
df2 = dfdx**2 + dfdy**2
dv = nv - v
nx -= dv * dfdx / df2
ny -= dv * dfdy / df2
nv = f (nx, ny)
if abs (nv/v - 1) < vtol2:
break
i += 1
else:
# Did not break out of loop.
raise PKError ('failed to converge with Newton\'s method')
# Ok, we found our next value.
pts[n] = (nx, ny)
x = nx
y = ny
n += 1
# Time to stop? Make sure we've gone at least a half-turn so that we
# don't just exit on the first iteration.
if quitflag == 2:
dist2 = (x/x0 - 1)**2 + (y/y0 - 1)**2
if dist2 < 3 * (dx**2 + dy**2):
break
else:
raise PKError ('needed too many points to close contour')
# Woohoo! All done.
return pts[:n]
|
Java
|
UTF-8
| 1,527 | 2.234375 | 2 |
[] |
no_license
|
package Entity;
// Generated 9 nov. 2019 21:08:11 by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Dept generated by hbm2java
*/
@Entity
@Table(name="dept"
,catalog="jeetp"
)
public class Dept implements java.io.Serializable {
private String deptno;
private String dname;
private Set<Emp> emps = new HashSet<Emp>(0);
public Dept() {
}
public Dept(String deptno) {
this.deptno = deptno;
}
public Dept(String deptno, String dname, Set<Emp> emps) {
this.deptno = deptno;
this.dname = dname;
this.emps = emps;
}
@Id
@Column(name="deptno", unique=true, nullable=false, length=6)
public String getDeptno() {
return this.deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
@Column(name="dname", length=14)
public String getDname() {
return this.dname;
}
public void setDname(String dname) {
this.dname = dname;
}
@OneToMany(fetch=FetchType.LAZY, mappedBy="dept")
public Set<Emp> getEmps() {
return this.emps;
}
public void setEmps(Set<Emp> emps) {
this.emps = emps;
}
}
|
JavaScript
|
UTF-8
| 2,942 | 2.515625 | 3 |
[] |
no_license
|
const Tought = require('../models/Tought')
const User = require('../models/User')
const { Op } = require('sequelize')
module.exports = class ToughController {
static async dashboard(req, res) {
const userId = req.session.userid
const user = await User.findOne({
where: {
id: userId,
},
include: Tought,
plain: true,
})
const toughts = user.Toughts.map((result) => result.dataValues)
let emptyToughts = true
if (toughts.length > 0) {
emptyToughts = false
}
console.log(toughts)
console.log(emptyToughts)
res.render('toughts/dashboard', { toughts, emptyToughts })
}
static createTought(req, res) {
res.render('toughts/create')
}
static createToughtSave(req, res) {
const tought = {
title: req.body.title,
UserId: req.session.userid,
}
Tought.create(tought)
.then(() => {
req.flash('message', 'Pensamento criado com sucesso!')
req.session.save(() => {
res.redirect('/toughts/dashboard')
})
})
.catch((err) => console.log())
}
static showToughts(req, res) {
console.log(req.query)
// check if user is searching
let search = ''
if (req.query.search) {
search = req.query.search
}
// order results, newest first
let order = 'DESC'
if (req.query.order === 'old') {
order = 'ASC'
} else {
order = 'DESC'
}
Tought.findAll({
include: User,
where: {
title: { [Op.like]: `%${search}%` },
},
order: [['createdAt', order]],
})
.then((data) => {
let toughtsQty = data.length
if (toughtsQty === 0) {
toughtsQty = false
}
const toughts = data.map((result) => result.get({ plain: true }))
res.render('toughts/home', { toughts, toughtsQty, search })
})
.catch((err) => console.log(err))
}
static removeTought(req, res) {
const id = req.body.id
Tought.destroy({ where: { id: id } })
.then(() => {
req.flash('message', 'Pensamento removido com sucesso!')
req.session.save(() => {
res.redirect('/toughts/dashboard')
})
})
.catch((err) => console.log())
}
static updateTought(req, res) {
const id = req.params.id
Tought.findOne({ where: { id: id }, raw: true })
.then((tought) => {
res.render('toughts/edit', { tought })
})
.catch((err) => console.log())
}
static updateToughtPost(req, res) {
const id = req.body.id
const tought = {
title: req.body.title,
description: req.body.description,
}
Tought.update(tought, { where: { id: id } })
.then(() => {
req.flash('message', 'Pensamento atualizado com sucesso!')
req.session.save(() => {
res.redirect('/toughts/dashboard')
})
})
.catch((err) => console.log())
}
}
|
Java
|
UTF-8
| 3,528 | 3.21875 | 3 |
[] |
no_license
|
//package tools;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.sql.*;
public class Loader {
private static final String file = "Markets.csv";
private static BufferedReader reader;
public Loader() {
// Connect to the JDBC
String url = "jdbc:mysql://localhost:3306/farmers_markets";
Connection conn = null;
try {
conn = DriverManager.getConnection(url, "USERNAME", "PASSWORD");
} catch(SQLException e) {
e.printStackTrace();
System.err.println("ERROR: <couldn't connect to database>");
System.exit(1);
}
// Read in the data from the Markets.csv file and load it into the database
try {
String line;
reader = new BufferedReader(new FileReader(file)); // Skip the first line
reader.readLine();
while ((line = reader.readLine()) != null) {
String insert = "INSERT INTO markets (markets_id,market_name,website,state,city,zipcode,latitude,longitude)"
+ "VALUES (?,?,?,?,?,?,?,?)";
// Use regulat expressions to avoid splitting comma's within strings
String[] tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
PreparedStatement stat = conn.prepareStatement(insert);
stat.setInt(1, Integer.parseInt(tokens[0])); // id
stat.setString(2, tokens[1]); // name
stat.setString(3, tokens[2]); // website
stat.setString(4, tokens[10]); // city
stat.setString(5, tokens[8]); // state
int zip = handleZip(tokens[11]);
stat.setInt(6, zip); // zipcode
// Parse latitude and longitude, set to default if issue arises
try {
stat.setDouble(7, Double.parseDouble(tokens[21])); // latitude
stat.setDouble(8, Double.parseDouble(tokens[20])); // longitude
} catch(Exception e) {
stat.setDouble(7, 0); // If no value supplied set 0,0
stat.setDouble(8, 0); // If no value supplied set 0,0
}
stat.execute();
}
// Print out the error details
} catch(Exception e) {
System.err.println("ERROR: <trouble loading into database>");
e.printStackTrace();
System.exit(1);
} finally {
// Close the reader
try {
if (reader != null) {
reader.close();
}
} catch(IOException e) {
System.err.println("ERROR: <couldn't close reader>");
}
}
}
/**
* Ensures that a zip code is the right size
* @param zip - the zipcode as a string
* @return return the zipcode as an integer
*/
private int handleZip(String zip) {
// Try to parse the first 5 digits
if (zip.length() >= 5) {
try {
return Integer.parseInt(zip.substring(0, 5));
} catch(NumberFormatException e) {
return -1;
}
}
// Return -1 for empty zipcodes
else if (zip.equals(""))
return -1;
// Parse the entire zipcode, if trouble, return -1
else
try {
return Integer.parseInt(zip);
} catch(NumberFormatException e) {
return -1;
}
}
// Call the main method from the command line or the script to populate the database
public static void main(String[] args) {
Loader loader = new Loader();
}
}
|
C++
|
UTF-8
| 490 | 3.234375 | 3 |
[] |
no_license
|
#include <iostream>
#include <cmath>
using namespace std;
int main(){
double x, y, result1, result2, result3, result4, result5 ;
x = 3;
y = 4;
result1 = abs(x + y);
cout << result1 <<endl;
result2 = abs(x) + abs(y);
cout << result2 << endl;
result3 = pow(x, 3)/ x + y;
cout << result3 << endl;
result4 = sqrt(pow(x, 6) + pow(y, 5));
cout << result4 << endl;
result5 = pow((x + sqrt(y)), 7);
cout << result5 << endl;
return 0;
}
|
C
|
UTF-8
| 696 | 3.109375 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
int main(int argc, char *argv[])
{
// 1. 创建/打开共享内存,大小为4k
int shmid = shmget(1000, 0, 0);
if (shmid == -1) {
perror("shmget error");
return -1;
}
// 2. 当前进程和共享内存关联
void *ptr = shmat(shmid, NULL, 0);
if (ptr == (void*)-1) {
perror("shmat error");
return -1;
}
// 3. 读共享内存
printf("共享内存数据:%s\n", (char*)ptr);
// 阻塞程序
printf("按任意键继续,删除共享内存\n");
getchar();
// 解除关联
shmctl(shmid, IPC_RMID, NULL);
printf("共享内存已经被删除...\n");
return 0;
}
|
C#
|
UTF-8
| 5,494 | 2.90625 | 3 |
[] |
no_license
|
using Logit_Transport.Data;
using Logit_Transport.Data.Models;
using Logit_Transport.DataProcessor.ImportDto;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Logit_Transport.Services
{
public class ParticipantService : IPraticipantService
{
private const string ErrorMessage = "Invalid data";
private const string SuccessfullyImportedParticipant = "Imported {0}";
private LogitDbContext context;
public ParticipantService(LogitDbContext context)
{
this.context = context;
}
public string CreateParticipant()
{
var sb = new StringBuilder();
Console.Write("Enter your First and Last Name or Company name:");
string name = Console.ReadLine();
Console.Write("Phone:");
string phone = Console.ReadLine();
Console.Write("Email:");
string email = Console.ReadLine();
Console.Write("Town:");
string town = Console.ReadLine();
Console.Write("Street:");
string street = Console.ReadLine();
Console.Write("Street Number:");
string streetNumber = Console.ReadLine();
Console.Write("Block:");
string inputBlock = Console.ReadLine();
string block = IfInputIsEmptyOrWtiteSpace(inputBlock);
Console.Write("Entrance:");
string inputEntrance = Console.ReadLine();
string entrance = IfInputIsEmptyOrWtiteSpace(inputEntrance);
Console.Write("Floor:");
string floorAsString = Console.ReadLine();
int? floor = null;
if (!string.IsNullOrWhiteSpace(floorAsString))
{
floor = int.Parse(floorAsString);
}
//1. Тук правя инстанция на адреса без да се интересувам дали са верни данните. По-късно ще го проверявам
var currImportAddressDto = new ImportAddressDto
{
Town = town,
Street = street,
StreetNumber = streetNumber,
Block = block,
Entrance = entrance,
Floor = floor
};
//2. Тук проверявам дали адреса отговаря на изискванията, ако не, гърмя
if (!IsValid(currImportAddressDto))
{
sb.AppendLine(ErrorMessage);
return sb.ToString().TrimEnd();
}
//3. Щом адреса отговаря на изискванията, то тогава си правя оригиналния адрес за да мога да го запазя в базата
var currAddress = new Address
{
Town = currImportAddressDto.Town,
Street = currImportAddressDto.Street,
StreetNumber = currImportAddressDto.StreetNumber,
Block = currImportAddressDto.Block,
Entrance = currImportAddressDto.Entrance,
Floor = currImportAddressDto.Floor
};
//4. Тук си правя ImportParticipantDto без проверка на входните данни
var currImportParticipantDto = new ImportParticipantDto
{
Name = name,
Phone = phone,
Address = currAddress,
Email = email
};
//5. Тук вече си правя проверката на Name и Phone на ParticipantDto. Ако не е валидно името или телефона гърмя
if (!IsValid(currImportAddressDto))
{
sb.AppendLine(ErrorMessage);
return sb.ToString().TrimEnd();
}
//6. Ако всичко е валидно, правя си от ImportParticipantDto, оригиналния клас Participant и го записвам в базата данни ---> Кой ми вкарва нови Address в базата
var currParticipant = new Participant
{
Name = currImportParticipantDto.Name,
Phone = currImportParticipantDto.Phone,
Address = currImportParticipantDto.Address,
Email = currImportParticipantDto.Email
};
context.Participants.Add(currParticipant);
context.SaveChanges();
sb.AppendLine(string.Format(SuccessfullyImportedParticipant, currParticipant.Name));
return sb.ToString().TrimEnd();
}
private static bool IsValid(object entity)
{
var validationContext = new ValidationContext(entity);
var validationResult = new List<ValidationResult>();
var result = Validator.TryValidateObject(entity, validationContext, validationResult, true);
return result;
}
private string IfInputIsEmptyOrWtiteSpace(string input)
{
string exitValue;
if (string.IsNullOrWhiteSpace(input))
{
exitValue = null;
}
else
{
exitValue = input;
}
return exitValue;
}
}
}
|
Java
|
UTF-8
| 2,708 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
package com.graphs.commands;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import com.graphs.AbstractTest;
import com.graphs.exception.GraphException;
import com.graphs.exception.NoSuchRouteException;
public class RoutesCommandTest extends AbstractTest {
private Command command = new RoutesCommand();
@Before
public void setUp() {
initComplexGraph();
}
@Test
public void shouldPassWhenExecuteWithCorrectGraphTest() throws IOException, GraphException {
assertEquals("7", command.execute(graph, new String[] {"C", "C"}, "<30"));
assertEquals("9", command.execute(graph, new String[] {"C", "C"}, "<=30"));
assertEquals("1", command.execute(graph, new String[] {"C", "C"}, "=32"));
assertEquals("76", command.execute(graph, new String[] {"C", "C"}, ">50"));
assertEquals("82", command.execute(graph, new String[] {"C", "C"}, ">=50"));
}
@Test
public void shouldPassWhenExecuteWithCorrectGraphEvenWithoutVertexesToGoTest() throws IOException, GraphException {
assertEquals("0", command.execute(graph, new String[] {}, "<1" ));
}
@Test
public void shouldPassWhenExecuteWithCorrectGraphButLowRestrictionNumberTest() throws IOException, GraphException {
assertEquals("0", command.execute(graph, new String[] {"A", "B"}, "<1"));
}
@Test
public void shouldPassWhenExecuteWithCorrectGraphButNotExistingVertexToGoTest() throws IOException, GraphException {
expect(GraphException.class, "Vertex 'F' not found");
command.execute(graph, new String[] {"A", "F"}, "<1");
}
@Test
public void shouldFailWhenExecuteWithCorrectGraphButInvalidExtraParameterTest() throws IOException, GraphException {
expect(IllegalArgumentException.class, "Parameter is missing or not valid. e.g.: routes A-B <=4");
command.execute(graph, new String[] {"A", "B"}, "1");
}
@Test
public void shouldFailWhenExecuteWithCorrectGraphButInvalidExtraParameterRegexTest() throws IOException, GraphException {
expect(IllegalArgumentException.class, "Parameter is missing or not valid. e.g.: routes A-B <=4");
command.execute(graph, new String[] {"A", "B"}, ">>1");
}
@Test
public void shouldFailWhenExecuteWithCorrectGraphButNoExtraParameterRegexTest() throws IOException, GraphException {
expect(IllegalArgumentException.class, "Parameter is missing or not valid. e.g.: routes A-B <=4");
command.execute(graph, new String[] {"A", "B"}, (String) null);
}
@Test
public void shouldPassWhenExecuteWithCorrectGraphButNotExistingRouteToGoTest() throws IOException, GraphException {
expect(NoSuchRouteException.class, "NO SUCH ROUTE");
command.execute(graph, new String[] {"E", "A"}, "<1" );
}
}
|
Java
|
UTF-8
| 1,963 | 2.078125 | 2 |
[] |
no_license
|
/***********************************************************************************************************************
*
* Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************/
package eu.stratosphere.nephele.checkpointing;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import eu.stratosphere.nephele.execution.RuntimeEnvironment;
import eu.stratosphere.nephele.io.channels.ChannelType;
import eu.stratosphere.nephele.taskmanager.runtime.RuntimeTask;
public final class CheckpointDecision {
private static final Log LOG = LogFactory.getLog(CheckpointDecision.class);
public static boolean getDecision(final RuntimeTask task) {
switch (CheckpointUtils.getCheckpointMode()) {
case NEVER:
return false;
case ALWAYS:
return true;
case NETWORK:
return isNetworkTask(task);
}
return false;
}
private static boolean isNetworkTask(final RuntimeTask task) {
final RuntimeEnvironment environment = task.getRuntimeEnvironment();
for (int i = 0; i < environment.getNumberOfOutputGates(); ++i) {
if (environment.getOutputGate(i).getChannelType() == ChannelType.NETWORK) {
LOG.info(environment.getTaskNameWithIndex() + " is a network task");
return true;
}
}
return false;
}
}
|
SQL
|
UTF-8
| 2,657 | 2.90625 | 3 |
[] |
no_license
|
ALTER TABLE Student
ADD CONSTRAINT fks_course_code FOREIGN KEY(CourseCode) REFERENCES Course(CourseCode)
ON DELETE RESTRICT
ON UPDATE CASCADE;
ALTER TABLE PQualification
ADD CONSTRAINT fkp_student_id FOREIGN KEY(StudentID) REFERENCES Student(StudentID)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE Course
ADD CONSTRAINT fkc_faculty_id FOREIGN KEY(FacultyID) REFERENCES Faculty(FacultyID)
ON DELETE SET NULL
ON UPDATE CASCADE;
ALTER TABLE ALStudent_Subject
ADD CONSTRAINT fka_student_id FOREIGN KEY(StudentID) REFERENCES Student(StudentID)
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT fka_subject_code FOREIGN KEY(SubjectCode) REFERENCES ALSubject(SubjectCode)
ON DELETE RESTRICT
ON UPDATE CASCADE;
ALTER TABLE Subject_
ADD CONSTRAINT fksu_course_code FOREIGN KEY(CourseCode) REFERENCES Course(CourseCode)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE Enrollment
ADD CONSTRAINT fke_student_id FOREIGN KEY(StudentID) REFERENCES Student(StudentID)
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT fke_subject_code FOREIGN KEY(SubjectCode) REFERENCES Subject_(SubjectCode)
ON DELETE RESTRICT
ON UPDATE CASCADE,
ADD CONSTRAINT fke_invoice_id FOREIGN KEY(InvoiceID) REFERENCES Payment(InvoiceID)
ON DELETE SET NULL
ON UPDATE CASCADE;
ALTER TABLE Lecture
ADD CONSTRAINT fkl_staff_id FOREIGN KEY(Staff_ID) REFERENCES Lecturer(Staff_ID)
ON DELETE SET NULL
ON UPDATE CASCADE,
ADD CONSTRAINT fkl_subject_code FOREIGN KEY(SubjectCode) REFERENCES Subject_(SubjectCode)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE Lecturer
ADD CONSTRAINT fkl_faculty_id FOREIGN KEY(FacultyID) REFERENCES Faculty(FacultyID)
ON DELETE SET NULL
ON UPDATE CASCADE;
ALTER TABLE Assessment
ADD CONSTRAINT fka_enrollment_id FOREIGN KEY(EnrollmentID) REFERENCES Enrollment(EnrollmentID)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE LabSession
ADD CONSTRAINT fkla_subject_code FOREIGN KEY(SubjectCode) REFERENCES Subject_(SubjectCode)
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT fkl_lab_id FOREIGN KEY(LabID) REFERENCES Laboratory(LabID)
ON DELETE SET NULL
ON UPDATE CASCADE;
ALTER TABLE LabSession_Instructor
ADD CONSTRAINT fklabs_lab_session_id FOREIGN KEY(LabSessionID) REFERENCES LabSession(LabSessionID)
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT fklabs_staff_id FOREIGN KEY(Staff_ID) REFERENCES Instructor(Staff_ID)
ON DELETE CASCADE
ON UPDATE CASCADE;
ALTER TABLE LabSession_Student
ADD CONSTRAINT fkl_lab_session_id FOREIGN KEY(LabSessionID) REFERENCES LabSession(LabSessionID)
ON DELETE CASCADE
ON UPDATE CASCADE,
ADD CONSTRAINT fkl_student_id FOREIGN KEY(StudentID) REFERENCES Student(StudentID)
ON DELETE CASCADE
ON UPDATE CASCADE;
|
Java
|
UTF-8
| 3,975 | 2.15625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package projectzulu.common.mobs.entity;
import java.util.EnumSet;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.passive.IAnimals;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import projectzulu.common.api.BlockList;
import projectzulu.common.core.DefaultProps;
import projectzulu.common.mobs.entityai.EntityAIAttackOnCollide;
import projectzulu.common.mobs.entityai.EntityAIFollowParent;
import projectzulu.common.mobs.entityai.EntityAIHurtByTarget;
import projectzulu.common.mobs.entityai.EntityAIMate;
import projectzulu.common.mobs.entityai.EntityAINearestAttackableTarget;
import projectzulu.common.mobs.entityai.EntityAIPanic;
import projectzulu.common.mobs.entityai.EntityAITempt;
import projectzulu.common.mobs.entityai.EntityAIWander;
import cpw.mods.fml.common.Loader;
public class EntityPenguin extends EntityGenericAnimal implements IAnimals {
public EntityPenguin(World par1World){
super(par1World);
setSize(0.9f, 1.5f);
this.moveSpeed = 0.25f;
this.getNavigator().setAvoidsWater(true);
this.tasks.addTask(0, new EntityAISwimming(this));
this.tasks.addTask(1, new EntityAIPanic(this, this.moveSpeed));
this.tasks.addTask(3, new EntityAIAttackOnCollide(this, this.moveSpeed, false));
// this.tasks.addTask(4, new EntityAIFollowOwner(this, this.moveSpeed, 10.0F, 2.0F));
this.tasks.addTask(5, new EntityAIMate(this, this.moveSpeed));
this.tasks.addTask(6, new EntityAITempt(this, this.moveSpeed, Item.fishRaw.itemID, false));
this.tasks.addTask(6, new EntityAITempt(this, this.moveSpeed, Item.fishCooked.itemID, false));
this.tasks.addTask(7, new EntityAIFollowParent(this, this.moveSpeed));
this.tasks.addTask(9, new EntityAIWander(this, this.moveSpeed, 120));
this.targetTasks.addTask(3, new EntityAIHurtByTarget(this, false, false));
this.targetTasks.addTask(4, new EntityAINearestAttackableTarget(this, EnumSet.of(EntityStates.attacking, EntityStates.looking), EntityPlayer.class, 16.0F, 0, true));
// this.targetTasks.addTask(4, new EntityAINearestAttackableTarget(this, EntityLiving.class, 16.0F, 0, false, true, IMob.mobSelector));
}
@Override
protected int getAttackStrength(World par1World) {
switch (par1World.difficultySetting) {
case 0:
return 3;
case 1:
return 3;
case 2:
return 4;
case 3:
return 6;
default:
return 3;
}
}
@Override
public String getTexture() {
this.texture = DefaultProps.mobDiretory + "penguin.png";
return super.getTexture();
}
@Override
protected boolean isValidLocation(World world, int xCoord, int yCoord, int zCoord) {
return worldObj.canBlockSeeTheSky(xCoord, yCoord, zCoord);
}
@Override
public int getMaxHealth(){return 15;}
/**
* Returns the current armor value as determined by a call to InventoryPlayer.getTotalArmorValue
*/
@Override
public int getTotalArmorValue(){return 0;}
/**
* Returns the sound this mob makes while it's alive.
*/
@Override
protected String getLivingSound(){return "sounds.penguinhurt";}
/**
* Returns the sound this mob makes when it is hurt.
*/
@Override
protected String getHurtSound(){ return "sounds.penguinhurt"; }
/**
* Checks if the Provided ItemStack is considered an item that should be used for Breeding
* This is overriden by each Entity if deviations from default are desired
*/
@Override
public boolean isValidBreedingItem(ItemStack itemStack){
if( itemStack != null && (itemStack.itemID == Item.fishRaw.itemID || itemStack.itemID == Item.fishCooked.itemID) ){
return true;
}else{
return super.isValidBreedingItem(itemStack);
}
}
@Override
protected void dropRareDrop(int par1) {
if(Loader.isModLoaded(DefaultProps.BlocksModId) && BlockList.mobHeads.isPresent()){
entityDropItem(new ItemStack(BlockList.mobHeads.get().blockID,1,13), 1);
}
super.dropRareDrop(par1);
}
}
|
C#
|
UTF-8
| 1,882 | 3.25 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Text;
namespace TestADLogin
{
[Serializable]
public class ADUser : IComparable
{
public ADUser()
{ }
public ADUser(UserPrincipal principal)
{
FirstName = principal.GivenName;
MiddleName = principal.MiddleName;
LastName = principal.Surname;
Enabled = principal.Enabled;
UserName = principal.SamAccountName;
EmailAddress = principal.EmailAddress;
}
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public bool? Enabled { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
public override string ToString()
{
return UserName;
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings:
/// Value Meaning Less than zero This instance precedes <paramref name="obj" /> in the sort order.
/// Zero This instance occurs in the same position in the sort order as <paramref name="obj" />.
/// Greater than zero This instance follows <paramref name="obj" /> in the sort order.
/// </returns>
public int CompareTo(object obj)
{
if (obj == null) return 1;
ADUser otherUser = obj as ADUser;
if (otherUser != null)
{
return this.UserName.CompareTo(otherUser.UserName);
}
else
{
throw new ArgumentException("Object is not an ADUser");
}
}
}
}
|
Markdown
|
UTF-8
| 1,224 | 2.734375 | 3 |
[] |
no_license
|
# kmer-counter-abseil
The `kfs` program reads in multiline FASTA records, counts canonical kmers using the [Abseil C++ `container:flat_hash_map`](https://github.com/abseil/abseil-cpp).
## Abseil C++
Integration of the Abseil C++ kit requires use of [`bazel`](https://www.bazel.build/), *e.g.*, on OS X:
```
$ brew cask install homebrew/cask-versions/java8
$ brew install bazel
```
Clone the Abseil C++ Github repository:
```
$ make abseil-cpp
```
Edit the `WORKSPACE` file in this directory to specify the correct `path` for the Abseil C++ installation.
Then complete the build:
```
$ make abseil-cpp-build
```
This can take a few minutes.
## Usage
### Compilation
```
$ make kfs
$ make msl
$ make generate_fasta
```
These targets build binaries `bazel-bin/src/kfs`, `bazel-bin/src/msl`, and `bazel-bin/src/generate_fasta`, respectively.
### Test data
```
$ bazel-bin/src/generate_fasta > test.fa
```
(Or build the `generate_test_data` target.)
### Performance testing
Specify variables `K` (integer) and `FASTA` (path to FASTA sequences), before running tests with those variables, *e.g.*:
```
$ export K=29
$ export FASTA=test.fa
$ /usr/bin/time -l bazel-bin/src/kfs -k ${K} -i ${FASTA}
...
```
Etc.
|
Java
|
UTF-8
| 409 | 2.515625 | 3 |
[] |
no_license
|
package kr.co.fastcampus.eatgo.domain;
import lombok.Getter;
@Getter
public class Restaurant {
private Long id;
private String name;
private String address;
public Restaurant(Long id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
public String getInformation() {
return name + " in " + address;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.