answer
stringlengths 15
1.25M
|
|---|
package com.dotmarketing.portlets.mailinglists.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.dotcms.repackage.portlet.javax.portlet.PortletConfig;
import com.dotcms.repackage.portlet.javax.portlet.RenderRequest;
import com.dotcms.repackage.portlet.javax.portlet.RenderResponse;
import com.dotcms.repackage.portlet.javax.portlet.WindowState;
import javax.servlet.jsp.PageContext;
import com.dotcms.repackage.commons_beanutils.org.apache.commons.beanutils.BeanUtils;
import com.dotcms.repackage.struts.org.apache.struts.action.ActionForm;
import com.dotcms.repackage.struts.org.apache.struts.action.ActionForward;
import com.dotcms.repackage.struts.org.apache.struts.action.ActionMapping;
import com.dotmarketing.business.Role;
import com.dotmarketing.portlets.mailinglists.factories.MailingListFactory;
import com.dotmarketing.portlets.mailinglists.model.MailingList;
import com.dotmarketing.portlets.userfilter.factories.UserFilterFactory;
import com.dotmarketing.util.Config;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
import com.dotmarketing.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.struts.PortletAction;
import com.liferay.portal.util.Constants;
/**
* <a href="ViewQuestionsAction.java.html"><b><i>View Source</i></b></a>
*
* @author Brian Wing Shun Chan
* @version $Revision: 1.4 $
*
*/
public class <API key> extends PortletAction {
public ActionForward render(
ActionMapping mapping, ActionForm form, PortletConfig config,
RenderRequest req, RenderResponse res)
throws Exception {
Logger.debug(this, "Running <API key>");
try {
//get the user, order, direction
User user = com.liferay.portal.util.PortalUtil.getUser(req);
String orderBy = req.getParameter("orderby");
String direction = req.getParameter("direction");
String condition = req.getParameter("query");
//get their lists
List list = null;
List roles = com.dotmarketing.business.APILocator.getRoleAPI().loadRolesForUser(user.getUserId());
boolean isMarketingAdmin = false;
Iterator rolesIt = roles.iterator();
while (rolesIt.hasNext()) {
Role role = (Role) rolesIt.next();
if (UtilMethods.isSet(role.getRoleKey()) && role.getRoleKey().equals(Config.getStringProperty("<API key>"))) {
isMarketingAdmin = true;
break;
}
}
if (isMarketingAdmin) {
if (UtilMethods.isSet(orderBy) && UtilMethods.isSet(direction)) {
//list = MailingListFactory.getAllMailingLists(orderBy, direction);
list = MailingListFactory.getAllMailingLists();
list.addAll(UserFilterFactory.getAllUserFilter());
if (orderBy.equals("title")) {
if (direction.equals(" asc"))
Collections.sort(list, new ComparatorTitleAsc());
else
Collections.sort(list, new ComparatorTitleDesc());
}
} else if(UtilMethods.isSet(condition)) {
list = MailingListFactory.<API key>(condition);
list.addAll(UserFilterFactory.<API key>(condition));
Collections.sort(list, new ComparatorTitleAsc());
} else {
list = MailingListFactory.getAllMailingLists();
list.addAll(UserFilterFactory.getAllUserFilter());
Collections.sort(list, new ComparatorTitleAsc());
}
} else {
if (UtilMethods.isSet(orderBy) && UtilMethods.isSet(direction)) {
//list = MailingListFactory.<API key>(user, orderBy, direction);
list = MailingListFactory.<API key>(user);
list.add(MailingListFactory.<API key>());
list.addAll(UserFilterFactory.<API key>(user));
if (orderBy.equals("title")) {
if (direction.equals(" asc"))
Collections.sort(list, new ComparatorTitleAsc());
else
Collections.sort(list, new ComparatorTitleDesc());
}
} else if(UtilMethods.isSet(condition)) {
list = MailingListFactory.<API key>(user, condition);
list.add(MailingListFactory.<API key>());
list.addAll(UserFilterFactory.<API key>(condition, user));
Collections.sort(list, new ComparatorTitleAsc());
} else {
list = MailingListFactory.<API key>(user);
list.add(MailingListFactory.<API key>());
list.addAll(UserFilterFactory.<API key>(user));
Collections.sort(list, new ComparatorTitleAsc());
}
}
if (req.getWindowState().equals(WindowState.NORMAL)) {
// if (list != null)
// list = <API key>(list);
req.setAttribute(WebKeys.<API key>, list);
return mapping.findForward("portlet.ext.mailinglists.view");
}
else {
req.setAttribute(WebKeys.MAILING_LIST_VIEW, list);
return mapping.findForward("portlet.ext.mailinglists.view_mailinglists");
}
}
catch (Exception e) {
req.setAttribute(PageContext.EXCEPTION, e);
return mapping.findForward(Constants.COMMON_ERROR);
}
}
private List<MailingList> <API key>(List<MailingList> list) {
List<MailingList> result = new ArrayList<MailingList>(list.size());
int i;
boolean added;
MailingList mailingList2;
for (MailingList mailingList1: list) {
if (result.size() == 0) {
result.add(mailingList1);
} else {
added = false;
for (i = 0; i < result.size(); ++i) {
mailingList2 = result.get(i);
if (mailingList2.getIDate().before(mailingList1.getIDate())) {
result.add(i, mailingList1);
added = true;
break;
}
}
if (!added)
result.add(mailingList1);
}
}
return result;
}
private class ComparatorTitleAsc implements Comparator {
public int compare(Object o1, Object o2) {
String title1, title2;
try {
if (o1 instanceof MailingList)
title1 = BeanUtils.getProperty(o1, "title");
else
title1 = BeanUtils.getProperty(o1, "userFilterTitle");
} catch (Exception e) {
title1 = "";
}
try {
if (o2 instanceof MailingList)
title2 = BeanUtils.getProperty(o2, "title");
else
title2 = BeanUtils.getProperty(o2, "userFilterTitle");
} catch (Exception e) {
title2 = "";
}
return title1.compareToIgnoreCase(title2);
}
}
private class ComparatorTitleDesc implements Comparator {
public int compare(Object o1, Object o2) {
String title1, title2;
try {
if (o1 instanceof MailingList)
title1 = BeanUtils.getProperty(o1, "title");
else
title1 = BeanUtils.getProperty(o1, "userFilterTitle");
} catch (Exception e) {
title1 = "";
}
try {
if (o2 instanceof MailingList)
title2 = BeanUtils.getProperty(o2, "title");
else
title2 = BeanUtils.getProperty(o2, "userFilterTitle");
} catch (Exception e) {
title2 = "";
}
return title2.compareToIgnoreCase(title1);
}
}
}
|
/* FIXME:
* This code does not fully handle the following cases:
* - when the watched directory does not yet exist
* - when the watched directory is later deleted
* In the event of the watched directory not yet existing, this code should
* watch the parent directory for its subsequent creation; if the parent
* does not yet exist, it should watch the parent's parent, etc., up to the
* root. This might be best accomplished by initially registering all of
* parent directories up to the root for the directory being watched.
* In the event of the watched directory being deleted (event IN_IGNORED),
* once the existing watch has been removed, this should degenerate into the
* case above where the watched directory does not yet exist.
*
* Currently, inotify works as expected as long as the parent directory being
* watched persists for the lifetime of the daemon. But once that
* directory's inode is removed, the daemon falls back to using timers to
* periodically resurrect downed objects.
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */
#if ! HAVE_SYS_INOTIFY_H
#include "inevent.h"
int
inevent_add (const char *filename, inevent_cb_f cb_fnc, void *cb_arg)
{
return (-1);
}
int
inevent_remove (const char *filename)
{
return (-1);
}
int
inevent_get_fd (void)
{
return (-1);
}
int inevent_process (void)
{
return (-1);
}
#else /* HAVE_SYS_INOTIFY_H */
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
#include "inevent.h"
#include "list.h"
#include "log.h"
#include "util-file.h"
/* Number of bytes for the average inotify event (w/ 16 bytes for name).
*/
#define INEVENT_SIZE ((sizeof (struct inotify_event)) + 16)
/* Number of average inotify events to process per read invocation.
*/
#define INEVENT_NUM 128
/* Number of bytes to allocate for the inotify event buffer.
*/
#define INEVENT_BUF_LEN ((INEVENT_SIZE) * (INEVENT_NUM))
struct inevent {
char *pathname; /* pathname being watched */
char *dirname; /* directory component of pathname */
char *filename; /* filename component of pathname */
inevent_cb_f cb_fnc; /* callback function */
void *cb_arg; /* callback function arg */
int wd; /* inotify watch descriptor */
};
typedef struct inevent inevent_t;
static int _inevent_init (void);
static void _inevent_fini (void);
static inevent_t * _inevent_create (const char *pathname,
inevent_cb_f cb_fnc, void *cb_arg);
static void _inevent_destroy (inevent_t *inevent_ptr);
static int _list_find_by_path (const inevent_t *inevent_ptr,
const char *pathname);
static int _list_find_by_wd (const inevent_t *inevent_ptr,
const int *wd_ptr);
static int _list_find_by_event (const inevent_t *inevent_ptr,
const struct inotify_event *event_ptr);
static int inevent_fd = -1; /* inotify file descriptor */
static List inevent_list = NULL; /* list of inevent structs */
int
inevent_add (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg)
{
/* Adds an inotify event for [pathname], causing [cb_fnc] to be invoked with
* [cb_arg] whenever the specified file is created.
* Returns 0 on success, or -1 on error.
*/
inevent_t *inevent_ptr;
if (pathname == NULL) {
log_msg (LOG_ERR, "inotify event pathname not specified");
return (-1);
}
if (cb_fnc == NULL) {
log_msg (LOG_ERR, "inotify event callback not specified");
return (-1);
}
if (pathname[0] != '/') {
log_msg (LOG_ERR, "inotify event path \"%s\" is not absolute",
pathname);
return (-1);
}
if (inevent_fd == -1) {
if (_inevent_init () < 0) {
log_msg (LOG_ERR, "unable to initialize inotify: %s",
strerror (errno));
return (-1);
}
}
if (list_find_first (inevent_list, (ListFindF) _list_find_by_path,
(void *) pathname)) {
log_msg (LOG_ERR, "inotify event path \"%s\" already specified",
pathname);
return (-1);
}
inevent_ptr = _inevent_create (pathname, cb_fnc, cb_arg);
if (inevent_ptr == NULL) {
return (-1);
}
list_append (inevent_list, inevent_ptr);
return (0);
}
int
inevent_remove (const char *pathname)
{
/* Removes the inotify event (if present) for [pathname].
* Returns 0 on success, or -1 on error.
*/
ListIterator li = NULL;
inevent_t *inevent_ptr;
int wd_cnt;
if (pathname == NULL) {
return (0);
}
if (inevent_list == NULL) {
return (0);
}
li = <API key> (inevent_list);
inevent_ptr = list_find (li, (ListFindF) _list_find_by_path,
(void *) pathname);
if (inevent_ptr == NULL) {
log_msg (LOG_ERR, "inotify event path \"%s\" not registered",
pathname);
<API key> (li);
return (0);
}
(void) list_remove (li);
list_iterator_reset (li);
wd_cnt = 0;
while (list_find (li, (ListFindF) _list_find_by_wd, &(inevent_ptr->wd))) {
wd_cnt++;
}
<API key> (li);
/* If no other inevents were found with a matching wd, then this inevent
* is the only one associated with this watch descriptor. As such, the
* watch associated with this watch descriptor can be removed since no
* other objects are relying on it.
* Note that multiple files may share the same watch descriptor since it
* is the file's directory that is watched.
*/
if ((inevent_ptr->wd >= 0) && (wd_cnt == 0)) {
(void) inotify_rm_watch (inevent_fd, inevent_ptr->wd);
DPRINTF((10, "Removed inotify watch wd=%d for directory \"%s\".\n",
inevent_ptr->wd, inevent_ptr->dirname));
}
_inevent_destroy (inevent_ptr);
if (list_is_empty (inevent_list)) {
_inevent_fini ();
}
return (0);
}
int
inevent_get_fd (void)
{
/* Returns the file descriptor associated with the inotify event queue,
* or -1 on error.
*/
return (inevent_fd);
}
int
inevent_process (void)
{
/* Processes the callback functions for all available events in the inotify
* event queue.
* Returns the number of events processed on success, or -1 on error.
*/
char buf [INEVENT_BUF_LEN];
int len;
int n = 0;
if (inevent_fd == -1) {
return (-1);
}
retry_read:
len = read (inevent_fd, buf, sizeof (buf));
if (len < 0) {
if (errno == EINTR) {
goto retry_read;
}
log_msg (LOG_ERR, "unable to read inotify fd: %s", strerror (errno));
return (-1);
}
else if (len == 0) {
log_msg (LOG_ERR, "inotify read buffer is too small");
return (-1);
}
else {
unsigned int i = 0;
uint32_t event_mask = IN_CREATE | IN_MOVED_TO;
while (i < (unsigned int) len) {
struct inotify_event *event_ptr;
inevent_t *inevent_ptr;
event_ptr = (struct inotify_event *) &buf[i];
DPRINTF((15,
"Received inotify event wd=%d mask=0x%x len=%u name=\"%s\".\n",
event_ptr->wd, event_ptr->mask, event_ptr->len,
(event_ptr->len > 0 ? event_ptr->name : "")));
if (event_ptr->mask & IN_IGNORED) {
(void) list_delete_all (inevent_list,
(ListFindF) _list_find_by_wd, &(event_ptr->wd));
}
else if ((event_ptr->mask & event_mask) && (event_ptr->len > 0)) {
inevent_ptr = list_find_first (inevent_list,
(ListFindF) _list_find_by_event, event_ptr);
if ((inevent_ptr != NULL) && (inevent_ptr->cb_fnc != NULL)) {
inevent_ptr->cb_fnc (inevent_ptr->cb_arg);
}
}
i += sizeof (struct inotify_event) + event_ptr->len;
n++;
}
}
return (n);
}
static int
_inevent_init (void)
{
/* Initializes the inotify event subsystem.
* Returns 0 on success, or -1 on error (with errno set).
*/
assert (inevent_fd == -1);
assert (inevent_list == NULL);
if (inevent_fd == -1) {
inevent_fd = inotify_init ();
if (inevent_fd == -1) {
goto err;
}
<API key> (inevent_fd);
set_fd_nonblocking (inevent_fd);
}
if (inevent_list == NULL) {
inevent_list = list_create ((ListDelF) _inevent_destroy);
if (inevent_list == NULL) {
goto err;
}
}
DPRINTF((5, "Initialized inotify event subsystem.\n"));
return (inevent_fd);
err:
_inevent_fini ();
return (-1);
}
static void
_inevent_fini (void)
{
/* Shuts down the inotify event subsystem.
*/
assert (inevent_fd >= 0);
assert (inevent_list != NULL);
if (inevent_fd >= 0) {
(void) close (inevent_fd);
inevent_fd = -1;
}
if (inevent_list != NULL) {
list_destroy (inevent_list);
inevent_list = NULL;
}
DPRINTF((5, "Shut down inotify event subsystem.\n"));
return;
}
static inevent_t *
_inevent_create (const char *pathname, inevent_cb_f cb_fnc, void *cb_arg)
{
/* Creates an inotify event object for [cb_fnc] to be invoked with [cb_arg]
* whenever the file specified by [pathname] is created.
* Returns a pointer to the new object on success, or NULL on error
* (with errno set).
*/
inevent_t *inevent_ptr = NULL;
char *p;
uint32_t event_mask = IN_CREATE | IN_MOVED_TO;
assert (pathname != NULL);
assert (pathname[0] == '/');
assert (cb_fnc != NULL);
inevent_ptr = malloc (sizeof (*inevent_ptr));
if (inevent_ptr == NULL) {
goto err;
}
memset (inevent_ptr, 0, sizeof (*inevent_ptr));
inevent_ptr->wd = -1;
inevent_ptr->pathname = strdup (pathname);
if (inevent_ptr->pathname == NULL) {
goto err;
}
inevent_ptr->dirname = strdup (pathname);
if (inevent_ptr->dirname == NULL) {
goto err;
}
p = strrchr (inevent_ptr->dirname, '/');
inevent_ptr->filename = strdup (p + 1);
if (inevent_ptr->filename == NULL) {
goto err;
}
if (p == inevent_ptr->dirname) { /* dirname is root directory ("/") */
*++p = '\0';
}
else {
*p = '\0';
}
inevent_ptr->cb_fnc = cb_fnc;
inevent_ptr->cb_arg = cb_arg;
inevent_ptr->wd = inotify_add_watch (inevent_fd, inevent_ptr->dirname,
event_mask);
if (inevent_ptr->wd == -1) {
goto err;
}
DPRINTF((10, "Added inotify watch wd=%d for \"%s\".\n",
inevent_ptr->wd, inevent_ptr->pathname));
return (inevent_ptr);
err:
_inevent_destroy (inevent_ptr);
return (NULL);
}
static void
_inevent_destroy (inevent_t *inevent_ptr)
{
/* Destroys the inotify event object referenced by [inevent_ptr].
*/
assert (inevent_ptr != NULL);
if (inevent_ptr == NULL) {
return;
}
DPRINTF((10, "Removed inotify watch wd=%d for \"%s\".\n",
inevent_ptr->wd, inevent_ptr->pathname));
if (inevent_ptr->pathname != NULL) {
free (inevent_ptr->pathname);
}
if (inevent_ptr->dirname != NULL) {
free (inevent_ptr->dirname);
}
if (inevent_ptr->filename != NULL) {
free (inevent_ptr->filename);
}
free (inevent_ptr);
return;
}
static int
_list_find_by_path (const inevent_t *inevent_ptr, const char *pathname)
{
/* List function helper to match items in a list of inevent_t pointers using
* the pathname [pathname] as the key.
* Returns non-zero if the key is found; o/w, returns zero.
*/
assert (inevent_ptr != NULL);
assert (pathname != NULL);
return (strcmp (inevent_ptr->pathname, pathname) == 0);
}
static int
_list_find_by_wd (const inevent_t *inevent_ptr, const int *wd_ptr)
{
/* List function helper to match items in a list of inevent_t pointers using
* a pointer to an inotify watch descriptor [wd_ptr] as the key.
* Returns non-zero if the key is found; o/w, returns zero.
*/
assert (inevent_ptr != NULL);
assert (wd_ptr != NULL);
return (inevent_ptr->wd == *wd_ptr);
}
static int
_list_find_by_event (const inevent_t *inevent_ptr,
const struct inotify_event *event_ptr)
{
/* List function helper to match items in a list of inevent_t pointers using
* a pointer to an inotify_event struct [event_ptr] as the key.
* Returns non-zero if the key is found; o/w, returns zero.
*/
assert (inevent_ptr != NULL);
assert (inevent_ptr->filename != NULL);
assert (event_ptr != NULL);
assert (event_ptr->len > 0);
assert (event_ptr->name != NULL);
return ((inevent_ptr->wd == event_ptr->wd) &&
(strcmp (inevent_ptr->filename, event_ptr->name) == 0));
}
#endif /* HAVE_SYS_INOTIFY_H */
|
package org.obiba.mica.core.service;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import net.minidev.json.JSONArray;
import org.obiba.mica.core.domain.<API key>;
import org.obiba.mica.file.FileStoreService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import com.google.common.collect.Sets;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.<API key>;
import com.jayway.jsonpath.internal.JsonReader;
import static com.jayway.jsonpath.Configuration.<API key>;
@Service
public class <API key> {
@Inject
private FileStoreService fileStoreService;
public void save(@NotNull <API key> newEntity, <API key> oldEntity, String entityPath) {
Assert.notNull(newEntity, "New content cannot be null");
Object json = <API key>().jsonProvider().parse(newEntity.getContent());
DocumentContext newContext = JsonPath.using(<API key>().addOptions(Option.AS_PATH_LIST)).parse(json);
Map<String, JSONArray> newPaths = getPathFilesMap(newContext, json);
if (newPaths == null) return; // content does not have any file field
if (oldEntity != null) {
Object oldJson = <API key>().jsonProvider().parse(oldEntity.getContent());
DocumentContext oldContext = JsonPath.using(<API key>().addOptions(Option.AS_PATH_LIST)).parse(oldJson);
Map<String, JSONArray> oldPaths = getPathFilesMap(oldContext, oldJson);
if (oldPaths != null) {
saveAndDelete(oldPaths, newPaths, entityPath);
} else {
// schema and definition now have files
newPaths.values().forEach(v -> saveFiles(v, entityPath));
}
} else {
newPaths.values().forEach(v -> saveFiles(v, entityPath));
}
cleanup(newPaths, newContext);
newEntity.setContent(newContext.jsonString());
}
public void deleteFiles(<API key> entity) {
Object json = <API key>().jsonProvider().parse(entity.getContent());
DocumentContext context = JsonPath.using(<API key>().addOptions(Option.AS_PATH_LIST)).parse(json);
DocumentContext reader =
new JsonReader(<API key>().addOptions(Option.REQUIRE_PROPERTIES)).parse(json);
try {
((JSONArray)context.read("$..obibaFiles")).stream()
.map(p -> (JSONArray) reader.read(p.toString()))
.flatMap(Collection::stream)
.forEach(file -> fileStoreService.delete(((LinkedHashMap)file).get("id").toString()));
} catch(<API key> e) {
}
}
/**
* Removes the fields with empty obibaFiles from content.
*
* @param newPaths
* @param newContext
*/
private void cleanup(Map<String, JSONArray> newPaths, DocumentContext newContext) {
newPaths.keySet().forEach(p -> {
if (newPaths.get(p).isEmpty()) {
newContext.delete(p.replace("['obibaFiles']", ""));
}
});
}
private void saveAndDelete(Map<String, JSONArray> oldPaths, Map<String, JSONArray> newPaths, String entityPath) {
newPaths.keySet().forEach(p -> {
if (oldPaths.containsKey(p)) {
saveAndDeleteFiles(oldPaths.get(p), newPaths.get(p), entityPath);
} else {
saveFiles(newPaths.get(p), entityPath);
}
});
}
private Map<String, JSONArray> getPathFilesMap(DocumentContext context, Object json) {
DocumentContext reader =
new JsonReader(<API key>().addOptions(Option.REQUIRE_PROPERTIES)).parse(json);
JSONArray paths = null;
try {
paths = context.read("$..obibaFiles");
} catch(<API key> e) {
return null;
}
return paths.stream().collect(Collectors.toMap(Object::toString, p -> (JSONArray) reader.read(p.toString())));
}
private Iterable<Object> saveAndDeleteFiles(JSONArray oldFiles, JSONArray newFiles, String entityPath) {
cleanFileJsonArrays(oldFiles, newFiles);
Iterable<Object> toDelete = Sets.difference(Sets.newHashSet(oldFiles), Sets.newHashSet(newFiles));
Iterable<Object> toSave = Sets.difference(Sets.newHashSet(newFiles), Sets.newHashSet(oldFiles));
toDelete.forEach(file -> fileStoreService.delete(((LinkedHashMap)file).get("id").toString()));
saveFiles(toSave, entityPath);
return toDelete;
}
private void cleanFileJsonArrays(JSONArray... arrays) {
if (arrays != null) {
Arrays.stream(arrays).forEach(s -> s.forEach(a -> {
if (a instanceof LinkedHashMap) {
LinkedHashMap<String, String> jsonMap = (LinkedHashMap<String, String>) a;
jsonMap.keySet().stream().filter(k -> k.contains("$")).collect(Collectors.toList()).forEach(jsonMap::remove);
}
}));
}
}
private void saveFiles(Iterable files, String entityPath) {
if(files != null) files.forEach(file -> {
LinkedHashMap map = (LinkedHashMap)file;
map.put("path", entityPath);
fileStoreService.save(map.get("id").toString());
});
}
}
|
// This file is part of cancer.
// cancer is free software: you can redistribute it and/or modify
// (at your option) any later version.
// cancer is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
use libc::c_void;
pub struct GList {
pub data: *mut c_void,
pub next: *mut GList,
pub prev: *mut GList,
}
extern "C" {
pub fn g_list_free(ptr: *mut GList);
pub fn g_object_unref(ptr: *mut c_void);
pub fn g_object_ref(ptr: *mut c_void) -> *mut c_void;
}
|
{% extends "base.html" %}
{% block content_title %}Cursos{% endblock %}
{% block box_title %}Detalhes Curso: <span class="label label-info">{{ object.pk }}</span>{% endblock %}
{% block box_body %}
<div class="page-header">
<a class="btn btn-large btn-default" title="Lista" href="{% url 'curso_home' %}"><i class="fa fa-list fa-1x"></i></a>
<a class="btn btn-large btn-warning" title="Editar" href="{% url 'curso_atualizar' object.pk %}"><i class="fa fa-edit fa-1x"></i></a>
<a class="btn btn-large btn-info" title="Imprimir" href="{% url 'imprime_curso' object.pk %}" ><i class="fa fa-print fa-1x"></i> </a>
<a class="btn btn-large btn-danger" title="Excluir" href="{% url 'curso_deletar' object.pk %}"><i class="fa fa-remove fa-1x"></i></a>
</div>
<div class="row">
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Descrição</h3>
<span class="pull-right clickable"></span>
</div>
<div class="panel-body">
{{ object.descricao }}
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Quantidade de Vagas</h3>
<span class="pull-right clickable"></span>
</div>
<div class="panel-body">
{{ object.quant_vaga }}
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Carga Horária</h3>
<span class="pull-right clickable"></span>
</div>
<div class="panel-body">
{{ object.carga_horaria }}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Semestre</h3>
<span class="pull-right clickable"></span>
</div>
<div class="panel-body">
{{ object.semestre }}
</div>
</div>
</div>
<div class="col-md-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Turno</h3>
<span class="pull-right clickable"></span>
</div>
<div class="panel-body">
{{ object.turno }}
</div>
</div>
</div>
<div class="col-md-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Pré-Requisito</h3>
<span class="pull-right clickable"></span>
</div>
<div class="panel-body">
{{ object.<API key> }}
</div>
</div>
</div>
<div class="col-md-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Ativo</h3>
<span class="pull-right clickable"></span>
</div>
<div class="panel-body">
{{ object.get_ativo_display }}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<div class="panel panel-info">
<div class="panel-heading clickable">
<h3 class="panel-title">
Quem Cadastrou</h3>
<span class="pull-right "></span>
</div>
<div class="panel-body">
{% if object.quem_criou %}
{{ object.quem_criou }}
{% else %}
Não Informado!
{% endif %}
</div>
</div>
</div>
<div class="col-md-2">
<div class="panel panel-info">
<div class="panel-heading clickable">
<h3 class="panel-title">
Data Cadastro</h3>
<span class="pull-right "></span>
</div>
<div class="panel-body">
{{ object.data_criacao|date:"d/m/Y"|default:"
</div>
</div>
</div>
<div class="col-md-2">
<div class="panel panel-info">
<div class="panel-heading clickable">
<h3 class="panel-title">
Hora Cadastro</h3>
<span class="pull-right "></span>
</div>
<div class="panel-body">
{{ object.hora_criacao|time:"h:i:s"|default:"
</div>
</div>
</div>
<div class="col-md-2">
<div class="panel panel-info">
<div class="panel-heading clickable">
<h3 class="panel-title">
Quem Alterou</h3>
<span class="pull-right "></span>
</div>
<div class="panel-body">
{% if object.quem_alterou %}
{{ object.quem_alterou }}
{% else %}
Não Informado!
{% endif %}
</div>
</div>
</div>
<div class="col-md-2">
<div class="panel panel-info">
<div class="panel-heading clickable">
<h3 class="panel-title">
Data Alteração</h3>
<span class="pull-right "></span>
</div>
<div class="panel-body">
{{ object.data_alteracao|date:"d/m/Y" }}
</div>
</div>
</div>
<div class="col-md-2">
<div class="panel panel-info">
<div class="panel-heading clickable">
<h3 class="panel-title">
Hora Alteração</h3>
<span class="pull-right "></span>
</div>
<div class="panel-body">
{{ object.hora_alteracao|time:"h:i:s" }}
</div>
</div>
</div>
</div>
{% endblock %}
|
Bitrix 17.0.9 Business Demo = <API key>
|
<?php /*%%SmartyHeaderCode:<API key>%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'<SHA1-like>' =>
array (
0 => '/var/www/html/admin240x2hjae/themes/default/template/page_header_toolbar.tpl',
1 => 1506184509,
2 => 'file',
),
),
'nocache_hash' => '<API key>',
'function' =>
array (
),
'variables' =>
array (
'title' => 0,
'<API key>' => 0,
'<API key>' => 0,
'current_tab_level' => 0,
'breadcrumbs2' => 0,
'toolbar_btn' => 0,
'k' => 0,
'table' => 0,
'btn' => 0,
'help_link' => 0,
'tab_modules_open' => 0,
'tab_modules_list' => 0,
'tabs' => 0,
'level_1' => 0,
'level_2' => 0,
'level_3' => 0,
'level_4' => 0,
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.19',
'unifunc' => '<API key>',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('<API key>')) {function <API key>($_smarty_tpl) {?>
<?php if (!isset($_smarty_tpl->tpl_vars['title']->value)&&isset($_smarty_tpl->tpl_vars['<API key>']->value)) {?>
<?php $_smarty_tpl->tpl_vars['title'] = new Smarty_variable($_smarty_tpl->tpl_vars['<API key>']->value, null, 0);?>
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['<API key>']->value)) {?>
<?php $_smarty_tpl->tpl_vars['toolbar_btn'] = new Smarty_variable($_smarty_tpl->tpl_vars['<API key>']->value, null, 0);?>
<?php }?>
<div class="bootstrap">
<div class="page-head <?php if (isset($_smarty_tpl->tpl_vars['current_tab_level']->value)&&$_smarty_tpl->tpl_vars['current_tab_level']->value==3) {?>with-tabs<?php }?>">
<h2 class="page-title">
<?php if (is_array($_smarty_tpl->tpl_vars['title']->value)) {?><?php echo preg_replace('!<[^>]*?>!', ' ', end($_smarty_tpl->tpl_vars['title']->value));?>
<?php } else { ?><?php echo preg_replace('!<[^>]*?>!', ' ', $_smarty_tpl->tpl_vars['title']->value);?>
<?php }?>
</h2>
<ul class="breadcrumb page-breadcrumb">
<?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']!='') {?>
<li class="<API key>">
<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']);?>
</li>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']!=''&&$_smarty_tpl->tpl_vars['breadcrumbs2']->value['container']['name']!=$_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']) {?>
<li class="breadcrumb-current">
<?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']!='') {?><a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']);?>
"><?php }?>
<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['name']);?>
<?php if ($_smarty_tpl->tpl_vars['breadcrumbs2']->value['tab']['href']!='') {?></a><?php }?>
</li>
<?php }?>
</ul>
<div class="page-bar toolbarBox">
<div class="btn-toolbar">
<a href="#" class="toolbar_btn dropdown-toolbar navbar-toggle" data-toggle="collapse"
data-target="#toolbar-nav"><i class="<API key>"></i>
<div><?php echo smartyTranslate(array('s'=>'Menu'),$_smarty_tpl);?>
</div>
</a>
<ul id="toolbar-nav" class="nav nav-pills pull-right collapse navbar-collapse">
<?php $_smarty_tpl->tpl_vars['btn'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['btn']->_loop = false;
$_smarty_tpl->tpl_vars['k'] = new Smarty_Variable;
$_from = $_smarty_tpl->tpl_vars['toolbar_btn']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['btn']->key => $_smarty_tpl->tpl_vars['btn']->value) {
$_smarty_tpl->tpl_vars['btn']->_loop = true;
$_smarty_tpl->tpl_vars['k']->value = $_smarty_tpl->tpl_vars['btn']->key;
?>
<?php if ($_smarty_tpl->tpl_vars['k']->value!='back'&&$_smarty_tpl->tpl_vars['k']->value!='modules-list') {?>
<li>
<a id="page-header-desc-<?php echo $_smarty_tpl->tpl_vars['table']->value;?>
-<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['imgclass'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['imgclass']);?>
<?php } else { ?><?php echo $_smarty_tpl->tpl_vars['k']->value;?>
<?php }?>"
class="toolbar_btn <?php if (isset($_smarty_tpl->tpl_vars['btn']->value['target'])&&$_smarty_tpl->tpl_vars['btn']->value['target']) {?> _blank<?php }?> pointer"<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['href'])) {?> href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['href']);?>
"<?php }?>
title="<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['help'])) {?><?php echo $_smarty_tpl->tpl_vars['btn']->value['help'];?>
<?php } else { ?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['desc']);?>
<?php }?>"<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['js'])&&$_smarty_tpl->tpl_vars['btn']->value['js']) {?> onclick="<?php echo $_smarty_tpl->tpl_vars['btn']->value['js'];?>
"<?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['modal_target'])&&$_smarty_tpl->tpl_vars['btn']->value['modal_target']) {?> data-target="<?php echo $_smarty_tpl->tpl_vars['btn']->value['modal_target'];?>
" data-toggle="modal"<?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['help'])) {?> data-toggle="tooltip" data-placement="bottom"<?php }?>>
<i
class="<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['icon'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['icon']);?>
<?php } else { ?>process-icon-<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['imgclass'])) {?><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['imgclass']);?>
<?php } else { ?><?php echo $_smarty_tpl->tpl_vars['k']->value;?>
<?php }?><?php }?><?php if (isset($_smarty_tpl->tpl_vars['btn']->value['class'])) {?> <?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['class']);?>
<?php }?>"></i>
<div<?php if (isset($_smarty_tpl->tpl_vars['btn']->value['force_desc'])&&$_smarty_tpl->tpl_vars['btn']->value['force_desc']==true) {?> class="locked"<?php }?>><?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['btn']->value['desc']);?>
</div>
</a>
</li>
<?php }?>
<?php } ?>
<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list'])) {?>
<li>
<a
id="page-header-desc-<?php echo $_smarty_tpl->tpl_vars['table']->value;?>
-<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'];?>
<?php } else { ?>modules-list<?php }?>"
class="toolbar_btn<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['class'])) {?> <?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['class'];?>
<?php }?><?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['target'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['target']) {?> _blank<?php }?>"
<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['href'])) {?>href="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['href'];?>
"<?php }?>
title="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['desc'];?>
"<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js']) {?> onclick="<?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['js'];?>
"<?php }?>>
<i
class="<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['icon'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['icon'];?>
<?php } else { ?>process-icon-<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'])) {?><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['imgclass'];?>
<?php } else { ?>modules-list<?php }?><?php }?>"></i>
<div<?php if (isset($_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['force_desc'])&&$_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['force_desc']==true) {?> class="locked"<?php }?>><?php echo $_smarty_tpl->tpl_vars['toolbar_btn']->value['modules-list']['desc'];?>
</div>
</a>
</li>
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['help_link']->value)) {?>
<li>
<a class="toolbar_btn btn-help" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['escape'][0][0]->smartyEscape($_smarty_tpl->tpl_vars['help_link']->value);?>
" title="<?php echo smartyTranslate(array('s'=>'Help'),$_smarty_tpl);?>
">
<i class="process-icon-help"></i>
<div><?php echo smartyTranslate(array('s'=>'Help'),$_smarty_tpl);?>
</div>
</a>
</li>
<?php }?>
</ul>
<?php if ((isset($_smarty_tpl->tpl_vars['tab_modules_open']->value)&&$_smarty_tpl->tpl_vars['tab_modules_open']->value)||isset($_smarty_tpl->tpl_vars['tab_modules_list']->value)) {?>
<script type="text/javascript">
//<![CDATA[
var modules_list_loaded = false;
<?php if (isset($_smarty_tpl->tpl_vars['tab_modules_open']->value)&&$_smarty_tpl->tpl_vars['tab_modules_open']->value) {?>
$(function () {
$('#<API key>').modal('show');
openModulesList();
});
<?php }?>
<?php if (isset($_smarty_tpl->tpl_vars['tab_modules_list']->value)) {?>
$('.<API key>').parent('a').unbind().bind('click', function (event) {
event.preventDefault();
$('#<API key>').modal('show');
openModulesList();
});
<?php }?>
</script>
<?php }?>
</div>
</div>
<?php if (isset($_smarty_tpl->tpl_vars['current_tab_level']->value)&&$_smarty_tpl->tpl_vars['current_tab_level']->value==3) {?>
<div class="page-head-tabs">
<?php $_smarty_tpl->tpl_vars['level_1'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_1']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['tabs']->value; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['level_1']->key => $_smarty_tpl->tpl_vars['level_1']->value) {
$_smarty_tpl->tpl_vars['level_1']->_loop = true;
?>
<?php $_smarty_tpl->tpl_vars['level_2'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_2']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['level_1']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['level_2']->key => $_smarty_tpl->tpl_vars['level_2']->value) {
$_smarty_tpl->tpl_vars['level_2']->_loop = true;
?>
<?php $_smarty_tpl->tpl_vars['level_3'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_3']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['level_2']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['level_3']->key => $_smarty_tpl->tpl_vars['level_3']->value) {
$_smarty_tpl->tpl_vars['level_3']->_loop = true;
?>
<?php if ($_smarty_tpl->tpl_vars['level_3']->value['current']) {?>
<?php $_smarty_tpl->tpl_vars['level_4'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['level_4']->_loop = false;
$_from = $_smarty_tpl->tpl_vars['level_3']->value['sub_tabs']; if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');}
foreach ($_from as $_smarty_tpl->tpl_vars['level_4']->key => $_smarty_tpl->tpl_vars['level_4']->value) {
$_smarty_tpl->tpl_vars['level_4']->_loop = true;
?>
<a href="<?php echo $_smarty_tpl->tpl_vars['level_4']->value['href'];?>
" <?php if ($_smarty_tpl->tpl_vars['level_4']->value['current']) {?>class="current"<?php }?>><?php echo $_smarty_tpl->tpl_vars['level_4']->value['name'];?>
</a>
<?php } ?>
<?php }?>
<?php } ?>
<?php } ?>
<?php } ?>
</div>
<?php }?>
</div>
<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h'=>'displayDashboardTop'),$_smarty_tpl);?>
</div>
<?php }} ?>
|
// ResInsight is free software: you can redistribute it and/or modify
// (at your option) any later version.
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// FITNESS FOR A PARTICULAR PURPOSE.
// for more details.
#pragma once
#include "RiaDefines.h"
#include <QString>
class <API key>
{
public:
<API key>( const QString& <API key>,
const QString& fractureName,
const QString& <API key>,
double measuredDepth );
void setData( double trans, size_t connCount, double area );
void <API key>( double width, double conductivity );
void <API key>( double height, double halfLength );
void <API key>( double permeability );
void setUnitSystem( RiaDefines::EclipseUnitSystem unitSystem );
void <API key>( bool <API key>,
const QString& timeStepString,
const QString& wbhpString,
double userWBHP,
double actualWBHP,
double minPressureDrop,
double maxPressureDrop );
QString <API key>() const;
QString fractureName() const;
QString <API key>() const;
RiaDefines::EclipseUnitSystem unitSystem() const;
double transmissibility() const;
size_t connectionCount() const;
double fcd() const;
double area() const;
double kfwf() const;
double kf() const;
double wf() const;
double xf() const;
double h() const;
double km() const;
double kmxf() const;
bool <API key>() const;
QString <API key>() const;
QString <API key>() const;
double <API key>() const;
double <API key>() const;
double <API key>() const;
double <API key>() const;
bool operator<( const <API key>& other ) const;
private:
RiaDefines::EclipseUnitSystem m_unitSystem;
QString <API key>;
QString m_wellPathFracture;
QString <API key>;
double m_mesuredDepth;
double m_transmissibility;
size_t m_connectionCount;
double m_area;
double m_kfwf;
double m_kf;
double m_wf;
double m_xf;
double m_h;
double m_km;
bool <API key>;
QString <API key>;
QString <API key>;
double <API key>;
double <API key>;
double <API key>;
double <API key>;
};
|
#include <stdio.h>
#include <string>
#include <iostream>
#include <cppunit/TestCase.h>
#include <tulip/TulipPluginHeaders.h>
using namespace std;
class Test2 : public tlp::BooleanAlgorithm {
public:
PLUGININFORMATION("Test2","Jezequel","03/11/2004","0","1.0", "")
Test2(tlp::PluginContext* context) : tlp::BooleanAlgorithm(context) {}
~Test2() {}
bool run() {
return true;
}
};
PLUGIN(Test2)
|
#include <opm/parser/eclipse/EclipseState/Schedule/TimeMap.hpp>
#include <opm/parser/eclipse/EclipseState/Schedule/RFTConfig.hpp>
namespace Opm {
RFTConfig::RFTConfig(const TimeMap& time_map) :
tm(time_map)
{
}
bool RFTConfig::rft(const std::string& well_name, std::size_t report_step) const {
if (report_step >= this->tm.size())
throw std::invalid_argument("Invalid ");
const auto well_iter = this->well_open.find(well_name);
if (well_iter != this->well_open.end()) {
// A general "Output RFT when the well is opened" has been configured with WRFT
if (this->well_open_rft_time.first && this->well_open_rft_time.second <= report_step) {
if (well_iter->second == report_step)
return true;
}
// A FOPN setting has been configured with the WRFTPLT keyword
if (this->well_open_rft_name.count(well_name) > 0) {
if (well_iter->second == report_step)
return true;
}
}
if (this->rft_config.count(well_name) == 0)
return false;
auto rft_pair = this->rft_config.at(well_name)[report_step];
if (rft_pair.first == RFTConnections::YES)
return (rft_pair.second == report_step);
if (rft_pair.first == RFTConnections::NO)
return false;
if (rft_pair.first == RFTConnections::REPT)
return true;
if (rft_pair.first == RFTConnections::TIMESTEP)
return true;
return false;
}
bool RFTConfig::plt(const std::string& well_name, std::size_t report_step) const {
if (report_step >= this->tm.size())
throw std::invalid_argument("Invalid ");
if (this->plt_config.count(well_name) == 0)
return false;
auto plt_pair = this->plt_config.at(well_name)[report_step];
if (plt_pair.first == PLTConnections::YES)
return (plt_pair.second == report_step);
if (plt_pair.first == PLTConnections::NO)
return false;
if (plt_pair.first == PLTConnections::REPT)
return true;
if (plt_pair.first == PLTConnections::TIMESTEP)
return true;
return false;
}
void RFTConfig::updateRFT(const std::string& well_name, std::size_t report_step, RFTConnections::RFTEnum value) {
if (value == RFTConnections::FOPN)
this->setWellOpenRFT(well_name);
else {
if (this->rft_config.count(well_name) == 0) {
auto state = DynamicState<std::pair<RFTConnections::RFTEnum, std::size_t>>(this->tm, std::make_pair(RFTConnections::NO, 0));
this->rft_config.emplace( well_name, state );
}
this->rft_config.at(well_name).update(report_step, std::make_pair(value, report_step));
}
}
void RFTConfig::updatePLT(const std::string& well_name, std::size_t report_step, PLTConnections::PLTEnum value) {
if (this->plt_config.count(well_name) == 0) {
auto state = DynamicState<std::pair<PLTConnections::PLTEnum, std::size_t>>(this->tm, std::make_pair(PLTConnections::NO, 0));
this->plt_config.emplace( well_name, state );
}
this->plt_config.at(well_name).update(report_step, std::make_pair(value, report_step));
}
bool RFTConfig::getWellOpenRFT(const std::string& well_name, std::size_t report_step) const {
if (this->well_open_rft_name.count(well_name) > 0)
return true;
return (this->well_open_rft_time.first && this->well_open_rft_time.second <= report_step);
}
void RFTConfig::setWellOpenRFT(std::size_t report_step) {
this->well_open_rft_time = std::make_pair(true, report_step);
}
void RFTConfig::setWellOpenRFT(const std::string& well_name) {
this->well_open_rft_name.insert( well_name );
}
void RFTConfig::addWellOpen(const std::string& well_name, std::size_t report_step) {
if (this->well_open.count(well_name) == 0)
this->well_open[well_name] = report_step;
}
std::size_t RFTConfig::firstRFTOutput() const {
std::size_t first_rft = this->tm.size();
if (this->well_open_rft_time.first) {
// The WRFT keyword has been used to request RFT output at well open for all wells.
std::size_t rft_time = this->well_open_rft_time.second;
for (const auto& rft_pair : this->well_open) {
if (rft_pair.second >= rft_time)
first_rft = std::min(first_rft, rft_pair.second);
}
} else {
// Go through the individual wells and look for first open settings
for (const auto& rft_pair : this->well_open)
first_rft = std::min(first_rft, rft_pair.second);
}
for (const auto& rft_pair : this->plt_config) {
const auto& dynamic_state = rft_pair.second;
auto pred = [] (const std::pair<PLTConnections::PLTEnum, std::size_t>& ) { return false; };
int this_first_rft = dynamic_state.find_if(pred);
if (this_first_rft >= 0)
first_rft = std::min(first_rft, static_cast<std::size_t>(this_first_rft));
}
return first_rft;
}
bool RFTConfig::active(std::size_t report_step) const {
for (const auto& rft_pair : this->rft_config) {
if (this->rft(rft_pair.first, report_step))
return true;
}
for (const auto& plt_pair : this->plt_config) {
if (this->rft(plt_pair.first, report_step))
return true;
}
return false;
}
}
|
"""Test class for Custom Sync UI
:Requirement: Sync
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: Repositories
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_string
from nailgun import entities
from robottelo import manifests
from robottelo.api.utils import <API key>
from robottelo.constants import (
DISTRO_RHEL6, DISTRO_RHEL7,
DOCKER_REGISTRY_HUB,
<API key>,
FAKE_1_YUM_REPO,
<API key>,
REPOS,
REPOSET,
REPO_TYPE,
PRDS,
)
from robottelo.decorators import (
fixture,
run_in_one_thread,
skip_if_not_set,
tier2,
upgrade,
skip_if_bug_open,
)
from robottelo.decorators.host import skip_if_os
from robottelo.products import (
<API key>,
RHELCloudFormsTools,
<API key>,
)
@fixture(scope='module')
def module_org():
return entities.Organization().create()
@fixture(scope='module')
def <API key>(module_org):
return entities.Product(organization=module_org).create()
@fixture(scope='module')
def <API key>():
org = entities.Organization().create()
manifests.<API key>(org.id)
return org
@tier2
def <API key>(session, <API key>):
"""Create Content Custom Sync with minimal input parameters
:id: <API key>
:expectedresults: Sync procedure is successful
:CaseImportance: Critical
"""
repo = entities.Repository(
url=FAKE_1_YUM_REPO, product=<API key>).create()
with session:
results = session.sync_status.synchronize([
(<API key>.name, repo.name)])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@run_in_one_thread
@skip_if_not_set('fake_manifest')
@tier2
@upgrade
def <API key>(session, <API key>):
"""Create Content RedHat Sync with two repos.
:id: <API key>
:expectedresults: Sync procedure for RedHat Repos is successful
:CaseLevel: Integration
"""
repos = (
<API key>(cdn=True),
RHELCloudFormsTools(cdn=True)
)
distros = [DISTRO_RHEL7, DISTRO_RHEL6]
repo_collections = [
<API key>(distro=distro, repositories=[repo])
for distro, repo in zip(distros, repos)
]
for repo_collection in repo_collections:
repo_collection.setup(<API key>.id, synchronize=False)
repo_paths = [
(
repo.repo_data['product'],
repo.repo_data.get('releasever'),
repo.repo_data.get('arch'),
repo.repo_data['name'],
)
for repo in repos
]
with session:
session.organization.select(org_name=<API key>.name)
results = session.sync_status.synchronize(repo_paths)
assert len(results) == len(repo_paths)
assert all([result == 'Syncing Complete.' for result in results])
@skip_if_bug_open('bugzilla', 1625783)
@skip_if_os('RHEL6')
@tier2
@upgrade
def <API key>(session, <API key>):
"""Create custom ostree repository and sync it.
:id: <API key>
:expectedresults: ostree repo should be synced successfully
:CaseLevel: Integration
"""
repo = entities.Repository(
content_type='ostree',
url=<API key>,
product=<API key>,
unprotected=False,
).create()
with session:
results = session.sync_status.synchronize([
(<API key>.name, repo.name)])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@run_in_one_thread
@skip_if_bug_open('bugzilla', 1625783)
@skip_if_os('RHEL6')
@skip_if_not_set('fake_manifest')
@tier2
@upgrade
def <API key>(session, <API key>):
"""Sync CDN based ostree repository.
:id: <API key>
:Steps:
1. Import a valid manifest
2. Enable the OStree repo and sync it
:expectedresults: ostree repo should be synced successfully from CDN
:CaseLevel: Integration
"""
<API key>(
basearch=None,
org_id=<API key>.id,
product=PRDS['rhah'],
repo=REPOS['rhaht']['name'],
reposet=REPOSET['rhaht'],
releasever=None,
)
with session:
session.organization.select(org_name=<API key>.name)
results = session.sync_status.synchronize([
(PRDS['rhah'], REPOS['rhaht']['name'])])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@tier2
@upgrade
def <API key>(session, module_org):
"""Create custom docker repo and sync it via the sync status page.
:id: <API key>
:expectedresults: Sync procedure for specific docker repository is
successful
:CaseLevel: Integration
"""
product = entities.Product(organization=module_org).create()
repo_name = gen_string('alphanumeric')
with session:
session.repository.create(
product.name,
{'name': repo_name,
'repo_type': REPO_TYPE['docker'],
'repo_content.upstream_url': DOCKER_REGISTRY_HUB,
'repo_content.upstream_repo_name': <API key>}
)
assert session.repository.search(product.name, repo_name)[0]['Name'] == repo_name
result = session.sync_status.synchronize([(product.name, repo_name)])
assert result[0] == 'Syncing Complete.'
|
<?php
$L['Alerts_Title'] = 'Allarmi personalizzati';
$L['Alerts_Description'] = 'Allarmi personalizzati da ${0}';
$L['Alerts_header'] = 'Allarmi personalizzati da ${0}';
$L['<API key>'] = 'Configura download automatico';
$L['Update_Alerts_label'] = 'Scarica allarmi personalizzati';
$L['Refresh_label'] = 'Download configurazioni allarmi';
$L['last_update_label'] = 'Ultimo aggiornamento';
$L['Type_label'] = 'Allarme';
$L['Instance_label'] = 'Parametro';
$L['Threshold_label'] = 'Soglia';
$L['<API key>'] = 'Abilita download automatico degli allarmi personalizzati (raccomandato)';
$L['<API key>'] = 'Disabilita download automatico degli allarmi personalizzati';
$L['df_label'] = 'Spazio disco libero';
$L['load_label'] = 'Carico CPU';
$L['ping_droprate_label'] = 'Tasso di pacchetti persi';
$L['ping_label'] = 'Latenza ping';
$L['swap_label'] = 'Swap libero';
$L['Partition_label'] = 'Partizione';
$L['Host_label'] = 'Host';
$L['Intro_label'] = 'Ogni server ha una lista predefinita di allarmi di default. Solo alcuni possono essere personalizzati. <br/> Questa pagina mostra solo gli allarmi personalizzati su <a href="${0}">${0}</a>.';
$L['Download_label'] = 'Di default, le modifiche agli allarmi fatte su <a href="${0}">${0}</a> sono applicate ogni notte. <br/> Il tasto "Scarica allarmi personalizzati" scarica la configurazione subito.';
$L['max_fail_label'] = 'Critica sopra';
$L['min_fail_label'] = 'Critica sotto';
$L['max_warn_label'] = 'Media sopra';
$L['min_warn_label'] = 'Media sotto';
|
// dependencies
define(['mvc/ui/ui-tabs', 'mvc/ui/ui-misc', 'mvc/ui/ui-portlet', 'utils/utils',
'plugin/models/chart', 'plugin/models/group',
'plugin/views/group', 'plugin/views/settings', 'plugin/views/types'],
function(Tabs, Ui, Portlet, Utils, Chart, Group, GroupView, SettingsView, TypesView) {
/**
* The charts editor holds the tabs for selecting chart types, chart configuration
* and data group selections.
*/
return Backbone.View.extend({
// initialize
initialize: function(app, options){
// link this
var self = this;
// link application
this.app = app;
// get current chart object
this.chart = this.app.chart;
// message element
this.message = new Ui.Message();
// create portlet
this.portlet = new Portlet.View({
icon : 'fa-bar-chart-o',
title: 'Editor',
operations : {
'save' : new Ui.ButtonIcon({
icon : 'fa-save',
tooltip : 'Draw Chart',
title : 'Draw',
onclick : function() {
self._saveChart();
}
}),
'back' : new Ui.ButtonIcon({
icon : 'fa-caret-left',
tooltip : 'Return to Viewer',
title : 'Cancel',
onclick : function() {
// show viewer/viewport
self.app.go('viewer');
// reset chart
self.app.storage.load();
}
})
}
});
// grid with chart types
this.types = new TypesView(app, {
onchange : function(chart_type) {
// get chart definition
var chart_definition = self.app.types.get(chart_type);
if (!chart_definition) {
console.debug('FAILED - Editor::onchange() - Chart type not supported.');
}
// parse chart definition
self.chart.definition = chart_definition;
// reset type relevant chart content
self.chart.settings.clear();
// update chart type
self.chart.set({type: chart_type});
// set modified flag
self.chart.set('modified', true);
// log
console.debug('Editor::onchange() - Switched chart type.');
},
ondblclick : function(chart_id) {
self._saveChart();
}
});
// tabs
this.tabs = new Tabs.View({
title_new : 'Add Data',
onnew : function() {
var group = self._addGroupModel();
self.tabs.show(group.id);
}
});
// main/default tab
// construct elements
this.title = new Ui.Input({
placeholder: 'Chart title',
onchange: function() {
self.chart.set('title', self.title.value());
}
});
// append element
var $main = $('<div/>');
$main.append(Utils.wrap((new Ui.Label({ title : 'Provide a chart title:'})).$el));
$main.append(Utils.wrap(this.title.$el));
$main.append(Utils.wrap(this.types.$el));
// add tab
this.tabs.add({
id : 'main',
title : 'Start',
$el : $main
});
// main settings tab
// create settings view
this.settings = new SettingsView(this.app);
// add tab
this.tabs.add({
id : 'settings',
title : 'Configuration',
$el : this.settings.$el
});
// append tabs
this.portlet.append(this.message.$el);
this.portlet.append(this.tabs.$el);
// elements
this.setElement(this.portlet.$el);
// hide back button on startup
this.tabs.hideOperation('back');
// chart events
var self = this;
this.chart.on('change:title', function(chart) {
self._refreshTitle();
});
this.chart.on('change:type', function(chart) {
self.types.value(chart.get('type'));
});
this.chart.on('reset', function(chart) {
self._resetChart();
});
this.app.chart.on('redraw', function(chart) {
self.portlet.showOperation('back');
});
// groups events
this.app.chart.groups.on('add', function(group) {
self._addGroup(group);
});
this.app.chart.groups.on('remove', function(group) {
self._removeGroup(group);
});
this.app.chart.groups.on('reset', function(group) {
self._removeAllGroups();
});
this.app.chart.groups.on('change:key', function(group) {
self._refreshGroupKey();
});
// reset
this._resetChart();
},
// hide
show: function() {
this.$el.show();
},
// hide
hide: function() {
this.$el.hide();
},
// refresh title
_refreshTitle: function() {
var title = this.chart.get('title');
this.portlet.title(title);
this.title.value(title);
},
// refresh group
_refreshGroupKey: function() {
var self = this;
var counter = 0;
this.chart.groups.each(function(group) {
var title = group.get('key', '');
if (title == '') {
title = 'Data label';
}
self.tabs.title(group.id, ++counter + ': ' + title);
});
},
// add group model
_addGroupModel: function() {
var group = new Group({
id : Utils.uuid()
});
this.chart.groups.add(group);
return group;
},
// add group tab
_addGroup: function(group) {
// link this
var self = this;
// create view
var group_view = new GroupView(this.app, {group: group});
// add new tab
this.tabs.add({
id : group.id,
$el : group_view.$el,
ondel : function() {
self.chart.groups.remove(group.id);
}
});
// update titles
this._refreshGroupKey();
// reset
this.chart.set('modified', true);
},
// remove group
_removeGroup: function(group) {
this.tabs.del(group.id);
// update titles
this._refreshGroupKey();
// reset
this.chart.set('modified', true);
},
// remove group
_removeAllGroups: function(group) {
this.tabs.delRemovable();
},
// reset
_resetChart: function() {
// reset chart details
this.chart.set('id', Utils.uuid());
this.chart.set('type', 'nvd3_bar');
this.chart.set('dataset_id', this.app.options.config.dataset_id);
this.chart.set('title', 'New Chart');
// reset back button
this.portlet.hideOperation('back');
},
// create chart
_saveChart: function() {
// update chart data
this.chart.set({
type : this.types.value(),
title : this.title.value(),
date : Utils.time()
});
// make sure that at least one data group is available
if (this.chart.groups.length == 0) {
this.message.update({message: 'Please select data columns before drawing the chart.'});
var group = this._addGroupModel();
this.tabs.show(group.id);
return;
}
// make sure that all necessary columns are assigned
var self = this;
var valid = true;
var chart_def = this.chart.definition;
this.chart.groups.each(function(group) {
if (!valid) {
return;
}
for (var key in chart_def.columns) {
if (group.attributes[key] == 'null') {
self.message.update({status: 'danger', message: 'This chart type requires column types not found in your tabular file.'});
self.tabs.show(group.id);
valid = false;
return;
}
}
});
// validate if columns have been selected
if (!valid) {
return;
}
// show viewport
this.app.go('viewer');
// wait until chart is ready
var self = this;
this.app.deferred.execute(function() {
// save
self.app.storage.save();
// trigger redraw
self.chart.trigger('redraw');
});
}
});
});
|
{% extends "jblux/base.html" %}
{% block title %}New Character{% endblock %}
{% block content %}
<form method="post" action="{% url jblux_django.jblux.views.new_character %}">
{% csrf_token %}
{% include "jblux/base_form.html" %}
<p><input type="submit" value="Create Character" /></p>
</form>
{% endblock %}
|
#include "canvas.h"
Canvas::Canvas()
: Entity()
{
this->init(16);
}
Canvas::Canvas(int pixelsize)
: Entity()
{
this->init(pixelsize);
}
Canvas::~Canvas()
{
}
void Canvas::update(float deltaTime)
{
}
void Canvas::init(int pixelsize)
{
this->position = Point2(SWIDTH/2, SHEIGHT/2);
this->scale = Point2(pixelsize, pixelsize);
// width, height, bitdepth, filter, wrap
PixelBuffer tmp = PixelBuffer(SWIDTH/pixelsize, SHEIGHT/pixelsize, 4, 0, 0);
this->addDynamicSprite(&tmp);
// get the pixels from the texture and make the framebuffer point to it
this->_framebuffer = this->sprite()->texture()->pixels();
this->_width = SWIDTH / pixelsize;
this->_height = SHEIGHT / pixelsize;
backgroundcolor = RGBAColor(0, 0, 0, 0);
this->fill(backgroundcolor);
}
void Canvas::setPixel(int x, int y, RGBAColor color)
{
this->_framebuffer->setPixel(x, y, color);
}
RGBAColor Canvas::getPixel(int x, int y)
{
return this->_framebuffer->getPixel(x, y);
}
void Canvas::clearPixel(int x, int y)
{
this->_framebuffer->setPixel(x, y, backgroundcolor);
}
void Canvas::fill(RGBAColor color)
{
// fill framebuffer with color
for (long y=0; y<_framebuffer->height; y++) {
for (long x=0; x<_framebuffer->width; x++) {
this->setPixel(x, y, color);
}
}
}
void Canvas::drawSprite(const PixelSprite& spr)
{
size_t s = spr.pixels.size();
for (size_t i = 0; i < s; i++) {
this->setPixel(spr.pixels[i].position.x + spr.position.x, spr.pixels[i].position.y + spr.position.y, spr.pixels[i].color);
}
}
void Canvas::clearSprite(const PixelSprite& spr)
{
size_t s = spr.pixels.size();
for (size_t i = 0; i < s; i++) {
this->clearPixel(spr.pixels[i].position.x + spr.position.x, spr.pixels[i].position.y + spr.position.y);
}
}
void Canvas::drawLine(Vector2f from, Vector2f to, RGBAColor color) {
float x0 = from.x;
float y0 = from.y;
float x1 = to.x;
float y1 = to.y;
bool steep = false;
if (std::abs(x0-x1) < std::abs(y0-y1)) {
std::swap(x0, y0);
std::swap(x1, y1);
steep = true;
}
if (x0 > x1) {
std::swap(x0, x1);
std::swap(y0, y1);
}
int dx = x1-x0;
int dy = y1-y0;
int derror2 = std::abs(dy)*2;
int error2 = 0;
int y = y0;
for (int x = x0; x <= x1; x++) {
if (steep) {
this->setPixel(y, x, color);
} else {
this->setPixel(x, y, color);
}
error2 += derror2;
if (error2 > dx) {
y += (y1 > y0 ? 1 : -1);
error2 -= dx*2;
}
}
}
|
#!/usr/bin/env python
from keyring import get_password
from boto.iam.connection import IAMConnection
import lib.LoadBotoConfig as BotoConfig
from sys import exit
envs = ['dev', 'qa', 'staging', 'demo', 'prod']
for env in envs:
id = BotoConfig.config.get(env, 'aws_access_key_id')
key = get_password(BotoConfig.config.get(env, 'keyring'), id)
conn = IAMConnection(aws_access_key_id=id, <API key>=key)
print(conn.get_signin_url())
|
<?php
namespace App\Services\Geografico\ObterOsc;
use App\Services\BaseService;
use App\Dao\Geografico\GeolocalizacaoDao;
class Service extends BaseService{
public function executar(){
$conteudoRequisicao = $this->requisicao->getConteudo();
$modelo = new Model($conteudoRequisicao);
if($modelo->obterCodigoResposta() === 200){
$requisicao = $modelo->obterRequisicao();
$geolocalizacaoOsc = (new GeolocalizacaoDao())-><API key>($requisicao->id_osc);
if($geolocalizacaoOsc){
$this->resposta->prepararResposta($geolocalizacaoOsc, 200);
}else{
$this->resposta->prepararResposta(null, 204);
}
}else{
$this->resposta->prepararResposta($modelo-><API key>(), $modelo->obterCodigoResposta());
}
}
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
// This Source Code Form is subject to the terms of the Mozilla
// with this file, You can obtain one at the mozilla.org home page
#ifndef <API key>
#define <API key>
#include "SkylineStorage.h"
#include "SkylineMatrixBase.h"
namespace Eigen {
/** \ingroup Skyline_Module
*
* \class SkylineMatrix
*
* \brief The main skyline matrix class
*
* This class implements a skyline matrix using the very uncommon storage
* scheme.
*
* \param _Scalar the scalar type, i.e. the type of the coefficients
* \param _Options Union of bit flags controlling the storage scheme. Currently the only possibility
* is RowMajor. The default is 0 which means column-major.
*
*
*/
namespace internal {
template<typename _Scalar, int _Options>
struct traits<SkylineMatrix<_Scalar, _Options> > {
typedef _Scalar Scalar;
typedef Sparse StorageKind;
enum {
RowsAtCompileTime = Dynamic,
ColsAtCompileTime = Dynamic,
<API key> = Dynamic,
<API key> = Dynamic,
Flags = SkylineBit | _Options,
CoeffReadCost = NumTraits<Scalar>::ReadCost,
};
};
}
template<typename _Scalar, int _Options>
class SkylineMatrix
: public SkylineMatrixBase<SkylineMatrix<_Scalar, _Options> > {
public:
<API key>(SkylineMatrix)
<API key>(SkylineMatrix, +=)
<API key>(SkylineMatrix, -=)
using Base::IsRowMajor;
protected:
typedef SkylineMatrix<Scalar, (Flags&~RowMajorBit) | (IsRowMajor ? RowMajorBit : 0) > <API key>;
Index m_outerSize;
Index m_innerSize;
public:
Index* m_colStartIndex;
Index* m_rowStartIndex;
SkylineStorage<Scalar> m_data;
public:
inline Index rows() const {
return IsRowMajor ? m_outerSize : m_innerSize;
}
inline Index cols() const {
return IsRowMajor ? m_innerSize : m_outerSize;
}
inline Index innerSize() const {
return m_innerSize;
}
inline Index outerSize() const {
return m_outerSize;
}
inline Index upperNonZeros() const {
return m_data.upperSize();
}
inline Index lowerNonZeros() const {
return m_data.lowerSize();
}
inline Index upperNonZeros(Index j) const {
return m_colStartIndex[j + 1] - m_colStartIndex[j];
}
inline Index lowerNonZeros(Index j) const {
return m_rowStartIndex[j + 1] - m_rowStartIndex[j];
}
inline const Scalar* _diagPtr() const {
return &m_data.diag(0);
}
inline Scalar* _diagPtr() {
return &m_data.diag(0);
}
inline const Scalar* _upperPtr() const {
return &m_data.upper(0);
}
inline Scalar* _upperPtr() {
return &m_data.upper(0);
}
inline const Scalar* _lowerPtr() const {
return &m_data.lower(0);
}
inline Scalar* _lowerPtr() {
return &m_data.lower(0);
}
inline const Index* _upperProfilePtr() const {
return &m_data.upperProfile(0);
}
inline Index* _upperProfilePtr() {
return &m_data.upperProfile(0);
}
inline const Index* _lowerProfilePtr() const {
return &m_data.lowerProfile(0);
}
inline Index* _lowerProfilePtr() {
return &m_data.lowerProfile(0);
}
inline Scalar coeff(Index row, Index col) const {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
if (outer == inner)
return this->m_data.diag(outer);
if (IsRowMajor) {
if (inner > outer) //upper matrix
{
const Index minOuterIndex = inner - m_data.upperProfile(inner);
if (outer >= minOuterIndex)
return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
else
return Scalar(0);
}
if (inner < outer) //lower matrix
{
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
if (inner >= minInnerIndex)
return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
else
return Scalar(0);
}
return m_data.upper(m_colStartIndex[inner] + outer - inner);
} else {
if (outer > inner) //upper matrix
{
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
if (outer <= maxOuterIndex)
return this->m_data.upper(m_colStartIndex[inner] + (outer - inner));
else
return Scalar(0);
}
if (outer < inner) //lower matrix
{
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
if (inner <= maxInnerIndex)
return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer));
else
return Scalar(0);
}
}
}
inline Scalar& coeffRef(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
if (outer == inner)
return this->m_data.diag(outer);
if (IsRowMajor) {
if (col > row) //upper matrix
{
const Index minOuterIndex = inner - m_data.upperProfile(inner);
eigen_assert(outer >= minOuterIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
}
if (col < row) //lower matrix
{
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
eigen_assert(inner >= minInnerIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
}
} else {
if (outer > inner) //upper matrix
{
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
eigen_assert(outer <= maxOuterIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.upper(m_colStartIndex[inner] + (outer - inner));
}
if (outer < inner) //lower matrix
{
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
eigen_assert(inner <= maxInnerIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer));
}
}
}
inline Scalar coeffDiag(Index idx) const {
eigen_assert(idx < outerSize());
eigen_assert(idx < innerSize());
return this->m_data.diag(idx);
}
inline Scalar coeffLower(Index row, Index col) const {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
if (inner >= minInnerIndex)
return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
else
return Scalar(0);
} else {
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
if (inner <= maxInnerIndex)
return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer));
else
return Scalar(0);
}
}
inline Scalar coeffUpper(Index row, Index col) const {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minOuterIndex = inner - m_data.upperProfile(inner);
if (outer >= minOuterIndex)
return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
else
return Scalar(0);
} else {
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
if (outer <= maxOuterIndex)
return this->m_data.upper(m_colStartIndex[inner] + (outer - inner));
else
return Scalar(0);
}
}
inline Scalar& coeffRefDiag(Index idx) {
eigen_assert(idx < outerSize());
eigen_assert(idx < innerSize());
return this->m_data.diag(idx);
}
inline Scalar& coeffRefLower(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
eigen_assert(inner >= minInnerIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
} else {
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
eigen_assert(inner <= maxInnerIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.lower(m_rowStartIndex[outer] + (inner - outer));
}
}
inline bool coeffExistLower(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
return inner >= minInnerIndex;
} else {
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
return inner <= maxInnerIndex;
}
}
inline Scalar& coeffRefUpper(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minOuterIndex = inner - m_data.upperProfile(inner);
eigen_assert(outer >= minOuterIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
} else {
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
eigen_assert(outer <= maxOuterIndex && "you try to acces a coeff that do not exist in the storage");
return this->m_data.upper(m_colStartIndex[inner] + (outer - inner));
}
}
inline bool coeffExistUpper(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
eigen_assert(inner != outer);
if (IsRowMajor) {
const Index minOuterIndex = inner - m_data.upperProfile(inner);
return outer >= minOuterIndex;
} else {
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
return outer <= maxOuterIndex;
}
}
protected:
public:
class InnerUpperIterator;
class InnerLowerIterator;
class OuterUpperIterator;
class OuterLowerIterator;
/** Removes all non zeros */
inline void setZero() {
m_data.clear();
memset(m_colStartIndex, 0, (m_outerSize + 1) * sizeof (Index));
memset(m_rowStartIndex, 0, (m_outerSize + 1) * sizeof (Index));
}
/** \returns the number of non zero coefficients */
inline Index nonZeros() const {
return m_data.diagSize() + m_data.upperSize() + m_data.lowerSize();
}
/** Preallocates \a reserveSize non zeros */
inline void reserve(Index reserveSize, Index reserveUpperSize, Index reserveLowerSize) {
m_data.reserve(reserveSize, reserveUpperSize, reserveLowerSize);
}
/** \returns a reference to a novel non zero coefficient with coordinates \a row x \a col.
*
* \warning This function can be extremely slow if the non zero coefficients
* are not inserted in a coherent order.
*
* After an insertion session, you should call the finalize() function.
*/
EIGEN_DONT_INLINE Scalar & insert(Index row, Index col) {
const Index outer = IsRowMajor ? row : col;
const Index inner = IsRowMajor ? col : row;
eigen_assert(outer < outerSize());
eigen_assert(inner < innerSize());
if (outer == inner)
return m_data.diag(col);
if (IsRowMajor) {
if (outer < inner) //upper matrix
{
Index minOuterIndex = 0;
minOuterIndex = inner - m_data.upperProfile(inner);
if (outer < minOuterIndex) //The value does not yet exist
{
const Index previousProfile = m_data.upperProfile(inner);
m_data.upperProfile(inner) = inner - outer;
const Index bandIncrement = m_data.upperProfile(inner) - previousProfile;
//shift data stored after this new one
const Index stop = m_colStartIndex[cols()];
const Index start = m_colStartIndex[inner];
for (Index innerIdx = stop; innerIdx >= start; innerIdx
m_data.upper(innerIdx + bandIncrement) = m_data.upper(innerIdx);
}
for (Index innerIdx = cols(); innerIdx > inner; innerIdx
m_colStartIndex[innerIdx] += bandIncrement;
}
//zeros new data
memset(this->_upperPtr() + start, 0, (bandIncrement - 1) * sizeof (Scalar));
return m_data.upper(m_colStartIndex[inner]);
} else {
return m_data.upper(m_colStartIndex[inner] + outer - (inner - m_data.upperProfile(inner)));
}
}
if (outer > inner) //lower matrix
{
const Index minInnerIndex = outer - m_data.lowerProfile(outer);
if (inner < minInnerIndex) //The value does not yet exist
{
const Index previousProfile = m_data.lowerProfile(outer);
m_data.lowerProfile(outer) = outer - inner;
const Index bandIncrement = m_data.lowerProfile(outer) - previousProfile;
//shift data stored after this new one
const Index stop = m_rowStartIndex[rows()];
const Index start = m_rowStartIndex[outer];
for (Index innerIdx = stop; innerIdx >= start; innerIdx
m_data.lower(innerIdx + bandIncrement) = m_data.lower(innerIdx);
}
for (Index innerIdx = rows(); innerIdx > outer; innerIdx
m_rowStartIndex[innerIdx] += bandIncrement;
}
//zeros new data
memset(this->_lowerPtr() + start, 0, (bandIncrement - 1) * sizeof (Scalar));
return m_data.lower(m_rowStartIndex[outer]);
} else {
return m_data.lower(m_rowStartIndex[outer] + inner - (outer - m_data.lowerProfile(outer)));
}
}
} else {
if (outer > inner) //upper matrix
{
const Index maxOuterIndex = inner + m_data.upperProfile(inner);
if (outer > maxOuterIndex) //The value does not yet exist
{
const Index previousProfile = m_data.upperProfile(inner);
m_data.upperProfile(inner) = outer - inner;
const Index bandIncrement = m_data.upperProfile(inner) - previousProfile;
//shift data stored after this new one
const Index stop = m_rowStartIndex[rows()];
const Index start = m_rowStartIndex[inner + 1];
for (Index innerIdx = stop; innerIdx >= start; innerIdx
m_data.upper(innerIdx + bandIncrement) = m_data.upper(innerIdx);
}
for (Index innerIdx = inner + 1; innerIdx < outerSize() + 1; innerIdx++) {
m_rowStartIndex[innerIdx] += bandIncrement;
}
memset(this->_upperPtr() + m_rowStartIndex[inner] + previousProfile + 1, 0, (bandIncrement - 1) * sizeof (Scalar));
return m_data.upper(m_rowStartIndex[inner] + m_data.upperProfile(inner));
} else {
return m_data.upper(m_rowStartIndex[inner] + (outer - inner));
}
}
if (outer < inner) //lower matrix
{
const Index maxInnerIndex = outer + m_data.lowerProfile(outer);
if (inner > maxInnerIndex) //The value does not yet exist
{
const Index previousProfile = m_data.lowerProfile(outer);
m_data.lowerProfile(outer) = inner - outer;
const Index bandIncrement = m_data.lowerProfile(outer) - previousProfile;
//shift data stored after this new one
const Index stop = m_colStartIndex[cols()];
const Index start = m_colStartIndex[outer + 1];
for (Index innerIdx = stop; innerIdx >= start; innerIdx
m_data.lower(innerIdx + bandIncrement) = m_data.lower(innerIdx);
}
for (Index innerIdx = outer + 1; innerIdx < outerSize() + 1; innerIdx++) {
m_colStartIndex[innerIdx] += bandIncrement;
}
memset(this->_lowerPtr() + m_colStartIndex[outer] + previousProfile + 1, 0, (bandIncrement - 1) * sizeof (Scalar));
return m_data.lower(m_colStartIndex[outer] + m_data.lowerProfile(outer));
} else {
return m_data.lower(m_colStartIndex[outer] + (inner - outer));
}
}
}
}
/** Must be called after inserting a set of non zero entries.
*/
inline void finalize() {
if (IsRowMajor) {
if (rows() > cols())
m_data.resize(cols(), cols(), rows(), m_colStartIndex[cols()] + 1, m_rowStartIndex[rows()] + 1);
else
m_data.resize(rows(), cols(), rows(), m_colStartIndex[cols()] + 1, m_rowStartIndex[rows()] + 1);
// eigen_assert(rows() == cols() && "memory reorganisatrion only works with suare matrix");
// Scalar* newArray = new Scalar[m_colStartIndex[cols()] + 1 + m_rowStartIndex[rows()] + 1];
// Index dataIdx = 0;
// for (Index row = 0; row < rows(); row++) {
// const Index nbLowerElts = m_rowStartIndex[row + 1] - m_rowStartIndex[row];
// // std::cout << "nbLowerElts" << nbLowerElts << std::endl;
// memcpy(newArray + dataIdx, m_data.m_lower + m_rowStartIndex[row], nbLowerElts * sizeof (Scalar));
// m_rowStartIndex[row] = dataIdx;
// dataIdx += nbLowerElts;
// const Index nbUpperElts = m_colStartIndex[row + 1] - m_colStartIndex[row];
// memcpy(newArray + dataIdx, m_data.m_upper + m_colStartIndex[row], nbUpperElts * sizeof (Scalar));
// m_colStartIndex[row] = dataIdx;
// dataIdx += nbUpperElts;
// //todo : don't access m_data profile directly : add an accessor from SkylineMatrix
// m_rowStartIndex[rows()] = m_rowStartIndex[rows()-1] + m_data.lowerProfile(rows()-1);
// m_colStartIndex[cols()] = m_colStartIndex[cols()-1] + m_data.upperProfile(cols()-1);
// delete[] m_data.m_lower;
// delete[] m_data.m_upper;
// m_data.m_lower = newArray;
// m_data.m_upper = newArray;
} else {
if (rows() > cols())
m_data.resize(cols(), rows(), cols(), m_rowStartIndex[cols()] + 1, m_colStartIndex[cols()] + 1);
else
m_data.resize(rows(), rows(), cols(), m_rowStartIndex[rows()] + 1, m_colStartIndex[rows()] + 1);
}
}
inline void squeeze() {
finalize();
m_data.squeeze();
}
void prune(Scalar reference, RealScalar epsilon = dummy_precision<RealScalar > ()) {
//TODO
}
/** Resizes the matrix to a \a rows x \a cols matrix and initializes it to zero
* \sa resizeNonZeros(Index), reserve(), setZero()
*/
void resize(size_t rows, size_t cols) {
const Index diagSize = rows > cols ? cols : rows;
m_innerSize = IsRowMajor ? cols : rows;
eigen_assert(rows == cols && "Skyline matrix must be square matrix");
if (diagSize % 2) { // diagSize is odd
const Index k = (diagSize - 1) / 2;
m_data.resize(diagSize, IsRowMajor ? cols : rows, IsRowMajor ? rows : cols,
2 * k * k + k + 1,
2 * k * k + k + 1);
} else // diagSize is even
{
const Index k = diagSize / 2;
m_data.resize(diagSize, IsRowMajor ? cols : rows, IsRowMajor ? rows : cols,
2 * k * k - k + 1,
2 * k * k - k + 1);
}
if (m_colStartIndex && m_rowStartIndex) {
delete[] m_colStartIndex;
delete[] m_rowStartIndex;
}
m_colStartIndex = new Index [cols + 1];
m_rowStartIndex = new Index [rows + 1];
m_outerSize = diagSize;
m_data.reset();
m_data.clear();
m_outerSize = diagSize;
memset(m_colStartIndex, 0, (cols + 1) * sizeof (Index));
memset(m_rowStartIndex, 0, (rows + 1) * sizeof (Index));
}
void resizeNonZeros(Index size) {
m_data.resize(size);
}
inline SkylineMatrix()
: m_outerSize(-1), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) {
resize(0, 0);
}
inline SkylineMatrix(size_t rows, size_t cols)
: m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) {
resize(rows, cols);
}
template<typename OtherDerived>
inline SkylineMatrix(const SkylineMatrixBase<OtherDerived>& other)
: m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) {
*this = other.derived();
}
inline SkylineMatrix(const SkylineMatrix & other)
: Base(), m_outerSize(0), m_innerSize(0), m_colStartIndex(0), m_rowStartIndex(0) {
*this = other.derived();
}
inline void swap(SkylineMatrix & other) {
//EIGEN_DBG_SKYLINE(std::cout << "SkylineMatrix:: swap\n");
std::swap(m_colStartIndex, other.m_colStartIndex);
std::swap(m_rowStartIndex, other.m_rowStartIndex);
std::swap(m_innerSize, other.m_innerSize);
std::swap(m_outerSize, other.m_outerSize);
m_data.swap(other.m_data);
}
inline SkylineMatrix & operator=(const SkylineMatrix & other) {
std::cout << "SkylineMatrix& operator=(const SkylineMatrix& other)\n";
if (other.isRValue()) {
swap(other.const_cast_derived());
} else {
resize(other.rows(), other.cols());
memcpy(m_colStartIndex, other.m_colStartIndex, (m_outerSize + 1) * sizeof (Index));
memcpy(m_rowStartIndex, other.m_rowStartIndex, (m_outerSize + 1) * sizeof (Index));
m_data = other.m_data;
}
return *this;
}
template<typename OtherDerived>
inline SkylineMatrix & operator=(const SkylineMatrixBase<OtherDerived>& other) {
const bool needToTranspose = (Flags & RowMajorBit) != (OtherDerived::Flags & RowMajorBit);
if (needToTranspose) {
// TODO
// return *this;
} else {
// there is no special optimization
return SkylineMatrixBase<SkylineMatrix>::operator=(other.derived());
}
}
friend std::ostream & operator <<(std::ostream & s, const SkylineMatrix & m) {
EIGEN_DBG_SKYLINE(
std::cout << "upper elements : " << std::endl;
for (Index i = 0; i < m.m_data.upperSize(); i++)
std::cout << m.m_data.upper(i) << "\t";
std::cout << std::endl;
std::cout << "upper profile : " << std::endl;
for (Index i = 0; i < m.m_data.upperProfileSize(); i++)
std::cout << m.m_data.upperProfile(i) << "\t";
std::cout << std::endl;
std::cout << "lower startIdx : " << std::endl;
for (Index i = 0; i < m.m_data.upperProfileSize(); i++)
std::cout << (IsRowMajor ? m.m_colStartIndex[i] : m.m_rowStartIndex[i]) << "\t";
std::cout << std::endl;
std::cout << "lower elements : " << std::endl;
for (Index i = 0; i < m.m_data.lowerSize(); i++)
std::cout << m.m_data.lower(i) << "\t";
std::cout << std::endl;
std::cout << "lower profile : " << std::endl;
for (Index i = 0; i < m.m_data.lowerProfileSize(); i++)
std::cout << m.m_data.lowerProfile(i) << "\t";
std::cout << std::endl;
std::cout << "lower startIdx : " << std::endl;
for (Index i = 0; i < m.m_data.lowerProfileSize(); i++)
std::cout << (IsRowMajor ? m.m_rowStartIndex[i] : m.m_colStartIndex[i]) << "\t";
std::cout << std::endl;
);
for (Index rowIdx = 0; rowIdx < m.rows(); rowIdx++) {
for (Index colIdx = 0; colIdx < m.cols(); colIdx++) {
s << m.coeff(rowIdx, colIdx) << "\t";
}
s << std::endl;
}
return s;
}
/** Destructor */
inline ~SkylineMatrix() {
delete[] m_colStartIndex;
delete[] m_rowStartIndex;
}
/** Overloaded for performance */
Scalar sum() const;
};
template<typename Scalar, int _Options>
class SkylineMatrix<Scalar, _Options>::InnerUpperIterator {
public:
InnerUpperIterator(const SkylineMatrix& mat, Index outer)
: m_matrix(mat), m_outer(outer),
m_id(_Options == RowMajor ? mat.m_colStartIndex[outer] : mat.m_rowStartIndex[outer] + 1),
m_start(m_id),
m_end(_Options == RowMajor ? mat.m_colStartIndex[outer + 1] : mat.m_rowStartIndex[outer + 1] + 1) {
}
inline InnerUpperIterator & operator++() {
m_id++;
return *this;
}
inline InnerUpperIterator & operator+=(Index shift) {
m_id += shift;
return *this;
}
inline Scalar value() const {
return m_matrix.m_data.upper(m_id);
}
inline Scalar* valuePtr() {
return const_cast<Scalar*> (&(m_matrix.m_data.upper(m_id)));
}
inline Scalar& valueRef() {
return const_cast<Scalar&> (m_matrix.m_data.upper(m_id));
}
inline Index index() const {
return IsRowMajor ? m_outer - m_matrix.m_data.upperProfile(m_outer) + (m_id - m_start) :
m_outer + (m_id - m_start) + 1;
}
inline Index row() const {
return IsRowMajor ? index() : m_outer;
}
inline Index col() const {
return IsRowMajor ? m_outer : index();
}
inline size_t size() const {
return m_matrix.m_data.upperProfile(m_outer);
}
inline operator bool() const {
return (m_id < m_end) && (m_id >= m_start);
}
protected:
const SkylineMatrix& m_matrix;
const Index m_outer;
Index m_id;
const Index m_start;
const Index m_end;
};
template<typename Scalar, int _Options>
class SkylineMatrix<Scalar, _Options>::InnerLowerIterator {
public:
InnerLowerIterator(const SkylineMatrix& mat, Index outer)
: m_matrix(mat),
m_outer(outer),
m_id(_Options == RowMajor ? mat.m_rowStartIndex[outer] : mat.m_colStartIndex[outer] + 1),
m_start(m_id),
m_end(_Options == RowMajor ? mat.m_rowStartIndex[outer + 1] : mat.m_colStartIndex[outer + 1] + 1) {
}
inline InnerLowerIterator & operator++() {
m_id++;
return *this;
}
inline InnerLowerIterator & operator+=(Index shift) {
m_id += shift;
return *this;
}
inline Scalar value() const {
return m_matrix.m_data.lower(m_id);
}
inline Scalar* valuePtr() {
return const_cast<Scalar*> (&(m_matrix.m_data.lower(m_id)));
}
inline Scalar& valueRef() {
return const_cast<Scalar&> (m_matrix.m_data.lower(m_id));
}
inline Index index() const {
return IsRowMajor ? m_outer - m_matrix.m_data.lowerProfile(m_outer) + (m_id - m_start) :
m_outer + (m_id - m_start) + 1;
;
}
inline Index row() const {
return IsRowMajor ? m_outer : index();
}
inline Index col() const {
return IsRowMajor ? index() : m_outer;
}
inline size_t size() const {
return m_matrix.m_data.lowerProfile(m_outer);
}
inline operator bool() const {
return (m_id < m_end) && (m_id >= m_start);
}
protected:
const SkylineMatrix& m_matrix;
const Index m_outer;
Index m_id;
const Index m_start;
const Index m_end;
};
} // end namespace Eigen
#endif // <API key>
|
//cmdtypist: the main of cmdtypist
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<ctype.h>
#include <unistd.h>
//cmdtypist.c: Implementing the main
#include"<API key>.h"//function prototypes and global variables.
#include"display.h"//display fixing
#include"utils.h"//useful functions
#include"files.h"//file manipulations
#include"config.h"//configuration
#include"terminal.h"//manipulating the terminal
char argv[5][18];
int main(int argc, char **argv)//argc=command line counter, argv=pointer to pointer to character(command line arguments)
{
redirect();
lmt_pg_size();
name_display();
read_message_conf();//welcome message for first time users.
int lesson_choice=1;//global variable to hold the number corresponding to the chosen lesson.
//char commands[][10]={"0ls","1edituser","2myown","3--help","4man","5mkuser","6mkrand","7mkstd", "8select","9chblk","10sound","11--off","12--on","13cch","14reset","15timeset","16atv","17raw"};
char commands[][10]={"ls","edituser","myown","--help","man","mkuser","mkrand","mkstd", "select","chblk","sound","--off","--on","cch","reset","timeset","atv","raw"};
if(argc<1||argc>3)
{
fprintf(stderr, "%s\n", "Invalid number of arguments to cmdtypist");
exit(EXIT_FAILURE);
}
switch(argc)//switching command depending on the number of command line arguments.
{
case 1:
if(read_myown_config()!=0)
{
lesson_list();//list all lessons present.
select_lesson(argc,&lesson_choice);
}
main_play(argc,&lesson_choice);
break;
case 2:
if(strcmp(argv[1],commands[2])==0)
{
write_myown_config(0);
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[13])==0)
{
write_myown_config(1);
lesson_list();
select_lesson(argc,&lesson_choice);
system("clear");
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[3])==0)
{
FILE *fp;
if((fp=fopen("help.md","r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF)
printf("%c", ch);
puts("");
if(fclose(fp))
{
fprintf(stderr, "%s\n", "Fatal Error, Unable to close some files\n");
exit(EXIT_FAILURE);
}
}
else if(strcmp(argv[1],commands[4])==0)
{
FILE *fp;
if((fp=fopen("Readme.txt","r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF)
printf("%c", ch);
}
else if(strcmp(argv[1],commands[6])==0)
write_conf_mode(0);
else if(strcmp(argv[1],commands[7])==0)
write_conf_mode(1);
else if(strcmp(argv[1],commands[14])==0)
{
printf("%s","Will reset to default; continue? [y/n]:");
if(get_only_char()=='n')
exit(EXIT_SUCCESS);
<API key>(argv[2],argc);
printf("%s\n","Settings reset to default");
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[16])==0)
{
adapt_to_ver();
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[0])==0)
{
lesson_list();
select_lesson(argc,&lesson_choice);
main_play(argc,&lesson_choice);
}
else fprintf(stderr, "%s\n", "Ensure the second argument is corrrectly spelled");
break;
case 3:
if(strcmp(argv[1],commands[5])==0)
{
test_new_user(argv[2]);
lesson_list();
select_lesson(argc,&lesson_choice);
main_play(argc,&lesson_choice);
}
else if(strcmp(argv[1],commands[14])==0&&strcmp(argv[2],commands[17])==0)
{
<API key>(argv[2],argc);
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[1],commands[8])==0)
{
if(read_myown_config()==1)
lesson_choice = range_verifier(is_integral(argv[2],argc));
else
{
lesson_choice=1;
fprintf(stderr, "%s\n\n", "You have been redirected here because you are typing in \"myown\"");
}
main_play(argc,&lesson_choice);
}
/*
else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--on")==0)//modifying system sound
{
sound_config_write(1);
exit(EXIT_SUCCESS);
}
else if((strcmp(argv[1],"sound")==0)&&strcmp(argv[2],"--off")==0)
{
sound_config_write(0);
exit(EXIT_SUCCESS);
}*/
else if((strcmp(argv[1],commands[10])==0))//modifying system sound
{
if(strcmp(argv[2],commands[12])==0)
{
sound_config_write(1);
exit(EXIT_SUCCESS);
}
else if(strcmp(argv[2],commands[11])==0)
{
sound_config_write(0);
exit(EXIT_SUCCESS);
}
else
{
fprintf(stderr, "%s\n", "Check argument 3 for errors, can be \"--on or --off\"");
exit(EXIT_SUCCESS);
}
}
else if(strcmp(argv[1],commands[9])==0)
{
<API key>(is_integral(argv[2],argc));
exit(EXIT_SUCCESS);
}
break;
/*case 4://later update
if((strcmp(argv[1],"timeset")==0))//testing if user wants to play for specific amount of time.
{
if(strcmp(argv[2],"--on")==0)
{
time_set=1;
main_play();
}
else
{
fprintf(stderr, "%s\n", "Argument 3 invalid or not recognized");
exit(EXIT_SUCCESS);
}
}*/
default:
fprintf(stderr, "%s\n", "Argument is invalid, use \"help\" to find out more");
break;
}
return 0;
}
void select_lesson(int argc_cmd, int* user_choice)
{
char firstarg[81];
if(argc_cmd>0&&argc_cmd<4)//checking on the command line argument.
{
char ch;
printf("%s", "Enter command >>");
while(scanf("%s",firstarg)!=1||(scanf("%d",&*user_choice))!=1||*user_choice<1||*user_choice>15||strncmp(firstarg,"select",6)!=0)//Ensuring that "select"
{ //is entered accurately and the selected value is within the correct range.
if((strncmp(firstarg,"se",2)==0||strcmp(firstarg,"sel")==0||strcmp(firstarg,"sele")==0||strcmp(firstarg,"selec")==0)&&strcmp(firstarg,"select")!=0)
//Making suggestion to help user prevent errors.
fprintf(stderr, "\n%s\n%s", "Did you mean \"select usernumber\"","Enter command >>");
else if(ch!=1&&strcmp(firstarg,"select")==0)
printf("%s%s", "Lesson number cannot contain symbols or alphas\n","Enter command >>");
else if((*user_choice<1||*user_choice>20)&&strcmp(firstarg,"select")==0)
fprintf(stderr, "%s %d\n", "No lesson entry for ",*user_choice);
else printf("%s\nEnter command >>", "Command not found");
while(ch=getchar()!='\n');//disposing off wrong input string.
}
}
else
{
fprintf(stderr, "%s\n", "Invalid number of arguments, consult \"cmdtypist --help\" for more");
exit(EXIT_FAILURE);
}
/*
if(argc_cmd==3)
if(strncmp(argv[2],"select",6)!=0||lesson_choice<1||lesson_choice>20)
{
fprintf(stderr, "%s\n", "Command not found\n");
if(strncmp(argv[2],"se",2))
fprintf(stderr, "%s\n", "Did you mean \"select\"");
else if(lesson_choice<1||lesson_choice>20)
fprintf(stderr, "%s %d\n", "No lesson entry for ",lesson_choice);
//else if(ch!=1)
printf("%s", "Lesson number cannot contain symbols or alpha letters.\n");
exit(EXIT_FAILURE);
}*/
printf("\n");
}
void urs_or_cchl(void)
{
if(read_myown_config()==0)
{
strcpy(file_to_read,"my_own.txt");
mode=1;
}
else if(read_myown_config()==1)
strcpy(file_to_read,"noslaclessons.txt");
else
{
fprintf(stderr, "%s\n", "Fatal Error, lesson file corrupted or does not exist");
exit(EXIT_FAILURE);
}
}
void lesson_position(long *read_this_length,long *point_to,int *my_choice)//setting up the pointer in a position of the file to start reading.
{
FILE *lesson_point;
urs_or_cchl();
if((lesson_point=fopen(file_to_read,"r+"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
if(read_myown_config()==0)
{
rewind(lesson_point);//return to beginning
*read_this_length=read_file_size(lesson_point);
*point_to=0;
}
else
switch(*my_choice)
{
case 1:
*point_to=0;
if(read_myown_config()==1)
*read_this_length=25510;
break;
case 2:
*point_to=25512L;
*read_this_length=21660;
break;
case 3:
*point_to=39326L;
*read_this_length=397417;
break;
case 4:
*point_to=444591L;
*read_this_length=11142;
break;
case 5:
*point_to=455733L;
*read_this_length=98588;
break;
case 6:
*point_to=554321L;
*read_this_length=19564;
break;
case 7:
*point_to=573885L;
*read_this_length=79999;
break;
case 8:
*point_to=653884L;
*read_this_length=327523;
break;
case 9:
*point_to=981407L;
*read_this_length=208614;
break;
case 10:
*point_to=1190021L;
*read_this_length=400980;
break;
case 11:
*point_to=1591001L;
*read_this_length=625353;
break;
case 12:
*point_to=2216354L;
*read_this_length=1132581;
break;
default:
*point_to=0;
}
if(fclose(lesson_point))
{
fprintf(stderr, "%s\n", "Unable to close lesson file");
exit(EXIT_FAILURE);
}
}
void main_play(int argc_cmd,int *lesson_choice)
{
//lmt_pg_size();
char terminate=0;
long length_to_read;//holds information on how long the text to be read is.
long move_lesson_to;
lesson_position(&length_to_read,&move_lesson_to,lesson_choice);
unsigned short block_count=0;
user_test();//test if a user already exists or not.
long num_of_chars_typed=0;
block_length=<API key>();
mode=read_conf_mode();
urs_or_cchl();//selects file to read from
remove_ext_ascii();//removes any non ascii 7 bits characters from lesson file.
unsigned int start_time,elapsed_time=0;//elapsed_time: time used during the typing session measured from start time.
unsigned short <API key>=1;//used to count the total number of lines to print.
const unsigned short chars_to_read=77;//total number of characters to read for each line.
unsigned int i=0;//counter variable for loop counting.
char linetype[150];//char array to hold the total number of characters to to read from file per line.
//lesson_list();
//fseek(noslac_lessonsp,25531L,SEEK_SET);//places the pointer to the position of the file to read.
int wrong_letters=0;//sums up the total number of wrong characters entered during program run.
srand((unsigned)time(NULL));//randomizing seed
FILE *noslac_lessonsp;//lesson pointer
if((noslac_lessonsp=fopen(file_to_read,"r"))==NULL)
{
fprintf(stderr, "%s\n", "Fatal Error, Some files are missing");
exit(EXIT_FAILURE);
}
fseek(noslac_lessonsp,move_lesson_to,SEEK_SET);
while(block_count <= (int)(length_to_read/((chars_to_read+1) * block_length)))//testing inorder to read the entire lesson chosen.
{
num_of_chars_typed=0;
char time_checker=0;//changes back to zero after every block typing
/*goes =reads a certain number of characters in the file using a loop determined
by the random generator and places the pointer at the end of it's reading. thereby
making the lesson each time to be random*/
if(mode==0)
{
int u=0;//counter
while(u<=rand()%(length_to_read-((chars_to_read+1)*block_length))&&(ch=getc(noslac_lessonsp))!=EOF)//program feels new
u++;
do
fseek(noslac_lessonsp,-2L,SEEK_CUR);
while((ch=getc(noslac_lessonsp))!=' ');//moving backwards from where it is placed
//to start reading from where there is a space or has found an uppercase letter.
}
<API key>=1;
while(<API key><=block_length)//testing for number of lines to read.
{
i=0;
char endl = guess(14, 33);//endl holds the char to end a line in place of usual '\n'
char startl = guess(14, 33); //guess generates a random char
while(i <= chars_to_read)//test on i to get 77 characters. the screen size is exactly 77 characters.
{
linetype[i] = getc(noslac_lessonsp);//getting characters and placing in the linetype array.
if(linetype[0] == ' ')//prevent a the start of a line from ever being a space character
linetype[0] = startl; //replace with random char
if(linetype[chars_to_read] == ' ')//ensuring a line does not end with a space character.
linetype[chars_to_read] = '-';//replacing space character at the end of a line with a -
if(i > 1)
if(linetype[i-1] == ' ' && linetype[i] == ' ')//preventing two consecutive space characters since text read is random.
i -= 2;
//checking and eliminating newlines to prevent brakes.
if(linetype[i]=='\n'){
linetype[i] = endl;
linetype[++i] = ' ';
}
if(linetype[i]==EOF)//making sure a line does not contain any end of file character by any chance
{
fprintf(stderr, "%s\n", "Closed unexpectedly, <possibly a corrupt cmdtypist file OR you haven't placed any text in myown.txt>");
exit(EXIT_FAILURE);
}
i++;
}
linetype[i]='\0';//Adding string terminator and subtracting the number of spaces removed.
if((<API key> % (block_length)) == 0 && <API key> != 0)
printf(""LAST_LINE_BLUE"");
else
printf(""RESET"");
puts(linetype);//using puts inorder to print the a line and move to the next for the user to follow
<API key>++;
i=0;//setting i to 0 to begin new counting.
unsigned short error_store[3000], j=0;//error_store: array of ints to note the index of a wrong character.
while(i <= chars_to_read+1)//adding 1 for the extra enter key after the 77 letters are entered.
{
int u=0;//loop counter
if((ch=getche())!='\n'&&ch!=EOF)//using getche to prevent printing of enter key.
{
putchar(ch);
if(time_checker==0)//Making sure time is initialized only once
{
time_checker=1;
wrong_letters=0;//setting errors to 0 to start next typing session
start_time=(unsigned)time(NULL);//to start timing.
}
}
if(ch==EOF)
{
fprintf(stderr, "%s\n", "Closed unexpectedly, <an unexpected character keyed in>");
exit(EXIT_FAILURE);
}
if(ch == 27 || ch == '\t')/*testing for ESC character or a tab to exit program.
iscntrl ensures a control character is entered to exit the program*/
{
terminate=1;
letter_clear(1);
puts("\n");
break;
}
if((ch==127 || ch == 8)&& i == 0)//not using '\b' since most terminals are 'cooked' (keys like backspace are handled by terminal driver) //checking for both delete and backspace.
letter_clear(adapt_to_ver_read());
else if((ch == 127 || ch == 8) && i > 0)//testing for delete of backspace
{
i--;//decremting the number of characters entered when backspaced is pressed.
letter_clear(adapt_to_ver_read());
j=wrong_letters;
while(j>u)//counting from u to j, to find if there is a wrong character stored in the error_store array of ints.
{
//printf("j=%d and u=%d\n", j,u);
if(error_store[j]==i)//checking through the array for errased wrong charactes initially entered.
{ //also ensuring before any decrement, wrong_letters>0
wrong_letters--;//decrementing the number of wrong letters.
/*if(wrong_letters<0)
{
printf("finally got a case %d\n",wrong_letters);
wrong_letters=0;
}*/
error_store[j]=-99;//-99 is a value which will never be reached.
//this is to mark the erased index as no longer wrong.
break;//Ensuring that immediately there is a match, the while loop is escaped for speed.
}
j
}
}
else if(i==78&&ch!='\n')
letter_clear(1);
else if(ch!=linetype[i])
{
if(ch!='\n')//testing for ENTER to prevent its printing by printf which will cause a newline.
{
num_of_chars_typed++;
letter_clear(1);//clearing the wrong character
//printf("\a"RED"%c"RESET"",ch );//to print again with color RED. \a is used to include a beep for wrong charater
printf("%s%c",(sound_config_read())==1? "\a"RED"":""RED"",ch);//\a is used to include a beep for wrong character entries
wrong_letters++;
error_store[wrong_letters]=i;//recording the index of a wrong letter
u=0;
j++; //Incrementing the backspace counter.
i++; //incrementing the number of wrong characters entered.
}
}
else
{
if(ch!='\n')//Preventing printing of newline which causes an escape from current typing position in the console.
{
letter_clear(1);
num_of_chars_typed++;
printf(""GREEN"%c"RESET"", ch);//changing color of correct character to green.
i++;
}
}
if(ch=='\n'&&i==78)
break;//escaping loop when the user keys in an Enter.
}
printf("%s","\n" ); //Prints two spaces to ensure the two console spaces left are used, so next printing goes to next line. Game console is 80 and 78 is being used.
if(terminate==1||argc_cmd==4)
break;
}
elapsed_time = (unsigned)time(NULL) - start_time;/*getting the final time and subtracting from the initial
to get the elapsed time*/
block_count++;
//printf("lines=%d block = %d\n",<API key>,block_length );
if(terminate==1)//exiting on tabs and other systme keys
{
char user_name[81];
if(elapsed_time <= 10)
{
fprintf(stderr, "%s\n", "Speed not recorded");
printf(""RESET"\n");
exit(EXIT_SUCCESS);
}
get_user_name(user_name);
printf(""GREEN" ");
printf("%s", user_name);
if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters.
wrong_letters=0;
write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed);
session_style(elapsed_time,wrong_letters,num_of_chars_typed);
exit(EXIT_SUCCESS);//display current typing speed and error
}
if(((<API key>)%block_length)==0)
{
char user_name[81];
if(wrong_letters<0)//optional statement to reduce proberbility of ever having a -ve wrong_letters.
wrong_letters=0;
printf(""GREEN" ");
get_user_name(user_name);//reading user name from file to display in session
printf("%s", user_name);
session_style(elapsed_time,wrong_letters,num_of_chars_typed);//printing session speed details
write_user_speed(elapsed_time,wrong_letters,num_of_chars_typed);//writing user speed to speed file
}
}
}
/*Wrong letters algorithm:
if a user is at the first position of the line and presses backspace, then, that backspace is simply cleared and i not incremented
the array error_store[] keeps track of the index(the i position of the wrong character) and increments a counter variable j, which which be used as
A stop point in a for loop when this stored inex is searched.
When ever backspace keyed in(i!=0), i is first decremented and a search is done through out the loop to see if the decremented i was stored in error store,
if so, then the user is erasing a wrong character, so the wrong_letters is decremented.*/
/*solving the case where wrong_letters shows a messy value
changing it's type to int and making sure it's always greater than 0
*/
|
package com.dank.festivalapp.lib;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static final String DATABASE_NAME = "FestivalApp.db";
private static final int DATABASE_VERSION = 1;
private static DataBaseHelper mInstance = null;
private DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static DataBaseHelper getInstance(Context ctx) {
if (mInstance == null) {
mInstance = new DataBaseHelper(ctx);
}
return mInstance;
}
public boolean isTableExists(SQLiteDatabase db, String tableName)
{
Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+ tableName +"'", null);
if(cursor != null) {
if(cursor.getCount() > 0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DataBaseHelper.class.getName(), "TODO ");
}
}
|
#ifndef WR_ACCESS_LOG_H_
#define WR_ACCESS_LOG_H_
#define WR_ACCESS_LOG_FILE "/var/log/webroar/access.log"
#define WR_REQ_USER_AGENT "HTTP_USER_AGENT"
#define WR_REQ_REFERER "HTTP_REFERER"
#include <wr_request.h>
int wr_access_log(wr_req_t*);
#endif /*WR_ACCESS_LOG_H_*/
|
// -*- Mode: Go; indent-tabs-mode: t -*-
package install
import (
"bytes"
"fmt"
"os/exec"
"strconv"
"strings"
"time"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/gadget/quantity"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/strutil"
)
var (
ensureNodesExist = <API key>
)
var <API key> = []string{
"<API key>", // Linux filesystem data
"<API key>", // Linux swap partition
}
// creationSupported returns whether we support and expect to create partitions
// of the given type, it also means we are ready to remove them for re-installation
// or retried installation if they are appropriately marked with <API key>.
func creationSupported(ptype string) bool {
return strutil.ListContains(<API key>, strings.ToUpper(ptype))
}
// <API key> creates the partitions listed in the laid out volume
// pv that are missing from the existing device layout, returning a list of
// structures that have been created.
func <API key>(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume) ([]gadget.OnDiskStructure, error) {
buf, created := buildPartitionList(dl, pv)
if len(created) == 0 {
return created, nil
}
logger.Debugf("create partitions on %s: %s", dl.Device, buf.String())
// Write the partition table. By default sfdisk will try to re-read the
// partition table with the BLKRRPART ioctl but will fail because the
// kernel side rescan removes and adds partitions and we have partitions
// mounted (so it fails on removal). Use --no-reread to skip this attempt.
cmd := exec.Command("sfdisk", "--append", "--no-reread", dl.Device)
cmd.Stdin = buf
if output, err := cmd.CombinedOutput(); err != nil {
return created, osutil.OutputErr(output, err)
}
// Re-read the partition table
if err := <API key>(dl.Device); err != nil {
return nil, err
}
// Make sure the devices for the partitions we created are available
if err := ensureNodesExist(created, 5*time.Second); err != nil {
return nil, fmt.Errorf("partition not available: %v", err)
}
return created, nil
}
// buildPartitionList builds a list of partitions based on the current
// device contents and gadget structure list, in sfdisk dump format, and
// returns a partitioning description suitable for sfdisk input and a
// list of the partitions to be created.
func buildPartitionList(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume) (sfdiskInput *bytes.Buffer, toBeCreated []gadget.OnDiskStructure) {
sectorSize := dl.SectorSize
// Keep track what partitions we already have on disk
seen := map[quantity.Offset]bool{}
for _, s := range dl.Structure {
start := s.StartOffset / quantity.Offset(sectorSize)
seen[start] = true
}
// Check if the last partition has a system-data role
canExpandData := false
if n := len(pv.LaidOutStructure); n > 0 {
last := pv.LaidOutStructure[n-1]
if last.VolumeStructure.Role == gadget.SystemData {
canExpandData = true
}
}
// The partition index
pIndex := 0
// Write new partition data in named-fields format
buf := &bytes.Buffer{}
for _, p := range pv.LaidOutStructure {
if !p.IsPartition() {
continue
}
pIndex++
s := p.VolumeStructure
// Skip partitions that are already in the volume
start := p.StartOffset / quantity.Offset(sectorSize)
if seen[start] {
continue
}
// Only allow the creation of partitions with known GUIDs
// TODO:UC20: also provide a mechanism for MBR (RPi)
ptype := partitionType(dl.Schema, p.Type)
if dl.Schema == "gpt" && !creationSupported(ptype) {
logger.Noticef("cannot create partition with unsupported type %s", ptype)
continue
}
// Check if the data partition should be expanded
size := s.Size
if s.Role == gadget.SystemData && canExpandData && quantity.Size(p.StartOffset)+s.Size < dl.Size {
size = dl.Size - quantity.Size(p.StartOffset)
}
// Can we use the index here? Get the largest existing partition number and
// build from there could be safer if the disk partitions are not consecutive
// (can this actually happen in our images?)
node := deviceName(dl.Device, pIndex)
fmt.Fprintf(buf, "%s : start=%12d, size=%12d, type=%s, name=%q\n", node,
p.StartOffset/quantity.Offset(sectorSize), size/sectorSize, ptype, s.Name)
toBeCreated = append(toBeCreated, gadget.OnDiskStructure{
LaidOutStructure: p,
Node: node,
Size: size,
})
}
return buf, toBeCreated
}
func partitionType(label, ptype string) string {
t := strings.Split(ptype, ",")
if len(t) < 1 {
return ""
}
if len(t) == 1 {
return t[0]
}
if label == "gpt" {
return t[1]
}
return t[0]
}
func deviceName(name string, index int) string {
if len(name) > 0 {
last := name[len(name)-1]
if last >= '0' && last <= '9' {
return fmt.Sprintf("%sp%d", name, index)
}
}
return fmt.Sprintf("%s%d", name, index)
}
// <API key> removes partitions added during a previous install.
func <API key>(lv *gadget.LaidOutVolume, dl *gadget.OnDiskVolume) error {
indexes := make([]string, 0, len(dl.Structure))
for i, s := range dl.Structure {
if <API key>(lv, s) {
logger.Noticef("partition %s was created during previous install", s.Node)
indexes = append(indexes, strconv.Itoa(i+1))
}
}
if len(indexes) == 0 {
return nil
}
// Delete disk partitions
logger.Debugf("delete disk partitions %v", indexes)
cmd := exec.Command("sfdisk", append([]string{"--no-reread", "--delete", dl.Device}, indexes...)...)
if output, err := cmd.CombinedOutput(); err != nil {
return osutil.OutputErr(output, err)
}
// Reload the partition table
if err := <API key>(dl.Device); err != nil {
return err
}
// Re-read the partition table from the device to update our partition list
if err := gadget.UpdatePartitionList(dl); err != nil {
return err
}
// Ensure all created partitions were removed
if remaining := <API key>(lv, dl); len(remaining) > 0 {
return fmt.Errorf("cannot remove partitions: %s", strings.Join(remaining, ", "))
}
return nil
}
// ensureNodeExists makes sure the device nodes for all device structures are
// available and notified to udev, within a specified amount of time.
func <API key>(dss []gadget.OnDiskStructure, timeout time.Duration) error {
t0 := time.Now()
for _, ds := range dss {
found := false
for time.Since(t0) < timeout {
if osutil.FileExists(ds.Node) {
found = true
break
}
time.Sleep(100 * time.Millisecond)
}
if found {
if err := udevTrigger(ds.Node); err != nil {
return err
}
} else {
return fmt.Errorf("device %s not available", ds.Node)
}
}
return nil
}
// <API key> instructs the kernel to re-read the partition
// table of a given block device.
func <API key>(device string) error {
// Re-read the partition table using the BLKPG ioctl, which doesn't
// remove existing partitions, only appends new partitions with the right
// size and offset. As long as we provide consistent partitioning from
// userspace we're safe.
output, err := exec.Command("partx", "-u", device).CombinedOutput()
if err != nil {
return osutil.OutputErr(output, err)
}
return nil
}
// udevTrigger triggers udev for the specified device and waits until
// all events in the udev queue are handled.
func udevTrigger(device string) error {
if output, err := exec.Command("udevadm", "trigger", "--settle", device).CombinedOutput(); err != nil {
return osutil.OutputErr(output, err)
}
return nil
}
// <API key> returns if the OnDiskStructure was created during
// install by referencing the gadget volume. A structure is only considered to
// be created during install if it is a role that is created during install and
// the start offsets match. We specifically don't look at anything on the
// structure such as filesystem information since this may be incomplete due to
// ARM tools (i.e. ptool and fastboot) when flashing images to internal MMC.
func <API key>(lv *gadget.LaidOutVolume, s gadget.OnDiskStructure) bool {
// for a structure to have been created during install, it must be one of
// the system-boot, system-data, or system-save roles from the gadget, and
// as such the on disk structure must exist in the exact same location as
// the role from the gadget, so only return true if the provided structure
// has the exact same StartOffset as one of those roles
for _, gs := range lv.LaidOutStructure {
// TODO: how to handle ubuntu-save here? maybe a higher level function
// should decide whether to delete it or not?
switch gs.Role {
case gadget.SystemSave, gadget.SystemData, gadget.SystemBoot:
// then it was created during install or is to be created during
// install, see if the offset matches the provided on disk structure
// has
if s.StartOffset == gs.StartOffset {
return true
}
}
}
return false
}
// <API key> returns a list of partitions created during the
// install process.
func <API key>(lv *gadget.LaidOutVolume, layout *gadget.OnDiskVolume) (created []string) {
created = make([]string, 0, len(layout.Structure))
for _, s := range layout.Structure {
if <API key>(lv, s) {
created = append(created, s.Node)
}
}
return created
}
|
-- PostgreSQL database dump
SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET <API key> = on;
SET <API key> = false;
SET client_min_messages = warning;
-- Name: casts; Type: SCHEMA; Schema: -; Owner: -
CREATE SCHEMA casts;
SET search_path = casts, pg_catalog;
-- Name: _date_to_bigint(date); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _date_to_bigint(date) RETURNS bigint
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT casts._date_to_integer($1)::bigint
$_$;
-- Name: _date_to_integer(date); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _date_to_integer(date) RETURNS integer
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT
EXTRACT(YEAR FROM $1)::integer * 10000
+ EXTRACT(MONTH FROM $1)::integer * 100
+ EXTRACT(DAY FROM $1)::integer
$_$;
-- Name: _interval_to_bigint(interval); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _interval_to_bigint(interval) RETURNS bigint
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT
EXTRACT(YEAR FROM $1)::bigint * 10000000000
+ EXTRACT(MONTH FROM $1)::bigint * 100000000
+ EXTRACT(DAY FROM $1)::bigint * 1000000
+ EXTRACT(HOUR FROM $1)::bigint * 10000
+ EXTRACT(MINUTE FROM $1)::bigint * 100
+ EXTRACT(SECONDS FROM $1)::bigint
$_$;
-- Name: _text_to_bigint(text); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _text_to_bigint(text) RETURNS bigint
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
return $1 if ($_[0] =~ m/^(\d+)(\.\d+)?$/);
return undef;
$_X$;
-- Name: _text_to_date(text); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _text_to_date(text) RETURNS date
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
$_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format
return $& if( $_[0] =~ m/^(\d{4}-\d{1,2}-\d{1,2})/ );
return undef;
$_X$;
-- Name: _text_to_numeric(text); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _text_to_numeric(text) RETURNS numeric
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
return $1.$2 if( $_[0] =~ m/^(\d+)(\.\d+)?$/);
return undef;
$_X$;
-- Name: _text_to_time(text); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _text_to_time(text) RETURNS time without time zone
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
return $& if( $_[0] =~ s/^(\d{1,2}:\d{1,2})(:\d{1,2}(\.\d+)?)?$/$1$2/ );
return undef;
$_X$;
-- Name: _text_to_timestamp(text); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _text_to_timestamp(text) RETURNS timestamp without time zone
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
$_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format
return $_[0] if( $_[0] =~ s/^(\d{4}-\d{2}-\d{2})( \d{1,2}:\d{2}:\d{2})?(\.\d+)?([\+\-\d\:.]+)?/$1$2$3$4/ );
return undef;
$_X$;
-- Name: <API key>(text); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION <API key>(text) RETURNS timestamp with time zone
LANGUAGE plperlu IMMUTABLE STRICT COST 1
AS $_X$
$_[0] =~ s/0000-00-00/0001-01-01/; #its just for mysql date format
return $_[0] if( $_[0] =~ s/^(\d{4}-\d{2}-\d{2})( \d{1,2}:\d{2}:\d{2})?(\.\d+)?([\+\-\d\:.]+)?/$1$2$3$4/ );
return undef;
$_X$;
-- Name: _time_to_integer(time without time zone); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _time_to_integer(time without time zone) RETURNS integer
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT
EXTRACT(HOUR FROM $1)::integer * 10000
+ EXTRACT(MINUTE FROM $1)::integer * 100
+ EXTRACT(SECONDS FROM $1)::integer
$_$;
-- Name: _time_to_integer(time with time zone); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _time_to_integer(time with time zone) RETURNS integer
LANGUAGE sql IMMUTABLE STRICT
AS $_$
SELECT
EXTRACT(HOUR FROM $1)::integer * 10000
+ EXTRACT(MINUTE FROM $1)::integer * 100
+ EXTRACT(SECONDS FROM $1)::integer
$_$;
-- Name: _unknown_to_bigint(unknown); Type: FUNCTION; Schema: casts; Owner: -
CREATE OR REPLACE FUNCTION _unknown_to_bigint(unknown) RETURNS bigint
LANGUAGE plperlu
AS $_X$
return $1 if ($_[0] =~ m/^(\d+)(\.\d+)?$/);
return undef;
$_X$;
SET search_path = pg_catalog;
-- Name: CAST (date AS integer); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (date AS integer) WITH FUNCTION casts._date_to_integer(date) AS IMPLICIT;
-- Name: CAST (date AS bigint); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (date AS bigint) WITH FUNCTION casts._date_to_bigint(date) AS IMPLICIT;
-- Name: CAST (interval AS bigint); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (interval AS bigint) WITH FUNCTION casts._interval_to_bigint(interval) AS IMPLICIT;
-- Name: CAST (text AS date); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (text AS date) WITH FUNCTION casts._text_to_date(text) AS IMPLICIT;
-- Name: CAST (text AS bigint); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (text AS bigint) WITH FUNCTION casts._text_to_bigint(text) AS IMPLICIT;
-- Name: CAST (text AS numeric); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (text AS numeric) WITH FUNCTION casts._text_to_numeric(text) AS IMPLICIT;
-- Name: CAST (text AS time without time zone); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (text AS time without time zone) WITH FUNCTION casts._text_to_time(text) AS IMPLICIT;
-- Name: CAST (text AS timestamp without time zone); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (text AS timestamp without time zone) WITH FUNCTION casts._text_to_timestamp(text) AS IMPLICIT;
-- Name: CAST (text AS timestamp with time zone); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (text AS timestamp with time zone) WITH FUNCTION casts.<API key>(text) AS IMPLICIT;
-- Name: CAST (time without time zone AS integer); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (time without time zone AS integer) WITH FUNCTION casts._time_to_integer(time without time zone) AS IMPLICIT;
-- Name: CAST (time with time zone AS integer); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (time with time zone AS integer) WITH FUNCTION casts._time_to_integer(time with time zone) AS IMPLICIT;
-- Name: CAST (unknown AS bigint); Type: CAST; Schema: pg_catalog; Owner: -
CREATE CAST (unknown AS bigint) WITH FUNCTION casts._unknown_to_bigint(unknown) AS IMPLICIT;
-- PostgreSQL database dump complete
|
// File: <API key>.cc
#include "<API key>.hh"
#include "utils/Macros.hh"
#include "Formatter.hh"
namespace quarkdb {
// Indicate which revision we're referring to. When called multiple times
// for the same object, the given value MUST be the same.
void <API key>::setRevisionNumber(uint64_t rev) {
if(currentRevision != 0) {
qdb_assert(currentRevision == rev);
}
else {
currentRevision = rev;
}
}
// Add to update batch - empty value indicates deletion
void <API key>::addUpdate(std::string_view field, std::string_view value) {
updateBatch.emplace_back(field, value);
}
// Serialize contents
std::string <API key>::serialize() const {
return Formatter::vhashRevision(currentRevision, updateBatch).val;
}
// Get revision for a specific key
<API key>& <API key>::forKey(std::string_view key) {
return contents[std::string(key)];
}
// Iterate through contents
std::map<std::string, <API key>>::iterator <API key>::begin() {
return contents.begin();
}
std::map<std::string, <API key>>::iterator <API key>::end() {
return contents.end();
}
}
|
package ems.server.protocol;
import ems.server.domain.Device;
import ems.server.domain.EventSeverity;
import ems.server.domain.EventType;
import ems.server.utils.EventHelper;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class <API key> implements ResponseHandler {
private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
private final Device device;
public <API key>(Device device) {
this.device = device;
format.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@Override
public void onTimeout(String variable) {
EventHelper.getInstance().addEvent(device, EventType.EVENT_NETWORK, EventSeverity.EVENT_WARN);
}
@Override
public void onSuccess(String variable) {
//do nothing
}
@Override
public void onError(String variable, int errorCode, String errorDescription) {
EventSeverity eventSeverity = EventSeverity.EVENT_ERROR;
EventType eventType = EventType.EVENT_PROTOCOL;
String description = "Event of type: \'" + eventType + "\' at: " +
format.format(new Date(System.currentTimeMillis())) + " with severity: \'" +
eventSeverity + "\' for device: " + device.getName() + ". Error code:" +
errorCode + ", Error description: " + errorDescription;
EventHelper.getInstance().addEvent(device, eventType, eventSeverity, description);
}
}
|
<?php
require_once ('category.inc.php');
require_once ('lists.inc.php');
require_once ('dynamic_forms.php');
global $ad_tag_to_field_id;
global $ad_tag_to_search;
global $CACHE_ENABLED;
if ($CACHE_ENABLED=='YES') {
$dir = dirname(__FILE__);
$dir = preg_split ('%[/\\\]%', $dir);
$blank = array_pop($dir);
$dir = implode('/', $dir);
include ("$dir/cache/form1_cache.inc.php");
$ad_tag_to_search = $tag_to_search;
$ad_tag_to_field_id = $tag_to_field_id;
} else {
$ad_tag_to_search = tag_to_search_init(1);
$ad_tag_to_field_id = <API key>();
}
function <API key> () {
global $CACHE_ENABLED;
if ($CACHE_ENABLED=='YES') {
global $ad_tag_to_field_id;
return $ad_tag_to_field_id;
}
global $label;
$sql = "SELECT *, t2.field_label AS NAME FROM `form_fields` as t1, <API key> as t2 where t1.field_id = t2.field_id AND t2.lang='".$_SESSION['MDS_LANG']."' AND form_id=1 ORDER BY list_sort_order ";
$result = mysql_query($sql) or die (mysql_error());
# do a query for each field
while ($fields = mysql_fetch_array($result, MYSQL_ASSOC)) {
//$form_data = $row[]
$tag_to_field_id[$fields['template_tag']]['field_id'] = $fields['field_id'];
$tag_to_field_id[$fields['template_tag']]['field_type'] = $fields['field_type'];
$tag_to_field_id[$fields['template_tag']]['field_label'] = $fields['NAME'];
}
$tag_to_field_id["ORDER_ID"]['field_id'] = 'order_id';
$tag_to_field_id["ORDER_ID"]['field_label'] = 'Order ID';
//$tag_to_field_id["ORDER_ID"]['field_label'] = $label["<API key>"];
$tag_to_field_id["BID"]['field_id'] = 'banner_id';
$tag_to_field_id["BID"]['field_label'] = 'Grid ID';
$tag_to_field_id["USER_ID"]['field_id'] = 'user_id';
$tag_to_field_id["USER_ID"]['field_label'] = 'User ID';
$tag_to_field_id["AD_ID"]['field_id'] = 'ad_id';
$tag_to_field_id["AD_ID"]['field_label'] = 'Ad ID';
$tag_to_field_id["DATE"]['field_id'] = 'ad_date';
$tag_to_field_id["DATE"]['field_label'] = 'Date';
return $tag_to_field_id;
}
function load_ad_values ($ad_id) {
$prams = array();
$sql = "SELECT * FROM `ads` WHERE ad_id='$ad_id' ";
$result = mysql_query($sql) or die ($sql. mysql_error());
if ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$prams['ad_id'] = $ad_id;
$prams['user_id'] = $row['user_id'];
$prams['order_id'] = $row['order_id'];
$prams['banner_id'] = $row['banner_id'];
$sql = "SELECT * FROM form_fields WHERE form_id=1 AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' ";
$result = mysql_query($sql) or die(mysql_error());
while ($fields = mysql_fetch_array($result, MYSQL_ASSOC)) {
$prams[$fields['field_id']] = $row[$fields['field_id']];
if ($fields['field_type']=='DATE') {
$day = $_REQUEST[$row['field_id']."d"];
$month = $_REQUEST[$row['field_id']."m"];
$year = $_REQUEST[$row['field_id']."y"];
$prams[$fields['field_id']] = "$year-$month-$day";
} elseif (($fields['field_type']=='MSELECT') || ($row['field_type']=='CHECK')) {
if (is_array($_REQUEST[$row['field_id']])) {
$prams[$fields['field_id']] = implode (",", $_REQUEST[$fields['field_id']]);
} else {
$prams[$fields['field_id']] = $_REQUEST[$fields['field_id']];
}
}
}
return $prams;
} else {
return false;
}
}
function assign_ad_template($prams) {
global $label;
$str = $label['<API key>'];
$sql = "SELECT * FROM form_fields WHERE form_id='1' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' ";
//echo $sql;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($row['field_type']=='IMAGE') {
if ((file_exists(UPLOAD_PATH.'images/'.$prams[$row['field_id']]))&&($prams[$row['field_id']])) {
$str = str_replace('%'.$row['template_tag'].'%', '<img alt="" src="'. UPLOAD_HTTP_PATH."images/".$prams[$row['field_id']].'" >', $str);
} else {
//$str = str_replace('%'.$row['template_tag'].'%', '<IMG SRC="'.UPLOAD_HTTP_PATH.'images/no-image.gif" WIDTH="150" HEIGHT="150" BORDER="0" ALT="">', $str);
$str = str_replace('%'.$row['template_tag'].'%', '', $str);
}
} else {
$str = str_replace('%'.$row['template_tag'].'%', get_template_value($row['template_tag'],1), $str);
}
$str = str_replace('$'.$row['template_tag'].'$', <API key>($row['template_tag'],1), $str);
}
return $str;
}
function display_ad_form ($form_id, $mode, $prams) {
global $label;
global $error;
global $BID;
if ($prams == '' ) {
$prams['mode'] = $_REQUEST['mode'];
$prams['ad_id']= $_REQUEST['ad_id'];
$prams['banner_id'] = $BID;
$prams['user_id'] = $_REQUEST['user_id'];
$sql = "SELECT * FROM form_fields WHERE form_id='$form_id' AND field_type != 'SEPERATOR' AND field_type != 'BLANK' AND field_type != 'NOTE' ";
//echo $sql;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//$prams[$row[field_id]] = $_REQUEST[$row[field_id]];
if ($row['field_type']=='DATE') {
$day = $_REQUEST[$row['field_id']."d"];
$month = $_REQUEST[$row['field_id']."m"];
$year = $_REQUEST[$row['field_id']."y"];
$prams[$row['field_id']] = "$year-$month-$day";
} elseif (($row['field_type']=='MSELECT') || ($row['field_type']=='CHECK')) {
if (is_array($_REQUEST[$row['field_id']])) {
$prams[$row['field_id']] = implode (",", $_REQUEST[$row['field_id']]);
} else {
$prams[$row['field_id']] = $_REQUEST[$row['field_id']];
}
} else {
$prams[$row['field_id']] = stripslashes ($_REQUEST[$row['field_id']]);
}
}
}
if (!defined('SCW_INCLUDE')) {
?>
<script type='text/JavaScript' src='<?php echo BASE_HTTP_PATH."scw/scw_js.php?lang=".$_SESSION['MDS_LANG']; ?>'></script>
<?php
define ('SCW_INCLUDE', 'Y');
}
?>
<form method="POST" action="<?php htmlentities($_SERVER['PHP_SELF']); ?>" name="form1" onsubmit=" form1.savebutton.disabled=true;" enctype="multipart/form-data">
<input type="hidden" name="mode" size="" value="<?php echo $mode; ?>">
<input type="hidden" name="ad_id" size="" value="<?php echo $prams['ad_id']; ?>">
<input type="hidden" name="user_id" size="" value="<?php echo $prams['user_id']; ?>">
<input type="hidden" name="order_id" size="" value="<?php echo $prams['order_id']; ?>">
<input type="hidden" name="banner_id" size="" value="<?php echo $prams['banner_id']; ?>">
<table cellSpacing="1" cellPadding="5" class="ad_data" id="ad" >
<?php if (($error != '' ) && ($mode!='EDIT')) { ?>
<tr>
<td bgcolor="#F2F2F2" colspan="2"><?php echo "<span class='error_msg_label'>".$label['ad_save_error']."</span><br> <b>".$error."</b>"; ?></td>
</tr>
<?php } ?>
<tr bgColor="#ffffff">
<td bgColor="#eaeaea">
<?php if ($mode == "EDIT") {
echo "[Ad Form]";
}
// section 1
display_form ($form_id, $mode, $prams, 1);
?>
</tr>
<tr><td colspan="2" bgcolor="#ffffff">
<input type="hidden" name="save" id="save101" value="">
<?php if ($mode=='edit') { ?>
<input class="form_submit_button" TYPE="SUBMIT" class='big_button' name="savebutton" value="<?php echo $label['ad_save_button'];?>" onClick="save101.value='1';">
<?php } ?>
</td></tr>
</table>
</form>
<?php
}
function list_ads ($admin=false, $order, $offset, $list_mode='ALL', $user_id='') {
## Globals
global $label;
global $tag_to_field_id;
$tag_to_field_id = <API key>();
# Load in the form data, including column names
# (dont forget LANGUAGE TOO)
global $ad_tag_to_field_id;
$records_per_page = 40;
global $label; // languages array
$order_str = $order;
if ($order == '') {
$order = " `order_id` ";
} else {
$order = " `$order` ";
}
global $action;
// process search result
if ($_REQUEST['action'] == 'search') {
$q_string = generate_q_string(1);
$where_sql = generate_search_sql(1);
}
// DATE_FORMAT(`adate`, '%d-%b-%Y') AS formatted_date
$order = $_REQUEST['order_by'];
if ($_REQUEST['ord']=='asc') {
$ord = 'ASC';
} elseif ($_REQUEST['ord']=='desc') {
$ord = 'DESC';
} else {
$ord = 'DESC'; // sort descending by default
}
if ($order == '') {
$order = " `ad_date` ";
} else {
$order = " `$order` ";
}
global $BID;
if ($list_mode == 'USER' ) {
if (!is_numeric($user_id)) {
$user_id = $_SESSION['MDS_ID'];
}
$sql = "Select * FROM `ads` as t1, `orders` as t2 WHERE t1.ad_id=t2.ad_id AND t1.order_id > 0 AND t1.banner_id='".$BID."' AND t1.user_id='".$user_id."' AND (t2.status = 'completed' OR t2.status = 'expired') $where_sql ORDER BY $order $ord ";
} elseif ($list_mode =='TOPLIST') {
// $sql = "SELECT *, DATE_FORMAT(MAX(order_date), '%Y-%c-%d') as max_date, sum(quantity) AS pixels FROM orders, ads where ads.order_id=orders.order_id AND status='completed' and orders.banner_id='$BID' GROUP BY orders.user_id, orders.banner_id order by pixels desc ";
} else {
$sql = "Select * FROM `ads` as t1, `orders` AS t2 WHERE t1.ad_id=t2.ad_id AND t1.banner_id='$BID' and t1.order_id > 0 $where_sql ORDER BY $order $ord ";
}
//echo "[".$sql."]";
$result = mysql_query($sql) or die (mysql_error());
# get the count
$count = mysql_num_rows($result);
if ($count > $records_per_page) {
mysql_data_seek($result, $offset);
}
if ($count > 0 ) {
if ($pages == 1) {
} elseif ($list_mode!='USER') {
$pages = ceil($count / $records_per_page);
$cur_page = $_REQUEST['offset'] / $records_per_page;
$cur_page++;
echo "<center>";
//echo "Page $cur_page of $pages - ";
$label["navigation_page"] = str_replace ("%CUR_PAGE%", $cur_page, $label["navigation_page"]);
$label["navigation_page"] = str_replace ("%PAGES%", $pages, $label["navigation_page"]);
echo "<span > ".$label["navigation_page"]."</span> ";
$nav = nav_pages_struct($result, $q_string, $count, $records_per_page);
$LINKS = 10;
render_nav_pages($nav, $LINKS, $q_string, $show_emp, $cat);
echo "</center>";
}
$dir = dirname(__FILE__);
$dir = preg_split ('%[/\\\]%', $dir);
$blank = array_pop($dir);
$dir = implode('/', $dir);
include ($dir.'/mouseover_box.htm'); // edit this file to change the style of the mouseover box!
echo '<script language="JAVASCRIPT">';
include ('mouseover_js.inc.php');
echo '</script>';
?>
<table border='0' bgcolor='#d9d9d9' cellspacing="1" cellpadding="5" id="adslist" >
<tr bgcolor="#EAEAEA">
<?php
if ($admin == true ) {
echo '<td class="list_header_cell"> </td>';
}
if ($list_mode == 'USER' ) {
echo '<td class="list_header_cell"> </td>';
}
echo_list_head_data(1, $admin);
if (($list_mode == 'USER' ) || ($admin)) {
echo '<td class="list_header_cell">'.$label['ads_inc_pixels_col'].'</td>';
echo '<td class="list_header_cell">'.$label['ads_inc_expires_col'].'</td>';
echo '<td class="list_header_cell" >'.$label['ad_list_status'].'</td>';
}
?>
</tr>
<?php
$i=0; global $prams;
while (($prams = mysql_fetch_array($result, MYSQL_ASSOC)) && ($i < $records_per_page)) {
$i++;
?>
<tr bgcolor="ffffff" onmouseover="old_bg=this.getAttribute('bgcolor');this.setAttribute('bgcolor', '#FBFDDB', 0);" onmouseout="this.setAttribute('bgcolor', old_bg, 0);">
<?php
if ($admin == true ) {
echo '<td class="list_data_cell" >';
?>
<!--<input style="font-size: 8pt" type="button" value="Delete" onClick="if (!confirmLink(this, 'Delete, are you sure?')) {return false;} window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=delete&ad_id=<?php echo $prams['ad_id']; ?>'"><br>!-->
<input type="button" style="font-size: 8pt" value="Edit" onClick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=edit&ad_id=<?php echo $prams['ad_id']; ?>'">
<?php
echo '</td>';
}
if ($list_mode == 'USER' ) {
echo '<td class="list_data_cell">';
?>
<!--<input style="font-size: 8pt" type="button" value="Delete" onClick="if (!confirmLink(this, 'Delete, are you sure?')) {return false;} window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?action=delete&ad_id=<?php echo $prams['ad_id']; ?>'"><br>-->
<input type="button" style="font-size: 8pt" value="Edit" onClick="window.location='<?php echo htmlentities($_SERVER['PHP_SELF']);?>?ad_id=<?php echo $prams['ad_id']; ?>'">
<?php
echo '</td>';
}
echo_ad_list_data($admin);
if (($list_mode == 'USER' ) || ($admin)) {
echo '<td class="list_data_cell"><img src="get_order_image.php?BID='.$BID.'&aid='.$prams['ad_id'].'"></td>';
echo '<td>';
if ($prams['days_expire'] > 0) {
if ($prams['published']!='Y') {
$time_start = strtotime(gmdate('r'));
} else {
$time_start = strtotime($prams['date_published']." GMT");
}
$elapsed_time = strtotime(gmdate('r')) - $time_start;
$elapsed_days = floor ($elapsed_time / 60 / 60 / 24);
$exp_time = ($prams['days_expire'] * 24 * 60 * 60);
$exp_time_to_go = $exp_time - $elapsed_time;
$exp_days_to_go = floor ($exp_time_to_go / 60 / 60 / 24);
$to_go = elapsedtime($exp_time_to_go);
$elapsed = elapsedtime($elapsed_time);
if ($prams['status']=='expired') {
$days = "<a href='orders.php'>".$label['ads_inc_expied_stat']."</a>";
} elseif ($prams['date_published']=='') {
$days = $label['ads_inc_nyp_stat'];
} else {
$days = str_replace ('%ELAPSED%', $elapsed, $label['<API key>']);
$days = str_replace ('%TO_GO%', $to_go, $days);
//$days = "$elapsed elapsed<br> $to_go to go ";
}
//$days = $elapsed_time;
//print_r($prams);
} else {
$days = $label['ads_inc_nev_stat'];
}
echo $days;
echo '</td>';
if ($prams['published']=='Y') {
$pub =$label['ads_inc_pub_stat'];
} else {
$pub = $label['ads_inc_npub_stat'];
}
if ($prams['approved']=='Y') {
$app = $label['ads_inc_app_stat'].', ';
} else {
$app = $label['ads_inc_napp_stat'].', ';
}
//$label['ad_list_st_'.$prams['status']]."
echo '<td class="list_data_cell">'.$app.$pub."</td>";
}
?>
</tr>
<?php
//$prams[file_photo] = '';
// $new_name='';
}
echo "</table>";
} else {
echo "<center><font size='2' face='Arial'><b>".$label["ads_not_found"].".</b></font></center>";
}
return $count;
}
function delete_ads_files ($ad_id) {
$sql = "select * from form_fields where form_id=1 ";
$result = mysql_query ($sql) or die (mysql_error());
while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
$field_id = $row['field_id'];
$field_type = $row['field_type'];
if (($field_type == "FILE")) {
deleteFile("ads", "ad_id", $ad_id, $field_id);
}
if (($field_type == "IMAGE")){
deleteImage("ads", "ad_id", $ad_id, $field_id);
}
}
}
function delete_ad ($ad_id) {
delete_ads_files ($ad_id);
$sql = "delete FROM `ads` WHERE `ad_id`='".$ad_id."' ";
$result = mysql_query($sql) or die (mysql_error().$sql);
}
function <API key>() {
if (func_num_args() > 0 ) {
$cat_id = func_get_arg(0);
} else {
$cat_id = $_REQUEST[cat];
}
$sql = "select search_set from categories where category_id='$cat_id' ";
$result2 = mysql_query ($sql) or die (mysql_error());
$row = mysql_fetch_array($result2);
$search_set = $row[search_set];
$sql = "select * from form_fields where field_type='CATEGORY' AND form_id='1'";
$result = mysql_query ($sql) or die (mysql_error());
$i=0;
if (mysql_num_rows($result) >0) {
while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($i>0) {
$where_cat .= " OR ";
}
$where_cat .= " `$row[field_id]` IN ($search_set) ";
$i++;
}
}
if ($where_cat=='') {
return " AND 1=2 ";
}
if ($search_set=='') {
return "";
}
return " AND ($where_cat) ";
}
function <API key>() {
if (func_num_args() > 0 ) {
$cat_id = func_get_arg(0);
} else {
$cat_id = $_REQUEST[cat];
}
$sql = "select * from form_fields where field_type='CATEGORY' AND form_id='1'";
$result = mysql_query ($sql) or die (mysql_error());
$i=0;
if (mysql_num_rows($result) >0) {
while ($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($i>0) {
$where_cat .= " OR ";
}
$where_cat .= " `$row[field_id]`='$cat_id' ";
$i++;
}
}
if ($where_cat=='') {
return " AND 1=2 ";
}
return " AND ($where_cat) ";
//$sql ="Select * from posts_table where $where_cat ";
//echo $sql."<br/>";
//$result2 = mysql_query ($sql) or die (mysql_error());
}
function generate_ad_id () {
$query ="SELECT max(`ad_id`) FROM `ads`";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
$row[0]++;
return $row[0];
}
function temp_ad_exists($sid) {
$query ="SELECT ad_id FROM `ads` where user_id='$sid' ";
$result = mysql_query($query) or die(mysql_error());
// $row = mysql_fetch_row($result);
return mysql_num_rows($result);
}
function insert_ad_data() {
if (func_num_args() > 0) {
$admin = func_get_arg(0); // admin mode.
}
$user_id = $_SESSION['MDS_ID'];
if ($user_id=='') {
$user_id = addslashes(session_id());
}
$order_id = $_REQUEST['order_id'];
$ad_date = (gmdate("Y-m-d H:i:s"));
$banner_id = $_REQUEST['banner_id'];
if ($_REQUEST['ad_id'] == '') {
$ad_id = generate_ad_id ();
$now = (gmdate("Y-m-d H:i:s"));
$sql = "REPLACE INTO `ads` (`ad_id`, `order_id`, `user_id`, `ad_date`, `banner_id` ".<API key>(1).") VALUES ('$ad_id', '$order_id', '$user_id', '$ad_date', '$banner_id' ".<API key>(1, "ads", "ad_id", $_REQUEST['ad_id'], $user_id).") ";
} else {
$ad_id = $_REQUEST['ad_id'];
if (!$admin) { // make sure that the logged in user is the owner of this ad.
if (!is_numeric($_REQUEST['user_id'])) { // temp order (user_id = session_id())
if ($_REQUEST['user_id']!=session_id()) return false;
} else { // user is logged in
$sql = "select user_id from `ads` WHERE ad_id='".$_REQUEST['ad_id']."'";
$result = mysql_query ($sql) or die(mysql_error());
$row = @mysql_fetch_array($result);
if ($_SESSION['MDS_ID']!==$row['user_id']) {
return false; // not the owner, hacking attempt!
}
}
}
$now = (gmdate("Y-m-d H:i:s"));
$sql = "UPDATE `ads` SET `ad_date`='$now' ".<API key> (1, "ads", "ad_id", $_REQUEST['ad_id'], $user_id)." WHERE ad_id='".$ad_id."'";
}
//echo "<hr><b>Insert:</b> $sql<hr>";
//print_r ($_FILES);
mysql_query ($sql) or die("[$sql]".mysql_error());
//build_ad_count(0);
return $ad_id;
}
function validate_ad_data($form_id) {
return validate_form_data(1);
return $error;
}
function <API key>($ad_id, $user_id) {
global $prams;
$prams = load_ad_values($ad_id);
if ($prams['order_id']>0) {
$sql = "UPDATE blocks SET alt_text='".addslashes(get_template_value('ALT_TEXT', 1))."', url='".addslashes(get_template_value('URL', 1))."' WHERE order_id='".$prams['order_id']."' AND user_id='".$user_id."' ";
mysql_query($sql) or die(mysql_error());
mds_log("Updated blocks with ad URL, ALT_TEXT", $sql);
}
}
?>
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
plt.close('all')
emitX=12
alphaX=-10.
betaX=13.
gammaX=(1.+alphaX**2)/betaX
sigmaX=np.array([[betaX,-alphaX],[-alphaX,gammaX]])*emitX;
numPart=np.int32(1e5);
X=np.random.multivariate_normal([0.,0.],sigmaX,numPart).T
plt.figure(1)
plt.plot(X[0,:],X[1,:],'.')
w=tf.Variable(tf.random_normal([1,1]))
w1=tf.cos(w)
w2=tf.sin(w)
P_Row_1=tf.concat([w1,-w2],0)
P_Row_2=tf.concat([w2,w1],0)
P=tf.concat([P_Row_1,P_Row_2],1)
xI=tf.placeholder(tf.float32,[2,None])
xO=tf.matmul(P,xI)
xxp=tf.reduce_mean(xO[0]*xO[1])
lossAlpha=xxp**2
rateLearn=1e-4
optTotal=tf.train.AdamOptimizer(rateLearn)
trainAlpha=optTotal.minimize(lossAlpha)
sess = tf.InteractiveSession(config=tf.ConfigProto(<API key>=True))
sess.run(tf.<API key>())
sizeBatch=64
for _ in xrange(8000):
startBatch=np.random.randint(0,high=numPart-sizeBatch-1)
xFeed=X[:,startBatch:startBatch+sizeBatch:]
sess.run(trainAlpha,feed_dict={xI:xFeed})
#print(sess.run(LambdaR))
print(sess.run(lossAlpha,feed_dict={xI:X}),_)
print('<API key>')
zReal=sess.run(xO,feed_dict={xI:X})
plt.figure(2)
plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.axis('equal')
plt.figure(10)
plt.hold
plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.plot(X[0,:],X[1,:],'b.')
#plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.axis('equal')
plt.figure(11)
plt.hold
#plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.plot(X[0,:],X[1,:],'b.')
plt.plot(zReal[0,:],zReal[1,:],'r.')
plt.axis('equal')
zRealCov=np.cov(zReal)
emitXReal=np.sqrt(np.linalg.det(zRealCov))
print(emitXReal)
|
<?php
theme()->render("2column-right", [
["Header", "top"],
["Post", "content"],
["Comments", "content"],
["SidebarRight", "right"],
["Footer", "bottom"]
]);
|
package arkhados.spell.buffs.info;
import arkhados.controls.CRotation;
import arkhados.controls.CTrackLocation;
import arkhados.effects.BuffEffect;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
public class MineralArmorInfo extends BuffInfo {
{
setIconPath("Interface/Images/SpellIcons/MineralArmor.png");
}
@Override
public BuffEffect createBuffEffect(BuffInfoParameters params) {
MineralArmorEffect effect = new MineralArmorEffect(params.duration);
effect.addToCharacter(params);
return effect;
}
}
class MineralArmorEffect extends BuffEffect {
private Node centralNode = null;
public MineralArmorEffect(float timeLeft) {
super(timeLeft);
}
public void addToCharacter(BuffInfoParameters params) {
Node character = (Node) params.buffControl.getSpatial();
Spatial crystals1 = assets.loadModel("Models/crystals.j3o");
Spatial crystals2 = assets.loadModel("Models/crystals.j3o");
Spatial crystals3 = assets.loadModel("Models/crystals.j3o");
Spatial crystals4 = assets.loadModel("Models/crystals.j3o");
centralNode = new Node("mineral-armor-node");
centralNode.attachChild(crystals1);
centralNode.attachChild(crystals2);
centralNode.attachChild(crystals3);
centralNode.attachChild(crystals4);
crystals1.setLocalTranslation(-7.5f, 0f, 0f);
crystals2.setLocalTranslation(7.5f, 0f, 0f);
crystals3.setLocalTranslation(0f, 0f, -7.5f);
crystals4.setLocalTranslation(0f, 0f, 7.5f);
Node world = character.getParent();
world.attachChild(centralNode);
centralNode.addControl(
new CTrackLocation(character, new Vector3f(0f, 10f, 0f)));
centralNode.addControl(new CRotation(0f, 2f, 0f));
}
@Override
public void destroy() {
super.destroy();
centralNode.removeFromParent();
}
}
|
jQuery(document).ready(function(){
if( $('.cd-stretchy-nav').length > 0 ) {
var stretchyNavs = $('.cd-stretchy-nav');
stretchyNavs.each(function(){
var stretchyNav = $(this),
stretchyNavTrigger = stretchyNav.find('.cd-nav-trigger');
stretchyNavTrigger.on('click', function(event){
event.preventDefault();
stretchyNav.toggleClass('nav-is-visible');
});
});
$(document).on('click', function(event){
( !$(event.target).is('.cd-nav-trigger') && !$(event.target).is('.cd-nav-trigger span') ) && stretchyNavs.removeClass('nav-is-visible');
});
};
toggle en contenido
$(".toggle-view li").on('click', function(e){
e.currentTarget.classList.toggle("active");
});
});
|
use strict;
use warnings;
package RPG::ResultSet::Election;
use base 'DBIx::Class::ResultSet';
use Carp;
sub schedule {
my $self = shift;
my $town = shift || croak "Town not supplied";
my $days = shift || croak "Number of days not supplied";
croak "Already have an election scheduled\n" if $town->current_election;
my $mayor = $town->mayor;
croak "No mayor in this town" unless $mayor;
croak "Invalid day\n" if $days < 3;
my $schema = $self->result_source->schema;
my $today = $schema->resultset('Day')->find_today;
my $day = $today->day_number + $days;
my $election = $self->create(
{
town_id => $town->id,
scheduled_day => $day,
status => 'Open',
}
);
$schema->resultset('Election_Candidate')->create(
{
character_id => $mayor->id,
election_id => $election->id,
},
);
$schema->resultset('Town_History')->create(
{
town_id => $town->id,
day_id => $today->id,
message => $mayor->name . " has called an election for day $day. " . ucfirst $mayor->pronoun('subjective')
. " invites prospective candidates to register to run.",
}
);
$schema->resultset('Global_News')->create(
{
day_id => $today->id,
message => "The town of " . $town->town_name . " has scheduled an election for day $day.",
},
);
return $election;
}
1;
|

#FEWD - Review, Process, and Debugging
Lesson 11 - Mar 14, 2016
"What was the hardest part of learning to code?
It’s learning to not let errors and complicated functions get you down. Everyone makes mistakes and it’s the process of debugging them that teaches you how to be a better coder." - <a href="http://imagirlwhocodes.com/post/140868820390/<API key>">Amanda Xu</a>
##Agenda
* Surveys, please!
* Exit Ticket Review
* Debugging
* Assignment 5 review: from pseudocode to implementation
##Exit Tickets
* What is a good way to memorize the most used functions in Jquery/javascript?
Answer: Once you encounter a jQuery function, you'll find that many of them are named pretty transparently after what they do (`.html` and `.css` for example). But as you're starting out, you may still need to look up the documentation or StackOverflow to jog your memory -- that's ok!
* How in the hell do I get good at this?
Answer: Persistence, practice, and patience with yourself!
## Resources for practicing
* <a href="http://tympanus.net/codrops/">Codrops tutorials and playground</a>
* <a href="https:
* <a href="https:
* <a href="http://jqexercise.droppages.com/">jQuery drills</a> - these range in difficulty and don't offer much to help you learn, but it's great for practicing!
##Debugging
<img src="http:
The very first "bug", <a href="http:
##Debugging tips
* The console is your friend:
* The first thing you should always do if your code starts doing things contrary to your expectations is open up your console. A lot of times console will just tell you what went wrong!
* Use `console.log` whenever you need to check if something is working: write out variable values to check that they are updating correctly, log out messages to verify your event handlers are firing correctly, etc. [You can even log out jQuery elements!]
* When a part of your code doesn't work, take a step back and ask yourself these questions:
* What did I expect to happen?
* What happened instead?
* Where in the place in my code where this functionality is being implemented?
* Instead of attempting to throw more code at an already buggy codebase, simplify.
##Debug-a-long
* Fixing errors with the <a href="starter/debugging-relaxr">Relaxr blog exercise</a>.
* Fixing errors with the <a href="starter/<API key>">Compare That exercise</a>.
## Assignment 5 : pseudocode to implementation
Pseudocoding the CitiPix app:
* Need to set up a click listener + handler for the submit button.
* When the submit button is clicked, need to get the input value.
* Verify (using `console.log`) that you are getting the value before you continue to the next parts.
* Once you have the input value, our program needs to **DECIDE** if we should add a class to the body based on what was typed. *Because each of these should work approximately the same way, if we figure out one case, we can carry over the technique to the other cases.*
* If the user typed "New York" or "New York City" or "NYC", we should see the nyc.jpg background
* If the user typed "San Francisco" or "SF" or "Bay Area", we should see the sf background
* If the user typed "Los Angeles" or "LA" or "LAX", we should see the la.jpg background
* If the user typed "Austin" or "ATX", we should see the austin.jpg background
* If the user typed "Sydney" or "SYD", we should see the sydney.jpg background
## More Practice: Number Guesser
We will build a number guesser game where the computer generates a random number from 1-10, and the user enters numbers into the input field until the number they enter is a match. When the user's guess is incorrect, the program will tell user if they need to guess higher or lower.
<a href="http://codepen.io/emmacunningham/pen/pyNJJy?editors=1010">Starter code</a>
* Write pseudocode for the logic flow of your program
* Convert the pseudocode to real JavaScript code, working on things piece-by-piece
##Homework
* Work on the HTML + CSS for your Final Project
* Surveys if you haven't yet filled yours out
##Exit Tickets - Lesson #11, Topic: Review & Debugging
Please fill out the <a href="https://docs.google.com/forms/d/<API key>/viewform">exit ticket</a> before you leave
|
#include "precomp.h"
#include "stdinc.h"
#include "io_sfen.h"
#include "commandpacket.h"
namespace godwhale {
const CommandPacket::CharSeparator CommandPacket::ms_separator(" ", "");
CommandPacket::CommandPacket(CommandType type)
: m_type(type), m_positionId(-1), m_position(false)
{
}
CommandPacket::CommandPacket(CommandPacket const & other)
: m_positionId(-1), m_position(false)
{
}
CommandPacket::CommandPacket(CommandPacket && other)
: m_positionId(-1), m_position(false)
{
}
int CommandPacket::getPriority() const
{
switch (m_type) {
case COMMAND_QUIT:
case COMMAND_STOP:
return 100;
case COMMAND_LOGIN:
case COMMAND_SETPOSITION:
case <API key>:
case COMMAND_SETPV:
case COMMAND_SETMOVELIST:
case COMMAND_VERIFY:
return 50;
case COMMAND_NONE:
return 0;
}
unreachable();
return -1;
}
bool CommandPacket::isToken(std::string const & str, std::string const & target)
{
return (str.compare(target) == 0);
}
shared_ptr<CommandPacket> CommandPacket::parse(std::string const & rsi)
{
if (rsi.empty()) {
throw new std::invalid_argument("rsi");
}
Tokenizer tokens(rsi, ms_separator);
std::string token = *tokens.begin();
if (isToken(token, "login")) {
return parse_Login(rsi, tokens);
}
else if (isToken(token, "setposition")) {
return parse_SetPosition(rsi, tokens);
}
else if (isToken(token, "makerootmove")) {
return parse_MakeRootMove(rsi, tokens);
}
else if (isToken(token, "setmovelist")) {
return parse_SetMoveList(rsi, tokens);
}
else if (isToken(token, "stop")) {
return parse_Stop(rsi, tokens);
}
else if (isToken(token, "quit")) {
return parse_Quit(rsi, tokens);
}
return shared_ptr<CommandPacket>();
}
std::string CommandPacket::toRSI() const
{
assert(m_type != COMMAND_NONE);
switch (m_type) {
case COMMAND_LOGIN:
return toRSI_Login();
case COMMAND_SETPOSITION:
return toRSI_SetPosition();
case <API key>:
return toRSI_MakeRootMove();
case COMMAND_SETMOVELIST:
return toRSI_SetMoveList();
case COMMAND_STOP:
return toRSI_Stop();
case COMMAND_QUIT:
return toRSI_Quit();
}
unreachable();
return std::string();
}
#pragma region Login
shared_ptr<CommandPacket> CommandPacket::parse_Login(std::string const & rsi,
Tokenizer & tokens)
{
shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_LOGIN));
Tokenizer::iterator begin = ++tokens.begin();
result->m_serverAddress = *begin++;
result->m_serverPort = *begin++;
result->m_loginId = *begin++;
return result;
}
std::string CommandPacket::toRSI_Login() const
{
return (F("login %1% %2% %3%")
% m_serverAddress % m_serverPort % m_loginId)
.str();
}
#pragma endregion
#pragma region SetPosition
shared_ptr<CommandPacket> CommandPacket::parse_SetPosition(std::string const & rsi,
Tokenizer & tokens)
{
shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_SETPOSITION));
Tokenizer::iterator begin = ++tokens.begin();
result->m_positionId = lexical_cast<int>(*begin++);
std::string token = *begin++;
if (token == "sfen") {
std::string sfen;
sfen += *begin++ + " "; // board
sfen += *begin++ + " "; // turn
sfen += *begin++ + " "; // hand
sfen += *begin++; // nmoves
result->m_position = sfenToPosition(sfen);
}
else if (token == "startpos") {
result->m_position = Position();
}
if (begin == tokens.end()) {
return result;
}
if (*begin++ != "moves") {
throw new ParseException(F("%1%: wµèª³µ èܹñB") % rsi);
}
for (; begin != tokens.end(); ++begin) {
Move move = sfenToMove(result->m_position, *begin);
if (!result->m_position.makeMove(move)) {
LOG_ERROR() << result->m_position;
LOG_ERROR() << *begin << ": wµèª³µ èܹñB";
throw new ParseException(F("%1%: wµèª³µ èܹñB") % *begin);
}
}
return result;
}
std::string CommandPacket::toRSI_SetPosition() const
{
Position position = m_position;
std::vector<Move> moves = position.getMoveList();
while (!position.getMoveList().empty()) {
position.unmakeMove();
}
std::string posStr;
if (position.isInitial()) {
posStr = " startpos";
}
else {
posStr = " sfen ";
posStr += positionToSfen(position);
}
std::string movesStr;
if (!moves.empty()) {
movesStr += " moves";
BOOST_FOREACH(Move move, moves) {
movesStr += " ";
movesStr += moveToSfen(move);
}
}
return (F("setposition %1%%2%%3%")
% m_positionId % posStr % movesStr)
.str();
}
#pragma endregion
#pragma region MakeRootMove
shared_ptr<CommandPacket> CommandPacket::parse_MakeRootMove(std::string const & rsi,
Tokenizer & tokens)
{
shared_ptr<CommandPacket> result(new CommandPacket(<API key>));
Tokenizer::iterator begin = ++tokens.begin();
result->m_positionId = lexical_cast<int>(*begin++);
result->m_oldPositionId = lexical_cast<int>(*begin++);
Position position;
result->m_move = sfenToMove(position, *begin++);
return result;
}
std::string CommandPacket::toRSI_MakeRootMove() const
{
return (F("makerootmove %1% %2% %3%")
% m_positionId % m_oldPositionId % moveToSfen(m_move))
.str();
}
#pragma endregion
#pragma region SetMoveList
shared_ptr<CommandPacket> CommandPacket::parse_SetMoveList(std::string const & rsi,
Tokenizer & tokens)
{
shared_ptr<CommandPacket> result(new CommandPacket(COMMAND_SETMOVELIST));
Tokenizer::iterator begin = ++tokens.begin();
result->m_positionId = lexical_cast<int>(*begin++);
result->m_iterationDepth = lexical_cast<int>(*begin++);
result->m_plyDepth = lexical_cast<int>(*begin++);
Position position;
Tokenizer::iterator end = tokens.end();
for (; begin != end; ++begin) {
Move move = sfenToMove(position, *begin);
if (move.isEmpty()) {
throw ParseException(F("%1%: ³µ¢wµèÅÍ èܹñB") % *begin);
}
result->m_moveList.push_back(move);
}
return result;
}
std::string CommandPacket::toRSI_SetMoveList() const
{
std::string movesStr;
BOOST_FOREACH(Move move, m_moveList) {
movesStr += " ";
movesStr += moveToSfen(move);
}
return (F("setmovelist %1% %2% %3% %4%")
% m_positionId %m_iterationDepth % m_plyDepth % movesStr)
.str();
}
#pragma endregion
#pragma region Stop
shared_ptr<CommandPacket> CommandPacket::parse_Stop(std::string const & rsi,
Tokenizer & tokens)
{
return shared_ptr<CommandPacket>(new CommandPacket(COMMAND_STOP));
}
std::string CommandPacket::toRSI_Stop() const
{
return "stop";
}
#pragma endregion
#pragma region Quit
shared_ptr<CommandPacket> CommandPacket::parse_Quit(std::string const & rsi,
Tokenizer & tokens)
{
return shared_ptr<CommandPacket>(new CommandPacket(COMMAND_QUIT));
}
std::string CommandPacket::toRSI_Quit() const
{
return "quit";
}
#pragma endregion
} // namespace godwhale
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using KSP;
namespace panelfar
{
public static class <API key>
{
//Take the raw part geometry and simplify it so that further simplification of the entire vessel is faster
public static <API key> PreProcessLocalMesh(<API key> mesh)
{
//Array of vertices; indexing must not change
Vector3[] verts = new Vector3[mesh.vertexes.Length];
mesh.vertexes.CopyTo(verts, 0);
//Array of triangles; each triangle points to an index in verts
MeshIndexTriangle[] indexTris = new MeshIndexTriangle[mesh.triangles.Length];
mesh.triangles.CopyTo(indexTris, 0);
//Array of a list of triangles that contain a given vertex; indexing is same as verts, each index in list points to an index in indexTris
List<int>[] trisAttachedToVerts = <API key>(verts, indexTris);
//Array of quadrics associated with a particular vertex; indexing is same as verts
Quadric[] vertQuadrics = <API key>(verts, indexTris);
//A list of possible vertex pairs that can be contracted into a single point
MinHeap<MeshPairContraction> pairContractions = <API key>(indexTris, verts, vertQuadrics);
int faces = (int)Math.Floor(indexTris.Length * 0.5);
faces = DecimateVertices(faces, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics);
//This will be used to update the old array (which has many empty elements) to a new vertex array and allow the indexTris to be updated as well
Dictionary<int, int> <API key> = new Dictionary<int, int>();
int currentIndex = 0;
List<Vector3> newVerts = new List<Vector3>();
for (int i = 0; i < verts.Length; i++)
{
Vector3 v = verts[i];
if (trisAttachedToVerts[i] != null)
{
<API key>.Add(i, currentIndex);
currentIndex++;
newVerts.Add(v);
}
}
MeshIndexTriangle[] newIndexTris = new MeshIndexTriangle[faces];
currentIndex = 0;
foreach(MeshIndexTriangle tri in indexTris)
{
if(tri != null)
{
MeshIndexTriangle newTri = new MeshIndexTriangle(<API key>[tri.v0], <API key>[tri.v1], <API key>[tri.v2]);
newIndexTris[currentIndex] = newTri;
currentIndex++;
}
}
mesh.vertexes = newVerts.ToArray();
mesh.triangles = newIndexTris;
return mesh;
}
public static int DecimateVertices(int targetFaces, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics)
{
int validFaces = indexTris.Length;
int counter = 1;
StringBuilder debug = new StringBuilder();
debug.AppendLine("Target Faces: " + targetFaces);
try
{
while (validFaces > targetFaces)
{
debug.AppendLine("Iteration: " + counter + " Faces: " + validFaces);
//Get the pair contraction with the least error associated with it
MeshPairContraction pair = pairContractions.ExtractDominating();
debug.AppendLine("Contraction between vertices at indicies: " + pair.v0 + " and " + pair.v1);
debug.AppendLine("Tris attached to v0: " + trisAttachedToVerts[pair.v0].Count + " Tris attached to v1: " + trisAttachedToVerts[pair.v1].Count);
//Get faces that will be deleted / changed by contraction
ComputeContraction(ref pair, indexTris, trisAttachedToVerts);
//Act on faces, delete extra vertex, change all references to second vertex
validFaces -= ApplyContraction(ref pair, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics);
counter++;
}
for(int i = 0; i < indexTris.Length; i++)
{
MeshIndexTriangle tri = indexTris[i];
if (tri == null)
continue;
if (trisAttachedToVerts[tri.v0] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v0);
}
if (trisAttachedToVerts[tri.v1] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v1);
}
if (trisAttachedToVerts[tri.v2] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v2);
}
}
debug.AppendLine("Final: Faces: " + validFaces);
}
catch (Exception e)
{
debug.AppendLine("Error: " + e.Message);
debug.AppendLine("Stack trace");
debug.AppendLine(e.StackTrace);
}
Debug.Log(debug.ToString());
return validFaces;
}
public static int ApplyContraction(ref MeshPairContraction pair, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics)
{
int removedFaces = pair.deletedFaces.Count;
//Move v0, clear v1
verts[pair.v0] = pair.contractedPosition;
verts[pair.v1] = Vector3.zero;
foreach (int triIndex in trisAttachedToVerts[pair.v1])
if (!pair.deletedFaces.Contains(triIndex) && !trisAttachedToVerts[pair.v0].Contains(triIndex))
trisAttachedToVerts[pair.v0].Add(triIndex);
//Clear out all the tris attached to a non-existent vertex
trisAttachedToVerts[pair.v1] = null;
//Accumulate quadrics, clear unused one
vertQuadrics[pair.v0] += vertQuadrics[pair.v1];
vertQuadrics[pair.v1] = new Quadric();
//Adjust deformed triangles
foreach (int changedTri in pair.deformedFaces)
{
MeshIndexTriangle tri = indexTris[changedTri];
if (tri.v0.Equals(pair.v1))
tri.v0 = pair.v0;
else if (tri.v1.Equals(pair.v1))
tri.v1 = pair.v0;
else
tri.v2 = pair.v0;
indexTris[changedTri] = tri;
}
//Clear deleted triangles
foreach(int deletedTri in pair.deletedFaces)
{
indexTris[deletedTri] = null;
}
List<MeshPairContraction> pairList = pairContractions.ToList();
for (int i = 0; i < pairContractions.Count; i++)
{
MeshPairContraction otherPair = pairList[i];
if (otherPair.v0.Equals(pair.v1))
{
otherPair.v0 = pair.v0;
}
else if (otherPair.v1.Equals(pair.v1))
{
otherPair.v1 = pair.v0;
}
pairList[i] = otherPair;
}
int count = pairList.Count;
for (int i = 0; i < count; i++ )
{
MeshPairContraction iItem = pairList[i];
for(int j = i + 1; j < count; j++)
{
if (pairList[j].Equals(iItem))
{
pairList.RemoveAt(j); //Remove duplicate element
count--; //Reduce length to iterate over
j--; //Make sure not to skip over a duplicate
}
}
if(iItem.v1 == iItem.v0)
{
pairList.RemoveAt(i); //Remove degenerate edge
count--; //Reduce length to iterate over
i--; //Make sure not to skip over a duplicate
continue;
}
<API key>(ref iItem, verts, vertQuadrics);
pairList[i] = iItem;
}
pairContractions = new MinHeap<MeshPairContraction>(pairList);
return removedFaces;
}
public static void ComputeContraction(ref MeshPairContraction pair, MeshIndexTriangle[] indexTris, List<int>[] trisAttachedToVerts)
{
//This contains a list of all tris that will be changed by this contraction; boolean indicates whether they will be removed or not
Dictionary<int, bool> trisToChange = new Dictionary<int, bool>();
pair.deformedFaces.Clear();
pair.deletedFaces.Clear();
//Iterate through every triangle attached to vertex 0 of this pair and add them to the dict
foreach(int triIndex in trisAttachedToVerts[pair.v0])
{
if(indexTris[triIndex] != null)
trisToChange.Add(triIndex, false);
}
//Iterate through tris attached to vert 1...
foreach (int triIndex in trisAttachedToVerts[pair.v1])
{
if (indexTris[triIndex] == null)
continue;
//if the tri is already there, it will become degenerate during this contraction and should be removed
if (trisToChange.ContainsKey(triIndex))
trisToChange[triIndex] = true;
//else, add it and it will simply be deformed
else
trisToChange.Add(triIndex, false);
}
//Now, divide them into the appropriate lists
foreach(KeyValuePair<int, bool> triIndex in trisToChange)
{
if (triIndex.Value)
pair.deletedFaces.Add(triIndex.Key);
else
pair.deformedFaces.Add(triIndex.Key);
}
}
public static MinHeap<MeshPairContraction> <API key>(MeshIndexTriangle[] indexTris, Vector3[] verts, Quadric[] vertQuadrics)
{
List<MeshPairContraction> pairContractions = new List<MeshPairContraction>();
foreach(MeshIndexTriangle tri in indexTris)
{
MeshPairContraction e0 = new MeshPairContraction(tri.v0, tri.v1),
e1 = new MeshPairContraction(tri.v1, tri.v2),
e2 = new MeshPairContraction(tri.v2, tri.v0);
if (!pairContractions.Contains(e0))
pairContractions.Add(e0);
if (!pairContractions.Contains(e1))
pairContractions.Add(e1);
if (!pairContractions.Contains(e2))
pairContractions.Add(e2);
}
//Calculate point that each pair contraction will contract to if it is to be done
<API key>(ref pairContractions, verts, vertQuadrics);
MinHeap<MeshPairContraction> heap = new MinHeap<MeshPairContraction>(pairContractions);
return heap;
}
public static void <API key>(ref List<MeshPairContraction> pairContractions, Vector3[] verts, Quadric[] vertQuadrics)
{
for (int i = 0; i < pairContractions.Count; i++)
{
MeshPairContraction pair = pairContractions[i];
<API key>(ref pair, verts, vertQuadrics);
pairContractions[i] = pair;
}
}
public static void <API key>(ref MeshPairContraction pair, Vector3[] verts, Quadric[] vertQuadrics)
{
Vector3 v0 = verts[pair.v0], v1 = verts[pair.v1];
Quadric Q0 = vertQuadrics[pair.v0], Q1 = vertQuadrics[pair.v1];
Quadric Q = Q0 + Q1;
if (Q.Optimize(ref pair.contractedPosition, 1e-12))
pair.error = Q.Evaluate(pair.contractedPosition);
else
{
double ei = Q.Evaluate(v0), ej = Q.Evaluate(v1);
if (ei < ej)
{
pair.error = ei;
pair.contractedPosition = v0;
}
else
{
pair.error = ej;
pair.contractedPosition = v1;
}
}
}
//This returns an array that contains (in each element) a list of indexes that specify which MeshIndexTriangles (in indexTris) are connected to which Vector3s (in verts)
public static List<int>[] <API key>(Vector3[] verts, MeshIndexTriangle[] indexTris)
{
List<int>[] trisAttachedToVerts = new List<int>[verts.Length];
for (int i = 0; i < trisAttachedToVerts.Length; i++)
{
trisAttachedToVerts[i] = new List<int>();
}
for (int i = 0; i < indexTris.Length; i++)
{
MeshIndexTriangle tri = indexTris[i];
trisAttachedToVerts[tri.v0].Add(i);
trisAttachedToVerts[tri.v1].Add(i);
trisAttachedToVerts[tri.v2].Add(i);
}
return trisAttachedToVerts;
}
//Returns an array of quadrics for evaluating the error of each possible contraction
public static Quadric[] <API key>(Vector3[] verts, MeshIndexTriangle[] indexTris)
{
Quadric[] vertQuadrics = new Quadric[verts.Length];
for (int i = 0; i < vertQuadrics.Length; i++ )
vertQuadrics[i] = new Quadric();
foreach (MeshIndexTriangle tri in indexTris)
{
Vector3 v0, v1, v2;
v0 = verts[tri.v0];
v1 = verts[tri.v1];
v2 = verts[tri.v2];
double area = <API key>.triangle_area(v0, v1, v2);
Vector4 p;
if (area > 0)
p = <API key>.triangle_plane(v0, v1, v2);
else
{
p = <API key>.triangle_plane(v2, v1, v0);
area = -area;
}
Quadric Q = new Quadric(p.x, p.y, p.z, p.w, area);
// Area-weight quadric and add it into the three quadrics for the corners
Q *= Q.area;
vertQuadrics[tri.v0] += Q;
vertQuadrics[tri.v1] += Q;
vertQuadrics[tri.v2] += Q;
}
return vertQuadrics;
}
}
}
|
# CMake generated Testfile for
# Source directory: /home/aviral/GNU-Niyantran/gr36/gr-blocks/include/blocks
# Build directory: /home/aviral/GNU-Niyantran/build/gr36/gr-blocks/include/blocks
# This file includes the relevent testing commands required for
# testing this directory and lists subdirectories to be tested as well.
|
import threading
import asyncio
async def hello():
print('Hello world! (%s)' % threading.currentThread())
await asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
|
#include <iostream>
#include <string>
class Shape {
public :
virtual void draw (void) = 0;
static Shape *Create (std::string type);
};
class circle : public Shape {
public :
void draw(void){
std::cout << "circle" << std::endl;
}
};
class square : public Shape {
public :
void draw(void){
std::cout << "square" << std::endl;
}
};
Shape * Shape::Create (std::string type){
if(type == "circle"){
std::cout << "creating circle" << std::endl;
return new circle();
}
if(type == "square") {
std::cout << "creating circle" << std::endl;
return new square();
}
return NULL;
};
int main (){
Shape *cir = Shape::Create("circle");
if ( cir != NULL ) cir->draw();
return 0;
}
|
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[5];
atomic_int atom_1_r1_1;
atomic_int atom_1_r13_0;
void *t0(void *arg){
label_1:;
<API key>(&vars[0], 1, <API key>);
<API key>(&vars[1], 1, <API key>);
return NULL;
}
void *t1(void *arg){
label_2:;
int v2_r1 = <API key>(&vars[1], <API key>);
int v3_r3 = v2_r1 ^ v2_r1;
int v6_r4 = <API key>(&vars[2+v3_r3], <API key>);
int v7_r6 = v6_r4 ^ v6_r4;
int v8_r6 = v7_r6 + 1;
<API key>(&vars[3], v8_r6, <API key>);
int v10_r8 = <API key>(&vars[3], <API key>);
int v11_cmpeq = (v10_r8 == v10_r8);
if (v11_cmpeq) goto lbl_LC00; else goto lbl_LC00;
lbl_LC00:;
<API key>(&vars[4], 1, <API key>);
int v13_r11 = <API key>(&vars[4], <API key>);
int v14_r12 = v13_r11 ^ v13_r11;
int v17_r13 = <API key>(&vars[0+v14_r12], <API key>);
int v21 = (v2_r1 == 1);
<API key>(&atom_1_r1_1, v21, <API key>);
int v22 = (v17_r13 == 0);
<API key>(&atom_1_r13_0, v22, <API key>);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[3], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[0], 0);
atomic_init(&vars[4], 0);
atomic_init(&vars[1], 0);
atomic_init(&atom_1_r1_1, 0);
atomic_init(&atom_1_r13_0, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v18 = <API key>(&atom_1_r1_1, <API key>);
int v19 = <API key>(&atom_1_r13_0, <API key>);
int v20_conj = v18 & v19;
if (v20_conj == 1) assert(0);
return 0;
}
|
{% extends "allauth/account/base.html" %}
{% load i18n %}
{% block head_title %}{% trans "Set Password" %}{% endblock %}
{% block content %}
<h1>{% trans "Set Password" %}</h1>
<form method="POST" action="{% url '<API key>' %}" class="password_set">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="action" value="{% trans 'Set Password' %}"/>
</form>
{% endblock %}
|
#include "CAN.h"
#include "led.h"
#include "delay.h"
#include "usart.h"
u8 CAN_Mode_Init(u8 tsjw,u8 tbs2,u8 tbs1,u16 brp,u8 mode)
{
GPIO_InitTypeDef GPIO_InitStructure;
CAN_InitTypeDef CAN_InitStructure;
<API key> <API key>;
#if CAN_RX0_INT_ENABLE
NVIC_InitTypeDef NVIC_InitStructure;
#endif
<API key>(<API key>, ENABLE);
<API key>(RCC_APB1Periph_CAN2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOB, &GPIO_InitStructure);
CAN_InitStructure.CAN_TTCM=DISABLE;
CAN_InitStructure.CAN_ABOM=DISABLE;
CAN_InitStructure.CAN_AWUM=DISABLE;
CAN_InitStructure.CAN_NART=ENABLE;
CAN_InitStructure.CAN_RFLM=DISABLE;
CAN_InitStructure.CAN_TXFP=DISABLE;
CAN_InitStructure.CAN_Mode= mode;
CAN_InitStructure.CAN_SJW=tsjw;
CAN_InitStructure.CAN_BS1=tbs1;
CAN_InitStructure.CAN_BS2=tbs2;
CAN_InitStructure.CAN_Prescaler=brp;
CAN_Init(CAN2, &CAN_InitStructure);
<API key>.CAN_FilterNumber=0;
<API key>.CAN_FilterMode=<API key>;
<API key>.CAN_FilterScale=<API key>;
<API key>.CAN_FilterIdHigh=0x0000;
<API key>.CAN_FilterIdLow=0x0000;
<API key>.<API key>=0x0000;
<API key>.CAN_FilterMaskIdLow=0x0000;
<API key>.<API key>=CAN_Filter_FIFO0;
<API key>.<API key>=ENABLE;
CAN_FilterInit(&<API key>);
return 0;
}
u8 Can_Send_Msg(u8* msg,u8 len)
{
u8 mbox;
u16 i=0;
CanTxMsg TxMessage;
TxMessage.StdId=0x12;
TxMessage.ExtId=0x12;
TxMessage.IDE=0;
TxMessage.RTR=0;
TxMessage.DLC=len;
for(i=0;i<len;i++)
TxMessage.Data[i]=msg[i];
mbox= CAN_Transmit(CAN2, &TxMessage);
i=0;
while((CAN_TransmitStatus(CAN2, mbox)==CAN_TxStatus_Failed)&&(i<0XFFF))i++;
if(i>=0XFFF)return 1;
return 0;
}
u8 Can_Receive_Msg(u8 *buf)
{
u32 i;
CanRxMsg RxMessage;
if( CAN_MessagePending(CAN2,CAN_FIFO0)==0)return 0;
CAN_Receive(CAN2, CAN_FIFO0, &RxMessage);
for(i=0;i<8;i++)
buf[i]=RxMessage.Data[i];
return RxMessage.DLC;
}
|
#include "../../fl/defuzzifier/IntegralDefuzzifier.h"
namespace fl {
int IntegralDefuzzifier::_defaultResolution = 200;
void IntegralDefuzzifier::<API key>(int defaultResolution) {
_defaultResolution = defaultResolution;
}
int IntegralDefuzzifier::defaultResolution() {
return _defaultResolution;
}
IntegralDefuzzifier::IntegralDefuzzifier(int resolution)
: Defuzzifier(), _resolution(resolution) {
}
IntegralDefuzzifier::~IntegralDefuzzifier() {
}
void IntegralDefuzzifier::setResolution(int resolution) {
this->_resolution = resolution;
}
int IntegralDefuzzifier::getResolution() const {
return this->_resolution;
}
}
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include <CUnit/CUnit.h>
#include "mat.h"
int
main (int argc, const char *argv[])
{
int ret = 0;
lw6sys_context_t *sys_context = NULL;
int mode = 0;
LW6SYS_MAIN_BEGIN (sys_context);
lw6sys_log_clear (sys_context, NULL);
mode = <API key> (sys_context, argc, argv);
if (<API key> () == CUE_SUCCESS)
{
if (<API key> (sys_context, mode))
{
ret = lw6mat_test_run (sys_context, mode);
}
CU_cleanup_registry ();
}
LW6SYS_TEST_OUTPUT;
LW6SYS_MAIN_END (sys_context);
return (!ret);
}
|
"""
Tests are performed against <API key>.03.15.00.S.155-2.S-std.
"""
import unittest
from iosxe.iosxe import IOSXE
from iosxe.exceptions import AuthError
node = '172.16.92.134'
username = 'cisco'
password = 'cisco'
port = 55443
class TestIOSXE(unittest.TestCase):
def setUp(self):
self.xe = IOSXE(node=node, username=username, password=password, disable_warnings=True)
def <API key>(self):
self.assertIsInstance(self.xe, IOSXE)
def <API key>(self):
self.assertRaises(AuthError, IOSXE, node=node, username='stuff', password='things',
disable_warnings=True)
def test_url_base(self):
self.assertEqual(self.xe.url_base, 'https://{0}:{1}/api/v1'.format(node, port))
def test_token_uri(self):
self.assertEqual(self.xe.token_uri, '/auth/token-services')
def <API key>(self):
resp = self.xe.save_config()
self.assertEqual(204, resp.status_code)
|
//This program is free software: you can redistribute it and/or modify
//(at your option) any later version.
//This program is distributed in the hope that it will be useful,
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#ifndef APIQUERYRESULT_HPP
#define APIQUERYRESULT_HPP
#include "definitions.hpp"
#include <QString>
#include <QList>
#include <QHash>
#include "queryresult.hpp"
namespace Huggle
{
//! Key/value node for data from API queries
//! \todo Currently value is provided even for nodes that shouldn't have it
class HUGGLE_EX_CORE ApiQueryResultNode
{
public:
ApiQueryResultNode();
~ApiQueryResultNode();
/*!
* \brief GetAttribute Return the specified attribute if it exists, otherwise return the default
* \param name Name of attribute
* \param default_val Value to return if the attribute is not found
* \return Value of attribute or default value
*/
QString GetAttribute(const QString &name, const QString &default_val = "");
//! Name of attribute
QString Name;
//! Value of attribute
QString Value;
//! Hashtable of attribtues
QHash<QString, QString> Attributes;
QList<ApiQueryResultNode*> ChildNodes;
};
//! Api queries have their own result class so that we can use it to parse them
//! this is a universal result class that uses same format for all known
//! formats we are going to use, including XML or JSON, so that it shouldn't
//! matter which one we use, we always get this structure as output
class HUGGLE_EX_CORE ApiQueryResult : public QueryResult
{
public:
ApiQueryResult();
//! Frees the results from memory
~ApiQueryResult() override;
/*!
* \brief Process Process the data into Nodes and handle any warnings / errors
*/
void Process();
/*!
* \brief GetNode Get the first node with the specified name
* IMPORTANT: do not delete this node, it's a pointer to item in a list which get deleted in destructor of class
* \param node_name Name of node
* \return The specified node or a null pointer if none found
*/
ApiQueryResultNode *GetNode(const QString& node_name);
/*!
* \brief GetNodes Get all nodes with the specified name
* IMPORTANT: do not delete these nodes, they point to items in a list which get deleted in destructor of class
* \param node_name Name of node
* \return QList of pointers to found nodes
*/
QList<ApiQueryResultNode*> GetNodes(const QString& node_name);
QString GetNodeValue(const QString &node_name, const QString &default_value = "");
/*!
* \brief HasWarnings Return if the API has returned any warnings
* \return True if there are warnings, false otherwise
*/
bool HasWarnings();
//! List of result nodes unsorted with no hierarchy
QList<ApiQueryResultNode*> Nodes;
ApiQueryResultNode *Root;
//! Warning from API query
QString Warning;
//! If any error was encountered during the query
bool HasErrors = false;
};
}
#endif // APIQUERYRESULT_HPP
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = versionTransform;
var _path2 = require('path');
var _path3 = <API key>(_path2);
function <API key>(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var packagePath = _path3.default.resolve(process.cwd(), './package.json');
var _require = require(packagePath);
var version = _require.version;
function versionTransform() {
return {
visitor: {
Identifier: function Identifier(path) {
if (path.node.name === 'VERSION') {
path.<API key>('"' + version + '"');
}
}
}
};
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Basic Table</h2>
<p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@example.com</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
|
from __future__ import absolute_import
from pywb.framework.wbrequestresponse import WbResponse, WbRequest
from pywb.framework.archivalrouter import ArchivalRouter
from six.moves.urllib.parse import urlsplit
import base64
import socket
import ssl
from io import BytesIO
from pywb.rewrite.url_rewriter import <API key>, UrlRewriter
from pywb.rewrite.rewrite_content import RewriteContent
from pywb.utils.wbexception import BadRequestException
from pywb.utils.bufferedreaders import BufferedReader
from pywb.utils.loaders import to_native_str
from pywb.framework.proxy_resolvers import ProxyAuthResolver, CookieResolver, IPCacheResolver
from tempfile import <API key>
class ProxyArchivalRouter(ArchivalRouter):
"""
A router which combines both archival and proxy modes support
First, request is treated as a proxy request using ProxyRouter
Second, if not handled by the router, it is treated as a regular
archival mode request.
"""
def __init__(self, routes, **kwargs):
super(ProxyArchivalRouter, self).__init__(routes, **kwargs)
self.proxy = ProxyRouter(routes, **kwargs)
def __call__(self, env):
response = self.proxy(env)
if response:
return response
response = super(ProxyArchivalRouter, self).__call__(env)
if response:
return response
class ProxyRouter(object):
BLOCK_SIZE = 4096
DEF_MAGIC_NAME = 'pywb.proxy'
<API key> = 1024*1024
CERT_DL_PEM = '/pywb-ca.pem'
CERT_DL_P12 = '/pywb-ca.p12'
CA_ROOT_FILE = './ca/pywb-ca.pem'
CA_ROOT_NAME = 'pywb https proxy replay CA'
CA_CERTS_DIR = './ca/certs/'
EXTRA_HEADERS = {'cache-control': 'no-cache',
'connection': 'close',
'p3p': 'CP="NOI ADM DEV COM NAV OUR STP"'}
def __init__(self, routes, **kwargs):
self.error_view = kwargs.get('error_view')
proxy_options = kwargs.get('config', {})
if proxy_options:
proxy_options = proxy_options.get('proxy_options', {})
self.magic_name = proxy_options.get('magic_name')
if not self.magic_name:
self.magic_name = self.DEF_MAGIC_NAME
proxy_options['magic_name'] = self.magic_name
self.extra_headers = proxy_options.get('extra_headers')
if not self.extra_headers:
self.extra_headers = self.EXTRA_HEADERS
proxy_options['extra_headers'] = self.extra_headers
res_type = proxy_options.get('cookie_resolver', True)
if res_type == 'auth' or not res_type:
self.resolver = ProxyAuthResolver(routes, proxy_options)
elif res_type == 'ip':
self.resolver = IPCacheResolver(routes, proxy_options)
#elif res_type == True or res_type == 'cookie':
# self.resolver = CookieResolver(routes, proxy_options)
else:
self.resolver = CookieResolver(routes, proxy_options)
self.use_banner = proxy_options.get('use_banner', True)
self.use_wombat = proxy_options.get('use_client_rewrite', True)
self.proxy_cert_dl_view = proxy_options.get('<API key>')
if not proxy_options.get('enable_https_proxy'):
self.ca = None
return
try:
from certauth.certauth import <API key>
except ImportError: #pragma: no cover
print('HTTPS proxy is not available as the "certauth" module ' +
'is not installed')
print('Please install via "pip install certauth" ' +
'to enable HTTPS support')
self.ca = None
return
# HTTPS Only Options
ca_file = proxy_options.get('root_ca_file', self.CA_ROOT_FILE)
# attempt to create the root_ca_file if doesn't exist
# (generally recommended to create this seperately)
ca_name = proxy_options.get('root_ca_name', self.CA_ROOT_NAME)
certs_dir = proxy_options.get('certs_dir', self.CA_CERTS_DIR)
self.ca = <API key>(ca_file=ca_file,
certs_dir=certs_dir,
ca_name=ca_name)
self.use_wildcard = proxy_options.get('use_wildcard_certs', True)
def __call__(self, env):
is_https = (env['REQUEST_METHOD'] == 'CONNECT')
ArchivalRouter.ensure_rel_uri_set(env)
# for non-https requests, check non-proxy urls
if not is_https:
url = env['REL_REQUEST_URI']
if not url.startswith(('http:
return None
env['pywb.proxy_scheme'] = 'http'
route = None
coll = None
matcher = None
response = None
ts = None
# check resolver, for pre connect resolve
if self.resolver.pre_connect:
route, coll, matcher, ts, response = self.resolver.resolve(env)
if response:
return response
# do connect, then get updated url
if is_https:
response = self.handle_connect(env)
if response:
return response
url = env['REL_REQUEST_URI']
else:
parts = urlsplit(env['REL_REQUEST_URI'])
hostport = parts.netloc.split(':', 1)
env['pywb.proxy_host'] = hostport[0]
env['pywb.proxy_port'] = hostport[1] if len(hostport) == 2 else ''
env['pywb.proxy_req_uri'] = parts.path
if parts.query:
env['pywb.proxy_req_uri'] += '?' + parts.query
env['pywb.proxy_query'] = parts.query
if self.resolver.supports_switching:
env['pywb_proxy_magic'] = self.magic_name
# route (static) and other resources to archival replay
if env['pywb.proxy_host'] == self.magic_name:
env['REL_REQUEST_URI'] = env['pywb.proxy_req_uri']
# special case for proxy install
response = self.handle_cert_install(env)
if response:
return response
return None
# check resolver, post connect
if not self.resolver.pre_connect:
route, coll, matcher, ts, response = self.resolver.resolve(env)
if response:
return response
rel_prefix = ''
custom_prefix = env.get('<API key>', '')
if custom_prefix:
host_prefix = custom_prefix
urlrewriter_class = UrlRewriter
abs_prefix = True
# always rewrite to absolute here
rewrite_opts = dict(no_match_rel=True)
else:
host_prefix = env['pywb.proxy_scheme'] + '://' + self.magic_name
urlrewriter_class = <API key>
abs_prefix = False
rewrite_opts = {}
# special case for proxy calendar
if (env['pywb.proxy_host'] == 'query.' + self.magic_name):
url = env['pywb.proxy_req_uri'][1:]
rel_prefix = '/'
if ts is not None:
url = ts + '/' + url
wbrequest = route.request_class(env,
request_uri=url,
wb_url_str=url,
coll=coll,
host_prefix=host_prefix,
rel_prefix=rel_prefix,
wburl_class=route.handler.get_wburl_type(),
urlrewriter_class=urlrewriter_class,
use_abs_prefix=abs_prefix,
rewrite_opts=rewrite_opts,
is_proxy=True)
if matcher:
route.apply_filters(wbrequest, matcher)
# full rewrite and banner
if self.use_wombat and self.use_banner:
wbrequest.wb_url.mod = ''
elif self.use_banner:
# banner only, no rewrite
wbrequest.wb_url.mod = 'bn_'
else:
# unaltered, no rewrite or banner
wbrequest.wb_url.mod = 'uo_'
response = route.handler(wbrequest)
if not response:
return None
# add extra headers for replay responses
if wbrequest.wb_url and wbrequest.wb_url.is_replay():
response.status_headers.replace_headers(self.extra_headers)
# check for content-length
res = response.status_headers.get_header('content-length')
try:
if int(res) > 0:
return response
except:
pass
# need to either chunk or buffer to get content-length
if env.get('SERVER_PROTOCOL') == 'HTTP/1.1':
response.status_headers.remove_header('content-length')
response.status_headers.headers.append(('Transfer-Encoding', 'chunked'))
response.body = self._chunk_encode(response.body)
else:
response.body = self._buffer_response(response.status_headers,
response.body)
return response
@staticmethod
def _chunk_encode(orig_iter):
for chunk in orig_iter:
if not len(chunk):
continue
chunk_len = b'%X\r\n' % len(chunk)
yield chunk_len
yield chunk
yield b'\r\n'
yield b'0\r\n\r\n'
@staticmethod
def _buffer_response(status_headers, iterator):
out = <API key>(ProxyRouter.<API key>)
size = 0
for buff in iterator:
size += len(buff)
out.write(buff)
content_length_str = str(size)
# remove existing content length
status_headers.replace_header('Content-Length',
content_length_str)
out.seek(0)
return RewriteContent.stream_to_gen(out)
def get_request_socket(self, env):
if not self.ca:
return None
sock = None
if env.get('uwsgi.version'): # pragma: no cover
try:
import uwsgi
fd = uwsgi.connection_fd()
conn = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
try:
sock = socket.socket(_sock=conn)
except:
sock = conn
except Exception as e:
pass
elif env.get('gunicorn.socket'): # pragma: no cover
sock = env['gunicorn.socket']
if not sock:
# attempt to find socket from wsgi.input
input_ = env.get('wsgi.input')
if input_:
if hasattr(input_, '_sock'): # pragma: no cover
raw = input_._sock
sock = socket.socket(_sock=raw) # pragma: no cover
elif hasattr(input_, 'raw'):
sock = input_.raw._sock
return sock
def handle_connect(self, env):
sock = self.get_request_socket(env)
if not sock:
return WbResponse.text_response('HTTPS Proxy Not Supported',
'405 HTTPS Proxy Not Supported')
sock.send(b'HTTP/1.0 200 Connection Established\r\n')
sock.send(b'Proxy-Connection: close\r\n')
sock.send(b'Server: pywb proxy\r\n')
sock.send(b'\r\n')
hostname, port = env['REL_REQUEST_URI'].split(':')
if not self.use_wildcard:
certfile = self.ca.cert_for_host(hostname)
else:
certfile = self.ca.get_wildcard_cert(hostname)
try:
ssl_sock = ssl.wrap_socket(sock,
server_side=True,
certfile=certfile,
#ciphers="ALL",
<API key>=False,
ssl_version=ssl.PROTOCOL_SSLv23
)
env['pywb.proxy_ssl_sock'] = ssl_sock
buffreader = BufferedReader(ssl_sock, block_size=self.BLOCK_SIZE)
statusline = to_native_str(buffreader.readline().rstrip())
except Exception as se:
raise BadRequestException(se.message)
statusparts = statusline.split(' ')
if len(statusparts) < 3:
raise BadRequestException('Invalid Proxy Request: ' + statusline)
env['REQUEST_METHOD'] = statusparts[0]
env['REL_REQUEST_URI'] = ('https:
env['REL_REQUEST_URI'].replace(':443', '') +
statusparts[1])
env['SERVER_PROTOCOL'] = statusparts[2].strip()
env['pywb.proxy_scheme'] = 'https'
env['pywb.proxy_host'] = hostname
env['pywb.proxy_port'] = port
env['pywb.proxy_req_uri'] = statusparts[1]
queryparts = env['REL_REQUEST_URI'].split('?', 1)
env['PATH_INFO'] = queryparts[0]
env['QUERY_STRING'] = queryparts[1] if len(queryparts) > 1 else ''
env['pywb.proxy_query'] = env['QUERY_STRING']
while True:
line = to_native_str(buffreader.readline())
if line:
line = line.rstrip()
if not line:
break
parts = line.split(':', 1)
if len(parts) < 2:
continue
name = parts[0].strip()
value = parts[1].strip()
name = name.replace('-', '_').upper()
if name not in ('CONTENT_LENGTH', 'CONTENT_TYPE'):
name = 'HTTP_' + name
env[name] = value
env['wsgi.input'] = buffreader
#remain = buffreader.rem_length()
#if remain > 0:
#remainder = buffreader.read()
#env['wsgi.input'] = BufferedReader(BytesIO(remainder))
#remainder = buffreader.read(self.BLOCK_SIZE)
#env['wsgi.input'] = BufferedReader(ssl_sock,
# block_size=self.BLOCK_SIZE,
# starting_data=remainder)
def handle_cert_install(self, env):
if env['pywb.proxy_req_uri'] in ('/', '/index.html', '/index.html'):
available = (self.ca is not None)
if self.proxy_cert_dl_view:
return (self.proxy_cert_dl_view.
render_response(available=available,
pem_path=self.CERT_DL_PEM,
p12_path=self.CERT_DL_P12))
elif env['pywb.proxy_req_uri'] == self.CERT_DL_PEM:
if not self.ca:
return None
buff = b''
with open(self.ca.ca_file, 'rb') as fh:
buff = fh.read()
content_type = 'application/x-x509-ca-cert'
headers = [('Content-Length', str(len(buff)))]
return WbResponse.bin_stream([buff],
content_type=content_type,
headers=headers)
elif env['pywb.proxy_req_uri'] == self.CERT_DL_P12:
if not self.ca:
return None
buff = self.ca.get_root_PKCS12()
content_type = 'application/x-pkcs12'
headers = [('Content-Length', str(len(buff)))]
return WbResponse.bin_stream([buff],
content_type=content_type,
headers=headers)
|
CKEDITOR.plugins.setLang( 'image', 'eo', {
alertUrl: 'Bonvolu tajpi la retadreson de la bildo',
alt: 'Anstataŭiga Teksto',
border: 'Bordero',
btnUpload: 'Sendu al Servilo',
button2Img: 'Ĉu vi volas transformi la selektitan bildbutonon en simplan bildon?',
hSpace: 'Horizontala Spaco',
img2Button: 'Ĉu vi volas transformi la selektitan bildon en bildbutonon?',
infoTab: 'Informoj pri Bildo',
linkTab: 'Ligilo',
lockRatio: 'Konservi Proporcion',
menu: 'Atributoj de Bildo',
resetSize: 'Origina Grando',
title: 'Atributoj de Bildo',
titleButton: 'Bildbutonaj Atributoj',
upload: 'Alŝuti',
urlMissing: 'La fontretadreso de la bildo mankas.',
vSpace: 'Vertikala Spaco',
validateBorder: 'La bordero devas esti entjera nombro.',
validateHSpace: 'La horizontala spaco devas esti entjera nombro.',
validateVSpace: 'La vertikala spaco devas esti entjera nombro.'
});
|
package aeminium.runtime.tools.benchmark;
public class RTBench {
private static Benchmark[] benchmarks = {
new <API key>(),
new <API key>(),
new LinearTaskGraph(),
new <API key>(),
new ChildTaskBenchmark(),
new FibonacciBenchmark()
};
public static void usage() {
System.out.println();
System.out.println("java aeminium.runtime.tools.benchmark.RTBench COMMAND");
System.out.println("");
System.out.println("COMMANDS:");
System.out.println(" list - List available benchmarks.");
System.out.println(" run BENCHMARK - Run specified benchmark.");
System.out.println();
}
public static void main(String[] args) {
if ( args.length == 0 ) {
usage();
return;
}
if ( args[0].equals("list") ) {
for( Benchmark benchmark : benchmarks ) {
System.out.println(benchmark.getName());
}
} else if ( args[0].equals("run") && args.length == 2 ) {
Benchmark benchmark = null;
for ( Benchmark b : benchmarks ) {
if ( b.getName().equals(args[1])) {
benchmark = b;
}
}
if ( benchmark != null ) {
Reporter reporter = new <API key>();
reporter.startBenchmark(benchmark.getName());
benchmark.run(reporter);
reporter.stopBenchmark(benchmark.getName());
reporter.flush();
} else {
usage();
}
} else {
usage();
}
}
protected static void reportVMStats(Reporter reporter) {
reporter.reportLn(String.format("Memory (TOTAL/MAX/FREE) (%d,%d,%d)", Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory(),
Runtime.getRuntime().freeMemory()));
}
}
|
<h1><?php the_issuu_message('Document'); ?></h1>
<form action="" method="post" id="document-upload">
<input type="hidden" name="name" value="<?= $doc->name; ?>">
<table class="form-table">
<tbody>
<tr>
<th><label for="title"><?php the_issuu_message('Title'); ?></label></th>
<td><input type="text" name="title" id="title" class="regular-text code" value="<?= $doc->title; ?>"></td>
</tr>
<tr>
<th><label for="description"><?php the_issuu_message('Description'); ?></label></th>
<td>
<textarea name="description" id="description" cols="45" rows="6"><?= $doc->description; ?></textarea>
</td>
</tr>
<tr>
<th><label for="tags">Tags</label></th>
<td>
<textarea name="tags" id="tags" cols="45" rows="6"><?= $tags; ?></textarea>
<p class="description">
<?php the_issuu_message('Use commas to separate tags. Do not use spaces.'); ?>
</p>
</td>
</tr>
<tr>
<th><label><?php the_issuu_message('Publish date'); ?></label></th>
<td>
<input type="text" name="pub[day]" id="dia" placeholder="<?php the_issuu_message('Day'); ?>" class="small-text"
maxlength="2" value="<?= date('d', strtotime($doc->publishDate)); ?>"> /
<input type="text" name="pub[month]" id="mes" placeholder="<?php the_issuu_message('Month'); ?>" class="small-text"
maxlength="2" value="<?= date('m', strtotime($doc->publishDate)); ?>"> /
<input type="text" name="pub[year]" id="ano" placeholder="<?php the_issuu_message('Year'); ?>" class="small-text"
maxlength="4" value="<?= date('Y', strtotime($doc->publishDate)); ?>">
<p class="description">
<?php the_issuu_message('Date of publication of the document.<br><strong>NOTE:</strong> If you do not enter a value, the current date will be used'); ?>
</p>
</td>
</tr>
<tr>
<th><label for="commentsAllowed"><?php the_issuu_message('Allow comments'); ?></label></th>
<td>
<input type="checkbox" name="commentsAllowed" id="commentsAllowed" value="true"
<?= ($doc->commentsAllowed == true)? 'checked' : ''; ?>>
</td>
</tr>
<tr>
<th><label for="downloadable"><?php the_issuu_message('Allow file download'); ?></label></th>
<td>
<input type="checkbox" name="downloadable" id="downloadable" value="true"
<?= ($doc->downloadable == true)? 'checked' : ''; ?>>
</td>
</tr>
<tr>
<th><label><?php the_issuu_message('Access'); ?></label></th>
<td>
<?php if ($doc->access == 'private') : ?>
<p><strong><?php the_issuu_message('Private'); ?></strong></p>
<p class="description">
<?php the_issuu_message('To publish this document <a href="http://issuu.com/home/publications" target="_blank">click here</a>'); ?>
</p>
<?php else: ?>
<p><strong><?php the_issuu_message('Public'); ?></strong></p>
<?php endif; ?>
</td>
</tr>
<tr>
<th>
<input type="submit" class="button-primary" value="<?php the_issuu_message('Update'); ?>">
<h3>
<a href="admin.php?page=<API key>" style="text-decoration: none;">
<?php the_issuu_message('Back'); ?>
</a>
</h3>
</th>
</tr>
</tbody>
</table>
</form>
|
#include "component.h"
#include "entity.h"
namespace entity {
Component::Component(Entity* parent) : QObject(parent) {
if (parent != NULL) {
parent->addComponent(this);
}
}
}
uint qHash(entity::HashableComponent* key, uint seed) {
return key == 0 ? 0 : key->hash(seed);
}
|
#include "fontforgeui.h"
#include "groups.h"
#include <unistd.h>
#include <ustring.h>
#include <utype.h>
#include <gkeysym.h>
#include <math.h>
#define COLOR_CHOOSE (-10)
static GTextInfo std_colors[] = {
{ (unichar_t *) N_("Select by Color"), NULL, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) N_("Color|Choose..."), NULL, 0, 0, (void *) COLOR_CHOOSE, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ (unichar_t *) N_("Color|Default"), &def_image, 0, 0, (void *) COLOR_DEFAULT, NULL, 0, 1, 0, 0, 0, 0, 1, 0, 0, '\0' },
{ NULL, &white_image, 0, 0, (void *) 0xffffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &red_image, 0, 0, (void *) 0xff0000, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &green_image, 0, 0, (void *) 0x00ff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &blue_image, 0, 0, (void *) 0x0000ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &yellow_image, 0, 0, (void *) 0xffff00, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &cyan_image, 0, 0, (void *) 0x00ffff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
{ NULL, &magenta_image, 0, 0, (void *) 0xff00ff, NULL, 0, 1, 0, 0, 0, 0, 0, 0, 0, '\0' },
GTEXTINFO_EMPTY
};
struct groupdlg {
unsigned int oked: 1;
unsigned int done: 1;
unsigned int select_many: 1;
/* define groups can only select one group at a time, select/restrict */
/* to groups can select multiple things */
unsigned int select_kids_too: 1;
/* When we select a parent group do we want to select all the kids? */
Group *root;
Group *oldsel;
int open_cnt, lines_page, off_top, off_left, page_width, bmargin;
int maxl;
GWindow gw,v;
GGadget *vsb, *hsb, *cancel, *ok, *compact;
GGadget *newsub, *delete, *line1, *gpnamelab, *gpname, *glyphslab, *glyphs;
GGadget *idlab, *idname, *iduni, *set, *select, *unique, *colour, *line2;
int fh, as;
GFont *font;
FontView *fv;
void (*select_callback)(struct groupdlg *);
GTimer *showchange;
};
extern int _GScrollBar_Width;
static Group *GroupFindLPos(Group *group,int lpos,int *depth) {
int i;
forever {
if ( group->lpos==lpos )
return( group );
if ( !group->open )
return( NULL );
for ( i=0; i<group->kid_cnt-1; ++i ) {
if ( lpos<group->kids[i+1]->lpos )
break;
}
group = group->kids[i];
++*depth;
}
}
static int GroupPosInParent(Group *group) {
Group *parent = group->parent;
int i;
if ( parent==NULL )
return( 0 );
for ( i=0; i<parent->kid_cnt; ++i )
if ( parent->kids[i]==group )
return( i );
return( -1 );
}
static Group *GroupNext(Group *group,int *depth) {
if ( group->open && group->kids ) {
++*depth;
return( group->kids[0] );
}
forever {
int pos;
if ( group->parent==NULL )
return( NULL );
pos = GroupPosInParent(group);
if ( pos+1<group->parent->kid_cnt )
return( group->parent->kids[pos+1] );
group = group->parent;
--*depth;
}
}
static Group *GroupPrev(struct groupdlg *grp, Group *group,int *depth) {
int pos;
while ( group->parent!=NULL && group==group->parent->kids[0] ) {
group = group->parent;
--*depth;
}
if ( group->parent==NULL )
return( NULL );
pos = GroupPosInParent(group);
group = group->parent->kids[pos-1];
while ( group->open ) {
group = group->kids[group->kid_cnt-1];
++*depth;
}
return( group );
}
static int _GroupSBSizes(struct groupdlg *grp, Group *group, int lpos, int depth) {
int i, len;
group->lpos = lpos++;
len = 5+8*depth+ grp->as + 5 + GDrawGetText8Width(grp->v,group->name,-1);
if ( group->glyphs!=NULL )
len += 5 + GDrawGetText8Width(grp->v,group->glyphs,-1);
if ( len > grp->maxl )
grp->maxl = len;
if ( group->open ) {
for ( i=0; i< group->kid_cnt; ++i )
lpos = _GroupSBSizes(grp,group->kids[i],lpos,depth+1);
}
return( lpos );
}
static int GroupSBSizes(struct groupdlg *grp) {
int lpos;
grp->maxl = 0;
GDrawSetFont(grp->v,grp->font);
lpos = _GroupSBSizes(grp,grp->root,0,0);
grp->maxl += 5; /* margin */
GScrollBarSetBounds(grp->vsb,0,lpos,grp->lines_page);
GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width);
grp->open_cnt = lpos;
return( lpos );
}
static void GroupSelectKids(Group *group,int sel) {
int i;
group->selected = sel;
for ( i=0; i<group->kid_cnt; ++i )
GroupSelectKids(group->kids[i],sel);
}
static void GroupDeselectAllBut(Group *root,Group *group) {
int i;
if ( root!=group )
root->selected = false;
for ( i=0; i<root->kid_cnt; ++i )
GroupDeselectAllBut(root->kids[i],group);
}
static Group *<API key>(Group *group) {
int i;
Group *sel;
if ( group->selected )
return( group );
for ( i=0; i<group->kid_cnt; ++i ) {
sel = <API key>(group->kids[i]);
if ( sel!=NULL )
return( sel );
}
return( NULL );
}
static Group *<API key>(struct groupdlg *grp) {
if ( grp->select_many )
return( NULL );
return( <API key>(grp->root));
}
static void GroupWExpose(struct groupdlg *grp,GWindow pixmap,GRect *rect) {
int depth, y, len;
Group *group;
GRect r;
Color fg;
GDrawFillRect(pixmap,rect,<API key>(NULL));
GDrawSetLineWidth(pixmap,0);
r.height = r.width = grp->as;
y = (rect->y/grp->fh) * grp->fh + grp->as;
depth=0;
group = GroupFindLPos(grp->root,rect->y/grp->fh+grp->off_top,&depth);
GDrawSetFont(pixmap,grp->font);
while ( group!=NULL ) {
r.y = y-grp->as+1;
r.x = 5+8*depth - grp->off_left;
fg = group->selected ? 0xff0000 : 0x000000;
if ( group->glyphs==NULL ) {
GDrawDrawRect(pixmap,&r,fg);
GDrawDrawLine(pixmap,r.x+2,r.y+grp->as/2,r.x+grp->as-2,r.y+grp->as/2,
fg);
if ( !group->open )
GDrawDrawLine(pixmap,r.x+grp->as/2,r.y+2,r.x+grp->as/2,r.y+grp->as-2,
fg);
}
len = GDrawDrawText8(pixmap,r.x+r.width+5,y,group->name,-1,fg);
if ( group->glyphs )
GDrawDrawText8(pixmap,r.x+r.width+5+len+5,y,group->glyphs,-1,fg);
group = GroupNext(group,&depth);
y += grp->fh;
if ( y-grp->fh>rect->y+rect->height )
break;
}
}
static void GroupWMouse(struct groupdlg *grp,GEvent *event) {
int x;
int depth=0;
Group *group;
group = GroupFindLPos(grp->root,event->u.mouse.y/grp->fh+grp->off_top,&depth);
if ( group==NULL )
return;
x = 5+8*depth - grp->off_left;
if ( event->u.mouse.x<x )
return;
if ( event->u.mouse.x<=x+grp->as ) {
if ( group->glyphs != NULL )
return;
group->open = !group->open;
GroupSBSizes(grp);
} else {
group->selected = !group->selected;
if ( grp->select_kids_too )
GroupSelectKids(group,group->selected);
else if ( group->selected && !grp->select_many )
GroupDeselectAllBut(grp->root,group);
if ( grp->select_callback!=NULL )
(grp->select_callback)(grp);
}
GDrawRequestExpose(grp->v,NULL,false);
}
static void GroupScroll(struct groupdlg *grp,struct sbevent *sb) {
int newpos = grp->off_top;
switch( sb->type ) {
case et_sb_top:
newpos = 0;
break;
case et_sb_uppage:
newpos -= grp->lines_page;
break;
case et_sb_up:
--newpos;
break;
case et_sb_down:
++newpos;
break;
case et_sb_downpage:
newpos += grp->lines_page;
break;
case et_sb_bottom:
newpos = grp->open_cnt-grp->lines_page;
break;
case et_sb_thumb:
case et_sb_thumbrelease:
newpos = sb->pos;
break;
}
if ( newpos>grp->open_cnt-grp->lines_page )
newpos = grp->open_cnt-grp->lines_page;
if ( newpos<0 ) newpos =0;
if ( newpos!=grp->off_top ) {
int diff = newpos-grp->off_top;
grp->off_top = newpos;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,diff*grp->fh);
}
}
static void GroupHScroll(struct groupdlg *grp,struct sbevent *sb) {
int newpos = grp->off_left;
switch( sb->type ) {
case et_sb_top:
newpos = 0;
break;
case et_sb_uppage:
newpos -= grp->page_width;
break;
case et_sb_up:
--newpos;
break;
case et_sb_down:
++newpos;
break;
case et_sb_downpage:
newpos += grp->page_width;
break;
case et_sb_bottom:
newpos = grp->maxl-grp->page_width;
break;
case et_sb_thumb:
case et_sb_thumbrelease:
newpos = sb->pos;
break;
}
if ( newpos>grp->maxl-grp->page_width )
newpos = grp->maxl-grp->page_width;
if ( newpos<0 ) newpos =0;
if ( newpos!=grp->off_left ) {
int diff = newpos-grp->off_left;
grp->off_left = newpos;
GScrollBarSetPos(grp->hsb,grp->off_left);
GDrawScroll(grp->v,NULL,-diff,0);
}
}
static void GroupResize(struct groupdlg *grp,GEvent *event) {
GRect size, wsize;
int lcnt, offy;
int sbsize = GDrawPointsToPixels(grp->gw,_GScrollBar_Width);
GDrawGetSize(grp->gw,&size);
lcnt = (size.height-grp->bmargin)/grp->fh;
GGadgetResize(grp->vsb,sbsize,lcnt*grp->fh);
GGadgetMove(grp->vsb,size.width-sbsize,0);
GGadgetResize(grp->hsb,size.width-sbsize,sbsize);
GGadgetMove(grp->hsb,0,lcnt*grp->fh);
GDrawResize(grp->v,size.width-sbsize,lcnt*grp->fh);
grp->page_width = size.width-sbsize;
grp->lines_page = lcnt;
GScrollBarSetBounds(grp->vsb,0,grp->open_cnt,grp->lines_page);
GScrollBarSetBounds(grp->hsb,0,grp->maxl,grp->page_width);
GGadgetGetSize(grp->cancel,&wsize);
offy = size.height-wsize.height-6 - wsize.y;
GGadgetMove(grp->cancel,size.width-wsize.width-30, wsize.y+offy);
GGadgetMove(grp->ok , 30-3,wsize.y+offy-3);
if ( grp->newsub!=NULL ) {
GGadgetGetSize(grp->newsub,&wsize);
GGadgetMove(grp->newsub,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->delete,&wsize);
GGadgetMove(grp->delete,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->line1,&wsize);
GGadgetMove(grp->line1,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->gpnamelab,&wsize);
GGadgetMove(grp->gpnamelab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->gpname,&wsize);
GGadgetMove(grp->gpname,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->glyphslab,&wsize);
GGadgetMove(grp->glyphslab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->glyphs,&wsize);
GGadgetMove(grp->glyphs,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->idlab,&wsize);
GGadgetMove(grp->idlab,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->idname,&wsize);
GGadgetMove(grp->idname,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->iduni,&wsize);
GGadgetMove(grp->iduni,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->set,&wsize);
GGadgetMove(grp->set,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->select,&wsize);
GGadgetMove(grp->select,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->unique,&wsize);
GGadgetMove(grp->unique,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->colour,&wsize);
GGadgetMove(grp->colour,wsize.x,wsize.y+offy);
GGadgetGetSize(grp->line2,&wsize);
GGadgetMove(grp->line2,wsize.x,wsize.y+offy);
} else {
GGadgetGetSize(grp->compact,&wsize);
GGadgetMove(grp->compact,wsize.x,wsize.y+offy);
}
GDrawRequestExpose(grp->v,NULL,true);
GDrawRequestExpose(grp->gw,NULL,true);
}
static void GroupWChangeCurrent(struct groupdlg *grp,Group *current,Group *next ) {
if ( current!=NULL )
current->selected = false;
next->selected = true;
if ( next->lpos<grp->off_top || next->lpos>=grp->off_top+grp->lines_page ) {
if ( next->lpos>=grp->off_top+grp->lines_page )
grp->off_top = next->lpos;
else {
grp->off_top = next->lpos-grp->lines_page-1;
if ( grp->off_top<0 ) grp->off_top = 0;
}
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawRequestExpose(grp->v,NULL,false);
}
}
static int GroupChar(struct groupdlg *grp,GEvent *event) {
int depth = 0;
int pos;
Group *current = <API key>(grp);
switch (event->u.chr.keysym) {
case GK_F1: case GK_Help:
help("groups.html");
return( true );
case GK_Return: case GK_KP_Enter:
if ( current!=NULL ) {
current->open = !current->open;
GroupSBSizes(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
case GK_Page_Down: case GK_KP_Page_Down:
pos = grp->off_top+(grp->lines_page<=1?1:grp->lines_page-1);
if ( pos >= grp->open_cnt-grp->lines_page )
pos = grp->open_cnt-grp->lines_page;
if ( pos<0 ) pos = 0;
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
return( true );
case GK_Down: case GK_KP_Down:
if ( current==NULL || (event->u.chr.state&ksm_control)) {
if ( grp->off_top<grp->open_cnt-1 ) {
++grp->off_top;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,grp->fh);
}
} else
GroupWChangeCurrent(grp,current,GroupNext(current,&depth));
return( true );
case GK_Up: case GK_KP_Up:
if ( current==NULL || (event->u.chr.state&ksm_control)) {
if (grp->off_top!=0 ) {
--grp->off_top;
GScrollBarSetPos(grp->vsb,grp->off_top);
GDrawScroll(grp->v,NULL,0,-grp->fh);
}
} else
GroupWChangeCurrent(grp,current,GroupPrev(grp,current,&depth));
return( true );
case GK_Page_Up: case GK_KP_Page_Up:
pos = grp->off_top-(grp->lines_page<=1?1:grp->lines_page-1);
if ( pos<0 ) pos = 0;
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
return( true );
case GK_Left: case GK_KP_Left:
if ( !grp->select_many && current!=NULL )
GroupWChangeCurrent(grp,current,current->parent);
return( true );
case GK_Right: case GK_KP_Right:
if ( !grp->select_many && current != NULL && current->kid_cnt!=0 ) {
if ( !current->open ) {
current->open = !current->open;
GroupSBSizes(grp);
}
GroupWChangeCurrent(grp,current,current->kids[0]);
}
return( true );
case GK_Home: case GK_KP_Home:
if ( grp->off_top!=0 ) {
grp->off_top = 0;
GScrollBarSetPos(grp->vsb,0);
GDrawRequestExpose(grp->v,NULL,false);
}
if ( !grp->select_many )
GroupWChangeCurrent(grp,current,grp->root);
return( true );
case GK_End: case GK_KP_End:
pos = grp->open_cnt-grp->lines_page;
if ( pos<0 ) pos = 0;
if ( pos!=grp->off_top ) {
grp->off_top = pos;
GScrollBarSetPos(grp->vsb,pos);
GDrawRequestExpose(grp->v,NULL,false);
}
if ( !grp->select_many )
GroupWChangeCurrent(grp,current,GroupFindLPos(grp->root,grp->open_cnt-1,&depth));
return( true );
}
return( false );
}
static int grpv_e_h(GWindow gw, GEvent *event) {
struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw);
if (( event->type==et_mouseup || event->type==et_mousedown ) &&
(event->u.mouse.button>=4 && event->u.mouse.button<=7) ) {
return( <API key>(grp->vsb,event));
}
switch ( event->type ) {
case et_expose:
GroupWExpose(grp,gw,&event->u.expose.rect);
break;
case et_char:
return( GroupChar(grp,event));
case et_mouseup:
GroupWMouse(grp,event);
break;
}
return( true );
}
static void GroupWCreate(struct groupdlg *grp,GRect *pos) {
FontRequest rq;
int as, ds, ld;
GGadgetCreateData gcd[5];
GTextInfo label[4];
int sbsize = GDrawPointsToPixels(NULL,_GScrollBar_Width);
GWindowAttrs wattrs;
static GFont *font=NULL;
if ( font==NULL ) {
memset(&rq,'\0',sizeof(rq));
rq.utf8_family_name = SANS_UI_FAMILIES;
rq.point_size = 12;
rq.weight = 400;
font = <API key>(grp->gw,&rq);
font = GResourceFindFont("Groups.Font",font);
}
grp->font = font;
<API key>(grp->gw,grp->font,&as,&ds,&ld);
grp->fh = as+ds; grp->as = as;
grp->lines_page = (pos->height-grp->bmargin)/grp->fh;
grp->page_width = pos->width-sbsize;
wattrs.mask = wam_events|wam_cursor/*|wam_bordwidth|wam_bordcol*/;
wattrs.event_masks = ~0;
wattrs.border_width = 1;
wattrs.border_color = 0x000000;
wattrs.cursor = ct_pointer;
pos->x = 0; pos->y = 0;
pos->width -= sbsize; pos->height = grp->lines_page*grp->fh;
grp->v = <API key>(grp->gw,pos,grpv_e_h,grp,&wattrs);
GDrawSetVisible(grp->v,true);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
gcd[0].gd.pos.x = pos->width; gcd[0].gd.pos.y = 0;
gcd[0].gd.pos.width = sbsize;
gcd[0].gd.pos.height = pos->height;
gcd[0].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels | gg_sb_vert;
gcd[0].creator = GScrollBarCreate;
gcd[1].gd.pos.x = 0; gcd[1].gd.pos.y = pos->height;
gcd[1].gd.pos.height = sbsize;
gcd[1].gd.pos.width = pos->width;
gcd[1].gd.flags = gg_visible | gg_enabled | gg_pos_in_pixels;
gcd[1].creator = GScrollBarCreate;
GGadgetsCreate(grp->gw,gcd);
grp->vsb = gcd[0].ret;
grp->hsb = gcd[1].ret;
}
static int <API key>(int seek,char *str) {
char *start;
if ( str==NULL )
return( false );
while ( *str!='\0' ) {
while ( *str==' ' ) ++str;
start = str;
while ( *str!=' ' && *str!='\0' ) ++str;
if ( start==str )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) {
char *end;
int val = strtol(start+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
if ( seek>=val && seek<=val2 )
return( true );
}
}
return( false );
}
static int <API key>(char *name,char *str) {
char *start;
if ( str==NULL )
return( false );
while ( *str!='\0' ) {
while ( *str==' ' ) ++str;
start = str;
while ( *str!=' ' && *str!='\0' ) ++str;
if ( start==str )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' )
/* Skip it */;
else {
int ch = *str;
*str = '\0';
if ( strcmp(name,start)==0 ) {
*str = ch;
return( true );
}
*str = ch;
}
}
return( false );
}
static Group *FindDuplicateNumber(Group *top,int val,Group *cur,char *str) {
int i;
Group *grp;
if ( <API key>(val,str))
return( cur );
if ( top==cur )
return( NULL );
if ( <API key>(val,top->glyphs))
return( top );
for ( i=0; i<top->kid_cnt; ++i )
if ( (grp = FindDuplicateNumber(top->kids[i],val,cur,NULL))!=NULL )
return( grp );
return( NULL );
}
static Group *FindDuplicateName(Group *top,char *name,Group *cur,char *str) {
int i;
Group *grp;
if ( <API key>(name,str))
return( cur );
if ( top==cur )
return( NULL );
if ( <API key>(name,top->glyphs))
return( top );
for ( i=0; i<top->kid_cnt; ++i )
if ( (grp = FindDuplicateName(top->kids[i],name,cur,NULL))!=NULL )
return( grp );
return( NULL );
}
static int GroupValidateGlyphs(Group *cur,char *g,const unichar_t *gu,int unique) {
char *gpt, *start;
Group *top, *grp;
if ( gu!=NULL ) {
for ( ; *gu!='\0'; ++gu ) {
if ( *gu<' ' || *gu>=0x7f || *gu=='(' || *gu==')' ||
*gu=='[' || *gu==']' || *gu=='{' || *gu=='}' ||
*gu=='<' || *gu=='>' || *gu=='%' || *gu=='/' ) {
ff_post_error(_("Glyph names must be valid postscript names"),_("Glyph names must be valid postscript names"));
return( false );
}
}
}
if ( unique ) { /* Can't use cur->unique because it hasn't been set yet */
top = cur;
while ( top->parent!=NULL && top->parent->unique )
top = top->parent;
for ( gpt=g; *gpt!='\0' ; ) {
while ( *gpt==' ' ) ++gpt;
start = gpt;
while ( *gpt!=' ' && *gpt!='\0' ) ++gpt;
if ( start==gpt )
break;
if ( (start[0]=='U' || start[0]=='u') && start[1]=='+' ) {
char *end;
int val = strtol(start+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
if ( val2<val ) {
ff_post_error(_("Bad Range"),_("Bad Range, start (%1$04X) is greater than end (%2$04X)"), val, val2 );
return( false );
}
for ( ; val<=val2; ++val )
if ( (grp=FindDuplicateNumber(top,val,cur,gpt))!=NULL ) {
ff_post_error(_("Duplicate Name"),_("The code point U+%1$04X occurs in groups %2$.30s and %3$.30s"), val, cur->name, grp->name);
return( false );
}
} else {
int ch = *gpt;
*gpt = '\0';
if ( (grp=FindDuplicateName(top,start,cur,ch!='\0'?gpt+1:NULL))!=NULL ) {
ff_post_error(_("Duplicate Name"),_("The glyph name \"%1$.30s\" occurs in groups %2$.30s and %3$.30s"), start, cur->name, grp->name);
*gpt = ch;
return( false );
}
*gpt = ch;
}
}
}
return( true );
}
static int GroupSetKidsUnique(Group *group) {
int i;
group->unique = true;
for ( i=0; i<group->kid_cnt; ++i )
if ( !GroupSetKidsUnique(group->kids[i]))
return( false );
if ( group->glyphs!=NULL ) {
if ( !GroupValidateGlyphs(group,group->glyphs,NULL,true))
return( false );
}
return( true );
}
static int GroupFinishOld(struct groupdlg *grp) {
if ( grp->oldsel!=NULL ) {
const unichar_t *gu = _GGadgetGetTitle(grp->glyphs);
char *g = cu_copy(gu);
int oldunique = grp->oldsel->unique;
if ( !GroupValidateGlyphs(grp->oldsel,g,gu,GGadgetIsChecked(grp->unique))) {
free(g);
return( false );
}
free(grp->oldsel->name);
grp->oldsel->name = GGadgetGetTitle8(grp->gpname);
free(grp->oldsel->glyphs);
if ( *g=='\0' ) {
grp->oldsel->glyphs = NULL;
free(g);
} else
grp->oldsel->glyphs = g;
grp->oldsel->unique = GGadgetIsChecked(grp->unique);
if ( grp->oldsel->unique && !oldunique ) {
/* The just set the unique bit. We must force it set in all */
/* kids. We really should check for uniqueness too!!!!! */
if ( !GroupSetKidsUnique(grp->oldsel))
return( false );
}
}
return( true );
}
static void GroupSelected(struct groupdlg *grp) {
Group *current = <API key>(grp);
if ( !GroupFinishOld(grp)) {
if ( current!=NULL )
current->selected=false;
if ( grp->oldsel!=NULL )
grp->oldsel->selected = true;
return;
}
grp->oldsel = current;
if ( current == NULL ) {
GGadgetSetEnabled(grp->newsub,false);
GGadgetSetEnabled(grp->delete,false);
GGadgetSetEnabled(grp->gpnamelab,false);
GGadgetSetEnabled(grp->gpname,false);
GGadgetSetEnabled(grp->glyphslab,false);
GGadgetSetEnabled(grp->glyphs,false);
GGadgetSetEnabled(grp->set,false);
GGadgetSetEnabled(grp->select,false);
GGadgetSetEnabled(grp->unique,false);
GGadgetSetEnabled(grp->colour,false);
} else {
unichar_t *glyphs = uc_copy(current->glyphs);
GGadgetSetTitle8(grp->gpname,current->name);
if ( glyphs==NULL ) glyphs = uc_copy("");
GGadgetSetTitle(grp->glyphs,glyphs);
free(glyphs);
GGadgetSetChecked(grp->unique,current->unique);
GGadgetSetEnabled(grp->newsub,current->glyphs==NULL || *current->glyphs=='\0');
GGadgetSetEnabled(grp->delete,current->parent!=NULL);
GGadgetSetEnabled(grp->gpnamelab,true);
GGadgetSetEnabled(grp->gpname,true);
GGadgetSetEnabled(grp->glyphslab,current->kid_cnt==0);
GGadgetSetEnabled(grp->glyphs,current->kid_cnt==0);
GGadgetSetEnabled(grp->set,current->kid_cnt==0);
GGadgetSetEnabled(grp->select,current->kid_cnt==0);
GGadgetSetEnabled(grp->unique,current->parent==NULL || !current->parent->unique);
GGadgetSetEnabled(grp->colour,current->kid_cnt==0);
}
}
static void GroupShowChange(struct groupdlg *grp) {
if ( GroupFinishOld(grp))
GDrawRequestExpose(grp->v,NULL,false);
grp->showchange = NULL;
}
static int <API key>(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_textchanged ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
const unichar_t *glyphs = _GGadgetGetTitle(g);
GGadgetSetEnabled(grp->newsub,*glyphs=='\0');
if ( grp->showchange!=NULL )
GDrawCancelTimer(grp->showchange);
grp->showchange = GDrawRequestTimer(grp->gw,500,0,NULL);
}
return( true );
}
static int Group_ToSelection(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
const unichar_t *ret = _GGadgetGetTitle(grp->glyphs);
SplineFont *sf = grp->fv->b.sf;
FontView *fv = grp->fv;
const unichar_t *end;
int pos, found=-1;
char *nm;
GDrawSetVisible(fv->gw,true);
GDrawRaise(fv->gw);
memset(fv->b.selected,0,fv->b.map->enccount);
while ( *ret ) {
end = u_strchr(ret,' ');
if ( end==NULL ) end = ret+u_strlen(ret);
nm = cu_copybetween(ret,end);
for ( ret = end; isspace(*ret); ++ret);
if ( (nm[0]=='U' || nm[0]=='u') && nm[1]=='+' ) {
char *end;
int val = strtol(nm+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
for ( ; val<=val2; ++val ) {
if (( pos = SFFindSlot(sf,fv->b.map,val,NULL))!=-1 ) {
if ( found==-1 ) found = pos;
if ( pos!=-1 )
fv->b.selected[pos] = true;
}
}
} else if ( strncasecmp(nm,"color=#",strlen("color=#"))==0 ) {
Color col = strtoul(nm+strlen("color=#"),NULL,16);
int gid; SplineChar *sc;
for ( pos=0; pos<fv->b.map->enccount; ++pos )
if ( (gid=fv->b.map->map[pos])!=-1 &&
(sc = sf->glyphs[gid])!=NULL &&
sc->color == col )
fv->b.selected[pos] = true;
} else {
if (( pos = SFFindSlot(sf,fv->b.map,-1,nm))!=-1 ) {
if ( found==-1 ) found = pos;
if ( pos!=-1 )
fv->b.selected[pos] = true;
}
}
free(nm);
}
if ( found!=-1 )
FVScrollToChar(fv,found);
GDrawRequestExpose(fv->v,NULL,false);
}
return( true );
}
static int Group_FromSelection(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
SplineFont *sf = grp->fv->b.sf;
FontView *fv = grp->fv;
unichar_t *vals, *pt;
int i, len, max, gid, k;
SplineChar *sc, dummy;
char buffer[20];
if ( GGadgetIsChecked(grp->idname) ) {
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
len += strlen(sc->name)+1;
if ( fv->b.selected[i]>max ) max = fv->b.selected[i];
}
pt = vals = galloc((len+1)*sizeof(unichar_t));
*pt = '\0';
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
uc_strcpy(pt,sc->name);
pt += u_strlen(pt);
*pt++ = ' ';
}
if ( pt>vals ) pt[-1]='\0';
} else {
vals = NULL;
for ( k=0; k<2; ++k ) {
int last=-2, start=-2;
len = 0;
for ( i=len=max=0; i<fv->b.map->enccount; ++i ) if ( fv->b.selected[i]) {
gid = fv->b.map->map[i];
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
sc = sf->glyphs[gid];
else
sc = SCBuildDummy(&dummy,sf,fv->b.map,i);
if ( sc->unicodeenc==-1 )
continue;
if ( sc->unicodeenc==last+1 )
last = sc->unicodeenc;
else {
if ( last!=-2 ) {
if ( start!=last )
sprintf( buffer, "U+%04X-U+%04X ", start, last );
else
sprintf( buffer, "U+%04X ", start );
if ( vals!=NULL )
uc_strcpy(vals+len,buffer);
len += strlen(buffer);
}
start = last = sc->unicodeenc;
}
}
if ( last!=-2 ) {
if ( start!=last )
sprintf( buffer, "U+%04X-U+%04X ", start, last );
else
sprintf( buffer, "U+%04X ", start );
if ( vals!=NULL )
uc_strcpy(vals+len,buffer);
len += strlen(buffer);
}
if ( !k )
vals = galloc((len+1)*sizeof(unichar_t));
else if ( len!=0 )
vals[len-1] = '\0';
else
*vals = '\0';
}
}
GGadgetSetTitle(grp->glyphs,vals);
free(vals);
}
return( true );
}
static int Group_AddColor(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_listselected ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
GTextInfo *ti = <API key>(g);
int set=false;
Color xcol=0;
if ( ti==NULL )
/* Can't happen */;
else if ( ti->userdata == (void *) COLOR_CHOOSE ) {
struct hslrgb col, font_cols[6];
memset(&col,0,sizeof(col));
col = GWidgetColor(_("Pick a color"),&col,SFFontCols(grp->fv->b.sf,font_cols));
if ( col.rgb ) {
xcol = (((int) rint(255.*col.r))<<16 ) |
(((int) rint(255.*col.g))<<8 ) |
(((int) rint(255.*col.b)) );
set = true;
}
} else {
xcol = (intpt) ti->userdata;
set = true;
}
if ( set ) {
char buffer[40]; unichar_t ubuf[40];
sprintf(buffer," color=#%06x", xcol );
uc_strcpy(ubuf,buffer);
GTextFieldReplace(grp->glyphs,ubuf);
if ( grp->showchange==NULL )
GroupShowChange(grp);
}
<API key>(g,0);
}
return( true );
}
static int Group_NewSubGroup(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
Group *new_grp;
if ( !GroupFinishOld(grp))
return( true );
GDrawRequestExpose(grp->v,NULL,false);
if ( grp->oldsel==NULL )
return( true );
if ( grp->oldsel->glyphs!=NULL && grp->oldsel->glyphs!='\0' ) {
GGadgetSetEnabled(grp->newsub,false);
return( true );
}
grp->oldsel->kids = grealloc(grp->oldsel->kids,(++grp->oldsel->kid_cnt)*sizeof(Group *));
grp->oldsel->kids[grp->oldsel->kid_cnt-1] = new_grp = chunkalloc(sizeof(Group));
new_grp->parent = grp->oldsel;
new_grp->unique = grp->oldsel->unique;
new_grp->name = copy(_("UntitledGroup"));
grp->oldsel->selected = false;
grp->oldsel->open = true;
new_grp->selected = true;
GroupSBSizes(grp);
GroupSelected(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
}
static int Group_Delete(GGadget *g, GEvent *e) {
if ( e->type==et_controlevent && e->u.control.subtype == et_buttonactivate ) {
struct groupdlg *grp = GDrawGetUserData(GGadgetGetWindow(g));
Group *parent;
int pos, i;
if ( grp->oldsel==NULL || grp->oldsel->parent==NULL )
return( true );
parent = grp->oldsel->parent;
pos = GroupPosInParent(grp->oldsel);
if ( pos==-1 )
return( true );
for ( i=pos; i<parent->kid_cnt-1; ++i )
parent->kids[i] = parent->kids[i+1];
--parent->kid_cnt;
GroupFree(grp->oldsel);
grp->oldsel = NULL;
GroupSBSizes(grp);
GroupSelected(grp);
GDrawRequestExpose(grp->v,NULL,false);
}
return( true );
}
static int displaygrp_e_h(GWindow gw, GEvent *event) {
struct groupdlg *grp = (struct groupdlg *) GDrawGetUserData(gw);
if (( event->type==et_mouseup || event->type==et_mousedown ) &&
(event->u.mouse.button>=4 && event->u.mouse.button<=7) ) {
return( <API key>(grp->vsb,event));
}
if ( grp==NULL )
return( true );
switch ( event->type ) {
case et_expose:
break;
case et_char:
return( GroupChar(grp,event));
break;
case et_timer:
GroupShowChange(grp);
break;
case et_resize:
if ( event->u.resize.sized )
GroupResize(grp,event);
break;
case et_controlevent:
switch ( event->u.control.subtype ) {
case et_scrollbarchange:
if ( event->u.control.g == grp->vsb )
GroupScroll(grp,&event->u.control.u.sb);
else
GroupHScroll(grp,&event->u.control.u.sb);
break;
case et_buttonactivate:
grp->done = true;
grp->oked = event->u.control.g == grp->ok;
break;
}
break;
case et_close:
grp->done = true;
break;
case et_destroy:
if ( grp->newsub!=NULL )
free(grp);
return( true );
}
if ( grp->done && grp->newsub!=NULL ) {
if ( grp->oked ) {
if ( !GroupFinishOld(grp)) {
grp->done = grp->oked = false;
return( true );
}
GroupFree(group_root);
if ( grp->root->kid_cnt==0 && grp->root->glyphs==NULL ) {
group_root = NULL;
GroupFree(grp->root);
} else
group_root = grp->root;
SaveGroupList();
} else
GroupFree(grp->root);
GDrawDestroyWindow(grp->gw);
}
return( true );
}
void DefineGroups(FontView *fv) {
struct groupdlg *grp;
GRect pos;
GWindowAttrs wattrs;
GGadgetCreateData gcd[20];
GTextInfo label[19];
int h, k,kk;
grp = gcalloc(1,sizeof(*grp));
grp->fv = fv;
grp->select_many = grp->select_kids_too = false;
grp->select_callback = GroupSelected;
if ( group_root==NULL ) {
grp->root = chunkalloc(sizeof(Group));
grp->root->name = copy(_("Groups"));
} else
grp->root = GroupCopy(group_root);
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict;
wattrs.event_masks = ~(1<<et_charup);
wattrs.is_dlg = true;
wattrs.<API key> = false;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Define Groups");
pos.x = pos.y = 0;
pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200));
pos.height = h = GDrawPointsToPixels(NULL,482);
grp->gw = <API key>(NULL,&pos,displaygrp_e_h,grp,&wattrs);
grp->bmargin = GDrawPointsToPixels(NULL,248)+GDrawPointsToPixels(grp->gw,_GScrollBar_Width);
GroupWCreate(grp,&pos);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
k = 0;
gcd[k].gd.pos.x = 20;
gcd[k].gd.pos.y = GDrawPixelsToPoints(NULL,h-grp->bmargin)+12;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("New Sub-Group");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.handle_controlevent = Group_NewSubGroup;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = GDrawPixelsToPoints(NULL,(pos.<API key>(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor)));
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("_Delete");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.handle_controlevent = Group_Delete;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20;
gcd[k].gd.pos.x = 10;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26;
gcd[k].gd.flags = gg_visible | gg_enabled;
gcd[k++].creator = GLineCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+8;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("Group Name:");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 80; gcd[k].gd.pos.width = 115;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-3;
gcd[k].gd.flags = gg_visible;
gcd[k++].creator = GTextFieldCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-2].gd.pos.y+16;
gcd[k].gd.flags = gg_visible;
label[k].text = (unichar_t *) _("Glyphs:");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+14;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-10; gcd[k].gd.pos.height = 4*13+4;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_textarea_wrap;
gcd[k].gd.handle_controlevent = <API key>;
gcd[k++].creator = GTextAreaCreate;
gcd[k].gd.pos.x = 5;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+gcd[k-1].gd.pos.height+5;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
label[k].text = (unichar_t *) _("Identify by");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GLabelCreate;
gcd[k].gd.pos.x = 90; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y-2;
label[k].text = (unichar_t *) _("Name");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = (gg_visible | gg_enabled | gg_cb_on | gg_utf8_popup);
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GRadioCreate;
gcd[k].gd.pos.x = 140; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
label[k].text = (unichar_t *) _("Unicode");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = gg_visible | gg_enabled | gg_utf8_popup;
gcd[k].gd.popup_msg = (unichar_t *) _("Glyphs may be either identified by name or by unicode code point.\nGenerally you control this by what you type in.\nTyping \"A\" would identify a glyph by name.\nTyping \"U+0041\" identifies a glyph by code point.\nWhen loading glyphs from the selection you must specify which format is desired.");
gcd[k++].creator = GRadioCreate;
label[k].text = (unichar_t *) _("Set From Font");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.pos.x = 5; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+18;
gcd[k].gd.popup_msg = (unichar_t *) _("Set this glyph list to be the glyphs selected in the fontview");
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.handle_controlevent = Group_FromSelection;
gcd[k++].creator = GButtonCreate;
label[k].text = (unichar_t *) _("Select In Font");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.pos.x = 110; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y;
gcd[k].gd.popup_msg = (unichar_t *) _("Set the fontview's selection to be the glyphs named here");
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.handle_controlevent = Group_ToSelection;
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+26;
label[k].text = (unichar_t *) _("No Glyph Duplicates");
label[k].text_is_1byte = true;
gcd[k].gd.label = &label[k];
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k].gd.popup_msg = (unichar_t *) _("Glyph names (or unicode code points) may occur at most once in this group and any of its sub-groups");
gcd[k++].creator = GCheckBoxCreate;
for ( kk=0; kk<3; ++kk )
std_colors[kk].text = (unichar_t *) S_((char *) std_colors[kk].text);
std_colors[1].image = GGadgetImageCache("colorwheel.png");
std_colors[0].selected = true;
gcd[k].gd.pos.x = 10; gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+15;
gcd[k].gd.label = &std_colors[0];
gcd[k].gd.u.list = std_colors;
gcd[k].gd.handle_controlevent = Group_AddColor;
gcd[k].gd.flags = gg_visible | gg_utf8_popup;
gcd[k++].creator = GListButtonCreate;
gcd[k].gd.pos.width = GDrawPixelsToPoints(NULL,pos.width)-20;
gcd[k].gd.pos.x = 10;
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+28;
gcd[k].gd.flags = gg_visible | gg_enabled;
gcd[k++].creator = GLineCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = 30;
gcd[k].gd.pos.y = <API key>(NULL,32);
gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels;
label[k].text = (unichar_t *) _("_OK");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GButtonCreate;
gcd[k].gd.pos.width = -1;
gcd[k].gd.pos.x = (pos.<API key>(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor));
gcd[k].gd.pos.y = gcd[k-1].gd.pos.y+3;
gcd[k].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels;
label[k].text = (unichar_t *) _("_Cancel");
label[k].text_is_1byte = true;
label[k].text_in_resource = true;
gcd[k].gd.label = &label[k];
gcd[k++].creator = GButtonCreate;
GGadgetsCreate(grp->gw,gcd);
grp->newsub = gcd[0].ret;
grp->delete = gcd[1].ret;
grp->line1 = gcd[2].ret;
grp->gpnamelab = gcd[3].ret;
grp->gpname = gcd[4].ret;
grp->glyphslab = gcd[5].ret;
grp->glyphs = gcd[6].ret;
grp->idlab = gcd[7].ret;
grp->idname = gcd[8].ret;
grp->iduni = gcd[9].ret;
grp->set = gcd[10].ret;
grp->select = gcd[11].ret;
grp->unique = gcd[12].ret;
grp->colour = gcd[13].ret;
grp->line2 = gcd[14].ret;
grp->ok = gcd[15].ret;
grp->cancel = gcd[16].ret;
GroupSBSizes(grp);
GroupResize(grp,NULL);
GDrawSetVisible(grp->gw,true);
}
static void MapEncAddGid(EncMap *map,SplineFont *sf, int compacted,
int gid, int uni, char *name) {
if ( compacted && gid==-1 )
return;
if ( gid!=-1 && map->backmap[gid]==-1 )
map->backmap[gid] = map->enccount;
if ( map->enccount>=map->encmax )
map->map = grealloc(map->map,(map->encmax+=100)*sizeof(int));
map->map[map->enccount++] = gid;
if ( !compacted ) {
Encoding *enc = map->enc;
if ( enc->char_cnt>=enc->char_max ) {
enc->unicode = grealloc(enc->unicode,(enc->char_max+=256)*sizeof(int));
enc->psnames = grealloc(enc->psnames,enc->char_max*sizeof(char *));
}
if ( uni==-1 && name!=NULL ) {
if ( gid!=-1 && sf->glyphs[gid]!=NULL )
uni = sf->glyphs[gid]->unicodeenc;
else
uni = UniFromName(name,ui_none,&custom);
}
enc->unicode[enc->char_cnt] = uni;
enc->psnames[enc->char_cnt++] = copy( name );
}
}
static void MapAddGroupGlyph(EncMap *map,SplineFont *sf,char *name, int compacted) {
int gid;
if ( (name[0]=='u' || name[0]=='U') && name[1]=='+' && ishexdigit(name[2])) {
char *end;
int val = strtol(name+2,&end,16), val2=val;
if ( *end=='-' ) {
if ( (end[1]=='u' || end[1]=='U') && end[2]=='+' )
end+=2;
val2 = strtol(end+1,NULL,16);
}
for ( ; val<=val2; ++val ) {
gid = SFFindExistingSlot(sf,val,NULL);
MapEncAddGid(map,sf,compacted,gid,val,NULL);
}
} else if ( strncasecmp(name,"color=#",strlen("color=#"))==0 ) {
Color col = strtoul(name+strlen("color=#"),NULL,16);
int gid; SplineChar *sc;
for ( gid=0; gid<sf->glyphcnt; ++gid )
if ( (sc = sf->glyphs[gid])!=NULL &&
sc->color == col )
MapEncAddGid(map,sf,compacted,gid,sc->unicodeenc,NULL);
} else {
gid = SFFindExistingSlot(sf,-1,name);
MapEncAddGid(map,sf,compacted,gid,-1,name);
}
}
static int <API key>(EncMap *map,SplineFont *sf,Group *group, int compacted) {
int i, cnt=0;
char *start, *pt;
int ch;
if ( group->glyphs==NULL ) {
for ( i=0; i<group->kid_cnt; ++i )
cnt += <API key>(map,sf,group->kids[i], compacted);
} else if ( group->selected ) {
for ( pt=group->glyphs; *pt!='\0'; ) {
while ( *pt==' ' ) ++pt;
start = pt;
while ( *pt!=' ' && *pt!='\0' ) ++pt;
ch = *pt; *pt='\0';
if ( *start!='\0' )
MapAddGroupGlyph(map,sf,start, compacted);
*pt=ch;
}
++cnt;
}
return( cnt );
}
static int GroupSelCnt(Group *group, Group **first, Group **second) {
int cnt = 0, i;
if ( group->glyphs==NULL ) {
for ( i=0; i<group->kid_cnt; ++i )
cnt += GroupSelCnt(group->kids[i],first,second);
} else if ( group->selected ) {
if ( *first==NULL )
*first = group;
else if ( *second==NULL )
*second = group;
++cnt;
}
return( cnt );
}
static char *EncNameFromGroups(Group *group) {
Group *first = NULL, *second = NULL;
int cnt = GroupSelCnt(group,&first,&second);
char *prefix = P_("Group","Groups",cnt);
char *ret;
switch ( cnt ) {
case 0:
return( copy( _("No Groups")) );
case 1:
ret = galloc(strlen(prefix) + strlen(first->name) + 3 );
sprintf( ret, "%s: %s", prefix, first->name);
break;
case 2:
ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 5 );
sprintf( ret, "%s: %s, %s", prefix, first->name, second->name );
break;
default:
ret = galloc(strlen(prefix) + strlen(first->name) + strlen(second->name) + 9 );
sprintf( ret, "%s: %s, %s ...", prefix, first->name, second->name );
break;
}
return( ret );
}
static void EncodeToGroups(FontView *fv,Group *group, int compacted) {
SplineFont *sf = fv->b.sf;
EncMap *map;
if ( compacted )
map = EncMapNew(0,sf->glyphcnt,&custom);
else {
Encoding *enc = gcalloc(1,sizeof(Encoding));
enc->enc_name = EncNameFromGroups(group);
enc->is_temporary = true;
enc->char_max = 256;
enc->unicode = galloc(256*sizeof(int32));
enc->psnames = galloc(256*sizeof(char *));
map = EncMapNew(0,sf->glyphcnt,enc);
}
if ( <API key>(map,sf,group,compacted)==0 ) {
ff_post_error(_("Nothing Selected"),_("Nothing Selected"));
EncMapFree(map);
} else if ( map->enccount==0 ) {
ff_post_error(_("Nothing Selected"),_("None of the glyphs in the current font match any names or code points in the selected groups"));
EncMapFree(map);
} else {
fv->b.selected = grealloc(fv->b.selected,map->enccount);
memset(fv->b.selected,0,map->enccount);
EncMapFree(fv->b.map);
fv->b.map = map;
FVSetTitle((FontViewBase *) fv);
FontViewReformatOne((FontViewBase *) fv);
}
}
void DisplayGroups(FontView *fv) {
struct groupdlg grp;
GRect pos;
GWindowAttrs wattrs;
GGadgetCreateData gcd[6];
GTextInfo label[5];
int h;
memset( &grp,0,sizeof(grp));
grp.fv = fv;
grp.select_many = grp.select_kids_too = true;
grp.root = group_root;
if ( grp.root==NULL ) {
grp.root = chunkalloc(sizeof(Group));
grp.root->name = copy(_("Groups"));
}
memset(&wattrs,0,sizeof(wattrs));
wattrs.mask = wam_events|wam_cursor|wam_utf8_wtitle|wam_undercursor|wam_isdlg|wam_restrict;
wattrs.event_masks = ~(1<<et_charup);
wattrs.is_dlg = true;
wattrs.<API key> = 1;
wattrs.undercursor = 1;
wattrs.cursor = ct_pointer;
wattrs.utf8_window_title = _("Display By Groups");
pos.x = pos.y = 0;
pos.width =GDrawPointsToPixels(NULL,GGadgetScale(200));
pos.height = h = GDrawPointsToPixels(NULL,317);
grp.gw = <API key>(NULL,&pos,displaygrp_e_h,&grp,&wattrs);
grp.bmargin = GDrawPointsToPixels(NULL,50)+GDrawPointsToPixels(grp.gw,_GScrollBar_Width);
GroupWCreate(&grp,&pos);
memset(&label,0,sizeof(label));
memset(&gcd,0,sizeof(gcd));
gcd[0].gd.pos.width = -1;
gcd[0].gd.pos.x = 30;
gcd[0].gd.pos.y = <API key>(NULL,30);
gcd[0].gd.flags = gg_visible | gg_enabled | gg_but_default | gg_pos_in_pixels;
label[0].text = (unichar_t *) _("_OK");
label[0].text_is_1byte = true;
label[0].text_in_resource = true;
gcd[0].gd.label = &label[0];
gcd[0].creator = GButtonCreate;
gcd[1].gd.pos.width = -1;
gcd[1].gd.pos.x = (pos.<API key>(_NUM_Buttonsize)*100/GIntGetResource(_NUM_ScaleFactor));
gcd[1].gd.pos.y = gcd[0].gd.pos.y+3;
gcd[1].gd.flags = gg_visible | gg_enabled | gg_but_cancel | gg_pos_in_pixels;
label[1].text = (unichar_t *) _("_Cancel");
label[1].text_is_1byte = true;
label[1].text_in_resource = true;
gcd[1].gd.label = &label[1];
gcd[1].creator = GButtonCreate;
gcd[2].gd.pos.width = -1;
gcd[2].gd.pos.x = 10;
gcd[2].gd.pos.y = gcd[0].gd.pos.<API key>(NULL,17);
gcd[2].gd.flags = gg_visible | gg_enabled | gg_cb_on | gg_pos_in_pixels;
label[2].text = (unichar_t *) _("Compacted");
label[2].text_is_1byte = true;
label[2].text_in_resource = true;
gcd[2].gd.label = &label[2];
gcd[2].creator = GCheckBoxCreate;
GGadgetsCreate(grp.gw,gcd);
grp.ok = gcd[0].ret;
grp.cancel = gcd[1].ret;
grp.compact = gcd[2].ret;
GroupSBSizes(&grp);
GDrawSetVisible(grp.gw,true);
while ( !grp.done )
<API key>(NULL);
GDrawSetUserData(grp.gw,NULL);
if ( grp.oked )
EncodeToGroups(fv,grp.root, GGadgetIsChecked(gcd[2].ret));
if ( grp.root!=group_root )
GroupFree(grp.root);
GDrawDestroyWindow(grp.gw);
}
|
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
import java.io.IOException;
import java.io.<API key>;
import java.lang.<API key>;
import java.util.Collections;
public class FanMapMaker {
private static class IntList extends ArrayList<Integer> {}
private void printChargesArray(int[] distribution, int size) {
int percent;
System.out.println("temp2tcharge:");
for(int i = 0; i <= size; i++) {
// retlw .248 ;31 PWM=97%
percent = (100*i)/60;
System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%");
}
}
private void <API key>(int[] distribution, int size) {
int percent;
System.out.println("temp2tcharge_tab:");
for(int i = 0; i <= size; i++) {
percent = (100*i)/size;
System.out.println("\XORLW\t\t."+i+"\n"+
"\tBTFSC\t\tSTATUS,Z\n"+
"\tMOVLW\t\t."+distribution[percent]+"\t\t; [" + i + "] " + percent + "%\n"
);
}
System.out.println("\tGOTO\t\<API key>");
}
private void <API key>(int[] distribution, int size) {
int percent;
String tmpRegName = "TMP0";
String endLabel = "<API key>";
System.out.println("temp2tcharge_tab:");
System.out.println("\tMOVLW\t\t.255\n\tMOVF\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\tnext1\n\tGOTO\t\t"+endLabel);
for(int i = 1; i <= size; i++) {
// retlw .248 ;31 PWM=97%
percent = (100*i)/60;
//System.out.println("\tretlw\t\t." + distribution[percent] + "\t\t; " + i + " " + percent + "%");
System.out.println("next"+i+":\n\tMOVLW\t\t."+ distribution[percent]+"\t\t; [" + i + "] " +
percent + "%\n\tDECFSZ\t\t"+tmpRegName+",F\n\tBTFSS\t\tSTATUS,Z\n\tGOTO\t\t"+
((i<size) ? "next"+(i+1) : endLabel) + "\n\tGOTO\t\t"+endLabel);
}
}
public static void main(String[] a) {
FanMapMaker fmp = new FanMapMaker();
IntList percentToCharge[] = new IntList[101];
int res[] = new int[101];
for(int i = 0; i < percentToCharge.length; i++)
percentToCharge[i] = new IntList();
File decFile = new File("allDec.dat");
File incFile = new File("allInc.dat");
BufferedReader decReader = null;
BufferedReader incReader = null;
Integer tchrg;
Integer fanPercx;
Float sum;
Float fanPerc;
try {
//decReader = new BufferedReader(new FileReader(decFile));
//incReader = new BufferedReader(new FileReader(incFile));
Scanner decScan = new Scanner(decFile);
Scanner incScan = new Scanner(incFile);
int cnt = 0;
while (decScan.hasNext()) {
tchrg = decScan.nextInt();
fanPerc = 0.0f;
for(int i = 0; i < 3; i++) {
fanPerc += decScan.nextFloat();
}
fanPerc /= 3.0f;
fanPercx = Math.round(fanPerc);
percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat())
//System.out.println(tchrg + " " + fanPercx);
}
while (incScan.hasNext()) {
tchrg = incScan.nextInt();
fanPerc = 0.0f;
for(int i = 0; i < 3; i++) {
fanPerc += incScan.nextFloat();
}
fanPerc /= 3.0f;
fanPercx = Math.round(fanPerc);
percentToCharge[fanPercx].add(tchrg); //new Float(decScan.nextFloat())
//System.out.println(tchrg + " " + fanPercx);
}
for (int i = 0; i < percentToCharge.length; i++) {
Collections.sort(percentToCharge[i]);
//System.out.print("" + i + " " + "[");
for(Integer e: percentToCharge[i]) {
//System.out.print(e + " ");
}
//System.out.println("]");
}
int last = 1;
for (int i = percentToCharge.length - 1; i >= 0; i
if(percentToCharge[i].size() > 0) {
res[i] = percentToCharge[i].get(0);
last = res[i];
} else {
res[i] = last;
}
//System.out.println(i + " " + res[i]);
}
fmp.<API key>(res, 50);
} catch (<API key> e) {
e.printStackTrace();
} catch (<API key> e) {
e.printStackTrace();
} finally {
/*try {
if (decReader != null) {
//decReader.close();
}
} //catch (IOException e) {
//}
try {
if (incReader != null) {
//incReader.close();
}
} //catch (IOException e) {
//}
*/
}
}
}
|
# -*- coding: utf-8 -*-
import os
from pygal import *
def listeEuler(f, x0, y0, pas, n):
x, y, L = x0, y0, []
for k in range(n):
L += [(x, y)]
x += pas
y += pas * f(x, y)
return L
def euler(f, x0, y0, xf, n):
pas = (xf - x0) / n
courbe = XY()
courbe.title = "Methode d Euler"
courbe.add("Solution approchee", listeEuler(f, x0, y0, pas, n))
courbe.render_to_file("courbeEulerPython.svg")
os.system("pause")
|
vti_encoding:SR|utf8-nl
<API key>:TW|14 Aug 2014 12:39:17 -0000
vti_extenderversion:SR|12.0.0.0
vti_author:SR|Office-PC\\Rafael
vti_modifiedby:SR|Office-PC\\Rafael
vti_timecreated:TR|01 Nov 2014 09:09:36 -0000
vti_backlinkinfo:VX|
<API key>:TW|14 Aug 2014 12:39:17 -0000
vti_cacheddtm:TX|03 Nov 2015 21:05:11 -0000
vti_filesize:IR|554
<API key>:BR|false
vti_cachedhasbots:BR|false
vti_cachedhastheme:BR|false
vti_cachedhasborder:BR|false
vti_charset:SR|utf-8
<API key>.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 12:39:17 -0000
<API key>.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:05:11 -0000
|
## Water Model construction
# Creates and constructs the model with all demands.
## `config` must be defined before loading this file!
include("world.jl")
include("weather.jl")
if get(config, "demandmodel", nothing) == "USGS"
include("WaterDemand.jl")
else
include("Thermoelectric.jl")
include("Livestock.jl")
include("Agriculture.jl");
include("<API key>.jl");
include("<API key>.jl");
include("IndustrialDemand.jl");
include("UrbanDemand.jl");
include("WaterDemand.jl");
end
## Check if the optimize-surface script has been called
storedresult = cached_fallback("extraction/withdrawals", () -> false)
if storedresult == false
@warn "Missing saved allocation files. Please run optimize-surface.jl"
elseif size(storedresult)[1] != numcanals || size(storedresult)[3] != numsteps
@warn "Cache file does not match current configuration. Please remove."
end
println("Creating model...")
model = newmodel();
# Add all of the components
if get(config, "demandmodel", nothing) != "USGS"
thermoelectric = initthermoelectric(model); # exogenous
livestock = initlivestock(model); # exogenous
<API key> = <API key>(model); # optimization-only
<API key> = <API key>(model); # optimization-only
agriculture = initagriculture(model); # optimization-only
industrialdemand = <API key>(model); # exogenous
urbandemand = initurbandemand(model); # exogenous
end
waterdemand = initwaterdemand(model); # dep. Agriculture, PopulationDemand
# Connect up the components
if get(config, "demandmodel", nothing) != "USGS"
agriculture[:irrcropareas] = <API key>[:totalareas]
agriculture[:irrcropproduction] = <API key>[:production]
agriculture[:irrirrigation] = <API key>[:totalirrigation]
agriculture[:unicropareas] = <API key>[:totalareas2]
agriculture[:unicropproduction] = <API key>[:production]
agriculture[:uniirrigation] = <API key>[:totalirrigation]
waterdemand[:totalirrigation] = agriculture[:allirrigation];
waterdemand[:thermoelectricuse] = thermoelectric[:demand_copy];
waterdemand[:livestockuse] = livestock[:demand_copy];
waterdemand[:urbanuse] = urbandemand[:waterdemand];
waterdemand[:industrialuse] = industrialdemand[:waterdemand];
end
|
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#include "cuisyntax.hpp"
#include <boost/spirit/include/qi_parse.hpp>
#include <cstdlib>
#include <iostream>
#include <iomanip>
// Boost modules
// Asio
// Program Options
namespace aha {
namespace pawn {
namespace testtool {
std::ostream& operator<<(std::ostream& os, const aha::pawn::testtool::hex128_t& hex)
{
std::ios save(NULL);
save.copyfmt(os);
os << std::hex << std::setfill('0') << std::setw(8) << hex.byte1
<< std::setw(8) << hex.byte2
<< std::setw(8) << hex.byte3
<< std::setw(8) << hex.byte4;
os.copyfmt(save);
return os;
}
std::ostream& operator<<(std::ostream& os, const aha::pawn::testtool::node_data_t& data)
{
std::ios save(NULL);
save.copyfmt(os);
os << std::setfill(' ') << std::left
<< std::setw(22) << "Key" << data.key << "\n"
<< std::setw(22) << "TX IV" << data.txiv << "\n"
<< std::setw(22) << "RX IV" << data.rxiv << "\n";
std::ios save2(NULL);
save2.copyfmt(os);
os << std::setw(22) << "Timeslot"
<< std::hex << std::setfill('0') << std::setw(4) << data.timeslot << "\n";
os.copyfmt(save2);
os << std::setw(22) << "Timeslot enable" << data.enable_timeslot << "\n"
<< std::setw(22) << "TX encryption enable" << data.<API key> << "\n"
<< std::setw(22) << "RX decryption enable" << data.<API key> << "\n";
os.copyfmt(save);
return os;
}
enum class <API key> {
SUCCESS,
DOES_NOT_EXIST,
ALREADY_EXISTS,
INVALID_COMMAND,
UNEXPECTED_DATA
};
class option_visitor
: public boost::static_visitor<<API key>>
{
private:
boost::spirit::qi::symbols<char, node_data_t> nodes;
public:
<API key> operator()(const <API key>& cmd)
{
nodes.for_each([](std::string& key, node_data_t& value){
std::cout << "Node " << key << "\n" << value << std::endl;
});
return <API key>::SUCCESS;
}
<API key> operator()(const <API key>& cmd)
{
node_data_t* node = nodes.find(cmd.node);
if(node == NULL)
{
return <API key>::DOES_NOT_EXIST;
}
std::cout << "Node " << cmd.node << "\n" << *node << std::endl;
return <API key>::SUCCESS;
}
<API key> operator()(const <API key>& cmd)
{
node_data_t* node = nodes.find(cmd.node);
if(node == NULL)
{
return <API key>::DOES_NOT_EXIST;
}
switch(cmd.param)
{
case <API key>::KEY:
node->key = boost::get<hex128_t>(cmd.data);
break;
case <API key>::RXDECRYPT:
node-><API key> = boost::get<bool>(cmd.data);
break;
case <API key>::RXIV:
node->rxiv = boost::get<hex128_t>(cmd.data);
break;
case <API key>::TIMESLOT:
if(cmd.data.type() == typeid(bool)) {
node->enable_timeslot = boost::get<bool>(cmd.data);
}
else if(cmd.data.type() == typeid(hex128_t)) {
node->timeslot = (uint16_t)boost::get<hex128_t>(cmd.data).byte4;
}
else {
return <API key>::UNEXPECTED_DATA;
}
break;
case <API key>::TXENCRYPT:
node-><API key> = boost::get<bool>(cmd.data);
break;
case <API key>::TXIV:
node->txiv = boost::get<hex128_t>(cmd.data);
break;
default:
return <API key>::INVALID_COMMAND;
}
return <API key>::SUCCESS;
}
<API key> operator()(const <API key>& cmd)
{
if(nodes.find(cmd.node) != NULL)
{
return <API key>::ALREADY_EXISTS;
}
nodes.at(cmd.node);
return <API key>::SUCCESS;
}
<API key> operator()(const transmit_command_t& cmd)
{
node_data_t* node = nodes.find(cmd.node);
if(node == NULL)
{
return <API key>::DOES_NOT_EXIST;
}
// TODO: Write this out to the designated serial port.
return <API key>::SUCCESS;
}
};
}}}
using aha::pawn::testtool::<API key>;
int main(int argc, char** argv)
{
std::string input;
std::string message;
aha::pawn::testtool::command_t* command;
std::string::const_iterator begin, end;
aha::pawn::testtool::grammar::cui_grammar<std::string::const_iterator> grammar;
std::getline(std::cin, input);
aha::pawn::testtool::option_visitor option_visitor;
while(input != "quit")
{
command = new aha::pawn::testtool::command_t();
begin = input.begin();
end = input.end();
bool result = boost::spirit::qi::phrase_parse(
begin,
end,
grammar,
boost::spirit::ascii::space,
(*command));
if(result && begin == end)
{
switch(boost::apply_visitor(option_visitor, *command))
{
case <API key>::SUCCESS:
std::cout << "OK.";
break;
case <API key>::DOES_NOT_EXIST:
std::cout << "Node does not exist.";
break;
case <API key>::ALREADY_EXISTS:
std::cout << "Node already exists.";
break;
case <API key>::INVALID_COMMAND:
case <API key>::UNEXPECTED_DATA:
std::cout << "An unexpected error occurred.";
break;
}
std::cout << std::endl;
}
else
{
std::cout << "Could not parse that." << std::endl;
}
delete command;
std::getline(std::cin, input);
}
return EXIT_SUCCESS;
}
// vim: set expandtab ts=4 sts=4 sw=4 fileencoding=utf-8:
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Wed May 02 09:32:45 CEST 2012 -->
<TITLE>
Uses of Class zisko.multicastor.program.controller.ViewController.MessageTyp
</TITLE>
<META NAME="date" CONTENT="2012-05-02">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class zisko.multicastor.program.controller.ViewController.MessageTyp";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?zisko/multicastor/program/controller//<API key>.MessageTyp.html" target="_top"><B>FRAMES</B></A>
<A HREF="ViewController.MessageTyp.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>zisko.multicastor.program.controller.ViewController.MessageTyp</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#zisko.multicastor.program.controller"><B>zisko.multicastor.program.controller</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="zisko.multicastor.program.controller"></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A> in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A> that return <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></CODE></FONT></TD>
<TD><CODE><B>ViewController.MessageTyp.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html#valueOf(java.lang.String)">valueOf</A></B>(java.lang.String name)</CODE>
<BR>
Returns the enum constant of this type with the specified name.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A>[]</CODE></FONT></TD>
<TD><CODE><B>ViewController.MessageTyp.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html#values()">values</A></B>()</CODE>
<BR>
Returns an array containing the constants of this enum type, in
the order they are declared.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="<API key>">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A> with parameters of type <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ViewController.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.html#showMessage(zisko.multicastor.program.controller.ViewController.MessageTyp, java.lang.String)">showMessage</A></B>(<A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A> typ,
java.lang.String message)</CODE>
<BR>
Funktion welche ermueglich Nachrichten in der GUI anzuzeigen.</TD>
</TR>
</TABLE>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?zisko/multicastor/program/controller//<API key>.MessageTyp.html" target="_top"><B>FRAMES</B></A>
<A HREF="ViewController.MessageTyp.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML>
|
import {Injectable} from '@angular/core';
import {SnackBarService} from './snack-bar.service';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
@Injectable({
providedIn: 'root'
})
export class <API key> {
/**
* @param snackBarService
* @param translateService
*/
constructor(private snackBarService: SnackBarService, private translateService: TranslateService) {
this.translateService.onLangChange.subscribe((event: LangChangeEvent) => {
this.translateService.get('snackbarMessages.dismiss').subscribe((res: string) => {
this.snackBarService.setDefaultAction(res);
});
});
}
/**
* Emit snackbar with given duration
* @param {string} key
* @param {Object} interpolateParams
* @param {number} duration
*/
open(key: string, interpolateParams: Object = {}, duration: number = SnackBarService.defaultDuration): void {
this.translateService.get(key, interpolateParams).subscribe((message: string) => {
this.snackBarService.open(message, duration);
});
}
/**
* Emit snackbar with duration short
* @param {string} key
* @param {Object} interpolateParams
*/
openShort(key: string, interpolateParams: Object = {}): void {
this.open(key, interpolateParams, SnackBarService.durationShort);
}
/**
* Emit snackbar with duration long
* @param {string} key
* @param {Object} interpolateParams
*/
openLong(key: string, interpolateParams: Object = {}): void {
this.open(key, interpolateParams, SnackBarService.durationLong);
}
}
|
import { AccessToken, Project, User, UserFeatureFlag, UserRole } from '@dev/translatr-model';
import { map } from 'rxjs/operators';
// General
export const isAdmin = (user?: User): boolean => user !== undefined && user.role === UserRole.Admin;
// Users
export const <API key> = () => map(isAdmin);
export const <API key> = (me: User, user: User) =>
me !== undefined && me.id !== user.id && isAdmin(me);
export const <API key> = (user: User) =>
map((me?: User) => (me !== undefined && me.id === user.id) || isAdmin(me));
export const <API key> = (user: User) =>
map((me?: User) => <API key>(me, user));
export const <API key> = (users: User[]) =>
map((me?: User) =>
users
.map((user: User) => <API key>(me, user))
.reduce((acc: boolean, next: boolean) => acc && next, true)
);
// Projects
export const <API key> = (me: User, project: Project) =>
(me !== undefined && me.id === project.ownerId) || isAdmin(me);
export const <API key> = (project: Project) =>
map((me?: User) => (me !== undefined && me.id === project.ownerId) || isAdmin(me));
export const <API key> = (project: Project) =>
map((me?: User) => <API key>(me, project));
export const <API key> = (projects: Project[]) =>
map((me?: User) =>
projects
.map((project: Project) => <API key>(me, project))
.reduce((acc: boolean, next: boolean) => acc && next, true)
);
// Access Tokens
export const <API key> = (me: User, accessToken: AccessToken) =>
(me !== undefined && me.id === accessToken.userId) || isAdmin(me);
export const <API key> = (me: User, accessToken: AccessToken) =>
(me !== undefined && me.id === accessToken.userId) || isAdmin(me);
export const <API key> = (accessToken: AccessToken) =>
map((me?: User) => <API key>(me, accessToken));
export const <API key> = (accessToken: AccessToken) =>
map((me?: User) => <API key>(me, accessToken));
export const <API key> = (accessTokens: AccessToken[]) =>
map((me?: User) =>
accessTokens
.map((accessToken: AccessToken) => <API key>(me, accessToken))
.reduce((acc: boolean, next: boolean) => acc && next, true)
);
// Feature Flags
export const <API key> = (me: User, featureFlag: UserFeatureFlag) =>
(me !== undefined && me.id === featureFlag.userId) || isAdmin(me);
export const <API key> = (me: User, featureFlag: UserFeatureFlag) =>
(me !== undefined && me.id === featureFlag.userId) || isAdmin(me);
export const <API key> = (featureFlag: UserFeatureFlag) =>
map((me?: User) => <API key>(me, featureFlag));
export const <API key> = (featureFlag: UserFeatureFlag) =>
map((me?: User) => <API key>(me, featureFlag));
export const <API key> = (featureFlags: UserFeatureFlag[]) =>
map((me?: User) =>
featureFlags
.map((featureFlag: UserFeatureFlag) => <API key>(me, featureFlag))
.reduce((acc: boolean, next: boolean) => acc && next, true)
);
|
package Ashafix::I18N::eu;
use utf8;
use Mojo::Base 'Ashafix::I18N';
our %Lexicon = (
YES => 'BAI',
NO => 'EZ',
edit => 'aldatu',
del => 'ezabatu',
exit => 'Exit',
cancel => 'Cancel',
save => 'Save',
confirm => 'Ziur al zaude ezabatu nahi duzula?\n',
confirm_domain => 'Ziur al zaude domeinu honetako erregistro guztiak ezbatu nahi dituzula? Hau ezin izango da desegin!\n',
check_update => 'Check for update',
invalid_parameter => 'Invalid parameter!',
pFooter_logged_as => 'Logged as %s',
pLogin_welcome => 'Kudeatzailearen logina domeinuak kudeatzeko.',
pLogin_username => 'Erabiltzailea (e-mail)',
pLogin_password => 'Pasahitza',
pLogin_button => 'Erabiltzailea',
pLogin_failed => 'Your email address or password are not correct.',
pLogin_login_users => 'Erabiltzaileen gunera joateko logina.',
pMenu_main => 'Main',
pMenu_overview => 'Laburpena',
pMenu_create_alias => 'Aliasa gehitu',
<API key> => 'Add Alias Domain',
<API key> => 'Postontzia gehitu',
pMenu_fetchmail => 'Fetch Email',
pMenu_sendmail => 'e-maila bidali',
pMenu_password => 'Pasahitza',
pMenu_viewlog => 'Logak ikusi',
pMenu_logout => 'Irten',
pMain_welcome => 'Ongietorri Postfix Adminera!',
pMain_overview => 'Alias eta postontzien zerrenda. Hemendik aldatu / ezabatu ditzakezu.',
pMain_create_alias => 'Zure domeinuarentzako alias berri baten sorkuntza.',
<API key> => 'Zure domeinuarentzako postontzi berri baten sorkuntza.',
pMain_sendmail => 'Duela gutxi sorturiko postontziren batera e-mail bat bidali.',
pMain_password => 'Kudeatzaile konturako pasahitza aldatu.',
pMain_viewlog => 'Logak ikusi.',
pMain_logout => 'Irten.',
pOverview_disabled => 'Disabled',
pOverview_unlimited => 'Unlimited',
pOverview_title => ':: Defined Domains',
pOverview_up_arrow => 'Go Top',
<API key> => 'Next Page',
<API key> => 'Previous Page',
<API key> => ':: Domain Aliases',
<API key> => ':: Alias',
<API key> => ':: Mailboxes',
pOverview_button => 'Joan',
pOverview_welcome => 'Laburpena ',
<API key> => 'Alias Domains',
<API key> => '%s is an Alias Domain for:',
<API key> => 'Aliasa',
<API key> => 'Postontziak',
<API key> => 'Igorlea',
<API key> => 'Norakoa',
<API key> => 'Azken aldaketa',
<API key> => 'Last Modified',
<API key> => 'Active',
<API key> => 'Active',
<API key> => 'Alias',
and_x_more => '[and %s more...]',
<API key> => 'E-mail',
<API key> => 'Izena',
<API key> => 'Kuota (MB)',
<API key> => 'Azken aldaketa',
<API key> => 'Aktibatua',
<API key> => 'VACATION IS ON',
<API key> => 'Set Vacation',
<API key> => 'Domeinua',
<API key> => 'Aliasa',
<API key> => 'Domain Aliases',
<API key> => 'Postontziak',
pOverview_get_quota => 'Postontzi kuota (MB)',
<API key> => 'Azken aldaketa',
<API key> => 'Ezinezkoa sarrera ezabatzea ',
<API key> => '%s deleted.',
<API key> => 'Unable to remove mailbox ',
<API key> => 'Ez zara domeinu honen jabe',
<API key> => 'This domain is not yours ',
pDelete_alias_error => 'Unable to delete alias ',
<API key> => 'Mirror addresses of one of your domains to another.',
<API key> => 'Alias Domain',
<API key> => 'The domain that mails come in for.',
<API key> => 'Target Domain',
<API key> => 'The domain where mails should go to.',
<API key> => 'Active',
<API key> => 'Add Alias Domain',
<API key> => 'You are not allowed to create the chosen configuration.',
<API key> => 'The chosen configuration is invalid, please choose a different one!',
<API key> => 'Database insert failed.',
<API key> => 'All domains are already aliased.',
<API key> => 'The domain alias has been added to the alias domain table!',
<API key> => 'Domeinuarentzat alias berri bat sortu.',
<API key> => 'Aliasa',
<API key> => 'ALIASa okerra da!',
<API key> => 'Helbide hau existitzen da, ezberdin bat aukera ezazu mesedez!',
<API key> => 'Alias sortze mugara heldu zara!',
pCreate_alias_goto => 'Norakoa',
<API key> => 'Active',
<API key> => 'Aliasa gehitu',
<API key> => 'Nora bidali behar den e-maila.',
<API key> => 'NORAKO okerra!',
<API key> => 'Ezinezkoa aliasa alias taulan sartzea!',
<API key> => 'Aliasa alias taulan gehituta!',
<API key> => 'Alias orokor bat sortzeko "*" erabil ezazu alias gisa. Domeinuz domeinurako birbideraketa baterako Norako gisa "*@domain.tld" erabil ezazu.',
pEdit_alias_welcome => 'Domeinuarentzat aliasa aldatu. Lerroko sarrera bat.',
pEdit_alias_address => 'Aliasa',
<API key> => 'Ezinezkoa aliasa aurkitzea!',
pEdit_alias_goto => 'Norakoa',
pEdit_alias_active => 'Active',
<API key> => 'Norakoan ez duzu ezer jarri',
<API key> => 'Sartutako e-mail helbidea baliiogabekoa da: ',
<API key> => 'Ez zara domeinu honen jabe: ',
<API key> => 'Unable to modify the alias domain!',
<API key> => 'Deliver to the local mailbox.',
<API key> => 'Forward to given email addresses only.',
pEdit_alias_button => 'Aliasa aldatu',
<API key> => 'Ezinezkoa aliasa aldatzea!',
<API key> => 'Postontzi berri bat sortu domeinuarentzat.',
<API key> => 'Erabiltzailea',
<API key> => 'E-maila baliogabekoa da!',
<API key> => 'E-mail hau existitzen da. Ezberdin bat aukera ezazu, mesedez!',
<API key> => 'Postontzi sorkuntza mugara iritsi zara!',
<API key> => 'Pasahitza',
<API key> => 'Pasahitza (errepikatu)',
<API key> => 'POP3/IMAP-entzat pasahitza',
<API key> => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!',
<API key> => 'Izena',
<API key> => 'Izen osoa',
<API key> => 'Kuota',
<API key> => 'MB',
<API key> => 'Zehazturiko kuota altuegia da!',
<API key> => 'Aktibatua',
<API key> => 'Postontzia sortu',
<API key> => 'Postontzia gehitu',
<API key> => 'Ezinezkoa postontzi taulara postontzia gehitzea!',
<API key> => 'Postontzia postontzi taulara sartu da!',
<API key> => 'The mailbox has been added to the mailbox table, but none (or only some) of the predefined sub-folders could be created',
<API key> => 'Domeinuarentzat postontzi bat aldatu.',
<API key> => 'Erabiltzailea',
<API key> => 'Ezinezkoa postontzia aurkitzea!',
<API key> => 'Pasahitz berria',
<API key> => 'Pasahitz berria (errepikatu)',
<API key> => 'Sartutako pasahitzak ez datoz bat!',
pEdit_mailbox_name => 'Izena',
<API key> => 'Full name',
pEdit_mailbox_quota => 'Kuota',
<API key> => 'MB',
<API key> => 'Zehazturiko kuota altuegia da!',
<API key> => 'Ez zara domeinu honen jabe: ',
<API key> => 'Postontzia aldatu',
<API key> => 'Ezinezkoa pasahitza aldatzea!',
pPassword_welcome => 'Login pasahitza aldatu.',
pPassword_admin => 'Login',
p<API key> => 'Emandako LOGINa ez dator inolako postontziekin bat!',
p<API key> => 'Egungo pasahitza',
p<API key> => 'Ez duzu egungo pasahitzik sartu!',
pPassword_password => 'Pasahitz berria',
pPassword_password2 => 'Pasahitz berria (errepikatu)',
p<API key> => 'Sarturiko pasahitzak ez datoz bat edo zuriz daude!',
pPassword_button => 'Pasahitza aldatu',
<API key> => 'Ezinezkoa pasahitza aldatzea!',
<API key> => 'Pasahitza aldatuta!',
pEdit_vacation_set => 'Change / Set away message',
<API key> => 'Remove away message',
<API key> => 'Unable to update auto response settings!',
<API key> => 'Auto response has been removed!',
<API key> => 'Auto response has been enabled!',
pViewlog_welcome => 'Honen azken 10 ekintzak ikusi ',
pViewlog_timestamp => 'Data/ordua',
pViewlog_username => 'Kudeatzailea',
pViewlog_domain => 'Domeinua',
pViewlog_action => 'Ekintza',
pViewlog_data => 'Datuak',
<API key> => 'create mailbox',
<API key> => 'delete mailbox',
<API key> => 'edit mailbox',
<API key> => 'edit mailbox active',
<API key> => 'create alias',
<API key> => 'create alias domain',
<API key> => 'delete alias',
<API key> => 'delete alias domain',
<API key> => 'edit alias',
<API key> => 'edit alias active',
<API key> => 'edit alias domain active',
<API key> => 'change password',
pViewlog_button => 'Joan',
<API key> => 'Ezinezkoa logak aurkitzea!',
pSendmail_welcome => 'e-mail bat bidali.',
pSendmail_admin => 'Igorlea',
pSendmail_to => 'Norakoa',
<API key> => 'Norako helbidea hutsa dago edo okerra da!',
pSendmail_subject => 'Gaia',
<API key> => 'Ongi etorri',
pSendmail_body => 'Gorputza',
pSendmail_button => 'Mezua bidali',
<API key> => 'Ezinezkoa postontzia sortzea!',
<API key> => 'Postontzia sortuta!',
<API key> => 'Kudeatzaile zerrenda',
<API key> => 'Domeinu zerrenda',
<API key> => 'Helbide birtualen zerrenda',
pAdminMenu_viewlog => 'Logak ikusi',
pAdminMenu_backup => 'Segurtasun kopia',
<API key> => 'Domeinu kudeatzaileak',
<API key> => 'Kudeatzaile berria',
<API key> => 'Domeinu berria',
<API key> => 'Aliasa gehitu',
<API key> => 'Postontzia gehitu',
<API key> => 'Domeinua',
<API key> => 'Kudeatzailea',
<API key> => 'Domeinuak',
<API key> => 'Azken aldaketa',
<API key> => 'Aktibatua',
<API key> => 'Domeinua',
<API key> => 'Deskripzioa',
<API key> => 'Aliasa',
<API key> => 'Postontziak',
<API key> => 'Gehienezko kuota (MB)',
<API key> => 'Transport',
<API key> => 'Backup MX',
<API key> => 'Azken aldaketa',
<API key> => 'Aktibatua',
<API key> => 'Joan',
<API key> => 'Laburpena ',
<API key> => 'Aliasa',
<API key> => 'Postontziak',
<API key> => 'Igorlea',
<API key> => 'Norakoa',
<API key> => 'Azken aldaketa',
<API key> => 'E-mail',
<API key> => 'Izena',
<API key> => 'Kuota (MB)',
<API key> => 'Azken aldaketa',
<API key> => 'Aktibatua',
<API key> => 'Domeinu berria gehitu',
<API key> => 'Domeinua',
<API key> => 'Domeinua existitzen da!',
<API key> => 'The domain is invalid!',
<API key> => 'Deskripzioa',
<API key> => 'Aliasa',
<API key> => '-1 = desegokitu | 0 = mugagabea',
<API key> => 'Postontziak',
<API key> => '-1 = desegokitu | 0 = mugagabea',
<API key> => 'Gehienezko kuota',
<API key> => 'MB -1 = desegokitu | 0 = mugagabea',
<API key> => 'Transport',
<API key> => 'Define transport',
<API key> => 'Aurremugatutako aliasa gehitu',
<API key> => '',
<API key> => 'Mail server is backup MX',
<API key> => 'Domeinua gehitu',
<API key> => 'Ezinezkoa domeinua gehitzea!',
<API key> => 'Domeinua gehituta!',
<API key> => 'Unable to remove domain!',
<API key> => 'Unable to remove domain alias!',
<API key> => 'Domeinu bat aldatu',
<API key> => 'Domeinua',
<API key> => 'Deskripzioa',
<API key> => 'Aliasa',
<API key> => '-1 = desegokitu | 0 = mugagabea',
<API key> => 'Postontziak',
<API key> => '-1 = desegokitu | 0 = mugagabea',
<API key> => 'Gehienezko kuota',
<API key> => 'MB -1 = desegokitu | 0 = mugagabea',
<API key> => 'Transport',
<API key> => 'Define transport',
<API key> => 'Mail server is backup MX',
<API key> => 'Aktibatua',
<API key> => 'Domeinua aldatu',
<API key> => 'Ezinezkoa domeinua aldatzea!',
<API key> => 'Domeinu kudeatzaile berri bat gehitu',
<API key> => 'Kudeatzailea',
<API key> => 'E-mail helbidea',
<API key> => 'Kudeatzaile e-mailak ez du balio!',
<API key> => 'Kudeatzailea existitzen da edo ez du balio!',
<API key> => 'Pasahitza',
<API key> => 'Pasahitza (errepikatu)',
<API key> => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!',
<API key> => 'Kudeatzailea gehitu',
<API key> => 'Ezinezkoa kudeatzailea gehitzea!',
<API key> => 'Kudeatzailea gehituta1',
<API key> => 'Domeinua',
<API key> => 'Domeinu kudeatzaile bat aldatu',
<API key> => 'Kudeatzailea',
<API key> => 'Pasahitza',
<API key> => 'Pasahitza (errepikatu)',
<API key> => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!',
<API key> => 'Aktibatua',
<API key> => 'Super admin',
<API key> => 'Kudeatzailea aldatu',
<API key> => 'Ezinezkoa kudeatzailea aldatzea!',
<API key> => 'Kudeatzailea aldatu da!',
pUsersLogin_welcome => 'Erabiltzaileen logina pasahitz eta aliasa aldatzeko.',
<API key> => 'Login (e-mail)',
<API key> => 'Pasahitza',
pUsersLogin_button => 'Login',
<API key> => 'Login okerra. Ziurta zaitez posta helbidea login gisa sartu duzula!',
<API key> => 'Pasahitz okerra!',
pUsersMenu_vacation => 'Erantzun automatikoa',
<API key> => 'Berbiderapen helbidea aldatu',
pUsersMenu_password => 'Pasahitza aldatu',
pUsersMain_vacation => 'Konfigura ezazu "lanetik kanpo" motako mezu bat edo erantzun automatikoa zure postarentzat.',
<API key> => 'Alda ezazu posta helbidea.',
pUsersMain_password => 'Alda ezazu pasahitza.',
<API key> => 'Erantzun automatikoa.',
<API key> => 'Erantzun automatiko bat konfiguratuta duzu!',
<API key> => 'Gaia',
<API key> => 'Lanetik kanpo',
pUsersVacation_body => 'Gorputza',
<API key> => '<date>-tik <date> arte kanpoan egongo naiz.
Larrialdiko gaientzat, hemen <contact person> kontakta dezakezu nirekin.
',
<API key> => 'Aldeginda',
<API key> => 'Itzulita',
<API key> => 'Ezinezkoa zure erantzun atomatikoaren konfigurazioa eguneratzea!',
<API key> => 'Zure erantzun automatikoa borratu da!',
<API key> => 'Active from',
<API key> => 'Active until',
<API key> => 'create mailbox',
<API key> => 'create alias',
<API key> => 'delete alias',
<API key> => 'delete mailbox',
<API key> => 'change active state',
<API key> => 'edit alias',
<API key> => 'edit mailbox',
pSearch => 'search',
pSearch_welcome => 'Searching for: ',
pReturn_to => 'Return to',
pBroadcast_title => 'Send broadcast message',
pBroadcast_from => 'From',
pBroadcast_name => 'Your name',
pBroadcast_subject => 'Subject',
pBroadcast_message => 'Message',
pBroadcast_send => 'Send message',
pBroadcast_success => 'Your broadcast message was sent.',
<API key> => 'Broadcast message',
<API key> => 'The fields Name, Subject and Message should\'t be empty !',
<API key> => 'maybe UNDELIVERABLE ',
pStatus_custom => 'Delivers to ',
pStatus_popimap => 'POP/IMAP ',
pPasswordTooShort => 'Password is too short - requires %s characters',
pInvalidDomainRegex => 'Invalid domain name %s, fails regexp check',
pInvalidDomainDNS => 'Invalid domain %s, and/or not discoverable in DNS',
pInvalidMailRegex => 'Invalid email address, fails regexp check',
pFetchmail_welcome => 'Fetch mail for:',
<API key> => 'New entry',
<API key> => 'Could not save this entry in the database!',
<API key> => 'Entry saved in database.',
<API key> => 'No entry with ID %s found!',
<API key> => 'Invalid mailbox!',
<API key> => 'Please enter the remote server name!',
<API key> => 'Please enter the remote username!',
<API key> => 'Please enter the remote password!',
pFetchmail_field_id => 'ID',
<API key> => 'Mailbox',
<API key> => 'Server',
<API key> => 'Auth Type',
<API key> => 'User',
<API key> => 'Password',
<API key> => 'Folder',
<API key> => 'Poll',
<API key> => 'Fetch All',
<API key> => 'Keep',
<API key> => 'Protocol',
<API key> => 'SSL active',
<API key> => 'Extra Options',
<API key> => 'MDA',
<API key> => 'Date',
<API key> => 'Returned Text',
pFetchmail_desc_id => 'Record ID',
<API key> => 'Local mailbox',
<API key> => 'Remote Server',
<API key> => 'Mostly \'password\'',
<API key> => 'Remote User',
<API key> => 'Remote Password',
<API key> => 'Remote Folder',
<API key> => 'Poll every ... minutes',
<API key> => 'Retrieve both old (seen) and new messages',
<API key> => 'Keep retrieved messages on the remote mailserver',
<API key> => 'Protocol to use',
<API key> => 'SSL encryption',
<API key> => 'Extra fetchmail Options',
pFetchmail_desc_mda => 'Mail Delivery Agent',
<API key> => 'Date of last polling/configuration change',
<API key> => 'Text message from last polling',
);
|
package com.bytezone.diskbrowser.nufx;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import com.bytezone.diskbrowser.prodos.write.DiskFullException;
import com.bytezone.diskbrowser.prodos.write.<API key>;
import com.bytezone.diskbrowser.prodos.write.ProdosDisk;
import com.bytezone.diskbrowser.prodos.write.<API key>;
public class Binary2
{
private static final String UNDERLINE =
"
+ "
Binary2Header binary2Header;
byte[] buffer;
List<Binary2Header> headers = new ArrayList<> ();
int totalBlocks;
String fileName;
public Binary2 (Path path) throws IOException
{
fileName = path.toFile ().getName ();
buffer = Files.readAllBytes (path);
read (buffer);
}
private void read (byte[] buffer)
{
int ptr = 0;
do
{
binary2Header = new Binary2Header (buffer, ptr);
System.out.println (binary2Header);
headers.add (binary2Header);
totalBlocks += binary2Header.totalBlocks;
ptr += ((binary2Header.eof - 1) / 128 + 1) * 128 + 128;
} while (binary2Header.filesToFollow > 0);
}
public byte[] getDiskBuffer () throws DiskFullException, <API key>,
<API key>, IOException
{
ProdosDisk disk = new ProdosDisk (800, "DiskBrowser");
for (Binary2Header header : headers)
{
byte[] dataBuffer = new byte[header.eof]; // this sux
System.arraycopy (buffer, header.ptr + 128, dataBuffer, 0, dataBuffer.length);
disk.addFile (header.fileName, header.fileType, header.auxType, header.created,
header.modified, dataBuffer, header.eof);
}
disk.close ();
return disk.getBuffer ();
}
@Override
public String toString ()
{
StringBuilder text = new StringBuilder ();
text.append (String.format (
" %-15.15s Files:%5d%n%n",
fileName, headers.size ()));
text.append (" Name Type Auxtyp Modified"
+ " Fmat Length\n");
text.append (String.format ("%s%n", UNDERLINE));
for (Binary2Header header : headers)
text.append (String.format ("%s%n", header.getLine ()));
text.append (String.format ("%s%n", UNDERLINE));
return text.toString ();
}
}
|
package componentes;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.<API key>;
import javax.swing.text.PlainDocument;
public class JTextFieldPrazo extends PlainDocument {
private static final long serialVersionUID = -<API key>;
private int iMaxLength;
private JTextField txt;
private long num;
public JTextFieldPrazo(int pMaxLen, JTextField pText) {
super();
iMaxLength = pMaxLen;
txt = pText;
}
public void insertString(int pOffSet, String pString, AttributeSet pAttributSet)
throws <API key> {
if (pString == null)
return;
if (iMaxLength <= 0) {// aceitara qualquer no. de caracteres
super.insertString(pOffSet, pString, pAttributSet);
return;
}
long ilen = (getLength() + pString.length());
try {
if(pString.length()==1 && !pString.equals("-"))
setNum(Long.parseLong(pString));
if(pString.equals("0") && txt.getText().length() == 0){
/**return;*/
}
if (ilen <= iMaxLength) // se o comprimento final for menor...
super.insertString(pOffSet, pString, pAttributSet); // ...aceita str
else if (getLength() == iMaxLength)
return; // nada a fazer
else {
String newStr = pString.substring(0, (iMaxLength - getLength()));
super.insertString(pOffSet, newStr, pAttributSet);
}
}
catch(Exception e) {}
}
public long getNum() {
return num;
}
public void setNum(long num) {
this.num = num;
}
}
|
CREATE OR REPLACE VIEW clin_measurements.vwsystolicdiastolic AS
SELECT vwmeasurements.fk_patient,
vwpatients.wholename,
vwpatients.fk_person,
vwpatients.surname,
vwpatients.firstname,
vwpatients.title,
vwpatients.sex,
vwpatients.age_numeric,
vwpatients.fk_lu_active_status,
vwpatients.deceased,
vwmeasurements.pk_measurement,
vwmeasurements.consult_date,
vwmeasurements.measurement,
round(vwmeasurements.measurement / 1000::numeric) AS systolic,
vwmeasurements.measurement % 1000::numeric AS diastolic
FROM clin_measurements.vwmeasurements
JOIN contacts.vwpatients ON vwpatients.fk_patient = vwmeasurements.fk_patient
WHERE vwmeasurements.deleted = false AND vwmeasurements.fk_type = 1 AND vwpatients.deceased = false AND vwpatients.fk_lu_active_status = 1
ORDER BY vwmeasurements.fk_patient, vwmeasurements.consult_date DESC;
ALTER TABLE clin_measurements.vwsystolicdiastolic OWNER TO easygp;
GRANT ALL ON TABLE clin_measurements.vwsystolicdiastolic TO staff;
CREATE OR REPLACE VIEW clin_measurements.vwaveragebp AS
SELECT vwsystolicdiastolic.fk_patient,
vwsystolicdiastolic.fk_patient AS pk,
vwsystolicdiastolic.fk_person,
vwsystolicdiastolic.surname,
vwsystolicdiastolic.firstname,
vwsystolicdiastolic.title,
vwsystolicdiastolic.sex,
vwsystolicdiastolic.age_numeric,
round(avg(vwsystolicdiastolic.systolic)) AS average_systolic,
round(avg(vwsystolicdiastolic.diastolic)) AS average_diastolic
FROM clin_measurements.vwsystolicdiastolic
GROUP BY vwsystolicdiastolic.fk_patient, vwsystolicdiastolic.fk_person, vwsystolicdiastolic.surname, vwsystolicdiastolic.firstname, vwsystolicdiastolic.title, vwsystolicdiastolic.sex, vwsystolicdiastolic.age_numeric
ORDER BY vwsystolicdiastolic.surname;
ALTER TABLE clin_measurements.vwaveragebp OWNER TO easygp;
GRANT ALL ON TABLE clin_measurements.vwaveragebp TO staff;
CREATE OR REPLACE VIEW research.<API key> AS
SELECT DISTINCT ON (vwpatients.surname, vwhealthissues.fk_patient) vwhealthissues.fk_patient AS pk_patient,
vwpatients.fk_person,
vwpatients.firstname,
vwpatients.surname,
vwpatients.sex,
vwpatients.title,
vwpatients.age_numeric,
vwpatients.fk_lu_active_status,
vwpatients.person_deleted,
vwpatients.deceased
FROM clin_history.vwhealthissues
JOIN contacts.vwpatients ON vwpatients.fk_patient = vwhealthissues.fk_patient
WHERE vwhealthissues.fk_code = 'K86005'::text OR vwhealthissues.fk_code = 'K85004'::text
ORDER BY vwpatients.surname;
ALTER TABLE research.<API key> OWNER TO easygp;
GRANT ALL ON TABLE research.<API key> TO staff;
update db.lu_version set lu_minor = 488;
|
using System;
using System.IO;
using System.Linq;
namespace FocalLengthAnalyzer
{
public class Program
{
public void Main(string[] args)
{
if (args.Count()<1) {
Console.WriteLine("Please pass the path to the directory with jpeg files as the first argument.");
return;
}
if (!Directory.Exists(args[0])) {
Console.WriteLine($"Error: directory {args[0]} does not exits.");
return;
}
var analyzer = new Analyzer();
analyzer.<API key>(args[0]);
}
}
}
|
#include <stdio.h>
#include <stdlib.h>
//#include <elf.h>
#define ELF_MAGIC 16
//#define MEM_ALLOC_H(ptr) ptr = (FILE *) malloc (sizeof(myElf32_Ehdr));
//#define MEM_ALLOC_S(ptr) ptr = (FILE *) malloc (sizeof(myElf32_Shdr));
#define VALIDATE(ptr) if (!(ptr)) {\
fprintf(stdout, "%s", "Returned NULL\n");\
exit(1);\
}
typedef unsigned short int myElf32_Half;
typedef unsigned int myElf32_Word;
typedef struct {
unsigned char magic_num[ELF_MAGIC];
myElf32_Half elfh_type;
myElf32_Half elfh_machine;
myElf32_Word elfh_version;
myElf32_Word elfh_entry;
myElf32_Word elfh_phoff;
myElf32_Word elfh_shoff;
myElf32_Word elfh_flags;
myElf32_Half elfh_ehsize;
myElf32_Half elfh_phentsize;
myElf32_Half elfh_phnum;
myElf32_Half elfh_shentsize;
myElf32_Half elfh_shnum;
myElf32_Half elfh_shstrndx;
} myElf32_Ehdr;
typedef struct {
myElf32_Word sech_name;
myElf32_Word sech_type;
myElf32_Word sech_flags;
myElf32_Word sech_addr;
myElf32_Word sech_offset;
myElf32_Word sech_size;
myElf32_Word sech_link;
myElf32_Word sech_info;
myElf32_Word sech_addralign;
myElf32_Word sech_entsize;
} myElf32_Shdr;
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import pprint
import proteindf_bridge as bridge
import logging
import logging.config
def <API key>(frame_molecule, selected_molecule):
# calc the rest
selector = bridge.Select_AtomGroup(selected_molecule)
selected = frame_molecule.select(selector)
rest_molecule = frame_molecule ^ selected
return rest_molecule
def <API key>(rest_molecule, output_atom_group,
model_id="model_1", chain_id="Z", res_name="UNK"):
chain = bridge.AtomGroup()
res = bridge.AtomGroup()
res.name = res_name
atom_id = 1
for atom in rest_molecule.get_atom_list():
res.set_atom(atom_id, atom)
atom_id += 1
chain.set_group(1, res)
output_atom_group[model_id].set_group(chain_id, chain)
def main():
parser = argparse.ArgumentParser(
description='restructure brd file by reference file')
parser.add_argument('target_brd_path',
nargs=1,
help='target brd file')
parser.add_argument('ref_brd_path',
nargs=1,
help='reference brd file')
parser.add_argument('-o', '--output_path',
nargs=1,
default=["output.brd"])
parser.add_argument('-r', '--range',
nargs=1,
default=[1.0E-5])
parser.add_argument('-v', '--verbose',
action='store_true',
default=False)
args = parser.parse_args()
# print(args)
target_brd_path = args.target_brd_path[0]
ref_brd_path = args.ref_brd_path[0]
output_path = args.output_path[0]
range = float(args.range[0])
verbose = args.verbose
if verbose:
print("target: {}".format(target_brd_path))
print("reference: {}".format(ref_brd_path))
# load
target_ag = bridge.load_atomgroup(target_brd_path)
ref_ag = bridge.load_atomgroup(ref_brd_path)
# matching
#target_selector = bridge.Select_AtomGroup(target_ag)
#restructured = ref_ag.select(target_selector)
# calc the rest
#rest_of_target = <API key>(target_ag, restructured)
#<API key>(rest_of_target, restructured)
restructured = target_ag.restructure(ref_ag, range)
if output_path:
if verbose:
print("output brd file: {}".format(output_path))
bridge.save_atomgroup(restructured, output_path)
if __name__ == '__main__':
#import cProfile
#pr = cProfile.Profile()
# pr.enable()
main()
# pr.disable()
# pr.dump_stats('program.profile')
|
package se.vidstige.jadb;
import se.vidstige.jadb.managers.Bash;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class JadbDevice {
public enum State {
Unknown,
Offline,
Device,
Recovery,
BootLoader
};
private final String serial;
private final ITransportFactory transportFactory;
JadbDevice(String serial, String type, ITransportFactory tFactory) {
this.serial = serial;
this.transportFactory = tFactory;
}
static JadbDevice createAny(JadbConnection connection) {
return new JadbDevice(connection);
}
private JadbDevice(ITransportFactory tFactory) {
serial = null;
this.transportFactory = tFactory;
}
private State convertState(String type) {
switch (type) {
case "device": return State.Device;
case "offline": return State.Offline;
case "bootloader": return State.BootLoader;
case "recovery": return State.Recovery;
default: return State.Unknown;
}
}
private Transport getTransport() throws IOException, JadbException {
Transport transport = transportFactory.createTransport();
if (serial == null) {
transport.send("host:transport-any");
transport.verifyResponse();
} else {
transport.send("host:transport:" + serial);
transport.verifyResponse();
}
return transport;
}
public String getSerial() {
return serial;
}
public State getState() throws IOException, JadbException {
Transport transport = transportFactory.createTransport();
if (serial == null) {
transport.send("host:get-state");
transport.verifyResponse();
} else {
transport.send("host-serial:" + serial + ":get-state");
transport.verifyResponse();
}
State state = convertState(transport.readString());
transport.close();
return state;
}
/** <p>Execute a shell command.</p>
*
* <p>For Lollipop and later see: {@link #execute(String, String...)}</p>
*
* @param command main command to run. E.g. "ls"
* @param args arguments to the command.
* @return combined stdout/stderr stream.
* @throws IOException
* @throws JadbException
*/
public InputStream executeShell(String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "shell:" + shellLine.toString());
return new <API key>(new BufferedInputStream(transport.getInputStream()));
}
/**
*
* @deprecated Use InputStream executeShell(String command, String... args) method instead. Together with
* Stream.copy(in, out), it is possible to achieve the same effect.
*/
@Deprecated
public void executeShell(OutputStream output, String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "shell:" + shellLine.toString());
if (output != null) {
<API key> out = new <API key>(output);
try {
transport.readResponseTo(out);
} finally {
out.close();
}
}
}
/** <p>Execute a command with raw binary output.</p>
*
* <p>Support for this command was added in Lollipop (Android 5.0), and is the recommended way to transmit binary
* data with that version or later. For earlier versions of Android, use
* {@link #executeShell(String, String...)}.</p>
*
* @param command main command to run, e.g. "screencap"
* @param args arguments to the command, e.g. "-p".
* @return combined stdout/stderr stream.
* @throws IOException
* @throws JadbException
*/
public InputStream execute(String command, String... args) throws IOException, JadbException {
Transport transport = getTransport();
StringBuilder shellLine = buildCmdLine(command, args);
send(transport, "exec:" + shellLine.toString());
return new BufferedInputStream(transport.getInputStream());
}
/**
* Builds a command line string from the command and its arguments.
*
* @param command the command.
* @param args the list of arguments.
* @return the command line.
*/
private StringBuilder buildCmdLine(String command, String... args) {
StringBuilder shellLine = new StringBuilder(command);
for (String arg : args) {
shellLine.append(" ");
shellLine.append(Bash.quote(arg));
}
return shellLine;
}
public List<RemoteFile> list(String remotePath) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("LIST", remotePath);
List<RemoteFile> result = new ArrayList<RemoteFile>();
for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) {
result.add(dent);
}
return result;
}
private int getMode(File file) {
//noinspection OctalInteger
return 0664;
}
public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("SEND", remote.getPath() + "," + Integer.toString(mode));
sync.sendStream(source);
sync.sendStatus("DONE", (int) lastModified);
sync.verifyStatus();
}
public void push(File local, RemoteFile remote) throws IOException, JadbException {
FileInputStream fileStream = new FileInputStream(local);
push(fileStream, local.lastModified(), getMode(local), remote);
fileStream.close();
}
public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException {
Transport transport = getTransport();
SyncTransport sync = transport.startSync();
sync.send("RECV", remote.getPath());
sync.readChunksTo(destination);
}
public void pull(RemoteFile remote, File local) throws IOException, JadbException {
FileOutputStream fileStream = new FileOutputStream(local);
pull(remote, fileStream);
fileStream.close();
}
private void send(Transport transport, String command) throws IOException, JadbException {
transport.send(command);
transport.verifyResponse();
}
@Override
public String toString() {
return "Device: " + serial;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((serial == null) ? 0 : serial.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JadbDevice other = (JadbDevice) obj;
if (serial == null) {
if (other.serial != null)
return false;
} else if (!serial.equals(other.serial))
return false;
return true;
}
}
|
import RPi.GPIO as GPIO
KnockPin = 11
LedPin = 12
Led_status = 1
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output
GPIO.setup(KnockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led
def swLed(ev=None):
global Led_status
Led_status = not Led_status
GPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on)
print "LED: " + ("on" if Led_status else "off")
def loop():
GPIO.add_event_detect(KnockPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling
while True:
pass # Don't do anything
def destroy():
GPIO.output(LedPin, GPIO.LOW) # led off
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
|
package org.icgc.dcc.submission.server.repository;
import static org.icgc.dcc.submission.core.model.QUser.user;
import java.util.List;
import org.icgc.dcc.submission.core.model.QUser;
import org.icgc.dcc.submission.core.model.User;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.NonNull;
public class UserRepository extends AbstractRepository<User, QUser> {
@Autowired
public UserRepository(@NonNull Morphia morphia, @NonNull Datastore datastore) {
super(morphia, datastore, user);
}
public List<User> findUsers() {
return list();
}
public User findUserByUsername(@NonNull String username) {
return uniqueResult(entity.username.eq(username));
}
public User saveUser(@NonNull User user) {
save(user);
return user;
}
public User updateUser(@NonNull User user) {
return findAndModify(
createQuery()
.filter("username", user.getUsername()),
<API key>()
.set("failedAttempts", user.getFailedAttempts()),
false, false);
}
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is free software; you can redistribute it and/or modify
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
# This file is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# along with GNU Emacs; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA,
# Python program to check if the input year is a leap year or not
year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
|
package Code.Domain;
/**
*
* @author Andres Orduz Grimaldo
*/
public class Jornada {
private int id;
private String nombre;
private TipoJornada tipoJornada;
private Anio anio;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public TipoJornada getTipoJornada() {
return tipoJornada;
}
public void setTipoJornada(TipoJornada tipoJornada) {
this.tipoJornada = tipoJornada;
}
public Anio getAnio() {
return anio;
}
public void setAnio(Anio anio) {
this.anio = anio;
}
}
|
<?php
namespace <API key>\AlgoliaSearch;
use Exception;
class ClientContext
{
/**
* @var string
*/
public $applicationID;
/**
* @var string
*/
public $apiKey;
/**
* @var array
*/
public $readHostsArray;
/**
* @var array
*/
public $writeHostsArray;
/**
* @var resource
*/
public $curlMHandle;
/**
* @var string
*/
public $adminAPIKey;
/**
* @var string
*/
public $endUserIP;
/**
* @var string
*/
public $algoliaUserToken;
/**
* @var int
*/
public $connectTimeout;
/**
* @var FailingHostsCache
*/
private $failingHostsCache;
/**
* @param string|null $applicationID
* @param string|null $apiKey
* @param array|null $hostsArray
* @param bool $placesEnabled
* @param FailingHostsCache|null $failingHostsCache
*
* @throws Exception
*/
public function __construct($applicationID = null, $apiKey = null, $hostsArray = null, $placesEnabled = false, \<API key>\AlgoliaSearch\FailingHostsCache $failingHostsCache = null)
{
// connect timeout of 1s by default
$this->connectTimeout = 1;
// global timeout of 30s by default
$this->readTimeout = 30;
// search timeout of 5s by default
$this->searchTimeout = 5;
$this->applicationID = $applicationID;
$this->apiKey = $apiKey;
$this->readHostsArray = $hostsArray;
$this->writeHostsArray = $hostsArray;
if ($this->readHostsArray == null || count($this->readHostsArray) == 0) {
$this->readHostsArray = $this->getDefaultReadHosts($placesEnabled);
$this->writeHostsArray = $this-><API key>();
}
if (($this->applicationID == null || mb_strlen($this->applicationID) == 0) && $placesEnabled === false) {
throw new \Exception('AlgoliaSearch requires an applicationID.');
}
if (($this->apiKey == null || mb_strlen($this->apiKey) == 0) && $placesEnabled === false) {
throw new \Exception('AlgoliaSearch requires an apiKey.');
}
$this->curlMHandle = null;
$this->adminAPIKey = null;
$this->endUserIP = null;
$this->algoliaUserToken = null;
$this->rateLimitAPIKey = null;
$this->headers = array();
if ($failingHostsCache === null) {
$this->failingHostsCache = new \<API key>\AlgoliaSearch\<API key>();
} else {
$this->failingHostsCache = $failingHostsCache;
}
$this->rotateHosts();
}
/**
* @param bool $placesEnabled
*
* @return array
*/
private function getDefaultReadHosts($placesEnabled)
{
if ($placesEnabled) {
$hosts = array('places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com');
shuffle($hosts);
array_unshift($hosts, 'places-dsn.algolia.net');
return $hosts;
}
$hosts = array($this->applicationID . '-1.algolianet.com', $this->applicationID . '-2.algolianet.com', $this->applicationID . '-3.algolianet.com');
shuffle($hosts);
array_unshift($hosts, $this->applicationID . '-dsn.algolia.net');
return $hosts;
}
/**
* @return array
*/
private function <API key>()
{
$hosts = array($this->applicationID . '-1.algolianet.com', $this->applicationID . '-2.algolianet.com', $this->applicationID . '-3.algolianet.com');
shuffle($hosts);
array_unshift($hosts, $this->applicationID . '.algolia.net');
return $hosts;
}
/**
* Closes eventually opened curl handles.
*/
public function __destruct()
{
if (is_resource($this->curlMHandle)) {
curl_multi_close($this->curlMHandle);
}
}
/**
* @param $curlHandle
*
* @return resource
*/
public function getMHandle($curlHandle)
{
if (!is_resource($this->curlMHandle)) {
$this->curlMHandle = curl_multi_init();
}
<API key>($this->curlMHandle, $curlHandle);
return $this->curlMHandle;
}
/**
* @param $curlHandle
*/
public function releaseMHandle($curlHandle)
{
<API key>($this->curlMHandle, $curlHandle);
}
/**
* @param string $ip
*/
public function setForwardedFor($ip)
{
$this->endUserIP = $ip;
}
/**
* @param string $token
*/
public function setAlgoliaUserToken($token)
{
$this->algoliaUserToken = $token;
}
/**
* @param string $adminAPIKey
* @param string $endUserIP
* @param string $rateLimitAPIKey
*/
public function setRateLimit($adminAPIKey, $endUserIP, $rateLimitAPIKey)
{
$this->adminAPIKey = $adminAPIKey;
$this->endUserIP = $endUserIP;
$this->rateLimitAPIKey = $rateLimitAPIKey;
}
/**
* Disables the rate limit.
*/
public function disableRateLimit()
{
$this->adminAPIKey = null;
$this->endUserIP = null;
$this->rateLimitAPIKey = null;
}
/**
* @param string $key
* @param string $value
*/
public function setExtraHeader($key, $value)
{
$this->headers[$key] = $value;
}
/**
* @param string $host
*/
public function addFailingHost($host)
{
$this->failingHostsCache->addFailingHost($host);
}
/**
* @return FailingHostsCache
*/
public function <API key>()
{
return $this->failingHostsCache;
}
/**
* This method is called to pass on failing hosts.
* If the host is first either in the failingHosts array, we
* rotate the array to ensure the next API call will be directly made with a working
* host. This mainly ensures we don't add the equivalent of the connection timeout value to each
* request to the API.
*/
public function rotateHosts()
{
$failingHosts = $this->failingHostsCache->getFailingHosts();
$i = 0;
while ($i <= count($this->readHostsArray) && in_array($this->readHostsArray[0], $failingHosts)) {
$i++;
$this->readHostsArray[] = array_shift($this->readHostsArray);
}
$i = 0;
while ($i <= count($this->writeHostsArray) && in_array($this->writeHostsArray[0], $failingHosts)) {
$i++;
$this->writeHostsArray[] = array_shift($this->writeHostsArray);
}
}
}
|
<?php
/* @var $this yii\web\View */
use yii\data\ActiveDataProvider;
use yii\widgets\ListView;
/* @var $books array */
/* @var $book \app\models\Books */
/* @var $booksPhotos \app\models\BooksPhotos */
/* @var $booksDataProvider ActiveDataProvider */
/* @var $<API key> ActiveDataProvider */
$this->title = Yii::t('seo','{appName} - Coding books | Programming Library', ['appName' => \Yii::$app->name]);
$this->registerMetaTag([
'name' => 'description',
'content' => Yii::t('seo', 'CoBooks is an online library consisting of books about programming, management of IT projects and other areas related to IT. Site for free online reading and downloading books in different formats.')
]);
?>
<div class="row clearfix text-center">
<h2 class="title-one">
<?= Yii::t('seo', 'Free IT e-library') ?>
</h2>
<div id="books-categories" class="portfolio-filter">
<ul class="nav nav-pills text-center">
<li class="active">
<a data-toggle="pill" href="#popular-books">
<?= Yii::t('books', 'Popular Books') ?>
</a>
</li>
<li>
<a data-toggle="pill" href="#last-books">
<?= Yii::t('categories', 'Novelties') ?>
</a>
</li>
</ul>
</div>
<div class="tab-content">
<div id="popular-books" class="tab-pane fade in active">
<div class="books-box">
<?= ListView::widget([
'dataProvider' => $<API key>,
'summary' => false,
'layout' => '{items}',
'itemView' => '/parts/book',
]); ?>
<a class="btn btn-default" href="<?= \yii\helpers\Url::to(['/book/popular']) ?>">
<?= Yii::t('app', 'View all') ?>
</a>
</div>
</div>
<div id="last-books" class="tab-pane fade">
<div class="books-box">
<?= ListView::widget([
'dataProvider' => $booksDataProvider,
'summary' => false,
'layout' => '{items}',
'itemView' => '/parts/book',
]); ?>
<a class="btn btn-default" href="<?= \yii\helpers\Url::to(['/book/last']) ?>">
<?= Yii::t('app', 'View all') ?>
</a>
</div>
</div>
</div>
</div>
|
function drawChart(len){
var box = document.createElement('div');
box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column');
for(var i=0; i<len; i++){
var row = document.createElement('div');
if(i<len-1){
row.setAttribute('style','border-bottom:1px solid black;display:flex;box-sizing: border-box; flex: 1;');
}
else{
row.setAttribute('style','display:flex;box-sizing: border-box; flex: 1;');
}
for(var j=0; j<len; j++){
var col = document.createElement('div');
if(i%2===0){
if(j%2===0){
col.setAttribute('style','background-color:white; flex: 1;');
}
else{
col.setAttribute('style','background-color:black; flex: 1;');
}
}else{
if(j%2===0){
col.setAttribute('style','background-color:black; flex: 1;');
}
else{
col.setAttribute('style','background-color:white; flex: 1;');
}
}
row.appendChild(col);
}
box.appendChild(row);
}
document.body.appendChild(box);
}
drawChart(5);
|
package com.tage.rpgutil.client.gui;
import net.minecraftforge.client.event.<API key>;
import cpw.mods.fml.common.eventhandler.Cancelable;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.common.eventhandler.EventPriority;
@Cancelable
public class GuiHealth extends Event
{
public static enum ElementType
{
ARMOR,
HEALTH,
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using log4net;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using common;
using jm726.lib.wrapper;
using jm726.lib.wrapper.logger;
namespace jm726.lib.wrapper.logger {
<summary>
Class which uses the ISpy interface to record all method calls to a given object. These are recorded to Xml.
Can also play back recordings
ONLY PUBLIC PROPERTIES WITH GETTERS _AND_ SETTERS WILL BE LOGGED CORRECTLY
</summary>
<typeparam name="TToLog">The interface which is being logged.</typeparam>
public class XmlLogWriter<TToLog> : Wrapper<TToLog>, IXmlLogWriter<TToLog> where TToLog : class {
#region Private Fields
<summary>
The log4net logger object used to log information to the console or log events.
</summary>
private readonly ILog _logger;
<summary>
The name of this logger. This is the name of the type being logged with '_Logger' added onto the end.
</summary>
private readonly string _name;
<summary>
The XML document which stores the event logging document as it is being built.
</summary>
private XmlDocument _doc;
<summary>
The root XML node to which all events are to be appended as children.
</summary>
private XmlNode _root;
<summary>
The XML document being built up to log all the events happening to the wrapped instance of TToLog.
</summary>
private DateTime _lastEvent;
<summary>
Wether or not events are to be logged currently.
</summary>
private bool _logging;
<summary>
Whether or not to serialize the return value of the method.
</summary>
private bool _recordForPlayback;
#endregion
#region XmlLogWriter Properties
<inheritdoc />
public XmlDocument Log {
get { return _doc; }
}
#endregion
#region Constructor
<summary>
Constructor which creates a generic logger. Instantiates a series of helper fields and stores the TToLog instance which is to be wrapped by this logger.
</summary>
<param name="spy">The instance of TToLog which this logger will log calls to.</param>
public XmlLogWriter(TToLog instance, bool recordForPlayback = false, bool recursive = true)
: base(instance, "XmlLogWriter", recursive) {
_lastEvent = default(DateTime);
_recordForPlayback = recordForPlayback;
_name = typeof(TToLog).FullName + "_Logger";
_logger = LogManager.GetLogger(_name);
_doc = new XmlDocument();
XmlNode declaration = _doc.<API key>("1.0", "utf-8", "yes");
_doc.AppendChild(declaration);
}
#endregion
#region Override Abstract Methods from Wrapper
public override void <API key>(string methodName, object[] parameters) {
if (!_logging) {
CallMethod(methodName, parameters);
return;
}
MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters);
if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet"))
return;
XmlNode callNode = m.Serialize(_doc, SwitchArgument);
callNode.Attributes.Append(GetTimeAttr());
_root.AppendChild(callNode);
}
public override object <API key>(string methodName, object[] parameters) {
if (!_logging)
return CallMethod(methodName, parameters);
MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters);
if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet"))
return m.Return;
XmlNode callNode = m.Serialize(_doc, SwitchArgument, _recordForPlayback);
callNode.Attributes.Append(GetTimeAttr());
_root.AppendChild(callNode);
return m.Return;
}
public override void <API key>(string eventName, object[] parameters) {
//Do Nothing
}
<summary>
Log the time at which a method call was made.
</summary>
private XmlAttribute GetTimeAttr() {
XmlAttribute time = _doc.CreateAttribute("Time");
if (_lastEvent.Equals(default(DateTime)))
time.Value = "0";
else
time.Value = DateTime.Now.Subtract(_lastEvent).TotalMilliseconds + "";
_lastEvent = DateTime.Now;
return time;
}
#endregion
#region XmlLogWriter Methods
<inheritdoc />
public void StartRecording() {
if (_root != null)
_doc.RemoveChild(_root);
XmlNode root = _doc.CreateElement("Events");
_doc.AppendChild(root);
StartRecording(_doc);
}
public void StartRecording(XmlDocument doc) {
XmlNodeList roots = doc.<API key>("Events");
if (roots.Count == 0)
throw new ArgumentException("Unable to append events to supplied XML document. Document is not in the correct format");
_doc = doc;
_doc.NodeInserted += (source, args) => {
if (args.NewParent.Name.Equals("Events"))
_lastEvent = DateTime.Now;
};
_root = roots[0];
_lastEvent = default(DateTime);
_logging = true;
}
<inheritdoc />
public void StopRecording() {
_logging = false;
}
<inheritdoc />
public void PauseRecording() {
_lastEvent = DateTime.Now;
_logging = false;
}
<inheritdoc />
public void RestartRecording() {
_logging = false;
}
#endregion
#region Util
<summary>
Used for extensibility.
Override this and check the type of the argument to define special behaviour for special types.
Original defined so that instance specific IDs can be swapped to general but less unique names in the XML
which can then be resolved back to new specific IDs when the sequence is played back.
</summary>
<param name="arg">The argument to swap for a different type.</param>
<returns>The type to swap the argument to.</returns>
protected virtual XmlNode SwitchArgument(ParameterInfo param, object arg) {
return null;
}
#endregion
}
}
|
#ifndef <API key>
#define <API key>
// Qt include.
#include <Qt3DCore/QEntity>
// C++ include.
#include <memory>
QT_BEGIN_NAMESPACE
namespace Qt3DRender {
class QCamera;
}
QT_END_NAMESPACE
// CameraController
class <API key>;
class CameraController Q_DECL_FINAL
: public Qt3DCore::QEntity
{
Q_OBJECT
public:
CameraController( Qt3DRender::QCamera * camera,
Qt3DCore::QEntity * parent );
~CameraController();
private slots:
void _q_onTriggered( float );
private:
friend class <API key>;
Q_DISABLE_COPY( CameraController )
std::unique_ptr< <API key> > d;
}; // class CameraController
#endif // <API key>
|
.ui-multiselect { padding:4px 2px 4px 4px; text-align:left }
.ui-multiselect span.ui-icon { float:right }
.<API key> .<API key> input { left:-9999px; position:absolute !important; top: auto !important; }
.<API key> .<API key> label { padding:5px !important }
.<API key> { margin-bottom:3px; padding:3px 0 3px 4px; }
.<API key> ul { font-size:0.9em }
.<API key> ul li { float:left; padding:0 10px 0 0; }
.<API key> a { text-decoration:none; }
.<API key> a:hover { text-decoration:underline; }
.<API key> span.ui-icon { float:left; }
.<API key> .<API key> { float:right; padding-right:0; text-align:right; }
.ui-multiselect-menu { display:none; padding:3px; position:absolute; text-align: left; }
.<API key> { overflow-y:auto; position:relative; }
.<API key> label { border:1px solid transparent; cursor:default; display:block; padding:3px 1px; }
.<API key> label input { position:relative; top:1px }
.<API key> label img { height: 30px; vertical-align: middle; padding-right: 3px;}
.<API key> li { clear:both; font-size:0.9em; list-style: none; padding-right:3px; }
.<API key> .<API key> { padding: 3px; }
.<API key> { display: inline-block; vertical-align: top; }
.<API key> .<API key> a { border-bottom:1px solid; cursor: pointer; display:block; font-weight:bold; margin:1px 0; padding:3px; text-align:center; text-decoration:none; }
@media print{
.ui-multiselect-menu {display: none;}
}
|
/* eslint-disable no-self-assign */
import Game from '../../../../gui/html/js/game';
import { Plugin } from '../../../../gui/html/js/plugin';
import Translator from '../../../../gui/html/js/translator';
jest.mock('../../../../gui/html/js/dom');
jest.mock('../../../../gui/html/js/filters');
describe('Game', () => {
const l10n = new Translator();
const <API key> = {
name: 'test',
isActive: false,
isDirty: false,
isEmpty: false,
isMaster: false,
isLightPlugin: false,
loadsArchive: false,
messages: [],
suggestedTags: [],
currentTags: []
};
const gameData = {
folder: 'test',
generalMessages: [
{
type: 'say',
text: 'test',
language: 'en',
condition: ''
}
],
masterlist: { revision: '0', date: '' },
groups: { masterlist: [], userlist: [] },
plugins: [<API key>],
bashTags: []
};
describe('#constructor()', () => {
test("should set folder to the object's value", () => {
const game = new Game(gameData, l10n);
expect(game.folder).toBe('test');
});
test("should set generalMessages to the object's value", () => {
const game = new Game(gameData, l10n);
expect(game.generalMessages).toEqual([
{
type: 'say',
text: 'test',
language: 'en',
condition: ''
}
]);
});
test("should set masterlist to the object's value", () => {
const game = new Game(gameData, l10n);
expect(game.masterlist).toEqual({ revision: '0', date: '' });
});
test("should construct plugins from the object's plugins value", () => {
const game = new Game(gameData, l10n);
expect(game.plugins.length).toBe(1);
expect(game.plugins[0]).toHaveProperty('update');
expect(game.plugins[0].name).toBe('test');
expect(game.plugins[0].cardZIndex).toBe(1);
});
test("should set oldLoadOrder to an empty array even if the object's value if defined", () => {
const game = new Game(gameData, l10n);
expect(game.oldLoadOrder).toEqual([]);
});
});
describe('#folder', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// <API key> @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener('<API key>', handleEvent);
});
test('setting value should not dispatch an event if the new value is equal to the old one', done => {
handleEvent = () => {
done(new Error('Should not have fired an event'));
};
document.addEventListener('<API key>', handleEvent);
game.folder = game.folder;
setTimeout(done, 100);
});
test('setting value should dispatch an event if the new value differs from the old one', done => {
handleEvent = evt => {
expect(evt.detail.folder).toBe('other test');
done();
};
document.addEventListener('<API key>', handleEvent);
game.folder = 'other test';
});
});
describe('#generalMessages', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// <API key> @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener(
'<API key>',
handleEvent
);
});
test('setting value should not dispatch an event if the new value is equal to the old one', done => {
handleEvent = () => {
done(new Error('Should not have fired an event'));
};
document.addEventListener(
'<API key>',
handleEvent
);
game.generalMessages = game.generalMessages;
setTimeout(done, 100);
});
test('setting value should dispatch an event if the new and old message strings differ', done => {
const newMessages = [
{
type: 'say',
text: 'bar',
language: 'en',
condition: ''
}
];
handleEvent = evt => {
expect(evt.detail.messages).toEqual(newMessages);
expect(evt.detail.totalDiff).toBe(0);
expect(evt.detail.errorDiff).toBe(0);
expect(evt.detail.warningDiff).toBe(0);
done();
};
document.addEventListener(
'<API key>',
handleEvent
);
game.generalMessages = newMessages;
});
test('setting value should dispatch an event if the new and old message type counts differ', done => {
const newMessages = [
{
type: 'warn',
text: 'foo',
language: 'en',
condition: ''
},
{
type: 'error',
text: 'bar',
language: 'en',
condition: ''
}
];
game.generalMessages = [];
handleEvent = evt => {
expect(evt.detail.messages).toEqual(newMessages);
expect(evt.detail.totalDiff).toBe(2);
expect(evt.detail.errorDiff).toBe(1);
expect(evt.detail.warningDiff).toBe(1);
done();
};
document.addEventListener(
'<API key>',
handleEvent
);
game.generalMessages = newMessages;
});
});
describe('#masterlist', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// <API key> @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener('<API key>', handleEvent);
});
test('setting value should not dispatch an event if the new value is equal to the old one', done => {
handleEvent = () => {
done(new Error('Should not have fired an event'));
};
document.addEventListener('<API key>', handleEvent);
game.masterlist = game.masterlist;
setTimeout(done, 100);
});
test('setting value should dispatch an event if the new value differs from the old one', done => {
const newMasterlist = {
revision: 'foo',
date: 'bar'
};
handleEvent = evt => {
expect(evt.detail).toEqual(newMasterlist);
done();
};
document.addEventListener('<API key>', handleEvent);
game.masterlist = newMasterlist;
});
});
describe('#plugins', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// <API key> @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener('<API key>', handleEvent);
});
test('setting value should dispatch an event if the new value is equal to the old one', done => {
handleEvent = () => {
done();
};
document.addEventListener('<API key>', handleEvent);
game.plugins = game.plugins;
});
test('setting value should dispatch an event if the new value differs from the old one', done => {
const newMessages = [
{
type: 'warn',
text: 'foo',
language: 'en',
condition: ''
},
{
type: 'error',
text: 'bar',
language: 'en',
condition: ''
}
];
const newPlugins = [
new Plugin({
<API key>,
name: 'a',
isActive: true,
messages: [newMessages[0]]
}),
new Plugin({
<API key>,
name: 'b',
isDirty: true,
messages: [{ ...newMessages[0], type: 'say' }]
})
];
handleEvent = evt => {
expect(evt.detail.valuesAreTotals).toBe(true);
expect(evt.detail.totalMessageNo).toBe(4);
expect(evt.detail.warnMessageNo).toBe(2);
expect(evt.detail.errorMessageNo).toBe(1);
expect(evt.detail.totalPluginNo).toBe(2);
expect(evt.detail.activePluginNo).toBe(1);
expect(evt.detail.dirtyPluginNo).toBe(1);
done();
};
document.addEventListener('<API key>', handleEvent);
game.generalMessages = newMessages;
game.plugins = newPlugins;
});
});
describe('groups', () => {
test("get should return the game's groups", () => {
const groups = {
masterlist: [{ name: 'a', after: [] }],
userlist: [{ name: 'b', after: [] }]
};
const game = new Game({ ...gameData, groups }, l10n);
expect(game.groups).toStrictEqual([
{ name: 'a', after: [], isUserAdded: false },
{ name: 'b', after: [], isUserAdded: true }
]);
});
});
describe('#setGroups()', () => {
// It's not worth the hassle of defining and checking the event type in test
// code.
// <API key> @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
afterEach(() => {
document.removeEventListener('<API key>', handleEvent);
});
test('should merge the given masterlist and userlist groups arrays', () => {
const game = new Game(gameData, l10n);
const groups = {
masterlist: [{ name: 'a', after: [] }],
userlist: [{ name: 'b', after: [] }]
};
game.setGroups(groups);
expect(game.groups).toStrictEqual([
{ name: 'a', after: [], isUserAdded: false },
{ name: 'b', after: [], isUserAdded: true }
]);
});
test('should dispatch an event', done => {
handleEvent = () => {
done();
};
document.addEventListener('<API key>', handleEvent);
const game = new Game(gameData, l10n);
const groups = {
masterlist: [{ name: 'a', after: [] }],
userlist: [{ name: 'b', after: [] }]
};
game.setGroups(groups);
});
});
describe('#getContent()', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should return an object of two empty arrays if there is no game data', () => {
game.plugins = [];
game.generalMessages = [];
expect(game.getContent()).toEqual({
messages: [],
plugins: []
});
});
test('should return a structure containing converted plugin and message structures', () => {
game.generalMessages = [
{
type: 'say',
condition: 'file("foo.esp")',
language: 'fr',
text: 'Bonjour le monde'
}
];
game.plugins = [
new Plugin({
name: 'foo',
crc: 0xdeadbeef,
version: '1.0',
isActive: true,
isEmpty: true,
isMaster: false,
isLightPlugin: false,
loadsArchive: true,
group: 'group1',
messages: [
{
type: 'warn',
condition: 'file("bar.esp")',
language: 'en',
text: 'Hello world'
}
],
currentTags: [
{
name: 'Relev',
isAddition: true,
condition: ''
}
],
suggestedTags: [
{
name: 'Delev',
isAddition: true,
condition: ''
}
],
isDirty: true
})
];
expect(game.getContent()).toEqual({
messages: game.generalMessages,
plugins: [
{
name: game.plugins[0].name,
crc: game.plugins[0].crc,
version: game.plugins[0].version,
isActive: game.plugins[0].isActive,
isEmpty: game.plugins[0].isEmpty,
loadsArchive: game.plugins[0].loadsArchive,
group: game.plugins[0].group,
messages: game.plugins[0].messages,
currentTags: game.plugins[0].currentTags,
suggestedTags: game.plugins[0].suggestedTags,
isDirty: game.plugins[0].isDirty
}
]
});
});
});
describe('#getPluginNames()', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should return an empty array if there are no plugins', () => {
game.plugins = [];
expect(game.getPluginNames().length).toBe(0);
});
test('should return an array of plugin filenames if there are plugins', () => {
game.plugins = [
new Plugin({
<API key>,
name: 'foo',
isActive: true,
messages: [{ type: 'warn', text: '', language: 'en', condition: '' }]
})
];
expect(game.getPluginNames()).toEqual(['foo']);
});
});
describe('#getGroupPluginNames()', () => {
let game: Game;
beforeEach(() => {
const plugins = [
new Plugin({
<API key>,
name: 'foo',
group: 'test group'
}),
new Plugin({
<API key>,
name: 'bar',
group: 'other group'
}),
new Plugin({
<API key>,
name: 'foobar',
group: 'test group'
})
];
game = new Game({ ...gameData, plugins }, l10n);
});
test('should return an empty array if there are no plugins in the given group', () => {
expect(game.getGroupPluginNames('empty group').length).toBe(0);
});
test('should return an array of filenames of plugins in the given group', () => {
expect(game.getGroupPluginNames('test group')).toEqual(['foo', 'foobar']);
});
});
describe('#setSortedPlugins', () => {
let game: Game;
// It's not worth the hassle of defining and checking the event type in test
// code.
// <API key> @typescript-eslint/no-explicit-any
let handleEvent: (evt: any) => void;
beforeEach(() => {
game = new Game(gameData, l10n);
});
afterEach(() => {
document.removeEventListener('<API key>', handleEvent);
});
test('should append new plugins to the plugins array', () => {
game.setSortedPlugins([
new Plugin({
<API key>,
name: 'foo'
})
]);
expect(game.plugins[0].name).toBe('foo');
});
test('should update existing plugins with new data', () => {
game.plugins = [
new Plugin({
<API key>,
name: 'foo',
isActive: true,
messages: [{ type: 'warn', text: '', language: 'en', condition: '' }]
})
];
game.setSortedPlugins([
new Plugin({
<API key>,
name: 'foo',
crc: 0xdeadbeef
})
]);
expect(game.plugins[0].crc).toBe(0xdeadbeef);
expect(game.plugins[0].isActive).toBe(false);
});
test('should reorder plugins to given order', () => {
game.plugins = [
new Plugin({
<API key>,
name: 'foo'
}),
new Plugin({
<API key>,
name: 'bar'
})
];
game.setSortedPlugins([
new Plugin({
<API key>,
name: 'bar'
}),
new Plugin({
<API key>,
name: 'foo'
})
]);
expect(game.plugins[0].name).toBe('bar');
expect(game.plugins[1].name).toBe('foo');
});
test('should store old load order', () => {
game.plugins = [
new Plugin({
<API key>,
name: 'foo'
}),
new Plugin({
<API key>,
name: 'bar'
})
];
game.setSortedPlugins([
new Plugin({
<API key>,
name: 'bar'
}),
new Plugin({
<API key>,
name: 'foo'
})
]);
expect(game.oldLoadOrder[0].name).toBe('foo');
expect(game.oldLoadOrder[1].name).toBe('bar');
});
test('should dispatch an event', done => {
handleEvent = () => {
done();
};
document.addEventListener('<API key>', handleEvent);
game.setSortedPlugins([
new Plugin({
<API key>,
name: 'foo'
})
]);
});
});
describe('#applySort', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should delete the stored old load order', () => {
game.oldLoadOrder = gameData.plugins.map(p => new Plugin(p));
game.applySort();
expect(game.oldLoadOrder).toEqual([]);
});
});
describe('#cancelSort', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should set the current load order to the given plugins', () => {
const oldLoadOrder = [
new Plugin({
<API key>,
name: 'foo'
}),
new Plugin({
<API key>,
name: 'bar'
}),
new Plugin({
<API key>,
name: 'baz'
})
];
game.oldLoadOrder = oldLoadOrder;
game.plugins = [oldLoadOrder[2], oldLoadOrder[1], oldLoadOrder[0]];
game.cancelSort(
[{ name: 'baz', loadOrderIndex: 0 }, { name: 'foo' }],
[]
);
expect(game.plugins).toEqual([oldLoadOrder[2], oldLoadOrder[0]]);
});
test('should delete the stored old load order', () => {
game.oldLoadOrder = [
new Plugin({
<API key>,
name: 'foo'
}),
new Plugin({
<API key>,
name: 'bar'
})
];
game.cancelSort([], []);
expect(game.oldLoadOrder).toEqual([]);
});
test('should set plugin load order indices using the array passed as the first parameter', () => {
game.oldLoadOrder = [
new Plugin({
<API key>,
name: 'foo',
loadOrderIndex: 1
}),
new Plugin({
<API key>,
name: 'bar',
loadOrderIndex: 0
})
];
game.cancelSort(
[
{ name: 'bar', loadOrderIndex: 0 },
{ name: 'foo', loadOrderIndex: 2 }
],
[]
);
expect(game.plugins[0].name).toBe('bar');
expect(game.plugins[0].loadOrderIndex).toBe(0);
expect(game.plugins[1].name).toBe('foo');
expect(game.plugins[1].loadOrderIndex).toBe(2);
});
test('should set the general messages to the second passed parameter', () => {
game.oldLoadOrder = [
new Plugin({
<API key>,
name: 'foo',
loadOrderIndex: 1
}),
new Plugin({
<API key>,
name: 'bar',
loadOrderIndex: 0
})
];
const messages = [
{
type: 'say',
text: 'foo',
language: 'en',
condition: ''
}
];
game.cancelSort([], messages);
expect(game.generalMessages).toEqual(messages);
});
});
describe('#clearMetadata', () => {
let game: Game;
beforeEach(() => {
game = new Game(gameData, l10n);
});
test('should delete stored userlist data for existing plugins', () => {
game.plugins = [
new Plugin({
<API key>,
name: 'foo',
userlist: {
name: '',
after: [],
req: [],
inc: [],
msg: [],
tag: [],
dirty: [],
clean: [],
url: []
}
})
];
game.clearMetadata([
new Plugin({
<API key>,
name: 'foo'
})
]);
expect(game.plugins[0].userlist).toBe(undefined);
});
test('should update existing plugin data', () => {
game.plugins = [
new Plugin({
<API key>,
name: 'foo',
isActive: true
})
];
game.clearMetadata([
new Plugin({
<API key>,
name: 'foo',
crc: 0xdeadbeef
})
]);
expect(game.plugins[0].crc).toBe(0xdeadbeef);
expect(game.plugins[0].isActive).toBe(false);
});
});
});
|
# == Schema Information
# Table name: causes
# id :integer not null, primary key
# name :string not null
# description :string
# image_id :integer
# created_at :datetime not null
# updated_at :datetime not null
require 'rails_helper'
RSpec.describe Cause, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
|
<?php
/**
* The template part for displaying single archive from hospital posts
*
* @package <API key>
*
*
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( sprintf( '<h2 class="<API key>"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );?>
</header><!-- .entry-header -->
<div class="<API key>">
<?php
$review_description = get_post_meta($post->ID);
if(!empty($review_description['reviewer_name'][0])){
$reviewer_name = $review_description['reviewer_name'][0];
echo '<h3>'.$reviewer_name.'</h3>';
}
the_post_thumbnail('thumbnail');
the_content();
echo '</br>';
echo get_the_tag_list( '<br>Tags: ', ', ','<br>' );
echo '</br>';
edit_post_link( );
?>
</div><!-- .<API key> -->
</article><!-- #post-## -->
|
// simplewall
#pragma once
#include "routine.h"
#include <winsock2.h>
#include <ws2ipdef.h>
#include <ws2tcpip.h>
#include <windns.h>
#include <mstcpip.h>
#include <iphlpapi.h>
#include <aclapi.h>
#include <dbt.h>
#include <fwpmu.h>
#include <mmsystem.h>
#include <netfw.h>
#include <shlguid.h>
#include <shobjidl.h>
#include <softpub.h>
#include <subauth.h>
#include <mscat.h>
#include "app.h"
#include "rapp.h"
#include "main.h"
#include "resource.h"
DECLSPEC_SELECTANY STATIC_DATA config = {0};
DECLSPEC_SELECTANY PROFILE_DATA profile_info = {0};
DECLSPEC_SELECTANY PR_HASHTABLE apps_table = NULL;
DECLSPEC_SELECTANY PR_LIST rules_list = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE rules_config = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE log_table = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE cache_information = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE cache_resolution = NULL;
DECLSPEC_SELECTANY PR_HASHTABLE colors_table = NULL;
DECLSPEC_SELECTANY PR_ARRAY filter_ids = NULL;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_apps = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_apply = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_rules = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_rules_config = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_loglist = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_profile = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK lock_transaction = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK <API key> = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_QUEUED_LOCK <API key> = PR_QUEUED_LOCK_INIT;
DECLSPEC_SELECTANY R_WORKQUEUE file_queue = {0};
DECLSPEC_SELECTANY R_WORKQUEUE log_queue = {0};
DECLSPEC_SELECTANY R_WORKQUEUE resolver_queue = {0};
DECLSPEC_SELECTANY R_WORKQUEUE <API key> = {0};
DECLSPEC_SELECTANY R_WORKQUEUE wfp_queue = {0};
DECLSPEC_SELECTANY R_FREE_LIST context_free_list = {0};
DECLSPEC_SELECTANY R_FREE_LIST listview_free_list = {0};
// timers array
DECLSPEC_SELECTANY const LONG64 timer_array[] =
{
2 * 60,
5 * 60,
10 * 60,
30 * 60,
1 * 3600,
2 * 3600,
4 * 3600,
6 * 3600
};
// dropped events callback subscription (win7+)
#ifndef FWP_DIRECTION_IN
#define FWP_DIRECTION_IN 0x00003900L
#endif
#ifndef FWP_DIRECTION_OUT
#define FWP_DIRECTION_OUT 0x00003901L
#endif
#include "controls.h"
#include "db.h"
#include "editor.h"
#include "helper.h"
#include "icons.h"
#include "listview.h"
#include "log.h"
#include "messages.h"
#include "network.h"
#include "notifications.h"
#include "packages.h"
#include "profile.h"
#include "search.h"
#include "security.h"
#include "timer.h"
#include "wfp.h"
|
\section{\-Getopt \-Class \-Reference}
\label{interface_getopt}\index{\-Getopt@{\-Getopt}}
{\ttfamily \#import $<$\-Getopt.\-h$>$}
\subsection*{\-Public \-Member \-Functions}
\begin{DoxyCompactItemize}
\item
(void) -\/ {\bf init\-Getopt\-:}
\item
(\-B\-O\-O\-L) -\/ {\bf response\-Is\-Valid}
\item
(\-N\-S\-String $\ast$) -\/ {\bf get\-Message}
\item
(\-N\-S\-String $\ast$) -\/ {\bf get\-Response\-Status}
\item
(int) -\/ {\bf get\-Response\-Code}
\item
(\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaigns\-Id\-List}
\item
(\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaign\-Status\-List}
\item
(\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaign\-Status\-Code\-List}
\item
(int) -\/ {\bf get\-Campaign\-Status\-Code\-:}
\item
(\-N\-S\-String $\ast$) -\/ {\bf get\-Campaign\-Status\-:}
\end{DoxyCompactItemize}
\subsection{\-Detailed \-Description}
\doxyref{\-Getopt.\-h}{p.}{_getopt_8h_source} \-Mercury\-\_\-i\-O\-S
\-Created by \-Julien \-Salvi on 9/12/11. \-Copyright 2011 \-Mogreet \-Inc. \-All rights reserved.
\-This file is part of \doxyref{\-Mercury}{p.}{interface_mercury}.
\doxyref{\-Mercury}{p.}{interface_mercury} is free software\-: you can redistribute it and/or modify it under the terms of the \-G\-N\-U \-General \-Public \-License as published by the \-Free \-Software \-Foundation, either version 3 of the \-License, or (at your option) any later version.
\doxyref{\-Mercury}{p.}{interface_mercury} is distributed in the hope that it will be useful, but \-W\-I\-T\-H\-O\-U\-T \-A\-N\-Y \-W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of \-M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or \-F\-I\-T\-N\-E\-S\-S \-F\-O\-R \-A \-P\-A\-R\-T\-I\-C\-U\-L\-A\-R \-P\-U\-R\-P\-O\-S\-E. \-See the \-G\-N\-U \-General \-Public \-License for more details.
\-You should have received a copy of the \-G\-N\-U \-General \-Public \-License along with \doxyref{\-Mercury}{p.}{interface_mercury}. \-If not, see $<${\tt http\-://www.\-gnu.\-org/licenses/}$>$. \-The \doxyref{\-Getopt}{p.}{interface_getopt} object contains the response from a \doxyref{\-Mercury\#getopt}{p.}{} request to the \-Mo\-M\-S \-A\-P\-I.
\-Getopt.\-m \-Mercury\-\_\-i\-O\-S
\-Created by \-Julien \-Salvi on 9/12/11. \-Copyright 2011 \-Mogreet \-Inc. \-All rights reserved.
\-This file is part of \doxyref{\-Mercury}{p.}{interface_mercury}.
\doxyref{\-Mercury}{p.}{interface_mercury} is free software\-: you can redistribute it and/or modify it under the terms of the \-G\-N\-U \-General \-Public \-License as published by the \-Free \-Software \-Foundation, either version 3 of the \-License, or (at your option) any later version.
\doxyref{\-Mercury}{p.}{interface_mercury} is distributed in the hope that it will be useful, but \-W\-I\-T\-H\-O\-U\-T \-A\-N\-Y \-W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of \-M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or \-F\-I\-T\-N\-E\-S\-S \-F\-O\-R \-A \-P\-A\-R\-T\-I\-C\-U\-L\-A\-R \-P\-U\-R\-P\-O\-S\-E. \-See the \-G\-N\-U \-General \-Public \-License for more details.
\-You should have received a copy of the \-G\-N\-U \-General \-Public \-License along with \doxyref{\-Mercury}{p.}{interface_mercury}. \-If not, see $<${\tt http\-:
\subsection{\-Member \-Function \-Documentation}
\index{\-Getopt@{\-Getopt}!get\-Campaigns\-Id\-List@{get\-Campaigns\-Id\-List}}
\index{get\-Campaigns\-Id\-List@{get\-Campaigns\-Id\-List}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaigns\-Id\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaigns\-Id\-List
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{<API key>}
\-Gets the campaign \-I\-Ds. \begin{DoxyReturn}{\-Returns}
\-An \-N\-S\-Mutable\-Array that contains all the campaigns \-I\-D.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-:@{get\-Campaign\-Status\-:}}
\index{get\-Campaign\-Status\-:@{get\-Campaign\-Status\-:}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaign\-Status\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Campaign\-Status\-:
\begin{DoxyParamCaption}
\item[{dummy(\-N\-S\-String$\ast$)}]{campaign\-Id}
\end{DoxyParamCaption}
}\label{<API key>}
\-Gets a campaign status.
\begin{DoxyParams}{\-Parameters}
{\em campaign\-Id} & \-The campaign \-I\-D. \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{\-Returns}
\-The campaign status of the specified campaign.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-Code\-:@{get\-Campaign\-Status\-Code\-:}}
\index{get\-Campaign\-Status\-Code\-:@{get\-Campaign\-Status\-Code\-:}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaign\-Status\-Code\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (int) get\-Campaign\-Status\-Code\-:
\begin{DoxyParamCaption}
\item[{dummy(\-N\-S\-String$\ast$)}]{campaign\-Id}
\end{DoxyParamCaption}
}\label{<API key>}
\-Gets a campaign status code.
\begin{DoxyParams}{\-Parameters}
{\em campaign\-Id} & \-The campaign \-I\-D. \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{\-Returns}
\-The campaign status code of the specified campaign.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-Code\-List@{get\-Campaign\-Status\-Code\-List}}
\index{get\-Campaign\-Status\-Code\-List@{get\-Campaign\-Status\-Code\-List}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaign\-Status\-Code\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaign\-Status\-Code\-List
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{<API key>}
\-Gets the campaign status codes. \begin{DoxyReturn}{\-Returns}
\-An \-N\-S\-Mutable\-Array that contains all the campaign status codes.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-List@{get\-Campaign\-Status\-List}}
\index{get\-Campaign\-Status\-List@{get\-Campaign\-Status\-List}!Getopt@{\-Getopt}}
\subsubsection[{get\-Campaign\-Status\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaign\-Status\-List
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{<API key>}
\-Gets the campaign status. \begin{DoxyReturn}{\-Returns}
\-An \-N\-S\-Mutable\-Array that contains all the campaigns status.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Message@{get\-Message}}
\index{get\-Message@{get\-Message}!Getopt@{\-Getopt}}
\subsubsection[{get\-Message}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Message
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{<API key>}
\begin{DoxyReturn}{\-Returns}
\-The \-Message.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Response\-Code@{get\-Response\-Code}}
\index{get\-Response\-Code@{get\-Response\-Code}!Getopt@{\-Getopt}}
\subsubsection[{get\-Response\-Code}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (int) get\-Response\-Code
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{<API key>}
\begin{DoxyReturn}{\-Returns}
\-The response \-Code.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!get\-Response\-Status@{get\-Response\-Status}}
\index{get\-Response\-Status@{get\-Response\-Status}!Getopt@{\-Getopt}}
\subsubsection[{get\-Response\-Status}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Response\-Status
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{<API key>}
\begin{DoxyReturn}{\-Returns}
\-The response \-Status.
\end{DoxyReturn}
\index{\-Getopt@{\-Getopt}!init\-Getopt\-:@{init\-Getopt\-:}}
\index{init\-Getopt\-:@{init\-Getopt\-:}!Getopt@{\-Getopt}}
\subsubsection[{init\-Getopt\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (void) init\-Getopt\-:
\begin{DoxyParamCaption}
\item[{dummy(\-N\-S\-String$\ast$)}]{url\-Getopt}
\end{DoxyParamCaption}
}\label{<API key>}
\-Initializes a new \doxyref{\-Getopt}{p.}{interface_getopt} response object.
\begin{DoxyParams}{\-Parameters}
{\em url\-Getopt} & \-U\-R\-L for calling requests from \-Mogreet \-A\-P\-I. \\
\hline
\end{DoxyParams}
\index{\-Getopt@{\-Getopt}!response\-Is\-Valid@{response\-Is\-Valid}}
\index{response\-Is\-Valid@{response\-Is\-Valid}!Getopt@{\-Getopt}}
\subsubsection[{response\-Is\-Valid}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-B\-O\-O\-L) response\-Is\-Valid
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{<API key>}
\-Checks if the response code is 1. \begin{DoxyReturn}{\-Returns}
\-Y\-E\-S if the response code is 1, \-N\-O if it is not
\end{DoxyReturn}
\-The documentation for this class was generated from the following files\-:\begin{DoxyCompactItemize}
\item
\-Mercury\-\_\-i\-O\-S/\-Classes/\-Getopt.\-h\item
\-Mercury\-\_\-i\-O\-S/\-Classes/\-Getopt.\-m\end{DoxyCompactItemize}
|
#!/usr/bin/env python
# distributed with this source distribution.
# This file is part of GNUHAWK.
# GNUHAWK is free software: you can redistribute it and/or modify is under the
# version.
# GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.<API key>):
"""Test for all component implementations in sig_source_i"""
def <API key>(self):
# Launch the component with the default execparams
execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False)
execparams = dict([(x.id, any.from_any(x.value)) for x in execparams])
self.launch(execparams)
# Verify the basic state of the component
self.assertNotEqual(self.comp, None)
self.assertEqual(self.comp.ref._non_existent(), False)
self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True)
self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier())
# Simulate regular component startup
# Verify that initialize nor configure throw errors
self.comp.initialize()
configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False)
self.comp.configure(configureProps)
# Validate that query returns all expected parameters
# Query of '[]' should return the following set of properties
expectedProps = []
expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True))
expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True))
props = self.comp.query([])
props = dict((x.id, any.from_any(x.value)) for x in props)
# Query may return more than expected, but not less
for expectedProp in expectedProps:
self.assertEquals(props.has_key(expectedProp.id), True)
# Verify that all expected ports are available
for port in self.scd.<API key>().get_ports().get_uses():
port_obj = self.comp.getPort(str(port.get_usesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True)
for port in self.scd.<API key>().get_ports().get_provides():
port_obj = self.comp.getPort(str(port.get_providesname()))
self.assertNotEqual(port_obj, None)
self.assertEqual(port_obj._non_existent(), False)
self.assertEqual(port_obj._is_a(port.get_repid()), True)
# Make sure start and stop can be called without throwing exceptions
self.comp.start()
self.comp.stop()
# Simulate regular component shutdown
self.comp.releaseObject()
# TODO Add additional tests here
# See:
# ossie.utils.bulkio.bulkio_helpers,
# ossie.utils.bluefile.bluefile_helpers
# for modules that will assist with testing components with BULKIO ports
if __name__ == "__main__":
ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations
|
#ifndef UI_ADDECGDIALOG_H
#define UI_ADDECGDIALOG_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Dialog
{
public:
QWidget *layoutWidget;
QHBoxLayout *hboxLayout;
QSpacerItem *horizontalSpacer_2;
QPushButton *okButton;
QSpacerItem *horizontalSpacer;
QPushButton *cancelButton;
QSpacerItem *horizontalSpacer_3;
QLabel *headLabel;
QLabel *nameLabel;
QCheckBox *checkBox;
QLabel *ECGlabel;
QComboBox *ECGBox;
QLineEdit *nameEdit;
void setupUi(QDialog *Dialog)
{
if (Dialog->objectName().isEmpty())
Dialog->setObjectName(QStringLiteral("Dialog"));
Dialog->resize(393, 233);
layoutWidget = new QWidget(Dialog);
layoutWidget->setObjectName(QStringLiteral("layoutWidget"));
layoutWidget->setGeometry(QRect(20, 180, 351, 33));
hboxLayout = new QHBoxLayout(layoutWidget);
hboxLayout->setSpacing(6);
hboxLayout->setObjectName(QStringLiteral("hboxLayout"));
hboxLayout->setContentsMargins(0, 0, 0, 0);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout->addItem(horizontalSpacer_2);
okButton = new QPushButton(layoutWidget);
okButton->setObjectName(QStringLiteral("okButton"));
hboxLayout->addWidget(okButton);
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout->addItem(horizontalSpacer);
cancelButton = new QPushButton(layoutWidget);
cancelButton->setObjectName(QStringLiteral("cancelButton"));
hboxLayout->addWidget(cancelButton);
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
hboxLayout->addItem(horizontalSpacer_3);
headLabel = new QLabel(Dialog);
headLabel->setObjectName(QStringLiteral("headLabel"));
headLabel->setGeometry(QRect(20, 20, 331, 16));
QFont font;
font.setPointSize(10);
font.setBold(true);
font.setWeight(75);
headLabel->setFont(font);
nameLabel = new QLabel(Dialog);
nameLabel->setObjectName(QStringLiteral("nameLabel"));
nameLabel->setGeometry(QRect(20, 70, 47, 13));
QFont font1;
font1.setBold(true);
font1.setWeight(75);
nameLabel->setFont(font1);
checkBox = new QCheckBox(Dialog);
checkBox->setObjectName(QStringLiteral("checkBox"));
checkBox->setGeometry(QRect(20, 110, 231, 17));
checkBox->setFont(font1);
ECGlabel = new QLabel(Dialog);
ECGlabel->setObjectName(QStringLiteral("ECGlabel"));
ECGlabel->setGeometry(QRect(20, 140, 81, 16));
ECGlabel->setFont(font1);
ECGBox = new QComboBox(Dialog);
ECGBox->setObjectName(QStringLiteral("ECGBox"));
ECGBox->setGeometry(QRect(100, 140, 271, 22));
ECGBox->setInsertPolicy(QComboBox::<API key>);
nameEdit = new QLineEdit(Dialog);
nameEdit->setObjectName(QStringLiteral("nameEdit"));
nameEdit->setGeometry(QRect(100, 70, 271, 20));
headLabel->raise();
nameLabel->raise();
checkBox->raise();
ECGlabel->raise();
ECGBox->raise();
nameEdit->raise();
layoutWidget->raise();
retranslateUi(Dialog);
QObject::connect(okButton, SIGNAL(clicked()), Dialog, SLOT(accept()));
QObject::connect(cancelButton, SIGNAL(clicked()), Dialog, SLOT(reject()));
QMetaObject::connectSlotsByName(Dialog);
} // setupUi
void retranslateUi(QDialog *Dialog)
{
Dialog->setWindowTitle(QApplication::translate("Dialog", "Add ECG Rhythm", 0));
okButton->setText(QApplication::translate("Dialog", "OK", 0));
cancelButton->setText(QApplication::translate("Dialog", "Cancel", 0));
headLabel->setText(QApplication::translate("Dialog", "Create a New ECG Rhythm", 0));
#ifndef QT_NO_TOOLTIP
nameLabel->setToolTip(QApplication::translate("Dialog", "The Name of the new ECG Rhythm", 0));
#endif // QT_NO_TOOLTIP
nameLabel->setText(QApplication::translate("Dialog", "Name", 0));
checkBox->setText(QApplication::translate("Dialog", "Copy parameters?", 0));
#ifndef QT_NO_TOOLTIP
ECGlabel->setToolTip(QApplication::translate("Dialog", "The set of predeefined rhythms", 0));
#endif // QT_NO_TOOLTIP
ECGlabel->setText(QApplication::translate("Dialog", "ECG Rythms", 0));
} // retranslateUi
};
namespace Ui {
class Dialog: public Ui_Dialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ADDECGDIALOG_H
|
#include "trayicon.h"
#include <QApplication>
#include <QMenu>
#include <QTimer>
#include <conf/addressgroup.h>
#include <conf/appgroup.h>
#include <conf/confmanager.h>
#include <conf/firewallconf.h>
#include <form/controls/mainwindow.h>
#include <fortsettings.h>
#include <manager/hotkeymanager.h>
#include <manager/windowmanager.h>
#include <user/iniuser.h>
#include <util/guiutil.h>
#include <util/iconcache.h>
#include "traycontroller.h"
namespace {
const char *const eventSingleClick = "singleClick";
const char *const eventDoubleClick = "doubleClick";
const char *const eventMiddleClick = "middleClick";
const char *const actionShowPrograms = "Programs";
const char *const actionShowOptions = "Options";
const char *const <API key> = "Statistics";
const char *const <API key> = "TrafficGraph";
const char *const <API key> = "FilterEnabled";
const char *const <API key> = "StopTraffic";
const char *const <API key> = "StopInetTraffic";
const char *const <API key> = "AutoAllowPrograms";
QString clickNameByType(TrayIcon::ClickType clickType)
{
switch (clickType) {
case TrayIcon::SingleClick:
return eventSingleClick;
case TrayIcon::DoubleClick:
return eventDoubleClick;
case TrayIcon::MiddleClick:
return eventMiddleClick;
default:
return QString();
}
}
QString actionNameByType(TrayIcon::ActionType actionType)
{
switch (actionType) {
case TrayIcon::ActionShowPrograms:
return actionShowPrograms;
case TrayIcon::ActionShowOptions:
return actionShowOptions;
case TrayIcon::<API key>:
return <API key>;
case TrayIcon::<API key>:
return <API key>;
case TrayIcon::<API key>:
return <API key>;
case TrayIcon::<API key>:
return <API key>;
case TrayIcon::<API key>:
return <API key>;
case TrayIcon::<API key>:
return <API key>;
default:
return QString();
}
}
TrayIcon::ActionType actionTypeByName(const QString &name)
{
if (name.isEmpty())
return TrayIcon::ActionNone;
if (name == actionShowPrograms)
return TrayIcon::ActionShowPrograms;
if (name == actionShowOptions)
return TrayIcon::ActionShowOptions;
if (name == <API key>)
return TrayIcon::<API key>;
if (name == <API key>)
return TrayIcon::<API key>;
if (name == <API key>)
return TrayIcon::<API key>;
if (name == <API key>)
return TrayIcon::<API key>;
if (name == <API key>)
return TrayIcon::<API key>;
if (name == <API key>)
return TrayIcon::<API key>;
return TrayIcon::ActionNone;
}
TrayIcon::ActionType <API key>(TrayIcon::ClickType clickType)
{
switch (clickType) {
case TrayIcon::SingleClick:
return TrayIcon::ActionShowPrograms;
case TrayIcon::DoubleClick:
return TrayIcon::ActionShowOptions;
case TrayIcon::MiddleClick:
return TrayIcon::<API key>;
default:
return TrayIcon::ActionNone;
}
}
void setActionCheckable(QAction *action, bool checked = false, const QObject *receiver = nullptr,
const char *member = nullptr)
{
action->setCheckable(true);
action->setChecked(checked);
if (receiver) {
QObject::connect(action, SIGNAL(toggled(bool)), receiver, member);
}
}
QAction *addAction(QWidget *widget, const QIcon &icon, const QString &text,
const QObject *receiver = nullptr, const char *member = nullptr, bool checkable = false,
bool checked = false)
{
auto action = new QAction(icon, text, widget);
if (receiver) {
QObject::connect(action, SIGNAL(triggered(bool)), receiver, member);
}
if (checkable) {
setActionCheckable(action, checked);
}
widget->addAction(action);
return action;
}
}
TrayIcon::TrayIcon(QObject *parent) :
QSystemTrayIcon(parent), m_trayTriggered(false), m_ctrl(new TrayController(this))
{
setupUi();
setupController();
connect(this, &QSystemTrayIcon::activated, this, &TrayIcon::onTrayActivated);
}
TrayIcon::~TrayIcon()
{
delete m_menu;
}
FortSettings *TrayIcon::settings() const
{
return ctrl()->settings();
}
ConfManager *TrayIcon::confManager() const
{
return ctrl()->confManager();
}
FirewallConf *TrayIcon::conf() const
{
return ctrl()->conf();
}
IniOptions *TrayIcon::ini() const
{
return ctrl()->ini();
}
IniUser *TrayIcon::iniUser() const
{
return ctrl()->iniUser();
}
HotKeyManager *TrayIcon::hotKeyManager() const
{
return ctrl()->hotKeyManager();
}
WindowManager *TrayIcon::windowManager() const
{
return ctrl()->windowManager();
}
void TrayIcon::onMouseClicked(TrayIcon::ClickType clickType)
{
QAction *action = m_clickActions[clickType];
if (action) {
action->trigger();
}
}
void TrayIcon::onTrayActivated(QSystemTrayIcon::ActivationReason reason)
{
switch (reason) {
case QSystemTrayIcon::Trigger:
m_trayTriggered = true;
QTimer::singleShot(QApplication::doubleClickInterval(), this, [&] {
if (m_trayTriggered) {
m_trayTriggered = false;
onMouseClicked(SingleClick);
}
});
break;
case QSystemTrayIcon::DoubleClick:
if (m_trayTriggered) {
m_trayTriggered = false;
onMouseClicked(DoubleClick);
}
break;
case QSystemTrayIcon::MiddleClick:
m_trayTriggered = false;
onMouseClicked(MiddleClick);
break;
case QSystemTrayIcon::Context:
m_trayTriggered = false;
showTrayMenu(QCursor::pos());
break;
default:
break;
}
}
void TrayIcon::updateTrayIcon(bool alerted)
{
const auto icon = alerted ? GuiUtil::overlayIcon(":/icons/sheild-96.png", ":/icons/error.png")
: IconCache::icon(":/icons/sheild-96.png");
this->setIcon(icon);
}
void TrayIcon::showTrayMenu(const QPoint &pos)
{
m_menu->popup(pos);
}
void TrayIcon::updateTrayMenu(bool onlyFlags)
{
if (!onlyFlags) {
<API key>();
}
updateTrayMenuFlags();
updateHotKeys();
}
void TrayIcon::setupController()
{
connect(windowManager(), &WindowManager::optWindowChanged, this,
&TrayIcon::updateTrayMenuFlags);
connect(windowManager(), &WindowManager::graphWindowChanged, m_graphAction,
&QAction::setChecked);
connect(settings(), &FortSettings::<API key>, this,
&TrayIcon::updateTrayMenuFlags);
connect(ctrl(), &TrayController::retranslateUi, this, &TrayIcon::retranslateUi);
retranslateUi();
}
void TrayIcon::retranslateUi()
{
m_programsAction->setText(tr("Programs"));
m_optionsAction->setText(tr("Options"));
m_statisticsAction->setText(tr("Statistics"));
m_zonesAction->setText(tr("Zones"));
m_graphAction->setText(tr("Traffic Graph"));
<API key>->setText(tr("Filter Enabled"));
m_stopTrafficAction->setText(tr("Stop Traffic"));
<API key>->setText(tr("Stop Internet Traffic"));
<API key>->setText(tr("Auto-Allow New Programs"));
m_quitAction->setText(tr("Quit"));
}
void TrayIcon::setupUi()
{
this->setToolTip(QApplication::<API key>());
setupTrayMenu();
updateTrayMenu();
updateTrayIcon();
updateClickActions();
}
void TrayIcon::setupTrayMenu()
{
m_menu = new QMenu();
m_programsAction = addAction(m_menu, IconCache::icon(":/icons/application.png"), QString(),
windowManager(), SLOT(showProgramsWindow()));
addHotKey(m_programsAction, iniUser()->hotKeyPrograms());
m_optionsAction = addAction(m_menu, IconCache::icon(":/icons/cog.png"), QString(),
windowManager(), SLOT(showOptionsWindow()));
addHotKey(m_optionsAction, iniUser()->hotKeyOptions());
m_statisticsAction = addAction(m_menu, IconCache::icon(":/icons/chart_bar.png"), QString(),
windowManager(), SLOT(<API key>()));
addHotKey(m_statisticsAction, iniUser()->hotKeyStatistics());
m_graphAction = addAction(m_menu, IconCache::icon(":/icons/action_log.png"), QString(),
windowManager(), SLOT(switchGraphWindow()), true, !!windowManager()->graphWindow());
addHotKey(m_graphAction, iniUser()->hotKeyGraph());
m_zonesAction = addAction(m_menu, IconCache::icon(":/icons/ip_class.png"), QString(),
windowManager(), SLOT(showZonesWindow()));
addHotKey(m_zonesAction, iniUser()->hotKeyZones());
m_menu->addSeparator();
<API key> =
addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
addHotKey(<API key>, iniUser()->hotKeyFilter());
m_stopTrafficAction =
addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
addHotKey(m_stopTrafficAction, iniUser()->hotKeyStopTraffic());
<API key> =
addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
addHotKey(<API key>, iniUser()-><API key>());
<API key> =
addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
addHotKey(<API key>, iniUser()->hotKeyAllowAllNew());
m_menu->addSeparator();
for (int i = 0; i < MAX_APP_GROUP_COUNT; ++i) {
QAction *a = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true);
if (i < 12) {
const QString shortcutText =
iniUser()-><API key>() + "+F" + QString::number(i + 1);
addHotKey(a, shortcutText);
}
m_appGroupActions.append(a);
}
m_menu->addSeparator();
m_quitAction = addAction(m_menu, QIcon(), tr("Quit"), this, SLOT(quitProgram()));
addHotKey(m_quitAction, iniUser()->hotKeyQuit());
}
void TrayIcon::updateTrayMenuFlags()
{
const bool editEnabled = (!settings()->isPasswordRequired() && !windowManager()->optWindow());
<API key>->setEnabled(editEnabled);
m_stopTrafficAction->setEnabled(editEnabled);
<API key>->setEnabled(editEnabled);
<API key>->setEnabled(editEnabled);
<API key>->setChecked(conf()->filterEnabled());
m_stopTrafficAction->setChecked(conf()->stopTraffic());
<API key>->setChecked(conf()->stopInetTraffic());
<API key>->setChecked(conf()->allowAllNew());
int appGroupIndex = 0;
for (QAction *action : qAsConst(m_appGroupActions)) {
if (!action->isVisible())
break;
const bool appGroupEnabled = conf()->appGroupEnabled(appGroupIndex++);
action->setEnabled(editEnabled);
action->setChecked(appGroupEnabled);
}
}
void TrayIcon::<API key>()
{
const int appGroupsCount = conf()->appGroups().count();
for (int i = 0; i < MAX_APP_GROUP_COUNT; ++i) {
QAction *action = m_appGroupActions.at(i);
QString menuLabel;
bool visible = false;
if (i < appGroupsCount) {
const AppGroup *appGroup = conf()->appGroups().at(i);
menuLabel = appGroup->menuLabel();
visible = true;
}
action->setText(menuLabel);
action->setVisible(visible);
action->setEnabled(visible);
}
}
void TrayIcon::saveTrayFlags()
{
conf()->setFilterEnabled(<API key>->isChecked());
conf()->setStopTraffic(m_stopTrafficAction->isChecked());
conf()->setStopInetTraffic(<API key>->isChecked());
conf()->setAllowAllNew(<API key>->isChecked());
int i = 0;
for (AppGroup *appGroup : conf()->appGroups()) {
const QAction *action = m_appGroupActions.at(i++);
appGroup->setEnabled(action->isChecked());
}
confManager()->saveFlags();
}
void TrayIcon::switchTrayFlag(bool checked)
{
if (iniUser()->confirmTrayFlags()) {
const auto action = qobject_cast<QAction *>(sender());
Q_ASSERT(action);
if (!windowManager()->showQuestionBox(
tr("Are you sure to switch the \"%1\"?").arg(action->text()))) {
action->setChecked(!checked);
return;
}
}
saveTrayFlags();
}
void TrayIcon::quitProgram()
{
if (iniUser()->confirmQuit()) {
if (!windowManager()->showQuestionBox(tr("Are you sure you want to quit the program?")))
return;
}
windowManager()->quitByCheckPassword();
}
void TrayIcon::addHotKey(QAction *action, const QString &shortcutText)
{
if (shortcutText.isEmpty())
return;
const QKeySequence shortcut = QKeySequence::fromString(shortcutText);
hotKeyManager()->addAction(action, shortcut);
}
void TrayIcon::updateHotKeys()
{
hotKeyManager()->setEnabled(iniUser()->hotKeyEnabled());
}
void TrayIcon::removeHotKeys()
{
hotKeyManager()->removeActions();
}
TrayIcon::ActionType TrayIcon::<API key>(ClickType clickType) const
{
const QString eventName = clickNameByType(clickType);
const QString actionName = iniUser()->trayAction(eventName);
const ActionType actionType = actionTypeByName(actionName);
return (actionType != ActionNone) ? actionType : <API key>(clickType);
}
void TrayIcon::<API key>(ClickType clickType, ActionType actionType)
{
const QString eventName = clickNameByType(clickType);
const QString actionName = actionNameByType(actionType);
iniUser()->setTrayAction(eventName, actionName);
updateClickActions();
}
void TrayIcon::updateClickActions()
{
m_clickActions[SingleClick] = clickActionFromIni(SingleClick);
m_clickActions[DoubleClick] = clickActionFromIni(DoubleClick);
m_clickActions[MiddleClick] = clickActionFromIni(MiddleClick);
}
QAction *TrayIcon::clickActionFromIni(ClickType clickType) const
{
const ActionType actionType = <API key>(clickType);
return clickActionByType(actionType);
}
QAction *TrayIcon::clickActionByType(ActionType actionType) const
{
switch (actionType) {
case TrayIcon::ActionShowPrograms:
return m_programsAction;
case TrayIcon::ActionShowOptions:
return m_optionsAction;
case TrayIcon::<API key>:
return m_statisticsAction;
case TrayIcon::<API key>:
return m_graphAction;
case TrayIcon::<API key>:
return <API key>;
case TrayIcon::<API key>:
return m_stopTrafficAction;
case TrayIcon::<API key>:
return <API key>;
case TrayIcon::<API key>:
return <API key>;
}
return nullptr;
}
|
package at.ltd.tools.fw.peer2peerFirewall.backend.entities.comparator;
@FunctionalInterface
public interface ComparatorLambda<T> {
int comp(T t1, T t2);
}
|
// Obdi - a REST interface and GUI for deploying software
// This program is free software: you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package main
import (
"encoding/json"
"fmt"
"net"
"net/rpc"
"os"
)
type PostedData struct {
Hostname string
}
// GO RPC PLUGIN
func (t *Plugin) GetRequest(args *Args, response *[]byte) error {
// List all keys
if len(args.QueryString["env_id"]) == 0 {
ReturnError("'env_id' must be set", response)
return nil
}
sa := ScriptArgs{
ScriptName: "saltkey-showkeys.sh",
CmdArgs: "",
EnvVars: "",
EnvCapDesc: "SALT_WORKER",
Type: 2,
}
var jobid int64
var err error
if jobid, err = t.RunScript(args, sa, response); err != nil {
// RunScript wrote the error
return nil
}
reply := Reply{jobid, "", SUCCESS, ""}
jsondata, err := json.Marshal(reply)
if err != nil {
ReturnError("Marshal error: "+err.Error(), response)
return nil
}
*response = jsondata
return nil
}
func (t *Plugin) PostRequest(args *Args, response *[]byte) error {
// Check for required query string entries
if len(args.QueryString["hostname"]) == 0 {
ReturnError("'type' must be set", response)
return nil
}
if len(args.QueryString["type"]) == 0 {
ReturnError("'type' must be set", response)
return nil
}
if len(args.QueryString["env_id"]) == 0 {
ReturnError("'env_id' must be set", response)
return nil
}
// Get the ScriptId from the scripts table for:
scriptName := ""
if args.QueryString["type"][0] == "accept" {
scriptName = "saltkey-acceptkeys.sh"
} else {
scriptName = "saltkey-rejectkeys.sh"
}
var jobid int64
sa := ScriptArgs{
ScriptName: scriptName,
CmdArgs: args.QueryString["hostname"][0],
EnvVars: "",
EnvCapDesc: "SALT_WORKER",
Type: 2,
}
var err error
if jobid, err = t.RunScript(args, sa, response); err != nil {
// RunScript wrote the error
return nil
}
reply := Reply{jobid, "", SUCCESS, ""}
jsondata, err := json.Marshal(reply)
if err != nil {
ReturnError("Marshal error: "+err.Error(), response)
return nil
}
*response = jsondata
return nil
}
func (t *Plugin) DeleteRequest(args *Args, response *[]byte) error {
// Check for required query string entries
if len(args.QueryString["env_id"]) == 0 {
ReturnError("'env_id' must be set", response)
return nil
}
var jobid int64
sa := ScriptArgs{
ScriptName: "saltkey-deletekeys.sh",
CmdArgs: args.PathParams["id"],
EnvVars: "",
EnvCapDesc: "SALT_WORKER",
Type: 2,
}
var err error
if jobid, err = t.RunScript(args, sa, response); err != nil {
// RunScript wrote the error
return nil
}
reply := Reply{jobid, "", SUCCESS, ""}
jsondata, err := json.Marshal(reply)
if err != nil {
ReturnError("Marshal error: "+err.Error(), response)
return nil
}
*response = jsondata
return nil
}
func (t *Plugin) HandleRequest(args *Args, response *[]byte) error {
// All plugins must have this.
if len(args.QueryType) > 0 {
switch args.QueryType {
case "GET":
t.GetRequest(args, response)
return nil
case "POST":
t.PostRequest(args, response)
return nil
case "DELETE":
t.DeleteRequest(args, response)
return nil
}
ReturnError("Internal error: Invalid HTTP request type for this plugin "+
args.QueryType, response)
return nil
} else {
ReturnError("Internal error: HTTP request type was not set", response)
return nil
}
}
func main() {
//logit("Plugin starting")
plugin := new(Plugin)
rpc.Register(plugin)
listener, err := net.Listen("tcp", ":"+os.Args[1])
if err != nil {
txt := fmt.Sprintf("Listen error. ", err)
logit(txt)
}
//logit("Plugin listening on port " + os.Args[1])
if conn, err := listener.Accept(); err != nil {
txt := fmt.Sprintf("Accept error. ", err)
logit(txt)
} else {
//logit("New connection established")
rpc.ServeConn(conn)
}
}
|
package com.shumz.think.ex004;
public class ExFour03 {
public ExFour03() {
System.out.println("An instance of ExFour03 was created...");
}
public static void main(String[] args) {
new ExFour03();
}
}
|
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[5];
atomic_int atom_1_r1_1;
void *t0(void *arg){
label_1:;
<API key>(&vars[0], 2, <API key>);
<API key>(&vars[1], 1, <API key>);
return NULL;
}
void *t1(void *arg){
label_2:;
int v2_r1 = <API key>(&vars[1], <API key>);
int v3_r3 = v2_r1 ^ v2_r1;
int v6_r4 = <API key>(&vars[2+v3_r3], <API key>);
int v7_r6 = v6_r4 ^ v6_r4;
<API key>(&vars[3+v7_r6], 1, <API key>);
int v9_r9 = <API key>(&vars[3], <API key>);
int v10_r10 = v9_r9 ^ v9_r9;
<API key>(&vars[4+v10_r10], 1, <API key>);
int v12_r13 = <API key>(&vars[4], <API key>);
int v13_cmpeq = (v12_r13 == v12_r13);
if (v13_cmpeq) goto lbl_LC00; else goto lbl_LC00;
lbl_LC00:;
<API key>(&vars[0], 1, <API key>);
int v18 = (v2_r1 == 1);
<API key>(&atom_1_r1_1, v18, <API key>);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[3], 0);
atomic_init(&vars[1], 0);
atomic_init(&vars[0], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[4], 0);
atomic_init(&atom_1_r1_1, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v14 = <API key>(&vars[0], <API key>);
int v15 = (v14 == 2);
int v16 = <API key>(&atom_1_r1_1, <API key>);
int v17_conj = v15 & v16;
if (v17_conj == 1) assert(0);
return 0;
}
|
package TFC.Handlers.Client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.event.<API key>;
import net.minecraftforge.client.event.<API key>.ElementType;
import net.minecraftforge.event.ForgeSubscribe;
import org.lwjgl.opengl.GL11;
import TFC.Core.TFC_Climate;
import TFC.Core.TFC_Settings;
import TFC.Core.Player.PlayerManagerTFC;
import TFC.Core.Player.TFC_PlayerClient;
import TFC.Food.FoodStatsTFC;
import TFC.Items.Tools.ItemChisel;
import TFC.Items.Tools.ItemCustomHoe;
public class <API key>
{
@ForgeSubscribe
public void render(<API key>.Pre event)
{
if(event.type == ElementType.HEALTH || event.type == ElementType.FOOD)
{
event.setCanceled(true);
}
}
@ForgeSubscribe
public void render(<API key>.Post event)
{
if(event.type == ElementType.HEALTH || event.type == ElementType.FOOD)
{
event.setCanceled(true);
}
ScaledResolution sr = event.resolution;
int healthRowHeight = sr.getScaledHeight() - 39;
int armorRowHeight = healthRowHeight - 10;
TFC_PlayerClient playerclient = ((TFC.Core.Player.TFC_PlayerClient)Minecraft.getMinecraft().thePlayer.getPlayerBase("TFC Player Client"));
if(playerclient != null)
{
//Draw Health
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
Minecraft.getMinecraft().renderEngine.bindTexture("/bioxx/icons.png");
this.<API key>(sr.getScaledWidth() / 2-91, healthRowHeight, 0, 0, 90, 10);
float maxHealth = playerclient.getMaxHealth();
float percentHealth = Minecraft.getMinecraft().thePlayer.getHealth()/maxHealth;
this.<API key>(sr.getScaledWidth() / 2-91, healthRowHeight, 0, 9, (int) (90*percentHealth), 9);
//Draw Food and Water
FoodStatsTFC foodstats = playerclient.getFoodStatsTFC();
int foodLevel = foodstats.getFoodLevel();
int preFoodLevel = foodstats.getPrevFoodLevel();
float waterLevel = foodstats.waterLevel;
float percentFood = foodLevel/100f;
float percentWater = waterLevel/foodstats.getMaxWater(Minecraft.getMinecraft().thePlayer);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.<API key>(sr.getScaledWidth() / 2, healthRowHeight, 0, 18, 90, 5);
if(playerclient.<API key>)
{
float percentFood2 = Math.min(percentFood + playerclient.<API key>/100f, 1);
GL11.glColor4f(0.0F, 0.6F, 0.0F, 0.3F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.<API key>(sr.getScaledWidth() / 2, healthRowHeight, 0, 23, (int) (90*(percentFood2)), 5);
}
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
//GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png"));
this.<API key>(sr.getScaledWidth() / 2, healthRowHeight, 0, 23, (int) (90*percentFood), 5);
this.<API key>(sr.getScaledWidth() / 2, healthRowHeight+5, 0, 28, 90, 5);
this.<API key>(sr.getScaledWidth() / 2, healthRowHeight+5, 0, 33, (int) (90*percentWater), 5);
//Render Tool Mode
if(Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem() != null &&
Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem().getItem() instanceof ItemCustomHoe)
{
int mode = PlayerManagerTFC.getInstance().getClientPlayer().hoeMode;
this.<API key>(sr.getScaledWidth() / 2 + 95, sr.getScaledHeight() - 21, 0+(20*mode), 38, 20, 20);
}
else if(Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem() != null &&
Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem().getItem() instanceof ItemChisel)
{
int mode = PlayerManagerTFC.getInstance().getClientPlayer().ChiselMode;
this.<API key>(sr.getScaledWidth() / 2 + 95, sr.getScaledHeight() - 21, 0+(20*mode), 58, 20, 20);
}
}
Minecraft.getMinecraft().renderEngine.resetBoundTexture();
}
@ForgeSubscribe
public void renderText(<API key>.Text event)
{
if(Minecraft.getMinecraft().gameSettings.showDebugInfo || TFC_Settings.enableDebugMode)
{
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
int xCoord = (int)player.posX;
int yCoord = (int)player.posY;
int zCoord = (int)player.posZ;
event.left.add(String.format("rain: %.0f, temp: %.2f, evt: %.3f", new Object[] {
TFC_Climate.getRainfall(xCoord, yCoord, zCoord),
TFC_Climate.<API key>(xCoord, yCoord, zCoord),
TFC_Climate.manager.getEVTLayerAt(xCoord, zCoord).floatdata1}));
event.left.add("Health: " + player.getHealth());
}
}
public void <API key>(int par1, int par2, int par3, int par4, int par5, int par6)
{
float f = 0.00390625F;
float f1 = 0.00390625F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(par1 + 0, par2 + par6, 0.0, (par3 + 0) * f, (par4 + par6) * f1);
tessellator.addVertexWithUV(par1 + par5, par2 + par6, 0.0, (par3 + par5) * f, (par4 + par6) * f1);
tessellator.addVertexWithUV(par1 + par5, par2 + 0, 0.0, (par3 + par5) * f, (par4 + 0) * f1);
tessellator.addVertexWithUV(par1 + 0, par2 + 0, 0.0, (par3 + 0) * f, (par4 + 0) * f1);
tessellator.draw();
}
}
|
namespace ContaLibre.Areas.HelpPage.ModelDescriptions
{
public class <API key>
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
}
|
var path = require('path')
module.exports = {
// Webpack aliases
aliases: {
quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'),
src: path.resolve(__dirname, '../src'),
assets: path.resolve(__dirname, '../src/assets'),
components: path.resolve(__dirname, '../src/components')
},
// Progress Bar Webpack plugin format
// https://github.com/clessg/<API key>#options
progressFormat: ' [:bar] ' + ':percent'.bold + ' (:msg)',
// Default theme to build with ('ios' or 'mat')
defaultTheme: 'mat',
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
publicPath: '',
productionSourceMap: false,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev <API key>
productionGzip: false,
<API key>: ['js', 'css']
},
dev: {
env: require('./dev.env'),
cssSourceMap: true,
// auto open browser or not
openBrowser: true,
publicPath: '/',
port: 8081,
// If for example you are using Quasar Play
// to generate a QR code then on each dev (re)compilation
// you need to avoid clearing out the console, so set this
// to "false", otherwise you can set it to "true" to always
// have only the messages regarding your last (re)compilation.
<API key>: false,
// Proxy your API if using any.
// Also see /build/script.dev.js and search for "proxy api requests"
proxyTable: {}
}
}
|
// This file is part of the aMule Project.
// Any parts of this program derived from the xMule, lMule or eMule project,
// respective authors.
// This program is free software; you can redistribute it and/or modify
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#include <wx/wx.h>
#include <wx/mstream.h>
#include <wx/tokenzr.h>
#include "updownclient.h" // Needed for CUpDownClient
#include "SharedFileList.h" // Needed for CSharedFileList
#include <protocol/Protocols.h>
#include <protocol/ed2k/Client2Client/TCP.h>
#include <protocol/ed2k/ClientSoftware.h>
#include <protocol/kad/Client2Client/UDP.h>
#include <protocol/kad2/Constants.h>
#include <protocol/kad2/Client2Client/TCP.h>
#include <protocol/kad2/Client2Client/UDP.h>
#include <common/ClientVersion.h>
#include <tags/ClientTags.h>
#include <zlib.h> // Needed for inflateEnd
#include <common/Format.h> // Needed for CFormat
#include "SearchList.h" // Needed for CSearchList
#include "DownloadQueue.h" // Needed for CDownloadQueue
#include "UploadQueue.h" // Needed for CUploadQueue
#include "IPFilter.h" // Needed for CIPFilter
#include "ServerConnect.h" // Needed for CServerConnect
#include "ClientCredits.h" // Needed for CClientCredits
#include "ClientCreditsList.h" // Needed for CClientCreditsList
#include "Server.h" // Needed for CServer
#include "Preferences.h" // Needed for CPreferences
#include "MemFile.h" // Needed for CMemFile
#include "Packet.h" // Needed for CPacket
#include "Friend.h" // Needed for CFriend
#include "ClientList.h" // Needed for CClientList
#ifndef AMULE_DAEMON
#include "amuleDlg.h" // Needed for CamuleDlg
#include "CaptchaDialog.h" // Needed for CCaptchaDialog
#include "CaptchaGenerator.h"
#include "ChatWnd.h" // Needed for CChatWnd
#endif
#include "amule.h" // Needed for theApp
#include "PartFile.h" // Needed for CPartFile
#include "ClientTCPSocket.h" // Needed for CClientTCPSocket
#include "ListenSocket.h" // Needed for CListenSocket
#include "FriendList.h" // Needed for CFriendList
#include "Statistics.h" // Needed for theStats
#include "ClientUDPSocket.h"
#include "Logger.h"
#include "DataToText.h" // Needed for GetSoftName()
#include "GuiEvents.h" // Needed for Notify_
#include "ServerList.h" // For CServerList
#include "kademlia/kademlia/Kademlia.h"
#include "kademlia/kademlia/Prefs.h"
#include "kademlia/kademlia/Search.h"
#include "kademlia/kademlia/UDPFirewallTester.h"
#include "kademlia/routing/RoutingZone.h"
//#define __PACKET_DEBUG__
// some client testing variables
static wxString crash_name = wxT("[Invalid User Name]");
static wxString empty_name = wxT("[Empty User Name]");
// members of CUpDownClient
// which are used by down and uploading functions
CUpDownClient::CUpDownClient(CClientTCPSocket* sender)
{
#ifdef __DEBUG__
m_socket = NULL;
SetSocket(sender);
#else
m_socket = sender;
#endif
Init();
}
CUpDownClient::CUpDownClient(uint16 in_port, uint32 in_userid, uint32 in_serverip, uint16 in_serverport, CPartFile* in_reqfile, bool ed2kID, bool checkfriend)
{
m_socket = NULL;
Init();
m_nUserPort = in_port;
if(ed2kID && !IsLowID(in_userid)) {
SetUserIDHybrid( <API key>(in_userid) );
} else {
SetUserIDHybrid( in_userid);
}
//If highID and ED2K source, incoming ID and IP are equal..
//If highID and Kad source, incoming IP needs swap for the IP
if (!HasLowID()) {
if (ed2kID) {
m_nConnectIP = in_userid;
} else {
m_nConnectIP = <API key>(in_userid);
}
// Will be on right endianess now
m_FullUserIP = m_nConnectIP;
}
m_dwServerIP = in_serverip;
m_nServerPort = in_serverport;
SetRequestFile( in_reqfile );
ReGetClientSoft();
if (checkfriend) {
if ((m_Friend = theApp->friendlist->FindFriend(CMD4Hash(), m_dwUserIP, m_nUserPort)) != NULL){
m_Friend->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::CUpDownClient m_Friend->LinkClient")));
} else{
// avoid that an unwanted client instance keeps a friend slot
m_bFriendSlot = false;
}
}
}
void CUpDownClient::Init()
{
m_linked = 0;
#ifdef <API key>
m_linkedDebug = false;
#endif
m_bAddNextConnect = false;
credits = NULL;
m_byChatstate = MS_NONE;
m_nKadState = KS_NONE;
m_nChatCaptchaState = CA_NONE;
m_cShowDR = 0;
m_reqfile = NULL; // No file required yet
m_nTransferredUp = 0;
m_cSendblock = 0;
m_cAsked = 0;
msReceivedPrev = 0;
kBpsDown = 0.0;
bytesReceivedCycle = 0;
m_nServerPort = 0;
<API key> = 0;
m_dwLastUpRequest = 0;
m_bEmuleProtocol = false;
m_bCompleteSource = false;
m_bFriendSlot = false;
m_bCommentDirty = false;
m_bReaskPending = false;
m_bUDPPending = false;
m_nUserPort = 0;
m_nPartCount = 0;
m_dwLastAskedTime = 0;
m_nDownloadState = DS_NONE;
m_dwUploadTime = 0;
m_nTransferredDown = 0;
m_nUploadState = US_NONE;
<API key> = 0;
m_bUnicodeSupport = false;
<API key> = 0;
<API key> = 0;
<API key> = 0;
m_nUpDatarate = 0;
<API key> = 0;
m_nRemoteQueueRank = 0;
<API key> = 0;
<API key> = 0;
<API key> = 0;
<API key> = 0;
m_SecureIdentState = IS_UNAVAILABLE;
m_dwLastSignatureIP = 0;
<API key> = IP_NONE;
m_bIsHybrid = false;
m_bIsML = false;
m_Friend = NULL;
m_iRating = 0;
m_nCurSessionUp = 0;
m_clientSoft=SO_UNKNOWN;
m_bRemoteQueueFull = false;
m_HasValidHash = false;
SetWaitStartTime();
<API key> = 0;
<API key> = 0;
m_lastPartAsked = 0xffff;
<API key>= 0;
m_waitingPosition = 0;
m_score = 0;
<API key> = 0;
<API key> = false;
<API key> = 0;
m_Aggressiveness = 0;
m_LastFileRequest = 0;
m_clientState = CS_NEW;
<API key>();
m_pReqFileAICHHash = NULL;
m_fSupportsAICH = 0;
m_fAICHRequested = 0;
<API key> = 0;
m_fExtMultiPacket = 0;
m_fIsSpammer = 0;
m_dwUserIP = 0;
m_nConnectIP = 0;
m_dwServerIP = 0;
m_fNeedOurPublicIP = false;
m_bHashsetRequested = false;
<API key> = 0;
m_uploadingfile = NULL;
m_OSInfo_sent = false;
/* Kad stuff */
SetBuddyID(NULL);
m_nBuddyIP = 0;
m_nBuddyPort = 0;
m_nUserIDHybrid = 0;
m_nSourceFrom = SF_NONE;
if (m_socket) {
SetIP(m_socket->GetPeerInt());
} else {
SetIP(0);
}
/* Statistics */
m_lastClientSoft = (uint32)(-1);
m_lastClientVersion = 0;
/* Creation time (for buddies timeout) */
m_nCreationTime = ::GetTickCount();
m_MaxBlockRequests = <API key>; // Safe starting amount
m_last_block_start = 0;
m_lastaverage = 0;
<API key>();
<API key> = 0;
<API key> = 0;
<API key> = 0;
<API key> = 0;
m_fSupportsCaptcha = 0;
<API key> = 0;
<API key> = 0;
<API key> = false;
m_cCaptchasSent = 0;
m_cMessagesReceived = 0;
m_cMessagesSent = 0;
}
CUpDownClient::~CUpDownClient()
{
#ifdef __DEBUG__
if (!connection_reason.IsEmpty()) {
AddDebugLogLineN(logClient, wxT("Client to check for ") + connection_reason + wxT(" was deleted without connection."));
}
#endif
if (m_lastClientSoft == SO_UNKNOWN) {
theStats::RemoveUnknownClient();
} else if (m_lastClientSoft != (uint32)(-1)) {
theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
}
// Indicate that we are not anymore on stats
m_lastClientSoft = (uint32)(-1);
// The socket should have been removed in Safe_Delete, but it
// doesn't hurt to have an extra check.
if (m_socket) {
m_socket->Safe_Delete();
// Paranoia
SetSocket(NULL);
}
<API key>();
<API key>();
DeleteContents(<API key>);
// Allow detection of deleted clients that didn't go through Safe_Delete
m_clientState = CS_DYING;
}
void CUpDownClient::<API key>()
{
m_nUDPPort = 0;
m_byUDPVer = 0;
m_byDataCompVer = 0;
m_byEmuleVersion = 0;
<API key> = 0;
<API key> = 0;
<API key> = 0;
<API key> = 0;
m_nKadPort = 0;
m_bySupportSecIdent = 0;
m_bSupportsPreview = 0;
m_nClientVersion = 0;
<API key> = 0;
m_bMultiPacket = 0;
m_fOsInfoSupport = 0;
<API key> = 0;
SecIdentSupRec = 0;
m_byKadVersion = 0;
<API key> = 0;
<API key> = 0;
<API key> = 0;
<API key> = 0;
m_fSupportsCaptcha = 0;
<API key> = 0;
m_bIsHybrid = false;
m_bIsML = false;
<API key> = true; // that's a sensible default to assume until we get the real value
m_bUnicodeSupport = false;
}
bool CUpDownClient::ProcessHelloPacket(const byte* pachPacket, uint32 nSize)
{
const CMemFile data(pachPacket,nSize);
uint8 hashsize = data.ReadUInt8();
if ( 16 != hashsize ) {
/*
* Hint: We can not accept other sizes here because:
* - the magic number is spread all over the source
* - the answer packet lacks the size field
*/
throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented"));
}
// eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer
<API key>();
return <API key>(data);
}
void CUpDownClient::Safe_Delete()
{
// Because we are delaying the deletion, we might end up trying to delete
// it twice, however, this is normal and shouldn't trigger any failures
if ( m_clientState == CS_DYING ) {
return;
}
// If called from background, post an event to process it in main thread
if (!wxThread::IsMain()) {
<API key>(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete <API key>")));
return;
}
m_clientState = CS_DYING;
// Make sure client doesn't get deleted until this method is finished
CClientRef ref(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete reflocker")));
// Close the socket to avoid any more connections and related events
if ( m_socket ) {
m_socket->Safe_Delete();
// Paranoia
SetSocket(NULL);
}
// Remove the client from the clientlist if we still have it
if ( theApp->clientlist ) {
theApp->clientlist->RemoveClient( this );
}
// Doing what RemoveClient used to do. Just to be sure...
if (theApp->uploadqueue) {
theApp->uploadqueue-><API key>(this);
theApp->uploadqueue-><API key>(this);
}
if (theApp->downloadqueue) {
theApp->downloadqueue->RemoveSource(this);
}
// For security, remove it from the lists unconditionally.
<API key>(ECID(), (CKnownFile*)NULL);
<API key>(ECID(), (CPartFile*)NULL);
if (IsAICHReqPending()){
m_fAICHRequested = FALSE;
CAICHHashSet::<API key>(this);
}
if (m_Friend) {
m_Friend->UnLinkClient(); // this notifies
m_Friend = NULL;
}
if (m_iRating>0 || !m_strComment.IsEmpty()) {
m_iRating = 0;
m_strComment.Clear();
if (m_reqfile) {
m_reqfile-><API key>();
}
}
// Ensure that source-counts gets updated in case
// of a source not on the download-queue
SetRequestFile( NULL );
SetUploadFileID(NULL);
delete m_pReqFileAICHHash;
m_pReqFileAICHHash = NULL;
#ifdef <API key>
if (m_linked > 1) {
AddLogLineC(CFormat(wxT("Client %d still linked in %d places: %s")) % ECID() % (m_linked - 1) % GetLinkedFrom());
m_linkedDebug = true;
}
#endif
}
bool CUpDownClient::ProcessHelloAnswer(const byte* pachPacket, uint32 nSize)
{
const CMemFile data(pachPacket,nSize);
bool bIsMule = <API key>(data);
<API key> = false;
return bIsMule;
}
bool CUpDownClient::<API key>(const CMemFile& data)
{
uint32 dwEmuleTags = 0;
CMD4Hash hash = data.ReadHash();
SetUserHash( hash );
SetUserIDHybrid( data.ReadUInt32() );
uint16 nUserPort = data.ReadUInt16(); // hmm clientport is sent twice - why?
uint32 tagcount = data.ReadUInt32();
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, true);
switch(temptag.GetNameID()){
case CT_NAME:
m_Username = temptag.GetStr();
break;
case CT_VERSION:
m_nClientVersion = temptag.GetInt();
break;
case ET_MOD_VERSION:
if (temptag.IsStr()) {
m_strModVersion = temptag.GetStr();
} else if (temptag.IsInt()) {
m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt();
} else {
m_strModVersion = wxT("ModID=<Unknown>");
}
break;
case CT_PORT:
nUserPort = temptag.GetInt();
break;
case CT_EMULE_UDPPORTS:
// 16 KAD Port
// 16 UDP Port
SetKadPort((temptag.GetInt() >> 16) & 0xFFFF);
m_nUDPPort = temptag.GetInt() & 0xFFFF;
dwEmuleTags |= 1;
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule ports UDP=%i KAD=%i")) % m_nUDPPort % m_nKadPort);
#endif
break;
case CT_EMULE_BUDDYIP:
// 32 BUDDY IP
m_nBuddyIP = temptag.GetInt();
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyIP=%u (%s)")) % m_nBuddyIP % Uint32toStringIP(m_nBuddyIP));
#endif
break;
case CT_EMULE_BUDDYUDP:
// 16 --Reserved for future use--
// 16 BUDDY Port
m_nBuddyPort = (uint16)temptag.GetInt();
#ifdef __PACKET_DEBUG__
AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyPort=%u")) % m_nBuddyPort);
#endif
break;
case <API key>: {
// 3 AICH Version (0 = not supported)
// 1 Unicode
// 4 UDP version
// 4 Data compression version
// 4 Secure Ident
// 4 Source Exchange
// 4 Ext. Requests
// 4 Comments
// 1 PeerCache supported
// 1 No 'View Shared Files' supported
// 1 MultiPacket
// 1 Preview
uint32 flags = temptag.GetInt();
m_fSupportsAICH = (flags >> (4*7+1)) & 0x07;
m_bUnicodeSupport = (flags >> 4*7) & 0x01;
m_byUDPVer = (flags >> 4*6) & 0x0f;
m_byDataCompVer = (flags >> 4*5) & 0x0f;
m_bySupportSecIdent = (flags >> 4*4) & 0x0f;
<API key> = (flags >> 4*3) & 0x0f;
<API key> = (flags >> 4*2) & 0x0f;
<API key> = (flags >> 4*1) & 0x0f;
<API key> = (flags >> 1*2) & 0x01;
m_bMultiPacket = (flags >> 1*1) & 0x01;
m_fSupportsPreview = (flags >> 1*0) & 0x01;
dwEmuleTags |= 2;
#ifdef __PACKET_DEBUG__
AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options:"));
AddLogLineNS(CFormat(wxT("m_byUDPVer = %i")) % m_byUDPVer);
AddLogLineNS(CFormat(wxT("m_byDataCompVer = %i")) % m_byDataCompVer);
AddLogLineNS(CFormat(wxT("m_bySupportSecIdent = %i")) % m_bySupportSecIdent);
AddLogLineNS(CFormat(wxT("<API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT("<API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT("<API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT("<API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT("m_bMultiPacket = %i")) % m_bMultiPacket);
AddLogLineNS(CFormat(wxT("m_fSupportsPreview = %i")) % <API key>);
AddLogLineNS(wxT("That's all."));
#endif
SecIdentSupRec += 1;
break;
}
case <API key>:
// 19 Reserved
// 1 Direct UDP Callback supported and available
// 1 Supports ChatCaptchas
// 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version
// 1 Requires CryptLayer
// 1 Requests CryptLayer
// 1 Supports CryptLayer
// 1 Reserved (ModBit)
// 1 Ext Multipacket (Hash+Size instead of Hash)
// 1 Large Files (includes support for 64bit tags)
// 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future)
<API key> = (temptag.GetInt() >> 12) & 0x01;
m_fSupportsCaptcha = (temptag.GetInt() >> 11) & 0x01;
<API key> = (temptag.GetInt() >> 10) & 0x01;
<API key> = (temptag.GetInt() >> 9) & 0x01;
<API key> = (temptag.GetInt() >> 8) & 0x01;
<API key> = (temptag.GetInt() >> 7) & 0x01;
// reserved 1
m_fExtMultiPacket = (temptag.GetInt() >> 5) & 0x01;
<API key> = (temptag.GetInt() >> 4) & 0x01;
m_byKadVersion = (temptag.GetInt() >> 0) & 0x0f;
dwEmuleTags |= 8;
<API key> &= <API key>;
<API key> &= <API key>;
#ifdef __PACKET_DEBUG__
AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options 2:"));
AddLogLineNS(CFormat(wxT(" <API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT(" m_fSupportsCaptcha = %i")) % m_fSupportsCaptcha);
AddLogLineNS(CFormat(wxT(" <API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT(" <API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT(" <API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT(" <API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT(" m_fExtMultiPacket = %i")) % m_fExtMultiPacket);
AddLogLineNS(CFormat(wxT(" <API key> = %i")) % <API key>);
AddLogLineNS(CFormat(wxT(" KadVersion = %u")) % m_byKadVersion);
AddLogLineNS(wxT("That's all."));
#endif
break;
// Special tag for Compat. Clients Misc options.
case <API key>:
// 1 Operative System Info
// 1 Value-based-type int tags (experimental!)
<API key> = (temptag.GetInt() >> 1*1) & 0x01;
m_fOsInfoSupport = (temptag.GetInt() >> 1*0) & 0x01;
break;
case CT_EMULE_VERSION:
// 8 Compatible Client ID
// 7 Mjr Version (Doesn't really matter..)
// 7 Min Version (Only need 0-99)
// 3 Upd Version (Only need 0-5)
// 7 Bld Version (Only need 0-99)
<API key> = (temptag.GetInt() >> 24);
m_nClientVersion = temptag.GetInt() & 0x00ffffff;
m_byEmuleVersion = 0x99;
<API key> = 1;
dwEmuleTags |= 4;
break;
}
}
m_nUserPort = nUserPort;
m_dwServerIP = data.ReadUInt32();
m_nServerPort = data.ReadUInt16();
// Hybrid now has an extra uint32.. What is it for?
// Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids..
if ( data.GetLength() - data.GetPosition() == sizeof(uint32) ) {
uint32 test = data.ReadUInt32();
/*if (test == 'KDLM') below kdlm is converted to ascii values.
This fixes a warning with gcc 3.4.
K=4b D=44 L=4c M=4d
*/
if (test == 0x4b444c4d) { //if it's == "KDLM"
m_bIsML=true;
} else{
m_bIsHybrid = true;
<API key> = 1;
}
}
if (m_socket) {
SetIP(m_socket->GetPeerInt());
} else {
throw wxString(wxT("Huh, socket failure. Avoided crash this time."));
}
if (thePrefs::<API key>()) {
CServer* addsrv = new CServer(m_nServerPort, Uint32toStringIP(m_dwServerIP));
addsrv->SetListName(addsrv->GetAddress());
if (!theApp->AddServer(addsrv)) {
delete addsrv;
}
}
//(a)If this is a highID user, store the ID in the Hybrid format.
//(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server.
//because they will send a ID that is the same as their IP..
if(!HasLowID() || m_nUserIDHybrid == 0 || m_nUserIDHybrid == m_dwUserIP ) {
SetUserIDHybrid(<API key>(m_dwUserIP));
}
// get client credits
CClientCredits* pFoundCredits = theApp->clientcredits->GetCredit(m_UserHash);
if (credits == NULL){
credits = pFoundCredits;
if (!theApp->clientlist-><API key>(m_dwUserIP, m_nUserPort, pFoundCredits)){
AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() );
Ban();
}
} else if (credits != pFoundCredits){
// userhash change ok, however two hours "waittime" before it can be used
credits = pFoundCredits;
AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() );
Ban();
}
if ((m_Friend = theApp->friendlist->FindFriend(m_UserHash, m_dwUserIP, m_nUserPort)) != NULL){
m_Friend->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::<API key> m_Friend->LinkClient")));
} else{
// avoid that an unwanted client instance keeps a friend slot
SetFriendSlot(false);
}
ReGetClientSoft();
<API key> |= IP_EDONKEYPROTPACK;
// check if at least CT_EMULEVERSION was received, all other tags are optional
bool bIsMule = (dwEmuleTags & 0x04) == 0x04;
if (bIsMule) {
m_bEmuleProtocol = true;
<API key> |= IP_EMULEPROTPACK;
}
if (GetKadPort() && GetKadVersion() > 1) {
Kademlia::CKademlia::Bootstrap(<API key>(GetIP()), GetKadPort());
}
return bIsMule;
}
bool CUpDownClient::SendHelloPacket()
{
if (m_socket == NULL) {
wxFAIL;
return true;
}
// if IP is filtered, don't greet him but disconnect...
if (theApp->ipfilter->IsFiltered(m_socket->GetPeerInt())) {
if (Disconnected(wxT("IPFilter"))) {
Safe_Delete();
return false;
}
return true;
}
CMemFile data(128);
data.WriteUInt8(16); // size of userhash
SendHelloTypePacket(&data);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLO);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true);
<API key> = true;
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLO to ") + GetFullIP() );
return true;
}
void CUpDownClient::SendMuleInfoPacket(bool bAnswer, bool OSInfo) {
if (m_socket == NULL){
wxFAIL;
return;
}
CPacket* packet = NULL;
CMemFile data;
data.WriteUInt8(<API key>);
if (OSInfo) {
// Special MuleInfo packet for clients supporting it.
// This means aMule >= 2.0.0 and Hydranode
// Violently mark it as special Mule Info packet
// Sending this makes <API key> clients to refuse to read this
// packet. Anyway, this packet should NEVER get to non-supporting clients.
data.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF);
data.WriteUInt32(1); // One Tag (OS_INFO)
CTagString tag1(ET_OS_INFO,theApp->GetOSType());
tag1.WriteTagToFile(&data);
m_OSInfo_sent = true; // So we don't send it again
} else {
// Normal MuleInfo packet
// Kry - There's no point on upgrading to VBT tags here
// as no client supporting it uses mule info packet.
data.WriteUInt8(EMULE_PROTOCOL);
// Tag number
data.WriteUInt32(9);
CTagInt32 tag1(ET_COMPRESSION,1);
tag1.WriteTagToFile(&data);
CTagInt32 tag2(ET_UDPVER,4);
tag2.WriteTagToFile(&data);
CTagInt32 tag3(ET_UDPPORT, thePrefs::GetEffectiveUDPPort());
tag3.WriteTagToFile(&data);
CTagInt32 tag4(ET_SOURCEEXCHANGE,3);
tag4.WriteTagToFile(&data);
CTagInt32 tag5(ET_COMMENTS,1);
tag5.WriteTagToFile(&data);
CTagInt32 tag6(ET_EXTENDEDREQUEST,2);
tag6.WriteTagToFile(&data);
uint32 dwTagValue = (theApp->CryptoAvailable() ? 3 : 0);
// Kry - Needs the preview code from eMule
/*
// set 'Preview supported' only if 'View Shared Files' allowed
if (thePrefs::CanSeeShares() != vsfaNobody) {
dwTagValue |= 128;
}
*/
CTagInt32 tag7(ET_FEATURES, dwTagValue);
tag7.WriteTagToFile(&data);
CTagInt32 tag8(ET_COMPATIBLECLIENT,SO_AMULE);
tag8.WriteTagToFile(&data);
// Support for tag ET_MOD_VERSION
wxString mod_name(MOD_VERSION_LONG);
CTagString tag9(ET_MOD_VERSION, mod_name);
tag9.WriteTagToFile(&data);
// Maella end
}
packet = new CPacket(data, OP_EMULEPROT, (bAnswer ? OP_EMULEINFOANSWER : OP_EMULEINFO));
if (m_socket) {
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true,true);
#ifdef __DEBUG__
if (!bAnswer) {
if (!OSInfo) {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() );
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() );
}
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() );
}
#endif
}
}
bool CUpDownClient::<API key>(const byte* pachPacket, uint32 nSize)
{
uint8 protocol_version;
const CMemFile data(pachPacket,nSize);
// The version number part of this packet will soon be useless since
// it is only able to go to v.99. Why the version is a uint8 and why
// it was not done as a tag like the eDonkey hello packet is not known.
// Therefore, sooner or later, we are going to have to switch over to
// using the eDonkey hello packet to set the version. No sense making
// a third value sent for versions.
uint8 mule_version = data.ReadUInt8();
protocol_version = data.ReadUInt8();
uint32 tagcount = data.ReadUInt32();
if (protocol_version == 0xFF) {
// OS Info supporting clients sending a recycled Mule info packet
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, true);
switch(temptag.GetNameID()){
case ET_OS_INFO:
// Special tag, only supporting clients (aMule/Hydranode)
// It was recycled from a mod's tag, so if the other side
// is not supporting OS Info, we're seriously fucked up :)
m_sClientOSInfo = temptag.GetStr();
// If we didn't send our OSInfo to this client, just send it
if (!m_OSInfo_sent) {
SendMuleInfoPacket(false,true);
}
UpdateStats();
break;
// Your ad... er... I mean TAG, here
default:
break;
}
}
} else {
// Old eMule sending tags
<API key> = 0;
m_byEmuleVersion = mule_version;
if( m_byEmuleVersion == 0x2B ) {
m_byEmuleVersion = 0x22;
}
if (!(m_bEmuleProtocol = (protocol_version == EMULE_PROTOCOL))) {
return false;
}
for (uint32 i = 0;i < tagcount; i++){
CTag temptag(data, false);
switch(temptag.GetNameID()){
case ET_COMPRESSION:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: data compression version
m_byDataCompVer = temptag.GetInt();
break;
case ET_UDPPORT:
// Bits 31-16: 0 - reserved
// Bits 15- 0: UDP port
m_nUDPPort = temptag.GetInt();
break;
case ET_UDPVER:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: UDP protocol version
m_byUDPVer = temptag.GetInt();
break;
case ET_SOURCEEXCHANGE:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: source exchange protocol version
<API key> = temptag.GetInt();
break;
case ET_COMMENTS:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: comments version
<API key> = temptag.GetInt();
break;
case ET_EXTENDEDREQUEST:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: extended requests version
<API key> = temptag.GetInt();
break;
case ET_COMPATIBLECLIENT:
// Bits 31- 8: 0 - reserved
// Bits 7- 0: compatible client ID
<API key> = temptag.GetInt();
break;
case ET_FEATURES:
// Bits 31- 8: 0 - reserved
// Bit 7: Preview
// Bit 6- 0: secure identification
m_bySupportSecIdent = temptag.GetInt() & 3;
m_bSupportsPreview = (temptag.GetInt() & 128) > 0;
SecIdentSupRec += 2;
break;
case ET_MOD_VERSION:
if (temptag.IsStr()) {
m_strModVersion = temptag.GetStr();
} else if (temptag.IsInt()) {
m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt();
} else {
m_strModVersion = wxT("ModID=<Unknown>");
}
break;
default:
AddDebugLogLineN( logPacketErrors,
CFormat( wxT("Unknown Mule tag (%s) from client: %s") )
% temptag.GetFullInfo()
% GetClientFullInfo()
);
break;
}
}
if( m_byDataCompVer == 0 ){
<API key> = 0;
<API key> = 0;
<API key> = 0;
m_nUDPPort = 0;
}
//implicitly supported options by older clients
//in the future do not use version to guess about new features
if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x22) {
m_byUDPVer = 1;
}
if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x21) {
<API key> = 1;
}
if(m_byEmuleVersion == 0x24) {
<API key> = 1;
}
// Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in
// the <API key> handler, which does not return the shared files for a
// directory which has a trailing backslash.
if(m_byEmuleVersion >= 0x28 && !m_bIsML) {// MLdonkey currently does not support shared directories
<API key> = 1;
}
ReGetClientSoft();
<API key> |= IP_EMULEPROTPACK;
}
return (protocol_version == 0xFF); // This was a OS_Info?
}
void CUpDownClient::SendHelloAnswer()
{
if (m_socket == NULL){
wxFAIL;
return;
}
CMemFile data(128);
SendHelloTypePacket(&data);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLOANSWER);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() );
SendPacket(packet,true);
}
void CUpDownClient::SendHelloTypePacket(CMemFile* data)
{
data->WriteHash(thePrefs::GetUserHash());
data->WriteUInt32(theApp->GetID());
data->WriteUInt16(thePrefs::GetPort());
uint32 tagcount = 6;
if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
tagcount += 2;
}
tagcount ++; // eMule misc flags 2 (kad version)
#ifdef __SVN__
// Kry - This is the tagcount!!! Be sure to update it!!
data->WriteUInt32(tagcount + 1);
#else
data->WriteUInt32(tagcount); // NO MOD_VERSION
#endif
CTagString tagname(CT_NAME,thePrefs::GetUserNick());
tagname.WriteTagToFile(data, utf8strRaw);
CTagVarInt tagversion(CT_VERSION, EDONKEYVERSION, GetVBTTags() ? 0 : 32);
tagversion.WriteTagToFile(data);
// eMule UDP Ports
uint32 kadUDPPort = 0;
if(Kademlia::CKademlia::IsConnected()) {
if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) {
kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetExternalKadPort();
} else {
kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetInternKadPort();
}
}
CTagVarInt tagUdpPorts(CT_EMULE_UDPPORTS, (kadUDPPort << 16) | ((uint32)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32);
tagUdpPorts.WriteTagToFile(data);
if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) {
CTagVarInt tagBuddyIP(CT_EMULE_BUDDYIP, theApp->clientlist->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32);
tagBuddyIP.WriteTagToFile(data);
CTagVarInt tagBuddyPort(CT_EMULE_BUDDYUDP,
// ( RESERVED )
((uint32)theApp->clientlist->GetBuddy()->GetUDPPort() )
, GetVBTTags() ? 0 : 32);
tagBuddyPort.WriteTagToFile(data);
}
// aMule Version
CTagVarInt tagMuleVersion(CT_EMULE_VERSION,
(SO_AMULE << 24) |
<API key>(VERSION_MJR, VERSION_MIN, VERSION_UPDATE)
// | (RESERVED )
, GetVBTTags() ? 0 : 32);
tagMuleVersion.WriteTagToFile(data);
// eMule Misc. Options
const uint32 uUdpVer = 4;
const uint32 uDataCompVer = 1;
const uint32 uSupportSecIdent = theApp->CryptoAvailable() ? 3 : 0;
const uint32 uSourceExchangeVer = 3;
const uint32 <API key> = 2;
const uint32 uAcceptCommentVer = 1;
const uint32 uNoViewSharedFiles = (thePrefs::CanSeeShares() == vsfaNobody) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag
const uint32 uMultiPacket = 1;
const uint32 uSupportPreview = 0; // No network preview at all.
const uint32 uPeerCache = 0; // No peercache for aMule, baby
const uint32 uUnicodeSupport = 1;
const uint32 nAICHVer = 1; // AICH is ENABLED right now.
CTagVarInt tagMisOptions(<API key>,
(nAICHVer << ((4*7)+1)) |
(uUnicodeSupport << 4*7) |
(uUdpVer << 4*6) |
(uDataCompVer << 4*5) |
(uSupportSecIdent << 4*4) |
(uSourceExchangeVer << 4*3) |
(<API key> << 4*2) |
(uAcceptCommentVer << 4*1) |
(uPeerCache << 1*3) |
(uNoViewSharedFiles << 1*2) |
(uMultiPacket << 1*1) |
(uSupportPreview << 1*0)
, GetVBTTags() ? 0 : 32);
tagMisOptions.WriteTagToFile(data);
// eMule Misc. Options
const uint32 uKadVersion = KADEMLIA_VERSION;
const uint32 uSupportLargeFiles = 1;
const uint32 uExtMultiPacket = 1;
const uint32 uReserved = 0; // mod bit
const uint32 uSupportsCryptLayer = thePrefs::<API key>() ? 1 : 0;
const uint32 uRequestsCryptLayer = thePrefs::<API key>() ? 1 : 0;
const uint32 uRequiresCryptLayer = thePrefs::<API key>() ? 1 : 0;
const uint32 uSupportsSourceEx2 = 1;
#ifdef AMULE_DAEMON
// captcha for daemon/remotegui not supported for now
const uint32 uSupportsCaptcha = 0;
#else
const uint32 uSupportsCaptcha = 1;
#endif
// direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT)
const uint32 uDirectUDPCallback = (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled()
&& !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0;
CTagVarInt tagMisOptions2(<API key>,
// (RESERVED )
(uDirectUDPCallback << 12) |
(uSupportsCaptcha << 11) |
(uSupportsSourceEx2 << 10) |
(uRequiresCryptLayer << 9) |
(uRequestsCryptLayer << 8) |
(uSupportsCryptLayer << 7) |
(uReserved << 6) |
(uExtMultiPacket << 5) |
(uSupportLargeFiles << 4) |
(uKadVersion << 0)
, GetVBTTags() ? 0 : 32 );
tagMisOptions2.WriteTagToFile(data);
const uint32 nOSInfoSupport = 1; // We support OS_INFO
const uint32 nValueBasedTypeTags = 0; // Experimental, disabled
CTagVarInt tagMisCompatOptions(<API key>,
(nValueBasedTypeTags << 1*1) |
(nOSInfoSupport << 1*0)
, GetVBTTags() ? 0 : 32);
tagMisCompatOptions.WriteTagToFile(data);
#ifdef __SVN__
wxString mod_name(MOD_VERSION_LONG);
CTagString tagModName(ET_MOD_VERSION, mod_name);
tagModName.WriteTagToFile(data);
#endif
uint32 dwIP = 0;
uint16 nPort = 0;
if (theApp->IsConnectedED2K()) {
dwIP = theApp->serverconnect->GetCurrentServer()->GetIP();
nPort = theApp->serverconnect->GetCurrentServer()->GetPort();
}
data->WriteUInt32(dwIP);
data->WriteUInt16(nPort);
}
void CUpDownClient::<API key>(const byte* pachPacket, uint32 nSize)
{
if (!m_reqfile) {
throw CInvalidPacket(wxT("Comment packet for unknown file"));
}
if (!m_reqfile->IsPartFile()) {
throw CInvalidPacket(wxT("Comment packet for completed file"));
}
const CMemFile data(pachPacket, nSize);
uint8 rating = data.ReadUInt8();
if (rating > 5) {
AddDebugLogLineN( logClient, wxString(wxT("Invalid Rating for file '")) << m_clientFilename << wxT("' received: ") << rating);
m_iRating = 0;
} else {
m_iRating = rating;
AddDebugLogLineN( logClient, wxString(wxT("Rating for file '")) << m_clientFilename << wxT("' received: ") << m_iRating);
}
// The comment is unicoded, with a uin32 len and safe read
// (won't break if string size is < than advertised len)
// Truncated to MAXFILECOMMENTLEN size
m_strComment = data.ReadString((GetUnicodeSupport() != utf8strNone), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN);
AddDebugLogLineN( logClient, wxString(wxT("Description for file '")) << m_clientFilename << wxT("' received: ") << m_strComment);
// Update file rating
m_reqfile-><API key>();
}
void CUpDownClient::<API key>()
{
{
std::list<<API key>*>::iterator it = <API key>.begin();
for (; it != <API key>.end(); ++it) {
<API key>* cur_block = *it;
if (m_reqfile){
m_reqfile->RemoveBlockFromList(cur_block->StartOffset, cur_block->EndOffset);
}
delete cur_block;
}
<API key>.clear();
}
{
std::list<<API key>*>::iterator it = <API key>.begin();
for (; it != <API key>.end(); ++it) {
<API key>* pending = *it;
if (m_reqfile) {
m_reqfile->RemoveBlockFromList(pending->block->StartOffset, pending->block->EndOffset);
}
delete pending->block;
// Not always allocated
if (pending->zStream){
inflateEnd(pending->zStream);
delete pending->zStream;
}
delete pending;
}
<API key>.clear();
}
}
bool CUpDownClient::Disconnected(const wxString& DEBUG_ONLY(strReason), bool bFromSocket)
{
//wxASSERT(theApp->clientlist->IsValidClient(this));
if (HasBeenDeleted()) {
AddDebugLogLineN(logClient, wxT("Disconnected() called for already deleted client on ip ") + Uint32toStringIP(GetConnectIP()));
return false;
}
// was this a direct callback?
if (<API key> != 0) {
theApp->clientlist-><API key>(this);
<API key> = 0;
theApp->clientlist->AddDeadSource(this);
AddDebugLogLineN(logClient, wxT("Direct callback failed to client on ip ") + Uint32toStringIP(GetConnectIP()));
}
if (GetKadState() == <API key> || GetKadState() == <API key>) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, <API key>(GetConnectIP()), 0); // inform the tester that this test was cancelled
} else if (GetKadState() == KS_FWCHECK_UDP) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, <API key>(GetConnectIP()), 0); // inform the tester that this test has failed
} else if (GetKadState() == KS_CONNECTED_BUDDY) {
AddDebugLogLineN(logClient, wxT("Buddy client disconnected - ") + strReason);
}
//If this is a KAD client object, just delete it!
SetKadState(KS_NONE);
if (GetUploadState() == US_UPLOADING) {
// sets US_NONE
theApp->uploadqueue-><API key>(this);
}
if (GetDownloadState() == DS_DOWNLOADING) {
SetDownloadState(DS_ONQUEUE);
} else {
// ensure that all possible block requests are removed from the partfile
<API key>();
if (GetDownloadState() == DS_CONNECTED) {
// successfully connected, but probably didn't respond to our filerequest
theApp->clientlist->AddDeadSource(this);
theApp->downloadqueue->RemoveSource(this);
}
}
// we had still an AICH request pending, handle it
if (IsAICHReqPending()) {
m_fAICHRequested = FALSE;
CAICHHashSet::<API key>(this);
}
// The remote client does not have to answer with OP_HASHSETANSWER *immediatly*
// after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client
// is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE.
if (((GetDownloadState() == DS_REQHASHSET) || <API key>) && (m_reqfile)) {
m_reqfile->SetHashSetNeeded(true);
}
SourceItemType source_type = UNAVAILABLE_SOURCE;
SourceItemType peer_type = UNAVAILABLE_SOURCE;
//check if this client is needed in any way, if not delete it
bool bDelete = true;
switch (m_nUploadState) {
case US_ONUPLOADQUEUE:
bDelete = false;
peer_type = AVAILABLE_SOURCE;
break;
};
switch (m_nDownloadState) {
case DS_ONQUEUE:
source_type = A4AF_SOURCE; // Will be checked.
case DS_TOOMANYCONNS:
case DS_NONEEDEDPARTS:
case DS_LOWTOLOWIP:
bDelete = false;
break;
};
switch (m_nUploadState) {
case US_CONNECTING:
case US_WAITCALLBACK:
case US_ERROR:
theApp->clientlist->AddDeadSource(this);
bDelete = true;
};
switch (m_nDownloadState) {
case DS_CONNECTING:
case DS_WAITCALLBACK:
case DS_ERROR:
case DS_BANNED:
theApp->clientlist->AddDeadSource(this);
bDelete = true;
};
// We keep chat partners in any case
if (GetChatState() != MS_NONE) {
bDelete = false;
m_pendingMessage.Clear();
<API key>(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString);
}
// Delete socket
if (!bFromSocket && m_socket) {
wxASSERT (theApp->listensocket->IsValidSocket(m_socket));
m_socket->Safe_Delete();
}
SetSocket(NULL);
if (<API key>) {
AddLogLineC(CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() );
<API key> = 0;
}
if (bDelete) {
if (m_Friend) {
// Remove the friend linkage
m_Friend->UnLinkClient(); // this notifies
}
} else {
<API key>(ECID(), peer_type);
<API key>(ECID(), source_type);
<API key> = 0;
<API key>(0);
<API key> = false;
<API key> = 0;
}
AddDebugLogLineN(logClient, CFormat(wxT("--- %s client D:%d U:%d \"%s\"; Reason was %s"))
% (bDelete ? wxT("Deleted") : wxT("Disconnected"))
% m_nDownloadState % m_nUploadState % GetClientFullInfo() % strReason );
return bDelete;
}
//Returned bool is not if the TryToConnect is successful or not..
//false means the client was deleted!
//true means the client was not deleted!
bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon)
{
// Kad reviewed
if (theApp->listensocket->TooManySockets() && !bIgnoreMaxCon ) {
if (!(m_socket && m_socket->IsConnected())) {
if(Disconnected(wxT("Too many connections"))) {
Safe_Delete();
return false;
}
return true;
}
}
// Do not try to connect to source which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it)
if ( (RequiresCryptLayer() && !thePrefs::<API key>()) || (thePrefs::<API key>() && !SupportsCryptLayer()) ){
if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){
Safe_Delete();
return false;
} else {
return true;
}
}
// Ipfilter check
uint32 uClientIP = GetIP();
if (uClientIP == 0 && !HasLowID()) {
uClientIP = <API key>(m_nUserIDHybrid);
}
if (uClientIP) {
// Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts,
// we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list
if (theApp->ipfilter->IsFiltered(uClientIP)) {
AddDebugLogLineN(logIPFilter, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP % Uint32toStringIP(uClientIP));
if (Disconnected(wxT("IPFilter"))) {
Safe_Delete();
return false;
}
return true;
}
// for safety: check again whether that IP is banned
if (theApp->clientlist->IsBannedClient(uClientIP)) {
AddDebugLogLineN(logClient, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP));
if (Disconnected(wxT("Banned IP"))) {
Safe_Delete();
return false;
}
return true;
}
}
if (GetKadState() == KS_QUEUED_FWCHECK) {
SetKadState(<API key>);
} else if (GetKadState() == <API key>) {
SetKadState(<API key>);
}
if (HasLowID()) {
if (!theApp->CanDoCallback(GetServerIP(), GetServerPort())) {
//We cannot do a callback!
if (GetDownloadState() == DS_CONNECTING) {
SetDownloadState(DS_LOWTOLOWIP);
} else if (GetDownloadState() == DS_REQHASHSET) {
SetDownloadState(DS_ONQUEUE);
m_reqfile->SetHashSetNeeded(true);
}
if (GetUploadState() == US_CONNECTING) {
if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) {
Safe_Delete();
return false;
}
}
return true;
}
//We already know we are not firewalled here as the above condition already detected LowID->LowID and returned.
//If ANYTHING changes with the "if(!theApp->CanDoCallback(this))" above that will let you fall through
//with the condition that the source is firewalled and we are firewalled, we must
//recheck it before the this check..
if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp->serverconnect->IsLocalServer(GetServerIP(), GetServerPort())
&& !(<API key>() && thePrefs::GetEffectiveUDPPort() != 0)) {
//This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort.
if( Kademlia::CKademlia::IsConnected() ) {
//We are connect to Kad
if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) {
//There are too many source lookups already or we are already searching this key.
SetDownloadState(DS_TOOMANYCONNSKAD);
return true;
}
}
}
}
if (!m_socket || !m_socket->IsConnected()) {
if (m_socket) {
m_socket->Safe_Delete();
}
m_socket = new CClientTCPSocket(this, thePrefs::GetProxyData());
} else {
<API key>();
return true;
}
if (HasLowID() && <API key>() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback
if (<API key> != 0) {
AddDebugLogLineN(logClient, wxT("ERROR: Trying Direct UDP Callback while already trying to connect to client on ip ") + Uint32toStringIP(GetConnectIP()));
return true; // We're already trying a direct connection to this client
}
// a direct callback is possible - since no other parties are involved and only one additional packet overhead
// is used we basically handle it like a normal connection try, no restrictions apply
// we already check above with !theApp->CanDoCallback(this) if any callback is possible at all
<API key> = ::GetTickCount() + SEC2MS(45);
theApp->clientlist-><API key>(this);
AddDebugLogLineN(logClient, CFormat(wxT("Direct Callback on port %u to client on ip %s")) % GetKadPort() % Uint32toStringIP(GetConnectIP()));
CMemFile data;
data.WriteUInt16(thePrefs::GetPort()); // needs to know our port
data.WriteHash(thePrefs::GetUserHash()); // and userhash
// our connection settings
data.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false));
AddDebugLogLineN(logClientUDP, wxT("Sending <API key> to ") + <API key>(GetConnectIP(), GetKadPort()));
CPacket* packet = new CPacket(data, OP_EMULEPROT, <API key>);
theStats::AddUpOverheadOther(packet->GetPacketSize());
theApp->clientudp->SendPacket(packet, GetConnectIP(), GetKadPort(), <API key>(), GetUserHash().GetHash(), false, 0);
} else if (HasLowID()) { // LOWID
if (GetDownloadState() == DS_CONNECTING) {
SetDownloadState(DS_WAITCALLBACK);
}
if (GetUploadState() == US_CONNECTING) {
if(Disconnected(wxT("LowID and US_CONNECTING"))) {
Safe_Delete();
return false;
}
return true;
}
if (theApp->serverconnect->IsLocalServer(m_dwServerIP,m_nServerPort)) {
CMemFile data;
// AFAICS, this id must be reversed to be sent to clients
// But if I reverse it, we do a serve violation ;)
data.WriteUInt32(m_nUserIDHybrid);
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_CALLBACKREQUEST);
theStats::AddUpOverheadServer(packet->GetPacketSize());
AddDebugLogLineN(logLocalClient, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP());
theApp->serverconnect->SendPacket(packet);
SetDownloadState(DS_WAITCALLBACK);
} else {
if (GetUploadState() == US_NONE && (!GetRemoteQueueRank() || m_bReaskPending)) {
if( !HasValidBuddyID() ) {
theApp->downloadqueue->RemoveSource(this);
if (Disconnected(wxT("LowID and US_NONE and QR=0"))) {
Safe_Delete();
return false;
}
return true;
}
if( !Kademlia::CKademlia::IsConnected() ) {
//We are not connected to Kad and this is a Kad Firewalled source..
theApp->downloadqueue->RemoveSource(this);
if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) {
Safe_Delete();
return false;
}
return true;
}
if( GetDownloadState() == DS_WAITCALLBACK ) {
if( GetBuddyIP() && GetBuddyPort()) {
CMemFile bio(34);
bio.WriteUInt128(Kademlia::CUInt128(GetBuddyID()));
bio.WriteUInt128(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
bio.WriteUInt16(thePrefs::GetPort());
CPacket* packet = new CPacket(bio, OP_KADEMLIAHEADER, <API key>);
// eMule FIXME: We don't know which kadversion the buddy has, so we need to send unencrypted
theApp->clientudp->SendPacket(packet, GetBuddyIP(), GetBuddyPort(), false, NULL, true, 0);
AddDebugLogLineN(logClientKadUDP, CFormat(wxT("KadCallbackReq (size=%i) to %s")) % packet->GetPacketSize() % <API key>(GetBuddyIP(), GetBuddyPort()));
theStats::AddUpOverheadKad(packet->GetRealPacketSize());
SetDownloadState(DS_WAITCALLBACKKAD);
} else {
AddLogLineN(_("Searching buddy for lowid connection"));
//Create search to find buddy.
Kademlia::CSearch *findSource = new Kademlia::CSearch;
findSource->SetSearchTypes(Kademlia::CSearch::FINDSOURCE);
findSource->SetTargetID(Kademlia::CUInt128(GetBuddyID()));
findSource->AddFileID(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash()));
if(Kademlia::CSearchManager::StartSearch(findSource)) {
//Started lookup..
SetDownloadState(DS_WAITCALLBACKKAD);
} else {
//This should never happen..
wxFAIL;
}
}
}
} else {
if (GetDownloadState() == DS_WAITCALLBACK) {
m_bReaskPending = true;
SetDownloadState(DS_ONQUEUE);
}
}
}
} else { // HIGHID
if (!Connect()) {
return false;
}
}
return true;
}
bool CUpDownClient::Connect()
{
<API key> = false;
if (!m_socket->IsOk()) {
// Enable or disable crypting based on our and the remote clients preference
if (HasValidHash() && SupportsCryptLayer() && thePrefs::<API key>() && (RequestsCryptLayer() || thePrefs::<API key>())){
m_socket-><API key>(true, GetUserHash().GetHash(), false);
} else {
m_socket-><API key>(false, NULL, false);
}
amuleIPV4Address tmp;
tmp.Hostname(GetConnectIP());
tmp.Service(GetUserPort());
AddDebugLogLineN(logClient, wxT("Trying to connect to ") + <API key>(GetConnectIP(),GetUserPort()));
m_socket->Connect(tmp, false);
// We should send hello packets AFTER connecting!
// so I moved it to OnConnect
return true;
} else {
return false;
}
}
void CUpDownClient::<API key>()
{
/* Kry - First thing, check if this client was just used to retrieve
info. That's some debug thing for myself... check connection_reason
definition */
<API key> = (m_socket && m_socket->IsConnected() && m_socket->IsObfusicating());
#ifdef __DEBUG__
if (!connection_reason.IsEmpty()) {
AddLogLineN(CFormat(wxT("Got client info checking for %s: %s\nDisconnecting and deleting.")) % connection_reason % GetClientFullInfo());
connection_reason.Clear(); // So we don't re-print on destructor.
Safe_Delete();
return;
}
#endif
// Check if we should use this client to retrieve our public IP
// Ignore local ip on GetPublicIP (could be wrong)
if (theApp->GetPublicIP(true) == 0 && theApp->IsConnectedED2K()) {
SendPublicIPRequest();
}
// was this a direct callback?
if (<API key> != 0){
theApp->clientlist-><API key>(this);
<API key> = 0;
AddDebugLogLineN(logClient, wxT("Direct Callback succeeded, connection established to ") + Uint32toStringIP(GetConnectIP()));
}
switch (GetKadState()) {
case <API key>:
SetKadState(<API key>);
break;
case KS_CONNECTING_BUDDY:
case KS_INCOMING_BUDDY:
SetKadState(KS_CONNECTED_BUDDY);
break;
case <API key>:
SetKadState(KS_FWCHECK_UDP);
<API key>();
break;
default:
break;
}
// ok we have a connection, lets see if we want anything from this client
if (GetChatState() == MS_CONNECTING) {
SetChatState( MS_CHATTING );
}
if (GetChatState() == MS_CHATTING) {
bool result = true;
if (!m_pendingMessage.IsEmpty()) {
result = SendChatMessage(m_pendingMessage);
}
<API key>(result,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage);
m_pendingMessage.Clear();
}
switch(GetDownloadState()) {
case DS_CONNECTING:
case DS_WAITCALLBACK:
case DS_WAITCALLBACKKAD:
m_bReaskPending = false;
SetDownloadState(DS_CONNECTED);
SendFileRequest();
}
if (m_bReaskPending){
m_bReaskPending = false;
if (GetDownloadState() != DS_NONE && GetDownloadState() != DS_DOWNLOADING) {
SetDownloadState(DS_CONNECTED);
SendFileRequest();
}
}
switch(GetUploadState()){
case US_CONNECTING:
case US_WAITCALLBACK:
if (theApp->uploadqueue->IsDownloading(this)) {
SetUploadState(US_UPLOADING);
CPacket* packet = new CPacket(OP_ACCEPTUPLOADREQ, 0, OP_EDONKEYPROT);
theStats::<API key>(packet->GetPacketSize());
SendPacket(packet,true);
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() );
}
}
if (<API key> == 1) {
CPacket* packet = new CPacket(<API key> ? OP_ASKSHAREDDIRS : OP_ASKSHAREDFILES, 0, OP_EDONKEYPROT);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SendPacket(packet,true,true);
#ifdef __DEBUG__
if (<API key>) {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() );
} else {
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() );
}
#endif
}
while (!<API key>.empty()) {
CPacket* packet = <API key>.front();
<API key>.pop_front();
SendPacket(packet);
}
}
int CUpDownClient::GetHashType() const
{
if ( m_UserHash[5] == 13 && m_UserHash[14] == 110 ) {
return SO_OLDEMULE;
}
if ( m_UserHash[5] == 14 && m_UserHash[14] == 111 ) {
return SO_EMULE;
}
if ( m_UserHash[5] == 'M' && m_UserHash[14] == 'L' ) {
return SO_MLDONKEY;
}
return SO_UNKNOWN;
}
void CUpDownClient::SetSocket(CClientTCPSocket* socket)
{
#ifdef __DEBUG__
if (m_socket == NULL && socket != NULL) {
theStats::<API key>();
} else if (m_socket != NULL && socket == NULL) {
theStats::<API key>();
}
#endif
m_socket = socket;
}
void CUpDownClient::ReGetClientSoft()
{
if (m_Username.IsEmpty()) {
m_clientSoft=SO_UNKNOWN;
m_clientVerString = m_clientSoftString = <API key> = <API key> = _("Unknown");
UpdateStats();
return;
}
int iHashType = GetHashType();
wxString clientModString;
if (iHashType == SO_EMULE) {
m_clientSoft = <API key>;
m_clientSoftString = GetSoftName(m_clientSoft);
// Special issues:
if(!GetClientModString().IsEmpty() && (m_clientSoft != SO_EMULE)) {
m_clientSoftString = GetClientModString();
}
// Isn't xMule annoying?
if ((m_clientSoft == SO_LXMULE) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) {
m_clientSoftString += CFormat(_(" (Fake eMule version %#x)")) % GetMuleVersion();
}
if ((m_clientSoft == SO_EMULE) &&
(
wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1
|| GetUserName().Find(wxT("xmule.")) != -1
)
) {
// FAKE eMule -a newer xMule faking is ident.
m_clientSoft = SO_LXMULE;
if (GetClientModString().IsEmpty() == false) {
m_clientSoftString = GetClientModString() + _(" (Fake eMule)");
} else {
m_clientSoftString = _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule.
}
}
// Now, what if we don't know this SO_ID?
if (m_clientSoftString.IsEmpty()) {
if(m_bIsML) {
m_clientSoft = SO_MLDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
} else if (m_bIsHybrid) {
m_clientSoft = SO_EDONKEYHYBRID;
m_clientSoftString = GetSoftName(m_clientSoft);
} else if (<API key> != 0) {
m_clientSoft = SO_COMPAT_UNK;
#ifdef __DEBUG__
if (
// Exceptions:
(<API key> != 0xf0) // Chinese leech mod
&& (1==1) // Your ad here
) {
AddLogLineNS(CFormat(wxT("Compatible client found with ET_COMPATIBLECLIENT of %x")) % <API key>);
}
#endif
m_clientSoftString = CFormat(wxT("%s(%#x)")) % GetSoftName(m_clientSoft) % <API key>;
} else {
// If we step here, it might mean 2 things:
// a eMule
// a Compat Client that has sent no MuleInfo packet yet.
m_clientSoft = SO_EMULE;
m_clientSoftString = wxT("eMule");
}
}
if (m_byEmuleVersion == 0) {
m_nClientVersion = MAKE_CLIENT_VERSION(0,0,0);
} else if (m_byEmuleVersion != 0x99) {
uint32 nClientMinVersion = (m_byEmuleVersion >> 4)*10 + (m_byEmuleVersion & 0x0f);
m_nClientVersion = MAKE_CLIENT_VERSION(0,nClientMinVersion,0);
switch (m_clientSoft) {
case SO_AMULE:
m_clientVerString = CFormat(_("1.x (based on eMule v0.%u)")) % nClientMinVersion;
break;
case SO_LPHANT:
m_clientVerString = wxT("< v0.05");
break;
default:
clientModString = GetClientModString();
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
break;
}
} else {
uint32 nClientMajVersion = (m_nClientVersion >> 17) & 0x7f;
uint32 nClientMinVersion = (m_nClientVersion >> 10) & 0x7f;
uint32 nClientUpVersion = (m_nClientVersion >> 7) & 0x07;
m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
switch (m_clientSoft) {
case SO_AMULE:
case SO_LXMULE:
case SO_HYDRANODE:
case SO_MLDONKEY:
case SO_NEW_MLDONKEY:
case SO_NEW2_MLDONKEY:
// Kry - xMule started sending correct version tags on 1.9.1b.
// It only took them 4 months, and being told by me and the
// eMule+ developers, so I think they're slowly getting smarter.
// They are based on our implementation, so we use the same format
// for the version string.
m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion;
break;
case SO_LPHANT:
m_clientVerString = CFormat(wxT(" v%u.%.2u%c")) % (nClientMajVersion-1) % nClientMinVersion % ('a' + nClientUpVersion);
break;
case SO_EMULEPLUS:
m_clientVerString = CFormat(wxT("v%u")) % nClientMajVersion;
if(nClientMinVersion != 0) {
m_clientVerString += CFormat(wxT(".%u")) % nClientMinVersion;
}
if(nClientUpVersion != 0) {
m_clientVerString += CFormat(wxT("%c")) % ('a' + nClientUpVersion - 1);
}
break;
default:
clientModString = GetClientModString();
m_clientVerString = CFormat(wxT("v%u.%u%c")) % nClientMajVersion % nClientMinVersion % ('a' + nClientUpVersion);
break;
}
}
} else if (m_bIsHybrid) {
// seen:
// 105010 50.10
// 10501 50.1
// 1051 51.0
// 501 50.1
m_clientSoft = SO_EDONKEYHYBRID;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMajVersion;
uint32 nClientMinVersion;
uint32 nClientUpVersion;
if (m_nClientVersion > 100000) {
uint32 uMaj = m_nClientVersion/100000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = (m_nClientVersion - uMaj*100000) / 100;
nClientUpVersion = m_nClientVersion % 100;
}
else if (m_nClientVersion > 10000) {
uint32 uMaj = m_nClientVersion/10000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = (m_nClientVersion - uMaj*10000) / 10;
nClientUpVersion = m_nClientVersion % 10;
}
else if (m_nClientVersion > 1000) {
uint32 uMaj = m_nClientVersion/1000;
nClientMajVersion = uMaj - 1;
nClientMinVersion = m_nClientVersion - uMaj*1000;
nClientUpVersion = 0;
}
else if (m_nClientVersion > 100) {
uint32 uMin = m_nClientVersion/10;
nClientMajVersion = 0;
nClientMinVersion = uMin;
nClientUpVersion = m_nClientVersion - uMin*10;
}
else{
nClientMajVersion = 0;
nClientMinVersion = m_nClientVersion;
nClientUpVersion = 0;
}
m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion);
if (nClientUpVersion) {
m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion;
} else {
m_clientVerString = CFormat(wxT("v%u.%u")) % nClientMajVersion % nClientMinVersion;
}
} else if (m_bIsML || (iHashType == SO_MLDONKEY)) {
m_clientSoft = SO_MLDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMinVersion = m_nClientVersion;
m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
} else if (iHashType == SO_OLDEMULE) {
m_clientSoft = SO_OLDEMULE;
m_clientSoftString = GetSoftName(m_clientSoft);
uint32 nClientMinVersion = m_nClientVersion;
m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0);
m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion;
} else {
m_clientSoft = SO_EDONKEY;
m_clientSoftString = GetSoftName(m_clientSoft);
m_nClientVersion *= 10;
m_clientVerString = CFormat(wxT("v%u.%u")) % (m_nClientVersion / 100000) % ((m_nClientVersion / 1000) % 100);
}
<API key> = m_clientVerString;
if (!clientModString.IsEmpty()) {
m_clientVerString += wxT(" - ") + clientModString;
}
<API key> = m_clientSoftString + wxT(" ") + m_clientVerString;
UpdateStats();
}
void CUpDownClient::<API key>()
{
if (<API key> == 0) {
AddDebugLogLineN( logClient, wxString( wxT("Requesting shared files from ") ) + GetUserName() );
<API key> = 1;
TryToConnect(true);
} else {
AddDebugLogLineN( logClient, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() );
}
}
void CUpDownClient::<API key>(const byte* pachPacket, uint32 nSize, wxString& pszDirectory)
{
if (<API key> > 0) {
<API key>
theApp->searchlist-><API key>(pachPacket, nSize, this, NULL, pszDirectory);
}
}
void CUpDownClient::ResetFileStatusInfo()
{
m_nPartCount = 0;
if ( m_reqfile ) {
m_reqfile-><API key>( this, false );
}
m_downPartStatus.clear();
m_clientFilename.Clear();
m_bCompleteSource = false;
m_dwLastAskedTime = 0;
m_iRating = 0;
m_strComment.Clear();
if (m_pReqFileAICHHash != NULL) {
delete m_pReqFileAICHHash;
m_pReqFileAICHHash = NULL;
}
}
wxString CUpDownClient::GetUploadFileInfo()
{
// build info text and display it
wxString sRet;
sRet = (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" ");
if (m_reqfile) {
sRet += CFormat(_("Requested: %s\n")) % m_reqfile->GetFileName();
sRet += CFormat(
wxPLURAL("Filestats for this session: Accepted %d of %d request, %s transferred\n", "Filestats for this session: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetRequests())
) % m_reqfile->statistic.GetAccepts() % m_reqfile->statistic.GetRequests() % CastItoXBytes(m_reqfile->statistic.GetTransferred());
sRet += CFormat(
wxPLURAL("Filestats for all sessions: Accepted %d of %d request, %s transferred\n", "Filestats for all sessions: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetAllTimeRequests())
) % m_reqfile->statistic.GetAllTimeAccepts() % m_reqfile->statistic.GetAllTimeRequests() % CastItoXBytes(m_reqfile->statistic.<API key>());
} else {
sRet += _("Requested unknown file");
}
return sRet;
}
// sends a packet, if needed it will establish a connection before
// options used: ignore max connections, control packet, delete packet
// !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails
bool CUpDownClient::SafeSendPacket(CPacket* packet)
{
if (IsConnected()) {
SendPacket(packet, true);
return true;
} else {
<API key>.push_back(packet);
return TryToConnect(true);
}
}
void CUpDownClient::SendPublicKeyPacket(){
// send our public key to the client who requested it
if (m_socket == NULL || credits == NULL || m_SecureIdentState != IS_KEYANDSIGNEEDED){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
CMemFile data;
data.WriteUInt8(theApp->clientcredits->GetPubKeyLen());
data.Write(theApp->clientcredits->GetPublicKey(), theApp->clientcredits->GetPubKeyLen());
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_PUBLICKEY);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() );
SendPacket(packet,true,true);
m_SecureIdentState = IS_SIGNATURENEEDED;
}
void CUpDownClient::SendSignaturePacket(){
// signate the public key of this client and send it
if (m_socket == NULL || credits == NULL || m_SecureIdentState == 0){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable()) {
return;
}
if (credits->GetSecIDKeyLen() == 0) {
return; // We don't have his public key yet, will be back here later
}
// do we have a challenge value received (actually we should if we are in this function)
if (credits-><API key> == 0){
AddDebugLogLineN( logClient, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName());
return;
}
// we will use v1 as default, except if only v2 is supported
bool bUseV2;
if ( (m_bySupportSecIdent&1) == 1 )
bUseV2 = false;
else
bUseV2 = true;
uint8 byChaIPKind = 0;
uint32 ChallengeIP = 0;
if (bUseV2){
if (::IsLowID(theApp->GetED2KID())) {
// we cannot do not know for sure our public ip, so use the remote clients one
ChallengeIP = GetIP();
byChaIPKind = <API key>;
} else {
ChallengeIP = theApp->GetED2KID();
byChaIPKind = <API key>;
}
}
//end v2
byte achBuffer[250];
uint8 siglen = theApp->clientcredits->CreateSignature(credits, achBuffer, 250, ChallengeIP, byChaIPKind );
if (siglen == 0){
wxFAIL;
return;
}
CMemFile data;
data.WriteUInt8(siglen);
data.Write(achBuffer, siglen);
if (bUseV2) {
data.WriteUInt8(byChaIPKind);
}
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SIGNATURE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() );
SendPacket(packet,true,true);
m_SecureIdentState = IS_ALLREQUESTSSEND;
}
void CUpDownClient::<API key>(const byte* pachPacket, uint32 nSize)
{
theApp->clientlist->AddTrackClient(this);
if (m_socket == NULL || credits == NULL || pachPacket[0] != nSize-1
|| nSize == 0 || nSize > 250){
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
// the function will handle everything (mulitple key etc)
if (credits->SetSecureIdent(pachPacket+1, pachPacket[0])){
// if this client wants a signature, now we can send him one
if (m_SecureIdentState == IS_SIGNATURENEEDED){
SendSignaturePacket();
}
else if (m_SecureIdentState == IS_KEYANDSIGNEEDED) {
// something is wrong
AddDebugLogLineN( logClient, wxT("Invalid State error: IS_KEYANDSIGNEEDED in <API key>") );
}
} else {
AddDebugLogLineN( logClient, wxT("Failed to use new received public key") );
}
}
void CUpDownClient::<API key>(const byte* pachPacket, uint32 nSize)
{
// here we spread the good guys from the bad ones ;)
if (m_socket == NULL || credits == NULL || nSize == 0 || nSize > 250){
wxFAIL;
return;
}
uint8 byChaIPKind;
if (pachPacket[0] == nSize-1)
byChaIPKind = 0;
else if (pachPacket[0] == nSize-2 && (m_bySupportSecIdent & 2) > 0)
byChaIPKind = pachPacket[nSize-1];
else{
wxFAIL;
return;
}
if (!theApp->CryptoAvailable())
return;
// we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions
if (m_dwLastSignatureIP == GetIP()){
AddDebugLogLineN( logClient, wxT("received multiple signatures from one client") );
return;
}
// also make sure this client has a public key
if (credits->GetSecIDKeyLen() == 0){
AddDebugLogLineN( logClient, wxT("received signature for client without public key") );
return;
}
// and one more check: did we ask for a signature and sent a challange packet?
if (credits-><API key> == 0){
AddDebugLogLineN( logClient, wxT("received signature for client with invalid challenge value - User ") + GetUserName() );
return;
}
// cppcheck-suppress duplicateBranch
if (theApp->clientcredits->VerifyIdent(credits, pachPacket+1, pachPacket[0], GetIP(), byChaIPKind ) ) {
// result is saved in function above
AddDebugLogLineN( logClient, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
} else {
AddDebugLogLineN( logClient, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind );
}
m_dwLastSignatureIP = GetIP();
}
void CUpDownClient::<API key>(){
// check if we need public key and signature
if (credits){
uint8 nValue = 0;
if (theApp->CryptoAvailable()){
if (credits->GetSecIDKeyLen() == 0) {
nValue = IS_KEYANDSIGNEEDED;
} else if (m_dwLastSignatureIP != GetIP()) {
nValue = IS_SIGNATURENEEDED;
}
}
if (nValue == 0){
AddDebugLogLineN( logClient, wxT("Not sending SecIdentState Packet, because State is Zero") );
return;
}
// crypt: send random data to sign
uint32 dwRandom = rand()+1;
credits-><API key> = dwRandom;
CMemFile data;
data.WriteUInt8(nValue);
data.WriteUInt32(dwRandom);
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SECIDENTSTATE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() );
SendPacket(packet,true,true);
} else {
wxFAIL;
}
}
void CUpDownClient::<API key>(const byte* pachPacket, uint32 nSize)
{
if ( nSize != 5 ) {
return;
}
if ( !credits ) {
wxASSERT( credits );
return;
}
CMemFile data(pachPacket,nSize);
switch ( data.ReadUInt8() ) {
case 0:
m_SecureIdentState = IS_UNAVAILABLE;
break;
case 1:
m_SecureIdentState = IS_SIGNATURENEEDED;
break;
case 2:
m_SecureIdentState = IS_KEYANDSIGNEEDED;
break;
default:
return;
}
credits-><API key> = data.ReadUInt32();
}
void CUpDownClient::InfoPacketsReceived()
{
// indicates that both Information Packets has been received
// needed for actions, which process data from both packets
wxASSERT ( <API key> == IP_BOTH );
<API key> = IP_NONE;
if (m_bySupportSecIdent){
<API key>();
}
}
bool CUpDownClient::<API key>() const
{
if (<API key>) {
// this triggers way too often.. need more time to look at this -> only create a warning
// The reason for this is that 2 clients are connecting to each other at the same time..
AddDebugLogLineN( logClient, wxT("Handshake not finished while processing packet.") );
return false;
}
return true;
}
#ifdef __DEBUG__
wxString CUpDownClient::GetClientFullInfo()
{
if (m_clientVerString.IsEmpty()) {
ReGetClientSoft();
}
return CFormat( wxT("Client %s on IP:Port %s:%d using %s %s %s") )
% ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
% GetFullIP()
% GetUserPort()
% m_clientSoftString
% m_clientVerString
% m_strModVersion;
}
#endif
wxString CUpDownClient::GetClientShortInfo()
{
if (m_clientVerString.IsEmpty()) {
ReGetClientSoft();
}
return CFormat( wxT("'%s' (%s %s %s)") )
% ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username )
% m_clientSoftString
% m_clientVerString
% m_strModVersion;
}
void CUpDownClient::SendPublicIPRequest()
{
if (IsConnected()){
CPacket* packet = new CPacket(OP_PUBLICIP_REQ,0,OP_EMULEPROT);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICIP_REQ to ") + GetFullIP());
SendPacket(packet,true);
m_fNeedOurPublicIP = true;
}
}
void CUpDownClient::<API key>(const byte* pbyData, uint32 uSize)
{
if (uSize != 4) {
throw wxString(wxT("Wrong Packet size on Public IP answer"));
}
uint32 dwIP = PeekUInt32(pbyData);
if (m_fNeedOurPublicIP == true){ // did we?
m_fNeedOurPublicIP = false;
// Ignore local ip on GetPublicIP (could be wrong)
if (theApp->GetPublicIP(true) == 0 && !IsLowID(dwIP) ) {
theApp->SetPublicIP(dwIP);
}
}
}
bool CUpDownClient::IsConnected() const
{
return m_socket && m_socket->IsConnected();
}
bool CUpDownClient::SendPacket(CPacket* packet, bool delpacket, bool controlpacket)
{
if ( m_socket ) {
m_socket->SendPacket(packet, delpacket, controlpacket );
return true;
} else {
AddLogLineN(wxT("CAUGHT DEAD SOCKET IN SENDPACKET()"));
return false;
}
}
float CUpDownClient::SetDownloadLimit(uint32 reducedownload)
{
// lfroen: in daemon it actually can happen
wxASSERT( m_socket );
float kBpsClient = CalculateKBpsDown();
if ( m_socket ) {
if (reducedownload) {
// (% to reduce * current speed) / 100 and THEN, / (1000 / CORE_TIMER_PERIOD)
// which is how often it is called per second.
uint32 limit = (uint32)(reducedownload * kBpsClient * 1024.0 / 100000.0 * CORE_TIMER_PERIOD);
if(limit<1024 && reducedownload >= 200) {
// If we're going up and this download is < 1kB,
// we want it to go up fast. Can be reduced later,
// and it'll probably be in a more fair way with
// other downloads that are faster.
limit +=1024;
} else if(limit == 0) {
// This download is not transferring yet... make it
// 1024 so we don't fill the TCP stack and lose the
// connection.
limit = 1024;
}
m_socket->SetDownloadLimit(limit);
} else {
m_socket-><API key>();
}
} else {
AddLogLineNS(CFormat(wxT("CAUGHT DEAD SOCKET IN SETDOWNLOADLIMIT() WITH SPEED %f")) % kBpsClient);
}
return kBpsClient;
}
void CUpDownClient::SetUserIDHybrid(uint32 nUserID)
{
theApp->clientlist->UpdateClientID( this, nUserID );
m_nUserIDHybrid = nUserID;
}
void CUpDownClient::SetIP( uint32 val )
{
theApp->clientlist->UpdateClientIP( this, val );
m_dwUserIP = val;
m_nConnectIP = val;
m_FullUserIP = val;
}
void CUpDownClient::SetUserHash(const CMD4Hash& userhash)
{
theApp->clientlist->UpdateClientHash( this, userhash );
m_UserHash = userhash;
ValidateHash();
}
EUtf8Str CUpDownClient::GetUnicodeSupport() const
{
return m_bUnicodeSupport ? utf8strRaw : utf8strNone;
}
void CUpDownClient::SetSpammer(bool bVal)
{
if (bVal) {
Ban();
} else if (IsBanned() && m_fIsSpammer) {
UnBan();
}
m_fIsSpammer = bVal;
}
uint8 CUpDownClient::GetSecureIdentState()
{
if (m_SecureIdentState != IS_UNAVAILABLE) {
if (!SecIdentSupRec) {
// This can be caused by a 0.30x based client which sends the old
// style Hello packet, and the mule info packet, but between them they
// send a secure ident state packet (after a hello but before we have
// the SUI capabilities). This is a misbehaving client, and somehow I
// feel like it should be dropped. But then again, it won't harm to use
// this SUI state if they are reporting no SUI (won't be used) and if
// they report using SUI on the mule info packet, it's ok to use it.
AddDebugLogLineN(logClient, wxT("A client sent secure ident state before telling us the SUI capabilities"));
AddDebugLogLineN(logClient, wxT("Client info: ") + GetClientFullInfo());
AddDebugLogLineN(logClient, wxT("This client won't be disconnected, but it should be. :P"));
}
}
return m_SecureIdentState;
}
bool CUpDownClient::SendChatMessage(const wxString& message)
{
if (GetChatCaptchaState() == CA_CAPTCHARECV) {
m_nChatCaptchaState = CA_SOLUTIONSENT;
} else if (GetChatCaptchaState() == CA_SOLUTIONSENT) {
wxFAIL; // we responsed to a captcha but didn't heard from the client afterwards - hopefully its just lag and this message will get through
} else {
m_nChatCaptchaState = CA_ACCEPTING;
}
SetSpammer(false);
IncMessagesSent();
// Already connecting?
if (GetChatState() == MS_CONNECTING) {
// Queue all messages till we're able to send them (or discard them)
if (!m_pendingMessage.IsEmpty()) {
m_pendingMessage += wxT("\n");
} else {
// There must be a message to send
// - except if we got disconnected. No need to assert therefore.
}
m_pendingMessage += message;
return false;
}
if (IsConnected()) {
// If we are already connected when we send the first message,
// we have to update the chat status.
SetChatState(MS_CHATTING);
CMemFile data;
data.WriteString(message, GetUnicodeSupport());
CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_MESSAGE);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_MESSAGE to ") + GetFullIP());
SendPacket(packet, true, true);
return true;
} else {
m_pendingMessage = message;
SetChatState(MS_CONNECTING);
// True to ignore "Too Many Connections"
TryToConnect(true);
return false;
}
}
/* Kad stuff */
void CUpDownClient::SetBuddyID(const byte* pucBuddyID)
{
if( pucBuddyID == NULL ){
md4clr(m_achBuddyID);
m_bBuddyIDValid = false;
return;
}
m_bBuddyIDValid = true;
md4cpy(m_achBuddyID, pucBuddyID);
}
// Kad added by me
bool CUpDownClient::SendBuddyPing() {
<API key>();
CPacket* buddyPing = new CPacket(OP_BUDDYPING, 0, OP_EMULEPROT);
theStats::AddUpOverheadKad(buddyPing->GetPacketSize());
AddDebugLogLineN(logLocalClient,wxT("Local Client: OP_BUDDYPING to ") + GetFullIP());
return SafeSendPacket(buddyPing);
}
/* Statistics */
void CUpDownClient::UpdateStats()
{
if (m_lastClientSoft != m_clientSoft || m_lastClientVersion != m_nClientVersion || m_lastOSInfo != m_sClientOSInfo) {
if (m_lastClientSoft == SO_UNKNOWN) {
theStats::RemoveUnknownClient();
} else if (m_lastClientSoft != (uint32)(-1)) {
theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo);
}
m_lastClientSoft = m_clientSoft;
m_lastClientVersion = m_nClientVersion;
m_lastOSInfo = m_sClientOSInfo;
if (m_clientSoft == SO_UNKNOWN) {
theStats::AddUnknownClient();
} else {
theStats::AddKnownClient(this);
}
}
}
bool CUpDownClient::IsIdentified() const
{
return (credits && credits-><API key>(GetIP()) == IS_IDENTIFIED);
}
bool CUpDownClient::IsBadGuy() const
{
return (credits && credits-><API key>(GetIP()) == IS_IDBADGUY);
}
bool CUpDownClient::SUIFailed() const
{
return (credits && credits-><API key>(GetIP()) == IS_IDFAILED);
}
bool CUpDownClient::SUINeeded() const
{
return (credits && credits-><API key>(GetIP()) == IS_IDNEEDED);
}
bool CUpDownClient::SUINotSupported() const
{
return (credits && credits-><API key>(GetIP()) == IS_NOTAVAILABLE);
}
uint64 CUpDownClient::GetDownloadedTotal() const
{
return credits ? credits->GetDownloadedTotal() : 0;
}
uint64 CUpDownClient::GetUploadedTotal() const
{
return credits ? credits->GetUploadedTotal() : 0;
}
double CUpDownClient::GetScoreRatio() const
{
return credits ? credits->GetScoreRatio(GetIP(), theApp->CryptoAvailable()) : 0;
}
const wxString CUpDownClient::GetServerName() const
{
wxString ret;
wxString srvaddr = Uint32toStringIP(GetServerIP());
CServer* cserver = theApp->serverlist->GetServerByAddress(
srvaddr, GetServerPort());
if (cserver) {
ret = cserver->GetListName();
} else {
ret = _("Unknown");
}
return ret;
}
bool CUpDownClient::<API key>() const
{
return (thePrefs::<API key>() && SupportsCryptLayer() && theApp->GetPublicIP() != 0
&& HasValidHash() && (thePrefs::<API key>() || RequestsCryptLayer()) );
}
#ifdef AMULE_DAEMON
void CUpDownClient::<API key>(CMemFile* WXUNUSED(data)) {}
void CUpDownClient::<API key>(uint8 WXUNUSED(nStatus)) {}
void CUpDownClient::ProcessChatMessage(const wxString WXUNUSED(message)) {}
#else
void CUpDownClient::<API key>(CMemFile* data)
{
uint64 id = GUI_ID(GetIP(),GetUserPort());
// received a captcha request, check if we actually accept it (only after sending a message ourself to this client)
if (GetChatCaptchaState() == CA_ACCEPTING && GetChatState() != MS_NONE
&& theApp->amuledlg->m_chatwnd->IsIdValid(id)) {
// read tags (for future use)
uint8 nTagCount = data->ReadUInt8();
if (nTagCount) {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client (%s) with (%u) tags")) % GetFullIP() % nTagCount);
// and ignore them for now
for (uint32 i = 0; i < nTagCount; i++) {
CTag tag(*data, true);
}
}
// sanitize checks - we want a small captcha not a wallpaper
uint32 nSize = (uint32)(data->GetLength() - data->GetPosition());
if ( nSize > 128 && nSize < 4096 ) {
uint64 pos = data->GetPosition();
wxMemoryInputStream memstr(data->GetRawBuffer() + pos, nSize);
wxImage imgCaptcha(memstr, wxBITMAP_TYPE_BMP);
if (imgCaptcha.IsOk() && imgCaptcha.GetHeight() > 10 && imgCaptcha.GetHeight() < 50
&& imgCaptcha.GetWidth() > 10 && imgCaptcha.GetWidth() < 150 ) {
m_nChatCaptchaState = CA_CAPTCHARECV;
CCaptchaDialog * dialog = new CCaptchaDialog(theApp->amuledlg, imgCaptcha, id);
dialog->Show();
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, processing image failed or invalid pixel size (%s)")) % GetFullIP());
}
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, size sanitize check failed (%u) (%s)")) % nSize % GetFullIP());
}
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, but don't accepting it at this time (%s)")) % GetFullIP());
}
}
void CUpDownClient::<API key>(uint8 nStatus)
{
uint64 id = GUI_ID(GetIP(),GetUserPort());
if (GetChatCaptchaState() == CA_SOLUTIONSENT && GetChatState() != MS_NONE
&& theApp->amuledlg->m_chatwnd->IsIdValid(id)) {
wxASSERT( nStatus < 3 );
m_nChatCaptchaState = CA_NONE;
theApp->amuledlg->m_chatwnd->ShowCaptchaResult(id, nStatus == 0);
} else {
m_nChatCaptchaState = CA_NONE;
AddDebugLogLineN(logClient, CFormat(wxT("Received captcha result from client, but not accepting it at this time (%s)")) % GetFullIP());
}
}
void CUpDownClient::ProcessChatMessage(wxString message)
{
if (IsMessageFiltered(message)) {
AddLogLineC(CFormat(_("Message filtered from '%s' (IP:%s)")) % GetUserName() % GetFullIP());
return;
}
// advanced spamfilter check
if (thePrefs::<API key>() && !IsFriend()) {
// captcha checks outrank any further checks - if the captcha has been solved, we assume it's not spam
// first check if we need to send a captcha request to this client
if (GetMessagesSent() == 0 && GetMessagesReceived() == 0 && GetChatCaptchaState() != CA_CAPTCHASOLVED) {
// we have never sent a message to this client, and no message from him has ever passed our filters
if (GetChatCaptchaState() != CA_CHALLENGESENT) {
// we also aren't currently expecting a captcha response
if (m_fSupportsCaptcha) {
// and he supports captcha, so send him one and store the message (without showing for now)
if (m_cCaptchasSent < 3) { // no more than 3 tries
<API key> = message;
<API key> memstr;
memstr.PutC(0); // no tags, for future use
CCaptchaGenerator captcha(4);
if (captcha.WriteCaptchaImage(memstr)){
<API key> = captcha.GetCaptchaText();
m_nChatCaptchaState = CA_CHALLENGESENT;
m_cCaptchasSent++;
CMemFile fileAnswer((byte*) memstr.<API key>()->GetBufferStart(), memstr.GetLength());
CPacket* packet = new CPacket(fileAnswer, OP_EMULEPROT, OP_CHATCAPTCHAREQ);
theStats::AddUpOverheadOther(packet->GetPacketSize());
AddLogLineN(CFormat(wxT("sent Captcha %s (%d)")) % <API key> % packet->GetPacketSize());
SafeSendPacket(packet);
} else {
wxFAIL;
}
}
} else {
// client doesn't support captchas, but we require them, tell him that it's not going to work out
// with an answer message (will not be shown and doesn't count as sent message)
if (m_cCaptchasSent < 1) { // don't send this notifier more than once
m_cCaptchasSent++;
// always sent in english
SendChatMessage(wxT("In order to avoid spam messages, this user requires you to solve a captcha before you can send a message to him. However your client does not supports captchas, so you will not be able to chat with this user."));
AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered and sent notifier (%s)")) % GetClientFullInfo());
} else {
AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered, didn't send notifier (%s)")) % GetClientFullInfo());
}
}
return;
} else { // (GetChatCaptchaState() == CA_CHALLENGESENT)
// this message must be the answer to the captcha request we sent him, let's verify
wxASSERT( !<API key>.IsEmpty() );
if (<API key>.CmpNoCase(message.Trim().Right(std::min(message.Length(), <API key>.Length()))) == 0) {
// allright
AddDebugLogLineN(logClient, CFormat(wxT("Captcha solved, showing withheld message (%s)")) % GetClientFullInfo());
m_nChatCaptchaState = CA_CAPTCHASOLVED; // this state isn't persitent, but the messagecounter will be used to determine later if the captcha has been solved
// replace captchaanswer with withheld message and show it
message = <API key>;
m_cCaptchasSent = 0;
<API key>.Clear();
CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false);
byte statusResponse = 0; // status response
packet->CopyToDataBuffer(0, &statusResponse, 1);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SafeSendPacket(packet);
} else { // wrong, cleanup and ignore
AddDebugLogLineN(logClient, CFormat(wxT("Captcha answer failed (%s)")) % GetClientFullInfo());
m_nChatCaptchaState = CA_NONE;
<API key>.Clear();
<API key>.Clear();
CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false);
byte statusResponse = (m_cCaptchasSent < 3) ? 1 : 2; // status response
packet->CopyToDataBuffer(0, &statusResponse, 1);
theStats::AddUpOverheadOther(packet->GetPacketSize());
SafeSendPacket(packet);
return; // nothing more todo
}
}
}
}
if (thePrefs::<API key>() && !IsFriend()) { // friends are never spammer... (but what if two spammers are friends :P )
bool bIsSpam = false;
if (m_fIsSpammer) {
bIsSpam = true;
} else {
// first fixed criteria: If a client sends me an URL in his first message before I respond to him
// there is a 99,9% chance that it is some poor guy advising his leech mod, or selling you .. well you know :P
if (GetMessagesSent() == 0) {
static wxArrayString urlindicators(wxStringTokenize(wxT("http:|www.|.de |.net |.com |.org |.to |.tk |.cc |.fr |ftp:|ed2k:|https:|ftp.|.info|.biz|.uk|.eu|.es|.tv|.cn|.tw|.ws|.nu|.jp"), wxT("|")));
for (size_t pos = urlindicators.GetCount(); pos
if (message.Find(urlindicators[pos]) != wxNOT_FOUND) {
bIsSpam = true;
break;
}
}
// second fixed criteria: he sent me 4 or more messages and I didn't answer him once
if (GetMessagesReceived() > 3) {
bIsSpam = true;
}
}
}
if (bIsSpam) {
AddDebugLogLineN(logClient, CFormat(wxT("'%s' has been marked as spammer")) % GetUserName());
SetSpammer(true);
theApp->amuledlg->m_chatwnd->EndSession(GUI_ID(GetIP(),GetUserPort()));
return;
}
}
wxString logMsg = CFormat(_("New message from '%s' (IP:%s)")) % GetUserName() % GetFullIP();
if(thePrefs::ShowMessagesInLog()) {
logMsg += wxT(": ") + message;
}
AddLogLineC(logMsg);
IncMessagesReceived();
<API key>(GUI_ID(GetIP(), GetUserPort()), GetUserName() + wxT("|") + message);
}
bool CUpDownClient::IsMessageFiltered(const wxString& message)
{
bool filtered = false;
// If we're chatting to the guy, we don't want to filter!
if (GetChatState() != MS_CHATTING) {
if (thePrefs::MsgOnlyFriends() && !IsFriend()) {
filtered = true;
} else if (thePrefs::MsgOnlySecure() && GetUserName().IsEmpty() ) {
filtered = true;
} else if (thePrefs::MustFilterMessages()) {
filtered = thePrefs::IsMessageFiltered(message);
}
}
if (filtered) {
SetSpammer(true);
}
return filtered;
}
#endif
void CUpDownClient::<API key>()
{
// This list will contain all (unique) folders.
PathList foldersToSend;
// The shared folders
const unsigned folderCount = theApp->glob_prefs->shareddir_list.size();
for (unsigned i = 0; i < folderCount; ++i) {
foldersToSend.push_back(theApp->glob_prefs->shareddir_list[i]);
}
// ... the categories folders ... (category 0 -> incoming)
for (unsigned i = 0; i < theApp->glob_prefs->GetCatCount(); ++i) {
foldersToSend.push_back(theApp->glob_prefs->GetCategory(i)->path);
}
// Strip duplicates
foldersToSend.sort();
foldersToSend.unique();
// Build packet
CMemFile tempfile(80);
tempfile.WriteUInt32(foldersToSend.size() + 1); // + 1 for the incomplete files
PathList::iterator it = foldersToSend.begin();
for (; it != foldersToSend.end(); ++it) {
// Note: the public shared name contains the 'raw' path, so we can recognize it again.
// the 'raw' path is determined using CPath::GetRaw()
tempfile.WriteString( theApp->sharedfiles-><API key>(*it), GetUnicodeSupport() );
}
// ... and the Magic thing from the eDonkey Hybrids...
tempfile.WriteString(<API key>, GetUnicodeSupport());
// Send the packet.
CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDDIRSANS);
theStats::AddUpOverheadOther(replypacket->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRSANS to ") + GetFullIP() );
SendPacket(replypacket, true, true);
}
void CUpDownClient::<API key>(const wxString& strReqDir)
{
CKnownFilePtrList list;
if (strReqDir == <API key>) {
// get all shared files from download queue
int iQueuedFiles = theApp->downloadqueue->GetFileCount();
for (int i = 0; i < iQueuedFiles; i++) {
CPartFile* pFile = theApp->downloadqueue->GetFileByIndex(i);
if (pFile == NULL || pFile->GetStatus(true) != PS_READY) {
continue;
}
list.push_back(pFile);
}
} else {
// get all shared files for the requested directory
const CPath *sharedDir = theApp->sharedfiles-><API key>(strReqDir);
if (sharedDir) {
theApp->sharedfiles-><API key>(sharedDir->GetRaw(), list);
} else {
AddLogLineC(CFormat(_("User %s (%u) requested sharedfiles-list for not existing directory '%s' -> Ignored")) % GetUserName() % GetUserIDHybrid() % strReqDir);
}
}
CMemFile tempfile(80);
tempfile.WriteString(strReqDir, GetUnicodeSupport());
tempfile.WriteUInt32(list.size());
while (!list.empty()) {
if (!list.front()->IsLargeFile() || SupportsLargeFiles()) {
list.front()-><API key>(&tempfile, NULL, this);
}
list.pop_front();
}
CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, <API key>);
theStats::AddUpOverheadOther(replypacket->GetPacketSize());
AddDebugLogLineN( logLocalClient, wxT("Local Client: <API key> to ") + GetFullIP() );
SendPacket(replypacket, true, true);
}
void CUpDownClient::<API key>()
{
wxASSERT(GetKadState() == KS_FWCHECK_UDP);
if (!Kademlia::CKademlia::IsRunning()) {
SetKadState(KS_NONE);
return;
} else if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE || GetKadVersion() <= 5 || GetKadPort() == 0) {
Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, <API key>(GetIP()), 0); // inform the tester that this test was cancelled
SetKadState(KS_NONE);
return;
}
CMemFile data;
data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort());
data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort());
data.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP()));
CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_FWCHECKUDPREQ);
theStats::AddUpOverheadKad(packet->GetPacketSize());
SafeSendPacket(packet);
}
void CUpDownClient::<API key>(CMemFile* data)
{
if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL) {
//DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), GetClientFullInfo());
return;
}
// first search if we know this IP already, if so the result might be biased and we need tell the requester
bool errorAlreadyKnown = false;
if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE) {
errorAlreadyKnown = true;
} else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(<API key>(GetConnectIP()), 0, false) != NULL) {
errorAlreadyKnown = true;
}
uint16_t remoteInternPort = data->ReadUInt16();
uint16_t remoteExternPort = data->ReadUInt16();
uint32_t senderKey = data->ReadUInt32();
if (remoteInternPort == 0) {
//DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), GetClientFullInfo());
return;
}
// if (senderKey == 0)
// DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), GetClientFullInfo());
CMemFile testPacket1;
testPacket1.WriteUInt8(errorAlreadyKnown ? 1 : 0);
testPacket1.WriteUInt16(remoteInternPort);
DebugSend(Kad2FirewallUDP, <API key>(GetConnectIP()), remoteInternPort);
Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1, <API key>, <API key>(GetConnectIP()), remoteInternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
// if the client has a router with PAT (and therefore a different extern port than intern), test this port too
if (remoteExternPort != 0 && remoteExternPort != remoteInternPort) {
CMemFile testPacket2;
testPacket2.WriteUInt8(errorAlreadyKnown ? 1 : 0);
testPacket2.WriteUInt16(remoteExternPort);
DebugSend(Kad2FirewalledUDP, <API key>(GetConnectIP()), remoteExternPort);
Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2, <API key>, <API key>(GetConnectIP()), remoteExternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL);
}
//DebugLog(_T("Answered UDP Firewallcheck request (%s)"), GetClientFullInfo());
}
void CUpDownClient::SetConnectOptions(uint8_t options, bool encryption, bool callback)
{
<API key>((options & 0x01) != 0 && encryption);
<API key>((options & 0x02) != 0 && encryption);
<API key>((options & 0x04) != 0 && encryption);
<API key>((options & 0x08) != 0 && callback);
}
#ifdef <API key>
void CUpDownClient::Unlink(const wxString& from)
{
std::multiset<wxString>::iterator it = m_linkedFrom.find(from);
if (it != m_linkedFrom.end()) {
m_linkedFrom.erase(it);
}
m_linked
if (!m_linked) {
if (m_linkedDebug) {
AddLogLineN(CFormat(wxT("Last reference to client %d %p unlinked, delete it.")) % ECID() % this);
}
delete this;
}
}
#else
void CUpDownClient::Unlink()
{
m_linked
if (!m_linked) {
delete this;
}
}
#endif
// <API key>
|
/*
* An Abstract communicator interface which implements listeners.
*/
package com.willwinder.<API key>;
import com.willwinder.<API key>.i18n.Localization;
import com.willwinder.<API key>.listeners.<API key>;
import com.willwinder.<API key>.types.GcodeCommand;
import java.io.IOException;
import java.util.ArrayList;
/**
*
* @author wwinder
*/
public abstract class <API key> {
public static String DEFAULT_TERMINATOR = "\r\n";
private String lineTerminator;
protected Connection conn;
// Callback interfaces
ArrayList<<API key>> <API key>;
ArrayList<<API key>> <API key>;
ArrayList<<API key>> <API key>;
ArrayList<<API key>> <API key>;
ArrayList<<API key>> <API key>;
private final ArrayList<Connection> connections;
public <API key>() {
this.lineTerminator = DEFAULT_TERMINATOR;
this.<API key> = new ArrayList<<API key>>();
this.<API key> = new ArrayList<<API key>>();
this.<API key> = new ArrayList<<API key>>();
this.<API key> = new ArrayList<<API key>>();
this.<API key> = new ArrayList<<API key>>();
//instanciate all known connection drivers
//TODO: Scan the classpath for classes extending Connection,
// and instantiate them dynamically.
this.connections = new ArrayList<Connection>();
this.addConnectionType(new SerialConnection());
}
final public void addConnectionType(Connection conn) {
this.connections.add(conn);
}
/* Serial Layer API. */
abstract public void setSingleStepMode(boolean enable);
abstract public boolean getSingleStepMode();
abstract public void queueStringForComm(final String input);
abstract public void sendByteImmediately(byte b) throws IOException;
abstract public boolean areActiveCommands();
abstract public void streamCommands();
abstract public void pauseSend();
abstract public void resumeSend();
abstract public void cancelSend();
abstract public void softReset();
abstract public void responseMessage(String response);
//do common operations (related to the connection, that is shared by all communicators)
protected boolean openCommPort(String name, int baud) throws Exception {
//choose port
for(Connection candidate: connections) {
if(candidate.supports(name)) {
conn = candidate;
conn.setCommunicator(this);
break;
}
}
if(conn==null) {
throw new Exception(Localization.getString("communicator.exception.port") + ": "+name);
}
//open it
conn.openPort(name, baud);
return true;
}
//do common things (related to the connection, that is shared by all communicators)
protected void closeCommPort() {
conn.closePort();
}
/** Getters & Setters. */
void setLineTerminator(String terminator) {
if (terminator == null || terminator.length() < 1) {
this.lineTerminator = DEFAULT_TERMINATOR;
} else {
this.lineTerminator = terminator;
}
}
String getLineTerminator() {
return this.lineTerminator;
}
/** Listener helpers. */
void setListenAll(<API key> scl) {
this.<API key>(scl);
this.<API key>(scl);
this.<API key>(scl);
this.<API key>(scl);
this.<API key>(scl);
}
void <API key>(<API key> scl) {
this.<API key>.add(scl);
}
void <API key>(<API key> scl) {
this.<API key>.add(scl);
}
void <API key>(<API key> scl) {
this.<API key>.add(scl);
}
void <API key>(<API key> scl) {
this.<API key>.add(scl);
}
void <API key>(<API key> scl) {
this.<API key>.add(scl);
}
// Helper for the console listener.
protected void <API key>(String msg) {
this.<API key>(msg, false);
}
protected void <API key>(String msg, boolean verbose) {
// Exit early if there are no listeners.
if (this.<API key> == null) {
return;
}
int verbosity;
if (!verbose) {
verbosity = CONSOLE_MESSAGE;
}
else {
verbosity = <API key>;
}
<API key>(verbosity, this.<API key>, msg);
}
// Serial Communicator Listener Events
protected static final int COMMAND_SENT = 1;
protected static final int COMMAND_COMPLETE = 2;
protected static final int RAW_RESPONSE = 3;
protected static final int CONSOLE_MESSAGE = 4;
protected static final int <API key> = 5;
/**
* A bunch of methods to dispatch listener events with various arguments.
*/
static protected void <API key>(int event, ArrayList<<API key>> sclList, String message) {
if (sclList != null) {
for (<API key> s : sclList) {
sendEventToListener(event, s, message, null);
}
}
}
static protected void <API key>(int event, ArrayList<<API key>> sclList, GcodeCommand command) {
if (sclList != null) {
for (<API key> s : sclList) {
sendEventToListener(event, s, null, command);
}
}
}
static protected void sendEventToListener(int event, <API key> scl,
String string, GcodeCommand command) {
switch(event) {
case COMMAND_SENT:
scl.commandSent(string);
break;
case CONSOLE_MESSAGE:
scl.messageForConsole(string);
break;
case <API key>:
scl.<API key>(string);
break;
case RAW_RESPONSE:
scl.rawResponseListener(string);
default:
}
}
}
|
import React from 'react'
import ManualLink from 'browser-components/ManualLink'
const title = 'FOREACH'
const subtitle = 'Operate on a collection'
const category = 'cypherHelp'
const content = (
<>
<p>
The <code>FOREACH</code> clause is used to update data within a collection
whether components of a path, or result of aggregation.
</p>
<div className="links">
<div className="link">
<p className="title">Reference</p>
<p className="content">
<ManualLink chapter="cypher-manual" page="/clauses/foreach/">
FOREACH
</ManualLink>{' '}
manual page
</p>
</div>
<div className="link">
<p className="title">Related</p>
<p className="content">
<a help-topic="create">:help CREATE</a>
<a help-topic="delete">:help DELETE</a>
<a help-topic="set">:help SET</a>
<a help-topic="cypher">:help Cypher</a>
</p>
</div>
</div>
<section className="example">
<figure className="runnable">
<pre>
{`MATCH p = (ups)<-[DEPENDS_ON]-(device) WHERE ups.id='EPS-7001'
FOREACH (n IN nodes(p) | SET n.available = FALSE )`}
</pre>
<figcaption>
Mark all devices plugged into a failed UPS as unavailable.
</figcaption>
</figure>
</section>
</>
)
export default { title, subtitle, category, content }
|
#include "queuemodel.h"
#include "queue.h"
namespace unplayer
{
QVariant QueueModel::data(const QModelIndex& index, int role) const
{
if (!mQueue || !index.isValid()) {
return QVariant();
}
const QueueTrack* track = mQueue->tracks()[static_cast<size_t>(index.row())].get();
switch (role) {
case UrlRole:
return track->url;
case IsLocalFileRole:
return track->url.isLocalFile();
case FilePathRole:
return track->url.path();
case TitleRole:
return track->title;
case ArtistRole:
return track->artist;
case DisplayedArtistRole:
return track->artist;
case AlbumRole:
return track->album;
case DisplayedAlbumRole:
return track->album;
case DurationRole:
return track->duration;
default:
return QVariant();
}
}
int QueueModel::rowCount(const QModelIndex&) const
{
return mQueue ? static_cast<int>(mQueue->tracks().size()) : 0;
}
Queue* QueueModel::queue() const
{
return mQueue;
}
void QueueModel::setQueue(Queue* queue)
{
if (queue == mQueue || !queue) {
return;
}
mQueue = queue;
QObject::connect(mQueue, &Queue::<API key>, this, [=](int count) {
const int first = rowCount();
beginInsertRows(QModelIndex(), first, first + count - 1);
});
QObject::connect(mQueue, &Queue::tracksAdded, this, [=]() {
endInsertRows();
});
QObject::connect(mQueue, &Queue::<API key>, this, [=](int index) {
beginRemoveRows(QModelIndex(), index, index);
});
QObject::connect(mQueue, &Queue::trackRemoved, this, [=]() {
endRemoveRows();
});
QObject::connect(mQueue, &Queue::aboutToBeCleared, this, [=]() {
beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
});
QObject::connect(mQueue, &Queue::cleared, this, [=]() {
endRemoveRows();
});
}
QHash<int, QByteArray> QueueModel::roleNames() const
{
return {{UrlRole, "url"},
{IsLocalFileRole, "isLocalFile"},
{FilePathRole, "filePath"},
{TitleRole, "title"},
{ArtistRole, "artist"},
{DisplayedArtistRole, "displayedArtist"},
{AlbumRole, "album"},
{DisplayedAlbumRole, "displayedAlbum"},
{DurationRole, "duration"}};
}
}
|
<div class="main-title">15, Sunday <span>2016</span>
</div>
<ul class="stage clearfix">
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>20:15 <small>GMT</small></strong></div>
<div class="cal-to"><strong>22:00 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Aldosivi
<br><small>vs</small>
<br>Atl. Rafaela</div><em><i class="fa fa-map-marker"></i>Argentina - Primera Division</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>22:30 <small>GMT</small></strong></div>
<div class="cal-to"><strong>0:15 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Barcelona SC
<br><small>vs</small>
<br>Emelec</div><em><i class="fa fa-map-marker"></i>Ecuador - Serie A</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-red">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>15:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>16:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Chelsea
<br><small>vs</small>
<br>Leicester City</div><em><i class="fa fa-map-marker"></i>England - Premier League</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="<API key> uppercase">LOSS</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>16:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>17:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Dinamo-Auto
<br><small>vs</small>
<br>Milsami Orhei</div><em><i class="fa fa-map-marker"></i>Moldova - Divizia Nationala</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key>">2.5</div>
<div class="<API key> uppercase">Under<i class="fa fa-angle-down"></i></div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>15:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>16:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Everton
<br><small>vs</small>
<br>Norwich City</div><em><i class="fa fa-map-marker"></i>England - Premier League</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-red">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>2:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>3:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">FBC Melgar
<br><small>vs</small>
<br>UTC Cajamarca</div><em><i class="fa fa-map-marker"></i>Peru - Primera Division</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="<API key> uppercase">LOSS</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>22:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>23:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Guaraní PRG
<br><small>vs</small>
<br>Sol de América</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-red">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>13:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>14:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">OB Odense
<br><small>vs</small>
<br>Hobro IK</div><em><i class="fa fa-map-marker"></i>Denmark - Superligaen</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="<API key> uppercase">LOSS</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>3:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>4:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Orange County B
<br><small>vs</small>
<br>Arizona United</div><em><i class="fa fa-map-marker"></i>USA - USL</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key>">2.5</div>
<div class="<API key> uppercase">Under<i class="fa fa-angle-down"></i></div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>22:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>23:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Rubio Nu
<br><small>vs</small>
<br>Olimpia PRG</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>22:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>23:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Sport. Luqueño
<br><small>vs</small>
<br>Nacional PRG</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-green">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>16:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>17:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Travnik
<br><small>vs</small>
<br>Drina Zvornik</div><em><i class="fa fa-map-marker"></i>Bosnia - Premier Liga</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="result-top-win-hist uppercase">WIN</div>
</div>
</div>
</a>
<a class="calendar-history poster tasklist-red">
<div class="max-constrain">
<div class="first-20">
<div class="cal-from"><strong>17:00 <small>GMT</small></strong></div>
<div class="cal-to"><strong>18:45 <small>GMT</small></strong></div>
</div>
<div class="second-40">
<div class="teams">Zenit
<br><small>vs</small>
<br>Lokomotiv M.</div><em><i class="fa fa-map-marker"></i>Russia - Premier League</em></div>
<div class="third-40 last-column">
<div class="over-under-hist">
<div class="<API key>">
<div class="<API key> uppercase"><i class="fa fa-angle-up"></i>Over</div>
<div class="<API key>">2.5</div>
</div>
</div>
<div class="<API key> uppercase">LOSS</div>
</div>
</div>
</a>
</ul>
|
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
def ImportGames():
games = list()
user_games = dict()
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesCleansed.txt', 'r', encoding = 'utf-8') as lines:
next(lines) # Skiping headers
for ln in lines:
user, board_game, board_type, list_type, score10 = ln.split('
if board_game not in games:
games.append(board_game.replace('\t',' ').replace(' ', ' '))
if user not in user_games:
user_games[user] = dict()
if board_game not in user_games[user].keys():
user_games[user][board_game] = 1
return (games, user_games)
games, user_games = ImportGames()
def BuildMatrix(games, user_games):
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesMatrix.tab', 'a', encoding = 'utf-8') as lines:
lines.write('user\t' + '\t'.join(games) + '\n')
for user in user_games:
user_line = list()
for game in games:
if game in user_games[user].keys():
user_line.append('1')
else:
user_line.append('0')
with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesMatrix.tab', 'a', encoding = 'utf-8') as lines:
lines.write(user + '\t' + '\t'.join(user_line) + '\n')
BuildMatrix(games, user_games)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.