text stringlengths 2 1.04M | meta dict |
|---|---|
Returns all the workflow definitions
**Namespace:** [Microsoft.SharePoint.Client](Microsoft.SharePoint.Client.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public static WorkflowDefinition[] GetWorkflowDefinitions(this Web web, Boolean publishedOnly)
```
### Parameters
#### web
  Type: Microsoft.SharePoint.Client.Web
  The target Web
#### publishedOnly
  Type: System.Boolean
  Defines whether to include only published definition, or all the definitions
### Return Value
Type: WorkflowDefinition[]
Returns all WorkflowDefinitions
## See also
- [WorkflowExtensions](Microsoft.SharePoint.Client.WorkflowExtensions.md)
- [Microsoft.SharePoint.Client](Microsoft.SharePoint.Client.md)
| {
"content_hash": "186b96307ad5095e808830e7a4fee8d6",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 94,
"avg_line_length": 26.620689655172413,
"alnum_prop": 0.7474093264248705,
"repo_name": "erwinvanhunen/PnP-Guidance",
"id": "77d2cccb74a85ec51f4582b976527c534da40a81",
"size": "825",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "sitescore/Microsoft.SharePoint.Client.WorkflowExtensions.7692b016.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PowerShell",
"bytes": "783"
}
],
"symlink_target": ""
} |
.. _kx_pkgs4bootstrap:
kx_pkgs4bootstrap - Install packages for configure
==================================================
SYNOPSIS
--------
**kx_pkgs4bootstrap**
DESCRIPTION
-----------
Try to install packages (on host) necessary for
bootstrapping **KaarPux**
| {
"content_hash": "7cc9bed05460291eb81b8df0210270cc",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 50,
"avg_line_length": 17.866666666666667,
"alnum_prop": 0.5671641791044776,
"repo_name": "8l/KaarPux",
"id": "f1c3824b8cd46fe09e59ae3f58f88f28f31bccc3",
"size": "268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "man/kx_pkgs4bootstrap.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "31617"
},
{
"name": "C++",
"bytes": "716"
},
{
"name": "Makefile",
"bytes": "245"
},
{
"name": "Perl",
"bytes": "97229"
},
{
"name": "Python",
"bytes": "17986"
},
{
"name": "Shell",
"bytes": "141721"
},
{
"name": "Tcl",
"bytes": "4062"
},
{
"name": "VimL",
"bytes": "116"
}
],
"symlink_target": ""
} |
// CallbackServer project doc.go
/*
CallbackServer document
*/
package main
| {
"content_hash": "8dc617e9357800633e4a328d221152f6",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 32,
"avg_line_length": 12.833333333333334,
"alnum_prop": 0.7662337662337663,
"repo_name": "DuoSoftware/DVP-CallBackService",
"id": "5b6bd8b6e69f36f92d0ebc02d458d240768461e9",
"size": "77",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CallbackServer/doc.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "44420"
}
],
"symlink_target": ""
} |
package lldp
import (
"github.com/skydive-project/skydive/graffiti/getter"
"strings"
)
func (obj *LinkAggregationMetadata) GetFieldBool(key string) (bool, error) {
switch key {
case "Enabled":
return obj.Enabled, nil
case "Supported":
return obj.Supported, nil
}
return false, getter.ErrFieldNotFound
}
func (obj *LinkAggregationMetadata) GetFieldInt64(key string) (int64, error) {
switch key {
case "PortID":
return int64(obj.PortID), nil
}
return 0, getter.ErrFieldNotFound
}
func (obj *LinkAggregationMetadata) GetFieldString(key string) (string, error) {
return "", getter.ErrFieldNotFound
}
func (obj *LinkAggregationMetadata) GetFieldKeys() []string {
return []string{
"Enabled",
"PortID",
"Supported",
}
}
func (obj *LinkAggregationMetadata) MatchBool(key string, predicate getter.BoolPredicate) bool {
if b, err := obj.GetFieldBool(key); err == nil {
return predicate(b)
}
return false
}
func (obj *LinkAggregationMetadata) MatchInt64(key string, predicate getter.Int64Predicate) bool {
if b, err := obj.GetFieldInt64(key); err == nil {
return predicate(b)
}
return false
}
func (obj *LinkAggregationMetadata) MatchString(key string, predicate getter.StringPredicate) bool {
return false
}
func (obj *LinkAggregationMetadata) GetField(key string) (interface{}, error) {
if i, err := obj.GetFieldInt64(key); err == nil {
return i, nil
}
if b, err := obj.GetFieldBool(key); err == nil {
return b, nil
}
return nil, getter.ErrFieldNotFound
}
func (obj *Metadata) GetFieldBool(key string) (bool, error) {
return false, getter.ErrFieldNotFound
}
func (obj *Metadata) GetFieldInt64(key string) (int64, error) {
switch key {
case "PVID":
return int64(obj.PVID), nil
case "VIDUsageDigest":
return int64(obj.VIDUsageDigest), nil
case "ManagementVID":
return int64(obj.ManagementVID), nil
}
return 0, getter.ErrFieldNotFound
}
func (obj *Metadata) GetFieldString(key string) (string, error) {
switch key {
case "Description":
return string(obj.Description), nil
case "ChassisID":
return string(obj.ChassisID), nil
case "ChassisIDType":
return string(obj.ChassisIDType), nil
case "SysName":
return string(obj.SysName), nil
case "MgmtAddress":
return string(obj.MgmtAddress), nil
case "PortID":
return string(obj.PortID), nil
case "PortIDType":
return string(obj.PortIDType), nil
}
return "", getter.ErrFieldNotFound
}
func (obj *Metadata) GetFieldKeys() []string {
return []string{
"Description",
"ChassisID",
"ChassisIDType",
"SysName",
"MgmtAddress",
"PVID",
"VIDUsageDigest",
"ManagementVID",
"PortID",
"PortIDType",
"LinkAggregation",
"VLANNames",
"PPVIDs",
}
}
func (obj *Metadata) MatchBool(key string, predicate getter.BoolPredicate) bool {
first := key
index := strings.Index(key, ".")
if index != -1 {
first = key[:index]
}
switch first {
case "LinkAggregation":
if index != -1 && obj.LinkAggregation != nil {
return obj.LinkAggregation.MatchBool(key[index+1:], predicate)
}
case "VLANNames":
if index != -1 {
for _, obj := range obj.VLANNames {
if obj.MatchBool(key[index+1:], predicate) {
return true
}
}
}
case "PPVIDs":
if index != -1 {
for _, obj := range obj.PPVIDs {
if obj.MatchBool(key[index+1:], predicate) {
return true
}
}
}
}
return false
}
func (obj *Metadata) MatchInt64(key string, predicate getter.Int64Predicate) bool {
if b, err := obj.GetFieldInt64(key); err == nil {
return predicate(b)
}
first := key
index := strings.Index(key, ".")
if index != -1 {
first = key[:index]
}
switch first {
case "LinkAggregation":
if index != -1 && obj.LinkAggregation != nil {
return obj.LinkAggregation.MatchInt64(key[index+1:], predicate)
}
case "VLANNames":
if index != -1 {
for _, obj := range obj.VLANNames {
if obj.MatchInt64(key[index+1:], predicate) {
return true
}
}
}
case "PPVIDs":
if index != -1 {
for _, obj := range obj.PPVIDs {
if obj.MatchInt64(key[index+1:], predicate) {
return true
}
}
}
}
return false
}
func (obj *Metadata) MatchString(key string, predicate getter.StringPredicate) bool {
if b, err := obj.GetFieldString(key); err == nil {
return predicate(b)
}
first := key
index := strings.Index(key, ".")
if index != -1 {
first = key[:index]
}
switch first {
case "LinkAggregation":
if index != -1 && obj.LinkAggregation != nil {
return obj.LinkAggregation.MatchString(key[index+1:], predicate)
}
case "VLANNames":
if index != -1 {
for _, obj := range obj.VLANNames {
if obj.MatchString(key[index+1:], predicate) {
return true
}
}
}
case "PPVIDs":
if index != -1 {
for _, obj := range obj.PPVIDs {
if obj.MatchString(key[index+1:], predicate) {
return true
}
}
}
}
return false
}
func (obj *Metadata) GetField(key string) (interface{}, error) {
if s, err := obj.GetFieldString(key); err == nil {
return s, nil
}
if i, err := obj.GetFieldInt64(key); err == nil {
return i, nil
}
first := key
index := strings.Index(key, ".")
if index != -1 {
first = key[:index]
}
switch first {
case "LinkAggregation":
if obj.LinkAggregation != nil {
if index != -1 {
return obj.LinkAggregation.GetField(key[index+1:])
} else {
return obj.LinkAggregation, nil
}
}
case "VLANNames":
if obj.VLANNames != nil {
if index != -1 {
var results []interface{}
for _, obj := range obj.VLANNames {
if field, err := obj.GetField(key[index+1:]); err == nil {
results = append(results, field)
}
}
return results, nil
} else {
var results []interface{}
for _, obj := range obj.VLANNames {
results = append(results, obj)
}
return results, nil
}
}
case "PPVIDs":
if obj.PPVIDs != nil {
if index != -1 {
var results []interface{}
for _, obj := range obj.PPVIDs {
if field, err := obj.GetField(key[index+1:]); err == nil {
results = append(results, field)
}
}
return results, nil
} else {
var results []interface{}
for _, obj := range obj.PPVIDs {
results = append(results, obj)
}
return results, nil
}
}
}
return nil, getter.ErrFieldNotFound
}
func (obj *PPVIDMetadata) GetFieldBool(key string) (bool, error) {
switch key {
case "Enabled":
return obj.Enabled, nil
case "Supported":
return obj.Supported, nil
}
return false, getter.ErrFieldNotFound
}
func (obj *PPVIDMetadata) GetFieldInt64(key string) (int64, error) {
switch key {
case "ID":
return int64(obj.ID), nil
}
return 0, getter.ErrFieldNotFound
}
func (obj *PPVIDMetadata) GetFieldString(key string) (string, error) {
return "", getter.ErrFieldNotFound
}
func (obj *PPVIDMetadata) GetFieldKeys() []string {
return []string{
"Enabled",
"ID",
"Supported",
}
}
func (obj *PPVIDMetadata) MatchBool(key string, predicate getter.BoolPredicate) bool {
if b, err := obj.GetFieldBool(key); err == nil {
return predicate(b)
}
return false
}
func (obj *PPVIDMetadata) MatchInt64(key string, predicate getter.Int64Predicate) bool {
if b, err := obj.GetFieldInt64(key); err == nil {
return predicate(b)
}
return false
}
func (obj *PPVIDMetadata) MatchString(key string, predicate getter.StringPredicate) bool {
return false
}
func (obj *PPVIDMetadata) GetField(key string) (interface{}, error) {
if i, err := obj.GetFieldInt64(key); err == nil {
return i, nil
}
if b, err := obj.GetFieldBool(key); err == nil {
return b, nil
}
return nil, getter.ErrFieldNotFound
}
func (obj *VLANNameMetadata) GetFieldBool(key string) (bool, error) {
return false, getter.ErrFieldNotFound
}
func (obj *VLANNameMetadata) GetFieldInt64(key string) (int64, error) {
switch key {
case "ID":
return int64(obj.ID), nil
}
return 0, getter.ErrFieldNotFound
}
func (obj *VLANNameMetadata) GetFieldString(key string) (string, error) {
switch key {
case "Name":
return string(obj.Name), nil
}
return "", getter.ErrFieldNotFound
}
func (obj *VLANNameMetadata) GetFieldKeys() []string {
return []string{
"ID",
"Name",
}
}
func (obj *VLANNameMetadata) MatchBool(key string, predicate getter.BoolPredicate) bool {
return false
}
func (obj *VLANNameMetadata) MatchInt64(key string, predicate getter.Int64Predicate) bool {
if b, err := obj.GetFieldInt64(key); err == nil {
return predicate(b)
}
return false
}
func (obj *VLANNameMetadata) MatchString(key string, predicate getter.StringPredicate) bool {
if b, err := obj.GetFieldString(key); err == nil {
return predicate(b)
}
return false
}
func (obj *VLANNameMetadata) GetField(key string) (interface{}, error) {
if s, err := obj.GetFieldString(key); err == nil {
return s, nil
}
if i, err := obj.GetFieldInt64(key); err == nil {
return i, nil
}
return nil, getter.ErrFieldNotFound
}
func init() {
strings.Index("", ".")
}
| {
"content_hash": "10f487c82315aa392a741cc443cd6969",
"timestamp": "",
"source": "github",
"line_count": 411,
"max_line_length": 100,
"avg_line_length": 21.676399026763992,
"alnum_prop": 0.662476147715793,
"repo_name": "skydive-project/skydive",
"id": "b535be3bb450f9f86b29d5a3c60aaaa90016319b",
"size": "8943",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "topology/probes/lldp/metadata_gendecoder.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "41318"
},
{
"name": "CSS",
"bytes": "61325"
},
{
"name": "Dockerfile",
"bytes": "1205"
},
{
"name": "Go",
"bytes": "2511767"
},
{
"name": "HTML",
"bytes": "7140"
},
{
"name": "JavaScript",
"bytes": "997192"
},
{
"name": "Jinja",
"bytes": "650"
},
{
"name": "Makefile",
"bytes": "29947"
},
{
"name": "Mustache",
"bytes": "5940"
},
{
"name": "Nix",
"bytes": "818"
},
{
"name": "Python",
"bytes": "119288"
},
{
"name": "Roff",
"bytes": "6623"
},
{
"name": "Shell",
"bytes": "103957"
},
{
"name": "TypeScript",
"bytes": "28054"
}
],
"symlink_target": ""
} |
alert("Editado");
console.log("Cambios en el archivo")
| {
"content_hash": "177c7742bc8e17f3c3693f496870ad1b",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 36,
"avg_line_length": 27.5,
"alnum_prop": 0.7272727272727273,
"repo_name": "juanpm32/github-para-desarrolladores",
"id": "cff2838fef267dbec78dd649abe266e4d59eb09e",
"size": "55",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mi_archivo.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "55"
}
],
"symlink_target": ""
} |
layout: page
title: Sobre mi
permalink: /about/
---
Soy un desarrollador iOS y un apasionado de la informática en general. He cacharreado con todo lo que me ha llegado a las manos: Android, PHP, Pascal, C#, ABAP, Arduino, Ruby, RoR, Node.js y iOS de lo que estoy profundamente enamorado.
Trabajo en Fever Labs.
Este blog está basado en [Jekill](http://jekyllrb.com/), usando el tema [Pixyll](https://github.com/johnotander/pixyll) y hospedado en [github](https://github.com/PabloLerma/PabloLerma.github.io).
| {
"content_hash": "c0a6b5bd0b06d0b0fce3116865d63947",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 235,
"avg_line_length": 56.666666666666664,
"alnum_prop": 0.7568627450980392,
"repo_name": "PabloLerma/PabloLerma.github.io",
"id": "ce2b7b555943b2d53a2a930da95ec40e29713f0f",
"size": "516",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "about.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "11325"
},
{
"name": "Makefile",
"bytes": "67"
},
{
"name": "Ruby",
"bytes": "236"
},
{
"name": "SCSS",
"bytes": "30599"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-samples-aspectj-jc</artifactId>
<version>4.0.3.CI-SNAPSHOT</version>
<name>spring-security-samples-aspectj-jc</name>
<description>spring-security-samples-aspectj-jc</description>
<url>http://spring.io/spring-security</url>
<organization>
<name>spring.io</name>
<url>http://spring.io/</url>
</organization>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rwinch</id>
<name>Rob Winch</name>
<email>rwinch@gopivotal.com</email>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-projects/spring-security</connection>
<developerConnection>scm:git:git://github.com/spring-projects/spring-security</developerConnection>
<url>https://github.com/spring-projects/spring-security</url>
</scm>
<repositories>
<repository>
<id>spring-snapshot</id>
<url>https://repo.spring.io/snapshot</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.3.CI-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.0.3.CI-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.4</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-aspects</artifactId>
<version>4.0.3.CI-SNAPSHOT</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<version>1.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.1.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "2b0ccaafd3d01600c897fc44b27eaf69",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 204,
"avg_line_length": 32.13076923076923,
"alnum_prop": 0.6485515920517118,
"repo_name": "xingguang2013/spring-security",
"id": "e632470dd706df84feca69ae3c530c12205bf917",
"size": "4177",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "samples/aspectj-jc/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "2756"
},
{
"name": "Groovy",
"bytes": "669923"
},
{
"name": "HTML",
"bytes": "468"
},
{
"name": "Java",
"bytes": "5119444"
},
{
"name": "PLSQL",
"bytes": "3177"
},
{
"name": "Python",
"bytes": "129"
},
{
"name": "Shell",
"bytes": "234"
},
{
"name": "XSLT",
"bytes": "2344"
}
],
"symlink_target": ""
} |
#ifndef FLOKI_H
#define FLOKI_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdbool.h>
#include <setjmp.h>
#include "strbuf.h"
#include "binbuf.h"
#include "array.h"
#include "hashmap.h"
#include "util.h"
#include "lex.h"
#include "tokensrc.h"
#include "value.h"
#include "json.h"
#include "parse-unit.h"
#include "unit-idx.h"
#include "parse-expr.h"
#include "parse-routine.h"
#include "symtab-global.h"
#include "symtab-local.h"
#include "compile.h"
#include "compile-fvm.h"
#endif
| {
"content_hash": "784ecd0759857f68e6550e6d199414f4",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 26,
"avg_line_length": 15.594594594594595,
"alnum_prop": 0.6949740034662045,
"repo_name": "jhawcroft/floki",
"id": "d5c6b5eccf2e38f9fbe2184d8770e54ace553f27",
"size": "1687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/bootstrap/floki.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "35526"
},
{
"name": "C++",
"bytes": "10944"
},
{
"name": "CSS",
"bytes": "4907"
},
{
"name": "HTML",
"bytes": "4699"
},
{
"name": "Visual Basic",
"bytes": "7229"
}
],
"symlink_target": ""
} |
/*
* Author: atotic
* Created on Mar 23, 2004
* License: Common Public License v1.0
*/
package com.jetbrains.python.debugger.pydev;
import com.google.common.collect.Maps;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.BaseOutputReader;
import com.intellij.xdebugger.frame.XValueChildrenList;
import com.jetbrains.python.console.pydev.PydevCompletionVariant;
import com.jetbrains.python.debugger.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
public class RemoteDebugger implements ProcessDebugger {
private static final int RESPONSE_TIMEOUT = 60000;
private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.pydev.remote.RemoteDebugger");
private static final String LOCAL_VERSION = "0.1";
public static final String TEMP_VAR_PREFIX = "__py_debug_temp_var_";
private static final SecureRandom ourRandom = new SecureRandom();
private final IPyDebugProcess myDebugProcess;
@NotNull
private final ServerSocket myServerSocket;
private final int myConnectionTimeout;
private final Object mySocketObject = new Object(); // for synchronization on socket
private Socket mySocket;
private volatile boolean myConnected = false;
private int mySequence = -1;
private final Object mySequenceObject = new Object(); // for synchronization on mySequence
private final Map<String, PyThreadInfo> myThreads = new ConcurrentHashMap<String, PyThreadInfo>();
private final Map<Integer, ProtocolFrame> myResponseQueue = new HashMap<Integer, ProtocolFrame>();
private final TempVarsHolder myTempVars = new TempVarsHolder();
private Map<Pair<String, Integer>, String> myTempBreakpoints = Maps.newHashMap();
private final List<RemoteDebuggerCloseListener> myCloseListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private DebuggerReader myDebuggerReader;
public RemoteDebugger(final IPyDebugProcess debugProcess, @NotNull final ServerSocket serverSocket, final int timeout) {
myDebugProcess = debugProcess;
myServerSocket = serverSocket;
myConnectionTimeout = timeout;
}
public IPyDebugProcess getDebugProcess() {
return myDebugProcess;
}
@Override
public boolean isConnected() {
return myConnected;
}
@Override
public void waitForConnect() throws Exception {
try {
//noinspection SocketOpenedButNotSafelyClosed
myServerSocket.setSoTimeout(myConnectionTimeout);
synchronized (mySocketObject) {
mySocket = myServerSocket.accept();
myConnected = true;
}
}
finally {
//it is closed in close() method on process termination
}
if (myConnected) {
try {
myDebuggerReader = createReader();
}
catch (Exception e) {
synchronized (mySocketObject) {
mySocket.close();
}
throw e;
}
}
}
@Override
public String handshake() throws PyDebuggerException {
final VersionCommand command = new VersionCommand(this, LOCAL_VERSION, SystemInfo.isUnix ? "UNIX" : "WIN");
command.execute();
String version = command.getRemoteVersion();
if (version != null) {
version = version.trim();
}
return version;
}
@Override
public PyDebugValue evaluate(final String threadId,
final String frameId,
final String expression, final boolean execute) throws PyDebuggerException {
return evaluate(threadId, frameId, expression, execute, true);
}
@Override
public PyDebugValue evaluate(final String threadId,
final String frameId,
final String expression,
final boolean execute,
boolean trimResult)
throws PyDebuggerException {
final EvaluateCommand command = new EvaluateCommand(this, threadId, frameId, expression, execute, trimResult);
command.execute();
return command.getValue();
}
@Override
public void consoleExec(String threadId, String frameId, String expression, PyDebugCallback<String> callback) {
final ConsoleExecCommand command = new ConsoleExecCommand(this, threadId, frameId, expression);
command.execute(callback);
}
@Override
public XValueChildrenList loadFrame(final String threadId, final String frameId) throws PyDebuggerException {
final GetFrameCommand command = new GetFrameCommand(this, threadId, frameId);
command.execute();
return command.getVariables();
}
// todo: don't generate temp variables for qualified expressions - just split 'em
@Override
public XValueChildrenList loadVariable(final String threadId, final String frameId, final PyDebugValue var) throws PyDebuggerException {
setTempVariable(threadId, frameId, var);
final GetVariableCommand command = new GetVariableCommand(this, threadId, frameId, var);
command.execute();
return command.getVariables();
}
@Override
public ArrayChunk loadArrayItems(String threadId,
String frameId,
PyDebugValue var,
int rowOffset,
int colOffset,
int rows,
int cols,
String format) throws PyDebuggerException {
final GetArrayCommand command = new GetArrayCommand(this, threadId, frameId, var, rowOffset, colOffset, rows, cols, format);
command.execute();
return command.getArray();
}
@Override
public void loadReferrers(final String threadId,
final String frameId,
final PyReferringObjectsValue var,
final PyDebugCallback<XValueChildrenList> callback) {
RunCustomOperationCommand cmd = new GetReferrersCommand(this, threadId, frameId, var);
cmd.execute(new PyDebugCallback<List<PyDebugValue>>() {
@Override
public void ok(List<PyDebugValue> value) {
XValueChildrenList list = new XValueChildrenList();
for (PyDebugValue v : value) {
list.add(v);
}
callback.ok(list);
}
@Override
public void error(PyDebuggerException exception) {
callback.error(exception);
}
});
}
@Override
public PyDebugValue changeVariable(final String threadId, final String frameId, final PyDebugValue var, final String value)
throws PyDebuggerException {
setTempVariable(threadId, frameId, var);
return doChangeVariable(threadId, frameId, var.getEvaluationExpression(), value);
}
private PyDebugValue doChangeVariable(final String threadId, final String frameId, final String varName, final String value)
throws PyDebuggerException {
final ChangeVariableCommand command = new ChangeVariableCommand(this, threadId, frameId, varName, value);
command.execute();
return command.getNewValue();
}
@Override
@Nullable
public String loadSource(String path) {
LoadSourceCommand command = new LoadSourceCommand(this, path);
try {
command.execute();
return command.getContent();
}
catch (PyDebuggerException e) {
return "#Couldn't load source of file " + path;
}
}
private void cleanUp() {
myThreads.clear();
myResponseQueue.clear();
synchronized (mySequenceObject) {
mySequence = -1;
}
myTempVars.clear();
}
// todo: change variable in lists doesn't work - either fix in pydevd or format var name appropriately
private void setTempVariable(final String threadId, final String frameId, final PyDebugValue var) {
final PyDebugValue topVar = var.getTopParent();
if (!myDebugProcess.canSaveToTemp(topVar.getName())) {
return;
}
if (myTempVars.contains(threadId, frameId, topVar.getTempName())) {
return;
}
topVar.setTempName(generateTempName());
try {
doChangeVariable(threadId, frameId, topVar.getTempName(), topVar.getName());
myTempVars.put(threadId, frameId, topVar.getTempName());
}
catch (PyDebuggerException e) {
LOG.error(e);
topVar.setTempName(null);
}
}
private void clearTempVariables(final String threadId) {
final Map<String, Set<String>> threadVars = myTempVars.get(threadId);
if (threadVars == null || threadVars.size() == 0) return;
for (Map.Entry<String, Set<String>> entry : threadVars.entrySet()) {
final Set<String> frameVars = entry.getValue();
if (frameVars == null || frameVars.size() == 0) continue;
final String expression = "del " + StringUtil.join(frameVars, ",");
try {
evaluate(threadId, entry.getKey(), expression, true);
}
catch (PyDebuggerException e) {
LOG.error(e);
}
}
myTempVars.clear(threadId);
}
private static String generateTempName() {
return TEMP_VAR_PREFIX + ourRandom.nextInt(Integer.MAX_VALUE);
}
@Override
public Collection<PyThreadInfo> getThreads() {
return Collections.unmodifiableCollection(new ArrayList<PyThreadInfo>(myThreads.values()));
}
int getNextSequence() {
synchronized (mySequenceObject) {
mySequence += 2;
return mySequence;
}
}
void placeResponse(final int sequence, final ProtocolFrame response) {
synchronized (myResponseQueue) {
if (response == null || myResponseQueue.containsKey(sequence)) {
myResponseQueue.put(sequence, response);
}
if (response != null) {
myResponseQueue.notifyAll();
}
}
}
@Nullable
ProtocolFrame waitForResponse(final int sequence) {
ProtocolFrame response;
long until = System.currentTimeMillis() + RESPONSE_TIMEOUT;
synchronized (myResponseQueue) {
do {
try {
myResponseQueue.wait(1000);
}
catch (InterruptedException ignore) {
}
response = myResponseQueue.get(sequence);
}
while (response == null && isConnected() && System.currentTimeMillis() < until);
myResponseQueue.remove(sequence);
}
return response;
}
@Override
public void execute(@NotNull final AbstractCommand command) {
if (command instanceof ResumeOrStepCommand) {
final String threadId = ((ResumeOrStepCommand)command).getThreadId();
clearTempVariables(threadId);
}
try {
command.execute();
}
catch (PyDebuggerException e) {
LOG.error(e);
}
}
boolean sendFrame(final ProtocolFrame frame) {
logFrame(frame, true);
try {
final byte[] packed = frame.pack();
synchronized (mySocketObject) {
final OutputStream os = mySocket.getOutputStream();
os.write(packed);
os.flush();
return true;
}
}
catch (SocketException se) {
disconnect();
fireCommunicationError();
}
catch (IOException e) {
LOG.error(e);
}
return false;
}
private static void logFrame(ProtocolFrame frame, boolean out) {
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("%1$tH:%1$tM:%1$tS.%1$tL %2$s %3$s\n", new Date(), (out ? "<<<" : ">>>"), frame));
}
}
@Override
public void suspendAllThreads() {
for (PyThreadInfo thread : getThreads()) {
suspendThread(thread.getId());
}
}
@Override
public void suspendThread(String threadId) {
final SuspendCommand command = new SuspendCommand(this, threadId);
execute(command);
}
@Override
public void close() {
if (!myServerSocket.isClosed()) {
try {
myServerSocket.close();
}
catch (IOException e) {
LOG.warn("Error closing socket", e);
}
}
if (myDebuggerReader != null) {
myDebuggerReader.stop();
}
fireCloseEvent();
}
@Override
public void disconnect() {
synchronized (mySocketObject) {
myConnected = false;
if (mySocket != null && !mySocket.isClosed()) {
try {
mySocket.close();
}
catch (IOException ignore) {
}
}
}
cleanUp();
}
@Override
public void run() throws PyDebuggerException {
new RunCommand(this).execute();
}
@Override
public void smartStepInto(String threadId, String functionName) {
final SmartStepIntoCommand command = new SmartStepIntoCommand(this, threadId, functionName);
execute(command);
}
@Override
public void resumeOrStep(String threadId, ResumeOrStepCommand.Mode mode) {
final ResumeOrStepCommand command = new ResumeOrStepCommand(this, threadId, mode);
execute(command);
}
@Override
public void setTempBreakpoint(String type, String file, int line) {
final SetBreakpointCommand command =
new SetBreakpointCommand(this, type, file, line);
execute(command); // set temp. breakpoint
myTempBreakpoints.put(Pair.create(file, line), type);
}
@Override
public void removeTempBreakpoint(String file, int line) {
String type = myTempBreakpoints.get(Pair.create(file, line));
if (type != null) {
final RemoveBreakpointCommand command = new RemoveBreakpointCommand(this, type, file, line);
execute(command); // remove temp. breakpoint
}
else {
LOG.error("Temp breakpoint not found for " + file + ":" + line);
}
}
@Override
public void setBreakpoint(String typeId, String file, int line, String condition, String logExpression) {
final SetBreakpointCommand command =
new SetBreakpointCommand(this, typeId, file, line,
condition,
logExpression);
execute(command);
}
@Override
public void setBreakpointWithFuncName(String typeId, String file, int line, String condition, String logExpression, String funcName) {
final SetBreakpointCommand command =
new SetBreakpointCommand(this, typeId, file, line,
condition,
logExpression,
funcName);
execute(command);
}
@Override
public void removeBreakpoint(String typeId, String file, int line) {
final RemoveBreakpointCommand command =
new RemoveBreakpointCommand(this, typeId, file, line);
execute(command);
}
private DebuggerReader createReader() throws IOException {
synchronized (mySocketObject) {
//noinspection IOResourceOpenedButNotSafelyClosed
return new DebuggerReader(mySocket.getInputStream());
}
}
private class DebuggerReader extends BaseOutputReader {
private StringBuilder myTextBuilder = new StringBuilder();
private DebuggerReader(final InputStream stream) throws IOException {
super(stream, CharsetToolkit.UTF8_CHARSET, SleepingPolicy.BLOCKING); //TODO: correct encoding?
start(getClass().getName());
}
protected void doRun() {
try {
while (true) {
boolean read = readAvailableBlocking();
if (!read) {
break;
}
else {
if (isStopped) {
break;
}
TimeoutUtil.sleep(mySleepingPolicy.getTimeToSleep(true));
}
}
}
catch (Exception e) {
fireCommunicationError();
}
finally {
close();
fireExitEvent();
}
}
private void processResponse(final String line) {
try {
final ProtocolFrame frame = new ProtocolFrame(line);
logFrame(frame, false);
if (AbstractThreadCommand.isThreadCommand(frame.getCommand())) {
processThreadEvent(frame);
}
else if (AbstractCommand.isWriteToConsole(frame.getCommand())) {
writeToConsole(ProtocolParser.parseIo(frame.getPayload()));
}
else if (AbstractCommand.isExitEvent(frame.getCommand())) {
fireCommunicationError();
}
else if (AbstractCommand.isCallSignatureTrace(frame.getCommand())) {
recordCallSignature(ProtocolParser.parseCallSignature(frame.getPayload()));
}
else if (AbstractCommand.isConcurrencyEvent(frame.getCommand())) {
recordConcurrencyEvent(ProtocolParser.parseConcurrencyEvent(frame.getPayload(), myDebugProcess.getPositionConverter()));
}
else {
placeResponse(frame.getSequence(), frame);
}
}
catch (Throwable t) {
// shouldn't interrupt reader thread
LOG.error(t);
}
}
private void recordCallSignature(PySignature signature) {
myDebugProcess.recordSignature(signature);
}
private void recordConcurrencyEvent(PyConcurrencyEvent event) {
myDebugProcess.recordLogEvent(event);
}
// todo: extract response processing
private void processThreadEvent(ProtocolFrame frame) throws PyDebuggerException {
switch (frame.getCommand()) {
case AbstractCommand.CREATE_THREAD: {
final PyThreadInfo thread = parseThreadEvent(frame);
if (!thread.isPydevThread()) { // ignore pydevd threads
myThreads.put(thread.getId(), thread);
}
break;
}
case AbstractCommand.SUSPEND_THREAD: {
final PyThreadInfo event = parseThreadEvent(frame);
PyThreadInfo thread = myThreads.get(event.getId());
if (thread == null) {
LOG.error("Trying to stop on non-existent thread: " + event.getId() + ", " + event.getStopReason() + ", " + event.getMessage());
myThreads.put(event.getId(), event);
thread = event;
}
thread.updateState(PyThreadInfo.State.SUSPENDED, event.getFrames());
thread.setStopReason(event.getStopReason());
thread.setMessage(event.getMessage());
myDebugProcess.threadSuspended(thread);
break;
}
case AbstractCommand.RESUME_THREAD: {
final String id = ProtocolParser.getThreadId(frame.getPayload());
final PyThreadInfo thread = myThreads.get(id);
if (thread != null) {
thread.updateState(PyThreadInfo.State.RUNNING, null);
myDebugProcess.threadResumed(thread);
}
break;
}
case AbstractCommand.KILL_THREAD: {
final String id = frame.getPayload();
final PyThreadInfo thread = myThreads.get(id);
if (thread != null) {
thread.updateState(PyThreadInfo.State.KILLED, null);
myThreads.remove(id);
}
if (myDebugProcess.getSession().getCurrentPosition() == null) {
for (PyThreadInfo threadInfo : myThreads.values()) {
// notify UI of suspended threads left in debugger if one thread finished its work
if ((threadInfo != null) && (threadInfo.getState() == PyThreadInfo.State.SUSPENDED)) {
myDebugProcess.threadResumed(threadInfo);
myDebugProcess.threadSuspended(threadInfo);
}
}
}
break;
}
case AbstractCommand.SHOW_CONSOLE: {
final PyThreadInfo event = parseThreadEvent(frame);
PyThreadInfo thread = myThreads.get(event.getId());
if (thread == null) {
myThreads.put(event.getId(), event);
thread = event;
}
thread.updateState(PyThreadInfo.State.SUSPENDED, event.getFrames());
thread.setStopReason(event.getStopReason());
thread.setMessage(event.getMessage());
myDebugProcess.showConsole(thread);
break;
}
}
}
private PyThreadInfo parseThreadEvent(ProtocolFrame frame) throws PyDebuggerException {
return ProtocolParser.parseThread(frame.getPayload(), myDebugProcess.getPositionConverter());
}
@NotNull
@Override
protected Future<?> executeOnPooledThread(@NotNull Runnable runnable) {
return ApplicationManager.getApplication().executeOnPooledThread(runnable);
}
@Override
protected void close() {
try {
super.close();
}
catch (IOException e) {
LOG.error(e);
}
}
@Override
public void stop() {
super.stop();
close();
}
@Override
protected void onTextAvailable(@NotNull String text) {
myTextBuilder.append(text);
if (text.contains("\n")) {
String[] lines = myTextBuilder.toString().split("\n");
myTextBuilder = new StringBuilder();
if (!text.endsWith("\n")) {
myTextBuilder.append(lines[lines.length - 1]);
lines = Arrays.copyOfRange(lines, 0, lines.length - 1);
}
for (String line : lines) {
processResponse(line + "\n");
}
}
}
}
private void writeToConsole(PyIo io) {
ConsoleViewContentType contentType;
if (io.getCtx() == 2) {
contentType = ConsoleViewContentType.ERROR_OUTPUT;
}
else {
contentType = ConsoleViewContentType.NORMAL_OUTPUT;
}
myDebugProcess.printToConsole(io.getText(), contentType);
}
private static class TempVarsHolder {
private final Map<String, Map<String, Set<String>>> myData = new HashMap<String, Map<String, Set<String>>>();
public boolean contains(final String threadId, final String frameId, final String name) {
final Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars == null) return false;
final Set<String> frameVars = threadVars.get(frameId);
if (frameVars == null) return false;
return frameVars.contains(name);
}
private void put(final String threadId, final String frameId, final String name) {
Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars == null) myData.put(threadId, (threadVars = new HashMap<String, Set<String>>()));
Set<String> frameVars = threadVars.get(frameId);
if (frameVars == null) threadVars.put(frameId, (frameVars = new HashSet<String>()));
frameVars.add(name);
}
private Map<String, Set<String>> get(final String threadId) {
return myData.get(threadId);
}
private void clear() {
myData.clear();
}
private void clear(final String threadId) {
final Map<String, Set<String>> threadVars = myData.get(threadId);
if (threadVars != null) {
threadVars.clear();
}
}
}
public void addCloseListener(RemoteDebuggerCloseListener listener) {
myCloseListeners.add(listener);
}
public void removeCloseListener(RemoteDebuggerCloseListener listener) {
myCloseListeners.remove(listener);
}
@Override
public List<PydevCompletionVariant> getCompletions(String threadId, String frameId, String prefix) {
final GetCompletionsCommand command = new GetCompletionsCommand(this, threadId, frameId, prefix);
execute(command);
return command.getCompletions();
}
@Override
public void addExceptionBreakpoint(ExceptionBreakpointCommandFactory factory) {
execute(factory.createAddCommand(this));
}
@Override
public void removeExceptionBreakpoint(ExceptionBreakpointCommandFactory factory) {
execute(factory.createRemoveCommand(this));
}
private void fireCloseEvent() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.closed();
}
}
private void fireCommunicationError() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.communicationError();
}
}
private void fireExitEvent() {
for (RemoteDebuggerCloseListener listener : myCloseListeners) {
listener.detached();
}
}
}
| {
"content_hash": "148a0565caf5725808223a68976a9a0a",
"timestamp": "",
"source": "github",
"line_count": 765,
"max_line_length": 140,
"avg_line_length": 31.762091503267975,
"alnum_prop": 0.6570088073092436,
"repo_name": "MichaelNedzelsky/intellij-community",
"id": "7778a06a473048762e05ee6b48ac63f317defcca",
"size": "24298",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "python/pydevSrc/com/jetbrains/python/debugger/pydev/RemoteDebugger.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "63554"
},
{
"name": "C",
"bytes": "214994"
},
{
"name": "C#",
"bytes": "1538"
},
{
"name": "C++",
"bytes": "190765"
},
{
"name": "CSS",
"bytes": "164277"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Cucumber",
"bytes": "14382"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "FLUX",
"bytes": "57"
},
{
"name": "Groff",
"bytes": "35232"
},
{
"name": "Groovy",
"bytes": "2361511"
},
{
"name": "HTML",
"bytes": "1755118"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "153250242"
},
{
"name": "JavaScript",
"bytes": "141020"
},
{
"name": "Kotlin",
"bytes": "1292120"
},
{
"name": "Lex",
"bytes": "166321"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "88100"
},
{
"name": "Objective-C",
"bytes": "28878"
},
{
"name": "Perl6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6570"
},
{
"name": "Python",
"bytes": "23157111"
},
{
"name": "Ruby",
"bytes": "1213"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "64014"
},
{
"name": "Smalltalk",
"bytes": "64"
},
{
"name": "TeX",
"bytes": "62325"
},
{
"name": "TypeScript",
"bytes": "6152"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
/* Desc: A persepective X11 OpenGL Camera Sensor
* Author: Nate Koenig
* Date: 15 July 2003
*/
#ifndef _DEPTHCAMERASENSOR_HH_
#define _DEPTHCAMERASENSOR_HH_
#include <string>
#include "gazebo/sensors/Sensor.hh"
#include "gazebo/msgs/MessageTypes.hh"
#include "gazebo/rendering/RenderTypes.hh"
namespace gazebo
{
/// \ingroup gazebo_sensors
/// \brief Sensors namespace
namespace sensors
{
/// \class DepthCameraSensor DepthCameraSensor.hh sensors/sensors.hh
/// \addtogroup gazebo_sensors Sensors
/// \brief A set of sensor classes, functions, and definitions
/// \{
/// \brief Depth camera sensor
/// This sensor is used for simulating standard monocular cameras
class DepthCameraSensor : public Sensor
{
/// \brief Constructor
public: DepthCameraSensor();
/// \brief Destructor
public: virtual ~DepthCameraSensor();
/// \brief Load the sensor with SDF parameters
/// \param[in] _sdf SDF Sensor parameters
/// \param[in] _worldName Name of world to load from
protected: virtual void Load(const std::string &_worldName,
sdf::ElementPtr &_sdf);
/// \brief Load the sensor with default parameters
/// \param[in] _worldName Name of world to load from
protected: virtual void Load(const std::string &_worldName);
/// \brief Initialize the camera
protected: virtual void Init();
/// \brief Update the sensor information
/// \param[in] _force True if update is forced, false if not
protected: virtual void UpdateImpl(bool _force);
/// Finalize the camera
protected: virtual void Fini();
/// \brief Set whether the sensor is active or not
/// \param[in] _value True if active, false if not
public: virtual void SetActive(bool _value);
/// \brief Returns a pointer to the rendering::DepthCamera
/// \return Depth Camera pointer
public: rendering::DepthCameraPtr GetDepthCamera() const
{return this->camera;}
/// \brief Saves an image frame of depth camera sensor to file
/// \param[in] Name of file to save as
/// \return True if saved, false if not
public: bool SaveFrame(const std::string &_filename);
private: rendering::DepthCameraPtr camera;
private: rendering::ScenePtr scene;
};
/// \}
}
}
#endif
| {
"content_hash": "a374eabc7301bbf4707ec4dd01201c07",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 72,
"avg_line_length": 30.329113924050635,
"alnum_prop": 0.6515025041736227,
"repo_name": "jonbinney/gazebo_ros_wrapper",
"id": "167a9fda0b5fbe449ca2b7e06c12a4ec8b9a1f7a",
"size": "3021",
"binary": false,
"copies": "1",
"ref": "refs/heads/indigo-devel",
"path": "gazebo/sensors/DepthCameraSensor.hh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "565866"
},
{
"name": "C++",
"bytes": "8280611"
},
{
"name": "CSS",
"bytes": "12592"
},
{
"name": "JavaScript",
"bytes": "25255"
}
],
"symlink_target": ""
} |
class RbenvVars < Formula
desc "Safely sets global and per-project environment variables"
homepage "https://github.com/sstephenson/rbenv-vars"
url "https://github.com/sstephenson/rbenv-vars/archive/v1.2.0.tar.gz"
sha256 "9e6a5726aad13d739456d887a43c220ba9198e672b32536d41e884c0a54b4ddb"
license "MIT"
revision 1
head "https://github.com/sstephenson/rbenv-vars.git"
bottle :unneeded
depends_on "rbenv"
def install
prefix.install Dir["*"]
end
test do
assert_match "rbenv-vars.bash", shell_output("rbenv hooks exec")
end
end
| {
"content_hash": "0e4818372a858874ecf7924701ca0a2e",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 75,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.7446428571428572,
"repo_name": "maxim-belkin/homebrew-core",
"id": "7f39d8a7e4a5f7e90848b17412f7a0bf24429119",
"size": "560",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "Formula/rbenv-vars.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Perl",
"bytes": "628"
},
{
"name": "Ruby",
"bytes": "8614761"
}
],
"symlink_target": ""
} |
#include <objc/message.h>
#import "CDVCommandQueue.h"
#import "CDVViewController.h"
#import "CDVCommandDelegateImpl.h"
#import "CDVJSON_private.h"
#import "CDVDebug.h"
// Parse JS on the main thread if it's shorter than this.
static const NSInteger JSON_SIZE_FOR_MAIN_THREAD = 4 * 1024; // Chosen arbitrarily.
// Execute multiple commands in one go until this many seconds have passed.
static const double MAX_EXECUTION_TIME = .008; // Half of a 60fps frame.
@interface CDVCommandQueue () {
NSInteger _lastCommandQueueFlushRequestId;
__weak CDVViewController* _viewController;
NSMutableArray* _queue;
NSTimeInterval _startExecutionTime;
}
@end
@implementation CDVCommandQueue
- (BOOL)currentlyExecuting
{
return _startExecutionTime > 0;
}
- (id)initWithViewController:(CDVViewController*)viewController
{
self = [super init];
if (self != nil) {
_viewController = viewController;
_queue = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dispose
{
// TODO(agrieve): Make this a zeroing weak ref once we drop support for 4.3.
_viewController = nil;
}
- (void)resetRequestId
{
_lastCommandQueueFlushRequestId = 0;
}
- (void)enqueueCommandBatch:(NSString*)batchJSON
{
if ([batchJSON length] > 0) {
NSMutableArray* commandBatchHolder = [[NSMutableArray alloc] init];
[_queue addObject:commandBatchHolder];
if ([batchJSON length] < JSON_SIZE_FOR_MAIN_THREAD) {
[commandBatchHolder addObject:[batchJSON cdv_JSONObject]];
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^() {
NSMutableArray* result = [batchJSON cdv_JSONObject];
@synchronized(commandBatchHolder) {
[commandBatchHolder addObject:result];
}
[self performSelectorOnMainThread:@selector(executePending) withObject:nil waitUntilDone:NO];
});
}
}
}
- (void)fetchCommandsFromJs
{
__weak CDVCommandQueue* weakSelf = self;
NSString* js = @"cordova.require('cordova/exec').nativeFetchMessages()";
[_viewController.webViewEngine evaluateJavaScript:js
completionHandler:^(id obj, NSError* error) {
if ((error == nil) && [obj isKindOfClass:[NSString class]]) {
NSString* queuedCommandsJSON = (NSString*)obj;
CDV_EXEC_LOG(@"Exec: Flushed JS->native queue (hadCommands=%d).", [queuedCommandsJSON length] > 0);
[weakSelf enqueueCommandBatch:queuedCommandsJSON];
// this has to be called here now, because fetchCommandsFromJs is now async (previously: synchronous)
[self executePending];
}
}];
}
- (void)executePending
{
// Make us re-entrant-safe.
if (_startExecutionTime > 0) {
return;
}
@try {
_startExecutionTime = [NSDate timeIntervalSinceReferenceDate];
while ([_queue count] > 0) {
NSMutableArray* commandBatchHolder = _queue[0];
NSMutableArray* commandBatch = nil;
@synchronized(commandBatchHolder) {
// If the next-up command is still being decoded, wait for it.
if ([commandBatchHolder count] == 0) {
break;
}
commandBatch = commandBatchHolder[0];
}
while ([commandBatch count] > 0) {
@autoreleasepool {
// Execute the commands one-at-a-time.
NSArray* jsonEntry = [commandBatch cdv_dequeue];
if ([commandBatch count] == 0) {
[_queue removeObjectAtIndex:0];
}
CDVInvokedUrlCommand* command = [CDVInvokedUrlCommand commandFromJson:jsonEntry];
CDV_EXEC_LOG(@"Exec(%@): Calling %@.%@", command.callbackId, command.className, command.methodName);
if (![self execute:command]) {
#ifdef DEBUG
NSString* commandJson = [jsonEntry cdv_JSONString];
static NSUInteger maxLogLength = 1024;
NSString* commandString = ([commandJson length] > maxLogLength) ?
[NSString stringWithFormat : @"%@[...]", [commandJson substringToIndex:maxLogLength]] :
commandJson;
DLog(@"FAILED pluginJSON = %@", commandString);
#endif
}
}
// Yield if we're taking too long.
if (([_queue count] > 0) && ([NSDate timeIntervalSinceReferenceDate] - _startExecutionTime > MAX_EXECUTION_TIME)) {
[self performSelector:@selector(executePending) withObject:nil afterDelay:0];
return;
}
}
}
} @finally
{
_startExecutionTime = 0;
}
}
- (BOOL)execute:(CDVInvokedUrlCommand*)command
{
if ((command.className == nil) || (command.methodName == nil)) {
NSLog(@"ERROR: Classname and/or methodName not found for command.");
return NO;
}
// Fetch an instance of this class
CDVPlugin* obj = [_viewController.commandDelegate getCommandInstance:command.className];
if (!([obj isKindOfClass:[CDVPlugin class]])) {
NSLog(@"ERROR: Plugin '%@' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.", command.className);
return NO;
}
BOOL retVal = YES;
double started = [[NSDate date] timeIntervalSince1970] * 1000.0;
// Find the proper selector to call.
NSString* methodName = [NSString stringWithFormat:@"%@:", command.methodName];
SEL normalSelector = NSSelectorFromString(methodName);
if ([obj respondsToSelector:normalSelector]) {
// [obj performSelector:normalSelector withObject:command];
((void (*)(id, SEL, id))objc_msgSend)(obj, normalSelector, command);
} else {
// There's no method to call, so throw an error.
NSLog(@"ERROR: Method '%@' not defined in Plugin '%@'", methodName, command.className);
retVal = NO;
}
double elapsed = [[NSDate date] timeIntervalSince1970] * 1000.0 - started;
if (elapsed > 10) {
NSLog(@"THREAD WARNING: ['%@'] took '%f' ms. Plugin should use a background thread.", command.className, elapsed);
}
return retVal;
}
@end
| {
"content_hash": "61679e2af32c5de38360960f11dcf95b",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 131,
"avg_line_length": 37.46892655367232,
"alnum_prop": 0.5857961399276237,
"repo_name": "soulfly/guinea-pig-smart-bot",
"id": "b6cab53331df992289672e2b3e7657dd9ac7c6c4",
"size": "7422",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "node_modules/quickblox/samples/cordova/video_chat/platforms/ios/CordovaLib/Classes/Public/CDVCommandQueue.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "4485"
}
],
"symlink_target": ""
} |
Experimental Rest API
=====================
Airflow exposes an experimental Rest API. It is available through the webserver. Endpoints are
available at /api/experimental/. Please note that we expect the endpoint definitions to change.
Endpoints
---------
This is a place holder until the swagger definitions are active
* /api/experimental/dags/<DAG_ID>/tasks/<TASK_ID> returns info for a task (GET).
* /api/experimental/dags/<DAG_ID>/dag_runs creates a dag_run for a given dag id (POST).
CLI
-----
For some functions the cli can use the API. To configure the CLI to use the API when available
configure as follows:
.. code-block:: bash
[cli]
api_client = airflow.api.client.json_client
endpoint_url = http://<WEBSERVER>:<PORT>
Authentication
--------------
Authentication for the API is handled separately to the Web Authentication. The default is to not
require any authentication on the API -- i.e. wide open by default. This is not recommended if your
Airflow webserver is publicly accessible, and you should probably use the deny all backend:
.. code-block:: ini
[api]
auth_backend = airflow.api.auth.backend.deny_all
Kerberos is the only "real" authentication mechanism currently supported for the API. To enable
this set the following in the configuration:
.. code-block:: ini
[api]
auth_backend = airflow.api.auth.backend.kerberos_auth
[kerberos]
keytab = <KEYTAB>
The Kerberos service is configured as ``airflow/fully.qualified.domainname@REALM``. Make sure this
principal exists in the keytab file.
| {
"content_hash": "0274ead1fd969afd07178542d88b0587",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 99,
"avg_line_length": 29.49056603773585,
"alnum_prop": 0.7293666026871402,
"repo_name": "Twistbioscience/incubator-airflow",
"id": "856ec9e1f737d50165f593c846580adf284d6910",
"size": "1563",
"binary": false,
"copies": "8",
"ref": "refs/heads/v1-9-stable",
"path": "docs/api.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "57033"
},
{
"name": "HTML",
"bytes": "151798"
},
{
"name": "JavaScript",
"bytes": "1364571"
},
{
"name": "Mako",
"bytes": "1037"
},
{
"name": "Python",
"bytes": "2530465"
},
{
"name": "Shell",
"bytes": "21139"
}
],
"symlink_target": ""
} |
package proofpeer.proofscript.serialization
import proofpeer.proofscript.logic._
import proofpeer.general._
import proofpeer.proofscript.frontend.{ParseTree, SourcePosition}
import Pretype._
import Preterm._
import proofpeer.indent.Span
final class CustomizablePretermSerializer(
SourcePositionSerializer : Serializer[SourcePosition],
IndexedNameSerializer : Serializer[IndexedName],
NamespaceSerializer : Serializer[Namespace],
NameSerializer : Serializer[Name],
TermSerializer : Serializer[Term],
TypeSerializer : Serializer[Type],
ParseTreeSerializer : Serializer[ParseTree])
extends NestedSerializer[Preterm]
{
val PretermSerializer = this
object QuotedSerializer extends TypecastSerializer[Any, ParseTree](ParseTreeSerializer)
object PretypeSerializer extends CaseClassSerializerBase[Pretype] {
object Kind {
val PTYUNIVERSE = 0
val PTYPROP = 1
val PTYFUN = -1
val PTYANY = 2
val PTYVAR = -2
val PTYQUOTE = 3
}
object Serializers {
val PTYFUN = PairSerializer(PretypeSerializer,PretypeSerializer)
val PTYVAR = BigIntSerializer
val PTYQUOTE = QuotedSerializer
}
def decomposeAndSerialize(obj : Pretype) : (Int, Option[Any]) = {
obj match {
case PTyUniverse =>
(Kind.PTYUNIVERSE, None)
case PTyProp =>
(Kind.PTYPROP, None)
case t : PTyFun =>
(Kind.PTYFUN, Some(Serializers.PTYFUN.serialize(PTyFun.unapply(t).get)))
case PTyAny =>
(Kind.PTYANY, None)
case PTyVar(x) =>
(Kind.PTYVAR, Some(Serializers.PTYVAR.serialize(x)))
case PTyQuote(x) =>
(Kind.PTYQUOTE, Some(Serializers.PTYQUOTE.serialize(x)))
case _ => throw new RuntimeException("PretypeSerializer: cannot serialize " + obj)
}
}
def deserializeAndCompose(kind : Int, args : Option[Any]) : Pretype = {
kind match {
case Kind.PTYUNIVERSE if args.isEmpty =>
PTyUniverse
case Kind.PTYPROP if args.isEmpty =>
PTyProp
case Kind.PTYFUN if args.isDefined =>
PTyFun.tupled(Serializers.PTYFUN.deserialize(args.get))
case Kind.PTYANY if args.isEmpty =>
PTyAny
case Kind.PTYVAR if args.isDefined =>
PTyVar(Serializers.PTYVAR.deserialize(args.get))
case Kind.PTYQUOTE if args.isDefined =>
PTyQuote(Serializers.PTYQUOTE.deserialize(args.get))
case _ => throw new RuntimeException("PretypeSerializer: cannot deserialize " + (kind, args))
}
}
}
object PretermSerializerBase extends CaseClassSerializerBase[Preterm] {
object Kind {
val PTMTYPING = 0
val PTMNAME = 1
val PTMABS = -1
val PTMCOMB = 2
val PTMQUOTE = -2
val PTMTERM = 3
val PTMERROR = -3
}
object Serializers {
val PTMTYPING = PairSerializer(PretermSerializer,PretypeSerializer)
val PTMNAME = PairSerializer(NameSerializer,PretypeSerializer)
val PTMABS = QuadrupleSerializer(IndexedNameSerializer,PretypeSerializer,PretermSerializer,PretypeSerializer)
val PTMCOMB = QuadrupleSerializer(PretermSerializer,PretermSerializer,OptionSerializer(BooleanSerializer),PretypeSerializer)
val PTMQUOTE = PairSerializer(QuotedSerializer,PretypeSerializer)
val PTMTERM = PairSerializer(TermSerializer,TypeSerializer)
val PTMERROR = StringSerializer
}
def decomposeAndSerialize(obj : Preterm) : (Int, Option[Any]) = {
obj match {
case t : PTmTyping =>
(Kind.PTMTYPING, Some(Serializers.PTMTYPING.serialize(PTmTyping.unapply(t).get)))
case t : PTmName =>
(Kind.PTMNAME, Some(Serializers.PTMNAME.serialize(PTmName.unapply(t).get)))
case t : PTmAbs =>
(Kind.PTMABS, Some(Serializers.PTMABS.serialize(PTmAbs.unapply(t).get)))
case t : PTmComb =>
(Kind.PTMCOMB, Some(Serializers.PTMCOMB.serialize(PTmComb.unapply(t).get)))
case t : PTmQuote =>
(Kind.PTMQUOTE, Some(Serializers.PTMQUOTE.serialize(PTmQuote.unapply(t).get)))
case t : PTmTerm =>
(Kind.PTMTERM, Some(Serializers.PTMTERM.serialize(PTmTerm.unapply(t).get)))
case PTmError(x) =>
(Kind.PTMERROR, Some(Serializers.PTMERROR.serialize(x)))
case _ => throw new RuntimeException("PretermSerializerBase: cannot serialize " + obj)
}
}
def deserializeAndCompose(kind : Int, args : Option[Any]) : Preterm = {
kind match {
case Kind.PTMTYPING if args.isDefined =>
PTmTyping.tupled(Serializers.PTMTYPING.deserialize(args.get))
case Kind.PTMNAME if args.isDefined =>
PTmName.tupled(Serializers.PTMNAME.deserialize(args.get))
case Kind.PTMABS if args.isDefined =>
PTmAbs.tupled(Serializers.PTMABS.deserialize(args.get))
case Kind.PTMCOMB if args.isDefined =>
PTmComb.tupled(Serializers.PTMCOMB.deserialize(args.get))
case Kind.PTMQUOTE if args.isDefined =>
PTmQuote.tupled(Serializers.PTMQUOTE.deserialize(args.get))
case Kind.PTMTERM if args.isDefined =>
PTmTerm.tupled(Serializers.PTMTERM.deserialize(args.get))
case Kind.PTMERROR if args.isDefined =>
PTmError(Serializers.PTMERROR.deserialize(args.get))
case _ => throw new RuntimeException("PretermSerializerBase: cannot deserialize " + (kind, args))
}
}
}
protected lazy val innerSerializer : Serializer[Preterm] = PretermSerializerBase
}
/** This is code used to create most of the above code. It is not needed during runtime, just during programming. */
object PretermSerializerGenerator {
val typeCases : Vector[Any] = Vector(
"PTyUniverse",
"PTyProp",
("PTyFun", "PretypeSerializer", "PretypeSerializer"),
"PTyAny",
("PTyVar", "BigIntSerializer"),
("PTyQuote", "QuotedSerializer")
)
val termCases : Vector[Any] = Vector(
("PTmTyping", "PretermSerializer", "PretypeSerializer"),
("PTmName", "NameSerializer", "PretypeSerializer"),
("PTmAbs", "IndexedNameSerializer", "PretypeSerializer", "PretermSerializer", "PretypeSerializer"),
("PTmComb", "PretermSerializer", "PretermSerializer", "OptionSerializer(BooleanSerializer)", "PretypeSerializer"),
("PTmQuote", "QuotedSerializer", "PretypeSerializer"),
("PTmTerm", "TermSerializer", "TypeSerializer"),
("PTmError", "StringSerializer")
)
/** Rename _main to main to generate the code. */
def _main(args : Array[String]) {
val typeTool = new CaseClassSerializerTool("PretypeSerializer", typeCases, "Pretype")
//typeTool.output()
val termTool = new CaseClassSerializerTool("PretermSerializerBase", termCases, "Preterm")
termTool.output()
}
}
| {
"content_hash": "7a9222bce666493f8a8296090a60200b",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 130,
"avg_line_length": 37.638888888888886,
"alnum_prop": 0.6792619926199261,
"repo_name": "proofpeer/proofpeer-proofscript",
"id": "2ffcff1fec7c2e374b154d615fbe816ae88c116c",
"size": "6775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "shared/src/main/scala/proofpeer/proofscript/serialization/PretermSerializer.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Emacs Lisp",
"bytes": "97"
},
{
"name": "Isabelle",
"bytes": "139417"
},
{
"name": "Nix",
"bytes": "364"
},
{
"name": "Scala",
"bytes": "505074"
}
],
"symlink_target": ""
} |
#nullable disable
using PasPasPas.Globals.Files;
namespace PasPasPas.Globals.Options {
/// <summary>
/// path options
/// </summary>
public interface IPathOptions {
/// <summary>
/// search paths
/// </summary>
IEnumerableOptionCollection<IFileReference> SearchPaths { get; }
/// <summary>
/// clear path options
/// </summary>
void Clear();
}
}
| {
"content_hash": "2128beab31e814c874a716547f26b310",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 72,
"avg_line_length": 21.285714285714285,
"alnum_prop": 0.5458612975391499,
"repo_name": "prjm/paspaspas",
"id": "18926a207c4f9cd44700d7653eaac2880def0300",
"size": "449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PasPasPas.Global/src/Options/IPathOptions.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "3376141"
}
],
"symlink_target": ""
} |
static NSString* const FOAssetsCellIdentifier = @"Cell";
static CGFloat const IPhone6ScreenWidth = 375;
static CGFloat const IPhone6PlusScreenWidth = 414;
static CGFloat const IPhone6CellSize = 89;
static CGFloat const IPhone6PlusCellSize = 78;
static CGFloat const IPhone5CellSize = 75;
@interface FOAssetCollectionViewController () <UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) NSArray* assetProxies;
@property (nonatomic) BOOL isPlayerPlaying;
@property (strong, nonatomic) MPMoviePlayerViewController* playerVC;
@property (weak, nonatomic) IBOutlet UIProgressView* progressView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *progressViewTopLayoutConstraint;
@property (weak, nonatomic) IBOutlet UICollectionView* collectionView;
@end
@implementation FOAssetCollectionViewController
- (void) viewDidLoad {
[super viewDidLoad];
self.assetProxies = [NSMutableArray array];
self.collectionView.delegate = (id)self;
self.collectionView.dataSource = (id)self;
self.collectionView.collectionViewLayout = [[UICollectionViewFlowLayout alloc] init];
if (self.videoPlaybackEnabled) {
UILongPressGestureRecognizer* longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget: self action: @selector(handleLongPressGesture:)];
[self.collectionView addGestureRecognizer: longPressGesture];
longPressGesture.delegate = (id)self;
}
}
- (void) viewWillAppear: (BOOL) animated {
[self.progressView setProgress:0];
self.progressView.hidden = NO;
// calculate inset due to navigation + status bar visibility
CGFloat liveTopInset = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
self.progressViewTopLayoutConstraint.constant = liveTopInset;
[self.collectionView setContentInset:UIEdgeInsetsMake(3, 0, 3, 0)];
}
- (void) viewDidAppear: (BOOL) animated {
[super viewDidAppear: animated];
UIBarButtonItem* doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone target: self action: @selector(doneTouched)];
self.navigationItem.rightBarButtonItem = doneBtn;
self.navigationItem.rightBarButtonItem.enabled = NO;
[self.assetsManager loadAssetsForGroup: self.assetsGroup withCompletionHandler: ^(NSArray* assets) {
self.assetProxies = assets;
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
[self updateTitle];
self.progressView.hidden = YES;
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:[self.assetProxies count] - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
});
} andProgressHandler:^(CGFloat progress) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.progressView setProgress:progress];
});
}];
}
- (void) handleLongPressGesture: (UILongPressGestureRecognizer*) gestureRecognizer {
self.collectionView.userInteractionEnabled = NO;
CGPoint p = [gestureRecognizer locationInView: self.collectionView];
NSIndexPath* indexPath = [self.collectionView indexPathForItemAtPoint: p];
if (indexPath == nil) {
NSLog(@"Long press on collection view but not on a row");
}
else {
FOAssetProxy* proxy = [self.assetProxies objectAtIndex: indexPath.row];
[self playVideoAtURL: [proxy assetURL]];
}
}
- (void) doneTouched {
// collect selected assets
NSMutableArray* selectedAssets = [NSMutableArray array];
for (FOAssetProxy* proxy in self.assetProxies) {
if (proxy.selected) {
[selectedAssets addObject: proxy];
}
}
if (self.selectionDoneHandler) {
self.selectionDoneHandler(selectedAssets);
}
}
#pragma mark - UICollectionViewDataSource methods
- (NSInteger) numberOfSectionsInCollectionView: (UICollectionView*) collectionView {
return 1;
}
- (NSInteger) collectionView: (UICollectionView*) collectionView numberOfItemsInSection: (NSInteger) section {
return [self.assetProxies count];
}
- (UICollectionViewCell*) collectionView: (UICollectionView*) collectionView cellForItemAtIndexPath: (NSIndexPath*) indexPath {
FOAssetCell* cell = (FOAssetCell*)[collectionView dequeueReusableCellWithReuseIdentifier: FOAssetsCellIdentifier forIndexPath: indexPath];
FOAssetProxy* proxy = [self.assetProxies objectAtIndex: indexPath.row];
if (proxy) {
cell.assetProxy = proxy;
}
return cell;
}
#pragma mark - UICollectionViewDelegate methods
- (void) collectionView: (UICollectionView*) collectionView didSelectItemAtIndexPath: (NSIndexPath*) indexPath {
FOAssetCell* cell = (FOAssetCell*)[collectionView cellForItemAtIndexPath: indexPath];
FOAssetProxy* assetProxy = [self.assetProxies objectAtIndex: indexPath.row];
if (assetProxy) {
if (!assetProxy.selected && [self selectionCount] >= self.maxSelectionCount) {
return;
}
assetProxy.selected = !assetProxy.selected;
cell.checked = assetProxy.selected;
[self updateTitle];
}
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGSize screenSize = [[UIScreen mainScreen] applicationFrame].size;
// TODO: generic cell size calculation based on the available width
if (screenSize.width == IPhone6ScreenWidth) {
return CGSizeMake(IPhone6CellSize, IPhone6CellSize);
} else if (screenSize.width == IPhone6PlusScreenWidth) {
return CGSizeMake(IPhone6PlusCellSize, IPhone6PlusCellSize);
}
return CGSizeMake(IPhone5CellSize, IPhone5CellSize);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(0, 4, 0, 4);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 2;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 4;
}
#pragma mark - Play Movie
- (void) playVideoAtURL: (NSURL*) videoUrl {
if (!self.isPlayerPlaying) {
self.isPlayerPlaying = YES;
self.playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL: videoUrl];
[[NSNotificationCenter defaultCenter] removeObserver: self.playerVC
name: MPMoviePlayerPlaybackDidFinishNotification
object: self.playerVC.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(movieFinishedCallback:)
name: MPMoviePlayerPlaybackDidFinishNotification
object: self.playerVC.moviePlayer];
self.playerVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
self.playerVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController: self.playerVC animated: YES completion: ^{
NSLog(@"done present player");
}];
[self.playerVC.moviePlayer setFullscreen: NO];
[self.playerVC.moviePlayer prepareToPlay];
[self.playerVC.moviePlayer play];
}
}
- (void) movieFinishedCallback: (NSNotification*) aNotification {
if ([aNotification.name isEqualToString: MPMoviePlayerPlaybackDidFinishNotification]) {
NSNumber* finishReason = [[aNotification userInfo] objectForKey: MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if ([finishReason intValue] != MPMovieFinishReasonPlaybackEnded) {
MPMoviePlayerController* moviePlayer = [aNotification object];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMoviePlayerPlaybackDidFinishNotification
object: moviePlayer];
[self dismissViewControllerAnimated: YES completion: ^{ }];
}
self.collectionView.userInteractionEnabled = YES;
self.isPlayerPlaying = NO;
}
}
#pragma mark - Helper
- (NSUInteger) selectionCount {
NSUInteger selectionCount = 0;
for (FOAssetProxy* proxy in self.assetProxies) {
if (proxy.selected) {
selectionCount++;
}
}
return selectionCount;
}
- (void) updateTitle {
NSUInteger selectionCount = [self selectionCount];
NSString* titlePattern = NSLocalizedString(@"FOAssetPicker.numAssetsSelectedMultiple", nil);
if (selectionCount == 1) {
titlePattern = NSLocalizedString(@"FOAssetPicker.numAssetsSelectedSingle", nil);
}
self.navigationItem.title = [NSString stringWithFormat: titlePattern, selectionCount];
self.navigationItem.rightBarButtonItem.enabled = selectionCount > 0;
}
- (void) didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
| {
"content_hash": "ac72bc5fbe4b85009f17e4144ec0f2e4",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 197,
"avg_line_length": 41.26293103448276,
"alnum_prop": 0.7102266792019221,
"repo_name": "foby/FOAssetPicker",
"id": "c51a188abd78759021824ddf7090e0ad14d4594b",
"size": "9953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FOAssetPicker/API/FOAssetCollectionViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "35804"
}
],
"symlink_target": ""
} |
var meetingtools = {};
(function(ns){
function shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
ns.createParticipantsRepository = function () {
return {
add: function(participant) {
var participants = JSON.parse(window.localStorage.getItem("participants"));
if (participants == null) {
participants = [];
}
participants.push(participant);
window.localStorage.setItem("participants", JSON.stringify(participants));
},
findAll: function() {
return JSON.parse(window.localStorage.getItem("participants"));
}
}
};
ns.createMeeting = function (repository, clock){
var initialTime = 0;
var started = false;
var initialDuration = 0;
return {
startMeeting: function(duration){
initialTime = clock.getSeconds();
started = true;
initialDuration = duration;
},
add: function(participant){
repository.add(participant)
},
participants: function(){
return repository.findAll();
},
interventionOrder: function(){
return shuffle(repository.findAll());
},
remainingTime: function(){
if (started == false){
return initialDuration;
}
var actualTime = clock.getSeconds();
var consumedTime = actualTime - initialTime;
return initialDuration - consumedTime;
},
tick: function(){
if (this.remainingTime() <= 0) {
this.onFinish();
}
},
onFinish: function(){/* event */}
}
};
ns.createClock = function(){
return {
getSeconds: function(){
return Math.floor(new Date().getTime()/1000);
}
}
};
}(meetingtools));
| {
"content_hash": "8cc74fe4d49421c34cc2fa4290981627",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 107,
"avg_line_length": 31.797101449275363,
"alnum_prop": 0.47447584320875114,
"repo_name": "eferro/meetingtools",
"id": "d690bb61791e6f9265199bd6cf9e00e899d813e6",
"size": "2194",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "meetingtools.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6537"
},
{
"name": "HTML",
"bytes": "8651"
},
{
"name": "JavaScript",
"bytes": "390420"
}
],
"symlink_target": ""
} |
import {BaseIfc} from "./BaseIfc"
import {IfcLabel} from "./IfcLabel.g"
import {IfcDataOriginEnum} from "./IfcDataOriginEnum.g"
import {IfcDateTime} from "./IfcDateTime.g"
import {IfcSchedulingTime} from "./IfcSchedulingTime.g"
/**
* http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifceventtime.htm
*/
export class IfcEventTime extends IfcSchedulingTime {
ActualDate : IfcDateTime // optional
EarlyDate : IfcDateTime // optional
LateDate : IfcDateTime // optional
ScheduleDate : IfcDateTime // optional
constructor() {
super()
}
getStepParameters() : string {
var parameters = new Array<string>();
parameters.push(BaseIfc.toStepValue(this.Name))
parameters.push(BaseIfc.toStepValue(this.DataOrigin))
parameters.push(BaseIfc.toStepValue(this.UserDefinedDataOrigin))
parameters.push(BaseIfc.toStepValue(this.ActualDate))
parameters.push(BaseIfc.toStepValue(this.EarlyDate))
parameters.push(BaseIfc.toStepValue(this.LateDate))
parameters.push(BaseIfc.toStepValue(this.ScheduleDate))
return parameters.join();
}
} | {
"content_hash": "aa643a16d7ea635f1b8825d29fd5e0d8",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 78,
"avg_line_length": 33.875,
"alnum_prop": 0.7472324723247232,
"repo_name": "ikeough/IFC-gen",
"id": "72e9991a66be263d59cef11a4fcd2c65c51a7d52",
"size": "1084",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lang/typescript/src/IfcEventTime.g.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "16049"
},
{
"name": "Batchfile",
"bytes": "593"
},
{
"name": "C#",
"bytes": "2679991"
},
{
"name": "JavaScript",
"bytes": "319"
},
{
"name": "Makefile",
"bytes": "1222"
},
{
"name": "TypeScript",
"bytes": "1605804"
}
],
"symlink_target": ""
} |
// Generated from TEXTGY.g4 by ANTLR 4.5.3
package TEXTGY;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* This class provides an empty implementation of {@link TEXTGYListener},
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
public class TEXTGYBaseListener implements TEXTGYListener {
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterProgramm(TEXTGYParser.ProgrammContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitProgramm(TEXTGYParser.ProgrammContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterLausetejada(TEXTGYParser.LausetejadaContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitLausetejada(TEXTGYParser.LausetejadaContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterLause(TEXTGYParser.LauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitLause(TEXTGYParser.LauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTagastuslause(TEXTGYParser.TagastuslauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTagastuslause(TEXTGYParser.TagastuslauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOmistamine(TEXTGYParser.OmistamineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOmistamine(TEXTGYParser.OmistamineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterMuutujadeklaratsioon(TEXTGYParser.MuutujadeklaratsioonContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitMuutujadeklaratsioon(TEXTGYParser.MuutujadeklaratsioonContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTuup(TEXTGYParser.TuupContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTuup(TEXTGYParser.TuupContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterIflause(TEXTGYParser.IflauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitIflause(TEXTGYParser.IflauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterWhilelause(TEXTGYParser.WhilelauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitWhilelause(TEXTGYParser.WhilelauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterAlterlause(TEXTGYParser.AlterlauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitAlterlause(TEXTGYParser.AlterlauseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterObjektiloomine(TEXTGYParser.ObjektiloomineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitObjektiloomine(TEXTGYParser.ObjektiloomineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFunktsiooniloomine(TEXTGYParser.FunktsiooniloomineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFunktsiooniloomine(TEXTGYParser.FunktsiooniloomineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterObjektituup(TEXTGYParser.ObjektituupContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitObjektituup(TEXTGYParser.ObjektituupContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterDescriptionParameeter(TEXTGYParser.DescriptionParameeterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitDescriptionParameeter(TEXTGYParser.DescriptionParameeterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterItemParameeter(TEXTGYParser.ItemParameeterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitItemParameeter(TEXTGYParser.ItemParameeterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSkillParameeter(TEXTGYParser.SkillParameeterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSkillParameeter(TEXTGYParser.SkillParameeterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterAttributeParameeter(TEXTGYParser.AttributeParameeterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitAttributeParameeter(TEXTGYParser.AttributeParameeterContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFunktsioonivaljakutseobjekt(TEXTGYParser.FunktsioonivaljakutseobjektContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFunktsioonivaljakutseobjekt(TEXTGYParser.FunktsioonivaljakutseobjektContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterAvaldis(TEXTGYParser.AvaldisContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitAvaldis(TEXTGYParser.AvaldisContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVordlemine(TEXTGYParser.VordlemineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVordlemine(TEXTGYParser.VordlemineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTriviaalneAvaldis5(TEXTGYParser.TriviaalneAvaldis5Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTriviaalneAvaldis5(TEXTGYParser.TriviaalneAvaldis5Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTriviaalneAvaldis4(TEXTGYParser.TriviaalneAvaldis4Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTriviaalneAvaldis4(TEXTGYParser.TriviaalneAvaldis4Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterLiitmineLahutamine(TEXTGYParser.LiitmineLahutamineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitLiitmineLahutamine(TEXTGYParser.LiitmineLahutamineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterKorrutamineJagamine(TEXTGYParser.KorrutamineJagamineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitKorrutamineJagamine(TEXTGYParser.KorrutamineJagamineContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTriviaalneAvaldis3(TEXTGYParser.TriviaalneAvaldis3Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTriviaalneAvaldis3(TEXTGYParser.TriviaalneAvaldis3Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterUnaarneMiinus(TEXTGYParser.UnaarneMiinusContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitUnaarneMiinus(TEXTGYParser.UnaarneMiinusContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTriviaalneAvaldis2(TEXTGYParser.TriviaalneAvaldis2Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTriviaalneAvaldis2(TEXTGYParser.TriviaalneAvaldis2Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFunktsiooniValjakutse(TEXTGYParser.FunktsiooniValjakutseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFunktsiooniValjakutse(TEXTGYParser.FunktsiooniValjakutseContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTriviaalneAvaldis1(TEXTGYParser.TriviaalneAvaldis1Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTriviaalneAvaldis1(TEXTGYParser.TriviaalneAvaldis1Context ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSoneLiteraalR(TEXTGYParser.SoneLiteraalRContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSoneLiteraalR(TEXTGYParser.SoneLiteraalRContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterMuutujaNimiR(TEXTGYParser.MuutujaNimiRContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitMuutujaNimiR(TEXTGYParser.MuutujaNimiRContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterArvuLiteraalR(TEXTGYParser.ArvuLiteraalRContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitArvuLiteraalR(TEXTGYParser.ArvuLiteraalRContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSuluAvaldis(TEXTGYParser.SuluAvaldisContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSuluAvaldis(TEXTGYParser.SuluAvaldisContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSkillAvaldis(TEXTGYParser.SkillAvaldisContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSkillAvaldis(TEXTGYParser.SkillAvaldisContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitTerminal(TerminalNode node) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitErrorNode(ErrorNode node) { }
} | {
"content_hash": "2f1a762d78a5d985877e1b79c3694c8c",
"timestamp": "",
"source": "github",
"line_count": 447,
"max_line_length": 112,
"avg_line_length": 28.257270693512304,
"alnum_prop": 0.701765497585306,
"repo_name": "RainVagel/TEXTGY",
"id": "445f225adafb2c0836f3ff13ef5c76c4151e3c9e",
"size": "12631",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/gen/java/TEXTGY/TEXTGYBaseListener.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "6030"
},
{
"name": "Java",
"bytes": "202599"
}
],
"symlink_target": ""
} |
package org.teavm.junit;
public @interface TeaVMProperty {
String key();
String value();
}
| {
"content_hash": "cf29d43c6e8501a57317c291beccacd0",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 33,
"avg_line_length": 12.75,
"alnum_prop": 0.6666666666666666,
"repo_name": "shannah/cn1-teavm-builds",
"id": "d94045efde4f6ba99af72fd6515e31d9f97032d4",
"size": "711",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "tools/junit/src/main/java/org/teavm/junit/TeaVMProperty.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "95209"
},
{
"name": "CSS",
"bytes": "1533"
},
{
"name": "HTML",
"bytes": "5991"
},
{
"name": "Java",
"bytes": "10108076"
},
{
"name": "JavaScript",
"bytes": "89228"
},
{
"name": "Shell",
"bytes": "3113"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.9.4"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="defines_13.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div id="SRResults"></div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
createResults();
/* @license-end */
</script>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
window.addEventListener("message", function(event) {
if (event.data == "take_focus") {
var elem = searchResults.NavNext(0);
if (elem) elem.focus();
}
});
/* @license-end */
</script>
</div>
</body>
</html>
| {
"content_hash": "8a3884037bfc125db2c83cadc08baccc",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 122,
"avg_line_length": 38.91891891891892,
"alnum_prop": 0.7125,
"repo_name": "or-tools/docs",
"id": "dc816cfa8e15515ad816b1b355afc2b3b0e39569",
"size": "1440",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/cpp/search/defines_13.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Best Man, The (1999/I)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0168501">Best Man, The (1999/I)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Chuck+Schwartz">Chuck Schwartz</A></H3><HR WIDTH="40%" SIZE="4">
<P>CrankyCritic® movie reviews: The Best Man
Rated [R], [116] minutes
Starring Taye Diggs, Nia Peeples
Written and Directed by Malcolm D. Lee
website: <A HREF="http://www.best-man.com">http://www.best-man.com</A></P>
<P>IN SHORT: A Rockin' African-American targeted date flick.</P>
<P>We begin with Harper Stewart (Taye Diggs), a novelist just months away
from the publication of "Unfinished Business," his first book. Based on
his friends from college, the writing is so steamy that Oprah Winfrey
wants to feature it in her book club. Not only does success beckon, so
does his beautiful girlfriend Robin (Sanaa Lathan), a caterer whose
business, too, is starting to take off. Three pending jobs is keeping
her from journeying from Chicago to New York, for the wedding of two of
Harper's friends. Truth of the matter is, they're his friends. Robin'll
just catch up at the wedding. Besides, she's getting just a bit
discouraged that her beau can't make the slightest move towards either
commitment or saying those three little words.</P>
<P>Those friends, quickly, are: the groom, Lance (Morris Chestnut), a NFL
running back (NY Giants?) who has used his fame to great advantage with
the ladies, if you know what I mean; his save it for the wedding night
bride Mia (Monica Calhoun); Jordan Armstrong (Nia Long), Harper's woulda
coulda shoulda but never did gal; career-phobic Quentin (Terrence
Howard), who plays a mean guitar; equally career-phobic Murch (Harold
Perrineau) who's staring down a six figure legal gig and his controlling
bitch of a girlfriend Shelby (Melissa DeSousa), whom everyone in this
group, save Murch, detests. With Robin away until the day of the
wedding, Jordan determines that she's going to nail Harper, one way or
the other.</P>
<P>The New York weekend means reunion for this crew. Thanks to a
prepublication copy of Harper's book obtained, and circulated among all
concerned, by teevee producer Jordan, old secrets come out in the open.
Each real person sees themselves in the book's fictional characters and
when the groom finally gets his turn, let's just say his eyes are opened
to the fact that his virginal bride may not be. A joyful weekend
escalates into something much more as the groom wants vengeance and each
of the other single men get to reevaluate their own relationships.</P>
<P>That doesn't give anything away as writer/director Malcolm D. Lee
fashions strong characters and the actors make you feel as if this group
had indeed been friends for years. Then again, the African-American
acting community isn't a very large one so they may actually be friends.
And, yes, I may be a middle aged white guy who ears can't follow the
vocal rhythms; I didn't catch half the lingo, but there's enough here
that when push came to shove and the film hit its edge of the seat
climax -- I know, for a comedy that's a bit of a stretch to imagine, but
that's what it was -- I was there, baby.</P>
<P>On average, a first run movie ticket will run you Eight Bucks. Were
Cranky able to set his own price to The Best Man, he would have paid...</P>
<PRE>$6.00</PRE>
<P>Much better than the average dateflick. The Best Man is not the kind of
African-American targeted movie that may not be accessible enough to
white audiences to cross over big time, but I'm an old fogey. The
kidlets who speak in rap rhythms may get this with no problem. With
dating couples all around me, and running commentary on the action from
all of 'em (there are advantages to sitting with "real" people), The
Best Man wasn't hard to follow. Just watching the crowd, as I've done at
other A-A starring flicks, left me with the impression that this is
bigger and better than the average flick targeted at them.</P>
<P>The Cranky Critic® is a Registered Trademark of, and Copyright © 1999
by, Chuck Schwartz. All Rights Reserved. Cranky on the web at
www.crankycritic.com</P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "48f44102cc095eb7c0473c9a98922880",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 205,
"avg_line_length": 63.18518518518518,
"alnum_prop": 0.7543962485345839,
"repo_name": "xianjunzhengbackup/code",
"id": "efacef627e4554b16fc8151dfa153ed6fa6179bf",
"size": "5118",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/21303.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
public class GoldenEditionBook : Book
{
public GoldenEditionBook(string author, string title, decimal price)
: base(author, title, price)
{
}
public override decimal Price
{
get
{
return base.Price * 1.3m;
}
}
}
| {
"content_hash": "936e97d3398f017fc78f5e7b6bb520c7",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 72,
"avg_line_length": 15.833333333333334,
"alnum_prop": 0.5508771929824562,
"repo_name": "varbanov88/SoftUniOOP",
"id": "dc718a75244f4c18121297ce790d72e92ef618b9",
"size": "287",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Inheritance/BookShop/GoldenEditionBook.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "421557"
}
],
"symlink_target": ""
} |
//
// RCRealTimeLocationEndMessage.h
// RongIMLib
//
// Created by 杜立召 on 15/8/13.
// Copyright (c) 2015年 RongCloud. All rights reserved.
//
#import "RCMessageContent.h"
#define RCRealTimeLocationEndMessageTypeIdentifier @"RC:RLEnd"
/**
* 地理位置结束消息
*/
@interface RCRealTimeLocationEndMessage : RCMessageContent
/**
* 附加信息
*/
@property(nonatomic, strong) NSString *extra;
/**
* 根据参数创建消息对象
*
* @param extra 附加信息
*/
+ (instancetype)messageWithExtra:(NSString *)extra;
@end | {
"content_hash": "3f8203b54528c68a7cbaeeb8cd1393b6",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 62,
"avg_line_length": 18.037037037037038,
"alnum_prop": 0.7084188911704312,
"repo_name": "sbcmadn1/rongyun",
"id": "cb86623bda9cf58bbfd6bd0873c8e8ea755824fa",
"size": "547",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "融云通讯/demo-app-ios-v2/ios-rongimdemo/framework/RongIMLib.framework/Headers/RCRealTimeLocationEndMessage.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "24484"
},
{
"name": "C++",
"bytes": "233"
},
{
"name": "Objective-C",
"bytes": "1880955"
}
],
"symlink_target": ""
} |
<?php
App::uses('CakeMigration', 'Migrations.Lib');
App::uses('ConnectionManager', 'Model');
App::uses('Inflector', 'Utility');
App::uses('Folder', 'Utility');
App::uses('ClassRegistry', 'Utility');
App::uses('MigrationVersionException', 'Migrations.Lib');
/**
* Migration version management.
*
* @package migrations
* @subpackage migrations.libs
*/
class MigrationVersion {
/**
* Connection used for the migration_schema table of the migration versions
*
* @var string
*/
public $connection = 'default';
/**
* Connection used for the migration
*
* This can be used to override the connection of migration file
*
* @var null|string
*/
public $migrationConnection = null;
/**
* Instance of SchemaMigrations model
*
* @var Model
*/
public $Version;
/**
* Mapping cache
*
* @var array
*/
private $__mapping = array();
/**
* Precheck mode
*
* @var string
*/
public $precheck = 'Migrations.PrecheckException';
/**
* Should the run be dry or not.
*
* If try, the SQL will be outputted to screen rather than
* applied to the database
*
* @var boolean
*/
public $dry = false;
/**
* Log of SQL queries generated
*
* This is used for dry run
*
* @var array
*/
public $log = array();
/**
* Constructor
*
* @param array $options optional load object properties
*/
public function __construct($options = array()) {
if (!empty($options['connection'])) {
$this->connection = $options['connection'];
}
if (!empty($options['precheck'])) {
$this->precheck = $options['precheck'];
}
if (!empty($options['migrationConnection'])) {
$this->migrationConnection = $options['migrationConnection'];
}
if (!isset($options['dry'])) {
$options['dry'] = false;
}
$this->dry = $options['dry'];
$this->initVersion();
if (!isset($options['autoinit']) || $options['autoinit'] !== false) {
$this->__initMigrations();
}
}
/**
* get a new SchemaMigration instance
*
* @return void
*/
public function initVersion() {
$this->Version = ClassRegistry::init(array(
'class' => 'Migrations.SchemaMigration',
'ds' => $this->connection
));
$this->Version->setDataSource($this->connection);
}
/**
* Get last version for given type
*
* @param string $type Can be 'app' or a plugin name
* @return integer Last version migrated
*/
public function getVersion($type) {
$mapping = $this->getMapping($type);
if ($mapping !== false) {
krsort($mapping);
foreach ($mapping as $version => $info) {
if ($info['migrated'] !== null) {
return $version;
}
}
}
return 0;
}
/**
* Set current version for given type
*
* @param integer $version Current version
* @param string $type Can be 'app' or a plugin name
* @param boolean $migrated If true, will add the record to the database
* If false, will remove the record from the database
* @return boolean
*/
public function setVersion($version, $type, $migrated = true) {
if ($this->dry) {
return true;
}
if ($type !== 'app') {
$type = Inflector::camelize($type);
}
$mapping = $this->getMapping($type);
// For BC, 002 was not applied yet.
$bc = ($this->Version->schema('class') === null);
$field = $bc ? 'version' : 'class';
$value = $bc ? $version : $mapping[$version]['class'];
if ($migrated) {
$this->Version->create();
$result = $this->Version->save(array(
$field => $value, 'type' => $type
));
} else {
$conditions = array(
$this->Version->alias . '.' . $field => $value,
$this->Version->alias . '.type' => $type
);
$result = $this->Version->deleteAll($conditions);
}
// Clear mapping cache
unset($this->__mapping[$type]);
return $result;
}
/**
* Get mapping for the given type
*
* @param string $type Can be 'app' or a plugin name
* @param bool $cache
* @return mixed False in case of no file found or empty mapping, array with mapping
*/
public function getMapping($type, $cache = true) {
if ($type !== 'app') {
$type = Inflector::camelize($type);
}
if ($cache && !empty($this->__mapping[$type])) {
return $this->__mapping[$type];
}
$mapping = $this->_enumerateMigrations($type);
if (empty($mapping)) {
return false;
}
$migrated = $this->Version->find('all', array(
'conditions' => array(
'OR' => array(
array($this->Version->alias . '.type' => Inflector::underscore($type)),
array($this->Version->alias . '.type' => $type),
)
),
'recursive' => -1,
));
// For BC, 002 was not applied yet.
$bc = ($this->Version->schema('class') === null);
if ($bc) {
$migrated = Set::combine($migrated, '/' . $this->Version->alias . '/version', '/' . $this->Version->alias . '/created');
} else {
$migrated = Set::combine($migrated, '/' . $this->Version->alias . '/class', '/' . $this->Version->alias . '/created');
}
$bcMapping = array();
if ($type == 'Migrations') {
$bcMapping = array(
'InitMigrations' => 'M4af6e0f0a1284147a0b100ca58157726',
'ConvertVersionToClassNames' => 'M4ec50d1f7a284842b1b770fdcbdd56cb',
);
}
ksort($mapping);
foreach ($mapping as $version => $migration) {
list($name, $class) = each($migration);
$mapping[$version] = array(
'version' => $version, 'name' => $name, 'class' => $class,
'type' => $type, 'migrated' => null
);
if ($bc) {
if (isset($migrated[$version])) {
$mapping[$version]['migrated'] = $migrated[$version];
}
} else {
if (isset($migrated[$class])) {
$mapping[$version]['migrated'] = $migrated[$class];
} elseif (isset($bcMapping[$class]) && !empty($migrated[$bcMapping[$class]])) {
$mapping[$version]['migrated'] = $migrated[$bcMapping[$class]];
}
}
}
$this->__mapping[$type] = $mapping;
return $mapping;
}
/**
* Load and make a instance of the migration
*
* @param string $name File name where migration resides
* @param string $class Migration class name
* @param string $type Can be 'app' or a plugin name
* @param array $options Extra options to send to CakeMigration class
* @return boolean|CakeMigration False in case of no file found, instance of the migration
* @throws MigrationVersionException
*/
public function getMigration($name, $class, $type, $options = array()) {
if (!class_exists($class) && (!$this->__loadFile($name, $type) || !class_exists($class))) {
throw new MigrationVersionException(sprintf(
__d('migrations', 'Class `%1$s` not found on file `%2$s` for %3$s.'),
$class, $name . '.php', (($type == 'app') ? 'Application' : Inflector::camelize($type) . ' Plugin')
));
}
$defaults = array(
'precheck' => $this->precheck);
if (!empty($this->migrationConnection)) {
$defaults['connection'] = $this->migrationConnection;
}
$options = array_merge($defaults, $options);
return new $class($options);
}
/**
* Run the migrations
*
* Options:
* - `direction` - Direction to run
* - `version` - Until what version want migrate to
*
* @param array $options An array with options.
* @return boolean
* @throws Exception
*/
public function run($options) {
$targetVersion = $latestVersion = $this->getVersion($options['type']);
$mapping = $this->getMapping($options['type'], false);
$direction = 'up';
if (!empty($options['direction'])) {
$direction = $options['direction'];
}
if (isset($options['version'])) {
$targetVersion = $options['version'];
$direction = ($targetVersion < $latestVersion) ? 'down' : $direction;
if (isset($mapping[$targetVersion]) && empty($mapping[$targetVersion]['migrated'])) {
$direction = 'up';
}
}
if ($direction === 'up' && !isset($options['version'])) {
$keys = array_keys($mapping);
$flipped = array_flip($keys);
$next = $flipped[$targetVersion + 1];
$targetVersion = $keys[$next];
}
if ($direction == 'down') {
krsort($mapping);
}
foreach ($mapping as $version => $info) {
if (($direction == 'up' && $version > $targetVersion)
|| ($direction == 'down' && $version < $targetVersion)) {
break;
} else if (($direction == 'up' && $info['migrated'] === null)
|| ($direction == 'down' && $info['migrated'] !== null)) {
$migration = $this->getMigration($info['name'], $info['class'], $info['type'], $options);
$migration->Version = $this;
$migration->info = $info;
try {
$result = $migration->run($direction, $options);
$this->log[$info['name']] = $migration->getQueryLog();
} catch (Exception $exception){
$mapping = $this->getMapping($options['type']);
$latestVersionName = '#' . number_format($mapping[$latestVersion]['version'] / 100, 2, '', '') . ' ' . $mapping[$latestVersion]['name'];
$errorMessage = __d('migrations', sprintf("There was an error during a migration. \n The error was: '%s' \n You must resolve the issue manually and try again.", $exception->getMessage(), $latestVersionName));
return $errorMessage;
}
$this->setVersion($version, $info['type'], ($direction == 'up'));
}
}
if (isset($result)) {
return $result;
}
return true;
}
/**
* Initialize the migrations schema and keep it up-to-date
*
* @return void
*/
private function __initMigrations() {
/** @var DboSource $db */
$db = ConnectionManager::getDataSource($this->connection);
if (!in_array($db->fullTableName('schema_migrations', false, false), $db->listSources())) {
$map = $this->_enumerateMigrations('migrations');
list($name, $class) = each($map[1]);
$migration = $this->getMigration($name, $class, 'Migrations');
$migration->run('up');
$this->setVersion(1, 'Migrations');
}
$mapping = $this->getMapping('Migrations');
if (count($mapping) > 1) {
end($mapping);
$this->run(array(
'version' => key($mapping),
'type' => 'Migrations'
));
}
}
/**
* Load a file based on name and type
*
* @param string $name File name to be loaded
* @param string $type Can be 'app' or a plugin name
* @return mixed Throw an exception in case of no file found, array with mapping
* @throws MigrationVersionException
*/
private function __loadFile($name, $type) {
$path = APP . 'Config' . DS . 'Migration' . DS;
if ($type != 'app') {
$path = CakePlugin::path(Inflector::camelize($type)) . 'Config' . DS . 'Migration' . DS;
}
if (!file_exists($path . $name . '.php')) {
throw new MigrationVersionException(sprintf(
__d('migrations', 'File `%1$s` not found in the %2$s.'),
$name . '.php', (($type == 'app') ? 'Application' : Inflector::camelize($type) . ' Plugin')
));
}
include $path . $name . '.php';
return true;
}
/**
* Returns a map of all available migrations for a type (app or plugin)
*
* @param string $type Can be 'app' or a plugin name
* @return array containing a list of migration versions ordered by filename
*/
protected function _enumerateMigrations($type) {
$map = $this->_enumerateNewMigrations($type);
$oldMap = $this->_enumerateOldMigrations($type);
foreach ($oldMap as $k => $v) {
$map[$k] = $oldMap[$k];
}
return $map;
}
/**
* Returns a map of all available migrations for a type (app or plugin) using inflection
*
* @param string $type Can be 'app' or a plugin name
* @return array containing a list of migration versions ordered by filename
*/
protected function _enumerateNewMigrations($type) {
$mapping = array();
$path = APP . 'Config' . DS . 'Migration' . DS;
if ($type != 'app') {
$path = CakePlugin::path(Inflector::camelize($type)) . 'Config' . DS . 'Migration' . DS;
}
if (!file_exists($path)) {
return $mapping;
}
$folder = new Folder($path);
foreach ($folder->find('.*?\.php', true) as $file) {
$parts = explode('_', $file);
$version = array_shift($parts);
$className = implode('_', $parts);
if ($version > 0 && strlen($className) > 0) {
$mapping[(int)$version] = array(substr($file, 0, -4) => Inflector::camelize(substr($className, 0, -4)));
}
}
return $mapping;
}
/**
* Returns a map of all available migrations for a type (app or plugin) using regular expressions
*
* @param string $type Can be 'app' or a plugin name
* @return array containing a list of migration versions ordered by filename
*/
protected function _enumerateOldMigrations($type) {
$mapping = array();
$path = APP . 'Config' . DS . 'Migration' . DS;
if ($type != 'app') {
$path = CakePlugin::path(Inflector::camelize($type)) . 'Config' . DS . 'Migration' . DS;
}
if (!file_exists($path)) {
return $mapping;
}
$folder = new Folder($path);
foreach ($folder->find('.*?\.php', true) as $file) {
$parts = explode('_', $file);
$version = array_shift($parts);
$className = implode('_', $parts);
if ($version > 0 && strlen($className) > 0) {
$contents = file_get_contents($path . $file);
if (preg_match("/class\s([\w]+)\sextends/", $contents, $matches)) {
$mapping[(int)$version] = array(substr($file, 0, -4) => $matches[1]);
}
}
}
return $mapping;
}
}
/**
* Usually used when migrations file/class or map files are not found
*
* @package migrations
* @subpackage migrations.libs
*/
class MigrationVersionException extends Exception {
}
| {
"content_hash": "c58d234a6d6f58daec37764ba26fcb3e",
"timestamp": "",
"source": "github",
"line_count": 488,
"max_line_length": 213,
"avg_line_length": 26.959016393442624,
"alnum_prop": 0.6148525387655822,
"repo_name": "CaoLP/tranhviet",
"id": "c32ae3d470b8521928362210acc5a0389b18aa2d",
"size": "13683",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Code/khoangtroixanh/source/croogo/app/Plugin/Migrations/Lib/MigrationVersion.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "286847"
},
{
"name": "JavaScript",
"bytes": "193608"
},
{
"name": "PHP",
"bytes": "17846680"
},
{
"name": "Ruby",
"bytes": "2412"
},
{
"name": "Shell",
"bytes": "4942"
}
],
"symlink_target": ""
} |
using System;
using System.Runtime.Serialization;
namespace GitDiffMargin.Core
{
public class WeakReference<T> : WeakReference
where T : class
{
public WeakReference(object target)
: base(target)
{
}
public WeakReference(object target, bool trackResurrection)
: base(target, trackResurrection)
{
}
protected WeakReference(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
public new T Target
{
get
{
return (T)base.Target;
}
set
{
base.Target = value;
}
}
}
}
| {
"content_hash": "768e2ac753c0b3ce5a6b0476bd6ec5be",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 81,
"avg_line_length": 19.23076923076923,
"alnum_prop": 0.496,
"repo_name": "laurentkempe/GitDiffMargin",
"id": "3c233fd2ab41e741992374793827ec92bb5aa3a0",
"size": "1914",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "GitDiffMargin.Shared/Core/WeakReference.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "192973"
},
{
"name": "HCL",
"bytes": "217"
},
{
"name": "PowerShell",
"bytes": "331"
}
],
"symlink_target": ""
} |
'use strict';
if (self.importScripts) {
if ('ServiceWorkerGlobalScope' in self && self instanceof ServiceWorkerGlobalScope) {
importScripts('../../serviceworker/resources/worker-testharness.js');
} else {
importScripts('../../resources/testharness.js');
}
}
//
// Straightforward unhandledrejection tests
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.reject(e);
}, 'unhandledrejection: from Promise.reject');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = new Promise(function(_, reject) {
reject(e);
});
}, 'unhandledrejection: from a synchronous rejection in new Promise');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = new Promise(function(_, reject) {
postMessageTask(function() {
reject(e);
});
});
}, 'unhandledrejection: from a task-delayed rejection');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
}, 1);
});
}, 'unhandledrejection: from a setTimeout-delayed rejection');
async_test(function(t) {
var e = new Error();
var e2 = new Error();
var promise2;
onUnhandledSucceed(t, e2, function() { return promise2; });
var unreached = t.unreached_func('promise should not be fulfilled');
promise2 = Promise.reject(e).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
throw e2;
});
}, 'unhandledrejection: from a throw in a rejection handler chained off of Promise.reject');
async_test(function(t) {
var e = new Error();
var e2 = new Error();
var promise2;
onUnhandledSucceed(t, e2, function() { return promise2; });
var unreached = t.unreached_func('promise should not be fulfilled');
promise2 = new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
}, 1);
}).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
throw e2;
});
}, 'unhandledrejection: from a throw in a rejection handler chained off of a setTimeout-delayed rejection');
async_test(function(t) {
var e = new Error();
var e2 = new Error();
var promise2;
onUnhandledSucceed(t, e2, function() { return promise2; });
var promise = new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
mutationObserverMicrotask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
promise2 = promise.then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
throw e2;
});
});
}, 1);
});
}, 'unhandledrejection: from a throw in a rejection handler attached one microtask after a setTimeout-delayed rejection');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.resolve().then(function() {
return Promise.reject(e);
});
}, 'unhandledrejection: from returning a Promise.reject-created rejection in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.resolve().then(function() {
throw e;
});
}, 'unhandledrejection: from a throw in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.resolve().then(function() {
return new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
}, 1);
});
});
}, 'unhandledrejection: from returning a setTimeout-delayed rejection in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.all([Promise.reject(e)]);
}, 'unhandledrejection: from Promise.reject, indirected through Promise.all');
//
// Negative unhandledrejection/rejectionhandled tests with immediate attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.reject(e).then(unreached, function() {});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise from Promise.reject');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.all([Promise.reject(e)]).then(unreached, function() {});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise from ' +
'Promise.reject, indirecting through Promise.all');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = new Promise(function(_, reject) {
reject(e);
}).then(unreached, function() {});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a synchronously-rejected ' +
'promise created with new Promise');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.resolve().then(function() {
throw e;
}).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise created from ' +
'throwing in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.resolve().then(function() {
return Promise.reject(e);
}).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise created from ' +
'returning a Promise.reject-created promise in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.resolve().then(function() {
return new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
}, 1);
});
}).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise created from ' +
'returning a setTimeout-delayed rejection in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
postMessageTask(function() {
p = Promise.resolve().then(function() {
return Promise.reject(e);
})
.catch(function() {});
});
}, 'no unhandledrejection/rejectionhandled: all inside a queued task, a rejection handler attached synchronously to ' +
'a promise created from returning a Promise.reject-created promise in a fulfillment handler');
//
// Negative unhandledrejection/rejectionhandled tests with delayed attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = Promise.reject(e);
mutationObserverMicrotask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function() {});
});
}, 'delayed handling: a microtask delay before attaching a handler prevents both events (Promise.reject-created ' +
'promise)');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = new Promise(function(_, reject) {
reject(e);
});
mutationObserverMicrotask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function() {});
});
}, 'delayed handling: a microtask delay before attaching a handler prevents both events (immediately-rejected new ' +
'Promise-created promise)');
async_test(function(t) {
var e = new Error();
var p1;
var p2;
onUnhandledFail(t, function() { return p1; });
onUnhandledFail(t, function() { return p2; });
p1 = new Promise(function(_, reject) {
mutationObserverMicrotask(function() {
reject(e);
});
});
p2 = Promise.all([p1]);
mutationObserverMicrotask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p2.then(unreached, function() {});
});
}, 'delayed handling: a microtask delay before attaching the handler, and before rejecting the promise, indirected ' +
'through Promise.all');
//
// Negative unhandledrejection/rejectionhandled tests with nested-microtask-delayed attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = Promise.reject(e);
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
}, 'microtask nesting: attaching a handler inside a combination of mutationObserverMicrotask + promise microtasks');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
postMessageTask(function() {
p = Promise.reject(e);
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
});
}, 'microtask nesting: attaching a handler inside a combination of mutationObserverMicrotask + promise microtasks, ' +
'all inside a postMessageTask');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
setTimeout(function() {
p = Promise.reject(e);
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
}, 0);
}, 'microtask nesting: attaching a handler inside a combination of mutationObserverMicrotask + promise microtasks, ' +
'all inside a setTimeout');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = Promise.reject(e);
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
p.catch(function() {});
});
});
});
});
}, 'microtask nesting: attaching a handler inside a combination of promise microtasks + mutationObserverMicrotask');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
postMessageTask(function() {
p = Promise.reject(e);
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
p.catch(function() {});
});
});
});
});
});
}, 'microtask nesting: attaching a handler inside a combination of promise microtasks + mutationObserverMicrotask, ' +
'all inside a postMessageTask');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
setTimeout(function() {
p = Promise.reject(e);
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
p.catch(function() {});
});
});
});
});
}, 0);
}, 'microtask nesting: attaching a handler inside a combination of promise microtasks + mutationObserverMicrotask, ' +
'all inside a setTimeout');
//
// Positive unhandledrejection/rejectionhandled tests with delayed attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
var _reject;
p = new Promise(function(_, reject) {
_reject = reject;
});
_reject(e);
postMessageTask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function() {});
});
}, 'delayed handling: a task delay before attaching a handler does not prevent unhandledrejection');
async_test(function(t) {
var unhandledPromises = [];
var unhandledReasons = [];
var e = new Error();
var p;
var unhandled = function(ev) {
if (ev.promise === p) {
t.step(function() {
unhandledPromises.push(ev.promise);
unhandledReasons.push(ev.reason);
});
}
};
var handled = function(ev) {
if (ev.promise === p) {
t.step(function() {
assert_array_equals(unhandledPromises, [p]);
assert_array_equals(unhandledReasons, [e]);
assert_equals(ev.promise, p);
assert_equals(ev.reason, e);
});
}
};
addEventListener('unhandledrejection', unhandled);
addEventListener('rejectionhandled', handled);
ensureCleanup(t, unhandled, handled);
p = new Promise(function() {
throw e;
});
setTimeout(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function(reason) {
assert_equals(reason, e);
setTimeout(function() { t.done(); }, 10);
});
}, 10);
}, 'delayed handling: delaying handling by setTimeout(,10) will cause both events to fire');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.reject(e);
postMessageTask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
}, 'delayed handling: postMessageTask after promise creation/rejection, plus promise microtasks, is too late to ' +
'attach a rejection handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
postMessageTask(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
});
p = Promise.reject(e);
}, 'delayed handling: postMessageTask before promise creation/rejection, plus many promise microtasks, is too late ' +
'to attach a rejection handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.reject(e);
postMessageTask(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
});
}, 'delayed handling: postMessageTask after promise creation/rejection, plus many promise microtasks, is too late ' +
'to attach a rejection handler');
//
// Miscellaneous tests about integration with the rest of the platform
//
async_test(function(t) {
var e = new Error();
var l = function(ev) {
var order = [];
mutationObserverMicrotask(function() {
order.push(1);
});
setTimeout(function() {
order.push(2);
t.step(function() {
assert_array_equals(order, [1, 2]);
});
t.done();
}, 1);
};
addEventListener('unhandledrejection', l);
ensureCleanup(t, l);
Promise.reject(e);
}, 'mutationObserverMicrotask vs. postMessageTask ordering is not disturbed inside unhandledrejection events');
//
// HELPERS
//
function postMessageTask(f) {
if ('document' in self) {
var l = function() {
removeEventListener('message', l);
f();
};
addEventListener('message', l);
postMessage('abusingpostmessageforfunandprofit', '*');
} else {
var channel = new MessageChannel();
channel.port1.onmessage = function() { channel.port1.close(); f(); };
channel.port2.postMessage('abusingpostmessageforfunandprofit');
channel.port2.close();
}
}
function mutationObserverMicrotask(f) {
if ('document' in self) {
var observer = new MutationObserver(function() { f(); });
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
node.data = 'foo';
} else {
// We don't have mutation observers on workers, so just post a promise-based
// microtask.
Promise.resolve().then(function() { f(); });
}
}
function onUnhandledSucceed(t, expectedReason, expectedPromiseGetter) {
var l = function(ev) {
if (ev.promise === expectedPromiseGetter()) {
t.step(function() {
assert_equals(ev.reason, expectedReason);
assert_equals(ev.promise, expectedPromiseGetter());
});
t.done();
}
};
addEventListener('unhandledrejection', l);
ensureCleanup(t, l);
}
function onUnhandledFail(t, expectedPromiseGetter) {
var unhandled = function(evt) {
if (evt.promise === expectedPromiseGetter()) {
t.unreached_func('unhandledrejection event is not supposed to be triggered');
}
};
var handled = function(evt) {
if (evt.promise === expectedPromiseGetter()) {
t.unreached_func('rejectionhandled event is not supposed to be triggered');
}
};
addEventListener('unhandledrejection', unhandled);
addEventListener('rejectionhandled', handled);
ensureCleanup(t, unhandled, handled);
setTimeout(function() {
t.done();
}, 10);
}
function ensureCleanup(t, unhandled, handled) {
t.add_cleanup(function() {
if (unhandled)
removeEventListener('unhandledrejection', unhandled);
if (handled)
removeEventListener('rejectionhandled', handled);
});
}
done();
| {
"content_hash": "46f3e2c246c43b82171d8f8d7255ced4",
"timestamp": "",
"source": "github",
"line_count": 668,
"max_line_length": 122,
"avg_line_length": 27.853293413173652,
"alnum_prop": 0.644362033752553,
"repo_name": "vadimtk/chrome4sdp",
"id": "8c1555588ae4e1d7c0c84647d32ecdd92e118744",
"size": "18606",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "third_party/WebKit/LayoutTests/http/tests/dom/resources/promise-rejection-events.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
/*
* xen console driver interface to hvc_console.c
*
* (c) 2007 Gerd Hoffmann <kraxel@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/console.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/irq.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/list.h>
#include <asm/io.h>
#include <asm/xen/hypervisor.h>
#include <xen/xen.h>
#include <xen/interface/xen.h>
#include <xen/hvm.h>
#include <xen/grant_table.h>
#include <xen/page.h>
#include <xen/events.h>
#include <xen/interface/io/console.h>
#include <xen/interface/sched.h>
#include <xen/hvc-console.h>
#include <xen/xenbus.h>
#include "hvc_console.h"
#define HVC_COOKIE 0x58656e /* "Xen" in hex */
struct xencons_info {
struct list_head list;
struct xenbus_device *xbdev;
struct xencons_interface *intf;
unsigned int evtchn;
struct hvc_struct *hvc;
int irq;
int vtermno;
grant_ref_t gntref;
};
static LIST_HEAD(xenconsoles);
static DEFINE_SPINLOCK(xencons_lock);
/* ------------------------------------------------------------------ */
static struct xencons_info *vtermno_to_xencons(int vtermno)
{
struct xencons_info *entry, *n, *ret = NULL;
if (list_empty(&xenconsoles))
return NULL;
list_for_each_entry_safe(entry, n, &xenconsoles, list) {
if (entry->vtermno == vtermno) {
ret = entry;
break;
}
}
return ret;
}
static inline int xenbus_devid_to_vtermno(int devid)
{
return devid + HVC_COOKIE;
}
static inline void notify_daemon(struct xencons_info *cons)
{
/* Use evtchn: this is called early, before irq is set up. */
notify_remote_via_evtchn(cons->evtchn);
}
static int __write_console(struct xencons_info *xencons,
const char *data, int len)
{
XENCONS_RING_IDX cons, prod;
struct xencons_interface *intf = xencons->intf;
int sent = 0;
cons = intf->out_cons;
prod = intf->out_prod;
mb(); /* update queue values before going on */
BUG_ON((prod - cons) > sizeof(intf->out));
while ((sent < len) && ((prod - cons) < sizeof(intf->out)))
intf->out[MASK_XENCONS_IDX(prod++, intf->out)] = data[sent++];
wmb(); /* write ring before updating pointer */
intf->out_prod = prod;
if (sent)
notify_daemon(xencons);
return sent;
}
static int domU_write_console(uint32_t vtermno, const char *data, int len)
{
int ret = len;
struct xencons_info *cons = vtermno_to_xencons(vtermno);
if (cons == NULL)
return -EINVAL;
/*
* Make sure the whole buffer is emitted, polling if
* necessary. We don't ever want to rely on the hvc daemon
* because the most interesting console output is when the
* kernel is crippled.
*/
while (len) {
int sent = __write_console(cons, data, len);
data += sent;
len -= sent;
if (unlikely(len))
HYPERVISOR_sched_op(SCHEDOP_yield, NULL);
}
return ret;
}
static int domU_read_console(uint32_t vtermno, char *buf, int len)
{
struct xencons_interface *intf;
XENCONS_RING_IDX cons, prod;
int recv = 0;
struct xencons_info *xencons = vtermno_to_xencons(vtermno);
if (xencons == NULL)
return -EINVAL;
intf = xencons->intf;
cons = intf->in_cons;
prod = intf->in_prod;
mb(); /* get pointers before reading ring */
BUG_ON((prod - cons) > sizeof(intf->in));
while (cons != prod && recv < len)
buf[recv++] = intf->in[MASK_XENCONS_IDX(cons++, intf->in)];
mb(); /* read ring before consuming */
intf->in_cons = cons;
notify_daemon(xencons);
return recv;
}
static struct hv_ops domU_hvc_ops = {
.get_chars = domU_read_console,
.put_chars = domU_write_console,
.notifier_add = notifier_add_irq,
.notifier_del = notifier_del_irq,
.notifier_hangup = notifier_hangup_irq,
};
static int dom0_read_console(uint32_t vtermno, char *buf, int len)
{
return HYPERVISOR_console_io(CONSOLEIO_read, len, buf);
}
/*
* Either for a dom0 to write to the system console, or a domU with a
* debug version of Xen
*/
static int dom0_write_console(uint32_t vtermno, const char *str, int len)
{
int rc = HYPERVISOR_console_io(CONSOLEIO_write, len, (char *)str);
if (rc < 0)
return 0;
return len;
}
static struct hv_ops dom0_hvc_ops = {
.get_chars = dom0_read_console,
.put_chars = dom0_write_console,
.notifier_add = notifier_add_irq,
.notifier_del = notifier_del_irq,
.notifier_hangup = notifier_hangup_irq,
};
static int xen_hvm_console_init(void)
{
int r;
uint64_t v = 0;
unsigned long mfn;
struct xencons_info *info;
if (!xen_hvm_domain())
return -ENODEV;
info = vtermno_to_xencons(HVC_COOKIE);
if (!info) {
info = kzalloc(sizeof(struct xencons_info), GFP_KERNEL | __GFP_ZERO);
if (!info)
return -ENOMEM;
} else if (info->intf != NULL) {
/* already configured */
return 0;
}
/*
* If the toolstack (or the hypervisor) hasn't set these values, the
* default value is 0. Even though mfn = 0 and evtchn = 0 are
* theoretically correct values, in practice they never are and they
* mean that a legacy toolstack hasn't initialized the pv console correctly.
*/
r = hvm_get_parameter(HVM_PARAM_CONSOLE_EVTCHN, &v);
if (r < 0 || v == 0)
goto err;
info->evtchn = v;
v = 0;
r = hvm_get_parameter(HVM_PARAM_CONSOLE_PFN, &v);
if (r < 0 || v == 0)
goto err;
mfn = v;
info->intf = xen_remap(mfn << PAGE_SHIFT, PAGE_SIZE);
if (info->intf == NULL)
goto err;
info->vtermno = HVC_COOKIE;
spin_lock(&xencons_lock);
list_add_tail(&info->list, &xenconsoles);
spin_unlock(&xencons_lock);
return 0;
err:
kfree(info);
return -ENODEV;
}
static int xen_pv_console_init(void)
{
struct xencons_info *info;
if (!xen_pv_domain())
return -ENODEV;
if (!xen_start_info->console.domU.evtchn)
return -ENODEV;
info = vtermno_to_xencons(HVC_COOKIE);
if (!info) {
info = kzalloc(sizeof(struct xencons_info), GFP_KERNEL | __GFP_ZERO);
if (!info)
return -ENOMEM;
} else if (info->intf != NULL) {
/* already configured */
return 0;
}
info->evtchn = xen_start_info->console.domU.evtchn;
info->intf = mfn_to_virt(xen_start_info->console.domU.mfn);
info->vtermno = HVC_COOKIE;
spin_lock(&xencons_lock);
list_add_tail(&info->list, &xenconsoles);
spin_unlock(&xencons_lock);
return 0;
}
static int xen_initial_domain_console_init(void)
{
struct xencons_info *info;
if (!xen_initial_domain())
return -ENODEV;
info = vtermno_to_xencons(HVC_COOKIE);
if (!info) {
info = kzalloc(sizeof(struct xencons_info), GFP_KERNEL | __GFP_ZERO);
if (!info)
return -ENOMEM;
}
info->irq = bind_virq_to_irq(VIRQ_CONSOLE, 0);
info->vtermno = HVC_COOKIE;
spin_lock(&xencons_lock);
list_add_tail(&info->list, &xenconsoles);
spin_unlock(&xencons_lock);
return 0;
}
static void xen_console_update_evtchn(struct xencons_info *info)
{
if (xen_hvm_domain()) {
uint64_t v;
int err;
err = hvm_get_parameter(HVM_PARAM_CONSOLE_EVTCHN, &v);
if (!err && v)
info->evtchn = v;
} else
info->evtchn = xen_start_info->console.domU.evtchn;
}
void xen_console_resume(void)
{
struct xencons_info *info = vtermno_to_xencons(HVC_COOKIE);
if (info != NULL && info->irq) {
if (!xen_initial_domain())
xen_console_update_evtchn(info);
rebind_evtchn_irq(info->evtchn, info->irq);
}
}
static void xencons_disconnect_backend(struct xencons_info *info)
{
if (info->irq > 0)
unbind_from_irqhandler(info->irq, NULL);
info->irq = 0;
if (info->evtchn > 0)
xenbus_free_evtchn(info->xbdev, info->evtchn);
info->evtchn = 0;
if (info->gntref > 0)
gnttab_free_grant_references(info->gntref);
info->gntref = 0;
if (info->hvc != NULL)
hvc_remove(info->hvc);
info->hvc = NULL;
}
static void xencons_free(struct xencons_info *info)
{
free_page((unsigned long)info->intf);
info->intf = NULL;
info->vtermno = 0;
kfree(info);
}
static int xen_console_remove(struct xencons_info *info)
{
xencons_disconnect_backend(info);
spin_lock(&xencons_lock);
list_del(&info->list);
spin_unlock(&xencons_lock);
if (info->xbdev != NULL)
xencons_free(info);
else {
if (xen_hvm_domain())
iounmap(info->intf);
kfree(info);
}
return 0;
}
#ifdef CONFIG_HVC_XEN_FRONTEND
static struct xenbus_driver xencons_driver;
static int xencons_remove(struct xenbus_device *dev)
{
return xen_console_remove(dev_get_drvdata(&dev->dev));
}
static int xencons_connect_backend(struct xenbus_device *dev,
struct xencons_info *info)
{
int ret, evtchn, devid, ref, irq;
struct xenbus_transaction xbt;
grant_ref_t gref_head;
unsigned long mfn;
ret = xenbus_alloc_evtchn(dev, &evtchn);
if (ret)
return ret;
info->evtchn = evtchn;
irq = bind_evtchn_to_irq(evtchn);
if (irq < 0)
return irq;
info->irq = irq;
devid = dev->nodename[strlen(dev->nodename) - 1] - '0';
info->hvc = hvc_alloc(xenbus_devid_to_vtermno(devid),
irq, &domU_hvc_ops, 256);
if (IS_ERR(info->hvc))
return PTR_ERR(info->hvc);
if (xen_pv_domain())
mfn = virt_to_mfn(info->intf);
else
mfn = __pa(info->intf) >> PAGE_SHIFT;
ret = gnttab_alloc_grant_references(1, &gref_head);
if (ret < 0)
return ret;
info->gntref = gref_head;
ref = gnttab_claim_grant_reference(&gref_head);
if (ref < 0)
return ref;
gnttab_grant_foreign_access_ref(ref, info->xbdev->otherend_id,
mfn, 0);
again:
ret = xenbus_transaction_start(&xbt);
if (ret) {
xenbus_dev_fatal(dev, ret, "starting transaction");
return ret;
}
ret = xenbus_printf(xbt, dev->nodename, "ring-ref", "%d", ref);
if (ret)
goto error_xenbus;
ret = xenbus_printf(xbt, dev->nodename, "port", "%u",
evtchn);
if (ret)
goto error_xenbus;
ret = xenbus_printf(xbt, dev->nodename, "type", "ioemu");
if (ret)
goto error_xenbus;
ret = xenbus_transaction_end(xbt, 0);
if (ret) {
if (ret == -EAGAIN)
goto again;
xenbus_dev_fatal(dev, ret, "completing transaction");
return ret;
}
xenbus_switch_state(dev, XenbusStateInitialised);
return 0;
error_xenbus:
xenbus_transaction_end(xbt, 1);
xenbus_dev_fatal(dev, ret, "writing xenstore");
return ret;
}
static int xencons_probe(struct xenbus_device *dev,
const struct xenbus_device_id *id)
{
int ret, devid;
struct xencons_info *info;
devid = dev->nodename[strlen(dev->nodename) - 1] - '0';
if (devid == 0)
return -ENODEV;
info = kzalloc(sizeof(struct xencons_info), GFP_KERNEL);
if (!info)
return -ENOMEM;
dev_set_drvdata(&dev->dev, info);
info->xbdev = dev;
info->vtermno = xenbus_devid_to_vtermno(devid);
info->intf = (void *)__get_free_page(GFP_KERNEL | __GFP_ZERO);
if (!info->intf)
goto error_nomem;
ret = xencons_connect_backend(dev, info);
if (ret < 0)
goto error;
spin_lock(&xencons_lock);
list_add_tail(&info->list, &xenconsoles);
spin_unlock(&xencons_lock);
return 0;
error_nomem:
ret = -ENOMEM;
xenbus_dev_fatal(dev, ret, "allocating device memory");
error:
xencons_disconnect_backend(info);
xencons_free(info);
return ret;
}
static int xencons_resume(struct xenbus_device *dev)
{
struct xencons_info *info = dev_get_drvdata(&dev->dev);
xencons_disconnect_backend(info);
memset(info->intf, 0, PAGE_SIZE);
return xencons_connect_backend(dev, info);
}
static void xencons_backend_changed(struct xenbus_device *dev,
enum xenbus_state backend_state)
{
switch (backend_state) {
case XenbusStateReconfiguring:
case XenbusStateReconfigured:
case XenbusStateInitialising:
case XenbusStateInitialised:
case XenbusStateUnknown:
break;
case XenbusStateInitWait:
break;
case XenbusStateConnected:
xenbus_switch_state(dev, XenbusStateConnected);
break;
case XenbusStateClosed:
if (dev->state == XenbusStateClosed)
break;
/* Missed the backend's CLOSING state -- fallthrough */
case XenbusStateClosing:
xenbus_frontend_closed(dev);
break;
}
}
static const struct xenbus_device_id xencons_ids[] = {
{ "console" },
{ "" }
};
static DEFINE_XENBUS_DRIVER(xencons, "xenconsole",
.probe = xencons_probe,
.remove = xencons_remove,
.resume = xencons_resume,
.otherend_changed = xencons_backend_changed,
);
#endif /* CONFIG_HVC_XEN_FRONTEND */
static int __init xen_hvc_init(void)
{
int r;
struct xencons_info *info;
const struct hv_ops *ops;
if (!xen_domain())
return -ENODEV;
if (xen_initial_domain()) {
ops = &dom0_hvc_ops;
r = xen_initial_domain_console_init();
if (r < 0)
return r;
info = vtermno_to_xencons(HVC_COOKIE);
} else {
ops = &domU_hvc_ops;
if (xen_hvm_domain())
r = xen_hvm_console_init();
else
r = xen_pv_console_init();
if (r < 0)
return r;
info = vtermno_to_xencons(HVC_COOKIE);
info->irq = bind_evtchn_to_irq(info->evtchn);
}
if (info->irq < 0)
info->irq = 0; /* NO_IRQ */
else
irq_set_noprobe(info->irq);
info->hvc = hvc_alloc(HVC_COOKIE, info->irq, ops, 256);
if (IS_ERR(info->hvc)) {
r = PTR_ERR(info->hvc);
spin_lock(&xencons_lock);
list_del(&info->list);
spin_unlock(&xencons_lock);
if (info->irq)
unbind_from_irqhandler(info->irq, NULL);
kfree(info);
return r;
}
r = 0;
#ifdef CONFIG_HVC_XEN_FRONTEND
r = xenbus_register_frontend(&xencons_driver);
#endif
return r;
}
static void __exit xen_hvc_fini(void)
{
struct xencons_info *entry, *next;
if (list_empty(&xenconsoles))
return;
list_for_each_entry_safe(entry, next, &xenconsoles, list) {
xen_console_remove(entry);
}
}
static int xen_cons_init(void)
{
const struct hv_ops *ops;
if (!xen_domain())
return 0;
if (xen_initial_domain())
ops = &dom0_hvc_ops;
else {
int r;
ops = &domU_hvc_ops;
if (xen_hvm_domain())
r = xen_hvm_console_init();
else
r = xen_pv_console_init();
if (r < 0)
return r;
}
hvc_instantiate(HVC_COOKIE, 0, ops);
return 0;
}
module_init(xen_hvc_init);
module_exit(xen_hvc_fini);
console_initcall(xen_cons_init);
#ifdef CONFIG_EARLY_PRINTK
static void xenboot_write_console(struct console *console, const char *string,
unsigned len)
{
unsigned int linelen, off = 0;
const char *pos;
if (!xen_pv_domain())
return;
dom0_write_console(0, string, len);
if (xen_initial_domain())
return;
domU_write_console(0, "(early) ", 8);
while (off < len && NULL != (pos = strchr(string+off, '\n'))) {
linelen = pos-string+off;
if (off + linelen > len)
break;
domU_write_console(0, string+off, linelen);
domU_write_console(0, "\r\n", 2);
off += linelen + 1;
}
if (off < len)
domU_write_console(0, string+off, len-off);
}
struct console xenboot_console = {
.name = "xenboot",
.write = xenboot_write_console,
.flags = CON_PRINTBUFFER | CON_BOOT | CON_ANYTIME,
.index = -1,
};
#endif /* CONFIG_EARLY_PRINTK */
void xen_raw_console_write(const char *str)
{
dom0_write_console(0, str, strlen(str));
}
void xen_raw_printk(const char *fmt, ...)
{
static char buf[512];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
xen_raw_console_write(buf);
}
| {
"content_hash": "430af621b96f09283afb0778587f6ee8",
"timestamp": "",
"source": "github",
"line_count": 674,
"max_line_length": 78,
"avg_line_length": 22.735905044510385,
"alnum_prop": 0.6690811798486035,
"repo_name": "OLIMEX/DIY-LAPTOP",
"id": "ff92155dbc88c6e026482e7c3afad1a7b9c6ea30",
"size": "15324",
"binary": false,
"copies": "504",
"ref": "refs/heads/rel3",
"path": "SOFTWARE/A64-TERES/linux-a64/drivers/tty/hvc/hvc_xen.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "11134321"
},
{
"name": "Awk",
"bytes": "19031"
},
{
"name": "Batchfile",
"bytes": "8351"
},
{
"name": "C",
"bytes": "567314664"
},
{
"name": "C++",
"bytes": "490541"
},
{
"name": "CSS",
"bytes": "3924"
},
{
"name": "Classic ASP",
"bytes": "4528"
},
{
"name": "Dockerfile",
"bytes": "652"
},
{
"name": "GDB",
"bytes": "21755"
},
{
"name": "Lex",
"bytes": "55791"
},
{
"name": "M4",
"bytes": "3388"
},
{
"name": "Makefile",
"bytes": "2068526"
},
{
"name": "PHP",
"bytes": "54081"
},
{
"name": "Perl",
"bytes": "701416"
},
{
"name": "Python",
"bytes": "307470"
},
{
"name": "Raku",
"bytes": "3727"
},
{
"name": "Roff",
"bytes": "63487"
},
{
"name": "Scilab",
"bytes": "21433"
},
{
"name": "Shell",
"bytes": "328623"
},
{
"name": "SmPL",
"bytes": "69316"
},
{
"name": "Tcl",
"bytes": "967"
},
{
"name": "UnrealScript",
"bytes": "6113"
},
{
"name": "XS",
"bytes": "1240"
},
{
"name": "XSLT",
"bytes": "445"
},
{
"name": "Yacc",
"bytes": "101755"
},
{
"name": "sed",
"bytes": "3126"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<title>Bamboo Flute Making - Part 1 - Binding | Rab Fulton</title>
<meta name="description" content="In this post I cover how to tie a binding knot commonly used by flute makers around the world to decorate, reinforce or repair an instrument.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-Frame-Options" content="sameorigin">
<!-- CSS -->
<link rel="stylesheet" href="/css/main.css">
<!--Favicon-->
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
<!-- Canonical -->
<link rel="canonical" href="http://localhost:4000/2015/06/27/Flute-Making-Part-1-Bindings.html">
<!-- RSS -->
<link rel="alternate" type="application/atom+xml" title="Rab Fulton" href="http://localhost:4000/feed.xml" />
<!-- Font Awesome -->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Google Fonts -->
<link href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,700italic,400italic" rel="stylesheet" type="text/css">
<!-- KaTeX -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min.js"></script>
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-57327814-2', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<header class="site-header">
<div class="branding">
<h1 class="site-title">
<a href="/">Rab Fulton</a>
</h1>
</div>
<nav class="site-nav">
<ul>
<li>
<a class="page-link" href="/about/">
About
</a>
</li>
<!-- Social icons from Font Awesome, if enabled -->
<li>
<a href="mailto:rabfulton@gmail.com" title="Email">
<i class="fa fa-fw fa-envelope"></i>
</a>
</li>
<li>
<a href="https://plus.google.com/u/0/108624488609783583375/posts/" title="Follow on Google+">
<i class="fa fa-fw fa-google-plus"></i>
</a>
</li>
</ul>
</nav>
</header>
<div class="content">
<article >
<header style="background-image: url('/')">
<h1 class="title">Bamboo Flute Making - Part 1 - Binding</h1>
<p class="meta">
June 27, 2015
</p>
</header>
<section class="post-content"><p>In this post I cover how to tie a binding knot commonly used by flute makers around the world to decorate, reinforce or repair an instrument.</p>
<p>I use fishing line for my bindings, you can use any type of string or material of choice, as long as it is strong. For a binding to be effective it must be as tight as possible. Begin by taking a few meters of your line and tying one end to something solid. At the other end create a loop and pin it in place on the instrument.</p>
<p><img src="/img/bind1.jpg" alt="Binding stage 1" /></p>
<p>Next comes the trickiest part. Begin by making a few wraps round working from the pinched base of the loop upwards. Try to get as much tension as practicable.</p>
<p><img src="/img/bind2.jpg" alt="Binding stage 2" /></p>
<p>Now continue wrapping round by rotating the flute while pulling away from the tied end. You can walk your thumbs over the bindings as you do this to prevent the binding from slipping. As you add more wraps you can keep increasing the tension by keeping a constant pull on the line as you wrap.</p>
<p><img src="/img/bind3.jpg" alt="Binding stage 3" /></p>
<p>Once you have the desired number of wraps, pin them tightly in place with your thumb and cut the line free from where you tied it.</p>
<p>Now take the free end and pass it through the top of the loop. Your loops should be much tighter than those pictured as you not simultaneously trying to operate a camera one handed.</p>
<p><img src="/img/bind4.jpg" alt="Binding stage 4" /></p>
<p>Begin pulling the loose end that was used to form the initial loop until the the loop starts to pull the newly cut end under the wraps. Now hold both ends tightly and pull them until the loop is centered under the wraps. As the loop slips under you will see the cross of the line as a lump under the wraps. This allows you to gauge the center.</p>
<p>It should require considerable force for this last step if wrapped the flute tightly enough.</p>
<p><img src="/img/bind5.jpg" alt="Binding stage 5" /></p>
<p>Complete the knot by trimming the ends with a scalpel and if you like add a drop of thin CA glue over the cross.</p>
<p><img src="/img/bind6.jpg" alt="Binding stage 6" /></p>
<p>You can see some of my bamboo flutes on <a href="https://plus.google.com/u/0/108624488609783583375/posts">Google+</a> and for sale on <a href="https://www.etsy.com/uk/shop/Soundcraft?ref=hdr_shop_menu">etsy</a>.</p>
<p>Also check out my <a href="http://duosear.ch/@rabfulton">OpenBazaar</a> listings.</p>
<script type="text/javascript" src="https://www.etsy.com/assets/js/etsy_mini_shop.js"></script>
<script type="text/javascript">new Etsy.Mini(10967912,'gallery',4,3,0,'https://www.etsy.com');</script>
</section>
</article>
<!-- Post navigation -->
<!-- Disqus -->
<!-- Muut -->
</div>
<script src="/js/katex_init.js"></script>
<footer class="site-footer">
<p class="text">Follow <a href="http://plus.google.com/u/0/108624488609783583375/posts/">Google + </a> See what I have for sale on <a href="http://www.etsy.com/uk/shop/Soundcraft?ref=hdr_shop_menu">Etsy</a>
</p>
</footer>
</body>
</html>
| {
"content_hash": "8644b7d5e4605631c06f75af9561e631",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 350,
"avg_line_length": 28.478048780487804,
"alnum_prop": 0.6724905789653991,
"repo_name": "rabfulton/rabfulton.github.io",
"id": "be52b387346f338a98b4dff815cb52c55b642ac9",
"size": "5838",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_site/2015/06/27/Flute-Making-Part-1-Bindings.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6819"
},
{
"name": "HTML",
"bytes": "85561"
},
{
"name": "JavaScript",
"bytes": "739"
},
{
"name": "Ruby",
"bytes": "77"
}
],
"symlink_target": ""
} |
#region licence
// The MIT License (MIT)
//
// Filename: SecurityHelper.cs
// Date Created: 2014/08/26
//
// Copyright (c) 2014 Jon Smith (www.selectiveanalytics.com & www.thereformedprogrammer.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using System;
using System.Data.Entity;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using GenericLibsBase;
using GenericLibsBase.Core;
namespace GenericServices.Core
{
public static class SecurityHelper
{
/// <summary>
/// This will take an IQueryable request and add single on the end to realise the request.
/// It catches if the single didn't produce an item
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="request">An IQueryable request with a filter that yeilds a single item</param>
/// <param name="methodName">Do not specify. System fills this in with the calling method</param>
/// <returns>Returns status. If Valid then status.Result is the single item, otherwise an new, empty class</returns>
public static ISuccessOrErrors<T> RealiseSingleWithErrorChecking<T>(this IQueryable<T> request, [CallerMemberName] string methodName = "") where T : class, new()
{
var status = new SuccessOrErrors<T>(new T(), "we return empty class if it fails");
try
{
var result = request.SingleOrDefault();
if (result == null)
status.AddSingleError(
"We could not find an entry using that filter. Has it been deleted by someone else?");
else
status.SetSuccessWithResult(result, "successful");
}
catch (Exception ex)
{
if (GenericServicesConfig.RealiseSingleExceptionMethod == null) throw; //nothing to catch error
var errMsg = GenericServicesConfig.RealiseSingleExceptionMethod(ex, methodName);
if (errMsg != null)
status.AddSingleError(errMsg);
else
throw; //do not understand the error so rethrow
}
return status;
}
/// <summary>
/// This will take an IQueryable request and add single on the end to realise the request.
/// It catches if the single didn't produce an item
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="request">An IQueryable request with a filter that yeilds a single item</param>
/// <param name="methodName">Do not specify. System fills this in with the calling method</param>
/// <returns>Returns task with status. If Valid then status.Result is the single item, otherwise an new, empty class</returns>
public static async Task<ISuccessOrErrors<T>> RealiseSingleWithErrorCheckingAsync<T>(this IQueryable<T> request, [CallerMemberName] string methodName = "") where T : class, new()
{
var status = new SuccessOrErrors<T>(new T(), "we return empty class if it fails");
try
{
var result = await request.SingleOrDefaultAsync().ConfigureAwait(false);
if (result == null)
status.AddSingleError(
"We could not find an entry using that filter. Has it been deleted by someone else?");
else
status.SetSuccessWithResult(result, "successful");
}
catch (Exception ex)
{
if (GenericServicesConfig.RealiseSingleExceptionMethod == null) throw; //nothing to catch error
var errMsg = GenericServicesConfig.RealiseSingleExceptionMethod(ex, methodName);
if (errMsg != null)
status.AddSingleError(errMsg);
else
throw; //do not understand the error so rethrow
}
return status;
}
}
}
| {
"content_hash": "762bb0b5ae0f30470653afe30218c324",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 186,
"avg_line_length": 47.47663551401869,
"alnum_prop": 0.6374015748031496,
"repo_name": "JonPSmith/GenericServices",
"id": "fff6ddfa085b06817d7eadb5858e23e4ae62329b",
"size": "5082",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GenericServices/Core/SecurityHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "738155"
}
],
"symlink_target": ""
} |
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "tensorflow/compiler/xla/stream_executor/tpu/status_helper.h"
#include "tensorflow/compiler/xla/stream_executor/tpu/tpu_api.h"
#include "tensorflow/compiler/xla/stream_executor/tpu/tpu_ops_c_api.h"
#include "tensorflow/tsl/platform/errors.h"
#include "tensorflow/tsl/platform/status.h"
#include "tensorflow/tsl/platform/types.h"
#include "tensorflow/tsl/profiler/lib/profiler_factory.h"
#include "tensorflow/tsl/profiler/lib/profiler_interface.h"
#include "tensorflow/tsl/profiler/protobuf/profiler_options.pb.h"
#include "tensorflow/tsl/profiler/protobuf/xplane.pb.h"
#include "tensorflow/tsl/profiler/utils/xplane_schema.h"
namespace xla {
namespace profiler {
namespace {
using tensorflow::ProfileOptions;
using tensorflow::profiler::XPlane;
using tensorflow::profiler::XSpace;
using tsl::OkStatus; // TENSORFLOW_STATUS_OK
using tsl::Status; // TENSORFLOW_STATUS_OK
using tsl::profiler::ProfilerInterface;
// Tpu implementation of ProfilerInterface.
//
// Thread-safety: This class is go/thread-compatible.
class TpuTracer : public ProfilerInterface {
public:
explicit TpuTracer();
~TpuTracer() override;
Status Start() override;
Status Stop() override;
Status CollectData(XSpace* space) override;
private:
TpuProfiler* tpu_profiler_;
};
TpuTracer::TpuTracer() {
StatusHelper status;
stream_executor::tpu::OpsApiFn()->TpuProfiler_CreateFn(&tpu_profiler_,
status.c_status);
if (!status.ok()) {
LOG(ERROR) << status.status().error_message();
}
}
TpuTracer::~TpuTracer() {
stream_executor::tpu::OpsApiFn()->TpuProfiler_DestroyFn(tpu_profiler_);
}
Status TpuTracer::Start() {
StatusHelper status;
stream_executor::tpu::OpsApiFn()->TpuProfiler_StartFn(tpu_profiler_,
status.c_status);
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to start.";
return status.status();
}
return OkStatus();
}
Status TpuTracer::Stop() {
StatusHelper status;
stream_executor::tpu::OpsApiFn()->TpuProfiler_StopFn(tpu_profiler_,
status.c_status);
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to stop.";
return status.status();
}
return OkStatus();
}
Status TpuTracer::CollectData(XSpace* space) {
StatusHelper status;
// Get size of buffer required for TPU driver to serialize XSpace into.
size_t size_in_bytes;
stream_executor::tpu::OpsApiFn()->TpuProfiler_CollectDataFn(
tpu_profiler_, status.c_status,
/*buffer=*/nullptr, &size_in_bytes);
// Prepare an appropriately sized buffer.
if (size_in_bytes > 0) {
std::vector<uint8_t> buffer(size_in_bytes);
stream_executor::tpu::OpsApiFn()->TpuProfiler_CollectDataFn(
tpu_profiler_, status.c_status, buffer.data(), &size_in_bytes);
// Deserialize XSpace from the buffer and return it.
XSpace tpu_space;
tpu_space.ParseFromArray(buffer.data(), buffer.size());
for (XPlane& tpu_plane : *tpu_space.mutable_planes()) {
XPlane* plane = space->add_planes();
plane->Swap(&tpu_plane);
}
}
if (!status.ok()) {
LOG(ERROR) << "TPU tracer failed to collect data.";
return status.status();
}
return OkStatus();
}
} // namespace
// Not in anonymous namespace for testing purposes.
std::unique_ptr<ProfilerInterface> CreateTpuTracer(
const ProfileOptions& options) {
if (options.device_type() != ProfileOptions::TPU &&
options.device_type() != ProfileOptions::UNSPECIFIED) {
return nullptr;
}
// Don't attempt to create a TpuTracer if the TPU C API isn't initialized.
if (stream_executor::tpu::OpsApiFn()->TpuProfiler_CreateFn == nullptr) {
return nullptr;
}
return std::make_unique<TpuTracer>();
}
auto register_tpu_tracer_factory = [] {
RegisterProfilerFactory(&CreateTpuTracer);
return 0;
}();
} // namespace profiler
} // namespace xla
| {
"content_hash": "800bb5beaf23310836c8a9a8746db471",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 76,
"avg_line_length": 30.567164179104477,
"alnum_prop": 0.68017578125,
"repo_name": "tensorflow/tensorflow-pywrap_saved_model",
"id": "48f9ec1beadd1a359f77cfe1a36d714b9adeebfb",
"size": "4764",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "tensorflow/compiler/xla/backends/profiler/tpu/tpu_tracer.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "36962"
},
{
"name": "C",
"bytes": "1392153"
},
{
"name": "C#",
"bytes": "13584"
},
{
"name": "C++",
"bytes": "125860957"
},
{
"name": "CMake",
"bytes": "182324"
},
{
"name": "Cython",
"bytes": "5003"
},
{
"name": "Dockerfile",
"bytes": "416133"
},
{
"name": "Go",
"bytes": "2123155"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "1074438"
},
{
"name": "Jupyter Notebook",
"bytes": "792906"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "11347297"
},
{
"name": "Makefile",
"bytes": "2760"
},
{
"name": "Objective-C",
"bytes": "172666"
},
{
"name": "Objective-C++",
"bytes": "300208"
},
{
"name": "Pawn",
"bytes": "5552"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "42738981"
},
{
"name": "Roff",
"bytes": "5034"
},
{
"name": "Ruby",
"bytes": "9214"
},
{
"name": "Shell",
"bytes": "621427"
},
{
"name": "Smarty",
"bytes": "89545"
},
{
"name": "SourcePawn",
"bytes": "14625"
},
{
"name": "Starlark",
"bytes": "7720442"
},
{
"name": "Swift",
"bytes": "78435"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
'use strict';
(function() {
describe('first filter Spec', function() {
// Initialize global variables
var firstFilter;
beforeEach(module('angular-toolbox'));
beforeEach(inject(function(_firstFilter_) {
firstFilter = _firstFilter_;
}));
it('should be testable', inject(function() {
expect(firstFilter).toBeDefined();
}));
it('should returns the first element of an array', inject(function() {
expect(firstFilter([5, 4, 3, 2, 1])).toEqual(5);
}));
it('should return undefined if array is empty', function () {
expect(firstFilter([])).toBeUndefined();
});
describe('head alias', function () {
var headFilter;
beforeEach(inject(function(_headFilter_) {
headFilter = _headFilter_;
}));
it('should be an alias', inject(function() {
expect(headFilter).toBe(firstFilter);
}));
});
});
}()); | {
"content_hash": "b203f048c254375762a37ae70a69b761",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 72,
"avg_line_length": 26.054054054054053,
"alnum_prop": 0.5663900414937759,
"repo_name": "nicolaspanel/angular-toolbox",
"id": "324ef675184c1f35a8b44ae05b943b8767f4d449",
"size": "964",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/first.filter.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "27879"
}
],
"symlink_target": ""
} |
struct IDataObject;
namespace WebKit {
class WebDragData;
}
struct WebDropData {
// Construct with a given drag identity. Note: identity is an int32 because
// it is passed over the renderer NPAPI interface to gears.
explicit WebDropData(int32 drag_identity) : identity(drag_identity) {}
// Construct from a WebDragData object.
explicit WebDropData(const WebKit::WebDragData&);
// For default constructions, use drag |identity| 0.
WebDropData() : identity(0) {}
int32 identity;
// User is dragging a link into the webview.
GURL url;
string16 url_title; // The title associated with |url|.
// File extension for dragging images from a webview to the desktop.
string16 file_extension;
// User is dropping one or more files on the webview.
std::vector<string16> filenames;
// User is dragging plain text into the webview.
string16 plain_text;
// User is dragging text/html into the webview (e.g., out of Firefox).
// |html_base_url| is the URL that the html fragment is taken from (used to
// resolve relative links). It's ok for |html_base_url| to be empty.
string16 text_html;
GURL html_base_url;
// User is dragging data from the webview (e.g., an image).
string16 file_description_filename;
std::string file_contents;
// Convert to a WebDragData object.
WebKit::WebDragData ToDragData() const;
// Helper method for converting Window's specific IDataObject to a WebDropData
// object. TODO(tc): Move this to the browser side since it's Windows
// specific and no longer used in webkit.
static void PopulateWebDropData(IDataObject* data_object,
WebDropData* drop_data);
};
#endif // WEBKIT_GLUE_WEBDROPDATA_H_
| {
"content_hash": "04a3079fbe01faeb1b78c8876dd8499f",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 80,
"avg_line_length": 32.528301886792455,
"alnum_prop": 0.7105568445475638,
"repo_name": "rwatson/chromium-capsicum",
"id": "fe8db6a4e23ac0ea30419dde022463c3cca14034",
"size": "2231",
"binary": false,
"copies": "3",
"ref": "refs/heads/chromium-capsicum",
"path": "webkit/glue/webdropdata.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
layout: about.hbs
title: Sobre
trademark: Trademark
---
# Sobre Node.js®
<!--
As an asynchronous event driven JavaScript runtime, Node is designed to build
scalable network applications. In the following "hello world" example, many
connections can be handled concurrently. Upon each connection the callback is
fired, but if there is no work to be done, Node will sleep.
-->
Como um ambiente de execução Javascript assíncrono orientado a eventos, o Node.js
é projetado para desenvolvimento de aplicações escaláveis de rede. No exemplo a
seguir, diversas conexões podem ser controladas ao mesmo tempo. Em cada conexão
a função de _callback_ é chamada. Mas, se não houver trabalho a ser realizado,
o Node.js ficará inativo.
```javascript
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
```
<!--
This is in contrast to today's more common concurrency model where OS threads
are employed. Thread-based networking is relatively inefficient and very
difficult to use. Furthermore, users of Node are free from worries of
dead-locking the process, since there are no locks. Almost no function in Node
directly performs I/O, so the process never blocks. Because nothing blocks,
scalable systems are very reasonable to develop in Node.
If some of this language is unfamiliar, there is a full article on
[Blocking vs Non-Blocking][].
-->
Essa é uma alternativa que contrasta com o modelo de concorrência mais comum, onde são
utilizadas _threads_ do SO. Aplicações de rede baseadas em _threads_ são relativamente
ineficientes e difíceis de usar. Além disso, os usuários do Node.js não precisam
se preocupar com _deadlock_ de processos, pois não existem _locks_. Quase nenhuma função
no Node.js realiza diretamente operações de E/S, por essa razão o processo nunca bloqueia.
Por não existirem operações bloqueantes, sistemas escaláveis são razoavelmente fáceis
de serem desenvolvidos em Node.js.
Se algum desses conceitos não é familiar, dê uma olhada no artigo [Blocking vs Non-Blocking][].
---
<!--
Node is similar in design to, and influenced by, systems like Ruby's
[Event Machine][] or Python's [Twisted][]. Node takes the event model a bit
further. It presents an [event loop][] as a runtime construct instead of as a library.
In other systems there is always a blocking call to start the event-loop.
Typically behavior is defined through callbacks at the beginning of a script
and at the end starts a server through a blocking call like
`EventMachine::run()`. In Node there is no such start-the-event-loop call. Node
simply enters the event loop after executing the input script. Node exits the
event loop when there are no more callbacks to perform. This behavior is like
browser JavaScript — the event loop is hidden from the user.
-->
Node.js é semelhante no projeto, e influenciado por sistemas como [Event Machine][] do Ruby
ou [Twisted][] do Python. Porém, leva o modelo de eventos um pouco mais além. No Node.js o _[event loop][]_
é exposto como uma parte do ambiente de execução ao invés de uma biblioteca. Em outros sistemas há
sempre uma chamada bloqueante para iniciar o _event-loop_. Tipicamente o comportamento esperado é
definido através de _callbacks_ no início do _script_, e no final um servidor é iniciado por uma
chamada bloqueante como por exemplo `EventMachine::run()`.
<!--
HTTP is a first class citizen in Node, designed with streaming and low latency
in mind. This makes Node well suited for the foundation of a web library or
framework.
-->
Em Node.js, HTTP é um cidadão de primeira classe, projetado para que tenha um alta
taxa de fluxo e baixa latência. Isso torna o Node.js uma ótima escolha para servir como base para
uma biblioteca web ou para um _framework_.
<!--
Just because Node is designed without threads, doesn't mean you cannot take
advantage of multiple cores in your environment. Child processes can be spawned
by using our [`child_process.fork()`][] API, and are designed to be easy to
communicate with. Built upon that same interface is the [`cluster`][] module,
which allows you to share sockets between processes to enable load balancing
over your cores.
-->
Embora Node.js seja projetado sem a utilização de _threads_, isso não quer dizer que
você não possa tirar vantagens de múltiplos núcleos de processamento em seu ambiente.
Processos filhos podem ser criados utilizando a API [`child_process.fork()`][], e foram
desenvolvidos para que a comunicação entre eles seja fácil. Da mesma maneira foi o módulo
[`cluster`][], que permite o compartilhamento de _sockets_ entre os processos, a fim de
permitir o balanceamento de carga entre os núcleos.
[Blocking vs Non-Blocking]: /en/docs/guides/blocking-vs-non-blocking/
[`child_process.fork()`]: https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options
[`cluster`]: https://nodejs.org/api/cluster.html
[event loop]: /en/docs/guides/event-loop-timers-and-nexttick/
[Event Machine]: https://github.com/eventmachine/eventmachine
[Twisted]: https://twistedmatrix.com/trac/
| {
"content_hash": "dc5bd7a7c2248c8c2ade1bd094debd60",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 124,
"avg_line_length": 48.6605504587156,
"alnum_prop": 0.7714932126696833,
"repo_name": "phillipj/new.nodejs.org",
"id": "2f6b603aae03dc4005a8e3d7688745f30df411d7",
"size": "5377",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "locale/pt-br/about/index.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "48225"
},
{
"name": "HTML",
"bytes": "37607"
},
{
"name": "JavaScript",
"bytes": "51279"
}
],
"symlink_target": ""
} |
@import "@folio/stripes-components/lib/variables";
.feefineButton {
color: var(--primary) !important;
}
.feefineButton:active {
outline: none;
}
.cursor {
cursor: pointer;
}
| {
"content_hash": "24be48450bf5860a4915dae68d17a735",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 50,
"avg_line_length": 13.142857142857142,
"alnum_prop": 0.6847826086956522,
"repo_name": "folio-org/ui-users",
"id": "743a0b6745be074dc782b984d57cd38eb5c0d8b6",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/views/LoanDetails/LoanDetails.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11251"
},
{
"name": "JavaScript",
"bytes": "1982478"
},
{
"name": "Shell",
"bytes": "814"
}
],
"symlink_target": ""
} |
<?php
/**
* @file
* Contains \Drupal\system\Tests\Theme\EngineTwigTest.
*/
namespace Drupal\system\Tests\Theme;
use Drupal\Core\Url;
use Drupal\simpletest\WebTestBase;
/**
* Tests Twig-specific theme functionality.
*
* @group Theme
*/
class EngineTwigTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('theme_test', 'twig_theme_test');
protected function setUp() {
parent::setUp();
\Drupal::service('theme_handler')->install(array('test_theme'));
}
/**
* Tests that the Twig engine handles PHP data correctly.
*/
function testTwigVariableDataTypes() {
$this->config('system.theme')
->set('default', 'test_theme')
->save();
$this->drupalGet('twig-theme-test/php-variables');
foreach (_test_theme_twig_php_values() as $type => $value) {
$this->assertRaw('<li>' . $type . ': ' . $value['expected'] . '</li>');
}
}
/**
* Tests the url and url_generate Twig functions.
*/
public function testTwigUrlGenerator() {
$this->drupalGet('twig-theme-test/url-generator');
// Find the absolute URL of the current site.
$url_generator = $this->container->get('url_generator');
$expected = array(
'path (as route) not absolute: ' . $url_generator->generateFromRoute('user.register'),
'url (as route) absolute: ' . $url_generator->generateFromRoute('user.register', array(), array('absolute' => TRUE)),
'path (as route) not absolute with fragment: ' . $url_generator->generateFromRoute('user.register', array(), array('fragment' => 'bottom')),
'url (as route) absolute despite option: ' . $url_generator->generateFromRoute('user.register', array(), array('absolute' => TRUE)),
'url (as route) absolute with fragment: ' . $url_generator->generateFromRoute('user.register', array(), array('absolute' => TRUE, 'fragment' => 'bottom')),
);
// Make sure we got something.
$content = $this->getRawContent();
$this->assertFalse(empty($content), 'Page content is not empty');
foreach ($expected as $string) {
$this->assertRaw('<div>' . $string . '</div>');
}
}
/**
* Tests the link_generator Twig functions.
*/
public function testTwigLinkGenerator() {
$this->drupalGet('twig-theme-test/link-generator');
$link_generator = $this->container->get('link_generator');
$expected = [
'link via the linkgenerator: ' . $link_generator->generate('register', new Url('user.register')),
];
$content = $this->getRawContent();
$this->assertFalse(empty($content), 'Page content is not empty');
foreach ($expected as $string) {
$this->assertRaw('<div>' . $string . '</div>');
}
}
/**
* Tests the magic url to string Twig functions.
*
* @see \Drupal\Core\Url
*/
public function testTwigUrlToString() {
$this->drupalGet('twig-theme-test/url-to-string');
$expected = [
'rendered url: ' . Url::fromRoute('user.register')->toString(),
];
$content = $this->getRawContent();
$this->assertFalse(empty($content), 'Page content is not empty');
foreach ($expected as $string) {
$this->assertRaw('<div>' . $string . '</div>');
}
}
/**
* Tests the automatic/magic calling of toString() on objects, if exists.
*/
public function testTwigFileUrls() {
$this->drupalGet('/twig-theme-test/file-url');
$filepath = file_create_url('core/modules/system/tests/modules/twig_theme_test/twig_theme_test.js');
$this->assertRaw('<div>file_url: ' . $filepath . '</div>');
}
/**
* Tests the attach of asset libraries.
*/
public function testTwigAttachLibrary() {
$this->drupalGet('/twig-theme-test/attach-library');
$this->assertRaw('ckeditor.js');
}
}
| {
"content_hash": "da1b4e74042bdb0ad9712a6e5e840268",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 161,
"avg_line_length": 30.975409836065573,
"alnum_prop": 0.6284731410426039,
"repo_name": "casivaagustin/drupalcon-mentoring",
"id": "ff84af7737f6dce1920759dca376b83b6a33632f",
"size": "3779",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "src/core/modules/system/src/Tests/Theme/EngineTwigTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "40800"
},
{
"name": "CSS",
"bytes": "301377"
},
{
"name": "HTML",
"bytes": "295561"
},
{
"name": "JavaScript",
"bytes": "739739"
},
{
"name": "PHP",
"bytes": "23084310"
},
{
"name": "Shell",
"bytes": "41527"
}
],
"symlink_target": ""
} |
package column
import (
"github.com/ClickHouse/clickhouse-go/lib/binary"
)
type UInt32 struct{ base }
func (UInt32) Read(decoder *binary.Decoder, isNull bool) (interface{}, error) {
v, err := decoder.UInt32()
if err != nil {
return uint32(0), err
}
return v, nil
}
func (u *UInt32) Write(encoder *binary.Encoder, v interface{}) error {
switch v := v.(type) {
case uint32:
return encoder.UInt32(v)
case uint64:
return encoder.UInt32(uint32(v))
case int64:
return encoder.UInt32(uint32(v))
case int:
return encoder.UInt32(uint32(v))
// this relies on Nullable never sending nil values through
case *uint64:
return encoder.UInt32(uint32(*v))
case *uint32:
return encoder.UInt32(*v)
case *int64:
return encoder.UInt32(uint32(*v))
case *int:
return encoder.UInt32(uint32(*v))
}
return &ErrUnexpectedType{
T: v,
Column: u,
}
}
| {
"content_hash": "9099b9b984eb9a6cc15178b6add78418",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 79,
"avg_line_length": 20.27906976744186,
"alnum_prop": 0.6869266055045872,
"repo_name": "kshvakov/clickhouse",
"id": "f5f72f5f16425510bf7f042bd6ed394cb3745bb7",
"size": "872",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/column/uint32.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "258270"
},
{
"name": "Makefile",
"bytes": "161"
},
{
"name": "Shell",
"bytes": "289"
}
],
"symlink_target": ""
} |
package org.netbeans.cubeon.ui.query;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.netbeans.cubeon.tasks.spi.query.TaskQuery;
import org.netbeans.cubeon.tasks.spi.query.TaskQuerySupportProvider;
import org.netbeans.cubeon.tasks.spi.repository.TaskRepository;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.util.NbBundle;
/**
*
* @author Anuradha
*/
public class QueryEditAction extends AbstractAction {
private TaskQuery query;
public QueryEditAction(TaskQuery query) {
this.query = query;
putValue(NAME, NbBundle.getMessage(QueryEditAction.class, "LBL_Edit_Query"));
TaskQuerySupportProvider provider = query.getTaskRepository().getLookup().lookup(TaskQuerySupportProvider.class);
setEnabled(provider.canModify(query));
}
public void actionPerformed(ActionEvent e) {
TaskQueryAttributes settings = new TaskQueryAttributes(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
//todo
}
});
settings.setWizardObject(new NewQueryWizardAction.WizardObject(query, query.getTaskRepository()));
DialogDescriptor dd = new DialogDescriptor(settings, settings.getName());
dd.setClosingOptions(new Object[]{
DialogDescriptor.OK_OPTION,
DialogDescriptor.CANCEL_OPTION
});
dd.setOptions(new Object[]{
DialogDescriptor.OK_OPTION,
DialogDescriptor.CANCEL_OPTION
});
Object ret = DialogDisplayer.getDefault().notify(dd);
if (DialogDescriptor.OK_OPTION == ret) {
TaskRepository repository = query.getTaskRepository();
TaskQuerySupportProvider provider = repository.getLookup().lookup(TaskQuerySupportProvider.class);
TaskQuery taskQuery = settings.getHandler().getTaskQuery();
provider.modifyTaskQuery(taskQuery);
taskQuery.synchronize();
}
}
}
| {
"content_hash": "7f85a8d2ec202b7595b6d63a2bca3ef1",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 121,
"avg_line_length": 36.42372881355932,
"alnum_prop": 0.6854350860865519,
"repo_name": "tectronics/cubeon",
"id": "54e99f6f75cf1f0e4fb998f940e4841d86d96091",
"size": "2778",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/ui/src/main/java/org/netbeans/cubeon/ui/query/QueryEditAction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2006529"
}
],
"symlink_target": ""
} |
package org.apache.wss4j.stax.ext;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoType;
import org.apache.wss4j.common.ext.WSPasswordCallback;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.stax.impl.processor.output.*;
import org.apache.wss4j.stax.impl.securityToken.KerberosClientSecurityToken;
import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.stax.config.JCEAlgorithmMapper;
import org.apache.xml.security.stax.ext.OutboundSecurityContext;
import org.apache.xml.security.stax.ext.OutputProcessor;
import org.apache.xml.security.stax.ext.SecurityContext;
import org.apache.xml.security.stax.ext.XMLSecurityConstants;
import org.apache.xml.security.stax.impl.DocumentContextImpl;
import org.apache.xml.security.stax.impl.OutboundSecurityContextImpl;
import org.apache.xml.security.stax.impl.OutputProcessorChainImpl;
import org.apache.xml.security.stax.impl.XMLSecurityStreamWriter;
import org.apache.xml.security.stax.impl.processor.output.FinalOutputProcessor;
import org.apache.xml.security.stax.impl.securityToken.GenericOutboundSecurityToken;
import org.apache.xml.security.stax.impl.util.IDGenerator;
import org.apache.xml.security.stax.securityEvent.SecurityEvent;
import org.apache.xml.security.stax.securityEvent.SecurityEventListener;
import org.apache.xml.security.stax.securityEvent.TokenSecurityEvent;
import org.apache.xml.security.stax.securityToken.OutboundSecurityToken;
import org.apache.xml.security.stax.securityToken.SecurityToken;
import org.apache.xml.security.stax.securityToken.SecurityTokenProvider;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.stream.XMLStreamWriter;
import java.io.OutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.List;
/**
* Outbound Streaming-WebService-Security
* An instance of this class can be retrieved over the WSSec class
*/
public class OutboundWSSec {
private final WSSSecurityProperties securityProperties;
public OutboundWSSec(WSSSecurityProperties securityProperties) {
this.securityProperties = securityProperties;
}
/**
* This method is the entry point for the incoming security-engine.
* Hand over a outputStream and use the returned XMLStreamWriter for further processing
*
* @param outputStream The original outputStream
* @return A new XMLStreamWriter which does transparently the security processing.
* @throws WSSecurityException thrown when a Security failure occurs
*/
public XMLStreamWriter processOutMessage(
OutputStream outputStream, String encoding,
List<SecurityEvent> requestSecurityEvents) throws WSSecurityException {
return processOutMessage(outputStream, encoding, requestSecurityEvents, null);
}
/**
* This method is the entry point for the incoming security-engine.
* Hand over the original XMLStreamWriter and use the returned one for further processing
*
* @param xmlStreamWriter The original xmlStreamWriter
* @return A new XMLStreamWriter which does transparently the security processing.
* @throws WSSecurityException thrown when a Security failure occurs
*/
public XMLStreamWriter processOutMessage(
XMLStreamWriter xmlStreamWriter, String encoding,
List<SecurityEvent> requestSecurityEvents) throws WSSecurityException {
return processOutMessage(xmlStreamWriter, encoding, requestSecurityEvents, null);
}
/**
* This method is the entry point for the incoming security-engine.
* Hand over a outputstream and use the returned XMLStreamWriter for further processing
*
* @param outputStream The original outputStream
* @return A new XMLStreamWriter which does transparently the security processing.
* @throws WSSecurityException thrown when a Security failure occurs
*/
public XMLStreamWriter processOutMessage(
OutputStream outputStream, String encoding, List<SecurityEvent> requestSecurityEvents,
SecurityEventListener securityEventListener) throws WSSecurityException {
final OutboundSecurityContextImpl outboundSecurityContext = new OutboundSecurityContextImpl();
outboundSecurityContext.putList(SecurityEvent.class, requestSecurityEvents);
outboundSecurityContext.addSecurityEventListener(securityEventListener);
return processOutMessage((Object) outputStream, encoding, outboundSecurityContext);
}
/**
* This method is the entry point for the incoming security-engine.
* Hand over the original XMLStreamWriter and use the returned one for further processing
*
* @param xmlStreamWriter The original outputStream
* @return A new XMLStreamWriter which does transparently the security processing.
* @throws WSSecurityException thrown when a Security failure occurs
*/
public XMLStreamWriter processOutMessage(
XMLStreamWriter xmlStreamWriter, String encoding, List<SecurityEvent> requestSecurityEvents,
SecurityEventListener securityEventListener) throws WSSecurityException {
final OutboundSecurityContextImpl outboundSecurityContext = new OutboundSecurityContextImpl();
outboundSecurityContext.putList(SecurityEvent.class, requestSecurityEvents);
outboundSecurityContext.addSecurityEventListener(securityEventListener);
return processOutMessage((Object) xmlStreamWriter, encoding, outboundSecurityContext);
}
/**
* This method is the entry point for the incoming security-engine.
* Hand over the original XMLStreamWriter and use the returned one for further processing
*
* @param xmlStreamWriter The original outputStream
* @return A new XMLStreamWriter which does transparently the security processing.
* @throws WSSecurityException thrown when a Security failure occurs
*/
public XMLStreamWriter processOutMessage(
XMLStreamWriter xmlStreamWriter, String encoding, OutboundSecurityContext outbounSecurityContext) throws WSSecurityException {
return processOutMessage((Object) xmlStreamWriter, encoding, outbounSecurityContext);
}
public XMLStreamWriter processOutMessage(
Object output, String encoding, OutboundSecurityContext outboundSecurityContext
) throws WSSecurityException {
final DocumentContextImpl documentContext = new DocumentContextImpl();
documentContext.setEncoding(encoding);
OutputProcessorChainImpl outputProcessorChain = new OutputProcessorChainImpl(outboundSecurityContext, documentContext);
try {
final SecurityHeaderOutputProcessor securityHeaderOutputProcessor = new SecurityHeaderOutputProcessor();
initializeOutputProcessor(outputProcessorChain, securityHeaderOutputProcessor, null);
//todo some combinations are not possible atm: eg Action.SIGNATURE and Action.USERNAMETOKEN_SIGNED
//todo they use the same signature parts
boolean signatureAction = false;
boolean encryptionAction = false;
boolean signedSAML = false;
boolean kerberos = false;
boolean signatureKerberos = false;
boolean encryptionKerberos = false;
boolean derivedSignature = false;
boolean derivedEncryption = false;
// Check to see whether we have a derived key signature, but not encryption, using
// an encrypted key reference (as we only want one encrypted key here...)
boolean derivedSignatureButNotDerivedEncryption = false;
if (securityProperties.getDerivedKeyTokenReference() == WSSConstants.DerivedKeyTokenReference.EncryptedKey) {
for (XMLSecurityConstants.Action action : securityProperties.getActions()) {
if (WSSConstants.SIGNATURE_WITH_DERIVED_KEY.equals(action)) {
derivedSignatureButNotDerivedEncryption = true;
} else if (WSSConstants.ENCRYPT_WITH_DERIVED_KEY.equals(action)) {
derivedSignatureButNotDerivedEncryption = false;
break;
}
}
}
for (XMLSecurityConstants.Action action : securityProperties.getActions()) {
if (WSSConstants.TIMESTAMP.equals(action)) {
final TimestampOutputProcessor timestampOutputProcessor = new TimestampOutputProcessor();
initializeOutputProcessor(outputProcessorChain, timestampOutputProcessor, action);
} else if (WSSConstants.SIGNATURE.equals(action)) {
signatureAction = true;
final BinarySecurityTokenOutputProcessor binarySecurityTokenOutputProcessor =
new BinarySecurityTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, binarySecurityTokenOutputProcessor, action);
final WSSSignatureOutputProcessor signatureOutputProcessor = new WSSSignatureOutputProcessor();
initializeOutputProcessor(outputProcessorChain, signatureOutputProcessor, action);
} else if (WSSConstants.ENCRYPT.equals(action)) {
encryptionAction = true;
EncryptedKeyOutputProcessor encryptedKeyOutputProcessor = null;
if (securityProperties.isEncryptSymmetricEncryptionKey()) {
final BinarySecurityTokenOutputProcessor binarySecurityTokenOutputProcessor =
new BinarySecurityTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, binarySecurityTokenOutputProcessor, action);
encryptedKeyOutputProcessor = new EncryptedKeyOutputProcessor();
initializeOutputProcessor(outputProcessorChain, encryptedKeyOutputProcessor, action);
}
final EncryptOutputProcessor encryptOutputProcessor = new EncryptOutputProcessor();
initializeOutputProcessor(outputProcessorChain, encryptOutputProcessor, action);
if (encryptedKeyOutputProcessor == null) {
final ReferenceListOutputProcessor referenceListOutputProcessor = new ReferenceListOutputProcessor();
referenceListOutputProcessor.addAfterProcessor(EncryptEndingOutputProcessor.class.getName());
initializeOutputProcessor(outputProcessorChain, referenceListOutputProcessor, action);
}
} else if (WSSConstants.USERNAMETOKEN.equals(action)) {
final UsernameTokenOutputProcessor usernameTokenOutputProcessor = new UsernameTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, usernameTokenOutputProcessor, action);
} else if (WSSConstants.USERNAMETOKEN_SIGNED.equals(action)) {
final UsernameTokenOutputProcessor usernameTokenOutputProcessor = new UsernameTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, usernameTokenOutputProcessor, action);
final WSSSignatureOutputProcessor signatureOutputProcessor = new WSSSignatureOutputProcessor();
initializeOutputProcessor(outputProcessorChain, signatureOutputProcessor, action);
} else if (WSSConstants.SIGNATURE_CONFIRMATION.equals(action)) {
final SignatureConfirmationOutputProcessor signatureConfirmationOutputProcessor =
new SignatureConfirmationOutputProcessor();
initializeOutputProcessor(outputProcessorChain, signatureConfirmationOutputProcessor, action);
} else if (WSSConstants.SIGNATURE_WITH_DERIVED_KEY.equals(action)) {
if (securityProperties.getDerivedKeyTokenReference() == WSSConstants.DerivedKeyTokenReference.EncryptedKey) {
if (derivedSignatureButNotDerivedEncryption) {
final EncryptedKeyOutputProcessor encryptedKeyOutputProcessor = new EncryptedKeyOutputProcessor();
initializeOutputProcessor(outputProcessorChain, encryptedKeyOutputProcessor, action);
}
encryptionAction = true;
derivedEncryption = true;
} else if (securityProperties.getDerivedKeyTokenReference() == WSSConstants.DerivedKeyTokenReference.SecurityContextToken) {
final SecurityContextTokenOutputProcessor securityContextTokenOutputProcessor =
new SecurityContextTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, securityContextTokenOutputProcessor, action);
signatureAction = true;
derivedSignature = true;
} else {
signatureAction = true;
derivedSignature = true;
}
final DerivedKeyTokenOutputProcessor derivedKeyTokenOutputProcessor = new DerivedKeyTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, derivedKeyTokenOutputProcessor, action);
final WSSSignatureOutputProcessor signatureOutputProcessor = new WSSSignatureOutputProcessor();
initializeOutputProcessor(outputProcessorChain, signatureOutputProcessor, action);
} else if (WSSConstants.ENCRYPT_WITH_DERIVED_KEY.equals(action)) {
encryptionAction = true;
derivedEncryption = true;
EncryptedKeyOutputProcessor encryptedKeyOutputProcessor = null;
if (securityProperties.getDerivedKeyTokenReference() == WSSConstants.DerivedKeyTokenReference.EncryptedKey) {
encryptedKeyOutputProcessor = new EncryptedKeyOutputProcessor();
initializeOutputProcessor(outputProcessorChain, encryptedKeyOutputProcessor, action);
} else if (securityProperties.getDerivedKeyTokenReference() == WSSConstants.DerivedKeyTokenReference.SecurityContextToken) {
final SecurityContextTokenOutputProcessor securityContextTokenOutputProcessor =
new SecurityContextTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, securityContextTokenOutputProcessor, action);
}
final DerivedKeyTokenOutputProcessor derivedKeyTokenOutputProcessor = new DerivedKeyTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, derivedKeyTokenOutputProcessor, action);
final EncryptOutputProcessor encryptOutputProcessor = new EncryptOutputProcessor();
initializeOutputProcessor(outputProcessorChain, encryptOutputProcessor, action);
if (encryptedKeyOutputProcessor == null) {
final ReferenceListOutputProcessor referenceListOutputProcessor = new ReferenceListOutputProcessor();
referenceListOutputProcessor.addAfterProcessor(EncryptEndingOutputProcessor.class.getName());
initializeOutputProcessor(outputProcessorChain, referenceListOutputProcessor, action);
}
} else if (WSSConstants.SAML_TOKEN_SIGNED.equals(action)) {
signatureAction = true;
signedSAML = true;
final BinarySecurityTokenOutputProcessor binarySecurityTokenOutputProcessor =
new BinarySecurityTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, binarySecurityTokenOutputProcessor, action);
final SAMLTokenOutputProcessor samlTokenOutputProcessor = new SAMLTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, samlTokenOutputProcessor, action);
final WSSSignatureOutputProcessor signatureOutputProcessor = new WSSSignatureOutputProcessor();
initializeOutputProcessor(outputProcessorChain, signatureOutputProcessor, action);
} else if (WSSConstants.SAML_TOKEN_UNSIGNED.equals(action)) {
final SAMLTokenOutputProcessor samlTokenOutputProcessor = new SAMLTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, samlTokenOutputProcessor, action);
} else if (WSSConstants.SIGNATURE_WITH_KERBEROS_TOKEN.equals(action)) {
kerberos = true;
signatureKerberos = true;
final BinarySecurityTokenOutputProcessor kerberosTokenOutputProcessor =
new BinarySecurityTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, kerberosTokenOutputProcessor, action);
final WSSSignatureOutputProcessor signatureOutputProcessor = new WSSSignatureOutputProcessor();
initializeOutputProcessor(outputProcessorChain, signatureOutputProcessor, action);
} else if (WSSConstants.ENCRYPT_WITH_KERBEROS_TOKEN.equals(action)) {
kerberos = true;
encryptionKerberos = true;
final BinarySecurityTokenOutputProcessor kerberosTokenOutputProcessor =
new BinarySecurityTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, kerberosTokenOutputProcessor, action);
final EncryptOutputProcessor encryptOutputProcessor = new EncryptOutputProcessor();
initializeOutputProcessor(outputProcessorChain, encryptOutputProcessor, action);
} else if (WSSConstants.KERBEROS_TOKEN.equals(action)) {
kerberos = true;
final BinarySecurityTokenOutputProcessor kerberosTokenOutputProcessor =
new BinarySecurityTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, kerberosTokenOutputProcessor, action);
} else if (WSSConstants.CUSTOM_TOKEN.equals(action)) {
final CustomTokenOutputProcessor unknownTokenOutputProcessor =
new CustomTokenOutputProcessor();
initializeOutputProcessor(outputProcessorChain, unknownTokenOutputProcessor, action);
}
}
// Set up appropriate keys
if (signatureAction) {
setupSignatureKey(outputProcessorChain, securityProperties, signedSAML);
}
if (encryptionAction) {
setupEncryptionKey(outputProcessorChain, securityProperties);
}
if (kerberos) {
setupKerberosKey(outputProcessorChain, securityProperties,
signatureKerberos, encryptionKerberos);
}
if (derivedSignature) {
String id =
outputProcessorChain.getSecurityContext().get(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE);
setDerivedIdentifier(outputProcessorChain, id);
}
if (derivedEncryption) {
String id =
outputProcessorChain.getSecurityContext().get(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTED_KEY);
if (id == null) {
// Maybe not encrypting the key here...
id = outputProcessorChain.getSecurityContext().get(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION);
}
setDerivedIdentifier(outputProcessorChain, id);
}
final SecurityHeaderReorderProcessor securityHeaderReorderProcessor = new SecurityHeaderReorderProcessor();
initializeOutputProcessor(outputProcessorChain, securityHeaderReorderProcessor, null);
if (output instanceof OutputStream) {
final FinalOutputProcessor finalOutputProcessor = new FinalOutputProcessor((OutputStream) output, encoding);
initializeOutputProcessor(outputProcessorChain, finalOutputProcessor, null);
} else if (output instanceof XMLStreamWriter) {
final FinalOutputProcessor finalOutputProcessor = new FinalOutputProcessor((XMLStreamWriter) output);
initializeOutputProcessor(outputProcessorChain, finalOutputProcessor, null);
} else {
throw new IllegalArgumentException(output + " is not supported as output");
}
} catch (XMLSecurityException e) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, e);
}
return new XMLSecurityStreamWriter(outputProcessorChain);
}
private void initializeOutputProcessor(
OutputProcessorChainImpl outputProcessorChain, OutputProcessor outputProcessor,
XMLSecurityConstants.Action action) throws XMLSecurityException {
outputProcessor.setXMLSecurityProperties(securityProperties);
outputProcessor.setAction(action);
outputProcessor.init(outputProcessorChain);
}
private void setupSignatureKey(
OutputProcessorChainImpl outputProcessorChain,
WSSSecurityProperties securityProperties,
boolean signedSAML
) throws XMLSecurityException {
final String signatureAlgorithm = securityProperties.getSignatureAlgorithm();
GenericOutboundSecurityToken securityToken =
getOutboundSecurityToken(outputProcessorChain, WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE);
// First off, see if we have a supplied token with the correct keys for
// (a)symmetric signature
if (securityToken != null && signatureAlgorithm != null) {
if (signatureAlgorithm.contains("hmac-sha")
&& securityToken.getSecretKey(signatureAlgorithm) != null) {
return;
} else if (!signatureAlgorithm.contains("hmac-sha") && securityToken.getX509Certificates() != null) {
if (securityToken.getSecretKey(signatureAlgorithm) != null) {
return;
} else {
// We have certs but no private key set. Use the CallbackHandler
Key key =
securityProperties.getSignatureCrypto().getPrivateKey(
securityToken.getX509Certificates()[0], securityProperties.getCallbackHandler()
);
securityToken.setSecretKey(signatureAlgorithm, key);
return;
}
}
}
// We have no supplied key. So use the PasswordCallback to get a secret key or password
String alias = securityProperties.getSignatureUser();
WSPasswordCallback pwCb = new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE);
WSSUtils.doPasswordCallback(securityProperties.getCallbackHandler(), pwCb);
String password = pwCb.getPassword();
byte[] secretKey = pwCb.getKey();
Key key = null;
X509Certificate[] x509Certificates = null;
try {
if (password != null && securityProperties.getSignatureCrypto() != null) {
key = securityProperties.getSignatureCrypto().getPrivateKey(alias, password);
CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
cryptoType.setAlias(alias);
x509Certificates = securityProperties.getSignatureCrypto().getX509Certificates(cryptoType);
if (x509Certificates == null || x509Certificates.length == 0) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_SIGNATURE, "noUserCertsFound",
new Object[] {alias});
}
} else if (secretKey != null) {
x509Certificates = null;
String algoFamily = JCEAlgorithmMapper.getJCEKeyAlgorithmFromURI(signatureAlgorithm);
key = new SecretKeySpec(secretKey, algoFamily);
} else {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_SIGNATURE, "noPassword",
new Object[] {alias});
}
} catch (WSSecurityException ex) {
if (signedSAML && securityProperties.getSamlCallbackHandler() != null) {
// We may get the keys we require from the SAML CallbackHandler...
return;
}
throw ex;
}
// Create a new outbound Signature token for the generated key / cert
final String id = IDGenerator.generateID(null);
final GenericOutboundSecurityToken binarySecurityToken =
new GenericOutboundSecurityToken(id, WSSecurityTokenConstants.X509V3Token, key, x509Certificates);
// binarySecurityToken.setSha1Identifier(reference);
final SecurityTokenProvider<OutboundSecurityToken> binarySecurityTokenProvider =
new SecurityTokenProvider<OutboundSecurityToken>() {
@Override
public OutboundSecurityToken getSecurityToken() throws WSSecurityException {
return binarySecurityToken;
}
@Override
public String getId() {
return id;
}
};
outputProcessorChain.getSecurityContext().registerSecurityTokenProvider(id, binarySecurityTokenProvider);
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE, id);
}
private void setupEncryptionKey(
OutputProcessorChainImpl outputProcessorChain,
WSSSecurityProperties securityProperties
) throws XMLSecurityException {
final String symmetricEncryptionAlgorithm = securityProperties.getEncryptionSymAlgorithm();
// First check to see if a Symmetric key is available
GenericOutboundSecurityToken securityToken =
getOutboundSecurityToken(outputProcessorChain, WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION);
if (securityToken == null || securityToken.getSecretKey(symmetricEncryptionAlgorithm) == null) {
//prepare the symmetric session key for all encryption parts
String keyAlgorithm = JCEAlgorithmMapper.getJCEKeyAlgorithmFromURI(securityProperties.getEncryptionSymAlgorithm());
KeyGenerator keyGen;
try {
keyGen = KeyGenerator.getInstance(keyAlgorithm);
} catch (NoSuchAlgorithmException e) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, e);
}
//the sun JCE provider expects the real key size for 3DES (112 or 168 bit)
//whereas bouncy castle expects the block size of 128 or 192 bits
if (keyAlgorithm.contains("AES")) {
int keyLength = JCEAlgorithmMapper.getKeyLengthFromURI(securityProperties.getEncryptionSymAlgorithm());
keyGen.init(keyLength);
}
final Key symmetricKey = keyGen.generateKey();
final String symmId = IDGenerator.generateID(null);
final GenericOutboundSecurityToken symmetricSecurityToken =
new GenericOutboundSecurityToken(symmId, WSSecurityTokenConstants.EncryptedKeyToken, symmetricKey);
securityToken = symmetricSecurityToken;
final SecurityTokenProvider<OutboundSecurityToken> securityTokenProvider =
new SecurityTokenProvider<OutboundSecurityToken>() {
@Override
public OutboundSecurityToken getSecurityToken() throws XMLSecurityException {
return symmetricSecurityToken;
}
@Override
public String getId() {
return symmId;
}
};
outputProcessorChain.getSecurityContext().registerSecurityTokenProvider(symmId, securityTokenProvider);
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION, symmId);
}
if (!securityProperties.isEncryptSymmetricEncryptionKey()) {
// No EncryptedKey Token required here, so return
return;
}
// Set up a security token with the certs required to encrypt the symmetric key
X509Certificate[] x509Certificates = null;
X509Certificate x509Certificate = getReqSigCert(outputProcessorChain.getSecurityContext());
if (securityProperties.isUseReqSigCertForEncryption()) {
if (x509Certificate == null) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_ENCRYPTION, "noCert");
}
x509Certificates = new X509Certificate[1];
x509Certificates[0] = x509Certificate;
} else if (securityProperties.getEncryptionUseThisCertificate() != null) {
x509Certificate = securityProperties.getEncryptionUseThisCertificate();
x509Certificates = new X509Certificate[1];
x509Certificates[0] = x509Certificate;
} else {
CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
cryptoType.setAlias(securityProperties.getEncryptionUser());
Crypto crypto = securityProperties.getEncryptionCrypto();
x509Certificates = crypto.getX509Certificates(cryptoType);
if (x509Certificates == null || x509Certificates.length == 0) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_ENCRYPTION, "noUserCertsFound",
new Object[] {securityProperties.getEncryptionUser(), "encryption"});
}
}
// Check for Revocation
if (securityProperties.isEnableRevocation()) {
Crypto crypto = securityProperties.getEncryptionCrypto();
crypto.verifyTrust(x509Certificates, true, null);
}
// Create a new outbound EncryptedKey token for the cert
final String id = IDGenerator.generateID(null);
final GenericOutboundSecurityToken encryptedKeyToken =
new GenericOutboundSecurityToken(id, WSSecurityTokenConstants.X509V3Token, null, x509Certificates);
encryptedKeyToken.addWrappedToken(securityToken);
securityToken.setKeyWrappingToken(encryptedKeyToken);
// binarySecurityToken.setSha1Identifier(reference);
final SecurityTokenProvider<OutboundSecurityToken> encryptedKeyTokenProvider =
new SecurityTokenProvider<OutboundSecurityToken>() {
@Override
public OutboundSecurityToken getSecurityToken() throws WSSecurityException {
return encryptedKeyToken;
}
@Override
public String getId() {
return id;
}
};
outputProcessorChain.getSecurityContext().registerSecurityTokenProvider(id, encryptedKeyTokenProvider);
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTED_KEY, id);
}
private void setupKerberosKey(
OutputProcessorChainImpl outputProcessorChain,
WSSSecurityProperties securityProperties,
boolean signature,
boolean encryption
) throws XMLSecurityException {
GenericOutboundSecurityToken securityToken =
getOutboundSecurityToken(outputProcessorChain, WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_KERBEROS);
String kerberosId = null;
// First off, see if we have a supplied token
if (securityToken == null) {
// If not then generate a new key
final String id = IDGenerator.generateID(null);
kerberosId = id;
final KerberosClientSecurityToken kerberosClientSecurityToken =
new KerberosClientSecurityToken(
securityProperties.getCallbackHandler(), id
);
final SecurityTokenProvider<OutboundSecurityToken> kerberosSecurityTokenProvider =
new SecurityTokenProvider<OutboundSecurityToken>() {
@Override
public OutboundSecurityToken getSecurityToken() throws WSSecurityException {
return kerberosClientSecurityToken;
}
@Override
public String getId() {
return id;
}
};
outputProcessorChain.getSecurityContext().registerSecurityTokenProvider(id, kerberosSecurityTokenProvider);
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_KERBEROS, id);
} else {
kerberosId = securityToken.getId();
}
if (signature) {
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_SIGNATURE, kerberosId);
}
if (encryption) {
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION, kerberosId);
}
}
// Return an outbound SecurityToken object for a given id (encryption/signature)
private GenericOutboundSecurityToken getOutboundSecurityToken(
OutputProcessorChainImpl outputProcessorChain, String id
) throws XMLSecurityException {
String tokenId =
outputProcessorChain.getSecurityContext().get(id);
SecurityTokenProvider<OutboundSecurityToken> signatureTokenProvider = null;
if (tokenId != null) {
signatureTokenProvider =
outputProcessorChain.getSecurityContext().getSecurityTokenProvider(tokenId);
if (signatureTokenProvider != null) {
return (GenericOutboundSecurityToken)signatureTokenProvider.getSecurityToken();
}
}
return null;
}
private X509Certificate getReqSigCert(SecurityContext securityContext) throws XMLSecurityException {
List<SecurityEvent> securityEventList = securityContext.getAsList(SecurityEvent.class);
if (securityEventList != null) {
for (int i = 0; i < securityEventList.size(); i++) {
SecurityEvent securityEvent = securityEventList.get(i);
if (securityEvent instanceof TokenSecurityEvent) {
@SuppressWarnings("unchecked")
TokenSecurityEvent<? extends SecurityToken> tokenSecurityEvent
= (TokenSecurityEvent<? extends SecurityToken>) securityEvent;
if (!tokenSecurityEvent.getSecurityToken().getTokenUsages().contains(WSSecurityTokenConstants.TokenUsage_MainSignature)) {
continue;
}
X509Certificate[] x509Certificates = tokenSecurityEvent.getSecurityToken().getX509Certificates();
if (x509Certificates != null && x509Certificates.length > 0) {
return x509Certificates[0];
}
}
}
}
return null;
}
private void setDerivedIdentifier(OutputProcessorChainImpl outputProcessorChain, String id) {
WSSConstants.DerivedKeyTokenReference derivedKeyTokenReference = securityProperties.getDerivedKeyTokenReference();
switch (derivedKeyTokenReference) {
case DirectReference:
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_DERIVED_KEY, id);
break;
case EncryptedKey:
String symmId = outputProcessorChain.getSecurityContext().get(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTION);
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_DERIVED_KEY, symmId);
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_ENCRYPTED_KEY, id);
break;
case SecurityContextToken:
outputProcessorChain.getSecurityContext().put(WSSConstants.PROP_USE_THIS_TOKEN_ID_FOR_SECURITYCONTEXTTOKEN, id);
break;
}
}
}
| {
"content_hash": "a024d12f5e63ff2c63027b55f6c56911",
"timestamp": "",
"source": "github",
"line_count": 673,
"max_line_length": 144,
"avg_line_length": 55.3001485884101,
"alnum_prop": 0.6696402181798641,
"repo_name": "asoldano/wss4j",
"id": "ae2ad42718aea6789a4ee38035b44ef93a26ee97",
"size": "38019",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "ws-security-stax/src/main/java/org/apache/wss4j/stax/ext/OutboundWSSec.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7170238"
},
{
"name": "Shell",
"bytes": "2519"
},
{
"name": "XSLT",
"bytes": "1265"
}
],
"symlink_target": ""
} |
package ui;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import gameobjects.GameObject;
import gameworld.GameWorld;
import helpers.AssetLoader;
/**
* Created by ManuGil on 14/03/15.
*/
public class Text extends GameObject {
private final BitmapFont font;
private final Color fontColor;
private final float distance;
private String text;
private BitmapFont.HAlignment center;
public Text(GameWorld world, float x, float y, float width, float height,
TextureRegion texture, Color color, String text, BitmapFont font, Color fontColor,
float distance, BitmapFont.HAlignment center) {
super(world, x, y, width, height, texture, color);
this.font = font;
this.text = text;
this.fontColor = fontColor;
this.distance = distance;
this.center = center;
}
@Override
public void update(float delta) {
super.update(delta);
}
public void render(SpriteBatch batch, ShapeRenderer shapeRenderer, ShaderProgram fontshader) {
if (getTexture() != AssetLoader.transparent) {
super.render(batch, shapeRenderer);
}
batch.setShader(fontshader);
font.setColor(fontColor);
font.drawWrapped(batch, text, getRectangle().x + 40,
getRectangle().y + getRectangle().height - distance, getRectangle().width - 80,
center);
font.setColor(Color.WHITE);
batch.setShader(null);
}
public void setText(String text) {
this.text = text;
}
}
| {
"content_hash": "c078366584c52f769e041a87956d0d39",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 98,
"avg_line_length": 30.864406779661017,
"alnum_prop": 0.6727073036792971,
"repo_name": "anisc/Farkesmatal9ach",
"id": "ae04c66abb45cc599bdb3e32a201458f78891847",
"size": "1821",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/ui/Text.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1290"
},
{
"name": "Java",
"bytes": "1329346"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">
<changeSet author="brianfreeman" id="changelog-25">
<createIndex
indexName="idx_participant_cohort_annotations"
tableName="participant_cohort_annotations"
unique="true">
<column name="cohort_review_id"/>
<column name="cohort_annotation_definition_id"/>
<column name="participant_id"/>
</createIndex>
</changeSet>
</databaseChangeLog>
| {
"content_hash": "9b020a9f91a7111e32f171ace7f26a66",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 135,
"avg_line_length": 47.5,
"alnum_prop": 0.6536842105263158,
"repo_name": "all-of-us/workbench",
"id": "17fc31ac27b262123266976952cdd806354eba91",
"size": "950",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "api/db/changelog/db.changelog-25.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "14709"
},
{
"name": "Dockerfile",
"bytes": "1601"
},
{
"name": "Groovy",
"bytes": "5004"
},
{
"name": "HTML",
"bytes": "354263"
},
{
"name": "Java",
"bytes": "4258561"
},
{
"name": "JavaScript",
"bytes": "104985"
},
{
"name": "Jupyter Notebook",
"bytes": "12135"
},
{
"name": "Kotlin",
"bytes": "76275"
},
{
"name": "Mustache",
"bytes": "126650"
},
{
"name": "Python",
"bytes": "52410"
},
{
"name": "R",
"bytes": "1157"
},
{
"name": "Ruby",
"bytes": "237944"
},
{
"name": "Shell",
"bytes": "507090"
},
{
"name": "TypeScript",
"bytes": "3656309"
},
{
"name": "wdl",
"bytes": "31820"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NullValuesArithmetic")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NullValuesArithmetic")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fb4bf779-505d-4939-8663-4f0c1cb51ae2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "a32fdd64828e1ab570a5f4115e7a047e",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 39.111111111111114,
"alnum_prop": 0.7507102272727273,
"repo_name": "kmirchev/Csharp-Part-1",
"id": "b46bf1cc4c5c66711e20b749f5f3dda7099505a6",
"size": "1411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "02. Data-Types-and-Variables-Homeworks/NullValuesArithmetic/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "126693"
}
],
"symlink_target": ""
} |
module Azure::Network::Mgmt::V2019_07_01
module Models
#
# Defines values for CircuitConnectionStatus
#
module CircuitConnectionStatus
Connected = "Connected"
Connecting = "Connecting"
Disconnected = "Disconnected"
end
end
end
| {
"content_hash": "6dcd74d1f53e8ac15eb0dc0653aee927",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 48,
"avg_line_length": 22.416666666666668,
"alnum_prop": 0.6765799256505576,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "c570122c0fc70417e1270d84ebe30793bbde2cae",
"size": "433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_network/lib/2019-07-01/generated/azure_mgmt_network/models/circuit_connection_status.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
@interface VotingViewController ()
@property (weak, nonatomic) IBOutlet UIButton *yesButton;
@property (weak, nonatomic) IBOutlet UIButton *noButton;
@end
@implementation VotingViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.yesButton.backgroundColor = [UIColor emerlandColor];
self.noButton.backgroundColor = [UIColor pomegranateColor];
self.yesButton.enabled = self.noButton.enabled = NO;
self.yesButton.alpha = self.noButton.alpha = 0.4;
__weak typeof(self) weakSelf = self;
BMProximityRule *buttonToggle = [[BMProximityRule alloc] initWithRegion:kEstimoteBeaconRegion activationProximity:CLProximityImmediate andCallback:^(BMBeaconRule *rule, BOOL activated) {
[UIView animateWithDuration:0.3 animations:^{
weakSelf.yesButton.enabled = activated;
weakSelf.noButton.enabled = !weakSelf.yesButton.enabled;
weakSelf.yesButton.alpha = activated ? 1.0 : 0.4;
weakSelf.noButton.alpha = activated ? 0.4 : 1.0;
}];
}];
[self.manager addRule:buttonToggle];
// Do any additional setup after loading the view.
}
@end
| {
"content_hash": "fd18ef7d342118ef54e5e736790f0b64",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 190,
"avg_line_length": 33.6,
"alnum_prop": 0.6879251700680272,
"repo_name": "brianmichel/BMBeaconRules",
"id": "84b2cd2eaf5016bd0490cabae4fd209cb00108f4",
"size": "1413",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BMBeaconRules/Classes/VotingViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1973"
},
{
"name": "C++",
"bytes": "626"
},
{
"name": "Objective-C",
"bytes": "107242"
},
{
"name": "Ruby",
"bytes": "55"
},
{
"name": "Shell",
"bytes": "3121"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.contrib.sites.models import Site
from future.builtins import str
from unittest import skipUnless
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.db import connection
from django.http import HttpResponse
from django.shortcuts import resolve_url
from django.template import Context, Template
from django.test.utils import override_settings
from django.utils.http import urlquote_plus
from django.utils.six.moves.urllib.parse import urlparse
from django.utils.translation import get_language
from mezzanine.conf import settings
from mezzanine.core.models import CONTENT_STATUS_PUBLISHED
from mezzanine.core.request import current_request
from mezzanine.pages.models import Page, RichTextPage
from mezzanine.pages.admin import PageAdminForm
from mezzanine.urls import PAGES_SLUG
from mezzanine.utils.sites import override_current_site_id
from mezzanine.utils.tests import TestCase
User = get_user_model()
class PagesTests(TestCase):
def setUp(self):
"""
Make sure we have a thread-local request with a site_id attribute set.
"""
super(PagesTests, self).setUp()
from mezzanine.core.request import _thread_local
request = self._request_factory.get('/')
request.site_id = settings.SITE_ID
_thread_local.request = request
def test_page_ascendants(self):
"""
Test the methods for looking up ascendants efficiently
behave as expected.
"""
# Create related pages.
primary, created = RichTextPage.objects.get_or_create(title="Primary")
secondary, created = primary.children.get_or_create(title="Secondary")
tertiary, created = secondary.children.get_or_create(title="Tertiary")
# Test that get_ascendants() returns the right thing.
page = Page.objects.get(id=tertiary.id)
ascendants = page.get_ascendants()
self.assertEqual(ascendants[0].id, secondary.id)
self.assertEqual(ascendants[1].id, primary.id)
# Test ascendants are returned in order for slug, using
# a single DB query.
connection.queries_log.clear()
pages_for_slug = Page.objects.with_ascendants_for_slug(tertiary.slug)
self.assertEqual(len(connection.queries), 1)
self.assertEqual(pages_for_slug[0].id, tertiary.id)
self.assertEqual(pages_for_slug[1].id, secondary.id)
self.assertEqual(pages_for_slug[2].id, primary.id)
# Test page.get_ascendants uses the cached attribute,
# without any more queries.
connection.queries_log.clear()
ascendants = pages_for_slug[0].get_ascendants()
self.assertEqual(len(connection.queries), 0)
self.assertEqual(ascendants[0].id, secondary.id)
self.assertEqual(ascendants[1].id, primary.id)
# Use a custom slug in the page path, and test that
# Page.objects.with_ascendants_for_slug fails, but
# correctly falls back to recursive queries.
secondary.slug += "custom"
secondary.save()
pages_for_slug = Page.objects.with_ascendants_for_slug(tertiary.slug)
self.assertEqual(len(pages_for_slug[0]._ascendants), 0)
connection.queries_log.clear()
ascendants = pages_for_slug[0].get_ascendants()
self.assertEqual(len(connection.queries), 2) # 2 parent queries
self.assertEqual(pages_for_slug[0].id, tertiary.id)
self.assertEqual(ascendants[0].id, secondary.id)
self.assertEqual(ascendants[1].id, primary.id)
def test_set_parent(self):
old_parent, _ = RichTextPage.objects.get_or_create(title="Old parent")
new_parent, _ = RichTextPage.objects.get_or_create(title="New parent")
child, _ = RichTextPage.objects.get_or_create(
title="Child", slug="kid")
self.assertTrue(child.parent is None)
self.assertTrue(child.slug == "kid")
child.set_parent(old_parent)
child.save()
self.assertEqual(child.parent_id, old_parent.id)
self.assertTrue(child.slug == "old-parent/kid")
child = RichTextPage.objects.get(id=child.id)
self.assertEqual(child.parent_id, old_parent.id)
self.assertTrue(child.slug == "old-parent/kid")
child.set_parent(new_parent)
child.save()
self.assertEqual(child.parent_id, new_parent.id)
self.assertTrue(child.slug == "new-parent/kid")
child = RichTextPage.objects.get(id=child.id)
self.assertEqual(child.parent_id, new_parent.id)
self.assertTrue(child.slug == "new-parent/kid")
child.set_parent(None)
child.save()
self.assertTrue(child.parent is None)
self.assertTrue(child.slug == "kid")
child = RichTextPage.objects.get(id=child.id)
self.assertTrue(child.parent is None)
self.assertTrue(child.slug == "kid")
child = RichTextPage(title="child2")
child.set_parent(new_parent)
self.assertEqual(child.slug, "new-parent/child2")
# Assert that cycles are detected.
p1, _ = RichTextPage.objects.get_or_create(title="p1")
p2, _ = RichTextPage.objects.get_or_create(title="p2")
p2.set_parent(p1)
with self.assertRaises(AttributeError):
p1.set_parent(p1)
with self.assertRaises(AttributeError):
p1.set_parent(p2)
p2c = RichTextPage.objects.get(title="p2")
with self.assertRaises(AttributeError):
p1.set_parent(p2c)
def test_set_slug(self):
parent, _ = RichTextPage.objects.get_or_create(
title="Parent", slug="parent")
child, _ = RichTextPage.objects.get_or_create(
title="Child", slug="parent/child", parent_id=parent.id)
parent.set_slug("new-parent-slug")
self.assertTrue(parent.slug == "new-parent-slug")
parent = RichTextPage.objects.get(id=parent.id)
self.assertTrue(parent.slug == "new-parent-slug")
child = RichTextPage.objects.get(id=child.id)
self.assertTrue(child.slug == "new-parent-slug/child")
def test_login_required(self):
public, _ = RichTextPage.objects.get_or_create(
title="Public", slug="public", login_required=False)
private, _ = RichTextPage.objects.get_or_create(
title="Private", slug="private", login_required=True)
accounts_installed = ("mezzanine.accounts" in settings.INSTALLED_APPS)
args = {"for_user": AnonymousUser()}
self.assertTrue(public in RichTextPage.objects.published(**args))
self.assertTrue(private not in RichTextPage.objects.published(**args))
args = {"for_user": User.objects.get(username=self._username)}
self.assertTrue(public in RichTextPage.objects.published(**args))
self.assertTrue(private in RichTextPage.objects.published(**args))
public_url = public.get_absolute_url()
private_url = private.get_absolute_url()
self.client.logout()
response = self.client.get(private_url, follow=True)
login_prefix = ""
login_url = resolve_url(settings.LOGIN_URL)
login_next = private_url
try:
redirects_count = len(response.redirect_chain)
response_url = response.redirect_chain[-1][0]
except (AttributeError, IndexError):
redirects_count = 0
response_url = ""
if urlparse(response_url).path.startswith("/%s/" % get_language()):
# With LocaleMiddleware a language code can be added at the
# beginning of the path.
login_prefix = "/%s" % get_language()
if redirects_count > 1:
# With LocaleMiddleware and a string LOGIN_URL there can be
# a second redirect that encodes the next parameter.
login_next = urlquote_plus(login_next)
login = "%s%s?next=%s" % (login_prefix, login_url, login_next)
if accounts_installed:
# For an inaccessible page with mezzanine.accounts we should
# see a login page, without it 404 is more appropriate than an
# admin login.
target_status_code = 200
else:
target_status_code = 404
self.assertRedirects(response, login,
target_status_code=target_status_code)
response = self.client.get(public_url, follow=True)
self.assertEqual(response.status_code, 200)
if accounts_installed:
# View / pattern name redirect properly, without encoding next.
login = "%s%s?next=%s" % (login_prefix, login_url, private_url)
with override_settings(LOGIN_URL="login"):
# Note: The "login" is a pattern name in accounts.urls.
response = self.client.get(public_url, follow=True)
self.assertEqual(response.status_code, 200)
response = self.client.get(private_url, follow=True)
self.assertRedirects(response, login)
self.client.login(username=self._username, password=self._password)
response = self.client.get(private_url, follow=True)
self.assertEqual(response.status_code, 200)
response = self.client.get(public_url, follow=True)
self.assertEqual(response.status_code, 200)
if accounts_installed:
with override_settings(LOGIN_URL="mezzanine.accounts.views.login"):
response = self.client.get(public_url, follow=True)
self.assertEqual(response.status_code, 200)
response = self.client.get(private_url, follow=True)
self.assertEqual(response.status_code, 200)
with override_settings(LOGIN_URL="login"):
response = self.client.get(public_url, follow=True)
self.assertEqual(response.status_code, 200)
response = self.client.get(private_url, follow=True)
self.assertEqual(response.status_code, 200)
def test_page_menu_queries(self):
"""
Test that rendering a page menu executes the same number of
queries regardless of the number of pages or levels of
children.
"""
template = ('{% load pages_tags %}'
'{% page_menu "pages/menus/tree.html" %}')
before = self.queries_used_for_template(template)
self.assertTrue(before > 0)
self.create_recursive_objects(RichTextPage, "parent", title="Page",
status=CONTENT_STATUS_PUBLISHED)
after = self.queries_used_for_template(template)
self.assertEqual(before, after)
def test_page_menu_flags(self):
"""
Test that pages only appear in the menu templates they've been
assigned to show in.
"""
menus = []
pages = []
template = "{% load pages_tags %}"
for i, label, path in settings.PAGE_MENU_TEMPLATES:
menus.append(i)
pages.append(RichTextPage.objects.create(in_menus=list(menus),
title="Page for %s" % str(label),
status=CONTENT_STATUS_PUBLISHED))
template += "{%% page_menu '%s' %%}" % path
rendered = Template(template).render(Context({}))
for page in pages:
self.assertEqual(rendered.count(page.title), len(page.in_menus))
def test_page_menu_default(self):
"""
Test that the settings-defined default value for the ``in_menus``
field is used, also checking that it doesn't get forced to text,
but that sequences are made immutable.
"""
with override_settings(
PAGE_MENU_TEMPLATES=((8, "a", "a"), (9, "b", "b"))):
with override_settings(PAGE_MENU_TEMPLATES_DEFAULT=None):
page_in_all_menus = Page.objects.create()
self.assertEqual(page_in_all_menus.in_menus, (8, 9))
with override_settings(PAGE_MENU_TEMPLATES_DEFAULT=tuple()):
page_not_in_menus = Page.objects.create()
self.assertEqual(page_not_in_menus.in_menus, tuple())
with override_settings(PAGE_MENU_TEMPLATES_DEFAULT=[9]):
page_in_a_menu = Page.objects.create()
self.assertEqual(page_in_a_menu.in_menus, (9,))
def test_overridden_page(self):
"""
Test that a page with a slug matching a non-page urlpattern
return ``True`` for its overridden property.
"""
# BLOG_SLUG is empty then urlpatterns for pages are prefixed
# with PAGE_SLUG, and generally won't be overridden. In this
# case, there aren't any overridding URLs by default, so bail
# on the test.
if PAGES_SLUG:
return
page, created = RichTextPage.objects.get_or_create(slug="edit")
self.assertTrue(page.overridden())
def test_unicode_slug_parm_to_processor_for(self):
"""
Test that passing an unicode slug to processor_for works for
python 2.x
"""
from mezzanine.pages.page_processors import processor_for
@processor_for(u'test unicode string')
def test_page_processor(request, page):
return {}
page, _ = RichTextPage.objects.get_or_create(title="test page")
self.assertEqual(test_page_processor(current_request(), page), {})
def test_exact_page_processor_for(self):
"""
Test that passing exact_page=True works with the PageMiddleware
"""
from mezzanine.pages.middleware import PageMiddleware
from mezzanine.pages.page_processors import processor_for
from mezzanine.pages.views import page as page_view
@processor_for('foo/bar', exact_page=True)
def test_page_processor(request, page):
return HttpResponse("bar")
foo, _ = RichTextPage.objects.get_or_create(title="foo")
bar, _ = RichTextPage.objects.get_or_create(title="bar", parent=foo)
request = self._request_factory.get('/foo/bar/')
request.user = self._user
response = PageMiddleware().process_view(request, page_view, [], {})
self.assertTrue(isinstance(response, HttpResponse))
self.assertContains(response, "bar")
@skipUnless(settings.USE_MODELTRANSLATION and len(settings.LANGUAGES) > 1,
"modeltranslation configured for several languages required")
def test_page_slug_has_correct_lang(self):
"""
Test that slug generation is done for the default language and
not the active one.
"""
from collections import OrderedDict
from django.utils.translation import get_language, activate
from mezzanine.utils.urls import slugify
default_language = get_language()
code_list = OrderedDict(settings.LANGUAGES)
del code_list[default_language]
title_1 = "Title firt language"
title_2 = "Title second language"
page, _ = RichTextPage.objects.get_or_create(title=title_1)
for code in code_list:
try:
activate(code)
except:
pass
else:
break
# No valid language found
page.delete()
return
page.title = title_2
page.save()
self.assertEqual(page.get_slug(), slugify(title_1))
self.assertEqual(page.title, title_2)
activate(default_language)
self.assertEqual(page.title, title_1)
page.delete()
def test_clean_slug(self):
"""
Test that PageAdminForm strips leading and trailing slashes
from slugs or returns `/`.
"""
class TestPageAdminForm(PageAdminForm):
class Meta:
fields = ["slug"]
model = Page
data = {'slug': '/'}
submitted_form = TestPageAdminForm(data=data)
self.assertTrue(submitted_form.is_valid())
self.assertEqual(submitted_form.cleaned_data['slug'], "/")
data = {'slug': '/hello/world/'}
submitted_form = TestPageAdminForm(data=data)
self.assertTrue(submitted_form.is_valid())
self.assertEqual(submitted_form.cleaned_data['slug'], 'hello/world')
def test_ascendants_different_site(self):
site2 = Site.objects.create(domain='site2.example.com', name='Site 2')
parent = Page.objects.create(title="Parent", site=site2)
child = parent.children.create(title="Child", site=site2)
grandchild = child.children.create(title="Grandchild", site=site2)
# Re-retrieve grandchild so its parent attribute is not cached
with override_current_site_id(site2.id):
grandchild = Page.objects.get(pk=grandchild.pk)
with self.assertNumQueries(1):
self.assertListEqual(grandchild.get_ascendants(), [child, parent])
| {
"content_hash": "ed0f3258cba4e2947d1b4fec5f9fc90e",
"timestamp": "",
"source": "github",
"line_count": 401,
"max_line_length": 79,
"avg_line_length": 42.34663341645885,
"alnum_prop": 0.630999352217184,
"repo_name": "sjuxax/mezzanine",
"id": "1b9f9dba8a652571784eaf11e2d1badb2efbed28",
"size": "16981",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mezzanine/pages/tests.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "60016"
},
{
"name": "HTML",
"bytes": "89073"
},
{
"name": "JavaScript",
"bytes": "452258"
},
{
"name": "Python",
"bytes": "660105"
}
],
"symlink_target": ""
} |
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import * as perf from 'vs/base/common/performance';
import { IAction, WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification } from 'vs/base/common/actions';
import { memoize } from 'vs/base/common/decorators';
import { IFilesConfiguration, ExplorerFolderContext, FilesExplorerFocusedContext, ExplorerFocusedContext, ExplorerRootContext, ExplorerResourceReadonlyContext, ExplorerResourceCut, ExplorerResourceMoveableToTrash, ExplorerCompressedFocusContext, ExplorerCompressedFirstFocusContext, ExplorerCompressedLastFocusContext, ExplorerResourceAvailableEditorIdsContext, VIEW_ID, VIEWLET_ID, ExplorerResourceNotReadonlyContext, ViewHasSomeCollapsibleRootItemContext } from 'vs/workbench/contrib/files/common/files';
import { FileCopiedContext, NEW_FILE_COMMAND_ID, NEW_FOLDER_COMMAND_ID } from 'vs/workbench/contrib/files/browser/fileActions';
import * as DOM from 'vs/base/browser/dom';
import { IWorkbenchLayoutService } from 'vs/workbench/services/layout/browser/layoutService';
import { ExplorerDecorationsProvider } from 'vs/workbench/contrib/files/browser/views/explorerDecorationsProvider';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IProgressService, ProgressLocation } from 'vs/platform/progress/common/progress';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IContextKeyService, IContextKey, ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { ResourceContextKey } from 'vs/workbench/common/contextkeys';
import { IDecorationsService } from 'vs/workbench/services/decorations/common/decorations';
import { WorkbenchCompressibleAsyncDataTree } from 'vs/platform/list/browser/listService';
import { DelayedDragHandler } from 'vs/base/browser/dnd';
import { IEditorService, SIDE_GROUP, ACTIVE_GROUP } from 'vs/workbench/services/editor/common/editorService';
import { IViewPaneOptions, ViewPane } from 'vs/workbench/browser/parts/views/viewPane';
import { ILabelService } from 'vs/platform/label/common/label';
import { ExplorerDelegate, ExplorerDataSource, FilesRenderer, ICompressedNavigationController, FilesFilter, FileSorter, FileDragAndDrop, ExplorerCompressionDelegate, isCompressedFolderName } from 'vs/workbench/contrib/files/browser/views/explorerViewer';
import { IThemeService, IFileIconTheme } from 'vs/platform/theme/common/themeService';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { ITreeContextMenuEvent, TreeVisibility } from 'vs/base/browser/ui/tree/tree';
import { IMenuService, MenuId, IMenu, Action2, registerAction2 } from 'vs/platform/actions/common/actions';
import { createAndFillInContextMenuActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ExplorerItem, NewExplorerItem } from 'vs/workbench/contrib/files/common/explorerModel';
import { ResourceLabels } from 'vs/workbench/browser/labels';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IAsyncDataTreeViewState } from 'vs/base/browser/ui/tree/asyncDataTree';
import { FuzzyScore } from 'vs/base/common/filters';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IFileService, FileSystemProviderCapabilities } from 'vs/platform/files/common/files';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { Event } from 'vs/base/common/event';
import { attachStyler, IColorMapping } from 'vs/platform/theme/common/styler';
import { ColorValue, listDropBackground } from 'vs/platform/theme/common/colorRegistry';
import { Color } from 'vs/base/common/color';
import { SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme';
import { IViewDescriptorService, IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { EditorResourceAccessor, SideBySideEditor } from 'vs/workbench/common/editor';
import { IExplorerService, IExplorerView } from 'vs/workbench/contrib/files/browser/files';
import { Codicon } from 'vs/base/common/codicons';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IEditorResolverService } from 'vs/workbench/services/editor/common/editorResolverService';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
import { EditorOpenSource } from 'vs/platform/editor/common/editor';
import { ResourceMap } from 'vs/base/common/map';
interface IExplorerViewColors extends IColorMapping {
listDropBackground?: ColorValue | undefined;
}
interface IExplorerViewStyles {
listDropBackground?: Color;
}
function hasExpandedRootChild(tree: WorkbenchCompressibleAsyncDataTree<ExplorerItem | ExplorerItem[], ExplorerItem, FuzzyScore>, treeInput: ExplorerItem[]): boolean {
for (const folder of treeInput) {
if (tree.hasNode(folder) && !tree.isCollapsed(folder)) {
for (const [, child] of folder.children.entries()) {
if (tree.hasNode(child) && tree.isCollapsible(child) && !tree.isCollapsed(child)) {
return true;
}
}
}
}
return false;
}
/**
* Whether or not any of the nodes in the tree are expanded
*/
function hasExpandedNode(tree: WorkbenchCompressibleAsyncDataTree<ExplorerItem | ExplorerItem[], ExplorerItem, FuzzyScore>, treeInput: ExplorerItem[]): boolean {
for (const folder of treeInput) {
if (tree.hasNode(folder) && !tree.isCollapsed(folder)) {
return true;
}
}
return false;
}
const identityProvider = {
getId: (stat: ExplorerItem) => {
if (stat instanceof NewExplorerItem) {
return `new:${stat.getId()}`;
}
return stat.getId();
}
};
export function getContext(focus: ExplorerItem[], selection: ExplorerItem[], respectMultiSelection: boolean,
compressedNavigationControllerProvider: { getCompressedNavigationController(stat: ExplorerItem): ICompressedNavigationController | undefined }): ExplorerItem[] {
let focusedStat: ExplorerItem | undefined;
focusedStat = focus.length ? focus[0] : undefined;
const compressedNavigationController = focusedStat && compressedNavigationControllerProvider.getCompressedNavigationController(focusedStat);
focusedStat = compressedNavigationController ? compressedNavigationController.current : focusedStat;
const selectedStats: ExplorerItem[] = [];
for (const stat of selection) {
const controller = compressedNavigationControllerProvider.getCompressedNavigationController(stat);
if (controller && focusedStat && controller === compressedNavigationController) {
if (stat === focusedStat) {
selectedStats.push(stat);
}
// Ignore stats which are selected but are part of the same compact node as the focused stat
continue;
}
if (controller) {
selectedStats.push(...controller.items);
} else {
selectedStats.push(stat);
}
}
if (!focusedStat) {
if (respectMultiSelection) {
return selectedStats;
} else {
return [];
}
}
if (respectMultiSelection && selectedStats.indexOf(focusedStat) >= 0) {
return selectedStats;
}
return [focusedStat];
}
export interface IExplorerViewContainerDelegate {
willOpenElement(event?: UIEvent): void;
didOpenElement(event?: UIEvent): void;
}
export class ExplorerView extends ViewPane implements IExplorerView {
static readonly TREE_VIEW_STATE_STORAGE_KEY: string = 'workbench.explorer.treeViewState';
private tree!: WorkbenchCompressibleAsyncDataTree<ExplorerItem | ExplorerItem[], ExplorerItem, FuzzyScore>;
private filter!: FilesFilter;
private resourceContext: ResourceContextKey;
private folderContext: IContextKey<boolean>;
private readonlyContext: IContextKey<boolean>;
private availableEditorIdsContext: IContextKey<string>;
private rootContext: IContextKey<boolean>;
private resourceMoveableToTrash: IContextKey<boolean>;
private renderer!: FilesRenderer;
private styleElement!: HTMLStyleElement;
private treeContainer!: HTMLElement;
private container!: HTMLElement;
private compressedFocusContext: IContextKey<boolean>;
private compressedFocusFirstContext: IContextKey<boolean>;
private compressedFocusLastContext: IContextKey<boolean>;
private viewHasSomeCollapsibleRootItem: IContextKey<boolean>;
private horizontalScrolling: boolean | undefined;
private dragHandler!: DelayedDragHandler;
private autoReveal: boolean | 'focusNoScroll' = false;
private decorationsProvider: ExplorerDecorationsProvider | undefined;
constructor(
options: IViewPaneOptions,
private readonly delegate: IExplorerViewContainerDelegate,
@IContextMenuService contextMenuService: IContextMenuService,
@IViewDescriptorService viewDescriptorService: IViewDescriptorService,
@IInstantiationService instantiationService: IInstantiationService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IProgressService private readonly progressService: IProgressService,
@IEditorService private readonly editorService: IEditorService,
@IEditorResolverService private readonly editorResolverService: IEditorResolverService,
@IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService,
@IKeybindingService keybindingService: IKeybindingService,
@IContextKeyService contextKeyService: IContextKeyService,
@IConfigurationService configurationService: IConfigurationService,
@IDecorationsService private readonly decorationService: IDecorationsService,
@ILabelService private readonly labelService: ILabelService,
@IThemeService themeService: IWorkbenchThemeService,
@IMenuService private readonly menuService: IMenuService,
@ITelemetryService telemetryService: ITelemetryService,
@IExplorerService private readonly explorerService: IExplorerService,
@IStorageService private readonly storageService: IStorageService,
@IClipboardService private clipboardService: IClipboardService,
@IFileService private readonly fileService: IFileService,
@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
@ICommandService private readonly commandService: ICommandService,
@IOpenerService openerService: IOpenerService
) {
super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService);
this.resourceContext = instantiationService.createInstance(ResourceContextKey);
this._register(this.resourceContext);
this.folderContext = ExplorerFolderContext.bindTo(contextKeyService);
this.readonlyContext = ExplorerResourceReadonlyContext.bindTo(contextKeyService);
this.availableEditorIdsContext = ExplorerResourceAvailableEditorIdsContext.bindTo(contextKeyService);
this.rootContext = ExplorerRootContext.bindTo(contextKeyService);
this.resourceMoveableToTrash = ExplorerResourceMoveableToTrash.bindTo(contextKeyService);
this.compressedFocusContext = ExplorerCompressedFocusContext.bindTo(contextKeyService);
this.compressedFocusFirstContext = ExplorerCompressedFirstFocusContext.bindTo(contextKeyService);
this.compressedFocusLastContext = ExplorerCompressedLastFocusContext.bindTo(contextKeyService);
this.viewHasSomeCollapsibleRootItem = ViewHasSomeCollapsibleRootItemContext.bindTo(contextKeyService);
this.explorerService.registerView(this);
}
get name(): string {
return this.labelService.getWorkspaceLabel(this.contextService.getWorkspace());
}
override get title(): string {
return this.name;
}
override set title(_: string) {
// noop
}
// Memoized locals
@memoize private get contributedContextMenu(): IMenu {
const contributedContextMenu = this.menuService.createMenu(MenuId.ExplorerContext, this.tree.contextKeyService);
this._register(contributedContextMenu);
return contributedContextMenu;
}
@memoize private get fileCopiedContextKey(): IContextKey<boolean> {
return FileCopiedContext.bindTo(this.contextKeyService);
}
@memoize private get resourceCutContextKey(): IContextKey<boolean> {
return ExplorerResourceCut.bindTo(this.contextKeyService);
}
// Split view methods
protected override renderHeader(container: HTMLElement): void {
super.renderHeader(container);
// Expand on drag over
this.dragHandler = new DelayedDragHandler(container, () => this.setExpanded(true));
const titleElement = container.querySelector('.title') as HTMLElement;
const setHeader = () => {
const workspace = this.contextService.getWorkspace();
const title = workspace.folders.map(folder => folder.name).join();
titleElement.textContent = this.name;
titleElement.title = title;
titleElement.setAttribute('aria-label', nls.localize('explorerSection', "Explorer Section: {0}", this.name));
};
this._register(this.contextService.onDidChangeWorkspaceName(setHeader));
this._register(this.labelService.onDidChangeFormatters(setHeader));
setHeader();
}
protected override layoutBody(height: number, width: number): void {
super.layoutBody(height, width);
this.tree.layout(height, width);
}
override renderBody(container: HTMLElement): void {
super.renderBody(container);
this.container = container;
this.treeContainer = DOM.append(container, DOM.$('.explorer-folders-view'));
this.styleElement = DOM.createStyleSheet(this.treeContainer);
attachStyler<IExplorerViewColors>(this.themeService, { listDropBackground }, this.styleListDropBackground.bind(this));
this.createTree(this.treeContainer);
this._register(this.labelService.onDidChangeFormatters(() => {
this._onDidChangeTitleArea.fire();
}));
// Update configuration
const configuration = this.configurationService.getValue<IFilesConfiguration>();
this.onConfigurationUpdated(configuration);
// When the explorer viewer is loaded, listen to changes to the editor input
this._register(this.editorService.onDidActiveEditorChange(() => {
this.selectActiveFile();
}));
// Also handle configuration updates
this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(this.configurationService.getValue<IFilesConfiguration>(), e)));
this._register(this.onDidChangeBodyVisibility(async visible => {
if (visible) {
// Always refresh explorer when it becomes visible to compensate for missing file events #126817
await this.setTreeInput();
// Update the collapse / expand button state
this.updateAnyCollapsedContext();
// Find resource to focus from active editor input if set
this.selectActiveFile(true);
}
}));
}
override focus(): void {
this.tree.domFocus();
const focused = this.tree.getFocus();
if (focused.length === 1 && this.autoReveal) {
this.tree.reveal(focused[0], 0.5);
}
}
hasFocus(): boolean {
return DOM.isAncestor(document.activeElement, this.container);
}
getContext(respectMultiSelection: boolean): ExplorerItem[] {
return getContext(this.tree.getFocus(), this.tree.getSelection(), respectMultiSelection, this.renderer);
}
isItemVisible(item: ExplorerItem): boolean {
return this.filter.filter(item, TreeVisibility.Visible);
}
isItemCollapsed(item: ExplorerItem): boolean {
return this.tree.isCollapsed(item);
}
async setEditable(stat: ExplorerItem, isEditing: boolean): Promise<void> {
if (isEditing) {
this.horizontalScrolling = this.tree.options.horizontalScrolling;
if (this.horizontalScrolling) {
this.tree.updateOptions({ horizontalScrolling: false });
}
await this.tree.expand(stat.parent!);
} else {
if (this.horizontalScrolling !== undefined) {
this.tree.updateOptions({ horizontalScrolling: this.horizontalScrolling });
}
this.horizontalScrolling = undefined;
this.treeContainer.classList.remove('highlight');
}
await this.refresh(false, stat.parent, false);
if (isEditing) {
this.treeContainer.classList.add('highlight');
this.tree.reveal(stat);
} else {
this.tree.domFocus();
}
}
private selectActiveFile(reveal = this.autoReveal): void {
if (this.autoReveal) {
const activeFile = EditorResourceAccessor.getCanonicalUri(this.editorService.activeEditor, { supportSideBySide: SideBySideEditor.PRIMARY });
if (activeFile) {
const focus = this.tree.getFocus();
const selection = this.tree.getSelection();
if (focus.length === 1 && this.uriIdentityService.extUri.isEqual(focus[0].resource, activeFile) && selection.length === 1 && this.uriIdentityService.extUri.isEqual(selection[0].resource, activeFile)) {
// No action needed, active file is already focused and selected
return;
}
this.explorerService.select(activeFile, reveal);
}
}
}
private createTree(container: HTMLElement): void {
this.filter = this.instantiationService.createInstance(FilesFilter);
this._register(this.filter);
this._register(this.filter.onDidChange(() => this.refresh(true)));
const explorerLabels = this.instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: this.onDidChangeBodyVisibility });
this._register(explorerLabels);
const updateWidth = (stat: ExplorerItem) => this.tree.updateWidth(stat);
this.renderer = this.instantiationService.createInstance(FilesRenderer, explorerLabels, updateWidth);
this._register(this.renderer);
this._register(createFileIconThemableTreeContainerScope(container, this.themeService));
const isCompressionEnabled = () => this.configurationService.getValue<boolean>('explorer.compactFolders');
const getFileNestingSettings = (item?: ExplorerItem) => this.configurationService.getValue<IFilesConfiguration>({ resource: item?.root.resource }).explorer.fileNesting;
this.tree = <WorkbenchCompressibleAsyncDataTree<ExplorerItem | ExplorerItem[], ExplorerItem, FuzzyScore>>this.instantiationService.createInstance(WorkbenchCompressibleAsyncDataTree, 'FileExplorer', container, new ExplorerDelegate(), new ExplorerCompressionDelegate(), [this.renderer],
this.instantiationService.createInstance(ExplorerDataSource, this.filter), {
compressionEnabled: isCompressionEnabled(),
accessibilityProvider: this.renderer,
identityProvider,
keyboardNavigationLabelProvider: {
getKeyboardNavigationLabel: (stat: ExplorerItem) => {
if (this.explorerService.isEditable(stat)) {
return undefined;
}
return stat.name;
},
getCompressedNodeKeyboardNavigationLabel: (stats: ExplorerItem[]) => {
if (stats.some(stat => this.explorerService.isEditable(stat))) {
return undefined;
}
return stats.map(stat => stat.name).join('/');
}
},
multipleSelectionSupport: true,
filter: this.filter,
sorter: this.instantiationService.createInstance(FileSorter),
dnd: this.instantiationService.createInstance(FileDragAndDrop, (item) => this.isItemCollapsed(item)),
collapseByDefault: (e) => {
if (e instanceof ExplorerItem) {
if (e.hasNests && getFileNestingSettings(e).expand) {
return false;
}
}
return true;
},
autoExpandSingleChildren: true,
expandOnlyOnTwistieClick: (e: unknown) => {
if (e instanceof ExplorerItem) {
if (e.hasNests) {
return true;
}
else if (this.configurationService.getValue<'singleClick' | 'doubleClick'>('workbench.tree.expandMode') === 'doubleClick') {
return true;
}
}
return false;
},
additionalScrollHeight: ExplorerDelegate.ITEM_HEIGHT,
overrideStyles: {
listBackground: SIDE_BAR_BACKGROUND
}
});
this._register(this.tree);
// Bind configuration
const onDidChangeCompressionConfiguration = Event.filter(this.configurationService.onDidChangeConfiguration, e => e.affectsConfiguration('explorer.compactFolders'));
this._register(onDidChangeCompressionConfiguration(_ => this.tree.updateOptions({ compressionEnabled: isCompressionEnabled() })));
// Bind context keys
FilesExplorerFocusedContext.bindTo(this.tree.contextKeyService);
ExplorerFocusedContext.bindTo(this.tree.contextKeyService);
// Update resource context based on focused element
this._register(this.tree.onDidChangeFocus(e => this.onFocusChanged(e.elements)));
this.onFocusChanged([]);
// Open when selecting via keyboard
this._register(this.tree.onDidOpen(async e => {
const element = e.element;
if (!element) {
return;
}
// Do not react if the user is expanding selection via keyboard.
// Check if the item was previously also selected, if yes the user is simply expanding / collapsing current selection #66589.
const shiftDown = e.browserEvent instanceof KeyboardEvent && e.browserEvent.shiftKey;
if (!shiftDown) {
if (element.isDirectory || this.explorerService.isEditable(undefined)) {
// Do not react if user is clicking on explorer items while some are being edited #70276
// Do not react if clicking on directories
return;
}
this.telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: 'workbench.files.openFile', from: 'explorer' });
try {
this.delegate.willOpenElement(e.browserEvent);
await this.editorService.openEditor({ resource: element.resource, options: { preserveFocus: e.editorOptions.preserveFocus, pinned: e.editorOptions.pinned, source: EditorOpenSource.USER } }, e.sideBySide ? SIDE_GROUP : ACTIVE_GROUP);
} finally {
this.delegate.didOpenElement();
}
}
}));
this._register(this.tree.onContextMenu(e => this.onContextMenu(e)));
this._register(this.tree.onDidScroll(async e => {
const editable = this.explorerService.getEditable();
if (e.scrollTopChanged && editable && this.tree.getRelativeTop(editable.stat) === null) {
await editable.data.onFinish('', false);
}
}));
this._register(this.tree.onDidChangeCollapseState(e => {
const element = e.node.element?.element;
if (element) {
const navigationController = this.renderer.getCompressedNavigationController(element instanceof Array ? element[0] : element);
navigationController?.updateCollapsed(e.node.collapsed);
}
// Update showing expand / collapse button
this.updateAnyCollapsedContext();
}));
this.updateAnyCollapsedContext();
this._register(this.tree.onMouseDblClick(e => {
if (e.element === null) {
// click in empty area -> create a new file #116676
this.commandService.executeCommand(NEW_FILE_COMMAND_ID);
}
}));
// save view state
this._register(this.storageService.onWillSaveState(() => {
this.storageService.store(ExplorerView.TREE_VIEW_STATE_STORAGE_KEY, JSON.stringify(this.tree.getViewState()), StorageScope.WORKSPACE, StorageTarget.MACHINE);
}));
}
// React on events
private onConfigurationUpdated(configuration: IFilesConfiguration, event?: IConfigurationChangeEvent): void {
this.autoReveal = configuration?.explorer?.autoReveal;
// Push down config updates to components of viewer
if (event && (event.affectsConfiguration('explorer.decorations.colors') || event.affectsConfiguration('explorer.decorations.badges'))) {
this.refresh(true);
}
}
private setContextKeys(stat: ExplorerItem | null | undefined): void {
const folders = this.contextService.getWorkspace().folders;
const resource = stat ? stat.resource : folders[folders.length - 1].uri;
stat = stat || this.explorerService.findClosest(resource);
this.resourceContext.set(resource);
this.folderContext.set(!!stat && stat.isDirectory);
this.readonlyContext.set(!!stat && stat.isReadonly);
this.rootContext.set(!!stat && stat.isRoot);
if (resource) {
const overrides = resource ? this.editorResolverService.getEditors(resource).map(editor => editor.id) : [];
this.availableEditorIdsContext.set(overrides.join(','));
} else {
this.availableEditorIdsContext.reset();
}
}
private async onContextMenu(e: ITreeContextMenuEvent<ExplorerItem>): Promise<void> {
const disposables = new DisposableStore();
const stat = e.element;
let anchor = e.anchor;
// Compressed folders
if (stat) {
const controller = this.renderer.getCompressedNavigationController(stat);
if (controller) {
if (e.browserEvent instanceof KeyboardEvent || isCompressedFolderName(e.browserEvent.target)) {
anchor = controller.labels[controller.index];
} else {
controller.last();
}
}
}
// update dynamic contexts
this.fileCopiedContextKey.set(await this.clipboardService.hasResources());
this.setContextKeys(stat);
const selection = this.tree.getSelection();
const actions: IAction[] = [];
const roots = this.explorerService.roots; // If the click is outside of the elements pass the root resource if there is only one root. If there are multiple roots pass empty object.
let arg: URI | {};
if (stat instanceof ExplorerItem) {
const compressedController = this.renderer.getCompressedNavigationController(stat);
arg = compressedController ? compressedController.current.resource : stat.resource;
} else {
arg = roots.length === 1 ? roots[0].resource : {};
}
disposables.add(createAndFillInContextMenuActions(this.contributedContextMenu, { arg, shouldForwardArgs: true }, actions));
this.contextMenuService.showContextMenu({
getAnchor: () => anchor,
getActions: () => actions,
onHide: (wasCancelled?: boolean) => {
if (wasCancelled) {
this.tree.domFocus();
}
disposables.dispose();
},
getActionsContext: () => stat && selection && selection.indexOf(stat) >= 0
? selection.map((fs: ExplorerItem) => fs.resource)
: stat instanceof ExplorerItem ? [stat.resource] : []
});
}
private onFocusChanged(elements: ExplorerItem[]): void {
const stat = elements && elements.length ? elements[0] : undefined;
this.setContextKeys(stat);
if (stat) {
const enableTrash = this.configurationService.getValue<IFilesConfiguration>().files.enableTrash;
const hasCapability = this.fileService.hasCapability(stat.resource, FileSystemProviderCapabilities.Trash);
this.resourceMoveableToTrash.set(enableTrash && hasCapability);
} else {
this.resourceMoveableToTrash.reset();
}
const compressedNavigationController = stat && this.renderer.getCompressedNavigationController(stat);
if (!compressedNavigationController) {
this.compressedFocusContext.set(false);
return;
}
this.compressedFocusContext.set(true);
this.updateCompressedNavigationContextKeys(compressedNavigationController);
}
// General methods
/**
* Refresh the contents of the explorer to get up to date data from the disk about the file structure.
* If the item is passed we refresh only that level of the tree, otherwise we do a full refresh.
*/
refresh(recursive: boolean, item?: ExplorerItem, cancelEditing: boolean = true): Promise<void> {
if (!this.tree || !this.isBodyVisible() || (item && !this.tree.hasNode(item))) {
// Tree node doesn't exist yet, when it becomes visible we will refresh
return Promise.resolve(undefined);
}
if (cancelEditing && this.explorerService.isEditable(undefined)) {
this.tree.domFocus();
}
const toRefresh = item || this.tree.getInput();
return this.tree.updateChildren(toRefresh, recursive, false, {
diffIdentityProvider: identityProvider
});
}
override getOptimalWidth(): number {
const parentNode = this.tree.getHTMLElement();
const childNodes = ([] as HTMLElement[]).slice.call(parentNode.querySelectorAll('.explorer-item .label-name')); // select all file labels
return DOM.getLargestChildWidth(parentNode, childNodes);
}
async setTreeInput(): Promise<void> {
if (!this.isBodyVisible()) {
return Promise.resolve(undefined);
}
const initialInputSetup = !this.tree.getInput();
if (initialInputSetup) {
perf.mark('code/willResolveExplorer');
}
const roots = this.explorerService.roots;
let input: ExplorerItem | ExplorerItem[] = roots[0];
if (this.contextService.getWorkbenchState() !== WorkbenchState.FOLDER || roots[0].isError) {
// Display roots only when multi folder workspace
input = roots;
}
let viewState: IAsyncDataTreeViewState | undefined;
if (this.tree && this.tree.getInput()) {
viewState = this.tree.getViewState();
} else {
const rawViewState = this.storageService.get(ExplorerView.TREE_VIEW_STATE_STORAGE_KEY, StorageScope.WORKSPACE);
if (rawViewState) {
viewState = JSON.parse(rawViewState);
}
}
const previousInput = this.tree.getInput();
const promise = this.tree.setInput(input, viewState).then(async () => {
if (Array.isArray(input)) {
if (!viewState || previousInput instanceof ExplorerItem) {
// There is no view state for this workspace (we transitioned from a folder workspace?), expand all roots.
await Promise.all(input.map(async item => {
try {
await this.tree.expand(item);
} catch (e) { }
}));
}
// Reloaded or transitioned from an empty workspace, but only have a single folder in the workspace.
if (!previousInput && input.length === 1 && this.configurationService.getValue<IFilesConfiguration>().explorer.expandSingleFolderWorkspaces) {
await this.tree.expand(input[0]).catch(() => { });
}
if (Array.isArray(previousInput)) {
const previousRoots = new ResourceMap<true>();
previousInput.forEach(previousRoot => previousRoots.set(previousRoot.resource, true));
// Roots added to the explorer -> expand them.
await Promise.all(input.map(async item => {
if (!previousRoots.has(item.resource)) {
try {
await this.tree.expand(item);
} catch (e) { }
}
}));
}
}
if (initialInputSetup) {
perf.mark('code/didResolveExplorer');
}
});
this.progressService.withProgress({
location: ProgressLocation.Explorer,
delay: this.layoutService.isRestored() ? 800 : 1500 // reduce progress visibility when still restoring
}, _progress => promise);
await promise;
if (!this.decorationsProvider) {
this.decorationsProvider = new ExplorerDecorationsProvider(this.explorerService, this.contextService);
this._register(this.decorationService.registerDecorationsProvider(this.decorationsProvider));
}
}
public async selectResource(resource: URI | undefined, reveal = this.autoReveal, retry = 0): Promise<void> {
// do no retry more than once to prevent inifinite loops in cases of inconsistent model
if (retry === 2) {
return;
}
if (!resource || !this.isBodyVisible()) {
return;
}
// Expand all stats in the parent chain.
let item: ExplorerItem | null = this.explorerService.findClosestRoot(resource);
while (item && item.resource.toString() !== resource.toString()) {
try {
await this.tree.expand(item);
} catch (e) {
return this.selectResource(resource, reveal, retry + 1);
}
for (const child of item.children.values()) {
if (this.uriIdentityService.extUri.isEqualOrParent(resource, child.resource)) {
item = child;
break;
}
item = null;
}
}
if (item) {
if (item === this.tree.getInput()) {
this.tree.setFocus([]);
this.tree.setSelection([]);
return;
}
try {
if (reveal === true && this.tree.getRelativeTop(item) === null) {
// Don't scroll to the item if it's already visible, or if set not to.
this.tree.reveal(item, 0.5);
}
this.tree.setFocus([item]);
this.tree.setSelection([item]);
} catch (e) {
// Element might not be in the tree, try again and silently fail
return this.selectResource(resource, reveal, retry + 1);
}
}
}
itemsCopied(stats: ExplorerItem[], cut: boolean, previousCut: ExplorerItem[] | undefined): void {
this.fileCopiedContextKey.set(stats.length > 0);
this.resourceCutContextKey.set(cut && stats.length > 0);
previousCut?.forEach(item => this.tree.rerender(item));
if (cut) {
stats.forEach(s => this.tree.rerender(s));
}
}
expandAll(): void {
if (this.explorerService.isEditable(undefined)) {
this.tree.domFocus();
}
this.tree.expandAll();
}
collapseAll(): void {
if (this.explorerService.isEditable(undefined)) {
this.tree.domFocus();
}
const treeInput = this.tree.getInput();
if (Array.isArray(treeInput)) {
if (hasExpandedRootChild(this.tree, treeInput)) {
treeInput.forEach(folder => {
folder.children.forEach(child => this.tree.hasNode(child) && this.tree.collapse(child, true));
});
return;
}
}
this.tree.collapseAll();
}
previousCompressedStat(): void {
const focused = this.tree.getFocus();
if (!focused.length) {
return;
}
const compressedNavigationController = this.renderer.getCompressedNavigationController(focused[0])!;
compressedNavigationController.previous();
this.updateCompressedNavigationContextKeys(compressedNavigationController);
}
nextCompressedStat(): void {
const focused = this.tree.getFocus();
if (!focused.length) {
return;
}
const compressedNavigationController = this.renderer.getCompressedNavigationController(focused[0])!;
compressedNavigationController.next();
this.updateCompressedNavigationContextKeys(compressedNavigationController);
}
firstCompressedStat(): void {
const focused = this.tree.getFocus();
if (!focused.length) {
return;
}
const compressedNavigationController = this.renderer.getCompressedNavigationController(focused[0])!;
compressedNavigationController.first();
this.updateCompressedNavigationContextKeys(compressedNavigationController);
}
lastCompressedStat(): void {
const focused = this.tree.getFocus();
if (!focused.length) {
return;
}
const compressedNavigationController = this.renderer.getCompressedNavigationController(focused[0])!;
compressedNavigationController.last();
this.updateCompressedNavigationContextKeys(compressedNavigationController);
}
private updateCompressedNavigationContextKeys(controller: ICompressedNavigationController): void {
this.compressedFocusFirstContext.set(controller.index === 0);
this.compressedFocusLastContext.set(controller.index === controller.count - 1);
}
private updateAnyCollapsedContext(): void {
const treeInput = this.tree.getInput();
if (treeInput === undefined) {
return;
}
const treeInputArray = Array.isArray(treeInput) ? treeInput : Array.from(treeInput.children.values());
// Has collapsible root when anything is expanded
this.viewHasSomeCollapsibleRootItem.set(hasExpandedNode(this.tree, treeInputArray));
}
styleListDropBackground(styles: IExplorerViewStyles): void {
const content: string[] = [];
if (styles.listDropBackground) {
content.push(`.explorer-viewlet .explorer-item .monaco-icon-name-container.multiple > .label-name.drop-target > .monaco-highlighted-label { background-color: ${styles.listDropBackground}; }`);
}
const newStyles = content.join('\n');
if (newStyles !== this.styleElement.textContent) {
this.styleElement.textContent = newStyles;
}
}
override dispose(): void {
if (this.dragHandler) {
this.dragHandler.dispose();
}
super.dispose();
}
}
function createFileIconThemableTreeContainerScope(container: HTMLElement, themeService: IThemeService): IDisposable {
container.classList.add('file-icon-themable-tree');
container.classList.add('show-file-icons');
const onDidChangeFileIconTheme = (theme: IFileIconTheme) => {
container.classList.toggle('align-icons-and-twisties', theme.hasFileIcons && !theme.hasFolderIcons);
container.classList.toggle('hide-arrows', theme.hidesExplorerArrows === true);
};
onDidChangeFileIconTheme(themeService.getFileIconTheme());
return themeService.onDidFileIconThemeChange(onDidChangeFileIconTheme);
}
registerAction2(class extends Action2 {
constructor() {
super({
id: 'workbench.files.action.createFileFromExplorer',
title: nls.localize('createNewFile', "New File"),
f1: false,
icon: Codicon.newFile,
precondition: ExplorerResourceNotReadonlyContext,
menu: {
id: MenuId.ViewTitle,
group: 'navigation',
when: ContextKeyExpr.equals('view', VIEW_ID),
order: 10
}
});
}
run(accessor: ServicesAccessor): void {
const commandService = accessor.get(ICommandService);
commandService.executeCommand(NEW_FILE_COMMAND_ID);
}
});
registerAction2(class extends Action2 {
constructor() {
super({
id: 'workbench.files.action.createFolderFromExplorer',
title: nls.localize('createNewFolder', "New Folder"),
f1: false,
icon: Codicon.newFolder,
precondition: ExplorerResourceNotReadonlyContext,
menu: {
id: MenuId.ViewTitle,
group: 'navigation',
when: ContextKeyExpr.equals('view', VIEW_ID),
order: 20
}
});
}
run(accessor: ServicesAccessor): void {
const commandService = accessor.get(ICommandService);
commandService.executeCommand(NEW_FOLDER_COMMAND_ID);
}
});
registerAction2(class extends Action2 {
constructor() {
super({
id: 'workbench.files.action.refreshFilesExplorer',
title: { value: nls.localize('refreshExplorer', "Refresh Explorer"), original: 'Refresh Explorer' },
f1: true,
icon: Codicon.refresh,
menu: {
id: MenuId.ViewTitle,
group: 'navigation',
when: ContextKeyExpr.equals('view', VIEW_ID),
order: 30
}
});
}
async run(accessor: ServicesAccessor): Promise<void> {
const paneCompositeService = accessor.get(IPaneCompositePartService);
const explorerService = accessor.get(IExplorerService);
await paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar);
await explorerService.refresh();
}
});
registerAction2(class extends Action2 {
constructor() {
super({
id: 'workbench.files.action.collapseExplorerFolders',
title: { value: nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer"), original: 'Collapse Folders in Explorer' },
f1: true,
icon: Codicon.collapseAll,
menu: {
id: MenuId.ViewTitle,
group: 'navigation',
when: ContextKeyExpr.equals('view', VIEW_ID),
order: 40
}
});
}
run(accessor: ServicesAccessor) {
const viewsService = accessor.get(IViewsService);
const explorerView = viewsService.getViewWithId(VIEW_ID) as ExplorerView;
explorerView.collapseAll();
}
});
| {
"content_hash": "2aab68e3ee61ab9134db9d0820ffab35",
"timestamp": "",
"source": "github",
"line_count": 1000,
"max_line_length": 506,
"avg_line_length": 38.588,
"alnum_prop": 0.7511920804395149,
"repo_name": "eamodio/vscode",
"id": "6e15cf4d9c84be285332978bcf98c0e6d62d58af",
"size": "38939",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/vs/workbench/contrib/files/browser/views/explorerView.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "19196"
},
{
"name": "C",
"bytes": "818"
},
{
"name": "C#",
"bytes": "709"
},
{
"name": "C++",
"bytes": "2745"
},
{
"name": "CSS",
"bytes": "620323"
},
{
"name": "Clojure",
"bytes": "1206"
},
{
"name": "CoffeeScript",
"bytes": "590"
},
{
"name": "Cuda",
"bytes": "3634"
},
{
"name": "Dart",
"bytes": "324"
},
{
"name": "Dockerfile",
"bytes": "475"
},
{
"name": "F#",
"bytes": "634"
},
{
"name": "Go",
"bytes": "652"
},
{
"name": "Groovy",
"bytes": "3928"
},
{
"name": "HLSL",
"bytes": "184"
},
{
"name": "HTML",
"bytes": "380999"
},
{
"name": "Hack",
"bytes": "16"
},
{
"name": "Handlebars",
"bytes": "1064"
},
{
"name": "Inno Setup",
"bytes": "304239"
},
{
"name": "Java",
"bytes": "599"
},
{
"name": "JavaScript",
"bytes": "1413253"
},
{
"name": "Julia",
"bytes": "940"
},
{
"name": "Jupyter Notebook",
"bytes": "929"
},
{
"name": "Less",
"bytes": "1029"
},
{
"name": "Lua",
"bytes": "252"
},
{
"name": "Makefile",
"bytes": "2252"
},
{
"name": "Objective-C",
"bytes": "1387"
},
{
"name": "Objective-C++",
"bytes": "1387"
},
{
"name": "PHP",
"bytes": "998"
},
{
"name": "Perl",
"bytes": "1922"
},
{
"name": "PowerShell",
"bytes": "12409"
},
{
"name": "Pug",
"bytes": "654"
},
{
"name": "Python",
"bytes": "2405"
},
{
"name": "R",
"bytes": "362"
},
{
"name": "Roff",
"bytes": "351"
},
{
"name": "Ruby",
"bytes": "1703"
},
{
"name": "Rust",
"bytes": "532"
},
{
"name": "SCSS",
"bytes": "6732"
},
{
"name": "ShaderLab",
"bytes": "330"
},
{
"name": "Shell",
"bytes": "57256"
},
{
"name": "Swift",
"bytes": "284"
},
{
"name": "TeX",
"bytes": "1602"
},
{
"name": "TypeScript",
"bytes": "41954506"
},
{
"name": "Visual Basic .NET",
"bytes": "893"
}
],
"symlink_target": ""
} |
#pragma once
#ifndef GWEN_CONTROLS_PROPERTIES_H
#define GWEN_CONTROLS_PROPERTIES_H
#include "Gwen/Controls/Base.h"
#include "Gwen/Controls/Label.h"
#include "Gwen/Controls/Property/BaseProperty.h"
#include "Gwen/Controls/Property/Text.h"
#include "Gwen/Controls/SplitterBar.h"
#include "Gwen/Gwen.h"
#include "Gwen/Skin.h"
namespace Gwen
{
namespace Controls
{
class PropertyRow;
class GWEN_EXPORT Properties : public Base
{
public:
GWEN_CONTROL( Properties, Base );
virtual void PostLayout( Gwen::Skin::Base* skin );
PropertyRow* Add( const TextObject& text, const TextObject& value = L"" );
PropertyRow* Add( const TextObject& text, Property::Base* pProp, const TextObject& value = L"" );
PropertyRow* Find( const TextObject& text );
virtual int GetSplitWidth();
virtual void Clear();
protected:
virtual void OnSplitterMoved( Controls::Base * control );
Controls::SplitterBar* m_SplitterBar;
};
class GWEN_EXPORT PropertyRow : public Base
{
public:
GWEN_CONTROL( PropertyRow, Base );
virtual Label* GetLabel(){ return m_Label; }
virtual void SetProperty( Property::Base* prop );
virtual Property::Base* GetProperty(){ return m_Property; }
virtual void Layout( Gwen::Skin::Base* skin );
virtual void Render( Gwen::Skin::Base* skin );
virtual bool IsEditing(){ return m_Property && m_Property->IsEditing(); }
virtual bool IsHovered(){ return BaseClass::IsHovered() || (m_Property && m_Property->IsHovered()); }
virtual void OnEditingChanged();
virtual void OnHoverChanged();
Event::Caller onChange;
protected:
void OnPropertyValueChanged( Gwen::Controls::Base* control );
Label* m_Label;
Property::Base* m_Property;
bool m_bLastEditing;
bool m_bLastHover;
};
}
}
#endif
| {
"content_hash": "5cb9d280bd95447cc3b9f759cbaf1325",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 105,
"avg_line_length": 22.9125,
"alnum_prop": 0.6846699399890889,
"repo_name": "seanstermonstr/test",
"id": "e78c5685d440c6c8e8155d55aa82591a536ceb4f",
"size": "1905",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Code/Angel/Libraries/gwen/include/Gwen/Controls/Properties.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "139983"
},
{
"name": "Awk",
"bytes": "3965"
},
{
"name": "C",
"bytes": "18808479"
},
{
"name": "C#",
"bytes": "54113"
},
{
"name": "C++",
"bytes": "6774304"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "41399"
},
{
"name": "JavaScript",
"bytes": "21904"
},
{
"name": "Lua",
"bytes": "487076"
},
{
"name": "OCaml",
"bytes": "6380"
},
{
"name": "Objective-C",
"bytes": "157922"
},
{
"name": "Pascal",
"bytes": "40318"
},
{
"name": "Perl",
"bytes": "32150"
},
{
"name": "Pike",
"bytes": "583"
},
{
"name": "Python",
"bytes": "202527"
},
{
"name": "Ruby",
"bytes": "234"
},
{
"name": "Scheme",
"bytes": "9578"
},
{
"name": "Shell",
"bytes": "1525373"
},
{
"name": "TeX",
"bytes": "144346"
}
],
"symlink_target": ""
} |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: org.xml.sax.helpers.AttributesImpl
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_XML_SAX_HELPERS_ATTRIBUTESIMPL_HPP_DECL
#define J2CPP_ORG_XML_SAX_HELPERS_ATTRIBUTESIMPL_HPP_DECL
namespace j2cpp { namespace org { namespace xml { namespace sax { class Attributes; } } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
#include <java/lang/Object.hpp>
#include <java/lang/String.hpp>
#include <org/xml/sax/Attributes.hpp>
namespace j2cpp {
namespace org { namespace xml { namespace sax { namespace helpers {
class AttributesImpl;
class AttributesImpl
: public object<AttributesImpl>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
J2CPP_DECLARE_METHOD(8)
J2CPP_DECLARE_METHOD(9)
J2CPP_DECLARE_METHOD(10)
J2CPP_DECLARE_METHOD(11)
J2CPP_DECLARE_METHOD(12)
J2CPP_DECLARE_METHOD(13)
J2CPP_DECLARE_METHOD(14)
J2CPP_DECLARE_METHOD(15)
J2CPP_DECLARE_METHOD(16)
J2CPP_DECLARE_METHOD(17)
J2CPP_DECLARE_METHOD(18)
J2CPP_DECLARE_METHOD(19)
J2CPP_DECLARE_METHOD(20)
J2CPP_DECLARE_METHOD(21)
J2CPP_DECLARE_METHOD(22)
J2CPP_DECLARE_METHOD(23)
explicit AttributesImpl(jobject jobj)
: object<AttributesImpl>(jobj)
{
}
operator local_ref<org::xml::sax::Attributes>() const;
operator local_ref<java::lang::Object>() const;
AttributesImpl();
AttributesImpl(local_ref< org::xml::sax::Attributes > const&);
jint getLength();
local_ref< java::lang::String > getURI(jint);
local_ref< java::lang::String > getLocalName(jint);
local_ref< java::lang::String > getQName(jint);
local_ref< java::lang::String > getType(jint);
local_ref< java::lang::String > getValue(jint);
jint getIndex(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);
jint getIndex(local_ref< java::lang::String > const&);
local_ref< java::lang::String > getType(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);
local_ref< java::lang::String > getType(local_ref< java::lang::String > const&);
local_ref< java::lang::String > getValue(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);
local_ref< java::lang::String > getValue(local_ref< java::lang::String > const&);
void clear();
void setAttributes(local_ref< org::xml::sax::Attributes > const&);
void addAttribute(local_ref< java::lang::String > const&, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);
void setAttribute(jint, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&, local_ref< java::lang::String > const&);
void removeAttribute(jint);
void setURI(jint, local_ref< java::lang::String > const&);
void setLocalName(jint, local_ref< java::lang::String > const&);
void setQName(jint, local_ref< java::lang::String > const&);
void setType(jint, local_ref< java::lang::String > const&);
void setValue(jint, local_ref< java::lang::String > const&);
}; //class AttributesImpl
} //namespace helpers
} //namespace sax
} //namespace xml
} //namespace org
} //namespace j2cpp
#endif //J2CPP_ORG_XML_SAX_HELPERS_ATTRIBUTESIMPL_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_XML_SAX_HELPERS_ATTRIBUTESIMPL_HPP_IMPL
#define J2CPP_ORG_XML_SAX_HELPERS_ATTRIBUTESIMPL_HPP_IMPL
namespace j2cpp {
org::xml::sax::helpers::AttributesImpl::operator local_ref<org::xml::sax::Attributes>() const
{
return local_ref<org::xml::sax::Attributes>(get_jobject());
}
org::xml::sax::helpers::AttributesImpl::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
org::xml::sax::helpers::AttributesImpl::AttributesImpl()
: object<org::xml::sax::helpers::AttributesImpl>(
call_new_object<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(0),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(0)
>()
)
{
}
org::xml::sax::helpers::AttributesImpl::AttributesImpl(local_ref< org::xml::sax::Attributes > const &a0)
: object<org::xml::sax::helpers::AttributesImpl>(
call_new_object<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(1),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(1)
>(a0)
)
{
}
jint org::xml::sax::helpers::AttributesImpl::getLength()
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(2),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(2),
jint
>(get_jobject());
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getURI(jint a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(3),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(3),
local_ref< java::lang::String >
>(get_jobject(), a0);
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getLocalName(jint a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(4),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(4),
local_ref< java::lang::String >
>(get_jobject(), a0);
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getQName(jint a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(5),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(5),
local_ref< java::lang::String >
>(get_jobject(), a0);
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getType(jint a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(6),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(6),
local_ref< java::lang::String >
>(get_jobject(), a0);
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getValue(jint a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(7),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(7),
local_ref< java::lang::String >
>(get_jobject(), a0);
}
jint org::xml::sax::helpers::AttributesImpl::getIndex(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(8),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(8),
jint
>(get_jobject(), a0, a1);
}
jint org::xml::sax::helpers::AttributesImpl::getIndex(local_ref< java::lang::String > const &a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(9),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(9),
jint
>(get_jobject(), a0);
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getType(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(10),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(10),
local_ref< java::lang::String >
>(get_jobject(), a0, a1);
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getType(local_ref< java::lang::String > const &a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(11),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(11),
local_ref< java::lang::String >
>(get_jobject(), a0);
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getValue(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(12),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(12),
local_ref< java::lang::String >
>(get_jobject(), a0, a1);
}
local_ref< java::lang::String > org::xml::sax::helpers::AttributesImpl::getValue(local_ref< java::lang::String > const &a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(13),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(13),
local_ref< java::lang::String >
>(get_jobject(), a0);
}
void org::xml::sax::helpers::AttributesImpl::clear()
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(14),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(14),
void
>(get_jobject());
}
void org::xml::sax::helpers::AttributesImpl::setAttributes(local_ref< org::xml::sax::Attributes > const &a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(15),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(15),
void
>(get_jobject(), a0);
}
void org::xml::sax::helpers::AttributesImpl::addAttribute(local_ref< java::lang::String > const &a0, local_ref< java::lang::String > const &a1, local_ref< java::lang::String > const &a2, local_ref< java::lang::String > const &a3, local_ref< java::lang::String > const &a4)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(16),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(16),
void
>(get_jobject(), a0, a1, a2, a3, a4);
}
void org::xml::sax::helpers::AttributesImpl::setAttribute(jint a0, local_ref< java::lang::String > const &a1, local_ref< java::lang::String > const &a2, local_ref< java::lang::String > const &a3, local_ref< java::lang::String > const &a4, local_ref< java::lang::String > const &a5)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(17),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(17),
void
>(get_jobject(), a0, a1, a2, a3, a4, a5);
}
void org::xml::sax::helpers::AttributesImpl::removeAttribute(jint a0)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(18),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(18),
void
>(get_jobject(), a0);
}
void org::xml::sax::helpers::AttributesImpl::setURI(jint a0, local_ref< java::lang::String > const &a1)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(19),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(19),
void
>(get_jobject(), a0, a1);
}
void org::xml::sax::helpers::AttributesImpl::setLocalName(jint a0, local_ref< java::lang::String > const &a1)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(20),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(20),
void
>(get_jobject(), a0, a1);
}
void org::xml::sax::helpers::AttributesImpl::setQName(jint a0, local_ref< java::lang::String > const &a1)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(21),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(21),
void
>(get_jobject(), a0, a1);
}
void org::xml::sax::helpers::AttributesImpl::setType(jint a0, local_ref< java::lang::String > const &a1)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(22),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(22),
void
>(get_jobject(), a0, a1);
}
void org::xml::sax::helpers::AttributesImpl::setValue(jint a0, local_ref< java::lang::String > const &a1)
{
return call_method<
org::xml::sax::helpers::AttributesImpl::J2CPP_CLASS_NAME,
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_NAME(23),
org::xml::sax::helpers::AttributesImpl::J2CPP_METHOD_SIGNATURE(23),
void
>(get_jobject(), a0, a1);
}
J2CPP_DEFINE_CLASS(org::xml::sax::helpers::AttributesImpl,"org/xml/sax/helpers/AttributesImpl")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,0,"<init>","()V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,1,"<init>","(Lorg/xml/sax/Attributes;)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,2,"getLength","()I")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,3,"getURI","(I)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,4,"getLocalName","(I)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,5,"getQName","(I)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,6,"getType","(I)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,7,"getValue","(I)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,8,"getIndex","(Ljava/lang/String;Ljava/lang/String;)I")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,9,"getIndex","(Ljava/lang/String;)I")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,10,"getType","(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,11,"getType","(Ljava/lang/String;)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,12,"getValue","(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,13,"getValue","(Ljava/lang/String;)Ljava/lang/String;")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,14,"clear","()V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,15,"setAttributes","(Lorg/xml/sax/Attributes;)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,16,"addAttribute","(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,17,"setAttribute","(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,18,"removeAttribute","(I)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,19,"setURI","(ILjava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,20,"setLocalName","(ILjava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,21,"setQName","(ILjava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,22,"setType","(ILjava/lang/String;)V")
J2CPP_DEFINE_METHOD(org::xml::sax::helpers::AttributesImpl,23,"setValue","(ILjava/lang/String;)V")
} //namespace j2cpp
#endif //J2CPP_ORG_XML_SAX_HELPERS_ATTRIBUTESIMPL_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| {
"content_hash": "98686e128d10ce872aaaf88ed0b2f58b",
"timestamp": "",
"source": "github",
"line_count": 401,
"max_line_length": 281,
"avg_line_length": 41.63092269326683,
"alnum_prop": 0.6875524140409728,
"repo_name": "seem-sky/ph-open",
"id": "9fbccbfb43af4d866d844802bfc06ddf493b7042",
"size": "16694",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "proj.android/jni/puzzleHero/platforms/android-8/org/xml/sax/helpers/AttributesImpl.hpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2586181"
},
{
"name": "C++",
"bytes": "151891430"
},
{
"name": "CSS",
"bytes": "45889"
},
{
"name": "Erlang",
"bytes": "25427"
},
{
"name": "Java",
"bytes": "320263"
},
{
"name": "JavaScript",
"bytes": "791651"
},
{
"name": "Lua",
"bytes": "10538"
},
{
"name": "Makefile",
"bytes": "26374"
},
{
"name": "Objective-C",
"bytes": "406244"
},
{
"name": "Objective-C++",
"bytes": "359678"
},
{
"name": "Perl",
"bytes": "6421"
},
{
"name": "Prolog",
"bytes": "7299"
},
{
"name": "Python",
"bytes": "5761"
},
{
"name": "Shell",
"bytes": "11405"
}
],
"symlink_target": ""
} |
package org.pentaho.di.repository.kdr.delegates;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.RepositoryAttributeInterface;
public class KettleDatabaseRepositoryJobAttribute implements RepositoryAttributeInterface {
private KettleDatabaseRepositoryConnectionDelegate connectionDelegate;
private ObjectId jobObjectId;
public KettleDatabaseRepositoryJobAttribute(KettleDatabaseRepositoryConnectionDelegate connectionDelegate, ObjectId jobObjectId) {
this.connectionDelegate = connectionDelegate;
this.jobObjectId = jobObjectId;
}
public boolean getAttributeBoolean(String code) throws KettleException {
return connectionDelegate.getJobAttributeBoolean(jobObjectId, 0, code);
}
public long getAttributeInteger(String code) throws KettleException {
return connectionDelegate.getJobAttributeInteger(jobObjectId, 0, code);
}
public String getAttributeString(String code) throws KettleException {
return connectionDelegate.getJobAttributeString(jobObjectId, 0, code);
}
public void setAttribute(String code, String value) throws KettleException {
connectionDelegate.insertJobAttribute(jobObjectId, 0, code, 0, value);
}
public void setAttribute(String code, boolean value) throws KettleException {
connectionDelegate.insertJobAttribute(jobObjectId, 0, code, 0, value?"Y":"N");
}
public void setAttribute(String code, long value) throws KettleException {
connectionDelegate.insertJobAttribute(jobObjectId, 0, code, value, null);
}
}
| {
"content_hash": "9224c04e728c0f7ff5126d9126a11f45",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 131,
"avg_line_length": 37.023809523809526,
"alnum_prop": 0.82508038585209,
"repo_name": "jjeb/kettle-trunk",
"id": "e16ee701ef199457ba78be3768eac03b9cb5e1e6",
"size": "2457",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "engine/src/org/pentaho/di/repository/kdr/delegates/KettleDatabaseRepositoryJobAttribute.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace igl
{
// Determine "edge flaps": two faces on either side of a unique edge (assumes
// edge-manifold mesh)
//
// Inputs:
// F #F by 3 list of face indices
// E #E by 2 list of edge indices into V.
// EMAP #F*3 list of indices into E, mapping each directed edge to unique
// unique edge in E
// Outputs:
// EF #E by 2 list of edge flaps, EF(e,0)=f means e=(i-->j) is the edge of
// F(f,:) opposite the vth corner, where EI(e,0)=v. Similarly EF(e,1) "
// e=(j->i)
// EI #E by 2 list of edge flap corners (see above).
IGL_INLINE void edge_flaps(
const Eigen::MatrixXi & F,
const Eigen::MatrixXi & E,
const Eigen::VectorXi & EMAP,
Eigen::MatrixXi & EF,
Eigen::MatrixXi & EI);
// Only faces as input
IGL_INLINE void edge_flaps(
const Eigen::MatrixXi & F,
Eigen::MatrixXi & E,
Eigen::VectorXi & EMAP,
Eigen::MatrixXi & EF,
Eigen::MatrixXi & EI);
}
#ifndef IGL_STATIC_LIBRARY
# include "edge_flaps.cpp"
#endif
#endif
| {
"content_hash": "ed936a38fb968b49f4a96e63814f877f",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 79,
"avg_line_length": 30,
"alnum_prop": 0.6127450980392157,
"repo_name": "ygling2008/direct_edge_imu",
"id": "199ca62eb4e75f38a58cd53c3e6703e3d56daff8",
"size": "1462",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "thirdparty/igl/edge_flaps.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2711"
},
{
"name": "C++",
"bytes": "470437"
},
{
"name": "CMake",
"bytes": "7389"
},
{
"name": "Python",
"bytes": "4947"
}
],
"symlink_target": ""
} |
<?php
/**
* Description of OrganisationInfoPageBuilder
*
* @author ben.dokter
*/
require_once('modules/interface/builder/organisation/OrganisationInfoInterfaceBuilder.class.php');
class OrganisationInfoPageBuilder
{
static function getPageHtml($displayWidth)
{
return OrganisationInfoInterfaceBuilder::getViewHtml($displayWidth);
}
static function getEditPopupHtml($displayWidth, $contentHeight, $showWarning)
{
list($safeFormHandler, $contentHtml) = OrganisationInfoInterfaceBuilder::getEditHtml($displayWidth);
// popup
$title = TXT_UCF('EDIT') . ' ' . TXT_LC('COMPANY_INFORMATION');
$formId = 'edit_organisation_info';
return ApplicationInterfaceBuilder::getEditPopupHtml( $formId,
$safeFormHandler,
$title,
$contentHtml,
$displayWidth,
$contentHeight,
$showWarning);
}
}
?>
| {
"content_hash": "7dc4dfaf63ff86495113be3d09b48aad",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 108,
"avg_line_length": 33.729729729729726,
"alnum_prop": 0.4935897435897436,
"repo_name": "joris520/broodjesalami",
"id": "b119df9649a37b1ad8837da75f1cebe2b1fd8a71",
"size": "1248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "php_cm/modules/interface/builder/organisation/OrganisationInfoPageBuilder.class.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7642"
},
{
"name": "C",
"bytes": "139881"
},
{
"name": "C++",
"bytes": "37560"
},
{
"name": "CSS",
"bytes": "97009"
},
{
"name": "Groff",
"bytes": "560"
},
{
"name": "HTML",
"bytes": "3252168"
},
{
"name": "Java",
"bytes": "26557"
},
{
"name": "JavaScript",
"bytes": "171666"
},
{
"name": "PHP",
"bytes": "6250140"
},
{
"name": "Perl",
"bytes": "3810713"
},
{
"name": "Perl6",
"bytes": "12908"
},
{
"name": "Prolog",
"bytes": "36099"
},
{
"name": "Shell",
"bytes": "251398"
},
{
"name": "Smarty",
"bytes": "527143"
},
{
"name": "Tcl",
"bytes": "2138370"
},
{
"name": "VimL",
"bytes": "590417"
},
{
"name": "Visual Basic",
"bytes": "416"
},
{
"name": "XSLT",
"bytes": "50637"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Responsive Layouts Assignment</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<!-- Place favicon.ico in the root directory -->
<link rel="stylesheet" href="css/normalize.css" property="stylesheet">
<link rel="stylesheet" href="css/main.css" property="stylesheet">
<link rel="stylesheet" href="css/styles.css" property="stylesheet">
<link rel="stylesheet" href="css/onepcssgrid.css" property="stylesheet">
<script src="js/vendor/modernizr-2.8.3.min.js"></script>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<div class="onepcssgrid-1000">
<div class="onerow" id="header">
<h1>Header</h1>
<h2>Subtitle</h2>
</div>
<div class="onerow" id="menu">
<ul>
<li><a href="">Home</a></li>
<li><a href="">About Us</a></li>
<li><a href="">Contact Us</a></li>
<li><a href="">Video</a></li>
<li><a href="">Pricing</a></li>
<li><a href="">Something</a></li>
<li><a href="">Something more...</a></li>
<li><a href="">Something even more ...</a></li>
</ul>
</div>
<div class="onerow" id="content">
<div class="col3">
<h1>Coffee Ipsum</h1>
<p>Qui at grinder, galão latte saucer kopi-luwak
aroma froth. Galão organic turkish java that
kopi-luwak americano redeye grounds. Con panna
turkish, body, viennese, mocha macchiato plunger
pot americano sugar. Id single shot mocha, et
affogato turkish roast cream brewed.
</p>
</div>
<div class="col3">
<h1>Lorem Ipsum</h1>
<p>Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Nam pharetra vitae ipsum a
convallis. Sed quis sapien sed lacus fringilla
commodo. Vivamus viverra egestas dolor, id ornare
sapien laoreet vel. Donec nisl lacus, accumsan
vitae iaculis ut, feugiat vel risus. Aenean
molestie nec lorem quis rhoncus. Vivamus sit amet
elementum nibh, a tristique dui. Proin blandit
dolor nec lacus lobortis, non imperdiet risus
porta. Maecenas adipiscing gravida congue. In non
viverra erat. Nam porta elit quis risus tempor
pharetra. Cras tempus augue ut dolor suscipit
cursus.
</p>
</div>
<div class="col3">
<h1>Baby Ipsum</h1>
<p>Ya yaya beddy-bye gaa ya ya. Doo gaga yaya
gaagaa doodoo. Da gaagaa num nums yaya laa yaya
doo laa laalaa passie ya goo ya. Doo gaga laa
laalaa laa doo. Gaagaa dada ga pee-pee yaya gaga
gaagaa doo doodoo goo dada gaagaa goo doo. Laa gaa
laa laalaa doodoo doo ya doodoo da. Goo dada goo
gaagaa da lickle laa goo ya da gaa botty da
laa. Da ga cootchie-coo gaagaa ya doodoo gaga
gaagaa goo gaagaa laa gaga brekkie gaa. Owie yaya
dada yucky doo goo ga doo laalaa doodoo da laalaa
ga. Uppie gaga ga laalaa ga gaa yaya gaagaa dada
gaagaa. Whoopsie yaya doo ickle gaga gaga dada
yaya goo laa moo-moo laalaa doo laalaa. Da ga dada
doodoo goo doodoo ga da botty da gaagaa. Goo
googoo da goo bye-bye puffer gaa dada d.
</p>
</div>
<div class="col3">
<h1>Zombie Ipsum</h1>
<p>Zombie ipsum reversus ab viral inferno, nam
rick grimes malum cerebro. De carne lumbering
animata corpora quaeritis. Summus brains sit,
morbo vel maleficia? De apocalypsi gorger omero
undead survivor dictum mauris. Hi mindless mortuis
soulless creaturas, imo evil stalking monstra
adventus resi dentevil vultus comedat cerebella
viventium. Qui animated corpse, cricket bat max
brucks terribilem incessu zomby. The voodoo
sacerdos flesh eater, suscitat mortuos comedere
carnem virus. Zonbi tattered for solum oculi eorum
defunctis go lum cerebro. Nescio brains an Undead
zombies. Sicut malus putrid voodoo horror. Nigh
tofth eliv ingdead.
</p>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='https://www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','UA-XXXXX-X','auto');ga('send','pageview');
</script>
</body>
</html>
| {
"content_hash": "15e526f4dcdf3f2a9878d3db5e991d32",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 187,
"avg_line_length": 51.29133858267716,
"alnum_prop": 0.5182683451028554,
"repo_name": "timoweave/media_query",
"id": "d169e3bf8bfb3c9aeef77949e9160ea802248c8f",
"size": "6520",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "39693"
},
{
"name": "CSS",
"bytes": "9197"
},
{
"name": "HTML",
"bytes": "7792"
},
{
"name": "JavaScript",
"bytes": "760"
}
],
"symlink_target": ""
} |
/**
* Used by the Map (modules/s3gis.py)
* This script is in Static to allow caching
* Dynamic constants (e.g. Internationalised strings) are set in server-generated script
*/
/* Global vars */
var map;
// @ToDo: move this to S3.gis when restoring this
//var printProvider;
// Images
S3.gis.ajax_loader = S3.Ap.concat('/static/img/ajax-loader.gif');
S3.gis.marker_url = S3.Ap.concat('/static/img/markers/');
OpenLayers.ImgPath = S3.Ap.concat('/static/img/gis/openlayers/');
// avoid pink tiles
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
OpenLayers.Util.onImageLoadErrorColor = 'transparent';
OpenLayers.ProxyHost = S3.Ap.concat('/gis/proxy?url=');
// See http://crschmidt.net/~crschmidt/spherical_mercator.html#reprojecting-points
S3.gis.proj4326 = new OpenLayers.Projection('EPSG:4326');
S3.gis.projection_current = new OpenLayers.Projection('EPSG:' + S3.gis.projection);
S3.gis.options = {
displayProjection: S3.gis.proj4326,
projection: S3.gis.projection_current,
// Use Manual stylesheet download (means can be done in HEAD to not delay pageload)
theme: null,
paddingForPopups: new OpenLayers.Bounds(50, 10, 200, 300),
units: S3.gis.units,
maxResolution: S3.gis.maxResolution,
maxExtent: S3.gis.maxExtent,
numZoomLevels: S3.gis.numZoomLevels
};
// Default values if not set by the layer
// http://dev.openlayers.org/docs/files/OpenLayers/Strategy/Cluster-js.html
S3.gis.cluster_distance = 2; // pixels
S3.gis.cluster_threshold = 2; // minimum # of features to form a cluster
/* Configure the Viewport */
function s3_gis_setCenter(bottom_left, top_right) {
bottom_left.transform(S3.gis.proj4326, S3.gis.projection_current);
var left = bottom_left.lon;
var bottom = bottom_left.lat;
top_right.transform(S3.gis.proj4326, S3.gis.projection_current);
var right = top_right.lon;
var top = top_right.lat;
S3.gis.bounds = OpenLayers.Bounds.fromArray([left, bottom, right, top]);
S3.gis.center = S3.gis.bounds.getCenterLonLat();
}
if (S3.gis.lat && S3.gis.lon) {
S3.gis.center = new OpenLayers.LonLat(S3.gis.lon, S3.gis.lat);
S3.gis.center.transform(S3.gis.proj4326, S3.gis.projection_current);
} else if (S3.gis.bottom_left && S3.gis.top_right) {
s3_gis_setCenter(S3.gis.bottom_left, S3.gis.top_right);
}
// Register Plugins
S3.gis.plugins = [];
function registerPlugin(plugin) {
S3.gis.plugins.push(plugin);
}
// Main Ext function
Ext.onReady(function() {
// Build the OpenLayers map
addMap();
// Set some common options
if ( undefined == S3.gis.west_collapsed ) {
S3.gis.west_collapsed = false;
}
// Which Elements do we want in our mapWindow?
// @ToDo: Move all these to Plugins
items = [S3.gis.layerTree];
if (S3.gis.wmsBrowser) {
items.push(S3.gis.wmsBrowser);
}
if (S3.gis.searchCombo) {
items.push(S3.gis.searchCombo);
}
if (S3.gis.printFormPanel) {
items.push(S3.gis.printFormPanel);
}
if (S3.gis.legendPanel) {
items.push(S3.gis.legendPanel);
}
for ( var i = 0; i < S3.gis.plugins.length; ++i ) {
S3.gis.plugins[i].addToMapWindow(items);
}
// Instantiate the main Map window
if (S3.gis.window) {
addMapWindow(items);
} else {
// Embedded Map
addMapPanel(items);
}
// If we were instantiated with bounds, use these now
if ( S3.gis.bounds ) {
map.zoomToExtent(S3.gis.bounds);
}
// Toolbar Tooltips
Ext.QuickTips.init();
});
// Add Map
function addMap() {
map = new OpenLayers.Map('center', S3.gis.options);
// Layers
// defined in s3.gis.layers.js
addLayers();
// Controls (add these after the layers)
// defined in s3.gis.controls.js
addControls();
// GeoExt UI
S3.gis.mapPanel = new GeoExt.MapPanel({
region: 'center',
height: S3.gis.map_height,
width: S3.gis.map_width,
id: 'mappanel',
xtype: 'gx_mappanel',
map: map,
center: S3.gis.center,
zoom: S3.gis.zoom,
plugins: []
});
// We need to put the mapPanel inside a 'card' container for the Google Earth Panel
S3.gis.mapPanelContainer = new Ext.Panel({
layout: 'card',
region: 'center',
id: 'mappnlcntr',
defaults: {
// applied to each contained panel
border: false
},
items: [
S3.gis.mapPanel
],
activeItem: 0,
tbar: new Ext.Toolbar(),
scope: this
});
if (S3.gis.Google && S3.gis.Google.Earth) {
// Add now rather than when button pressed as otherwise 1st press doesn't do anything
S3.gis.googleEarthPanel = new gxp.GoogleEarthPanel({
mapPanel: S3.gis.mapPanel
});
S3.gis.mapPanelContainer.items.items.push(S3.gis.googleEarthPanel);
}
// Layer Tree
addLayerTree();
// Toolbar
if (S3.gis.toolbar) {
addToolbar();
}
// WMS Browser
if (S3.gis.wms_browser_url) {
addWMSBrowser();
}
// Legend Panel
if (S3.i18n.gis_legend) {
S3.gis.legendPanel = new GeoExt.LegendPanel({
id: 'legendpanel',
title: S3.i18n.gis_legend,
defaults: {
labelCls: 'mylabel',
style: 'padding:5px'
},
bodyStyle: 'padding:5px',
autoScroll: true,
collapsible: true,
collapseMode: 'mini',
lines: false
});
}
// Search box
if (S3.i18n.gis_search) {
var mapSearch = new GeoExt.ux.GeoNamesSearchCombo({
map: map,
zoom: 12
});
S3.gis.searchCombo = new Ext.Panel({
id: 'searchCombo',
title: S3.i18n.gis_search,
layout: 'border',
rootVisible: false,
split: true,
autoScroll: true,
collapsible: true,
collapseMode: 'mini',
lines: false,
html: S3.i18n.gis_search_no_internet,
items: [{
region: 'center',
items: [ mapSearch ]
}]
});
}
for ( var i = 0; i < S3.gis.plugins.length; ++i ) {
S3.gis.plugins[i].setup(map);
}
}
// Create an embedded Map Panel
function addMapPanel(items) {
S3.gis.mapWin = new Ext.Panel({
id: 'gis-map-panel',
renderTo: 'map_panel',
autoScroll: true,
maximizable: true,
titleCollapse: true,
height: S3.gis.map_height,
width: S3.gis.map_width,
layout: 'border',
items: [{
region: 'west',
id: 'tools',
//title: 'Tools',
header: false,
border: true,
width: 250,
autoScroll: true,
collapsible: true,
collapseMode: 'mini',
collapsed: S3.gis.west_collapsed,
split: true,
items: items
},
S3.gis.mapPanelContainer
]
});
}
// Create a floating Map Window
function addMapWindow(items) {
S3.gis.mapWin = new Ext.Window({
id: 'gis-map-window',
collapsible: true,
constrain: true,
closeAction: 'hide',
autoScroll: true,
maximizable: true,
titleCollapse: true,
height: S3.gis.map_height,
width: S3.gis.map_width,
layout: 'border',
items: [{
region: 'west',
id: 'tools',
//title: 'Tools',
header: false,
border: true,
width: 250,
autoScroll: true,
collapsible: true,
collapseMode: 'mini',
collapsed: S3.gis.west_collapsed,
split: true,
items: items
},
S3.gis.mapPanelContainer
]
});
// Shortcut
var mapWin = S3.gis.mapWin;
// Set Options
if (!S3.gis.windowHide) {
if (S3.gis.windowNotClosable) {
mapWin.closable = false;
}
// If the window is meant to be displayed immediately then display it now that it is ready
mapWin.show();
mapWin.maximize();
}
}
// Add LayerTree (to be called after the layers are added)
function addLayerTree() {
var layerTreeBase = {
text: S3.i18n.gis_base_layers,
nodeType: 'gx_baselayercontainer',
layerStore: S3.gis.mapPanel.layers,
leaf: false,
expanded: true
};
//var layerTreeFeaturesExternal = {
// text: 'External Features',
// nodeType: 'gx_overlaylayercontainer',
// layerStore: S3.gis.mapPanel.layers,
// leaf: false,
// expanded: true
//};
var layerTreeFeaturesInternal = {
//text: 'Internal Features',
text: S3.i18n.gis_overlays,
nodeType: 'gx_overlaylayercontainer',
layerStore: S3.gis.mapPanel.layers,
leaf: false,
expanded: true
};
var treeRoot = new Ext.tree.AsyncTreeNode({
expanded: true,
children: [
layerTreeBase,
layerTreeFeaturesInternal
]
});
//treeRoot.appendChild(layerTreeFeaturesExternal);
S3.gis.layerTree = new Ext.tree.TreePanel({
id: 'treepanel',
title: S3.i18n.gis_layers,
loader: new Ext.tree.TreeLoader({applyLoader: false}),
root: treeRoot,
rootVisible: false,
split: true,
autoScroll: true,
collapsible: true,
collapseMode: 'mini',
lines: false,
enableDD: true
});
}
// Add WMS Browser
function addWMSBrowser() {
var root = new Ext.tree.AsyncTreeNode({
expanded: true,
loader: new GeoExt.tree.WMSCapabilitiesLoader({
url: OpenLayers.ProxyHost + S3.gis.wms_browser_url,
layerOptions: {buffer: 1, singleTile: false, ratio: 1, wrapDateLine: true},
layerParams: {'TRANSPARENT': 'TRUE'},
// customize the createNode method to add a checkbox to nodes
createNode: function(attr) {
attr.checked = attr.leaf ? false : undefined;
return GeoExt.tree.WMSCapabilitiesLoader.prototype.createNode.apply(this, [attr]);
}
})
});
S3.gis.wmsBrowser = new Ext.tree.TreePanel({
id: 'wmsbrowser',
title: S3.gis.wms_browser_name,
root: root,
rootVisible: false,
split: true,
autoScroll: true,
collapsible: true,
collapseMode: 'mini',
lines: false,
listeners: {
// Add layers to the map when checked, remove when unchecked.
// Note that this does not take care of maintaining the layer
// order on the map.
'checkchange': function(node, checked) {
if (checked === true) {
S3.gis.mapPanel.map.addLayer(node.attributes.layer);
} else {
S3.gis.mapPanel.map.removeLayer(node.attributes.layer);
}
}
}
});
}
// Toolbar Buttons
// The buttons called from here are defined in s3.gis.controls.js
function addToolbar() {
var toolbar = S3.gis.mapPanelContainer.getTopToolbar();
var zoomfull = new GeoExt.Action({
control: new OpenLayers.Control.ZoomToMaxExtent(),
map: map,
iconCls: 'zoomfull',
// button options
tooltip: S3.i18n.gis_zoomfull
});
var zoomout = new GeoExt.Action({
control: new OpenLayers.Control.ZoomBox({ out: true }),
map: map,
iconCls: 'zoomout',
// button options
tooltip: S3.i18n.gis_zoomout,
toggleGroup: 'controls'
});
var zoomin = new GeoExt.Action({
control: new OpenLayers.Control.ZoomBox(),
map: map,
iconCls: 'zoomin',
// button options
tooltip: S3.i18n.gis_zoomin,
toggleGroup: 'controls'
});
if (S3.gis.draw_feature == "active") {
var pan_pressed = false;
var point_pressed = true;
var polygon_pressed = false;
} else if (S3.gis.draw_polygon == "active") {
var pan_pressed = false;
var point_pressed = false;
var polygon_pressed = true;
} else {
var pan_pressed = true;
var point_pressed = false;
var polygon_pressed = false;
}
S3.gis.panButton = new GeoExt.Action({
control: new OpenLayers.Control.Navigation(),
map: map,
iconCls: 'pan-off',
// button options
tooltip: S3.i18n.gis_pan,
toggleGroup: 'controls',
allowDepress: true,
pressed: pan_pressed
});
// Controls for Draft Features (unused)
//var selectControl = new OpenLayers.Control.SelectFeature(S3.gis.draftLayer, {
// onSelect: onFeatureSelect,
// onUnselect: onFeatureUnselect,
// multiple: false,
// clickout: true,
// isDefault: true
//});
//var removeControl = new OpenLayers.Control.RemoveFeature(S3.gis.draftLayer, {
// onDone: function(feature) {
// console.log(feature)
// }
//});
//var selectButton = new GeoExt.Action({
//control: selectControl,
// map: map,
// iconCls: 'searchclick',
// button options
// tooltip: 'T("Query Feature")',
// toggleGroup: 'controls',
// enableToggle: true
//});
//var lineButton = new GeoExt.Action({
// control: new OpenLayers.Control.DrawFeature(S3.gis.draftLayer, OpenLayers.Handler.Path),
// map: map,
// iconCls: 'drawline-off',
// tooltip: 'T("Add Line")',
// toggleGroup: 'controls'
//});
//var dragButton = new GeoExt.Action({
// control: new OpenLayers.Control.DragFeature(S3.gis.draftLayer),
// map: map,
// iconCls: 'movefeature',
// tooltip: 'T("Move Feature: Drag feature to desired location")',
// toggleGroup: 'controls'
//});
//var resizeButton = new GeoExt.Action({
// control: new OpenLayers.Control.ModifyFeature(S3.gis.draftLayer, { mode: OpenLayers.Control.ModifyFeature.RESIZE }),
// map: map,
// iconCls: 'resizefeature',
// tooltip: 'T("Resize Feature: Select the feature you wish to resize & then Drag the associated dot to your desired size")',
// toggleGroup: 'controls'
//});
//var rotateButton = new GeoExt.Action({
// control: new OpenLayers.Control.ModifyFeature(S3.gis.draftLayer, { mode: OpenLayers.Control.ModifyFeature.ROTATE }),
// map: map,
// iconCls: 'rotatefeature',
// tooltip: 'T("Rotate Feature: Select the feature you wish to rotate & then Drag the associated dot to rotate to your desired location")',
// toggleGroup: 'controls'
//});
//var modifyButton = new GeoExt.Action({
// control: new OpenLayers.Control.ModifyFeature(S3.gis.draftLayer),
// map: map,
// iconCls: 'modifyfeature',
// tooltip: 'T("Modify Feature: Select the feature you wish to deform & then Drag one of the dots to deform the feature in your chosen manner")',
// toggleGroup: 'controls'
//});
//var removeButton = new GeoExt.Action({
// control: removeControl,
// map: map,
// iconCls: 'removefeature',
// tooltip: 'T("Remove Feature: Select the feature you wish to remove & press the delete key")',
// toggleGroup: 'controls'
//});
/* Add controls to Map & buttons to Toolbar */
toolbar.add(zoomfull);
if (navigator.geolocation) {
// HTML5 geolocation is available :)
addGeolocateControl(toolbar)
}
toolbar.add(zoomout);
toolbar.add(zoomin);
toolbar.add(S3.gis.panButton);
toolbar.addSeparator();
// Navigation
// @ToDo: Make these optional
addNavigationControl(toolbar);
// Save Viewport
// @ToDo: Don't Show for Regional Configs either
if (S3.gis.mapAdmin || S3.gis.region != 1) {
addSaveButton(toolbar);
}
toolbar.addSeparator();
// Measure Tools
// @ToDo: Make these optional
addMeasureControls(toolbar);
// MGRS Grid PDFs
if (S3.gis.mgrs_url) {
addPdfControl(toolbar);
}
if (S3.gis.draw_feature || S3.gis.draw_polygon) {
// Draw Controls
toolbar.addSeparator();
//toolbar.add(selectButton);
if (S3.gis.draw_feature) {
addPointControl(toolbar, point_pressed);
}
//toolbar.add(lineButton);
if (S3.gis.draw_polygon) {
addPolygonControl(toolbar, polygon_pressed);
}
//toolbar.add(dragButton);
//toolbar.add(resizeButton);
//toolbar.add(rotateButton);
//toolbar.add(modifyButton);
//toolbar.add(removeButton);
}
// OpenStreetMap Editor
if (S3.gis.osm_oauth) {
addPotlatchButton(toolbar);
}
// Google Streetview
if (S3.gis.Google && S3.gis.Google.StreetviewButton) {
addGoogleStreetviewControl(toolbar);
}
// Google Earth
if (S3.gis.Google && S3.gis.Google.Earth) {
addGoogleEarthControl(toolbar);
}
}
| {
"content_hash": "e7f2349498f302ae04a08cef2c909f00",
"timestamp": "",
"source": "github",
"line_count": 588,
"max_line_length": 152,
"avg_line_length": 29.860544217687075,
"alnum_prop": 0.5696548581843035,
"repo_name": "flavour/helios",
"id": "0ed50d4d118e07f3395fc6f68913622fd6175014",
"size": "17558",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "static/scripts/S3/s3.gis.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "13065177"
},
{
"name": "PHP",
"bytes": "15220"
},
{
"name": "Python",
"bytes": "21048713"
},
{
"name": "Shell",
"bytes": "1645"
}
],
"symlink_target": ""
} |
<?php
Route::group(['middleware' => 'auth'], function () {
//Profil pages
Route::group(['prefix' => 'profile'], function () {
Route::get('/', 'Frontend\ProfileController@index')->name('user.profile');
Route::get('/edit', 'Frontend\ProfileController@edit')->name('user.profile.edit');
Route::post('/update', 'Frontend\ProfileController@update')->name('user.profile.update');
Route::get('/password/edit', 'Frontend\ProfileController@editPassword')->name('user.profile.edit.password');
Route::post('/password/update', 'Frontend\ProfileController@updatePassword')->name('user.profile.update.password');
});
//Items pages
Route::group(['prefix' => 'items'], function () {
Route::get('/', 'Frontend\ItemsController@index')->name('user.items');
Route::get('/create', 'Frontend\ItemsController@create')->name('user.items.create');
Route::post('/store', 'Frontend\ItemsController@store')->name('user.items.store');
Route::get('/destroy/{id}', 'Frontend\ItemsController@destroy')->name('user.items.destroy');
Route::get('/edit/{id}', 'Frontend\ItemsController@edit')->name('user.items.edit');
Route::post('/update/{id}', 'Frontend\ItemsController@update')->name('user.items.update');
});
}); | {
"content_hash": "5c2123eb70bb97085610c3a9f84cd3df",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 123,
"avg_line_length": 43.166666666666664,
"alnum_prop": 0.6424710424710425,
"repo_name": "IvanSostarko/laravel-5-2-cook-book",
"id": "b47382d030262978d3cbbdfbe07a4464e5514b61",
"size": "1295",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Http/Routes/user.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1108"
},
{
"name": "HTML",
"bytes": "183201"
},
{
"name": "JavaScript",
"bytes": "971895"
},
{
"name": "PHP",
"bytes": "226775"
}
],
"symlink_target": ""
} |
(function() {
/* @ngdoc object
* @name app.account
* @description
* Module for the user accounts
*/
angular
.module('app.account', ['app.core', 'app.components'])
.config(configure);
configure.$inject = ['$stateProvider'];
function configure($stateProvider) {
$stateProvider
.state('account', {
url: '/account',
abstract: true,
template: '<ui-view />'
})
.state('account.login', {
url: '/login',
views: {
'main@': {
templateUrl: 'app/account/login/login.html',
controller: 'LoginCtrl',
controllerAs: 'login'
}
}
})
.state('account.signup', {
url: '/signup',
views: {
'main@': {
templateUrl: 'app/account/signup/signup.html',
controller: 'SignupCtrl',
controllerAs: 'signup'
}
}
})
.state('account.logout', {
url: '/logout?referrer',
referrer: 'main',
template: '', /* @ngInject */
controller: function($state, Auth) {
var referrer = $state.params.referrer ||
$state.current.referrer ||
'guild.home';
Auth.logout();
$state.go(referrer);
}
})
.state('account.profile', {
url: '/profile',
views: {
'main@': {
templateUrl: 'app/account/profile/profile.html',
controller: 'ProfileCtrl',
controllerAs: 'profile',
resolve: {
authenticated: function($q, $location, Auth) {
var deferred = $q.defer();
if (!Auth.isLoggedIn) {
$location.path('/account/login');
}
else {
deferred.resolve();
}
return deferred.promise;
}
}
}
}
})
.state('account.user', {
url: '/:id',
views: {
'main@': {
templateUrl: 'app/account/account.html',
controller: 'AccountCtrl',
controllerAs: 'acc',
resolve:
{ /* @ngInject */
person: function($stateParams, userSvc)
{
return userSvc.get($stateParams.id);
}
}
}
}
})
.state('account.password', {
abstract: true,
url: '/password',
template: '<ui-view/>'
})
.state('account.password.forgot', {
url: '/forgot',
templateUrl: 'app/account/password/forgot/forgot.html',
controller: 'ForgotCtrl as forgot'
})
.state('account.password.reset', {
abstract: true,
url: '/reset',
template: '<ui-view/>'
})
.state('account.password.reset.invalid', {
url: '/invalid',
templateUrl: 'app/account/password/reset/invalid.html'
})
.state('account.password.reset.form', {
url: '/:token',
templateUrl: 'app/account/password/reset/form.html',
controller: 'ResetCtrl as reset'
});
}
}());
| {
"content_hash": "a611ad9bf0fc2b9099791a23302912b3",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 63,
"avg_line_length": 27.016806722689076,
"alnum_prop": 0.4603421461897356,
"repo_name": "strues/TopShelf",
"id": "701a57a79db6bcfd12e9a5de9adf64ade48b3847",
"size": "3215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/client/app/account/account.module.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "176022"
},
{
"name": "HTML",
"bytes": "75382"
},
{
"name": "JavaScript",
"bytes": "216837"
}
],
"symlink_target": ""
} |
var win = Ti.UI.currentWindow;
win.addEventListener('focus', function(e){
Titanium.App.Analytics.trackPageview('/more/larryville-about');
});
var tv = Ti.UI.createTableView({minRowHeight:50,rowBackgroundColor:'white',backgroundColor:'white',});
var text1 = 'LarryvilleKU is a hyper-local news service originally inspired by the Open Block platform. It is now available to students as an exclusive deal-finder.';
var text2 = 'Map icons created by Nicolas Mollet\'s project';
var data = [];
var row = Ti.UI.createTableViewRow({height:'auto',className:"row"});
var textView = Ti.UI.createView({
height:'auto',
layout:'vertical',
left:20,
top:20,
bottom:60,
right:20
});
var l1 = Ti.UI.createLabel({
text:text1,
height:'auto',
color:'black'
});
textView.add(l1);
var l2 = Ti.UI.createLabel({
text:text2,
top:10,
color:'black',
height:'auto'
});
textView.add(l2);
row.add(textView);
data.push(row);
tv.setData(data);
win.add(tv); | {
"content_hash": "b0a2d6d696f3668bb1fc148c8d841731",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 166,
"avg_line_length": 21.755555555555556,
"alnum_prop": 0.6894790602655771,
"repo_name": "UniversityDailyKansan/app",
"id": "1e4a14112d4eed6a55d7e603b7b083f3a7447b03",
"size": "979",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Resources/more/about_larryville.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "258569"
},
{
"name": "Shell",
"bytes": "341"
}
],
"symlink_target": ""
} |
namespace YC.Ftp.Enums
{
internal enum FtpMethod
{
DeleteFile,
DownloadFile,
UploadFile,
AppendFile,
MakeDirectory,
GetFileSize,
RemoveDirectory,
Rename,
ListDirectoryDetails,
ListDirectory,
GetDateTimestamp
}
}
| {
"content_hash": "576533c150ea70b5b8f8bfbfb6f38679",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 29,
"avg_line_length": 18.352941176470587,
"alnum_prop": 0.5641025641025641,
"repo_name": "ychsu/YC.FTP",
"id": "4a1a2dd3c1c22016a402c64584cb449433e72c6e",
"size": "312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/YC.FTP/Enums/FtpMethod.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "31572"
},
{
"name": "Smalltalk",
"bytes": "2160"
}
],
"symlink_target": ""
} |
/*****************************************************************************/
/**
* @file xrtcpsu.h
* @addtogroup rtcpsu_v1_5
* @{
* @details
*
* The Xilinx RTC driver component. This component supports the Xilinx
* RTC Controller. RTC Core and RTC controller are the two main important sub-
* components for this RTC module. RTC core can run even in the battery powered
* domain when the power from auxiliary source is down. Because of this, RTC core
* latches the calibration,programmed time. This core interfaces with the crystal
* oscillator and maintains current time in seconds.Calibration circuitry
* calculates a second with maximum 1 PPM inaccuracy using a crystal oscillator
* with arbitrary static inaccuracy. Core also responsible to maintain control
* value used by the oscillator and power switching circuitry.
*
* RTC controller includes an APB interface responsible for register access with
* in controller and core. It contains alarm generation logic including the alarm
* register to hold alarm time in seconds.Interrupt management using Interrupt
* status, Interrupt mask, Interrupt enable, Interrupt disable registers are
* included to manage alarm and seconds interrupts. Address Slave error interrupts
* are not being handled by this driver component.
*
* This driver supports the following features:
* - Setting the RTC time.
* - Setting the Alarm value that can be one-time alarm or a periodic alarm.
* - Modifying the calibration value.
*
* <b>Initialization & Configuration</b>
*
* The XRtcPsu_Config structure is used by the driver to configure itself.
* Fields inside this structure are properties of XRtcPsu based on its hardware
* build.
*
* To support multiple runtime loading and initialization strategies employed
* by various operating systems, the driver instance can be initialized in the
* following way:
*
* - XRtcPsu_CfgInitialize(InstancePtr, CfgPtr, EffectiveAddr) - Uses a
* configuration structure provided by the caller. If running in a system
* with address translation, the parameter EffectiveAddr should be the
* virtual address.
*
* <b>Interrupts</b>
*
* The driver defaults to no interrupts at initialization such that interrupts
* must be enabled if desired. An interrupt is generated for one of the
* following conditions.
*
* - Alarm is generated.
* - A new second is generated.
*
* The application can control which interrupts are enabled using the
* XRtcPsu_SetInterruptMask() function.
*
* In order to use interrupts, it is necessary for the user to connect the
* driver interrupt handler, XRtcPsu_InterruptHandler(), to the interrupt
* system of the application. A separate handler should be provided by the
* application to communicate with the interrupt system, and conduct
* application specific interrupt handling. An application registers its own
* handler through the XRtcPsu_SetHandler() function.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- ----- -------- -----------------------------------------------
* 1.00 kvn 04/21/15 First release
* 1.1 kvn 09/25/15 Modify control register to enable battery
* switching when vcc_psaux is not available.
* 1.3 vak 04/25/16 Corrected the RTC read and write time logic(cr#948833).
* 1.4 MNK 01/27/17 Corrected calibration and frequency macros based on
* rtc input oscillator frequency ( 32.768Khz).
* ms 03/17/17 Added readme.txt file in examples folder for doxygen
* generation.
* ms 04/10/17 Modified filename tag in examples to include them in
* doxygen examples.
* 1.5 ms 08/27/17 Fixed compilation warnings in xrtcpsu.c file.
* ms 08/29/17 Updated the code as per source code style.
* </pre>
*
******************************************************************************/
#ifndef XRTC_H_ /* prevent circular inclusions */
#define XRTC_H_ /* by using protection macros */
#ifdef __cplusplus
extern "C" {
#endif
/***************************** Include Files *********************************/
#include "xstatus.h"
#include "xil_assert.h"
#include "xil_io.h"
#include "xrtcpsu_hw.h"
#include "xil_types.h"
/************************** Constant Definitions *****************************/
/** @name Callback events
*
* These constants specify the handler events that an application can handle
* using its specific handler function. Note that these constants are not bit
* mask, so only one event can be passed to an application at a time.
*
* @{
*/
#define XRTCPSU_EVENT_ALARM_GEN 1U /**< Alarm generated event */
#define XRTCPSU_EVENT_SECS_GEN 2U /**< A new second generated event */
/*@}*/
#define XRTCPSU_CRYSTAL_OSC_EN (u32)1 << XRTC_CTL_OSC_SHIFT
/**< Separate Mask for Crystal oscillator bit Enable */
/**************************** Type Definitions *******************************/
/******************************************************************************/
/**
* This data type defines a handler that an application defines to communicate
* with interrupt system to retrieve state information about an application.
*
* @param CallBackRef is a callback reference passed in by the upper layer
* when setting the handler, and is passed back to the upper layer
* when the handler is called. It is used to find the device driver
* instance.
* @param Event contains one of the event constants indicating events that
* have occurred.
* @param EventData contains the number of bytes sent or received at the
* time of the call for send and receive events and contains the
* modem status for modem events.
*
******************************************************************************/
typedef void (*XRtcPsu_Handler) (void *CallBackRef, u32 Event);
/**
* This typedef contains configuration information for a device.
*/
typedef struct {
u16 DeviceId; /**< Unique ID of device */
u32 BaseAddr; /**< Register base address */
} XRtcPsu_Config;
/**
* The XRtcPsu driver instance data. The user is required to allocate a
* variable of this type for the RTC device in the system. A pointer
* to a variable of this type is then passed to the driver API functions.
*/
typedef struct {
XRtcPsu_Config RtcConfig; /**< Device configuration */
u32 IsReady; /**< Device is initialized and ready */
u32 PeriodicAlarmTime;
u8 IsPeriodicAlarm;
u32 OscillatorFreq;
u32 CalibrationValue;
XRtcPsu_Handler Handler;
void *CallBackRef; /**< Callback reference for event handler */
u32 TimeUpdated;
u32 CurrTimeUpdated;
} XRtcPsu;
/**
* This typedef contains DateTime format structure.
*/
typedef struct {
u32 Year;
u32 Month;
u32 Day;
u32 Hour;
u32 Min;
u32 Sec;
u32 WeekDay;
} XRtcPsu_DT;
/************************* Variable Definitions ******************************/
/***************** Macros (Inline Functions) Definitions *********************/
#define XRTC_CALIBRATION_VALUE 0x8000U
#define XRTC_TYPICAL_OSC_FREQ 32768U
/****************************************************************************/
/**
*
* This macro updates the current time of RTC device.
*
* @param InstancePtr is a pointer to the XRtcPsu instance.
* @param Time is the desired time for RTC in seconds.
*
* @return None.
*
* @note C-Style signature:
* void XRtcPsu_SetTime(XRtcPsu *InstancePtr, u32 Time)
*
*****************************************************************************/
#define XRtcPsu_WriteSetTime(InstancePtr,Time) \
XRtcPsu_WriteReg(((InstancePtr)->RtcConfig.BaseAddr + \
XRTC_SET_TIME_WR_OFFSET),(Time))
/****************************************************************************/
/**
*
* This macro returns the last set time of RTC device. Whenever a reset
* happens, the last set time will be zeroth day first sec.
*
* @param InstancePtr is a pointer to the XRtcPsu instance.
*
* @return The last set time in seconds.
*
* @note C-Style signature:
* u32 XRtcPsu_GetLastSetTime(XRtcPsu *InstancePtr)
*
*****************************************************************************/
#define XRtcPsu_GetLastSetTime(InstancePtr) \
XRtcPsu_ReadReg((InstancePtr)->RtcConfig.BaseAddr + XRTC_SET_TIME_RD_OFFSET)
/****************************************************************************/
/**
*
* This macro returns the calibration value of RTC device.
*
* @param InstancePtr is a pointer to the XRtcPsu instance.
*
* @return Calibration value for RTC.
*
* @note C-Style signature:
* u32 XRtcPsu_GetCalibration(XRtcPsu *InstancePtr)
*
*****************************************************************************/
#define XRtcPsu_GetCalibration(InstancePtr) \
XRtcPsu_ReadReg((InstancePtr)->RtcConfig.BaseAddr+XRTC_CALIB_RD_OFFSET)
/****************************************************************************/
/**
*
* This macro returns the current time of RTC device.
*
* @param InstancePtr is a pointer to the XRtcPsu instance.
*
* @return Current Time. This current time will be in seconds.
*
* @note C-Style signature:
* u32 XRtcPsu_ReadCurrentTime(XRtcPsu *InstancePtr)
*
*****************************************************************************/
#define XRtcPsu_ReadCurrentTime(InstancePtr) \
XRtcPsu_ReadReg((InstancePtr)->RtcConfig.BaseAddr+XRTC_CUR_TIME_OFFSET)
/****************************************************************************/
/**
*
* This macro sets the control register value of RTC device.
*
* @param InstancePtr is a pointer to the XRtcPsu instance.
* @param Value is the desired control register value for RTC.
*
* @return None.
*
* @note C-Style signature:
* void XRtcPsu_SetControlRegister(XRtcPsu *InstancePtr, u32 Value)
*
*****************************************************************************/
#define XRtcPsu_SetControlRegister(InstancePtr, Value) \
XRtcPsu_WriteReg((InstancePtr)->RtcConfig.BaseAddr + \
XRTC_CTL_OFFSET,(Value))
/****************************************************************************/
/**
*
* This macro returns the safety check register value of RTC device.
*
* @param InstancePtr is a pointer to the XRtcPsu instance.
*
* @return Safety check register value.
*
* @note C-Style signature:
* u32 XRtcPsu_GetSafetyCheck(XRtcPsu *InstancePtr)
*
*****************************************************************************/
#define XRtcPsu_GetSafetyCheck(InstancePtr) \
XRtcPsu_ReadReg((InstancePtr)->RtcConfig.BaseAddr+XRTC_SFTY_CHK_OFFSET)
/****************************************************************************/
/**
*
* This macro sets the safety check register value of RTC device.
*
* @param InstancePtr is a pointer to the XRtcPsu instance.
* @param Value is a safety check value to be written in register.
*
* @return None.
*
* @note C-Style signature:
* void XRtcPsu_SetSafetyCheck(XRtcPsu *InstancePtr, u32 Value)
*
*****************************************************************************/
#define XRtcPsu_SetSafetyCheck(InstancePtr, Value) \
XRtcPsu_WriteReg((InstancePtr)->RtcConfig.BaseAddr + \
XRTC_SFTY_CHK_OFFSET,(Value))
/****************************************************************************/
/**
*
* This macro resets the alarm register
*
* @param InstancePtr is a pointer to the XRtcPsu instance.
*
* @return None.
*
* @note C-Style signature:
* u32 XRtcPsu_ResetAlarm(XRtcPsu *InstancePtr)
*
*****************************************************************************/
#define XRtcPsu_ResetAlarm(InstancePtr) \
XRtcPsu_WriteReg((InstancePtr)->RtcConfig.BaseAddr + \
XRTC_ALRM_OFFSET,XRTC_ALRM_RSTVAL)
/****************************************************************************/
/**
*
* This macro rounds off the given number
*
* @param Number is the one that needs to be rounded off..
*
* @return The rounded off value of the input number.
*
* @note C-Style signature:
* u32 XRtcPsu_RoundOff(float Number)
*
*****************************************************************************/
#define XRtcPsu_RoundOff(Number) \
(u32)(((Number) < (u32)0) ? ((Number) - (u32)0.5) : ((Number) + (u32)0.5))
/************************** Function Prototypes ******************************/
/* Functions in xrtcpsu.c */
s32 XRtcPsu_CfgInitialize(XRtcPsu *InstancePtr, XRtcPsu_Config *ConfigPtr,
u32 EffectiveAddr);
void XRtcPsu_SetAlarm(XRtcPsu *InstancePtr, u32 Alarm, u32 Periodic);
void XRtcPsu_SecToDateTime(u32 Seconds, XRtcPsu_DT *dt);
u32 XRtcPsu_DateTimeToSec(XRtcPsu_DT *dt);
void XRtcPsu_CalculateCalibration(XRtcPsu *InstancePtr,u32 TimeReal,
u32 CrystalOscFreq);
u32 XRtcPsu_IsSecondsEventGenerated(XRtcPsu *InstancePtr);
u32 XRtcPsu_IsAlarmEventGenerated(XRtcPsu *InstancePtr);
u32 XRtcPsu_GetCurrentTime(XRtcPsu *InstancePtr);
void XRtcPsu_SetTime(XRtcPsu *InstancePtr,u32 Time);
/* interrupt functions in xrtcpsu_intr.c */
void XRtcPsu_SetInterruptMask(XRtcPsu *InstancePtr, u32 Mask);
void XRtcPsu_ClearInterruptMask(XRtcPsu *InstancePtr, u32 Mask);
void XRtcPsu_InterruptHandler(XRtcPsu *InstancePtr);
void XRtcPsu_SetHandler(XRtcPsu *InstancePtr, XRtcPsu_Handler FuncPtr,
void *CallBackRef);
/* Functions in xrtcpsu_selftest.c */
s32 XRtcPsu_SelfTest(XRtcPsu *InstancePtr);
/* Functions in xrtcpsu_sinit.c */
XRtcPsu_Config *XRtcPsu_LookupConfig(u16 DeviceId);
#endif /* XRTC_H_ */
/** @} */
| {
"content_hash": "d58f65667cd999fdfd1159e40e3b0c21",
"timestamp": "",
"source": "github",
"line_count": 370,
"max_line_length": 81,
"avg_line_length": 35.7027027027027,
"alnum_prop": 0.6209689629068887,
"repo_name": "openthread/ot-rtos",
"id": "8320470303b1ca7193f1b783b8c86b7480064fcd",
"size": "14857",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "third_party/freertos/repo/FreeRTOS/Demo/CORTEX_A53_64-bit_UltraScale_MPSoC/RTOSDemo_A53_bsp/psu_cortexa53_0/libsrc/rtcpsu_v1_5/src/xrtcpsu.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "45552"
},
{
"name": "C++",
"bytes": "14485"
},
{
"name": "CMake",
"bytes": "6361"
},
{
"name": "Shell",
"bytes": "17804"
}
],
"symlink_target": ""
} |
package org.apache.flink.table.planner.plan.stream.sql
import org.apache.flink.table.api.ValidationException
import org.apache.flink.table.planner.utils.{StreamTableTestUtil, TableTestBase}
import org.junit.{Before, Test}
class MatchRecognizeTest extends TableTestBase {
protected val util: StreamTableTestUtil = streamTestUtil()
@Before
def before(): Unit = {
val ddl =
"""
|CREATE TABLE Ticker (
| `symbol` STRING,
| `ts_ltz` TIMESTAMP_LTZ(3),
| `price` INT,
| `tax` INT,
| WATERMARK FOR `ts_ltz` AS `ts_ltz` - INTERVAL '1' SECOND
|) WITH (
| 'connector' = 'values'
|)
|""".stripMargin
util.tableEnv.executeSql(ddl)
}
@Test
def testMatchRecognizeOnRowtime(): Unit = {
val ddl =
"""
|CREATE TABLE Ticker1 (
| `symbol` STRING,
| `ts` TIMESTAMP(3),
| `price` INT,
| `tax` INT,
| WATERMARK FOR `ts` AS `ts` - INTERVAL '1' SECOND
|) WITH (
| 'connector' = 'values'
|)
|""".stripMargin
util.tableEnv.executeSql(ddl)
val sqlQuery =
s"""
|SELECT
| symbol,
| SUM(price) as price,
| TUMBLE_ROWTIME(matchRowtime, interval '3' second) as rowTime,
| TUMBLE_START(matchRowtime, interval '3' second) as startTime
|FROM Ticker1
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME() as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|GROUP BY symbol, TUMBLE(matchRowtime, interval '3' second)
|""".stripMargin
util.verifyRelPlan(sqlQuery)
}
@Test
def testMatchRecognizeOnRowtimeLTZ(): Unit = {
val sqlQuery =
s"""
|SELECT
| symbol,
| SUM(price) as price,
| TUMBLE_ROWTIME(matchRowtime, interval '3' second) as rowTime,
| TUMBLE_START(matchRowtime, interval '3' second) as startTime
|FROM Ticker
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts_ltz
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME(ts_ltz) as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|GROUP BY symbol, TUMBLE(matchRowtime, interval '3' second)
|""".stripMargin
util.verifyRelPlan(sqlQuery)
}
@Test
def testWindowTVFOnMatchRecognizeOnRowtimeLTZ(): Unit = {
val sqlQuery =
s"""
|SELECT
| *
|FROM Ticker
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts_ltz
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME(ts_ltz) as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|""".stripMargin
val table = util.tableEnv.sqlQuery(sqlQuery)
util.tableEnv.registerTable("T", table)
val sqlQuery1 =
s"""
|SELECT *
|FROM TABLE(TUMBLE(TABLE T, DESCRIPTOR(matchRowtime), INTERVAL '3' second))
|""".stripMargin
util.verifyRelPlanWithType(sqlQuery1)
}
@Test
def testOverWindowOnMatchRecognizeOnRowtimeLTZ(): Unit = {
val sqlQuery =
s"""
|SELECT
| *
|FROM Ticker
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts_ltz
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME(ts_ltz) as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|""".stripMargin
val table = util.tableEnv.sqlQuery(sqlQuery)
util.tableEnv.registerTable("T", table)
val sqlQuery1 =
"""
|SELECT
| symbol,
| price,
| tax,
| matchRowtime,
| SUM(price) OVER (
| PARTITION BY symbol ORDER BY matchRowtime RANGE UNBOUNDED PRECEDING) as price_sum
|FROM T
""".stripMargin
util.verifyRelPlanWithType(sqlQuery1)
}
@Test
def testCascadeMatch(): Unit = {
val sqlQuery =
s"""
|SELECT *
|FROM (
| SELECT
| symbol,
| matchRowtime,
| price,
| TUMBLE_START(matchRowtime, interval '3' second) as startTime
| FROM Ticker
| MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts_ltz
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME(ts_ltz) as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|GROUP BY symbol, matchRowtime, price, TUMBLE(matchRowtime, interval '3' second)
|)
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY matchRowtime
| MEASURES
| A.price as dPrice,
| A.matchRowtime as matchRowtime
| PATTERN (A)
| DEFINE
| A AS A.matchRowtime >= (CURRENT_TIMESTAMP - INTERVAL '1' day)
|)
|""".stripMargin
util.verifyRelPlan(sqlQuery)
}
// ----------------------------------------------------------------------------------------
// Tests for Illegal use of Match_RowTime
// ----------------------------------------------------------------------------------------
@Test
def testMatchRowtimeWithoutArgumentOnRowtimeLTZ(): Unit = {
thrown.expectMessage(
"MATCH_ROWTIME(rowtimeField) should be used when input stream " +
"contains rowtime attribute with TIMESTAMP_LTZ type.\n" +
"Please pass rowtime attribute field as input argument of " +
"MATCH_ROWTIME(rowtimeField) function.")
thrown.expect(classOf[AssertionError])
val sqlQuery =
s"""
|SELECT
| symbol,
| SUM(price) as price,
| TUMBLE_ROWTIME(matchRowtime, interval '3' second) as rowTime,
| TUMBLE_START(matchRowtime, interval '3' second) as startTime
|FROM Ticker
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts_ltz
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME() as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|GROUP BY symbol, TUMBLE(matchRowtime, interval '3' second)
|""".stripMargin
util.verifyRelPlan(sqlQuery)
}
@Test
def testMatchRowtimeWithMultipleArgs(): Unit = {
thrown.expectMessage("Invalid number of arguments to function 'MATCH_ROWTIME'.")
thrown.expect(classOf[ValidationException])
val sqlQuery =
s"""
|SELECT
| symbol,
| SUM(price) as price,
| TUMBLE_ROWTIME(matchRowtime, interval '3' second) as rowTime,
| TUMBLE_START(matchRowtime, interval '3' second) as startTime
|FROM Ticker
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts_ltz
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME(ts_ltz, price) as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|GROUP BY symbol, TUMBLE(matchRowtime, interval '3' second)
|""".stripMargin
util.verifyRelPlan(sqlQuery)
}
@Test
def testMatchRowtimeWithNonRowTimeAttributeAsArgs(): Unit = {
thrown.expectMessage(
"The function MATCH_ROWTIME requires argument to be a row time attribute type, " +
"but is 'INTEGER'.")
thrown.expect(classOf[ValidationException])
val sqlQuery =
s"""
|SELECT
| symbol,
| SUM(price) as price,
| TUMBLE_ROWTIME(matchRowtime, interval '3' second) as rowTime,
| TUMBLE_START(matchRowtime, interval '3' second) as startTime
|FROM Ticker
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts_ltz
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME(price) as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|GROUP BY symbol, TUMBLE(matchRowtime, interval '3' second)
|""".stripMargin
util.verifyRelPlan(sqlQuery)
}
@Test
def testMatchRowtimeWithRexCallAsArg(): Unit = {
thrown.expectMessage(
"The function MATCH_ROWTIME requires a field reference as argument, " +
"but actual argument is not a simple field reference.")
thrown.expect(classOf[ValidationException])
val sqlQuery =
s"""
|SELECT
| symbol,
| SUM(price) as price,
| TUMBLE_ROWTIME(matchRowtime, interval '3' second) as rowTime,
| TUMBLE_START(matchRowtime, interval '3' second) as startTime
|FROM Ticker
|MATCH_RECOGNIZE (
| PARTITION BY symbol
| ORDER BY ts_ltz
| MEASURES
| A.price as price,
| A.tax as tax,
| MATCH_ROWTIME(ts_ltz + INTERVAL '1' SECOND) as matchRowtime
| ONE ROW PER MATCH
| PATTERN (A)
| DEFINE
| A AS A.price > 0
|) AS T
|GROUP BY symbol, TUMBLE(matchRowtime, interval '3' second)
|""".stripMargin
util.verifyRelPlan(sqlQuery)
}
}
| {
"content_hash": "65f485ae97ece3d96bda9cec71f8393e",
"timestamp": "",
"source": "github",
"line_count": 336,
"max_line_length": 94,
"avg_line_length": 29.511904761904763,
"alnum_prop": 0.5273295683743445,
"repo_name": "twalthr/flink",
"id": "a16de4abd1ca61beee144b525622d255f2f0ea39",
"size": "10721",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/plan/stream/sql/MatchRecognizeTest.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "20596"
},
{
"name": "Batchfile",
"bytes": "1863"
},
{
"name": "C",
"bytes": "847"
},
{
"name": "Clojure",
"bytes": "84752"
},
{
"name": "Cython",
"bytes": "130650"
},
{
"name": "Dockerfile",
"bytes": "5563"
},
{
"name": "FreeMarker",
"bytes": "92068"
},
{
"name": "GAP",
"bytes": "139514"
},
{
"name": "HTML",
"bytes": "154937"
},
{
"name": "HiveQL",
"bytes": "119074"
},
{
"name": "Java",
"bytes": "91868014"
},
{
"name": "JavaScript",
"bytes": "7038"
},
{
"name": "Less",
"bytes": "68979"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "2518003"
},
{
"name": "Scala",
"bytes": "10732536"
},
{
"name": "Shell",
"bytes": "525376"
},
{
"name": "TypeScript",
"bytes": "311274"
},
{
"name": "q",
"bytes": "9630"
}
],
"symlink_target": ""
} |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
$string['usingchat_help'] = 'The chat module contains some features to make chatting a little nicer.
* Smilies - Any smiley faces (emoticons) that you can type elsewhere in Moodle can also be typed here, for example :-)
* Links - Website addresses will be turned into links automatically
* Emoting - You can start a line with "/me" or ":" to emote, for example if your name is Kim and you type ":laughs!" or "/me laughs!" then everyone will see "Kim laughs!"
* Beeps - You can send a sound to other participants by clicking the "beep" link next to their name. A useful shortcut to beep all the people in the chat at once is to type "beep all".
* HTML - If you know some HTML code, you can use it in your text to do things like insert images, play sounds or create different colored text';
| {
"content_hash": "e81e3ad3c03a7484712961d2debd49eb",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 184,
"avg_line_length": 54.32142857142857,
"alnum_prop": 0.7370151216305062,
"repo_name": "carnegiespeech/translations",
"id": "978160c38400bb6440f1df8dd5faeae4b5e66278",
"size": "1769",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "en_us/chat.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "16603208"
}
],
"symlink_target": ""
} |
Hilary.scope('heinz').register({
name: 'ExceptionHandler',
dependencies: [],
factory: function (onError) {
'use strict';
var self = {
makeException: undefined,
argumentException: undefined,
throwArgumentException: undefined,
notImplementedException: undefined,
throwNotImplementedException: undefined,
fetchException: undefined,
throwFetchException: undefined,
throwException: undefined,
throw: undefined
},
makeException;
onError = (typeof onError === 'function') ? onError : function (exception) {
console.error(exception);
throw exception;
};
makeException = function (name, message, data) {
var msg,
err;
if (typeof name === 'object' && typeof name.message === 'string') {
// The name argument probably received an Error object
msg = name.message;
err = name;
} else {
msg = typeof message === 'string' ? message : name;
err = new Error(msg);
}
err.message = msg;
if (name !== msg) {
err.name = name;
}
if (data) {
err.data = data;
}
return err;
};
self.makeException = makeException;
self.argumentException = function (message, argument, data) {
var msg = typeof argument === 'undefined' ? message : message + ' (argument: ' + argument + ')';
return makeException('ArgumentException', msg, data);
};
self.throwArgumentException = function (message, argument, data) {
self.throw(self.argumentException(message, argument, data));
};
self.notImplementedException = function (message, data) {
return makeException('NotImplementedException', message, data);
};
self.throwNotImplementedException = function (message, data) {
self.throw(self.notImplementedException(message, data));
};
self.fetchException = function (response) {
response = response || {};
return makeException('FetchException', 'Server Request Failed with status: ' + response.status, response);
};
self.throwFetchException = function (response) {
self.throw(self.fetchException(response));
// In order to support fetch.throw, we have to throw a real JS Exception
// If self.throw doesn't do that for us, this will ensure that functionality
// is maintained
throw new Error('Server Request Failed with status: ' + response.status);
};
self.throwException = function (exception) {
self.throw(exception);
};
self.throw = function (exception) {
if (typeof exception === 'string') {
onError(makeException(exception));
} else {
onError(exception);
}
};
return self;
}
});
| {
"content_hash": "889e7b3fe02bbd050a946e3468de93cb",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 118,
"avg_line_length": 32.57575757575758,
"alnum_prop": 0.5336434108527132,
"repo_name": "pomonav/buy-books",
"id": "dfb41632ed8bb270603c74987515eae11bfe50d4",
"size": "3225",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node/web/public/scripts/ExceptionHandler.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "94"
},
{
"name": "C#",
"bytes": "200439"
},
{
"name": "CSS",
"bytes": "69268"
},
{
"name": "HTML",
"bytes": "19530"
},
{
"name": "JavaScript",
"bytes": "643944"
},
{
"name": "PowerShell",
"bytes": "6487"
},
{
"name": "Shell",
"bytes": "2057"
}
],
"symlink_target": ""
} |
require 'date'
require 'net/ftp'
require 'time'
module Metar
module Raw
class Base
attr_reader :metar
attr_reader :time
alias to_s metar
end
##
# Use this class when you have a METAR string and the date of reading
class Data < Base
def initialize(metar, time = nil)
if time.nil?
warn <<-WARNING
Using Metar::Raw::Data without a time parameter is deprecated.
Please supply the reading time as the second parameter.
WARNING
time = Time.now
end
@metar = metar
@time = time
end
end
##
# Use this class when you only have a METAR string.
# The date of the reading is decided as follows:
# * the day of the month is extracted from the METAR,
# * the most recent day with that day of the month is taken as the
# date of the reading.
class Metar < Base
def initialize(metar)
@metar = metar
@time = nil
end
def time
return @time if @time
dom = day_of_month
date = Date.today
loop do
if date.day >= dom
@time = Date.new(date.year, date.month, dom)
break
end
# skip to the last day of the previous month
date = Date.new(date.year, date.month, 1).prev_day
end
@time
end
private
def datetime
datetime = metar[/^\w{4} (\d{6})Z/, 1]
raise "The METAR string must have a 6 digit datetime" if datetime.nil?
datetime
end
def day_of_month
dom = datetime[0..1].to_i
raise "Day of month must be at most 31" if dom > 31
raise "Day of month must be greater than 0" if dom.zero?
dom
end
end
# Collects METAR data from the NOAA site via FTP
class Noaa < Base
def self.fetch(cccc)
connection = Net::FTP.new('tgftp.nws.noaa.gov')
connection.login
connection.chdir('data/observations/metar/stations')
connection.passive = true
attempts = 0
while attempts < 2
begin
s = ''
connection.retrbinary("RETR #{cccc}.TXT", 1024) do |chunk|
s += chunk
end
connection.close
return s
rescue Net::FTPPermError, Net::FTPTempError, EOFError
attempts += 1
end
end
raise "Net::FTP.retrbinary failed #{attempts} times"
end
# Station is a string containing the CCCC code, or
# an object with a 'cccc' method which returns the code
def initialize(station)
@cccc = station.respond_to?(:cccc) ? station.cccc : station
end
def data
fetch
@data
end
# #raw is deprecated, use #data
alias raw data
def time
fetch
@time
end
def metar
fetch
@metar
end
private
def fetch
return if @data
@data = Noaa.fetch(@cccc)
parse
end
def parse
raw_time, @metar = @data.split("\n")
@time = Time.parse(raw_time + " UTC")
end
end
end
end
| {
"content_hash": "5e82aec58687e052b2d458ba24db4c46",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 78,
"avg_line_length": 23.115107913669064,
"alnum_prop": 0.5415499533146592,
"repo_name": "joeyates/metar-parser",
"id": "aad96313dc62624266b3ea53e26ce773141bec17",
"size": "3244",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "lib/metar/raw.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "117943"
},
{
"name": "Shell",
"bytes": "141"
}
],
"symlink_target": ""
} |
package gnu.xml.xpath;
import javax.xml.namespace.QName;
import org.w3c.dom.Node;
/**
* The <code>last</code> function returns a number equal to the context
* size from the expression evaluation context.
*
* @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
*/
final class LastFunction
extends Expr
{
public Object evaluate(Node context, int pos, int len)
{
return new Double((double) len);
}
public Expr clone(Object context)
{
return new LastFunction();
}
public boolean references(QName var)
{
return false;
}
public String toString()
{
return "last()";
}
}
| {
"content_hash": "ad94df656364426827c400ca87583cd9",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 71,
"avg_line_length": 16.36842105263158,
"alnum_prop": 0.6704180064308681,
"repo_name": "the-linix-project/linix-kernel-source",
"id": "51f988f3c6fc49dc6cbc0787c0c7ec1644d6ee89",
"size": "2354",
"binary": false,
"copies": "153",
"ref": "refs/heads/master",
"path": "gccsrc/gcc-4.7.2/libjava/classpath/gnu/xml/xpath/LastFunction.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ada",
"bytes": "38139979"
},
{
"name": "Assembly",
"bytes": "3723477"
},
{
"name": "Awk",
"bytes": "83739"
},
{
"name": "C",
"bytes": "103607293"
},
{
"name": "C#",
"bytes": "55726"
},
{
"name": "C++",
"bytes": "38577421"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "32588"
},
{
"name": "Emacs Lisp",
"bytes": "13451"
},
{
"name": "FORTRAN",
"bytes": "4294984"
},
{
"name": "GAP",
"bytes": "13089"
},
{
"name": "Go",
"bytes": "11277335"
},
{
"name": "Haskell",
"bytes": "2415"
},
{
"name": "Java",
"bytes": "45298678"
},
{
"name": "JavaScript",
"bytes": "6265"
},
{
"name": "Matlab",
"bytes": "56"
},
{
"name": "OCaml",
"bytes": "148372"
},
{
"name": "Objective-C",
"bytes": "995127"
},
{
"name": "Objective-C++",
"bytes": "436045"
},
{
"name": "PHP",
"bytes": "12361"
},
{
"name": "Pascal",
"bytes": "40318"
},
{
"name": "Perl",
"bytes": "358808"
},
{
"name": "Python",
"bytes": "60178"
},
{
"name": "SAS",
"bytes": "1711"
},
{
"name": "Scilab",
"bytes": "258457"
},
{
"name": "Shell",
"bytes": "2610907"
},
{
"name": "Tcl",
"bytes": "17983"
},
{
"name": "TeX",
"bytes": "1455571"
},
{
"name": "XSLT",
"bytes": "156419"
}
],
"symlink_target": ""
} |
package com.livebetter.domain;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.PersistenceContext;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
@Configurable
@Entity
@Table(schema = "public",name = "metabolisms")
@Deprecated
public class Metabolism {
@OneToMany(mappedBy = "metabolismId")
private Set<Person> personss;
@Column(name = "name", length = 45)
@NotNull
private String name;
@Column(name = "created_by")
private Long createdBy;
@Column(name = "created_datetime")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "MM")
private Calendar createdDatetime;
@Column(name = "modified_datetime")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "MM")
private Calendar modifiedDatetime;
public Set<Person> getPersonss() {
return personss;
}
public void setPersonss(Set<Person> personss) {
this.personss = personss;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public Calendar getCreatedDatetime() {
return createdDatetime;
}
public void setCreatedDatetime(Calendar createdDatetime) {
this.createdDatetime = createdDatetime;
}
public Calendar getModifiedDatetime() {
return modifiedDatetime;
}
public void setModifiedDatetime(Calendar modifiedDatetime) {
this.modifiedDatetime = modifiedDatetime;
}
public String toString() {
return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).setExcludeFieldNames("personss").toString();
}
@PersistenceContext
transient EntityManager entityManager;
public static final List<String> fieldNames4OrderClauseFilter = java.util.Arrays.asList("");
public static final EntityManager entityManager() {
EntityManager em = new Metabolism().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public static long countMetabolismses() {
return entityManager().createQuery("SELECT COUNT(o) FROM Metabolism o", Long.class).getSingleResult();
}
public static List<Metabolism> findAllMetabolismses() {
return entityManager().createQuery("SELECT o FROM Metabolism o", Metabolism.class).getResultList();
}
public static List<Metabolism> findAllMetabolismses(String sortFieldName, String sortOrder) {
String jpaQuery = "SELECT o FROM Metabolism o";
if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
jpaQuery = jpaQuery + " " + sortOrder;
}
}
return entityManager().createQuery(jpaQuery, Metabolism.class).getResultList();
}
public static Metabolism findMetabolisms(Long id) {
if (id == null) return null;
return entityManager().find(Metabolism.class, id);
}
public static List<Metabolism> findMetabolismsEntries(int firstResult, int maxResults) {
return entityManager().createQuery("SELECT o FROM Metabolism o", Metabolism.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
public static List<Metabolism> findMetabolismsEntries(int firstResult, int maxResults, String sortFieldName, String sortOrder) {
String jpaQuery = "SELECT o FROM Metabolism o";
if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
jpaQuery = jpaQuery + " " + sortOrder;
}
}
return entityManager().createQuery(jpaQuery, Metabolism.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
@Transactional
public void persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
@Transactional
public void remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Metabolism attached = Metabolism.findMetabolisms(this.id);
this.entityManager.remove(attached);
}
}
@Transactional
public void flush() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.flush();
}
@Transactional
public void clear() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.clear();
}
@Transactional
public Metabolism merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Metabolism merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
@Id
@GeneratedValue(generator = "metabolisms_seq")
@GenericGenerator(name = "metabolisms_seq", strategy = "sequence-identity", parameters = @Parameter(name = "sequence", value = "metabolisms_id_seq"))
@Column(name = "id")
private Long id;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
}
| {
"content_hash": "6a6903931ac29b03015db7375d69e7f2",
"timestamp": "",
"source": "github",
"line_count": 195,
"max_line_length": 167,
"avg_line_length": 33.08205128205128,
"alnum_prop": 0.7025267400403038,
"repo_name": "ST-Team5/LiveBetterServer",
"id": "da2988381365112822db990ad309bf7bf038ae91",
"size": "6451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "live-better/src/main/java/com/livebetter/domain/Metabolism.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9019"
},
{
"name": "Java",
"bytes": "208531"
},
{
"name": "Shell",
"bytes": "125"
}
],
"symlink_target": ""
} |
<?php
/*!
* WordPress Social Login
*
* http://miled.github.io/wordpress-social-login/ | https://github.com/miled/wordpress-social-login
* (c) 2011-2015 Mohamed Mrassi and contributors | http://wordpress.org/plugins/wordpress-social-login/
*/
/**
* The Bouncer our friend whos trying to be funneh
*/
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
// --------------------------------------------------------------------
function wsl_component_bouncer()
{
// HOOKABLE:
do_action( "wsl_component_bouncer_start" );
include "wsl.components.bouncer.setup.php";
include "wsl.components.bouncer.sidebar.php";
?>
<form method="post" id="wsl_setup_form" action="options.php">
<?php settings_fields( 'wsl-settings-group-bouncer' ); ?>
<div class="metabox-holder columns-2" id="post-body">
<table width="100%">
<tr valign="top">
<td>
<?php
wsl_component_bouncer_setup();
?>
</td>
<td width="10"></td>
<td width="400">
<?php
wsl_component_bouncer_sidebar();
?>
</td>
</tr>
</table>
</div>
</form>
<?php
// HOOKABLE:
do_action( "wsl_component_bouncer_end" );
}
wsl_component_bouncer();
// --------------------------------------------------------------------
| {
"content_hash": "2676df280065258117cc5cf91b7b654f",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 103,
"avg_line_length": 23.11111111111111,
"alnum_prop": 0.563301282051282,
"repo_name": "sassafrastech/wordpress-social-login",
"id": "84ef6854c9a1ab0702559a7eb6b64f18880ae5e7",
"size": "1248",
"binary": false,
"copies": "24",
"ref": "refs/heads/master",
"path": "includes/admin/components/bouncer/index.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3072"
},
{
"name": "JavaScript",
"bytes": "2061"
},
{
"name": "PHP",
"bytes": "629058"
},
{
"name": "Shell",
"bytes": "2137"
}
],
"symlink_target": ""
} |
package cn.edu.gdut.zaoying.Option.series.graph.markLine.data.p1.label.normal;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FormatterString {
String value() default "";
} | {
"content_hash": "82f761f9ee23abef9c9e78267025257e",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 78,
"avg_line_length": 33.81818181818182,
"alnum_prop": 0.8145161290322581,
"repo_name": "zaoying/EChartsAnnotation",
"id": "b3ea2f8318f30536460fa76e4cb9457d49e0d64b",
"size": "372",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/cn/edu/gdut/zaoying/Option/series/graph/markLine/data/p1/label/normal/FormatterString.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "97"
},
{
"name": "Java",
"bytes": "1345279"
}
],
"symlink_target": ""
} |
package graphedit.actions.pallete;
import graphedit.app.MainFrame;
import graphedit.app.MainFrame.ToolSelected;
import graphedit.model.components.Link;
import graphedit.state.LinkState;
import graphedit.state.State;
import graphedit.util.ResourceLoader;
import graphedit.view.GraphEditView;
import graphedit.view.GraphEditView.GraphEditController;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
public class GeneralizationLinkButtonAction extends AbstractAction{
/**
*
*/
private static final long serialVersionUID = 1L;
public GeneralizationLinkButtonAction(){
putValue(SMALL_ICON, new ResourceLoader().loadImageIcon("generalization.png"));
putValue(SHORT_DESCRIPTION, "Generalization link");
putValue(NAME, "Generalization link");
}
@Override
public void actionPerformed(ActionEvent arg0) {
GraphEditView view = MainFrame.getInstance().getCurrentView();
if (view == null) {
return;
}
//ako se preslo iz povezivanje, mora da se ocisti
State state=MainFrame.getInstance().getCurrentView().getCurrentState();
state.clearEverything();
GraphEditController context = view.getCurrentState().getController();
view.getSelectionModel().removeAllSelectedElements();
view.getSelectionModel().setSelectedLink(null);
view.getSelectionModel().setSelectedNode(null);
state=MainFrame.getInstance().getCurrentView().getModel().getLinkState();
state.setView(view);
state.setController(context);
((LinkState)state).setLinkType(Link.LinkType.GENERALIZATION);
MainFrame.getInstance().setStatusTrack(state.toString());
context.setCurrentState(state);
view.setSelectedTool(ToolSelected.GENERALIZATION);
view.requestFocusInWindow();
view.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
view.repaint();
}
}
| {
"content_hash": "b3711511da2a7800a5a4e534b5465d69",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 82,
"avg_line_length": 28.424242424242426,
"alnum_prop": 0.7633262260127932,
"repo_name": "VladimirRadojcic/Master",
"id": "9460b4a63454513debf84d614ce6492df8f1e43b",
"size": "1876",
"binary": false,
"copies": "1",
"ref": "refs/heads/VladimirRadojcic",
"path": "GraphEdit/src/graphedit/actions/pallete/GeneralizationLinkButtonAction.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AspectJ",
"bytes": "46124"
},
{
"name": "CSS",
"bytes": "14198"
},
{
"name": "FreeMarker",
"bytes": "9550"
},
{
"name": "HTML",
"bytes": "13107"
},
{
"name": "Java",
"bytes": "2618620"
},
{
"name": "JavaScript",
"bytes": "25579"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>zchinese: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.14.0 / zchinese - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
zchinese
<small>
8.9.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-04-04 11:11:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-04 11:11:08 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.14.0 Formal proof management system
dune 3.0.3 Fast, portable, and opinionated build system
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/zchinese"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ZChinese"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: number theory"
"keyword: chinese remainder"
"keyword: primality"
"keyword: prime numbers"
"category: Mathematics/Arithmetic and Number Theory/Number theory"
"category: Miscellaneous/Extracted Programs/Arithmetic"
]
authors: [
"Valérie Ménissier-Morain"
]
bug-reports: "https://github.com/coq-contribs/zchinese/issues"
dev-repo: "git+https://github.com/coq-contribs/zchinese.git"
synopsis: "A proof of the Chinese Remainder Lemma"
description: """
This is a rewriting of the contribution chinese-lemma using Zarith"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/zchinese/archive/v8.9.0.tar.gz"
checksum: "md5=a5fddf5409ff7b7053a84bbf9491b8fc"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-zchinese.8.9.0 coq.8.14.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.14.0).
The following dependencies couldn't be met:
- coq-zchinese -> coq < 8.10~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-zchinese.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "f0d4d5aefa4bc9c8f689ac855f2f1c91",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 159,
"avg_line_length": 40.672413793103445,
"alnum_prop": 0.5472657905892327,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "c77927c14d7c50a4f4dc0bbc07c8cb7dd5ad26cf",
"size": "7104",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.14.0/zchinese/8.9.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
A JS plugin to display your Facebook events on your website.
## Getting Started
1. Go to [Facebook for Developers](https://developers.facebook.com/docs/apps/register/) and follow the guide except for the following changes to create an app.
* Select Web as the platform.
* Disable Development mode (Can be done after your ready to add it to your website).
* Copy your App id from the dashboard.
2. Add JS and CSS file to your html making sure setting precceds the main JS file.
3. To get your Profile ID or Page ID go to your profile or page profile press CTRL + Shift + I and Search the Pages source for either page_id= or profile_id= the number proceeding is to be used in the app.
4. Change these details:
```
const APP_ID = ""; // The App ID created on https://developers.facebook.com/
const MY_PROFILE = ""; // Your Profile or Page ID
var eventNum = 8; // The max number of events you want displayed on the page
const LOCATION_NAME = ""; // The Location, city, state, country displayed if none was given on facebook
const CITY_NAME = "";
const STATE_NAME = "";
const COUNTRY_NAME = "";
```
5. Add the following div to wherever on your page you want to display your events:
```
<div id="fbevents"></div>
```
## Prerequisites
JQuery and Bootstrap 4.
## Themes
I've provided two choices of color schemes for the app the default one and the dark one.


| {
"content_hash": "99aef8b52deb856fb2228ecf701d3197",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 205,
"avg_line_length": 39.23684210526316,
"alnum_prop": 0.7283702213279678,
"repo_name": "DylanHatherley/whazhapenin",
"id": "6f10025f83a8205a8bf3094115be1522744831d2",
"size": "1526",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "927"
},
{
"name": "HTML",
"bytes": "850"
},
{
"name": "JavaScript",
"bytes": "5852"
}
],
"symlink_target": ""
} |
//
// ImapFolderAnnotationsTests.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2021 .NET Foundation and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
using MimeKit;
using MailKit;
using MailKit.Search;
using MailKit.Net.Imap;
namespace UnitTests.Net.Imap {
[TestFixture]
public class ImapFolderAnnotationsTests
{
static readonly Encoding Latin1 = Encoding.GetEncoding (28591);
Stream GetResourceStream (string name)
{
return GetType ().Assembly.GetManifestResourceStream ("UnitTests.Net.Imap.Resources." + name);
}
[Test]
public void TestArgumentExceptions ()
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
commands.Add (new ImapReplayCommand ("A00000004 SELECT INBOX (CONDSTORE ANNOTATE)\r\n", "common.select-inbox-annotate.txt"));
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
inbox.Open (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadWrite, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Shared, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (20480, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var annotations = new List<Annotation> (new[] {
new Annotation (AnnotationEntry.AltSubject)
});
annotations[0].Properties.Add (AnnotationAttribute.SharedValue, "value");
// Store
Assert.Throws<ArgumentException> (() => inbox.Store (-1, annotations));
Assert.ThrowsAsync<ArgumentException> (() => inbox.StoreAsync (-1, annotations));
Assert.Throws<ArgumentNullException> (() => inbox.Store (0, (IList<Annotation>) null));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync (0, (IList<Annotation>) null));
Assert.Throws<ArgumentException> (() => inbox.Store (UniqueId.Invalid, annotations));
Assert.ThrowsAsync<ArgumentException> (() => inbox.StoreAsync (UniqueId.Invalid, annotations));
Assert.Throws<ArgumentNullException> (() => inbox.Store (UniqueId.MinValue, (IList<Annotation>) null));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync (UniqueId.MinValue, (IList<Annotation>) null));
Assert.Throws<ArgumentNullException> (() => inbox.Store ((IList<int>) null, annotations));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync ((IList<int>) null, annotations));
Assert.Throws<ArgumentNullException> (() => inbox.Store (new int[] { 0 }, (IList<Annotation>) null));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync (new int[] { 0 }, (IList<Annotation>) null));
Assert.Throws<ArgumentNullException> (() => inbox.Store ((IList<int>) null, 1, annotations));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync ((IList<int>) null, 1, annotations));
Assert.Throws<ArgumentNullException> (() => inbox.Store (new int[] { 0 }, 1, (IList<Annotation>) null));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync (new int[] { 0 }, 1, (IList<Annotation>) null));
Assert.Throws<ArgumentNullException> (() => inbox.Store ((IList<UniqueId>) null, annotations));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync ((IList<UniqueId>) null, annotations));
Assert.Throws<ArgumentNullException> (() => inbox.Store (UniqueIdRange.All, (IList<Annotation>) null));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync (UniqueIdRange.All, (IList<Annotation>) null));
Assert.Throws<ArgumentNullException> (() => inbox.Store ((IList<UniqueId>) null, 1, annotations));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync ((IList<UniqueId>) null, 1, annotations));
Assert.Throws<ArgumentNullException> (() => inbox.Store (UniqueIdRange.All, 1, (IList<Annotation>) null));
Assert.ThrowsAsync<ArgumentNullException> (() => inbox.StoreAsync (UniqueIdRange.All, 1, (IList<Annotation>) null));
client.Disconnect (false);
}
}
[Test]
public void TestNotSupportedExceptions ()
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
commands.Add (new ImapReplayCommand ("A00000004 SELECT INBOX (CONDSTORE ANNOTATE)\r\n", "common.select-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000005 SELECT INBOX (ANNOTATE)\r\n", "common.select-inbox-annotate-no-modseq.txt"));
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
inbox.Open (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.None, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.None, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (0, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var annotations = new List<Annotation> (new[] {
new Annotation (AnnotationEntry.AltSubject)
});
annotations[0].Properties.Add (AnnotationAttribute.SharedValue, "value");
// verify NotSupportedException for storing annotations
Assert.Throws<NotSupportedException> (() => inbox.Store (0, annotations));
Assert.ThrowsAsync<NotSupportedException> (() => inbox.StoreAsync (0, annotations));
Assert.Throws<NotSupportedException> (() => inbox.Store (UniqueId.MinValue, annotations));
Assert.ThrowsAsync<NotSupportedException> (() => inbox.StoreAsync (UniqueId.MinValue, annotations));
Assert.Throws<NotSupportedException> (() => inbox.Store (new int[] { 0 }, 1, annotations));
Assert.ThrowsAsync<NotSupportedException> (() => inbox.StoreAsync (new int[] { 0 }, 1, annotations));
Assert.Throws<NotSupportedException> (() => inbox.Store (UniqueIdRange.All, 1, annotations));
Assert.ThrowsAsync<NotSupportedException> (() => inbox.StoreAsync (UniqueIdRange.All, 1, annotations));
// disable CONDSTORE and verify that we get NotSupportedException when we send modseq
client.Capabilities &= ~ImapCapabilities.CondStore;
inbox.Open (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadWrite, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Shared, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (20480, inbox.MaxAnnotationSize, "MaxAnnotationSize");
Assert.Throws<NotSupportedException> (() => inbox.Store (new int[] { 0 }, 1, annotations));
Assert.ThrowsAsync<NotSupportedException> (() => inbox.StoreAsync (new int[] { 0 }, 1, annotations));
Assert.Throws<NotSupportedException> (() => inbox.Store (UniqueIdRange.All, 1, annotations));
Assert.ThrowsAsync<NotSupportedException> (() => inbox.StoreAsync (UniqueIdRange.All, 1, annotations));
client.Disconnect (false);
}
}
[Test]
public void TestChangingAnnotationsOnEmptyListOfMessages ()
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
commands.Add (new ImapReplayCommand ("A00000004 SELECT INBOX (CONDSTORE ANNOTATE)\r\n", "common.select-inbox-annotate.txt"));
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
inbox.Open (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadWrite, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Shared, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (20480, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var annotations = new List<Annotation> (new[] {
new Annotation (AnnotationEntry.AltSubject)
});
annotations[0].Properties.Add (AnnotationAttribute.SharedValue, "value");
ulong modseq = 409601020304;
var uids = new UniqueId[0];
var indexes = new int[0];
IList<UniqueId> unmodifiedUids;
IList<int> unmodifiedIndexes;
unmodifiedIndexes = inbox.Store (indexes, modseq, annotations);
Assert.AreEqual (0, unmodifiedIndexes.Count);
unmodifiedUids = inbox.Store (uids, modseq, annotations);
Assert.AreEqual (0, unmodifiedUids.Count);
client.Disconnect (false);
}
}
IList<ImapReplayCommand> CreateAppendWithAnnotationsCommands (bool withInternalDates, out List<MimeMessage> messages, out List<MessageFlags> flags, out List<DateTimeOffset> internalDates, out List<Annotation> annotations)
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
internalDates = withInternalDates ? new List<DateTimeOffset> () : null;
annotations = new List<Annotation> ();
messages = new List<MimeMessage> ();
flags = new List<MessageFlags> ();
var command = new StringBuilder ();
int id = 4;
for (int i = 0; i < 8; i++) {
MimeMessage message;
string latin1;
long length;
using (var resource = GetResourceStream (string.Format ("common.message.{0}.msg", i)))
message = MimeMessage.Load (resource);
messages.Add (message);
flags.Add (MessageFlags.Seen);
if (withInternalDates)
internalDates.Add (message.Date);
var annotation = new Annotation (AnnotationEntry.AltSubject);
annotation.Properties[AnnotationAttribute.PrivateValue] = string.Format ("Alternate subject {0}", i);
annotations.Add (annotation);
using (var stream = new MemoryStream ()) {
var options = FormatOptions.Default.Clone ();
options.NewLineFormat = NewLineFormat.Dos;
options.EnsureNewLine = true;
message.WriteTo (options, stream);
length = stream.Length;
stream.Position = 0;
using (var reader = new StreamReader (stream, Latin1))
latin1 = reader.ReadToEnd ();
}
var tag = string.Format ("A{0:D8}", id++);
command.Clear ();
command.AppendFormat ("{0} APPEND INBOX (\\Seen) ", tag);
if (withInternalDates)
command.AppendFormat ("\"{0}\" ", ImapUtils.FormatInternalDate (message.Date));
command.AppendFormat ("ANNOTATION (/altsubject (value.priv \"Alternate subject {0}\")) ", i);
command.Append ('{').Append (length.ToString ()).Append ("+}\r\n").Append (latin1).Append ("\r\n");
commands.Add (new ImapReplayCommand (command.ToString (), string.Format ("dovecot.append.{0}.txt", i + 1)));
}
commands.Add (new ImapReplayCommand (string.Format ("A{0:D8} LOGOUT\r\n", id), "gmail.logout.txt"));
return commands;
}
[TestCase (false, TestName = "TestAppendWithAnnotations")]
[TestCase (true, TestName = "TestAppendWithAnnotationsAndInternalDates")]
public void TestAppendWithAnnotations (bool withInternalDates)
{
var expectedFlags = MessageFlags.Answered | MessageFlags.Flagged | MessageFlags.Deleted | MessageFlags.Seen | MessageFlags.Draft;
var expectedPermanentFlags = expectedFlags | MessageFlags.UserDefined;
List<DateTimeOffset> internalDates;
List<Annotation> annotations;
List<MimeMessage> messages;
List<MessageFlags> flags;
var commands = CreateAppendWithAnnotationsCommands (withInternalDates, out messages, out flags, out internalDates, out annotations);
using (var client = new ImapClient ()) {
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate ("username", "password");
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
for (int i = 0; i < messages.Count; i++) {
UniqueId? uid;
if (withInternalDates)
uid = client.Inbox.Append (messages[i], flags[i], internalDates[i], new [] { annotations[i] });
else
uid = client.Inbox.Append (messages[i], flags[i], null, new [] { annotations[i] });
Assert.IsTrue (uid.HasValue, "Expected a UIDAPPEND resp-code");
Assert.AreEqual (i + 1, uid.Value.Id, "Unexpected UID");
messages[i].Dispose ();
}
client.Disconnect (true);
}
}
[TestCase (false, TestName = "TestAppendWithAnnotationsAsync")]
[TestCase (true, TestName = "TestAppendWithAnnotationsAndInternalDatesAsync")]
public async Task TestAppendWithAnnotationsAsync (bool withInternalDates)
{
var expectedFlags = MessageFlags.Answered | MessageFlags.Flagged | MessageFlags.Deleted | MessageFlags.Seen | MessageFlags.Draft;
var expectedPermanentFlags = expectedFlags | MessageFlags.UserDefined;
List<DateTimeOffset> internalDates;
List<Annotation> annotations;
List<MimeMessage> messages;
List<MessageFlags> flags;
var commands = CreateAppendWithAnnotationsCommands (withInternalDates, out messages, out flags, out internalDates, out annotations);
using (var client = new ImapClient ()) {
try {
await client.ReplayConnectAsync ("localhost", new ImapReplayStream (commands, true));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
client.AuthenticationMechanisms.Clear ();
try {
await client.AuthenticateAsync ("username", "password");
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
for (int i = 0; i < messages.Count; i++) {
UniqueId? uid;
if (withInternalDates)
uid = await client.Inbox.AppendAsync (messages[i], flags[i], internalDates[i], new[] { annotations[i] });
else
uid = await client.Inbox.AppendAsync (messages[i], flags[i], null, new[] { annotations[i] });
Assert.IsTrue (uid.HasValue, "Expected a UIDAPPEND resp-code");
Assert.AreEqual (i + 1, uid.Value.Id, "Unexpected UID");
messages[i].Dispose ();
}
await client.DisconnectAsync (true);
}
}
IList<ImapReplayCommand> CreateMultiAppendWithAnnotationsCommands (bool withInternalDates, out List<IAppendRequest> requests)
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
var command = new StringBuilder ("A00000004 APPEND INBOX");
var options = FormatOptions.Default.Clone ();
options.NewLineFormat = NewLineFormat.Dos;
options.EnsureNewLine = true;
int id = 5;
requests = new List<IAppendRequest> ();
for (int i = 0; i < 8; i++) {
MimeMessage message;
string latin1;
long length;
using (var resource = GetResourceStream (string.Format ("common.message.{0}.msg", i)))
message = MimeMessage.Load (resource);
var request = new AppendRequest (message, MessageFlags.Seen);
requests.Add (request);
if (withInternalDates)
request.InternalDate = message.Date;
var annotation = new Annotation (AnnotationEntry.AltSubject);
annotation.Properties[AnnotationAttribute.PrivateValue] = string.Format ("Alternate subject {0}", i);
request.Annotations = new Annotation[] { annotation };
using (var stream = new MemoryStream ()) {
message.WriteTo (options, stream);
length = stream.Length;
stream.Position = 0;
using (var reader = new StreamReader (stream, Latin1))
latin1 = reader.ReadToEnd ();
}
command.Append (" (\\Seen) ");
if (withInternalDates)
command.AppendFormat ("\"{0}\" ", ImapUtils.FormatInternalDate (message.Date));
command.AppendFormat ("ANNOTATION (/altsubject (value.priv \"Alternate subject {0}\")) ", i);
command.Append ('{');
command.AppendFormat ("{0}+", length);
command.Append ("}\r\n");
command.Append (latin1);
}
command.Append ("\r\n");
commands.Add (new ImapReplayCommand (command.ToString (), "dovecot.multiappend.txt"));
for (int i = 0; i < requests.Count; i++) {
var message = requests[i];
string latin1;
long length;
command.Clear ();
command.AppendFormat ("A{0:D8} APPEND INBOX", id++);
using (var stream = new MemoryStream ()) {
requests[i].Message.WriteTo (options, stream);
length = stream.Length;
stream.Position = 0;
using (var reader = new StreamReader (stream, Latin1))
latin1 = reader.ReadToEnd ();
}
command.Append (" (\\Seen) ");
if (withInternalDates)
command.AppendFormat ("\"{0}\" ", ImapUtils.FormatInternalDate (requests[i].InternalDate.Value));
command.AppendFormat ("ANNOTATION (/altsubject (value.priv \"Alternate subject {0}\")) ", i);
command.Append ('{');
command.AppendFormat ("{0}+", length);
command.Append ("}\r\n");
command.Append (latin1);
command.Append ("\r\n");
commands.Add (new ImapReplayCommand (command.ToString (), string.Format ("dovecot.append.{0}.txt", i + 1)));
}
commands.Add (new ImapReplayCommand (string.Format ("A{0:D8} LOGOUT\r\n", id), "gmail.logout.txt"));
return commands;
}
[TestCase (false, TestName = "TestMultiAppendWithAnnotations")]
[TestCase (true, TestName = "TestMultiAppendWithAnnotationsAndInternalDates")]
public void TestMultiAppendWithAnnotations (bool withInternalDates)
{
var expectedFlags = MessageFlags.Answered | MessageFlags.Flagged | MessageFlags.Deleted | MessageFlags.Seen | MessageFlags.Draft;
var expectedPermanentFlags = expectedFlags | MessageFlags.UserDefined;
List<IAppendRequest> requests;
IList<UniqueId> uids;
var commands = CreateMultiAppendWithAnnotationsCommands (withInternalDates, out requests);
using (var client = new ImapClient ()) {
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate ("username", "password");
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
// Use MULTIAPPEND to append some test messages
uids = client.Inbox.Append (requests);
Assert.AreEqual (8, uids.Count, "Unexpected number of messages appended");
for (int i = 0; i < uids.Count; i++)
Assert.AreEqual (i + 1, uids[i].Id, "Unexpected UID");
// Disable the MULTIAPPEND extension and do it again
client.Capabilities &= ~ImapCapabilities.MultiAppend;
uids = client.Inbox.Append (requests);
Assert.AreEqual (8, uids.Count, "Unexpected number of messages appended");
for (int i = 0; i < uids.Count; i++)
Assert.AreEqual (i + 1, uids[i].Id, "Unexpected UID");
client.Disconnect (true);
foreach (var request in requests)
request.Message.Dispose ();
}
}
[TestCase (false, TestName = "TestMultiAppendWithAnnotationsAsync")]
[TestCase (true, TestName = "TestMultiAppendWithAnnotationsAndInternalDatesAsync")]
public async Task TestMultiAppendWithAnnotationsAsync (bool withInternalDates)
{
var expectedFlags = MessageFlags.Answered | MessageFlags.Flagged | MessageFlags.Deleted | MessageFlags.Seen | MessageFlags.Draft;
var expectedPermanentFlags = expectedFlags | MessageFlags.UserDefined;
List<IAppendRequest> requests;
IList<UniqueId> uids;
var commands = CreateMultiAppendWithAnnotationsCommands (withInternalDates, out requests);
using (var client = new ImapClient ()) {
try {
await client.ReplayConnectAsync ("localhost", new ImapReplayStream (commands, true));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
client.AuthenticationMechanisms.Clear ();
try {
await client.AuthenticateAsync ("username", "password");
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
// Use MULTIAPPEND to append some test messages
uids = await client.Inbox.AppendAsync (requests);
Assert.AreEqual (8, uids.Count, "Unexpected number of messages appended");
for (int i = 0; i < uids.Count; i++)
Assert.AreEqual (i + 1, uids[i].Id, "Unexpected UID");
// Disable the MULTIAPPEND extension and do it again
client.Capabilities &= ~ImapCapabilities.MultiAppend;
uids = await client.Inbox.AppendAsync (requests);
Assert.AreEqual (8, uids.Count, "Unexpected number of messages appended");
for (int i = 0; i < uids.Count; i++)
Assert.AreEqual (i + 1, uids[i].Id, "Unexpected UID");
await client.DisconnectAsync (true);
foreach (var request in requests)
request.Message.Dispose ();
}
}
IList<ImapReplayCommand> CreateReplaceWithAnnotationsCommands (bool byUid, out List<ReplaceRequest> requests)
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate+replace.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
commands.Add (new ImapReplayCommand ("A00000004 SELECT INBOX (CONDSTORE ANNOTATE)\r\n", "common.select-inbox-annotate.txt"));
var command = new StringBuilder ();
int id = 5;
requests = new List<ReplaceRequest> ();
for (int i = 0; i < 8; i++) {
MimeMessage message;
string latin1;
long length;
using (var resource = GetResourceStream (string.Format ("common.message.{0}.msg", i)))
message = MimeMessage.Load (resource);
var annotation = new Annotation (AnnotationEntry.AltSubject);
annotation.Properties[AnnotationAttribute.PrivateValue] = string.Format ("Alternate subject {0}", i);
requests.Add (new ReplaceRequest (message, MessageFlags.Seen) {
Annotations = new Annotation[] { annotation }
});
using (var stream = new MemoryStream ()) {
var options = FormatOptions.Default.Clone ();
options.NewLineFormat = NewLineFormat.Dos;
options.EnsureNewLine = true;
message.WriteTo (options, stream);
length = stream.Length;
stream.Position = 0;
using (var reader = new StreamReader (stream, Latin1))
latin1 = reader.ReadToEnd ();
}
var tag = string.Format ("A{0:D8}", id++);
command.Clear ();
command.AppendFormat ("{0} {1} {2} INBOX (\\Seen) ", tag, byUid ? "UID REPLACE" : "REPLACE", i + 1);
command.AppendFormat ("ANNOTATION (/altsubject (value.priv \"Alternate subject {0}\")) ", i);
command.Append ('{').Append (length.ToString ()).Append ("+}\r\n").Append (latin1).Append ("\r\n");
commands.Add (new ImapReplayCommand (command.ToString (), string.Format ("dovecot.append.{0}.txt", i + 1)));
}
commands.Add (new ImapReplayCommand (string.Format ("A{0:D8} LOGOUT\r\n", id), "gmail.logout.txt"));
return commands;
}
[Test]
public void TestReplaceWithAnnotations ()
{
var commands = CreateReplaceWithAnnotationsCommands (false, out var requests);
using (var client = new ImapClient ()) {
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate ("username", "password");
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
client.Inbox.Open (FolderAccess.ReadWrite);
for (int i = 0; i < requests.Count; i++) {
var uid = client.Inbox.Replace (i, requests[i]);
Assert.IsTrue (uid.HasValue, "Expected a UIDAPPEND resp-code");
Assert.AreEqual (i + 1, uid.Value.Id, "Unexpected UID");
requests[i].Message.Dispose ();
}
client.Disconnect (true);
}
}
[Test]
public async Task TestReplaceWithAnnotationsAsync ()
{
var commands = CreateReplaceWithAnnotationsCommands (false, out var requests);
using (var client = new ImapClient ()) {
try {
await client.ReplayConnectAsync ("localhost", new ImapReplayStream (commands, true));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
client.AuthenticationMechanisms.Clear ();
try {
await client.AuthenticateAsync ("username", "password");
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
await client.Inbox.OpenAsync (FolderAccess.ReadWrite);
for (int i = 0; i < requests.Count; i++) {
var uid = await client.Inbox.ReplaceAsync (i, requests[i]);
Assert.IsTrue (uid.HasValue, "Expected a UIDAPPEND resp-code");
Assert.AreEqual (i + 1, uid.Value.Id, "Unexpected UID");
requests[i].Message.Dispose ();
}
await client.DisconnectAsync (true);
}
}
[Test]
public void TestReplaceByUidWithAnnotations ()
{
var commands = CreateReplaceWithAnnotationsCommands (true, out var requests);
using (var client = new ImapClient ()) {
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate ("username", "password");
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
client.Inbox.Open (FolderAccess.ReadWrite);
for (int i = 0; i < requests.Count; i++) {
var uid = client.Inbox.Replace (new UniqueId ((uint) i + 1), requests[i]);
Assert.IsTrue (uid.HasValue, "Expected a UIDAPPEND resp-code");
Assert.AreEqual (i + 1, uid.Value.Id, "Unexpected UID");
requests[i].Message.Dispose ();
}
client.Disconnect (true);
}
}
[Test]
public async Task TestReplaceByUidWithAnnotationsAsync ()
{
var commands = CreateReplaceWithAnnotationsCommands (true, out var requests);
using (var client = new ImapClient ()) {
try {
await client.ReplayConnectAsync ("localhost", new ImapReplayStream (commands, true));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
client.AuthenticationMechanisms.Clear ();
try {
await client.AuthenticateAsync ("username", "password");
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
await client.Inbox.OpenAsync (FolderAccess.ReadWrite);
for (int i = 0; i < requests.Count; i++) {
var uid = await client.Inbox.ReplaceAsync (new UniqueId ((uint) i + 1), requests[i]);
Assert.IsTrue (uid.HasValue, "Expected a UIDAPPEND resp-code");
Assert.AreEqual (i + 1, uid.Value.Id, "Unexpected UID");
requests[i].Message.Dispose ();
}
await client.DisconnectAsync (true);
}
}
[Test]
public void TestSelectAnnotateNone ()
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
commands.Add (new ImapReplayCommand ("A00000004 SELECT INBOX (CONDSTORE ANNOTATE)\r\n", "common.select-inbox-annotate-none.txt"));
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
inbox.Open (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.None, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.None, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (0, inbox.MaxAnnotationSize, "MaxAnnotationSize");
client.Disconnect (false);
}
}
List<ImapReplayCommand> CreateSearchAnnotationsCommands ()
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
commands.Add (new ImapReplayCommand ("A00000004 SELECT INBOX (CONDSTORE ANNOTATE)\r\n", "common.select-inbox-annotate-readonly.txt"));
commands.Add (new ImapReplayCommand ("A00000005 UID SEARCH RETURN (ALL) ANNOTATION /comment value \"a comment\"\r\n", "dovecot.search-uids.txt"));
return commands;
}
[Test]
public void TestSearchAnnotations ()
{
var commands = CreateSearchAnnotationsCommands ();
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
inbox.Open (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadOnly, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Both, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (0, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var query = SearchQuery.AnnotationsContain (AnnotationEntry.Comment, AnnotationAttribute.Value, "a comment");
var uids = inbox.Search (query);
Assert.AreEqual (14, uids.Count, "Unexpected number of UIDs");
// disable ANNOTATE-EXPERIMENT-1 and try again
client.Capabilities &= ~ImapCapabilities.Annotate;
Assert.Throws<NotSupportedException> (() => inbox.Search (query));
client.Disconnect (false);
}
}
[Test]
public async Task TestSearchAnnotationsAsync ()
{
var commands = CreateSearchAnnotationsCommands ();
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
await client.ReplayConnectAsync ("localhost", new ImapReplayStream (commands, true));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
await client.AuthenticateAsync (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
await inbox.OpenAsync (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadOnly, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Both, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (0, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var query = SearchQuery.AnnotationsContain (AnnotationEntry.Comment, AnnotationAttribute.Value, "a comment");
var uids = await inbox.SearchAsync (query);
Assert.AreEqual (14, uids.Count, "Unexpected number of UIDs");
// disable ANNOTATE-EXPERIMENT-1 and try again
client.Capabilities &= ~ImapCapabilities.Annotate;
Assert.ThrowsAsync<NotSupportedException> (() => inbox.SearchAsync (query));
await client.DisconnectAsync (false);
}
}
List<ImapReplayCommand> CreateSortAnnotationsCommands ()
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
commands.Add (new ImapReplayCommand ("A00000004 SELECT INBOX (CONDSTORE ANNOTATE)\r\n", "common.select-inbox-annotate-readonly.txt"));
commands.Add (new ImapReplayCommand ("A00000005 UID SORT RETURN (ALL) (ANNOTATION /altsubject value.shared) US-ASCII ALL\r\n", "dovecot.sort-by-strings.txt"));
commands.Add (new ImapReplayCommand ("A00000006 UID SORT RETURN (ALL) (REVERSE ANNOTATION /altsubject value.shared) US-ASCII ALL\r\n", "dovecot.sort-by-strings.txt"));
return commands;
}
[Test]
public void TestSortAnnotations ()
{
var commands = CreateSortAnnotationsCommands ();
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
inbox.Open (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadOnly, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Both, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (0, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var orderBy = new OrderByAnnotation (AnnotationEntry.AltSubject, AnnotationAttribute.SharedValue, SortOrder.Ascending);
var uids = inbox.Sort (SearchQuery.All, new OrderBy[] { orderBy });
Assert.AreEqual (14, uids.Count, "Unexpected number of UIDs");
orderBy = new OrderByAnnotation (AnnotationEntry.AltSubject, AnnotationAttribute.SharedValue, SortOrder.Descending);
uids = inbox.Sort (SearchQuery.All, new OrderBy[] { orderBy });
Assert.AreEqual (14, uids.Count, "Unexpected number of UIDs");
// disable ANNOTATE-EXPERIMENT-1 and try again
client.Capabilities &= ~ImapCapabilities.Annotate;
Assert.Throws<NotSupportedException> (() => inbox.Sort (SearchQuery.All, new OrderBy[] { orderBy }));
client.Disconnect (false);
}
}
[Test]
public async Task TestSortAnnotationsAsync ()
{
var commands = CreateSortAnnotationsCommands ();
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
await client.ReplayConnectAsync ("localhost", new ImapReplayStream (commands, true));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
await client.AuthenticateAsync (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
await inbox.OpenAsync (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadOnly, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Both, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (0, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var orderBy = new OrderByAnnotation (AnnotationEntry.AltSubject, AnnotationAttribute.SharedValue, SortOrder.Ascending);
var uids = await inbox.SortAsync (SearchQuery.All, new OrderBy[] { orderBy });
Assert.AreEqual (14, uids.Count, "Unexpected number of UIDs");
orderBy = new OrderByAnnotation (AnnotationEntry.AltSubject, AnnotationAttribute.SharedValue, SortOrder.Descending);
uids = await inbox.SortAsync (SearchQuery.All, new OrderBy[] { orderBy });
Assert.AreEqual (14, uids.Count, "Unexpected number of UIDs");
// disable ANNOTATE-EXPERIMENT-1 and try again
client.Capabilities &= ~ImapCapabilities.Annotate;
Assert.ThrowsAsync<NotSupportedException> (() => inbox.SortAsync (SearchQuery.All, new OrderBy[] { orderBy }));
await client.DisconnectAsync (false);
}
}
List<ImapReplayCommand> CreateStoreCommands ()
{
var commands = new List<ImapReplayCommand> ();
commands.Add (new ImapReplayCommand ("", "dovecot.greeting.txt"));
commands.Add (new ImapReplayCommand ("A00000000 LOGIN username password\r\n", "dovecot.authenticate+annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000001 NAMESPACE\r\n", "dovecot.namespace.txt"));
commands.Add (new ImapReplayCommand ("A00000002 LIST \"\" \"INBOX\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-inbox.txt"));
commands.Add (new ImapReplayCommand ("A00000003 LIST (SPECIAL-USE) \"\" \"*\" RETURN (SUBSCRIBED CHILDREN)\r\n", "dovecot.list-special-use.txt"));
commands.Add (new ImapReplayCommand ("A00000004 SELECT INBOX (CONDSTORE ANNOTATE)\r\n", "common.select-inbox-annotate.txt"));
commands.Add (new ImapReplayCommand ("A00000005 STORE 1 ANNOTATION (/altsubject (value.shared \"This is an alternate subject.\"))\r\n", ImapReplayCommandResponse.OK));
commands.Add (new ImapReplayCommand ("A00000006 UID STORE 1 ANNOTATION (/altsubject (value.shared \"This is an alternate subject.\"))\r\n", ImapReplayCommandResponse.OK));
commands.Add (new ImapReplayCommand ("A00000007 STORE 1 ANNOTATION (/altsubject (value.shared NIL))\r\n", ImapReplayCommandResponse.OK));
commands.Add (new ImapReplayCommand ("A00000008 UID STORE 1 ANNOTATION (/altsubject (value.shared NIL))\r\n", ImapReplayCommandResponse.OK));
return commands;
}
[Test]
public void TestStore ()
{
var commands = CreateStoreCommands ();
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
client.ReplayConnect ("localhost", new ImapReplayStream (commands, false));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
client.Authenticate (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
inbox.Open (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadWrite, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Shared, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (20480, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var annotation = new Annotation (AnnotationEntry.AltSubject);
annotation.Properties.Add (AnnotationAttribute.SharedValue, "This is an alternate subject.");
var annotations = new [] { annotation };
inbox.Store (0, annotations);
inbox.Store (new UniqueId (1), annotations);
annotation.Properties[AnnotationAttribute.SharedValue] = null;
inbox.Store (0, annotations);
inbox.Store (new UniqueId (1), annotations);
client.Disconnect (false);
}
}
[Test]
public async Task TestStoreAsync ()
{
var commands = CreateStoreCommands ();
using (var client = new ImapClient ()) {
var credentials = new NetworkCredential ("username", "password");
try {
await client.ReplayConnectAsync ("localhost", new ImapReplayStream (commands, true));
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Connect: {0}", ex);
}
// Note: we do not want to use SASL at all...
client.AuthenticationMechanisms.Clear ();
try {
await client.AuthenticateAsync (credentials);
} catch (Exception ex) {
Assert.Fail ("Did not expect an exception in Authenticate: {0}", ex);
}
Assert.IsInstanceOf<ImapEngine> (client.Inbox.SyncRoot, "SyncRoot");
var inbox = (ImapFolder) client.Inbox;
await inbox.OpenAsync (FolderAccess.ReadWrite);
Assert.AreEqual (AnnotationAccess.ReadWrite, inbox.AnnotationAccess, "AnnotationAccess");
Assert.AreEqual (AnnotationScope.Shared, inbox.AnnotationScopes, "AnnotationScopes");
Assert.AreEqual (20480, inbox.MaxAnnotationSize, "MaxAnnotationSize");
var annotation = new Annotation (AnnotationEntry.AltSubject);
annotation.Properties.Add (AnnotationAttribute.SharedValue, "This is an alternate subject.");
var annotations = new[] { annotation };
await inbox.StoreAsync (0, annotations);
await inbox.StoreAsync (new UniqueId (1), annotations);
annotation.Properties[AnnotationAttribute.SharedValue] = null;
await inbox.StoreAsync (0, annotations);
await inbox.StoreAsync (new UniqueId (1), annotations);
await client.DisconnectAsync (false);
}
}
}
}
| {
"content_hash": "c1919e7ad200638d82de245a1bf0c2c6",
"timestamp": "",
"source": "github",
"line_count": 1184,
"max_line_length": 223,
"avg_line_length": 40.551520270270274,
"alnum_prop": 0.6977276987482557,
"repo_name": "jstedfast/MailKit",
"id": "33989e89d8189c744282485264b505071e1f2d3b",
"size": "48015",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UnitTests/Net/Imap/ImapFolderAnnotationsTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "177"
},
{
"name": "C#",
"bytes": "5965972"
},
{
"name": "PowerShell",
"bytes": "8949"
}
],
"symlink_target": ""
} |
package org.jasig.cas.ticket.registry.support.kryo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import net.spy.memcached.CachedData;
import net.spy.memcached.transcoders.Transcoder;
import org.jasig.cas.authentication.BasicCredentialMetaData;
import org.jasig.cas.authentication.DefaultHandlerResult;
import org.jasig.cas.authentication.ImmutableAuthentication;
import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl;
import org.jasig.cas.services.RegexRegisteredService;
import org.jasig.cas.services.RegisteredServiceImpl;
import org.jasig.cas.ticket.ServiceTicketImpl;
import org.jasig.cas.ticket.TicketGrantingTicketImpl;
import org.jasig.cas.ticket.registry.support.kryo.serial.RegisteredServiceSerializer;
import org.jasig.cas.ticket.registry.support.kryo.serial.SimpleWebApplicationServiceSerializer;
import org.jasig.cas.ticket.registry.support.kryo.serial.URLSerializer;
import org.jasig.cas.ticket.support.HardTimeoutExpirationPolicy;
import org.jasig.cas.ticket.support.MultiTimeUseOrTimeoutExpirationPolicy;
import org.jasig.cas.ticket.support.NeverExpiresExpirationPolicy;
import org.jasig.cas.ticket.support.RememberMeDelegatingExpirationPolicy;
import org.jasig.cas.ticket.support.ThrottledUseAndTimeoutExpirationPolicy;
import org.jasig.cas.ticket.support.TicketGrantingTicketExpirationPolicy;
import org.jasig.cas.ticket.support.TimeoutExpirationPolicy;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.DefaultSerializers;
import de.javakaffee.kryoserializers.UnmodifiableCollectionsSerializer;
import de.javakaffee.kryoserializers.jodatime.JodaDateTimeSerializer;
import org.slf4j.impl.CasDelegatingLogger;
/**
* {@link net.spy.memcached.MemcachedClient} transcoder implementation based on Kryo fast serialization framework
* suited for efficient serialization of tickets.
*
* @author Marvin S. Addison
* @since 3.0.0
*/
@SuppressWarnings("rawtypes")
public class KryoTranscoder implements Transcoder<Object> {
/** Kryo serializer. */
private final Kryo kryo = new Kryo();
/** Logging instance. */
private final Logger logger = LoggerFactory.getLogger(getClass());
/** Map of class to serializer that handles it. */
private Map<Class<?>, Serializer> serializerMap;
/**
* Creates a Kryo-based transcoder.
*/
public KryoTranscoder() {
}
/**
* Sets a map of additional types that should be regisetered with Kryo,
* for example GoogleAccountsService and OpenIdService.
*
* @param map Map of class to the serializer instance that handles it.
*/
public void setSerializerMap(final Map<Class<?>, Serializer> map) {
this.serializerMap = map;
}
/**
* Initialize and register classes with kryo.
*/
public void initialize() {
// Register types we know about and do not require external configuration
kryo.register(ArrayList.class);
kryo.register(BasicCredentialMetaData.class);
kryo.register(Class.class, new DefaultSerializers.ClassSerializer());
kryo.register(Date.class, new DefaultSerializers.DateSerializer());
kryo.register(HardTimeoutExpirationPolicy.class);
kryo.register(HashMap.class);
kryo.register(DefaultHandlerResult.class);
kryo.register(ImmutableAuthentication.class);
kryo.register(MultiTimeUseOrTimeoutExpirationPolicy.class);
kryo.register(NeverExpiresExpirationPolicy.class);
kryo.register(RememberMeDelegatingExpirationPolicy.class);
kryo.register(ServiceTicketImpl.class);
kryo.register(SimpleWebApplicationServiceImpl.class, new SimpleWebApplicationServiceSerializer());
kryo.register(ThrottledUseAndTimeoutExpirationPolicy.class);
kryo.register(TicketGrantingTicketExpirationPolicy.class);
kryo.register(TicketGrantingTicketImpl.class);
kryo.register(TimeoutExpirationPolicy.class);
kryo.register(URL.class, new URLSerializer());
// we add these ones for tests only
kryo.register(RegisteredServiceImpl.class, new RegisteredServiceSerializer());
kryo.register(RegexRegisteredService.class, new RegisteredServiceSerializer());
// new serializers to manage Joda dates and immutable collections
kryo.register(DateTime.class, new JodaDateTimeSerializer());
kryo.register(CasDelegatingLogger.class, new DefaultSerializers.VoidSerializer());
// from the kryo-serializers library (https://github.com/magro/kryo-serializers)
UnmodifiableCollectionsSerializer.registerSerializers(kryo);
// Register other types
if (serializerMap != null) {
for (final Map.Entry<Class<?>, Serializer> clazz : serializerMap.entrySet()) {
kryo.register(clazz.getKey(), clazz.getValue());
}
}
// don't reinit the registered classes after every write or read
kryo.setAutoReset(false);
// don't replace objects by references
kryo.setReferences(false);
// Catchall for any classes not explicitly registered
kryo.setRegistrationRequired(false);
}
/**
* Asynchronous decoding is not supported.
*
* @param d Data to decode.
* @return False.
*/
@Override
public boolean asyncDecode(final CachedData d) {
return false;
}
@Override
public CachedData encode(final Object obj) {
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try (final Output output = new Output(byteStream)) {
kryo.writeClassAndObject(output, obj);
output.flush();
final byte[] bytes = byteStream.toByteArray();
return new CachedData(0, bytes, bytes.length);
}
}
@Override
public Object decode(final CachedData d) {
final byte[] bytes = d.getData();
try (final Input input = new Input(new ByteArrayInputStream(bytes))) {
final Object obj = kryo.readClassAndObject(input);
return obj;
}
}
/**
* Maximum size of encoded data supported by this transcoder.
*
* @return <code>net.spy.memcached.CachedData#MAX_SIZE</code>.
*/
@Override
public int getMaxSize() {
return CachedData.MAX_SIZE;
}
/**
* Gets the kryo object that provides encoding and decoding services for this instance.
*
* @return Underlying Kryo instance.
*/
public Kryo getKryo() {
return kryo;
}
}
| {
"content_hash": "e2ce28ba293bdf3cf6ff696125856e3d",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 113,
"avg_line_length": 38.22099447513812,
"alnum_prop": 0.7263660017346054,
"repo_name": "DICE-UNC/cas",
"id": "0658287629259079f25cc6c2911c2d6ff9d0a1e8",
"size": "7716",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cas-server-integration-memcached/src/main/java/org/jasig/cas/ticket/registry/support/kryo/KryoTranscoder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "196889"
},
{
"name": "HTML",
"bytes": "30670"
},
{
"name": "Java",
"bytes": "3256648"
},
{
"name": "JavaScript",
"bytes": "46646"
},
{
"name": "Shell",
"bytes": "8412"
}
],
"symlink_target": ""
} |
<?php
namespace ZF\ContentNegotiation\Filter;
use DirectoryIterator;
use PHPUnit_Framework_TestCase as TestCase;
use Zend\Http\Request as HttpRequest;
use ZF\ContentNegotiation\Request;
class RenameUploadTest extends TestCase
{
public function setUp()
{
$this->tmpDir = sys_get_temp_dir() . '/zf-content-negotiation-filter';
$this->uploadDir = $this->tmpDir . '/upload';
$this->targetDir = $this->tmpDir . '/target';
$this->tearDown();
mkdir($this->tmpDir);
mkdir($this->uploadDir);
mkdir($this->targetDir);
}
public function tearDown()
{
if (! is_dir($this->tmpDir)) {
return;
}
if (is_dir($this->uploadDir)) {
$this->removeDir($this->uploadDir);
}
if (is_dir($this->targetDir)) {
$this->removeDir($this->targetDir);
}
rmdir($this->tmpDir);
}
public function createUploadFile()
{
$filename = tempnam($this->uploadDir, 'zfc');
file_put_contents($filename, sprintf('File created by %s', __CLASS__));
$file = [
'name' => 'test.txt',
'type' => 'text/plain',
'tmp_name' => $filename,
'size' => filesize($filename),
'error' => UPLOAD_ERR_OK,
];
return $file;
}
public function removeDir($dir)
{
$it = new DirectoryIterator($dir);
foreach ($it as $file) {
if ($file->isDot()) {
continue;
}
if ($file->isDir()) {
$this->removeDir($file->getPathname());
continue;
}
unlink($file->getPathname());
}
unset($it);
rmdir($dir);
}
public function uploadMethods()
{
return [
'put' => ['PUT'],
'patch' => ['PATCH'],
];
}
/**
* @dataProvider uploadMethods
*/
public function testMoveUploadedFileSucceedsOnPutAndPatchHttpRequests($method)
{
$target = $this->targetDir . '/uploaded.txt';
$file = $this->createUploadFile();
$request = new HttpRequest();
$request->setMethod($method);
$filter = new RenameUpload($target);
$filter->setRequest($request);
$result = $filter->filter($file);
$this->assertInternalType('array', $result);
$this->assertArrayHasKey('tmp_name', $result);
$this->assertEquals($target, $result['tmp_name']);
$this->assertTrue(file_exists($target));
$this->assertFalse(file_exists($file['tmp_name']));
}
}
| {
"content_hash": "9eeb5e0e9003eb665c01d8a15413feaf",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 82,
"avg_line_length": 25.87378640776699,
"alnum_prop": 0.5193245778611633,
"repo_name": "pereiracruz2002/apiphp",
"id": "acb11dca666d5b200519b1705087ead9bfa29b3c",
"size": "2825",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "vendor/zfcampus/zf-content-negotiation/test/Filter/RenameUploadTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "711"
},
{
"name": "HTML",
"bytes": "7550"
},
{
"name": "PHP",
"bytes": "47234"
},
{
"name": "Shell",
"bytes": "928"
},
{
"name": "Smarty",
"bytes": "720"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. -->
<title>Canvas test: 2d.drawImage.svg</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/html/canvas/resources/canvas-tests.js"></script>
<link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css">
<body class="show_output">
<h1>2d.drawImage.svg</h1>
<p class="desc">drawImage() of an SVG image</p>
<p class="output">Actual output:</p>
<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
<p class="output expectedtext">Expected output:<p><img src="/images/green-100x50.png" class="output expected" id="expected" alt="">
<ul id="d"></ul>
<script>
var t = async_test("drawImage() of an SVG image");
_addTest(function(canvas, ctx) {
ctx.drawImage(document.getElementById('green.svg'), 0, 0);
_assertPixelApprox(canvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255", 2);
});
</script>
<img src="/images/green.svg" id="green.svg" class="resource">
| {
"content_hash": "e6363315802c1c6f147572ce4fc83122",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 131,
"avg_line_length": 37.724137931034484,
"alnum_prop": 0.6983546617915904,
"repo_name": "nwjs/chromium.src",
"id": "6c12a6bdccaed00338a080ffb303ad23eab7666d",
"size": "1094",
"binary": false,
"copies": "13",
"ref": "refs/heads/nw70",
"path": "third_party/blink/web_tests/external/wpt/html/canvas/element/drawing-images-to-the-canvas/2d.drawImage.svg.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package ch.heigvd.amt.selenium.pages;
import org.openqa.selenium.WebDriver;
/**
* This file will be used later to manage the site navigation.
*
* @author Mario Ferreira
*/
public abstract class AbstractMoussaRaserPage extends Page {
public AbstractMoussaRaserPage(WebDriver driver) {
super(driver);
}
}
| {
"content_hash": "7139cef5339e090e32876337b4d094b3",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 62,
"avg_line_length": 21.733333333333334,
"alnum_prop": 0.7300613496932515,
"repo_name": "Kjnokeer/Teaching-HEIGVD-AMT-2015-Project",
"id": "f62aa4afe508a1927b15675d7a72fb18d6b40daa",
"size": "326",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projet/MoussaRaserTest/MoussaRaserTests/src/test/java/ch/heigvd/amt/selenium/pages/AbstractMoussaRaserPage.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "140042"
},
{
"name": "HTML",
"bytes": "149911"
},
{
"name": "Java",
"bytes": "221761"
},
{
"name": "JavaScript",
"bytes": "114635"
},
{
"name": "PHP",
"bytes": "44609"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b48e3da42f3c592bac2a2159f1b40678",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "4d51a111caf76da5f84bb77fad540d51c8f175fd",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Bielschmeidia/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace TypiCMS\Modules\Roles\Repositories;
use TypiCMS\Modules\Core\Repositories\RepositoryInterface;
interface RoleInterface extends RepositoryInterface
{
}
| {
"content_hash": "1fa33d1f6b50e709a9a018c2e2d9e40c",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 58,
"avg_line_length": 18.88888888888889,
"alnum_prop": 0.8411764705882353,
"repo_name": "laravelproject2016/mkproject",
"id": "4d8a6197fdd5a98f5db78463a96051cd6381914a",
"size": "170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/typicms/roles/src/Repositories/RoleInterface.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "358573"
},
{
"name": "HTML",
"bytes": "15175"
},
{
"name": "JavaScript",
"bytes": "241902"
},
{
"name": "PHP",
"bytes": "228416"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/motine/Ohouse)
This is/shall a Clearinghouse for all the projects mentioned.
# Moved!
Since I am not part of the development any more, this project has been renamed to [C-BAS] and moved [here](https://github.com/zanetworker/C-BAS).
## Installation
### Environment
This software is based on AMsoil, please refer to the [installation guide there](https://github.com/fp7-ofelia/amsoil/wiki/Installation).
Please follow at least the "Base" and "Plugins" steps.
### Dependencies
Please install [Swig](http://www.swig.org/) (needed for the M2Crypto Python package). Ohouse currently relies on a [MongoDB](mongodb.org) database running on the local host (and default port).
Python dependencies can then be installed using `pip install -r requirements.txt`.
## Run
Fire up the server via `python src/main.py` and install the packages which are not found.
Note that sometimes the output is only given to the log in `log/amsoil.log`.
### Additional
* Copy the following files and adust the entries as required
* The `deploy/config.json.example` to `deploy/config.json`
* The `deploy/registry.json.example` to `deploy/registry.json`
* The `deploy/supplementary_fields.json.example` to `deploy/supplimentary_fields.json`
* Either
* Install trust root certificates to `deploy/trust` (as pem) and a admin cert (`admin-key.pem` and `admin-cert.pem`) to `admin`.
* Or create test certificates and credentials and copy them to the respective places (see `test/creds/TODO.md`).
* Run the server with `python src/main.py`
* In a new cosole run the config client `python admin/config_client.py --interactive` and make change according to your setup
### Test drive
You may run the `xx_tests.py` scripts in `test/unit` to make sure everything works fine.
The test scripts assume that there are test certificates and credentials in `test/creds` (for creating them please see `test/creds/TODO.md`).
## Architectural decisions
* Please see the `ofed` - `plugin.py` for considerations on how to protect information regarding authZ.
* Ohouse will support both [v1](http://groups.geni.net/geni/wiki/UniformClearinghouseAPI) and [v2](http://groups.geni.net/geni/wiki/UniformClearinghouseAPIV2) of the Uniform Clearinghouse API. This is realised through different service endpoints for each version.
| {
"content_hash": "cfb5cc51200d6c9886809e54db4b917c",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 263,
"avg_line_length": 49.224489795918366,
"alnum_prop": 0.7574626865671642,
"repo_name": "motine/Ohouse",
"id": "62c0f6ce06f89fa24ba19bd8c678d8be9b2b2219",
"size": "2433",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "265931"
},
{
"name": "Shell",
"bytes": "520"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!-- Do not modify this file directly. Instead, copy entries that you -->
<!-- wish to modify from this file into mapred-site.xml and change them -->
<!-- there. If mapred-site.xml does not already exist, create it. -->
<configuration>
<property>
<name>hadoop.job.history.location</name>
<value></value>
<description> If job tracker is static the history files are stored
in this single well known place. If No value is set here, by default,
it is in the local file system at ${hadoop.log.dir}/history.
</description>
</property>
<property>
<name>hadoop.job.history.user.location</name>
<value></value>
<description> User can specify a location to store the history files of
a particular job. If nothing is specified, the logs are stored in
output directory. The files are stored in "_logs/history/" in the directory.
User can stop logging by giving the value "none".
</description>
</property>
<property>
<name>mapred.job.tracker.history.completed.location</name>
<value></value>
<description> The completed job history files are stored at this single well
known location. If nothing is specified, the files are stored at
${hadoop.job.history.location}/done.
</description>
</property>
<!-- i/o properties -->
<property>
<name>io.sort.factor</name>
<value>10</value>
<description>The number of streams to merge at once while sorting
files. This determines the number of open file handles.</description>
</property>
<property>
<name>io.sort.mb</name>
<value>100</value>
<description>The total amount of buffer memory to use while sorting
files, in megabytes. By default, gives each merge stream 1MB, which
should minimize seeks.</description>
</property>
<property>
<name>io.sort.record.percent</name>
<value>0.05</value>
<description>The percentage of io.sort.mb dedicated to tracking record
boundaries. Let this value be r, io.sort.mb be x. The maximum number
of records collected before the collection thread must block is equal
to (r * x) / 4</description>
</property>
<property>
<name>io.sort.spill.percent</name>
<value>0.80</value>
<description>The soft limit in either the buffer or record collection
buffers. Once reached, a thread will begin to spill the contents to disk
in the background. Note that this does not imply any chunking of data to
the spill. A value less than 0.5 is not recommended.</description>
</property>
<property>
<name>io.map.index.skip</name>
<value>0</value>
<description>Number of index entries to skip between each entry.
Zero by default. Setting this to values larger than zero can
facilitate opening large map files using less memory.</description>
</property>
<property>
<name>mapred.job.tracker</name>
<value>local</value>
<description>The host and port that the MapReduce job tracker runs
at. If "local", then jobs are run in-process as a single map
and reduce task.
</description>
</property>
<property>
<name>mapred.job.tracker.http.address</name>
<value>0.0.0.0:50030</value>
<description>
The job tracker http server address and port the server will listen on.
If the port is 0 then the server will start on a free port.
</description>
</property>
<property>
<name>mapred.job.tracker.handler.count</name>
<value>10</value>
<description>
The number of server threads for the JobTracker. This should be roughly
4% of the number of tasktracker nodes.
</description>
</property>
<property>
<name>mapred.task.tracker.report.address</name>
<value>127.0.0.1:0</value>
<description>The interface and port that task tracker server listens on.
Since it is only connected to by the tasks, it uses the local interface.
EXPERT ONLY. Should only be changed if your host does not have the loopback
interface.</description>
</property>
<property>
<name>mapred.local.dir</name>
<value>${hadoop.tmp.dir}/mapred/local</value>
<description>The local directory where MapReduce stores intermediate
data files. May be a comma-separated list of
directories on different devices in order to spread disk i/o.
Directories that do not exist are ignored.
</description>
</property>
<property>
<name>mapred.system.dir</name>
<value>${hadoop.tmp.dir}/mapred/system</value>
<description>The shared directory where MapReduce stores control files.
</description>
</property>
<property>
<name>mapred.temp.dir</name>
<value>${hadoop.tmp.dir}/mapred/temp</value>
<description>A shared directory for temporary files.
</description>
</property>
<property>
<name>mapred.local.dir.minspacestart</name>
<value>0</value>
<description>If the space in mapred.local.dir drops under this,
do not ask for more tasks.
Value in bytes.
</description>
</property>
<property>
<name>mapred.local.dir.minspacekill</name>
<value>0</value>
<description>If the space in mapred.local.dir drops under this,
do not ask more tasks until all the current ones have finished and
cleaned up. Also, to save the rest of the tasks we have running,
kill one of them, to clean up some space. Start with the reduce tasks,
then go with the ones that have finished the least.
Value in bytes.
</description>
</property>
<property>
<name>mapred.tasktracker.expiry.interval</name>
<value>600000</value>
<description>Expert: The time-interval, in miliseconds, after which
a tasktracker is declared 'lost' if it doesn't send heartbeats.
</description>
</property>
<property>
<name>mapred.tasktracker.instrumentation</name>
<value>org.apache.hadoop.mapred.TaskTrackerMetricsInst</value>
<description>Expert: The instrumentation class to associate with each TaskTracker.
</description>
</property>
<property>
<name>mapred.tasktracker.memory_calculator_plugin</name>
<value></value>
<description>
Name of the class whose instance will be used to query memory information
on the tasktracker.
The class must be an instance of
org.apache.hadoop.util.MemoryCalculatorPlugin. If the value is null, the
tasktracker attempts to use a class appropriate to the platform.
Currently, the only platform supported is Linux.
</description>
</property>
<property>
<name>mapred.tasktracker.taskmemorymanager.monitoring-interval</name>
<value>5000</value>
<description>The interval, in milliseconds, for which the tasktracker waits
between two cycles of monitoring its tasks' memory usage. Used only if
tasks' memory management is enabled via mapred.tasktracker.tasks.maxmemory.
</description>
</property>
<property>
<name>mapred.tasktracker.tasks.sleeptime-before-sigkill</name>
<value>5000</value>
<description>The time, in milliseconds, the tasktracker waits for sending a
SIGKILL to a process, after it has been sent a SIGTERM.</description>
</property>
<property>
<name>mapred.map.tasks</name>
<value>2</value>
<description>The default number of map tasks per job.
Ignored when mapred.job.tracker is "local".
</description>
</property>
<property>
<name>mapred.reduce.tasks</name>
<value>1</value>
<description>The default number of reduce tasks per job. Typically set to 99%
of the cluster's reduce capacity, so that if a node fails the reduces can
still be executed in a single wave.
Ignored when mapred.job.tracker is "local".
</description>
</property>
<property>
<name>mapreduce.tasktracker.outofband.heartbeat</name>
<value>false</value>
<description>Expert: Set this to true to let the tasktracker send an
out-of-band heartbeat on task-completion for better latency.
</description>
</property>
<property>
<name>mapred.jobtracker.restart.recover</name>
<value>false</value>
<description>"true" to enable (job) recovery upon restart,
"false" to start afresh
</description>
</property>
<property>
<name>mapred.jobtracker.job.history.block.size</name>
<value>3145728</value>
<description>The block size of the job history file. Since the job recovery
uses job history, its important to dump job history to disk as
soon as possible. Note that this is an expert level parameter.
The default value is set to 3 MB.
</description>
</property>
<property>
<name>mapred.jobtracker.taskScheduler</name>
<value>org.apache.hadoop.mapred.JobQueueTaskScheduler</value>
<description>The class responsible for scheduling the tasks.</description>
</property>
<property>
<name>mapred.jobtracker.taskScheduler.maxRunningTasksPerJob</name>
<value></value>
<description>The maximum number of running tasks for a job before
it gets preempted. No limits if undefined.
</description>
</property>
<property>
<name>mapred.map.max.attempts</name>
<value>4</value>
<description>Expert: The maximum number of attempts per map task.
In other words, framework will try to execute a map task these many number
of times before giving up on it.
</description>
</property>
<property>
<name>mapred.reduce.max.attempts</name>
<value>4</value>
<description>Expert: The maximum number of attempts per reduce task.
In other words, framework will try to execute a reduce task these many number
of times before giving up on it.
</description>
</property>
<property>
<name>mapred.reduce.parallel.copies</name>
<value>5</value>
<description>The default number of parallel transfers run by reduce
during the copy(shuffle) phase.
</description>
</property>
<property>
<name>mapred.reduce.copy.backoff</name>
<value>300</value>
<description>The maximum amount of time (in seconds) a reducer spends on
fetching one map output before declaring it as failed.
</description>
</property>
<property>
<name>mapreduce.reduce.shuffle.connect.timeout</name>
<value>180000</value>
<description>Expert: The maximum amount of time (in milli seconds) a reduce
task spends in trying to connect to a tasktracker for getting map output.
</description>
</property>
<property>
<name>mapreduce.reduce.shuffle.read.timeout</name>
<value>180000</value>
<description>Expert: The maximum amount of time (in milli seconds) a reduce
task waits for map output data to be available for reading after obtaining
connection.
</description>
</property>
<property>
<name>mapred.task.timeout</name>
<value>600000</value>
<description>The number of milliseconds before a task will be
terminated if it neither reads an input, writes an output, nor
updates its status string.
</description>
</property>
<property>
<name>mapred.tasktracker.map.tasks.maximum</name>
<value>2</value>
<description>The maximum number of map tasks that will be run
simultaneously by a task tracker.
</description>
</property>
<property>
<name>mapred.tasktracker.reduce.tasks.maximum</name>
<value>2</value>
<description>The maximum number of reduce tasks that will be run
simultaneously by a task tracker.
</description>
</property>
<property>
<name>mapred.jobtracker.completeuserjobs.maximum</name>
<value>100</value>
<description>The maximum number of complete jobs per user to keep around
before delegating them to the job history.</description>
</property>
<property>
<name>mapred.job.tracker.retiredjobs.cache.size</name>
<value>1000</value>
<description>The number of retired job status to keep in the cache.
</description>
</property>
<property>
<name>mapred.job.tracker.jobhistory.lru.cache.size</name>
<value>5</value>
<description>The number of job history files loaded in memory. The jobs are
loaded when they are first accessed. The cache is cleared based on LRU.
</description>
</property>
<property>
<name>mapred.jobtracker.instrumentation</name>
<value>org.apache.hadoop.mapred.JobTrackerMetricsInst</value>
<description>Expert: The instrumentation class to associate with each JobTracker.
</description>
</property>
<property>
<name>mapred.child.java.opts</name>
<value>-Xmx200m</value>
<description>Java opts for the task tracker child processes.
The following symbol, if present, will be interpolated: @taskid@ is replaced
by current TaskID. Any other occurrences of '@' will go unchanged.
For example, to enable verbose gc logging to a file named for the taskid in
/tmp and to set the heap maximum to be a gigabyte, pass a 'value' of:
-Xmx1024m -verbose:gc -Xloggc:/tmp/@taskid@.gc
The configuration variable mapred.child.ulimit can be used to control the
maximum virtual memory of the child processes.
</description>
</property>
<property>
<name>mapred.child.env</name>
<value></value>
<description>User added environment variables for the task tracker child
processes. Example :
1) A=foo This will set the env variable A to foo
2) B=$B:c This is inherit tasktracker's B env variable.
</description>
</property>
<property>
<name>mapred.child.ulimit</name>
<value></value>
<description>The maximum virtual memory, in KB, of a process launched by the
Map-Reduce framework. This can be used to control both the Mapper/Reducer
tasks and applications using Hadoop Pipes, Hadoop Streaming etc.
By default it is left unspecified to let cluster admins control it via
limits.conf and other such relevant mechanisms.
Note: mapred.child.ulimit must be greater than or equal to the -Xmx passed to
JavaVM, else the VM might not start.
</description>
</property>
<property>
<name>mapred.child.tmp</name>
<value>./tmp</value>
<description> To set the value of tmp directory for map and reduce tasks.
If the value is an absolute path, it is directly assigned. Otherwise, it is
prepended with task's working directory. The java tasks are executed with
option -Djava.io.tmpdir='the absolute path of the tmp dir'. Pipes and
streaming are set with environment variable,
TMPDIR='the absolute path of the tmp dir'
</description>
</property>
<property>
<name>mapred.inmem.merge.threshold</name>
<value>1000</value>
<description>The threshold, in terms of the number of files
for the in-memory merge process. When we accumulate threshold number of files
we initiate the in-memory merge and spill to disk. A value of 0 or less than
0 indicates we want to DON'T have any threshold and instead depend only on
the ramfs's memory consumption to trigger the merge.
</description>
</property>
<property>
<name>mapred.job.shuffle.merge.percent</name>
<value>0.66</value>
<description>The usage threshold at which an in-memory merge will be
initiated, expressed as a percentage of the total memory allocated to
storing in-memory map outputs, as defined by
mapred.job.shuffle.input.buffer.percent.
</description>
</property>
<property>
<name>mapred.job.shuffle.input.buffer.percent</name>
<value>0.70</value>
<description>The percentage of memory to be allocated from the maximum heap
size to storing map outputs during the shuffle.
</description>
</property>
<property>
<name>mapred.job.reduce.input.buffer.percent</name>
<value>0.0</value>
<description>The percentage of memory- relative to the maximum heap size- to
retain map outputs during the reduce. When the shuffle is concluded, any
remaining map outputs in memory must consume less than this threshold before
the reduce can begin.
</description>
</property>
<property>
<name>mapred.map.tasks.speculative.execution</name>
<value>true</value>
<description>If true, then multiple instances of some map tasks
may be executed in parallel.</description>
</property>
<property>
<name>mapred.reduce.tasks.speculative.execution</name>
<value>true</value>
<description>If true, then multiple instances of some reduce tasks
may be executed in parallel.</description>
</property>
<property>
<name>mapred.job.reuse.jvm.num.tasks</name>
<value>1</value>
<description>How many tasks to run per jvm. If set to -1, there is
no limit.
</description>
</property>
<property>
<name>mapred.min.split.size</name>
<value>0</value>
<description>The minimum size chunk that map input should be split
into. Note that some file formats may have minimum split sizes that
take priority over this setting.</description>
</property>
<property>
<name>mapred.jobtracker.maxtasks.per.job</name>
<value>-1</value>
<description>The maximum number of tasks for a single job.
A value of -1 indicates that there is no maximum. </description>
</property>
<property>
<name>mapred.submit.replication</name>
<value>10</value>
<description>The replication level for submitted job files. This
should be around the square root of the number of nodes.
</description>
</property>
<property>
<name>mapred.tasktracker.dns.interface</name>
<value>default</value>
<description>The name of the Network Interface from which a task
tracker should report its IP address.
</description>
</property>
<property>
<name>mapred.tasktracker.dns.nameserver</name>
<value>default</value>
<description>The host name or IP address of the name server (DNS)
which a TaskTracker should use to determine the host name used by
the JobTracker for communication and display purposes.
</description>
</property>
<property>
<name>tasktracker.http.threads</name>
<value>40</value>
<description>The number of worker threads that for the http server. This is
used for map output fetching
</description>
</property>
<property>
<name>mapred.task.tracker.http.address</name>
<value>0.0.0.0:50060</value>
<description>
The task tracker http server address and port.
If the port is 0 then the server will start on a free port.
</description>
</property>
<property>
<name>keep.failed.task.files</name>
<value>false</value>
<description>Should the files for failed tasks be kept. This should only be
used on jobs that are failing, because the storage is never
reclaimed. It also prevents the map outputs from being erased
from the reduce directory as they are consumed.</description>
</property>
<!--
<property>
<name>keep.task.files.pattern</name>
<value>.*_m_123456_0</value>
<description>Keep all files from tasks whose task names match the given
regular expression. Defaults to none.</description>
</property>
-->
<property>
<name>mapred.output.compress</name>
<value>false</value>
<description>Should the job outputs be compressed?
</description>
</property>
<property>
<name>mapred.output.compression.type</name>
<value>RECORD</value>
<description>If the job outputs are to compressed as SequenceFiles, how should
they be compressed? Should be one of NONE, RECORD or BLOCK.
</description>
</property>
<property>
<name>mapred.output.compression.codec</name>
<value>org.apache.hadoop.io.compress.DefaultCodec</value>
<description>If the job outputs are compressed, how should they be compressed?
</description>
</property>
<property>
<name>mapred.compress.map.output</name>
<value>false</value>
<description>Should the outputs of the maps be compressed before being
sent across the network. Uses SequenceFile compression.
</description>
</property>
<property>
<name>mapred.map.output.compression.codec</name>
<value>org.apache.hadoop.io.compress.DefaultCodec</value>
<description>If the map outputs are compressed, how should they be
compressed?
</description>
</property>
<property>
<name>map.sort.class</name>
<value>org.apache.hadoop.util.QuickSort</value>
<description>The default sort class for sorting keys.
</description>
</property>
<property>
<name>mapred.userlog.limit.kb</name>
<value>0</value>
<description>The maximum size of user-logs of each task in KB. 0 disables the cap.
</description>
</property>
<property>
<name>mapred.userlog.retain.hours</name>
<value>24</value>
<description>The maximum time, in hours, for which the user-logs are to be
retained.
</description>
</property>
<property>
<name>mapred.hosts</name>
<value></value>
<description>Names a file that contains the list of nodes that may
connect to the jobtracker. If the value is empty, all hosts are
permitted.</description>
</property>
<property>
<name>mapred.hosts.exclude</name>
<value></value>
<description>Names a file that contains the list of hosts that
should be excluded by the jobtracker. If the value is empty, no
hosts are excluded.</description>
</property>
<property>
<name>mapred.heartbeats.in.second</name>
<value>100</value>
<description>Expert: Approximate number of heart-beats that could arrive
at JobTracker in a second. Assuming each RPC can be processed
in 10msec, the default value is made 100 RPCs in a second.
</description>
</property>
<property>
<name>mapred.max.tracker.blacklists</name>
<value>4</value>
<description>The number of blacklists for a taskTracker by various jobs
after which the task tracker could be blacklisted across
all jobs. The tracker will be given a tasks later
(after a day). The tracker will become a healthy
tracker after a restart.
</description>
</property>
<property>
<name>mapred.max.tracker.failures</name>
<value>4</value>
<description>The number of task-failures on a tasktracker of a given job
after which new tasks of that job aren't assigned to it.
</description>
</property>
<property>
<name>jobclient.output.filter</name>
<value>FAILED</value>
<description>The filter for controlling the output of the task's userlogs sent
to the console of the JobClient.
The permissible options are: NONE, KILLED, FAILED, SUCCEEDED and
ALL.
</description>
</property>
<property>
<name>mapred.job.tracker.persist.jobstatus.active</name>
<value>false</value>
<description>Indicates if persistency of job status information is
active or not.
</description>
</property>
<property>
<name>mapred.job.tracker.persist.jobstatus.hours</name>
<value>0</value>
<description>The number of hours job status information is persisted in DFS.
The job status information will be available after it drops of the memory
queue and between jobtracker restarts. With a zero value the job status
information is not persisted at all in DFS.
</description>
</property>
<property>
<name>mapred.job.tracker.persist.jobstatus.dir</name>
<value>/jobtracker/jobsInfo</value>
<description>The directory where the job status information is persisted
in a file system to be available after it drops of the memory queue and
between jobtracker restarts.
</description>
</property>
<property>
<name>mapred.task.profile</name>
<value>false</value>
<description>To set whether the system should collect profiler
information for some of the tasks in this job? The information is stored
in the user log directory. The value is "true" if task profiling
is enabled.</description>
</property>
<property>
<name>mapred.task.profile.maps</name>
<value>0-2</value>
<description> To set the ranges of map tasks to profile.
mapred.task.profile has to be set to true for the value to be accounted.
</description>
</property>
<property>
<name>mapred.task.profile.reduces</name>
<value>0-2</value>
<description> To set the ranges of reduce tasks to profile.
mapred.task.profile has to be set to true for the value to be accounted.
</description>
</property>
<property>
<name>mapred.line.input.format.linespermap</name>
<value>1</value>
<description> Number of lines per split in NLineInputFormat.
</description>
</property>
<property>
<name>mapred.skip.attempts.to.start.skipping</name>
<value>2</value>
<description> The number of Task attempts AFTER which skip mode
will be kicked off. When skip mode is kicked off, the
tasks reports the range of records which it will process
next, to the TaskTracker. So that on failures, TT knows which
ones are possibly the bad records. On further executions,
those are skipped.
</description>
</property>
<property>
<name>mapred.skip.map.auto.incr.proc.count</name>
<value>true</value>
<description> The flag which if set to true,
SkipBadRecords.COUNTER_MAP_PROCESSED_RECORDS is incremented
by MapRunner after invoking the map function. This value must be set to
false for applications which process the records asynchronously
or buffer the input records. For example streaming.
In such cases applications should increment this counter on their own.
</description>
</property>
<property>
<name>mapred.skip.reduce.auto.incr.proc.count</name>
<value>true</value>
<description> The flag which if set to true,
SkipBadRecords.COUNTER_REDUCE_PROCESSED_GROUPS is incremented
by framework after invoking the reduce function. This value must be set to
false for applications which process the records asynchronously
or buffer the input records. For example streaming.
In such cases applications should increment this counter on their own.
</description>
</property>
<property>
<name>mapred.skip.out.dir</name>
<value></value>
<description> If no value is specified here, the skipped records are
written to the output directory at _logs/skip.
User can stop writing skipped records by giving the value "none".
</description>
</property>
<property>
<name>mapred.skip.map.max.skip.records</name>
<value>0</value>
<description> The number of acceptable skip records surrounding the bad
record PER bad record in mapper. The number includes the bad record as well.
To turn the feature of detection/skipping of bad records off, set the
value to 0.
The framework tries to narrow down the skipped range by retrying
until this threshold is met OR all attempts get exhausted for this task.
Set the value to Long.MAX_VALUE to indicate that framework need not try to
narrow down. Whatever records(depends on application) get skipped are
acceptable.
</description>
</property>
<property>
<name>mapred.skip.reduce.max.skip.groups</name>
<value>0</value>
<description> The number of acceptable skip groups surrounding the bad
group PER bad group in reducer. The number includes the bad group as well.
To turn the feature of detection/skipping of bad groups off, set the
value to 0.
The framework tries to narrow down the skipped range by retrying
until this threshold is met OR all attempts get exhausted for this task.
Set the value to Long.MAX_VALUE to indicate that framework need not try to
narrow down. Whatever groups(depends on application) get skipped are
acceptable.
</description>
</property>
<!-- Job Notification Configuration -->
<!--
<property>
<name>job.end.notification.url</name>
<value>http://localhost:8080/jobstatus.php?jobId=$jobId&jobStatus=$jobStatus</value>
<description>Indicates url which will be called on completion of job to inform
end status of job.
User can give at most 2 variables with URI : $jobId and $jobStatus.
If they are present in URI, then they will be replaced by their
respective values.
</description>
</property>
-->
<property>
<name>job.end.retry.attempts</name>
<value>0</value>
<description>Indicates how many times hadoop should attempt to contact the
notification URL </description>
</property>
<property>
<name>job.end.retry.interval</name>
<value>30000</value>
<description>Indicates time in milliseconds between notification URL retry
calls</description>
</property>
<!-- Proxy Configuration -->
<property>
<name>hadoop.rpc.socket.factory.class.JobSubmissionProtocol</name>
<value></value>
<description> SocketFactory to use to connect to a Map/Reduce master
(JobTracker). If null or empty, then use hadoop.rpc.socket.class.default.
</description>
</property>
<property>
<name>mapred.task.cache.levels</name>
<value>2</value>
<description> This is the max level of the task cache. For example, if
the level is 2, the tasks cached are at the host level and at the rack
level.
</description>
</property>
<property>
<name>mapred.queue.names</name>
<value>default</value>
<description> Comma separated list of queues configured for this jobtracker.
Jobs are added to queues and schedulers can configure different
scheduling properties for the various queues. To configure a property
for a queue, the name of the queue must match the name specified in this
value. Queue properties that are common to all schedulers are configured
here with the naming convention, mapred.queue.$QUEUE-NAME.$PROPERTY-NAME,
for e.g. mapred.queue.default.submit-job-acl.
The number of queues configured in this parameter could depend on the
type of scheduler being used, as specified in
mapred.jobtracker.taskScheduler. For example, the JobQueueTaskScheduler
supports only a single queue, which is the default configured here.
Before adding more queues, ensure that the scheduler you've configured
supports multiple queues.
</description>
</property>
<property>
<name>mapred.acls.enabled</name>
<value>false</value>
<description> Specifies whether ACLs are enabled, and should be checked
for various operations.
</description>
</property>
<property>
<name>mapred.job.queue.name</name>
<value>default</value>
<description> Queue to which a job is submitted. This must match one of the
queues defined in mapred.queue.names for the system. Also, the ACL setup
for the queue must allow the current user to submit a job to the queue.
Before specifying a queue, ensure that the system is configured with
the queue, and access is allowed for submitting jobs to the queue.
</description>
</property>
<property>
<name>mapred.tasktracker.indexcache.mb</name>
<value>10</value>
<description> The maximum memory that a task tracker allows for the
index cache that is used when serving map outputs to reducers.
</description>
</property>
<property>
<name>mapred.merge.recordsBeforeProgress</name>
<value>10000</value>
<description> The number of records to process during merge before
sending a progress notification to the TaskTracker.
</description>
</property>
<property>
<name>mapred.reduce.slowstart.completed.maps</name>
<value>0.05</value>
<description>Fraction of the number of maps in the job which should be
complete before reduces are scheduled for the job.
</description>
</property>
<property>
<name>mapred.task.tracker.task-controller</name>
<value>org.apache.hadoop.mapred.DefaultTaskController</value>
<description>TaskController which is used to launch and manage task execution
</description>
</property>
<!-- Node health script variables -->
<property>
<name>mapred.healthChecker.script.path</name>
<value></value>
<description>Absolute path to the script which is
periodicallyrun by the node health monitoring service to determine if
the node is healthy or not. If the value of this key is empty or the
file does not exist in the location configured here, the node health
monitoring service is not started.</description>
</property>
<property>
<name>mapred.healthChecker.interval</name>
<value>60000</value>
<description>Frequency of the node health script to be run,
in milliseconds</description>
</property>
<property>
<name>mapred.healthChecker.script.timeout</name>
<value>600000</value>
<description>Time after node health script should be killed if
unresponsive and considered that the script has failed.</description>
</property>
<property>
<name>mapred.healthChecker.script.args</name>
<value></value>
<description>List of arguments which are to be passed to
node health script when it is being launched comma seperated.
</description>
</property>
<!-- end of node health script variables -->
</configuration>
| {
"content_hash": "fc5ceccdb06c9503c464fcb0b1968f87",
"timestamp": "",
"source": "github",
"line_count": 959,
"max_line_length": 89,
"avg_line_length": 33.83524504692388,
"alnum_prop": 0.7264238165680473,
"repo_name": "ghelmling/hadoop-common",
"id": "f86f5bdfc87f4883befeeabc76140c0c0e972437",
"size": "32448",
"binary": false,
"copies": "3",
"ref": "refs/heads/yahoo-hadoop-0.20",
"path": "src/mapred/mapred-default.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
const nest = require('depnest')
exports.gives = nest('app.sync.catchKeyboardShortcut')
exports.needs = nest({
'app.html.searchBar': 'first',
'app.html.tabs': 'first',
'app.sync.goTo': 'first'
})
var gPressed = false
exports.create = function (api) {
return nest('app.sync.catchKeyboardShortcut', catchKeyboardShortcut)
function catchKeyboardShortcut (root) {
var tabs = api.app.html.tabs()
var search = api.app.html.searchBar()
var goTo = api.app.sync.goTo
root.addEventListener('keydown', (ev) => {
isTextFieldEvent(ev)
? textFieldShortcuts(ev)
: genericShortcuts(ev, { tabs, search, goTo })
})
}
}
function isTextFieldEvent (ev) {
const tag = ev.target.nodeName
return (tag === 'INPUT' || tag === 'TEXTAREA')
}
function textFieldShortcuts (ev) {
switch (ev.keyCode) {
case 13: // ctrl+enter
if (ev.ctrlKey) {
ev.target.publish && ev.target.publish() // expects the textField to have a publish method
}
return
case 27: // esc
return ev.target.blur()
case 33: // PgUp
return ev.preventDefault()
case 34: // PgDn
return ev.preventDefault()
}
}
function genericShortcuts (ev, { tabs, search, goTo, back }) {
let scroll
const currentPage = tabs.currentPage()
if (currentPage) {
scroll = currentPage.keyboardScroll || noop
} else {
scroll = noop
}
// Messages
if (ev.keyCode === 71) { // gg = scroll to top
if (!gPressed) {
gPressed = true
window.setTimeout(() => {
gPressed = false
}, 3000)
return
}
scroll('first')
}
gPressed = false
switch (ev.keyCode) {
// Messages (cont'd)
case 74: // j = older
return scroll(1)
case 75: // k = newer
return scroll(-1)
case 13: // enter = open
return goToMessage(ev, { goTo })
case 79: // o = open
return goToMessage(ev, { goTo })
case 192: // ` = toggle raw message view
return toggleRawMessage(ev)
// Tabs
case 72: // h = left
tabs.selectRelative(-1)
return goTo(JSON.parse(tabs.currentPage().id))
case 76: // l = right
tabs.selectRelative(1)
return goTo(JSON.parse(tabs.currentPage().id))
case 88: // x = close
tabs.closeCurrentTab()
return
// Search
case 191: // / = routes search
if (ev.shiftKey) search.activate('?', ev)
else search.activate('/', ev)
return
case 50: // @ = mention search
if (ev.shiftKey) search.activate('@', ev)
return
case 51: // # = channel search
if (ev.shiftKey) search.activate('#', ev)
return
case 53: // % = message search
if (ev.shiftKey) search.activate('%', ev)
}
}
function goToMessage (ev, { goTo }) {
const msg = ev.target
if (msg.dataset && msg.dataset.key) {
goTo(msg.dataset.key)
// TODO - rm the dataset.root decorator
}
}
function toggleRawMessage (ev) {
const msg = ev.target
if (!msg.classList.contains('Message')) return
// this uses a crudely exported nav api
const target = msg.querySelector('.meta .toggle-raw-msg')
if (target) target.click()
}
function noop () {}
| {
"content_hash": "227c8a45168ca38252f18f7e161a5868",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 98,
"avg_line_length": 24.315384615384616,
"alnum_prop": 0.6048718759886113,
"repo_name": "dominictarr/patchboard",
"id": "db44d188a3e69107d56ecdd5c6b48ca956c7a031",
"size": "3161",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/sync/catch-keyboard-shortcut.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1219"
},
{
"name": "JavaScript",
"bytes": "10403"
}
],
"symlink_target": ""
} |
const should = require('should');
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const supertest = require('supertest');
const nock = require('nock');
const testUtils = require('../../utils');
const config = require('../../../core/shared/config');
const localUtils = require('./utils');
describe('Themes API', function () {
let ownerRequest;
const uploadTheme = (options) => {
const themePath = options.themePath;
const fieldName = 'file';
const request = options.request || ownerRequest;
return request
.post(localUtils.API.getApiQuery('themes/upload'))
.set('Origin', config.get('url'))
.attach(fieldName, themePath);
};
before(async function () {
await testUtils.startGhost();
ownerRequest = supertest.agent(config.get('url'));
await localUtils.doAuth(ownerRequest);
});
it('Can request all available themes', async function () {
const res = await ownerRequest
.get(localUtils.API.getApiQuery('themes/'))
.set('Origin', config.get('url'))
.expect(200);
const jsonResponse = res.body;
should.exist(jsonResponse.themes);
localUtils.API.checkResponse(jsonResponse, 'themes');
jsonResponse.themes.length.should.eql(6);
localUtils.API.checkResponse(jsonResponse.themes[0], 'theme');
jsonResponse.themes[0].name.should.eql('broken-theme');
jsonResponse.themes[0].package.should.be.an.Object().with.properties('name', 'version');
jsonResponse.themes[0].active.should.be.false();
localUtils.API.checkResponse(jsonResponse.themes[1], 'theme', 'templates');
jsonResponse.themes[1].name.should.eql('casper');
jsonResponse.themes[1].package.should.be.an.Object().with.properties('name', 'version');
jsonResponse.themes[1].active.should.be.true();
localUtils.API.checkResponse(jsonResponse.themes[2], 'theme');
jsonResponse.themes[2].name.should.eql('casper-1.4');
jsonResponse.themes[2].package.should.be.an.Object().with.properties('name', 'version');
jsonResponse.themes[2].active.should.be.false();
localUtils.API.checkResponse(jsonResponse.themes[3], 'theme');
jsonResponse.themes[3].name.should.eql('price-data-test-theme');
jsonResponse.themes[3].package.should.be.an.Object().with.properties('name', 'version');
jsonResponse.themes[3].active.should.be.false();
localUtils.API.checkResponse(jsonResponse.themes[4], 'theme');
jsonResponse.themes[4].name.should.eql('test-theme');
jsonResponse.themes[4].package.should.be.an.Object().with.properties('name', 'version');
jsonResponse.themes[4].active.should.be.false();
localUtils.API.checkResponse(jsonResponse.themes[5], 'theme');
jsonResponse.themes[5].name.should.eql('test-theme-channels');
jsonResponse.themes[5].package.should.be.false();
jsonResponse.themes[5].active.should.be.false();
});
it('Can download a theme', async function () {
await ownerRequest
.get(localUtils.API.getApiQuery('themes/casper/download/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /application\/zip/)
.expect('Content-Disposition', 'attachment; filename=casper.zip')
.expect(200);
});
it('Can upload a valid theme', async function () {
const res = await uploadTheme({themePath: path.join(__dirname, '..', '..', 'utils', 'fixtures', 'themes', 'valid.zip')});
const jsonResponse = res.body;
should.not.exist(res.headers['x-cache-invalidate']);
should.exist(jsonResponse.themes);
localUtils.API.checkResponse(jsonResponse, 'themes');
jsonResponse.themes.length.should.eql(1);
localUtils.API.checkResponse(jsonResponse.themes[0], 'theme');
jsonResponse.themes[0].name.should.eql('valid');
jsonResponse.themes[0].active.should.be.false();
// upload same theme again to force override
const res2 = await uploadTheme({themePath: path.join(__dirname, '..', '..', 'utils', 'fixtures', 'themes', 'valid.zip')});
const jsonResponse2 = res2.body;
should.not.exist(res2.headers['x-cache-invalidate']);
should.exist(jsonResponse2.themes);
localUtils.API.checkResponse(jsonResponse2, 'themes');
jsonResponse2.themes.length.should.eql(1);
localUtils.API.checkResponse(jsonResponse2.themes[0], 'theme');
jsonResponse2.themes[0].name.should.eql('valid');
jsonResponse2.themes[0].active.should.be.false();
// ensure tmp theme folder contains two themes now
const tmpFolderContents = fs.readdirSync(config.getContentPath('themes'));
tmpFolderContents.forEach((theme, index) => {
if (theme.match(/^\./)) {
tmpFolderContents.splice(index, 1);
}
});
// Note: at this point, the tmpFolder can legitimately still contain a valid_34324324 backup
// As it is deleted asynchronously
tmpFolderContents.should.containEql('valid');
tmpFolderContents.should.containEql('valid.zip');
// Check the Themes API returns the correct result
const res3 = await ownerRequest
.get(localUtils.API.getApiQuery('themes/'))
.set('Origin', config.get('url'))
.expect(200);
const jsonResponse3 = res3.body;
should.exist(jsonResponse3.themes);
localUtils.API.checkResponse(jsonResponse3, 'themes');
jsonResponse3.themes.length.should.eql(7);
// Casper should be present and still active
const casperTheme = _.find(jsonResponse3.themes, {name: 'casper'});
should.exist(casperTheme);
localUtils.API.checkResponse(casperTheme, 'theme', 'templates');
casperTheme.active.should.be.true();
// The added theme should be here
const addedTheme = _.find(jsonResponse3.themes, {name: 'valid'});
should.exist(addedTheme);
localUtils.API.checkResponse(addedTheme, 'theme');
addedTheme.active.should.be.false();
// Note: at this point, the API should not return a valid_34324324 backup folder as a theme
_.map(jsonResponse3.themes, 'name').should.eql([
'broken-theme',
'casper',
'casper-1.4',
'price-data-test-theme',
'test-theme',
'test-theme-channels',
'valid'
]);
});
it('Can delete a theme', async function () {
const res = await ownerRequest
.del(localUtils.API.getApiQuery('themes/valid'))
.set('Origin', config.get('url'))
.expect(204);
const jsonResponse = res.body;
// Delete requests have empty bodies
jsonResponse.should.eql({});
// ensure tmp theme folder contains one theme again now
const tmpFolderContents = fs.readdirSync(config.getContentPath('themes'));
tmpFolderContents.forEach((theme, index) => {
if (theme.match(/^\./) || theme === 'README.md') {
tmpFolderContents.splice(index, 1);
}
});
tmpFolderContents.should.be.an.Array().with.lengthOf(10);
tmpFolderContents.should.eql([
'broken-theme',
'casper',
'casper-1.4',
'casper.zip',
'invalid.zip',
'price-data-test-theme',
'test-theme',
'test-theme-channels',
'valid.zip',
'warnings.zip'
]);
// Check the themes API returns the correct result after deletion
const res2 = await ownerRequest
.get(localUtils.API.getApiQuery('themes/'))
.set('Origin', config.get('url'))
.expect(200);
const jsonResponse2 = res2.body;
should.exist(jsonResponse2.themes);
localUtils.API.checkResponse(jsonResponse2, 'themes');
jsonResponse2.themes.length.should.eql(6);
// Casper should be present and still active
const casperTheme = _.find(jsonResponse2.themes, {name: 'casper'});
should.exist(casperTheme);
localUtils.API.checkResponse(casperTheme, 'theme', 'templates');
casperTheme.active.should.be.true();
// The deleted theme should not be here
const deletedTheme = _.find(jsonResponse2.themes, {name: 'valid'});
should.not.exist(deletedTheme);
});
it('Can upload a theme, which has warnings', async function () {
const res = await uploadTheme({themePath: path.join(__dirname, '/../../utils/fixtures/themes/warnings.zip')});
const jsonResponse = res.body;
should.exist(jsonResponse.themes);
localUtils.API.checkResponse(jsonResponse, 'themes');
jsonResponse.themes.length.should.eql(1);
localUtils.API.checkResponse(jsonResponse.themes[0], 'theme', ['warnings']);
jsonResponse.themes[0].name.should.eql('warnings');
jsonResponse.themes[0].active.should.be.false();
jsonResponse.themes[0].warnings.should.be.an.Array();
// Delete the theme to clean up after the test
await ownerRequest
.del(localUtils.API.getApiQuery('themes/warnings'))
.set('Origin', config.get('url'))
.expect(204);
});
it('Can activate a theme', async function () {
const res = await ownerRequest
.get(localUtils.API.getApiQuery('themes/'))
.set('Origin', config.get('url'))
.expect(200);
const jsonResponse = res.body;
should.exist(jsonResponse.themes);
localUtils.API.checkResponse(jsonResponse, 'themes');
jsonResponse.themes.length.should.eql(6);
const casperTheme = _.find(jsonResponse.themes, {name: 'casper'});
should.exist(casperTheme);
localUtils.API.checkResponse(casperTheme, 'theme', 'templates');
casperTheme.active.should.be.true();
const testTheme = _.find(jsonResponse.themes, {name: 'test-theme'});
should.exist(testTheme);
localUtils.API.checkResponse(testTheme, 'theme');
testTheme.active.should.be.false();
// Finally activate the new theme
const res2 = await ownerRequest
.put(localUtils.API.getApiQuery('themes/test-theme/activate'))
.set('Origin', config.get('url'))
.expect(200);
const jsonResponse2 = res2.body;
should.exist(res2.headers['x-cache-invalidate']);
should.exist(jsonResponse2.themes);
localUtils.API.checkResponse(jsonResponse2, 'themes');
jsonResponse2.themes.length.should.eql(1);
const casperTheme2 = _.find(jsonResponse2.themes, {name: 'casper'});
should.not.exist(casperTheme2);
const testTheme2 = _.find(jsonResponse2.themes, {name: 'test-theme'});
should.exist(testTheme2);
localUtils.API.checkResponse(testTheme2, 'theme', ['warnings', 'templates']);
testTheme2.active.should.be.true();
testTheme2.warnings.should.be.an.Array();
});
it('Can download and install a theme from GitHub', async function () {
const githubZipball = nock('https://api.github.com')
.get('/repos/tryghost/test/zipball')
.reply(302, null, {Location: 'https://codeload.github.com/TryGhost/Test/legacy.zip/main'});
const githubDownload = nock('https://codeload.github.com')
.get('/TryGhost/Test/legacy.zip/main')
.replyWithFile(200, path.join(__dirname, '/../../utils/fixtures/themes/warnings.zip'), {
'Content-Type': 'application/zip',
'Content-Disposition': 'attachment; filename=TryGhost-Test-3.1.2-38-gfc8cf0b.zip'
});
const res = await ownerRequest
.post(localUtils.API.getApiQuery('themes/install/?source=github&ref=TryGhost/Test'))
.set('Origin', config.get('url'));
githubZipball.isDone().should.be.true();
githubDownload.isDone().should.be.true();
const jsonResponse = res.body;
should.exist(jsonResponse.themes);
localUtils.API.checkResponse(jsonResponse, 'themes');
jsonResponse.themes.length.should.eql(1);
localUtils.API.checkResponse(jsonResponse.themes[0], 'theme', ['warnings']);
jsonResponse.themes[0].name.should.eql('test');
jsonResponse.themes[0].active.should.be.false();
jsonResponse.themes[0].warnings.should.be.an.Array();
// Delete the theme to clean up after the test
await ownerRequest
.del(localUtils.API.getApiQuery('themes/test'))
.set('Origin', config.get('url'))
.expect(204);
});
});
| {
"content_hash": "848ec44b24c8568301148ae416e38839",
"timestamp": "",
"source": "github",
"line_count": 310,
"max_line_length": 130,
"avg_line_length": 41.564516129032256,
"alnum_prop": 0.6210322079937912,
"repo_name": "bitjson/Ghost",
"id": "35a1fea3521e6cfcf3f777060880fbbb119cebff",
"size": "12885",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/api-acceptance/admin/themes_spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "106334"
},
{
"name": "HTML",
"bytes": "97186"
},
{
"name": "Handlebars",
"bytes": "77516"
},
{
"name": "JavaScript",
"bytes": "2085284"
},
{
"name": "XSLT",
"bytes": "7177"
}
],
"symlink_target": ""
} |
<! DOCTYPE html>
<html>
<head>
<title>Iconic</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript' src='js/underscorev1.4.4.js'></script>
<script type='text/javascript' src='js/jQueryv1.10.1.js'></script>
<script type='text/javascript' src='js/jquery.color.js'></script>
<script type='text/javascript' src='js/davisv0.1.0.js'></script>
<script type='text/javascript' src='js/geov0.0.1.js'></script>
<script type='text/javascript' src='js/appv0.0.1.js'></script>
</head>
<body>
</body>
</html>
| {
"content_hash": "831ba7197f8862195eebcb9fb2d03721",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 70,
"avg_line_length": 26.428571428571427,
"alnum_prop": 0.6936936936936937,
"repo_name": "lucaswadedavis/iconic",
"id": "bc042802bee5c8941280f132a4e303e0c81c29c9",
"size": "555",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "35139"
}
],
"symlink_target": ""
} |
package org.kuali.rice.location.api.country;
import org.kuali.rice.core.api.criteria.QueryByCriteria;
import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import org.kuali.rice.core.api.exception.RiceIllegalStateException;
import org.kuali.rice.location.api.LocationConstants;
import org.springframework.cache.annotation.Cacheable;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import java.util.List;
/**
* <p>CountryService interface.</p>
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
@WebService(name = "CountryService", targetNamespace = LocationConstants.Namespaces.LOCATION_NAMESPACE_2_0)
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public interface CountryService {
/**
* Lookup a country object based on the given country code.
*
* @param code the given country code
* @return a country object with the given country code. A null reference is returned if an invalid or
* non-existant code is supplied.
* @throws RiceIllegalArgumentException if the code is blank or null
*/
@WebMethod(operationName = "getCountry")
@WebResult(name = "country")
@Cacheable(value=Country.Cache.NAME, key="'code=' + #p0")
Country getCountry(@WebParam(name = "code") String code) throws RiceIllegalArgumentException;
/**
* Get a country object based on an alternate country code
*
* @param alternateCode the given alternate country code
* @return A country object with the given alternate country code if a country with that alternate country code
* exists. Otherwise, null is returned.
* @throws RiceIllegalStateException if multiple Countries exist with the same passed in alternateCode
* @throws RiceIllegalArgumentException if alternateCode is null or is a whitespace only string.
*/
@WebMethod(operationName = "getCountryByAlternateCode")
@WebResult(name = "country")
@Cacheable(value=Country.Cache.NAME, key="'alternateCode=' + #p0")
Country getCountryByAlternateCode(@WebParam(name = "alternateCode") String alternateCode)
throws RiceIllegalStateException, RiceIllegalArgumentException;
/**
* Returns all Countries that are not restricted.
*
* @return all countries that are not restricted
*/
@WebMethod(operationName = "findAllCountriesNotRestricted")
@XmlElementWrapper(name = "countriesNotRestricted", required = false)
@XmlElement(name = "countryNotRestricted", required = false)
@WebResult(name = "countriesNotRestricted")
@Cacheable(value=Country.Cache.NAME, key="'allRestricted'")
List<Country> findAllCountriesNotRestricted();
/**
* Returns all Countries
*
* @return all countries
*/
@WebMethod(operationName = "findAllCountries")
@XmlElementWrapper(name = "countries", required = false)
@XmlElement(name = "country", required = false)
@WebResult(name = "countries")
@Cacheable(value=Country.Cache.NAME, key="'all'")
List<Country> findAllCountries();
/**
* Returns the system default country. This is simply meant to be informational for applications which need the
* ability to utilize a default country (such as for defaulting of certain fields during data entry). This method
* may return null in situations where no default country is configured.
*
* @return the default country, or null if no default country is defined
*/
@WebMethod(operationName = "getDefaultCountry")
@WebResult(name = "country")
@Cacheable(value = Country.Cache.NAME, key="'default'")
Country getDefaultCountry();
/**
* This method find Countries based on a query criteria. The criteria cannot be null.
*
* @since 2.0.1
* @param queryByCriteria the criteria. Cannot be null.
* @return query results. will never return null.
* @throws IllegalArgumentException if the queryByCriteria is null
*/
@WebMethod(operationName = "findCountries")
@WebResult(name = "results")
CountryQueryResults findCountries(@WebParam(name = "query") QueryByCriteria queryByCriteria) throws RiceIllegalArgumentException;
}
| {
"content_hash": "542f862320f94a0906507ab52a3f76b2",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 133,
"avg_line_length": 43.4,
"alnum_prop": 0.7085802062760588,
"repo_name": "mztaylor/rice-git",
"id": "342a2dcf89781c1f9de93449e7b487126ee2a021",
"size": "5192",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "rice-middleware/location/api/src/main/java/org/kuali/rice/location/api/country/CountryService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "795267"
},
{
"name": "Groovy",
"bytes": "2170621"
},
{
"name": "Java",
"bytes": "34571234"
},
{
"name": "JavaScript",
"bytes": "2652150"
},
{
"name": "PHP",
"bytes": "15766"
},
{
"name": "Shell",
"bytes": "10444"
},
{
"name": "XSLT",
"bytes": "107686"
}
],
"symlink_target": ""
} |
/**
* Created by dd on 2/24/15.
*/
Deps.autorun(function () {
if (Session.get("patient") && Session.get("patient")._id) {
Meteor.subscribe("patientFlags", Session.get("patient")._id);
}
});
Template.console.events({
'click #biolog-healthInfo-btn': function(event) {
ask('I am listening', function (err, result) {
if (result && result.transcript) {
speak(result.transcript);
Session.set("recognizedSpeech", result.transcript);
} else {
speak('I did not catch that');
}
});
},
'click #refreshChecklistButton': function(event) {
//console.log("search Isabel...");
searchIsabel();
}
});
Template.console.helpers({
recognizedSpeech: function() {
return Session.get("recognizedSpeech");
}
});
//Template.myChecklist.events({
//
//});
//
//Template.myChecklist.helpers({
// checklist: function() {
// return getPatientFlags(Session.get("patient")._id).fetch();
// }
//});
Template.isabelChecklist.helpers({
diagnoses: function() {
if (! Session.get("isabel")) return null;
return Session.get("isabel").diagnosis;
},
isabelIcon: function() {
if (this.red_flag && this.red_flag == "true") return "fa fa-warning";
return "fa fa-question-circle";
},
severityColor: function() {
if (this.red_flag && this.red_flag == "true") return "list-group-item-danger";
return "list-group-item-warning";
}
}); | {
"content_hash": "507d1189e46aeb892daabf121952fb26",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 86,
"avg_line_length": 24.555555555555557,
"alnum_prop": 0.5694893341952165,
"repo_name": "realdbio/biolog",
"id": "b4cbc25f88e1e9345abfe81dae45d1ffbeeb4b9d",
"size": "1547",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/console.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2684"
},
{
"name": "HTML",
"bytes": "25327"
},
{
"name": "JavaScript",
"bytes": "124681"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-finmap: 1 m 33 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.1 / mathcomp-finmap - 1.4.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-finmap
<small>
1.4.0
<span class="label label-success">1 m 33 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-16 04:20:23 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-16 04:20:23 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Cyril Cohen <cyril.cohen@inria.fr>"
homepage: "https://github.com/math-comp/finmap"
bug-reports: "https://github.com/math-comp/finmap/issues"
dev-repo: "git+https://github.com/math-comp/finmap.git"
license: "CeCILL-B"
build: [ make "-j" "%{jobs}%" ]
install: [ make "install" ]
depends: [
"coq" { (>= "8.7" & < "8.11.1") }
"coq-mathcomp-ssreflect" { (>= "1.8.0" & < "1.11~") }
"coq-mathcomp-bigenough" { (>= "1.0.0" & < "1.1~") }
]
tags: [ "keyword:finmap" "keyword:finset" "keyword:multiset" "keyword:order" "date:2019-11-27" "logpath:mathcomp.finmap"]
authors: [ "Cyril Cohen <cyril.cohen@inria.fr>" "Kazuhiko Sakaguchi <sakaguchi@coins.tsukuba.ac.jp>" ]
synopsis: "Finite sets, finite maps, finitely supported functions, orders"
description: """
This library is an extension of mathematical component in order to
support finite sets and finite maps on choicetypes (rather that finite
types). This includes support for functions with finite support and
multisets. The library also contains a generic order and set libary,
which will be used to subsume notations for finite sets, eventually."""
url {
src: "https://github.com/math-comp/finmap/archive/1.4.0.tar.gz"
checksum: "sha256=ed145e6b1be9fcc215d4de20a17d64bc8772f0a2afc2372a318733882ea69ad2"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-finmap.1.4.0 coq.8.8.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-mathcomp-finmap.1.4.0 coq.8.8.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 m 44 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-mathcomp-finmap.1.4.0 coq.8.8.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 m 33 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 6 M</p>
<ul>
<li>1 M <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/order.glob</code></li>
<li>1 M <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/order.vo</code></li>
<li>1 M <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/finmap.vo</code></li>
<li>1 M <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/finmap.glob</code></li>
<li>280 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/multiset.glob</code></li>
<li>279 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/multiset.vo</code></li>
<li>264 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/set.vo</code></li>
<li>230 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/order.v</code></li>
<li>230 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/set.glob</code></li>
<li>136 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/finmap.v</code></li>
<li>36 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/set.v</code></li>
<li>33 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/finmap/multiset.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-mathcomp-finmap.1.4.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "836f3a72c3ebfdad0ca400f786260696",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 181,
"avg_line_length": 50.245714285714286,
"alnum_prop": 0.566814511543273,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "241d1ff98a1d894b3a1c2f0e49cd586205b1f3ed",
"size": "8818",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.8.1/mathcomp-finmap/1.4.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
require 'faraday'
require 'faraday_middleware'
module Glip
class Poster
VERSION = '0.1.0'
GLIP_WEBHOOK_BASE_URL = 'https://hooks.glip.com/webhook/'
attr_reader :webhook_url
attr_accessor :options
attr_accessor :http
def initialize(webhook_url_or_id)
set_webhook_url(webhook_url_or_id)
@options = {}
@http = Faraday.new(url: GLIP_WEBHOOK_BASE_URL) do |faraday|
faraday.request :json
faraday.response :logger
faraday.adapter Faraday.default_adapter # use Net::HTTP
end
end
def set_webhook_url(webhook_url_or_id)
if webhook_url_or_id.to_s !~ %r{/}
@webhook_url = GLIP_WEBHOOK_BASE_URL + webhook_url_or_id
elsif webhook_url_or_id =~ %r{^https?://}
@webhook_url = webhook_url_or_id
else
fail ArgumentError, 'must include webhook URL or id argument'
end
end
def send_message(message, opts = {})
response = @http.post do |req|
req.url @webhook_url
req.body = @options.merge(opts).merge(body: message)
end
response
end
end
end
| {
"content_hash": "a55db8811eb623b041c00519d13bc552",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 69,
"avg_line_length": 25.113636363636363,
"alnum_prop": 0.6180995475113122,
"repo_name": "grokify/glip-poster-ruby",
"id": "d40f2fa6c58ee4054f2de530da3208a76debe5cc",
"size": "1105",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/glip-poster/poster.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "3764"
}
],
"symlink_target": ""
} |
namespace content {
// static
RenderFrameHostFactory* RenderFrameHostFactory::factory_ = NULL;
// static
std::unique_ptr<RenderFrameHostImpl> RenderFrameHostFactory::Create(
SiteInstance* site_instance,
RenderViewHostImpl* render_view_host,
RenderFrameHostDelegate* delegate,
RenderWidgetHostDelegate* rwh_delegate,
FrameTree* frame_tree,
FrameTreeNode* frame_tree_node,
int32_t routing_id,
int32_t widget_routing_id,
bool hidden,
bool renderer_initiated_creation) {
if (factory_) {
return factory_->CreateRenderFrameHost(
site_instance, render_view_host, delegate, rwh_delegate, frame_tree,
frame_tree_node, routing_id, widget_routing_id, hidden,
renderer_initiated_creation);
}
return base::WrapUnique(new RenderFrameHostImpl(
site_instance, render_view_host, delegate, rwh_delegate, frame_tree,
frame_tree_node, routing_id, widget_routing_id, hidden,
renderer_initiated_creation));
}
// static
void RenderFrameHostFactory::RegisterFactory(RenderFrameHostFactory* factory) {
DCHECK(!factory_) << "Can't register two factories at once.";
factory_ = factory;
}
// static
void RenderFrameHostFactory::UnregisterFactory() {
DCHECK(factory_) << "No factory to unregister.";
factory_ = NULL;
}
} // namespace content
| {
"content_hash": "342c2be4d9d834c01a54bab091ff77a2",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 79,
"avg_line_length": 31.404761904761905,
"alnum_prop": 0.7240333586050038,
"repo_name": "Samsung/ChromiumGStreamerBackend",
"id": "f94453e3f67ae998f6aef25aae805d1f24b35480",
"size": "1732",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "content/browser/frame_host/render_frame_host_factory.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
using DD4T.ContentModel;
using System;
using System.Web.Mvc;
using DVM4T.Attributes;
using DVM4T.Base;
using DVM4T.DD4T.Attributes;
using DVM4T.Core;
using DVM4T.Contracts;
using System.Collections.Generic;
using System.Linq;
namespace DVM4T.Testing.DomainModels
{
public class GeneralContentViewModel
{
public string Title { get; set; }
public string SubTitle { get; set; }
public MvcHtmlString Body { get; set; }
public bool ShowOnTop { get; set; }
public double NumberFieldExample { get; set; }
public string ViewName { get; set; }
public Color BackgroundColor { get; set; }
public List<StateType> State { get; set; }
}
public class ListAdapter<T> : List<object>, IEnumerable<T>
{
public new IEnumerator<T> GetEnumerator()
{
return this.ToArray().Cast<T>().GetEnumerator();
}
}
public class Image
{
public string Url { get; set; }
public IMultimediaData Multimedia { get; set; }
public string AltText { get; set; }
}
public class ContentContainerViewModel
{
public string Title { get; set; }
public List<GeneralContentViewModel> ContentList { get; set; }
public List<EmbeddedLinkViewModel> Links { get; set; }
public Image Image { get; set; }
public string ViewName { get; set; }
}
public class EmbeddedLinkViewModel
{
public string LinkText { get; set; }
public IComponent InternalLink { get; set; }
public string ExternalLink { get; set; }
public string Target { get; set; }
}
public class BrokenViewModel
{
public double BrokenTitle { get; set; }
public string SubTitle { get; set; }
public MvcHtmlString Body { get; set; }
public bool ShowOnTop { get; set; }
public double NumberFieldExample { get; set; }
}
public class Homepage
{
public List<GeneralContentViewModel> Carousels { get; set; }
public String Javascript { get; set; }
}
public class Color
{
public string Key { get; set; }
public string RgbValue { get; set; }
public double NumericValue { get; set; }
}
public enum StateType
{
VA,
PA,
NY,
MA,
MD,
DE
}
}
| {
"content_hash": "b281a56f2bc091cf50ea53a3d145a352",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 70,
"avg_line_length": 21.15929203539823,
"alnum_prop": 0.5964031785863655,
"repo_name": "josheinhorn/DVM4T",
"id": "b31ec3f80a4af142e1dfd6397ba89406d232d382",
"size": "2393",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "DVM4T.Tests/DomainModels.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "306257"
}
],
"symlink_target": ""
} |
var jwtHelper = (function() {
return {
urlBase64Decode : function(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0: { break; }
case 2: { output += '=='; break; }
case 3: { output += '='; break; }
default: {
throw 'Illegal base64url string!';
}
}
return decodeURIComponent(escape(window.atob(output))); //polifyll https://github.com/davidchambers/Base64.js
},
decodeToken : function(token) {
var parts = token.split('.');
if (parts.length !== 3) {
throw new Error('JWT must have 3 parts');
}
var decoded = this.urlBase64Decode(parts[1]);
if (!decoded) {
throw new Error('Cannot decode the token');
}
return JSON.parse(decoded);
},
getTokenExpirationDate : function(token) {
var decoded;
decoded = this.decodeToken(token);
if(typeof decoded.exp === "undefined") {
return null;
}
var d = new Date(0); // The 0 here is the key, which sets the date to the epoch
d.setUTCSeconds(decoded.exp);
return d;
},
isTokenExpired : function(token, offsetSeconds) {
var d = this.getTokenExpirationDate(token);
offsetSeconds = offsetSeconds || 0;
if (d === null) {
return false;
}
// Token expired?
return !(d.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000)));
}
};
})(); | {
"content_hash": "f3dbe6e155ba52007743875144ecd506",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 119,
"avg_line_length": 31.053571428571427,
"alnum_prop": 0.4715353651523864,
"repo_name": "jdbence/learn",
"id": "0917b765425791c6b34ae69bfabdcccca05fc66a",
"size": "1739",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/jwtHelper.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3347"
},
{
"name": "JavaScript",
"bytes": "6101"
}
],
"symlink_target": ""
} |
package se.toxbee.sleepfighter.utils.model;
/**
* {@link PrimitiveGetters} provides getters for all primitive<br/>
* types on a key-value data structure where the key is K.
*
* @author Centril<twingoow@gmail.com> / Mazdak Farrokhzad.
* @version 1.0
* @since Dec 15, 2013
*/
public interface PrimitiveGetters<K> {
/**
* Returns a boolean value for key.
*
* @param key the key to get value for.
* @return the value.
*/
public boolean getBoolean( K key );
/**
* Returns a char value for key.
*
* @param key the key to get value for.
* @return the value.
*/
public char getChar( K key );
/**
* Returns a short value for key.
*
* @param key the key to get value for.
* @return the value.
*/
public short getShort( K key );
/**
* Returns a integer value for key.
*
* @param key the key to get value for.
* @return the value.
*/
public int getInt( K key );
/**
* Returns a long value for key.
*
* @param key the key to get value for.
* @return the value.
*/
public long getLong( K key );
/**
* Returns a float value for key.
*
* @param key the key to get value for.
* @return the value.
*/
public float getFloat( K key );
/**
* Returns a double value for key.
*
* @param key the key to get value for.
* @return the value.
*/
public double getDouble( K key );
}
| {
"content_hash": "cc496179623a9886da21645623bbb880",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 67,
"avg_line_length": 19.6231884057971,
"alnum_prop": 0.6270310192023634,
"repo_name": "Centril/sleepfighter",
"id": "44aa2495558345c7efd06b3ecb5ed95a8ded346b",
"size": "1942",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "application/sleepfighter/src/main/java/se/toxbee/sleepfighter/utils/model/PrimitiveGetters.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6512"
},
{
"name": "Java",
"bytes": "900045"
},
{
"name": "JavaScript",
"bytes": "63829"
}
],
"symlink_target": ""
} |
<?php
namespace Hifone\Test\Functional;
use Hifone\Test\AbstractTestCase;
class WebTest extends AbstractTestCase
{
/**
* A basic functional test example.
*
* @return void
*/
public function testHomepage()
{
$this->get('/');
$this->assertResponseStatus(302);
}
}
| {
"content_hash": "af63e6d5a7ba0c9cf3aa04637f358bb3",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 41,
"avg_line_length": 15.19047619047619,
"alnum_prop": 0.6050156739811913,
"repo_name": "underdogg-forks/hifone",
"id": "3c98d4003e41561d8c0e6b3b545e66309d8cca85",
"size": "528",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tests/Functional/WebTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "59542"
},
{
"name": "CoffeeScript",
"bytes": "32650"
},
{
"name": "HTML",
"bytes": "216082"
},
{
"name": "JavaScript",
"bytes": "3171"
},
{
"name": "PHP",
"bytes": "771288"
}
],
"symlink_target": ""
} |
namespace base {
class FilePath;
} // namespace base
namespace component_updater {
// TODO(rsleevi): Remove in M86 or later.
void DeleteLegacySTHSet(const base::FilePath& user_data_dir);
} // namespace component_updater
#endif // CHROME_BROWSER_COMPONENT_UPDATER_STH_SET_COMPONENT_REMOVER_H_
| {
"content_hash": "0758e269490f50fa7264c7d4315be9db",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 72,
"avg_line_length": 24.916666666666668,
"alnum_prop": 0.7525083612040134,
"repo_name": "endlessm/chromium-browser",
"id": "51b028dafe4c8a58c5214ffad5374ed844eda0a1",
"size": "606",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chrome/browser/component_updater/sth_set_component_remover.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"use strict"
require('source-map-support').install()
const isCi = require("is-ci")
const isWindows = process.platform === "win32"
// Squirrel.Windows msi is very slow
jasmine.DEFAULT_TIMEOUT_INTERVAL = (isWindows ? 30 : 10) * 1000 * 60
const skip = test.skip
const skipSuite = describe.skip
const isAllTests = process.env.ALL_TESTS !== "false"
describe.ifAll = isAllTests ? describe : skipSuite
test.ifAll = isAllTests ? test : skip
skip.ifAll = skip
const isMac = process.platform === "darwin"
test.ifMac = isMac ? test : skip
test.ifNotWindows = isWindows ? skip : test
test.ifNotWindows.ifNotCiMac = isCi && isMac ? skip : test
test.ifWindows = isWindows ? test : skip
skip.ifMac = skip
skip.ifLinux = skip
skip.ifWindows = skip
skip.ifNotWindows = skip
skip.ifNotWindows.ifNotCiMac = skip
skip.ifCi = skip
skip.ifNotCi = skip
skip.ifNotCiMac = skip
skip.ifNotCiWin = skip
skip.ifDevOrWinCi = skip
skip.ifDevOrLinuxCi = skip
skip.ifWinCi = skip
skip.ifLinuxOrDevMac = skip
if (isCi) {
test.ifCi = test
test.ifNotCi = skip
}
else {
test.ifCi = skip
test.ifNotCi = test
}
test.ifNotCiMac = isCi && isMac ? skip : test
test.ifNotCiWin = isCi && isWindows ? skip : test
test.ifDevOrWinCi = !isCi || isWindows ? test : skip
test.ifDevOrLinuxCi = !isCi || process.platform === "linux" ? test : skip
test.ifWinCi = isCi && isWindows ? test : skip
test.ifLinux = process.platform === "linux" ? test : skip
test.ifLinuxOrDevMac = process.platform === "linux" || (!isCi && isMac) ? test : skip
delete process.env.CSC_NAME
if (process.env.TEST_APP_TMP_DIR == null) {
delete process.env.GH_TOKEN
}
if (!process.env.USE_HARD_LINKS) {
process.env.USE_HARD_LINKS = "true"
}
if (!process.env.SZA_COMPRESSION_LEVEL) {
process.env.SZA_COMPRESSION_LEVEL = "0"
}
process.env.FORCE_YARN = true | {
"content_hash": "88e1eb9b6bc040499b8c38d9cd6ad8d7",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 85,
"avg_line_length": 24.41891891891892,
"alnum_prop": 0.7083563918096292,
"repo_name": "MariaDima/electron-builder",
"id": "21da9a2d6e35b2b64f567e61f7efdb9e76fcefb7",
"size": "1807",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/jestSetup.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2429"
},
{
"name": "JavaScript",
"bytes": "73031"
},
{
"name": "NSIS",
"bytes": "70386"
},
{
"name": "Perl",
"bytes": "3174"
},
{
"name": "Python",
"bytes": "7628"
},
{
"name": "Shell",
"bytes": "9218"
},
{
"name": "Smarty",
"bytes": "112"
},
{
"name": "TypeScript",
"bytes": "913665"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<products>
<product id="8" xlink:href="http://localhost/api/products/8"/>
<product id="9" xlink:href="http://localhost/api/products/9"/>
</products>
</prestashop>
| {
"content_hash": "32ac8089d76a0642db3f5d6a659bce15",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 70,
"avg_line_length": 40.285714285714285,
"alnum_prop": 0.6347517730496454,
"repo_name": "itconsultis/prestashop-api-client",
"id": "bcdb00ec02de939ceda9b627e31e443867e1871b",
"size": "282",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/fixtures/products.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "53148"
},
{
"name": "Shell",
"bytes": "850"
},
{
"name": "VimL",
"bytes": "337"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<link rel="import" href="/base/base.html">
<link rel="import" href="/base/iteration_helpers.html">
<link rel="import" href="/base/statistics.html">
<link rel="import" href="/core/analysis/analysis_link.html">
<link rel="import" href="/core/analysis/multi_event_summary.html">
<link rel="import" href="/core/analysis/table_builder.html">
<link rel="import" href="/core/analysis/time_span.html">
</script>
<polymer-element name='tv-c-a-multi-event-summary-table'>
<template>
<style>
:host {
display: flex;
}
#table {
flex: 1 1 auto;
align-self: stretch;
}
</style>
<tracing-analysis-nested-table id="table">
</tracing-analysis-nested-table>
</div>
</template>
<script>
'use strict';
Polymer({
ready: function() {
this.showTotals_ = false;
this.eventsHaveDuration_ = true;
this.eventsHaveSubRows_ = true;
this.eventsByTitle_ = undefined;
},
updateTableColumns_: function(rows) {
var hasCpuData = false;
var hasAlerts = false;
rows.forEach(function(row) {
if (row.cpuDuration !== undefined)
hasCpuData = true;
if (row.cpuSelfTime !== undefined)
hasCpuData = true;
if (row.numAlerts)
hasAlerts = true;
});
var columns = [];
columns.push({
title: 'Name',
value: function(row) {
if (row.title === 'Totals')
return 'Totals';
var linkEl = document.createElement('tv-c-analysis-link');
linkEl.setSelectionAndContent(function() {
return new tv.c.Selection(row.events);
}, row.title);
return linkEl;
},
width: '350px',
cmp: function(rowA, rowB) {
return rowA.title.localeCompare(rowB.title);
}
});
if (this.eventsHaveDuration_) {
columns.push({
title: 'Wall Duration (ms)',
value: function(row) {
return tv.c.analysis.createTimeSpan(row.duration);
},
width: '<upated further down>',
cmp: function(rowA, rowB) {
return rowA.duration - rowB.duration;
}
});
}
if (this.eventsHaveDuration_ && hasCpuData) {
columns.push({
title: 'CPU Duration (ms)',
value: function(row) {
return tv.c.analysis.createTimeSpan(row.cpuDuration);
},
width: '<upated further down>',
cmp: function(rowA, rowB) {
return rowA.cpuDuration - rowB.cpuDuration;
}
});
}
if (this.eventsHaveSubRows_ && this.eventsHaveDuration_) {
columns.push({
title: 'Self time (ms)',
value: function(row) {
return tv.c.analysis.createTimeSpan(row.selfTime);
},
width: '<upated further down>',
cmp: function(rowA, rowB) {
return rowA.selfTime - rowB.selfTime;
}
});
}
if (this.eventsHaveSubRows_ && this.eventsHaveDuration_ && hasCpuData) {
columns.push({
title: 'CPU Self Time (ms)',
value: function(row) {
return tv.c.analysis.createTimeSpan(row.cpuSelfTime);
},
width: '<upated further down>',
cmp: function(rowA, rowB) {
return rowA.cpuSelfTime - rowB.cpuSelfTime;
}
});
}
columns.push({
title: 'Occurrences',
value: function(row) {
return row.numEvents;
},
width: '<upated further down>',
cmp: function(rowA, rowB) {
return rowA.numEvents - rowB.numEvents;
}
});
var alertsColumnIndex;
if (hasAlerts) {
columns.push({
title: 'Num Alerts',
value: function(row) {
return row.numAlerts;
},
width: '<upated further down>',
cmp: function(rowA, rowB) {
return rowA.numAlerts - rowB.numAlerts;
}
});
alertsColumnIndex = columns.length - 1;
}
var colWidthPercentage;
if (columns.length == 1)
colWidthPercentage = '100%';
else
colWidthPercentage = (100 / (columns.length - 1)).toFixed(3) + '%';
for (var i = 1; i < columns.length; i++)
columns[i].width = colWidthPercentage;
this.$.table.tableColumns = columns;
if (hasAlerts) {
this.$.table.sortColumnIndex = alertsColumnIndex;
this.$.table.sortDescending = true;
}
},
configure: function(config) {
if (config.eventsByTitle === undefined)
throw new Error('Required: eventsByTitle');
if (config.showTotals !== undefined)
this.showTotals_ = config.showTotals;
else
this.showTotals_ = true;
if (config.eventsHaveDuration !== undefined)
this.eventsHaveDuration_ = config.eventsHaveDuration;
else
this.eventsHaveDuration_ = true;
if (config.eventsHaveSubRows !== undefined)
this.eventsHaveSubRows_ = config.eventsHaveSubRows;
else
this.eventsHaveSubRows_ = true;
this.eventsByTitle_ = config.eventsByTitle;
this.updateContents_();
},
get showTotals() {
return this.showTotals_;
},
set showTotals(showTotals) {
this.showTotals_ = showTotals;
this.updateContents_();
},
get eventsHaveDuration() {
return this.eventsHaveDuration_;
},
set eventsHaveDuration(eventsHaveDuration) {
this.eventsHaveDuration_ = eventsHaveDuration;
this.updateContents_();
},
get eventsHaveSubRows() {
return this.eventsHaveSubRows_;
},
set eventsHaveSubRows(eventsHaveSubRows) {
this.eventsHaveSubRows_ = eventsHaveSubRows;
this.updateContents_();
},
get eventsByTitle() {
return this.eventsByTitle_;
},
set eventsByTitle(eventsByTitle) {
this.eventsByTitle_ = eventsByTitle;
this.updateContents_();
},
get selectionBounds() {
return this.selectionBounds_;
},
set selectionBounds(selectionBounds) {
this.selectionBounds_ = selectionBounds;
this.updateContents_();
},
updateContents_: function() {
var eventsByTitle;
if (this.eventsByTitle_ !== undefined)
eventsByTitle = this.eventsByTitle_;
else
eventsByTitle = [];
var allEvents = [];
var rows = [];
tv.b.iterItems(
eventsByTitle,
function(title, eventsOfSingleTitle) {
allEvents.push.apply(allEvents, eventsOfSingleTitle);
var row = new tv.c.analysis.MultiEventSummary(title,
eventsOfSingleTitle);
rows.push(row);
});
this.updateTableColumns_(rows);
this.$.table.tableRows = rows;
var footerRows = [];
if (this.showTotals_) {
footerRows.push(
new tv.c.analysis.MultiEventSummary('Totals', allEvents));
}
// TODO(selection bounds).
// TODO(sorting)
this.$.table.footerRows = footerRows;
this.$.table.rebuild();
}
});
</script>
</polymer-element>
| {
"content_hash": "570df9ebeab9830612477fe4fe88e074",
"timestamp": "",
"source": "github",
"line_count": 272,
"max_line_length": 79,
"avg_line_length": 27.1875,
"alnum_prop": 0.568762677484787,
"repo_name": "vmpstr/trace-viewer",
"id": "fadba0541baa8c4ed3ec4feae2468032f451f06f",
"size": "7395",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "trace_viewer/core/analysis/multi_event_summary_table.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "26321"
},
{
"name": "HTML",
"bytes": "6923565"
},
{
"name": "JavaScript",
"bytes": "22321"
},
{
"name": "Python",
"bytes": "93698"
}
],
"symlink_target": ""
} |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_RENDERER_RENDER_VIEW_H_
#define CONTENT_RENDERER_RENDER_VIEW_H_
#pragma once
#include <deque>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/gtest_prod_util.h"
#include "base/id_map.h"
#include "base/memory/linked_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/timer.h"
#include "build/build_config.h"
#include "content/renderer/renderer_webcookiejar_impl.h"
#include "content/common/edit_command.h"
#include "content/common/navigation_gesture.h"
#include "content/common/page_zoom.h"
#include "content/common/renderer_preferences.h"
#include "content/renderer/pepper_plugin_delegate_impl.h"
#include "content/renderer/render_widget.h"
#include "ipc/ipc_platform_file.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebAccessibilityNotification.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebConsoleMessage.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileSystem.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrameClient.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextDirection.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebViewClient.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebNavigationType.h"
#include "ui/gfx/surface/transport_dib.h"
#include "webkit/glue/webpreferences.h"
#include "webkit/plugins/npapi/webplugin_page_delegate.h"
#include "base/meegotouch_config.h"
#if defined(OS_WIN)
// RenderView is a diamond-shaped hierarchy, with WebWidgetClient at the root.
// VS warns when we inherit the WebWidgetClient method implementations from
// RenderWidget. It's safe to ignore that warning.
#pragma warning(disable: 4250)
#endif
class AudioMessageFilter;
class DeviceOrientationDispatcher;
class ExternalPopupMenu;
class FilePath;
class GeolocationDispatcher;
class GURL;
class LoadProgressTracker;
class NavigationState;
class NotificationProvider;
class P2PSocketDispatcher;
class PepperDeviceTest;
class PrintWebViewHelper;
class RenderViewObserver;
class RenderViewVisitor;
class RenderWidgetFullscreenPepper;
class SkBitmap;
class SpeechInputDispatcher;
class WebPluginDelegatePepper;
class WebPluginDelegateProxy;
class WebUIBindings;
struct ContextMenuMediaParams;
struct PP_Flash_NetAddress;
struct ViewHostMsg_RunFileChooser_Params;
struct ViewMsg_ClosePage_Params;
struct ViewMsg_Navigate_Params;
struct ViewMsg_StopFinding_Params;
struct WebDropData;
namespace base {
class WaitableEvent;
}
namespace chrome {
class ChromeContentRendererClient;
}
namespace gfx {
class Point;
class Rect;
}
namespace webkit {
namespace npapi {
class PluginGroup;
} // namespace npapi
namespace ppapi {
class PluginInstance;
class PluginModule;
} // namespace ppapi
} // namespace webkit
namespace webkit_glue {
struct CustomContextMenuContext;
class ImageResourceFetcher;
struct FileUploadData;
struct FormData;
struct PasswordFormFillData;
class ResourceFetcher;
class VideoRendererImpl;
}
namespace WebKit {
class WebAccessibilityCache;
class WebAccessibilityObject;
class WebApplicationCacheHost;
class WebApplicationCacheHostClient;
class WebDataSource;
class WebDocument;
class WebDragData;
class WebFrame;
class WebGeolocationClient;
class WebGeolocationServiceInterface;
class WebImage;
class WebInputElement;
class WebKeyboardEvent;
class WebMediaPlayer;
class WebMediaPlayerClient;
class WebMouseEvent;
class WebPlugin;
class WebSpeechInputController;
class WebSpeechInputListener;
class WebStorageNamespace;
class WebURLRequest;
class WebView;
struct WebContextMenuData;
struct WebFileChooserParams;
struct WebFindOptions;
struct WebMediaPlayerAction;
struct WebPluginParams;
struct WebPoint;
struct WebWindowFeatures;
}
// We need to prevent a page from trying to create infinite popups. It is not
// as simple as keeping a count of the number of immediate children
// popups. Having an html file that window.open()s itself would create
// an unlimited chain of RenderViews who only have one RenderView child.
//
// Therefore, each new top level RenderView creates a new counter and shares it
// with all its children and grandchildren popup RenderViews created with
// createView() to have a sort of global limit for the page so no more than
// kMaximumNumberOfPopups popups are created.
//
// This is a RefCounted holder of an int because I can't say
// scoped_refptr<int>.
typedef base::RefCountedData<int> SharedRenderViewCounter;
//
// RenderView is an object that manages a WebView object, and provides a
// communication interface with an embedding application process
//
class RenderView : public RenderWidget,
public WebKit::WebViewClient,
public WebKit::WebFrameClient,
public webkit::npapi::WebPluginPageDelegate,
public base::SupportsWeakPtr<RenderView> {
public:
// Creates a new RenderView. The parent_hwnd specifies a HWND to use as the
// parent of the WebView HWND that will be created. If this is a constrained
// popup or as a new tab, opener_id is the routing ID of the RenderView
// responsible for creating this RenderView (corresponding to parent_hwnd).
// |counter| is either a currently initialized counter, or NULL (in which case
// we treat this RenderView as a top level window).
static RenderView* Create(
RenderThreadBase* render_thread,
gfx::NativeViewId parent_hwnd,
gfx::PluginWindowHandle compositing_surface,
int32 opener_id,
const RendererPreferences& renderer_prefs,
const WebPreferences& webkit_prefs,
SharedRenderViewCounter* counter,
int32 routing_id,
int64 session_storage_namespace_id,
const string16& frame_name);
// Visit all RenderViews with a live WebView (i.e., RenderViews that have
// been closed but not yet destroyed are excluded).
static void ForEach(RenderViewVisitor* visitor);
// Returns the RenderView containing the given WebView.
static RenderView* FromWebView(WebKit::WebView* webview);
// Sets the "next page id" counter.
static void SetNextPageID(int32 next_page_id);
// May return NULL when the view is closing.
WebKit::WebView* webview() const;
bool is_prerendering() const { return is_prerendering_; }
int page_id() const { return page_id_; }
PepperPluginDelegateImpl* pepper_delegate() { return &pepper_delegate_; }
AudioMessageFilter* audio_message_filter() {
return audio_message_filter_;
}
const WebPreferences& webkit_preferences() const {
return webkit_preferences_;
}
bool content_state_immediately() { return send_content_state_immediately_; }
int enabled_bindings() const { return enabled_bindings_; }
void set_enabled_bindings(int b) { enabled_bindings_ = b; }
void set_send_content_state_immediately(bool value) {
send_content_state_immediately_ = value;
}
// Returns true if we should display scrollbars for the given view size and
// false if the scrollbars should be hidden.
bool should_display_scrollbars(int width, int height) const {
return (!send_preferred_size_changes_ ||
(disable_scrollbars_size_limit_.width() <= width ||
disable_scrollbars_size_limit_.height() <= height));
}
const WebKit::WebNode& context_menu_node() { return context_menu_node_; }
// Current P2PSocketDispatcher. Set to NULL if P2P API is disabled.
P2PSocketDispatcher* p2p_socket_dispatcher() {
return p2p_socket_dispatcher_;
}
// Functions to add and remove observers for this object.
void AddObserver(RenderViewObserver* observer);
void RemoveObserver(RenderViewObserver* observer);
// Evaluates a string of JavaScript in a particular frame.
void EvaluateScript(const string16& frame_xpath,
const string16& jscript,
int id,
bool notify_result);
// Adds the given file chooser request to the file_chooser_completion_ queue
// (see that var for more) and requests the chooser be displayed if there are
// no other waiting items in the queue.
//
// Returns true if the chooser was successfully scheduled. False means we
// didn't schedule anything.
bool ScheduleFileChooser(const ViewHostMsg_RunFileChooser_Params& params,
WebKit::WebFileChooserCompletion* completion);
// Sets whether the renderer should report load progress to the browser.
void SetReportLoadProgressEnabled(bool enabled);
// Gets the focused node. If no such node exists then the node will be isNull.
WebKit::WebNode GetFocusedNode() const;
// Returns true if the parameter node is a textfield, text area or a content
// editable div.
bool IsEditableNode(const WebKit::WebNode& node);
void LoadNavigationErrorPage(WebKit::WebFrame* frame,
const WebKit::WebURLRequest& failed_request,
const WebKit::WebURLError& error,
const std::string& html,
bool replace);
// Plugin-related functions --------------------------------------------------
// (See also WebPluginPageDelegate implementation.)
// Notification that the given plugin has crashed.
void PluginCrashed(const FilePath& plugin_path);
// Notification that the default plugin has done something about a missing
// plugin. See default_plugin_shared.h for possible values of |status|.
void OnMissingPluginStatus(WebPluginDelegateProxy* delegate,
int status);
// Create a new NPAPI plugin.
WebKit::WebPlugin* CreateNPAPIPlugin(WebKit::WebFrame* frame,
const WebKit::WebPluginParams& params,
const FilePath& path,
const std::string& mime_type);
// Create a new Pepper plugin.
WebKit::WebPlugin* CreatePepperPlugin(
WebKit::WebFrame* frame,
const WebKit::WebPluginParams& params,
const FilePath& path,
webkit::ppapi::PluginModule* pepper_module);
// Creates a fullscreen container for a pepper plugin instance.
RenderWidgetFullscreenPepper* CreatePepperFullscreenContainer(
webkit::ppapi::PluginInstance* plugin);
// Create a new plugin without checking the content settings.
WebKit::WebPlugin* CreatePluginNoCheck(WebKit::WebFrame* frame,
const WebKit::WebPluginParams& params);
#if defined(OS_MACOSX)
// Informs the render view that the given plugin has gained or lost focus.
void PluginFocusChanged(bool focused, int plugin_id);
// Starts plugin IME.
void StartPluginIme();
// Helper routines for accelerated plugin support. Used by the
// WebPluginDelegateProxy, which has a pointer to the RenderView.
gfx::PluginWindowHandle AllocateFakePluginWindowHandle(bool opaque,
bool root);
void DestroyFakePluginWindowHandle(gfx::PluginWindowHandle window);
void AcceleratedSurfaceSetIOSurface(gfx::PluginWindowHandle window,
int32 width,
int32 height,
uint64 io_surface_identifier);
TransportDIB::Handle AcceleratedSurfaceAllocTransportDIB(size_t size);
void AcceleratedSurfaceFreeTransportDIB(TransportDIB::Id dib_id);
void AcceleratedSurfaceSetTransportDIB(gfx::PluginWindowHandle window,
int32 width,
int32 height,
TransportDIB::Handle transport_dib);
void AcceleratedSurfaceBuffersSwapped(gfx::PluginWindowHandle window,
uint64 surface_id);
#endif
void RegisterPluginDelegate(WebPluginDelegateProxy* delegate);
void UnregisterPluginDelegate(WebPluginDelegateProxy* delegate);
// IPC::Channel::Listener implementation -------------------------------------
virtual bool OnMessageReceived(const IPC::Message& msg);
// WebKit::WebWidgetClient implementation ------------------------------------
// Most methods are handled by RenderWidget.
virtual void didFocus();
virtual void didBlur();
virtual void show(WebKit::WebNavigationPolicy policy);
virtual void runModal();
// WebKit::WebViewClient implementation --------------------------------------
virtual WebKit::WebView* createView(
WebKit::WebFrame* creator,
const WebKit::WebURLRequest& request,
const WebKit::WebWindowFeatures& features,
const WebKit::WebString& frame_name);
virtual WebKit::WebWidget* createPopupMenu(WebKit::WebPopupType popup_type);
virtual WebKit::WebWidget* createPopupMenu(
const WebKit::WebPopupMenuInfo& info);
virtual WebKit::WebExternalPopupMenu* createExternalPopupMenu(
const WebKit::WebPopupMenuInfo& popup_menu_info,
WebKit::WebExternalPopupMenuClient* popup_menu_client);
virtual WebKit::WebStorageNamespace* createSessionStorageNamespace(
unsigned quota);
virtual void didAddMessageToConsole(
const WebKit::WebConsoleMessage& message,
const WebKit::WebString& source_name,
unsigned source_line);
virtual void printPage(WebKit::WebFrame* frame);
virtual WebKit::WebNotificationPresenter* notificationPresenter();
virtual bool enumerateChosenDirectory(
const WebKit::WebString& path,
WebKit::WebFileChooserCompletion* chooser_completion);
virtual void didStartLoading();
virtual void didStopLoading();
virtual void didChangeLoadProgress(WebKit::WebFrame* frame,
double load_progress);
virtual bool isSmartInsertDeleteEnabled();
virtual bool isSelectTrailingWhitespaceEnabled();
virtual void didChangeSelection(bool is_selection_empty);
virtual void didExecuteCommand(const WebKit::WebString& command_name);
virtual bool handleCurrentKeyboardEvent();
virtual bool runFileChooser(
const WebKit::WebFileChooserParams& params,
WebKit::WebFileChooserCompletion* chooser_completion);
virtual void runModalAlertDialog(WebKit::WebFrame* frame,
const WebKit::WebString& message);
virtual bool runModalConfirmDialog(WebKit::WebFrame* frame,
const WebKit::WebString& message);
virtual bool runModalPromptDialog(WebKit::WebFrame* frame,
const WebKit::WebString& message,
const WebKit::WebString& default_value,
WebKit::WebString* actual_value);
virtual bool runModalBeforeUnloadDialog(WebKit::WebFrame* frame,
const WebKit::WebString& message);
virtual void showContextMenu(WebKit::WebFrame* frame,
const WebKit::WebContextMenuData& data);
virtual bool supportsFullscreen();
virtual void enterFullscreenForNode(const WebKit::WebNode&);
virtual void exitFullscreenForNode(const WebKit::WebNode&);
virtual void setStatusText(const WebKit::WebString& text);
virtual void setMouseOverURL(const WebKit::WebURL& url);
virtual void setKeyboardFocusURL(const WebKit::WebURL& url);
virtual void setToolTipText(const WebKit::WebString& text,
WebKit::WebTextDirection hint);
virtual void startDragging(const WebKit::WebDragData& data,
WebKit::WebDragOperationsMask mask,
const WebKit::WebImage& image,
const WebKit::WebPoint& imageOffset);
virtual bool acceptsLoadDrops();
virtual void focusNext();
virtual void focusPrevious();
virtual void focusedNodeChanged(const WebKit::WebNode& node);
virtual void navigateBackForwardSoon(int offset);
virtual int historyBackListCount();
virtual int historyForwardListCount();
virtual void postAccessibilityNotification(
const WebKit::WebAccessibilityObject& obj,
WebKit::WebAccessibilityNotification notification);
virtual void didUpdateInspectorSetting(const WebKit::WebString& key,
const WebKit::WebString& value);
virtual WebKit::WebGeolocationClient* geolocationClient();
virtual WebKit::WebSpeechInputController* speechInputController(
WebKit::WebSpeechInputListener* listener);
virtual WebKit::WebDeviceOrientationClient* deviceOrientationClient();
virtual void zoomLimitsChanged(double minimum_level, double maximum_level);
virtual void zoomLevelChanged();
virtual void registerProtocolHandler(const WebKit::WebString& scheme,
const WebKit::WebString& base_url,
const WebKit::WebString& url,
const WebKit::WebString& title);
// WebKit::WebFrameClient implementation -------------------------------------
virtual WebKit::WebPlugin* createPlugin(
WebKit::WebFrame* frame,
const WebKit::WebPluginParams& params);
virtual WebKit::WebWorker* createWorker(WebKit::WebFrame* frame,
WebKit::WebWorkerClient* client);
virtual WebKit::WebSharedWorker* createSharedWorker(
WebKit::WebFrame* frame, const WebKit::WebURL& url,
const WebKit::WebString& name, unsigned long long documentId);
virtual WebKit::WebMediaPlayer* createMediaPlayer(
WebKit::WebFrame* frame,
WebKit::WebMediaPlayerClient* client);
#if defined(TOOLKIT_MEEGOTOUCH)
/*PolicyAware */
virtual int resourceRequire(
WebKit::WebFrame* frame,
WebKit::WebMediaPlayer* client);
virtual int resourceRelease(void);
virtual int isHidden(void);
#endif
virtual WebKit::WebApplicationCacheHost* createApplicationCacheHost(
WebKit::WebFrame* frame,
WebKit::WebApplicationCacheHostClient* client);
virtual WebKit::WebCookieJar* cookieJar(WebKit::WebFrame* frame);
virtual void frameDetached(WebKit::WebFrame* frame);
virtual void willClose(WebKit::WebFrame* frame);
virtual void loadURLExternally(WebKit::WebFrame* frame,
const WebKit::WebURLRequest& request,
WebKit::WebNavigationPolicy policy);
virtual WebKit::WebNavigationPolicy decidePolicyForNavigation(
WebKit::WebFrame* frame,
const WebKit::WebURLRequest& request,
WebKit::WebNavigationType type,
const WebKit::WebNode&,
WebKit::WebNavigationPolicy default_policy,
bool is_redirect);
virtual bool canHandleRequest(WebKit::WebFrame* frame,
const WebKit::WebURLRequest& request);
virtual WebKit::WebURLError cannotHandleRequestError(
WebKit::WebFrame* frame,
const WebKit::WebURLRequest& request);
virtual WebKit::WebURLError cancelledError(
WebKit::WebFrame* frame,
const WebKit::WebURLRequest& request);
virtual void unableToImplementPolicyWithError(
WebKit::WebFrame* frame,
const WebKit::WebURLError& error);
virtual void willSendSubmitEvent(WebKit::WebFrame* frame,
const WebKit::WebFormElement& form);
virtual void willSubmitForm(WebKit::WebFrame* frame,
const WebKit::WebFormElement& form);
virtual void willPerformClientRedirect(WebKit::WebFrame* frame,
const WebKit::WebURL& from,
const WebKit::WebURL& to,
double interval,
double fire_time);
virtual void didCancelClientRedirect(WebKit::WebFrame* frame);
virtual void didCompleteClientRedirect(WebKit::WebFrame* frame,
const WebKit::WebURL& from);
virtual void didCreateDataSource(WebKit::WebFrame* frame,
WebKit::WebDataSource* datasource);
virtual void didStartProvisionalLoad(WebKit::WebFrame* frame);
virtual void didReceiveServerRedirectForProvisionalLoad(
WebKit::WebFrame* frame);
virtual void didFailProvisionalLoad(WebKit::WebFrame* frame,
const WebKit::WebURLError& error);
virtual void didReceiveDocumentData(WebKit::WebFrame* frame,
const char* data, size_t length,
bool& prevent_default);
virtual void didCommitProvisionalLoad(WebKit::WebFrame* frame,
bool is_new_navigation);
virtual void didClearWindowObject(WebKit::WebFrame* frame);
virtual void didCreateDocumentElement(WebKit::WebFrame* frame);
virtual void didReceiveTitle(WebKit::WebFrame* frame,
const WebKit::WebString& title);
virtual void didChangeIcons(WebKit::WebFrame*);
virtual void didFinishDocumentLoad(WebKit::WebFrame* frame);
virtual void didHandleOnloadEvents(WebKit::WebFrame* frame);
virtual void didFailLoad(WebKit::WebFrame* frame,
const WebKit::WebURLError& error);
virtual void didFinishLoad(WebKit::WebFrame* frame);
virtual void didNavigateWithinPage(WebKit::WebFrame* frame,
bool is_new_navigation);
virtual void didUpdateCurrentHistoryItem(WebKit::WebFrame* frame);
virtual void assignIdentifierToRequest(WebKit::WebFrame* frame,
unsigned identifier,
const WebKit::WebURLRequest& request);
virtual void willSendRequest(WebKit::WebFrame* frame,
unsigned identifier,
WebKit::WebURLRequest& request,
const WebKit::WebURLResponse& redirect_response);
virtual void didReceiveResponse(WebKit::WebFrame* frame,
unsigned identifier,
const WebKit::WebURLResponse& response);
virtual void didFinishResourceLoad(WebKit::WebFrame* frame,
unsigned identifier);
virtual void didFailResourceLoad(WebKit::WebFrame* frame,
unsigned identifier,
const WebKit::WebURLError& error);
virtual void didLoadResourceFromMemoryCache(
WebKit::WebFrame* frame,
const WebKit::WebURLRequest& request,
const WebKit::WebURLResponse&);
virtual void didDisplayInsecureContent(WebKit::WebFrame* frame);
virtual void didRunInsecureContent(
WebKit::WebFrame* frame,
const WebKit::WebSecurityOrigin& origin,
const WebKit::WebURL& target);
virtual bool allowImages(WebKit::WebFrame* frame, bool enabled_per_settings);
virtual bool allowPlugins(WebKit::WebFrame* frame, bool enabled_per_settings);
virtual bool allowScript(WebKit::WebFrame* frame, bool enabled_per_settings);
virtual bool allowDatabase(WebKit::WebFrame* frame,
const WebKit::WebString& name,
const WebKit::WebString& display_name,
unsigned long estimated_size);
virtual void didNotAllowScript(WebKit::WebFrame* frame);
virtual void didNotAllowPlugins(WebKit::WebFrame* frame);
virtual void didExhaustMemoryAvailableForScript(WebKit::WebFrame* frame);
virtual void didCreateScriptContext(WebKit::WebFrame* frame);
virtual void didDestroyScriptContext(WebKit::WebFrame* frame);
virtual void didCreateIsolatedScriptContext(WebKit::WebFrame* frame);
virtual bool allowScriptExtension(WebKit::WebFrame*,
const WebKit::WebString& extension_name,
int extensionGroup);
virtual void logCrossFramePropertyAccess(
WebKit::WebFrame* frame,
WebKit::WebFrame* target,
bool cross_origin,
const WebKit::WebString& property_name,
unsigned long long event_id);
virtual void didChangeContentsSize(WebKit::WebFrame* frame,
const WebKit::WebSize& size);
virtual void didChangeScrollOffset(WebKit::WebFrame* frame);
virtual void reportFindInPageMatchCount(int request_id,
int count,
bool final_update);
virtual void reportFindInPageSelection(int request_id,
int active_match_ordinal,
const WebKit::WebRect& sel);
virtual void openFileSystem(WebKit::WebFrame* frame,
WebKit::WebFileSystem::Type type,
long long size,
bool create,
WebKit::WebFileSystemCallbacks* callbacks);
virtual void queryStorageUsageAndQuota(
WebKit::WebFrame* frame,
WebKit::WebStorageQuotaType type,
WebKit::WebStorageQuotaCallbacks* callbacks);
virtual void requestStorageQuota(
WebKit::WebFrame* frame,
WebKit::WebStorageQuotaType type,
unsigned long long requested_size,
WebKit::WebStorageQuotaCallbacks* callbacks);
// webkit_glue::WebPluginPageDelegate implementation -------------------------
virtual webkit::npapi::WebPluginDelegate* CreatePluginDelegate(
const FilePath& file_path,
const std::string& mime_type);
virtual void CreatedPluginWindow(gfx::PluginWindowHandle handle);
virtual void WillDestroyPluginWindow(gfx::PluginWindowHandle handle);
virtual void DidMovePlugin(const webkit::npapi::WebPluginGeometry& move);
virtual void DidStartLoadingForPlugin();
virtual void DidStopLoadingForPlugin();
virtual WebKit::WebCookieJar* GetCookieJar();
#if defined(TOOLKIT_MEEGOTOUCH)
virtual WebKit::WebRect PluginFullScreenRect();
#endif
#if defined(PLUGIN_DIRECT_RENDERING)
void UpdatePluginWidget(
unsigned int pixmap_id,
const gfx::Rect& rect,
unsigned int seq,
WebPluginDelegateProxy* proxy);
void DestroyPluginWidget(WebPluginDelegateProxy* proxy);
#endif
// Please do not add your stuff randomly to the end here. If there is an
// appropriate section, add it there. If not, there are some random functions
// nearer to the top you can add it to.
virtual void DidFlushPaint();
// Cannot use std::set unfortunately since linked_ptr<> does not support
// operator<.
typedef std::vector<linked_ptr<webkit_glue::ImageResourceFetcher> >
ImageResourceFetcherList;
protected:
// RenderWidget overrides:
virtual void Close();
virtual void OnResize(const gfx::Size& new_size,
const gfx::Rect& resizer_rect);
virtual void DidInitiatePaint();
virtual webkit::ppapi::PluginInstance* GetBitmapForOptimizedPluginPaint(
const gfx::Rect& paint_bounds,
TransportDIB** dib,
gfx::Rect* location,
gfx::Rect* clip);
virtual gfx::Point GetScrollOffset();
virtual void DidHandleKeyEvent();
virtual void DidHandleMouseEvent(const WebKit::WebMouseEvent& event);
virtual void OnSetFocus(bool enable);
virtual void OnWasHidden();
virtual void OnWasRestored(bool needs_repainting);
#if defined(PLUGIN_DIRECT_RENDERING)
void OnDidPaintPluginWidget(
unsigned int id,
unsigned int ack);
#endif
private:
// For unit tests.
friend class ExternalPopupMenuTest;
friend class PepperDeviceTest;
friend class RenderViewTest;
FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuRemoveTest, RemoveOnChange);
FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuTest, NormalCase);
FRIEND_TEST_ALL_PREFIXES(ExternalPopupMenuTest, ShowPopupThenNavigate);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, ImeComposition);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, InsertCharacters);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, JSBlockSentAfterPageLoad);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, LastCommittedUpdateState);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, OnHandleKeyboardEvent);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, OnImeStateChanged);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, OnNavStateChanged);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, OnSetTextDirection);
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, UpdateTargetURLWithInvalidURL);
#if defined(OS_MACOSX)
FRIEND_TEST_ALL_PREFIXES(RenderViewTest, MacTestCmdUp);
#endif
typedef std::map<GURL, double> HostZoomLevels;
// Identifies an accessibility notification from webkit.
struct RendererAccessibilityNotification {
public:
bool ShouldIncludeChildren();
// The webkit glue id of the accessibility object.
int32 id;
// The accessibility notification type.
WebKit::WebAccessibilityNotification type;
};
enum ErrorPageType {
DNS_ERROR,
HTTP_404,
CONNECTION_ERROR,
};
RenderView(RenderThreadBase* render_thread,
gfx::NativeViewId parent_hwnd,
gfx::PluginWindowHandle compositing_surface,
int32 opener_id,
const RendererPreferences& renderer_prefs,
const WebPreferences& webkit_prefs,
SharedRenderViewCounter* counter,
int32 routing_id,
int64 session_storage_namespace_id,
const string16& frame_name);
// Do not delete directly. This class is reference counted.
virtual ~RenderView();
void UpdateURL(WebKit::WebFrame* frame);
void UpdateTitle(WebKit::WebFrame* frame, const string16& title);
void UpdateSessionHistory(WebKit::WebFrame* frame);
// Update current main frame's encoding and send it to browser window.
// Since we want to let users see the right encoding info from menu
// before finishing loading, we call the UpdateEncoding in
// a) function:DidCommitLoadForFrame. When this function is called,
// that means we have got first data. In here we try to get encoding
// of page if it has been specified in http header.
// b) function:DidReceiveTitle. When this function is called,
// that means we have got specified title. Because in most of webpages,
// title tags will follow meta tags. In here we try to get encoding of
// page if it has been specified in meta tag.
// c) function:DidFinishDocumentLoadForFrame. When this function is
// called, that means we have got whole html page. In here we should
// finally get right encoding of page.
void UpdateEncoding(WebKit::WebFrame* frame,
const std::string& encoding_name);
void OpenURL(const GURL& url, const GURL& referrer,
WebKit::WebNavigationPolicy policy);
bool RunJavaScriptMessage(int type,
const std::wstring& message,
const std::wstring& default_value,
const GURL& frame_url,
std::wstring* result);
// Sends a message and runs a nested message loop.
bool SendAndRunNestedMessageLoop(IPC::SyncMessage* message);
// Send queued accessibility notifications from the renderer to the browser.
void SendPendingAccessibilityNotifications();
// IPC message handlers ------------------------------------------------------
//
// The documentation for these functions should be in
// render_messages_internal.h for the message that the function is handling.
#if defined(TOOLKIT_MEEGOTOUCH)
void OnQueryScrollOffset(gfx::Point* output);
void OnSetSelectionRange(gfx::Point start, gfx::Point end, bool set);
void OnSelectItem(gfx::Point pos);
void OnCommitSelection();
/*PolicyAware Application*/
void OnResourceGet(int type);
void OnResourceInUsed(void);
void OnBackgroundPolicy(void);
void FreeHwResource(void);
// reimplement from webviewclient
virtual void UpdateSelectionRange(WebKit::WebPoint&, WebKit::WebPoint&, int height, bool set);
#endif
void OnAccessibilityDoDefaultAction(int acc_obj_id);
void OnAccessibilityNotificationsAck();
void OnAllowBindings(int enabled_bindings_flags);
void OnAllowScriptToClose(bool script_can_close);
void OnAsyncFileOpened(base::PlatformFileError error_code,
IPC::PlatformFileForTransit file_for_transit,
int message_id);
void OnPpapiBrokerChannelCreated(int request_id,
base::ProcessHandle broker_process_handle,
IPC::ChannelHandle handle);
void OnCancelDownload(int32 download_id);
void OnClearFocusedNode();
void OnClosePage(const ViewMsg_ClosePage_Params& params);
#if defined(ENABLE_FLAPPER_HACKS)
void OnConnectTcpACK(int request_id,
IPC::PlatformFileForTransit socket_for_transit,
const PP_Flash_NetAddress& local_addr,
const PP_Flash_NetAddress& remote_addr);
#endif
void OnContextMenuClosed(
const webkit_glue::CustomContextMenuContext& custom_context);
void OnCopy();
void OnCopyImageAt(int x, int y);
#if defined(OS_MACOSX)
void OnCopyToFindPboard();
#endif
void OnCut();
void OnCSSInsertRequest(const std::wstring& frame_xpath,
const std::string& css,
const std::string& id);
void OnCustomContextMenuAction(
const webkit_glue::CustomContextMenuContext& custom_context,
unsigned action);
void OnDelete();
void OnDeterminePageLanguage();
void OnDisableScrollbarsForSmallWindows(
const gfx::Size& disable_scrollbars_size_limit);
void OnDisassociateFromPopupCount();
void OnDragSourceEndedOrMoved(const gfx::Point& client_point,
const gfx::Point& screen_point,
bool ended,
WebKit::WebDragOperation drag_operation);
void OnDragSourceSystemDragEnded();
void OnDragTargetDrop(const gfx::Point& client_pt,
const gfx::Point& screen_pt);
void OnDragTargetDragEnter(const WebDropData& drop_data,
const gfx::Point& client_pt,
const gfx::Point& screen_pt,
WebKit::WebDragOperationsMask operations_allowed);
void OnDragTargetDragLeave();
void OnDragTargetDragOver(const gfx::Point& client_pt,
const gfx::Point& screen_pt,
WebKit::WebDragOperationsMask operations_allowed);
void OnEnablePreferredSizeChangedMode(int flags);
void OnEnumerateDirectoryResponse(int id, const std::vector<FilePath>& paths);
void OnExecuteEditCommand(const std::string& name, const std::string& value);
void OnFileChooserResponse(const std::vector<FilePath>& paths);
void OnFind(int request_id, const string16&, const WebKit::WebFindOptions&);
void OnFindReplyAck();
void OnEnableAccessibility();
void OnInstallMissingPlugin();
void OnDisplayPrerenderedPage();
void OnMediaPlayerActionAt(const gfx::Point& location,
const WebKit::WebMediaPlayerAction& action);
void OnMoveOrResizeStarted();
void OnNavigate(const ViewMsg_Navigate_Params& params);
void OnNetworkStateChanged(bool online);
void OnPaste();
#if defined(OS_MACOSX)
void OnPluginImeCompositionCompleted(const string16& text, int plugin_id);
#endif
void OnRedo();
void OnReloadFrame();
void OnReplace(const string16& text);
void OnReservePageIDRange(int size_of_range);
void OnResetPageEncodingToDefault();
void OnScriptEvalRequest(const string16& frame_xpath,
const string16& jscript,
int id,
bool notify_result);
void OnSelectAll();
void OnSetAccessibilityFocus(int acc_obj_id);
void OnSetActive(bool active);
void OnSetAltErrorPageURL(const GURL& gurl);
void OnSetBackground(const SkBitmap& background);
void OnSetWebUIProperty(const std::string& name, const std::string& value);
void OnSetEditCommandsForNextKeyEvent(const EditCommands& edit_commands);
void OnSetInitialFocus(bool reverse);
void OnScrollFocusedEditableNodeIntoView();
void OnSetPageEncoding(const std::string& encoding_name);
void OnSetRendererPrefs(const RendererPreferences& renderer_prefs);
#if defined(OS_MACOSX)
void OnSetWindowVisibility(bool visible);
#endif
void OnSetZoomLevel(double zoom_level);
void OnSetZoomLevelForLoadingURL(const GURL& url, double zoom_level);
void OnShouldClose();
void OnStop();
void OnStopFinding(const ViewMsg_StopFinding_Params& params);
void OnThemeChanged();
void OnUndo();
void OnUpdateTargetURLAck();
void OnUpdateWebPreferences(const WebPreferences& prefs);
#if defined(OS_MACOSX)
void OnWindowFrameChanged(const gfx::Rect& window_frame,
const gfx::Rect& view_frame);
#endif
#if defined(OS_MACOSX) || defined (TOOLKIT_MEEGOTOUCH)
void OnSelectPopupMenuItem(int selected_index);
#endif
void OnZoom(PageZoom::Function function);
void OnZoomFactor(double factor);
void OnQueryZoomFactor(double* factor);
void OnSetScrollPosition(int x, int y);
void OnMsgPaintContents(const TransportDIB::Handle& dib_id,
const gfx::Rect& rect,
int* retval);
void OnGetLayoutAlgorithm(int *retval);
void OnSetLayoutAlgorithm(int algorithm);
void OnZoom2TextPre(int x, int y);
void OnZoom2TextPost();
// Adding a new message handler? Please add it in alphabetical order above
// and put it in the same position in the .cc file.
// Misc private functions ----------------------------------------------------
void AltErrorPageFinished(WebKit::WebFrame* frame,
const WebKit::WebURLError& original_error,
const std::string& html);
// Check whether the preferred size has changed. This is called periodically
// by preferred_size_change_timer_.
void CheckPreferredSize();
// This callback is triggered when DownloadFavicon completes, either
// succesfully or with a failure. See DownloadFavicon for more
// details.
void DidDownloadFavicon(webkit_glue::ImageResourceFetcher* fetcher,
const SkBitmap& image);
// Requests to download a favicon image. When done, the RenderView
// is notified by way of DidDownloadFavicon. Returns true if the
// request was successfully started, false otherwise. id is used to
// uniquely identify the request and passed back to the
// DidDownloadFavicon method. If the image has multiple frames, the
// frame whose size is image_size is returned. If the image doesn't
// have a frame at the specified size, the first is returned.
bool DownloadFavicon(int id, const GURL& image_url, int image_size);
GURL GetAlternateErrorPageURL(const GURL& failed_url,
ErrorPageType error_type);
// Locates a sub frame with given xpath
WebKit::WebFrame* GetChildFrame(const std::wstring& frame_xpath) const;
WebUIBindings* GetWebUIBindings();
// Should only be called if this object wraps a PluginDocument.
WebKit::WebPlugin* GetWebPluginFromPluginDocument();
// Inserts a string of CSS in a particular frame. |id| can be specified to
// give the CSS style element an id, and (if specified) will replace the
// element with the same id.
void InsertCSS(const std::wstring& frame_xpath,
const std::string& css,
const std::string& id);
// Returns false unless this is a top-level navigation that crosses origins.
bool IsNonLocalTopLevelNavigation(const GURL& url,
WebKit::WebFrame* frame,
WebKit::WebNavigationType type);
bool MaybeLoadAlternateErrorPage(WebKit::WebFrame* frame,
const WebKit::WebURLError& error,
bool replace);
// Starts nav_state_sync_timer_ if it isn't already running.
void StartNavStateSyncTimerIfNecessary();
// Dispatches the current navigation state to the browser. Called on a
// periodic timer so we don't send too many messages.
void SyncNavigationState();
#if defined(OS_LINUX)
void UpdateFontRenderingFromRendererPrefs();
#else
void UpdateFontRenderingFromRendererPrefs() {}
#endif
// Update the target url and tell the browser that the target URL has changed.
// If |url| is empty, show |fallback_url|.
void UpdateTargetURL(const GURL& url, const GURL& fallback_url);
// ---------------------------------------------------------------------------
// ADDING NEW FUNCTIONS? Please keep private functions alphabetized and put
// it in the same order in the .cc file as it was in the header.
// ---------------------------------------------------------------------------
// Settings ------------------------------------------------------------------
WebPreferences webkit_preferences_;
RendererPreferences renderer_preferences_;
HostZoomLevels host_zoom_levels_;
// Whether content state (such as form state, scroll position and page
// contents) should be sent to the browser immediately. This is normally
// false, but set to true by some tests.
bool send_content_state_immediately_;
// Bitwise-ORed set of extra bindings that have been enabled. See
// BindingsPolicy for details.
int enabled_bindings_;
// The alternate error page URL, if one exists.
GURL alternate_error_page_url_;
// If true, we send IPC messages when |preferred_size_| changes.
bool send_preferred_size_changes_;
// If non-empty, and |send_preferred_size_changes_| is true, disable drawing
// scroll bars on windows smaller than this size. Used for windows that the
// browser resizes to the size of the content, such as browser action popups.
// If a render view is set to the minimum size of its content, webkit may add
// scroll bars. This makes sense for fixed sized windows, but it does not
// make sense when the size of the view was chosen to fit the content.
// This setting ensures that no scroll bars are drawn. The size limit exists
// because if the view grows beyond a size known to the browser, scroll bars
// should be drawn.
gfx::Size disable_scrollbars_size_limit_;
// Loading state -------------------------------------------------------------
// True if the top level frame is currently being loaded.
bool is_loading_;
// The gesture that initiated the current navigation.
NavigationGesture navigation_gesture_;
// Used for popups.
bool opened_by_user_gesture_;
GURL creator_url_;
// Whether this RenderView was created by a frame that was suppressing its
// opener. If so, we may want to load pages in a separate process. See
// decidePolicyForNavigation for details.
bool opener_suppressed_;
// If we are handling a top-level client-side redirect, this tracks the URL
// of the page that initiated it. Specifically, when a load is committed this
// is used to determine if that load originated from a client-side redirect.
// It is empty if there is no top-level client-side redirect.
GURL completed_client_redirect_src_;
// Holds state pertaining to a navigation that we initiated. This is held by
// the WebDataSource::ExtraData attribute. We use pending_navigation_state_
// as a temporary holder for the state until the WebDataSource corresponding
// to the new navigation is created. See DidCreateDataSource.
scoped_ptr<NavigationState> pending_navigation_state_;
// Timer used to delay the updating of nav state (see SyncNavigationState).
base::OneShotTimer<RenderView> nav_state_sync_timer_;
// True if the RenderView is currently prerendering a page.
bool is_prerendering_;
// Page IDs ------------------------------------------------------------------
//
// Page IDs allow the browser to identify pages in each renderer process for
// keeping back/forward history in sync.
// ID of the current page. Note that this is NOT updated for every main
// frame navigation, only for "regular" navigations that go into session
// history. In particular, client redirects, like the page cycler uses
// (document.location.href="foo") do not count as regular navigations and do
// not increment the page id.
int32 page_id_;
// Indicates the ID of the last page that we sent a FrameNavigate to the
// browser for. This is used to determine if the most recent transition
// generated a history entry (less than page_id_), or not (equal to or
// greater than). Note that this will be greater than page_id_ if the user
// goes back.
int32 last_page_id_sent_to_browser_;
// The next available page ID to use. This ensures that the page IDs are
// globally unique in the renderer.
static int32 next_page_id_;
// Page info -----------------------------------------------------------------
// The last gotten main frame's encoding.
std::string last_encoding_name_;
int history_list_offset_;
int history_list_length_;
// True if the page has any frame-level unload or beforeunload listeners.
bool has_unload_listener_;
// UI state ------------------------------------------------------------------
// The state of our target_url transmissions. When we receive a request to
// send a URL to the browser, we set this to TARGET_INFLIGHT until an ACK
// comes back - if a new request comes in before the ACK, we store the new
// URL in pending_target_url_ and set the status to TARGET_PENDING. If an
// ACK comes back and we are in TARGET_PENDING, we send the stored URL and
// revert to TARGET_INFLIGHT.
//
// We don't need a queue of URLs to send, as only the latest is useful.
enum {
TARGET_NONE,
TARGET_INFLIGHT, // We have a request in-flight, waiting for an ACK
TARGET_PENDING // INFLIGHT + we have a URL waiting to be sent
} target_url_status_;
// The URL we show the user in the status bar. We use this to determine if we
// want to send a new one (we do not need to send duplicates). It will be
// equal to either |mouse_over_url_| or |focus_url_|, depending on which was
// updated last.
GURL target_url_;
// The URL the user's mouse is hovering over.
GURL mouse_over_url_;
// The URL that has keyboard focus.
GURL focus_url_;
// The next target URL we want to send to the browser.
GURL pending_target_url_;
// The text selection the last time DidChangeSelection got called.
std::string last_selection_;
// View ----------------------------------------------------------------------
// Cache the preferred size of the page in order to prevent sending the IPC
// when layout() recomputes but doesn't actually change sizes.
gfx::Size preferred_size_;
// Nasty hack. WebKit does not send us events when the preferred size changes,
// so we must poll it. See also:
// https://bugs.webkit.org/show_bug.cgi?id=32807.
base::RepeatingTimer<RenderView> preferred_size_change_timer_;
#if defined(OS_MACOSX)
// Track the fake plugin window handles allocated on the browser side for
// the accelerated compositor and (currently) accelerated plugins so that
// we can discard them when the view goes away.
std::set<gfx::PluginWindowHandle> fake_plugin_window_handles_;
#endif
// Plugins -------------------------------------------------------------------
// Remember the first uninstalled plugin, so that we can ask the plugin
// to install itself when user clicks on the info bar.
base::WeakPtr<webkit::npapi::WebPluginDelegate> first_default_plugin_;
PepperPluginDelegateImpl pepper_delegate_;
// All the currently active plugin delegates for this RenderView; kept so that
// we can enumerate them to send updates about things like window location
// or tab focus and visibily. These are non-owning references.
std::set<WebPluginDelegateProxy*> plugin_delegates_;
// Helper objects ------------------------------------------------------------
ScopedRunnableMethodFactory<RenderView> accessibility_method_factory_;
RendererWebCookieJarImpl cookie_jar_;
// The next group of objects all implement RenderViewObserver, so are deleted
// along with the RenderView automatically. This is why we just store weak
// references.
// Holds a reference to the service which provides desktop notifications.
NotificationProvider* notification_provider_;
// The geolocation dispatcher attached to this view, lazily initialized.
GeolocationDispatcher* geolocation_dispatcher_;
// The speech dispatcher attached to this view, lazily initialized.
SpeechInputDispatcher* speech_input_dispatcher_;
// Device orientation dispatcher attached to this view; lazily initialized.
DeviceOrientationDispatcher* device_orientation_dispatcher_;
scoped_refptr<AudioMessageFilter> audio_message_filter_;
// Handles accessibility requests into the renderer side, as well as
// maintains the cache and other features of the accessibility tree.
scoped_ptr<WebKit::WebAccessibilityCache> accessibility_;
// Collect renderer accessibility notifications until they are ready to be
// sent to the browser.
std::vector<RendererAccessibilityNotification>
pending_accessibility_notifications_;
// Set if we are waiting for a accessibility notification ack.
bool accessibility_ack_pending_;
// Dispatches all P2P socket used by the renderer.
P2PSocketDispatcher* p2p_socket_dispatcher_;
// Misc ----------------------------------------------------------------------
// The current and pending file chooser completion objects. If the queue is
// nonempty, the first item represents the currently running file chooser
// callback, and the remaining elements are the other file chooser completion
// still waiting to be run (in order).
struct PendingFileChooser;
std::deque< linked_ptr<PendingFileChooser> > file_chooser_completions_;
// The current directory enumeration callback
std::map<int, WebKit::WebFileChooserCompletion*> enumeration_completions_;
int enumeration_completion_id_;
// The SessionStorage namespace that we're assigned to has an ID, and that ID
// is passed to us upon creation. WebKit asks for this ID upon first use and
// uses it whenever asking the browser process to allocate new storage areas.
int64 session_storage_namespace_id_;
// The total number of unrequested popups that exist and can be followed back
// to a common opener. This count is shared among all RenderViews created
// with createView(). All popups are treated as unrequested until
// specifically instructed otherwise by the Browser process.
scoped_refptr<SharedRenderViewCounter> shared_popup_counter_;
// Whether this is a top level window (instead of a popup). Top level windows
// shouldn't count against their own |shared_popup_counter_|.
bool decrement_shared_popup_at_destruction_;
// If the browser hasn't sent us an ACK for the last FindReply we sent
// to it, then we need to queue up the message (keeping only the most
// recent message if new ones come in).
scoped_ptr<IPC::Message> queued_find_reply_message_;
// Stores edit commands associated to the next key event.
// Shall be cleared as soon as the next key event is processed.
EditCommands edit_commands_;
// Allows Web UI pages (new tab page, etc.) to talk to the browser. The JS
// object is only exposed when Web UI bindings are enabled.
scoped_ptr<WebUIBindings> web_ui_bindings_;
// The external popup for the currently showing select popup.
scoped_ptr<ExternalPopupMenu> external_popup_menu_;
// The node that the context menu was pressed over.
WebKit::WebNode context_menu_node_;
// Reports load progress to the browser.
scoped_ptr<LoadProgressTracker> load_progress_tracker_;
#if defined(TOOLKIT_MEEGOTOUCH)
/*current media player handler*/
WebKit::WebMediaPlayer* mediaplayer_;
/*vector for all media player handler*/
std::vector<WebKit::WebMediaPlayer*> player_vec_;
#endif
// All the registered observers. We expect this list to be small, so vector
// is fine.
ObserverList<RenderViewObserver> observers_;
// ---------------------------------------------------------------------------
// ADDING NEW DATA? Please see if it fits appropriately in one of the above
// sections rather than throwing it randomly at the end. If you're adding a
// bunch of stuff, you should probably create a helper class and put your
// data and methods on that to avoid bloating RenderView more. You can use
// the Observer interface to filter IPC messages and receive frame change
// notifications.
// ---------------------------------------------------------------------------
DISALLOW_COPY_AND_ASSIGN(RenderView);
};
#endif // CONTENT_RENDERER_RENDER_VIEW_H_
| {
"content_hash": "cf8e92017e8293ebf1642629b29e4b5b",
"timestamp": "",
"source": "github",
"line_count": 1239,
"max_line_length": 96,
"avg_line_length": 42.79176755447942,
"alnum_prop": 0.6880740866481827,
"repo_name": "meego-tablet-ux/meego-app-browser",
"id": "6bbea980a855bd168655472e3b7ccb877e387ad8",
"size": "53019",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "content/renderer/render_view.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "5599"
},
{
"name": "AppleScript",
"bytes": "6772"
},
{
"name": "Assembly",
"bytes": "1871"
},
{
"name": "C",
"bytes": "1646303"
},
{
"name": "C++",
"bytes": "72324607"
},
{
"name": "CSS",
"bytes": "221604"
},
{
"name": "Diff",
"bytes": "11193"
},
{
"name": "Go",
"bytes": "3744"
},
{
"name": "HTML",
"bytes": "21930015"
},
{
"name": "Java",
"bytes": "11354"
},
{
"name": "JavaScript",
"bytes": "5339242"
},
{
"name": "Makefile",
"bytes": "2412"
},
{
"name": "Objective-C",
"bytes": "691329"
},
{
"name": "Objective-C++",
"bytes": "3786548"
},
{
"name": "PHP",
"bytes": "97796"
},
{
"name": "PLpgSQL",
"bytes": "70415"
},
{
"name": "Perl",
"bytes": "63704"
},
{
"name": "Protocol Buffer",
"bytes": "96399"
},
{
"name": "Python",
"bytes": "2296716"
},
{
"name": "QML",
"bytes": "452612"
},
{
"name": "QMake",
"bytes": "435"
},
{
"name": "Shell",
"bytes": "200146"
}
],
"symlink_target": ""
} |
package com.viesis.viescraft.client.particle;
import net.minecraft.client.particle.ParticleFlame;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class EntityUnholyFX extends ParticleFlame {
public EntityUnholyFX(World parWorld,
double parX, double parY, double parZ,
double parMotionX, double parMotionY, double parMotionZ)
{
super(parWorld, parX, parY, parZ, parMotionX, parMotionY, parMotionZ);
//this.particleScale = 10.25F;//.particleScale.particleMaxAge = 2;
setParticleTextureIndex(65);
setRBGColorF(0, 135, 0);
}
} | {
"content_hash": "36e7ec61b16011f7a875cde1253e15f3",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 78,
"avg_line_length": 33,
"alnum_prop": 0.7121212121212122,
"repo_name": "Weisses/Ebonheart-Mods",
"id": "d4f3c6dab3c963b2fffb9564832c3ad261580437",
"size": "726",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "ViesCraft/1.12.2-2859/src/main/java/com/viesis/viescraft/client/particle/EntityUnholyFX.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1727"
},
{
"name": "Java",
"bytes": "39129320"
}
],
"symlink_target": ""
} |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using NUnit.Framework;
using System;
using System.IO;
namespace Google.Protobuf
{
public class JsonTokenizerTest
{
[Test]
public void EmptyObjectValue()
{
AssertTokens("{}", JsonToken.StartObject, JsonToken.EndObject);
}
[Test]
public void EmptyArrayValue()
{
AssertTokens("[]", JsonToken.StartArray, JsonToken.EndArray);
}
[Test]
[TestCase("foo", "foo")]
[TestCase("tab\\t", "tab\t")]
[TestCase("line\\nfeed", "line\nfeed")]
[TestCase("carriage\\rreturn", "carriage\rreturn")]
[TestCase("back\\bspace", "back\bspace")]
[TestCase("form\\ffeed", "form\ffeed")]
[TestCase("escaped\\/slash", "escaped/slash")]
[TestCase("escaped\\\\backslash", "escaped\\backslash")]
[TestCase("escaped\\\"quote", "escaped\"quote")]
[TestCase("foo {}[] bar", "foo {}[] bar")]
[TestCase("foo\\u09aFbar", "foo\u09afbar")] // Digits, upper hex, lower hex
[TestCase("ab\ud800\udc00cd", "ab\ud800\udc00cd")]
[TestCase("ab\\ud800\\udc00cd", "ab\ud800\udc00cd")]
public void StringValue(string json, string expectedValue)
{
AssertTokensNoReplacement("\"" + json + "\"", JsonToken.Value(expectedValue));
}
// Valid surrogate pairs, with mixed escaping. These test cases can't be expressed
// using TestCase as they have no valid UTF-8 representation.
// It's unclear exactly how we should handle a mixture of escaped or not: that can't
// come from UTF-8 text, but could come from a .NET string. For the moment,
// treat it as valid in the obvious way.
[Test]
public void MixedSurrogatePairs()
{
string expected = "\ud800\udc00";
AssertTokens("'\\ud800\udc00'", JsonToken.Value(expected));
AssertTokens("'\ud800\\udc00'", JsonToken.Value(expected));
}
[Test]
public void ObjectDepth()
{
string json = "{ \"foo\": { \"x\": 1, \"y\": [ 0 ] } }";
var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json));
// If we had more tests like this, I'd introduce a helper method... but for one test, it's not worth it.
Assert.AreEqual(0, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
Assert.AreEqual(1, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.Name("foo"), tokenizer.Next());
Assert.AreEqual(1, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
Assert.AreEqual(2, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.Name("x"), tokenizer.Next());
Assert.AreEqual(2, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.Value(1), tokenizer.Next());
Assert.AreEqual(2, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.Name("y"), tokenizer.Next());
Assert.AreEqual(2, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.StartArray, tokenizer.Next());
Assert.AreEqual(2, tokenizer.ObjectDepth); // Depth hasn't changed in array
Assert.AreEqual(JsonToken.Value(0), tokenizer.Next());
Assert.AreEqual(2, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.EndArray, tokenizer.Next());
Assert.AreEqual(2, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.EndObject, tokenizer.Next());
Assert.AreEqual(1, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.EndObject, tokenizer.Next());
Assert.AreEqual(0, tokenizer.ObjectDepth);
Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
Assert.AreEqual(0, tokenizer.ObjectDepth);
}
[Test]
public void ObjectDepth_WithPushBack()
{
string json = "{}";
var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json));
Assert.AreEqual(0, tokenizer.ObjectDepth);
var token = tokenizer.Next();
Assert.AreEqual(1, tokenizer.ObjectDepth);
// When we push back a "start object", we should effectively be back to the previous depth.
tokenizer.PushBack(token);
Assert.AreEqual(0, tokenizer.ObjectDepth);
// Read the same token again, and get back to depth 1
token = tokenizer.Next();
Assert.AreEqual(1, tokenizer.ObjectDepth);
// Now the same in reverse, with EndObject
token = tokenizer.Next();
Assert.AreEqual(0, tokenizer.ObjectDepth);
tokenizer.PushBack(token);
Assert.AreEqual(1, tokenizer.ObjectDepth);
tokenizer.Next();
Assert.AreEqual(0, tokenizer.ObjectDepth);
}
[Test]
[TestCase("embedded tab\t")]
[TestCase("embedded CR\r")]
[TestCase("embedded LF\n")]
[TestCase("embedded bell\u0007")]
[TestCase("bad escape\\a")]
[TestCase("incomplete escape\\")]
[TestCase("incomplete Unicode escape\\u000")]
[TestCase("invalid Unicode escape\\u000H")]
// Surrogate pair handling, both in raw .NET strings and escaped. We only need
// to detect this in strings, as non-ASCII characters anywhere other than in strings
// will already lead to parsing errors.
[TestCase("\\ud800")]
[TestCase("\\udc00")]
[TestCase("\\ud800x")]
[TestCase("\\udc00x")]
[TestCase("\\udc00\\ud800y")]
public void InvalidStringValue(string json)
{
AssertThrowsAfter("\"" + json + "\"");
}
// Tests for invalid strings that can't be expressed in attributes,
// as the constants can't be expressed as UTF-8 strings.
[Test]
public void InvalidSurrogatePairs()
{
AssertThrowsAfter("\"\ud800x\"");
AssertThrowsAfter("\"\udc00y\"");
AssertThrowsAfter("\"\udc00\ud800y\"");
}
[Test]
[TestCase("0", 0)]
[TestCase("-0", 0)] // We don't distinguish between positive and negative 0
[TestCase("1", 1)]
[TestCase("-1", -1)]
// From here on, assume leading sign is okay...
[TestCase("1.125", 1.125)]
[TestCase("1.0", 1)]
[TestCase("1e5", 100000)]
[TestCase("1e000000", 1)] // Weird, but not prohibited by the spec
[TestCase("1E5", 100000)]
[TestCase("1e+5", 100000)]
[TestCase("1E-5", 0.00001)]
[TestCase("123E-2", 1.23)]
[TestCase("123.45E3", 123450)]
[TestCase(" 1 ", 1)]
public void NumberValue(string json, double expectedValue)
{
AssertTokens(json, JsonToken.Value(expectedValue));
}
[Test]
[TestCase("00")]
[TestCase(".5")]
[TestCase("1.")]
[TestCase("1e")]
[TestCase("1e-")]
[TestCase("--")]
[TestCase("--1")]
[TestCase("-1.7977e308")]
[TestCase("1.7977e308")]
public void InvalidNumberValue(string json)
{
AssertThrowsAfter(json);
}
[Test]
[TestCase("nul")]
[TestCase("nothing")]
[TestCase("truth")]
[TestCase("fALSEhood")]
public void InvalidLiterals(string json)
{
AssertThrowsAfter(json);
}
[Test]
public void NullValue()
{
AssertTokens("null", JsonToken.Null);
}
[Test]
public void TrueValue()
{
AssertTokens("true", JsonToken.True);
}
[Test]
public void FalseValue()
{
AssertTokens("false", JsonToken.False);
}
[Test]
public void SimpleObject()
{
AssertTokens("{'x': 'y'}",
JsonToken.StartObject, JsonToken.Name("x"), JsonToken.Value("y"), JsonToken.EndObject);
}
[Test]
[TestCase("[10, 20", 3)]
[TestCase("[10,", 2)]
[TestCase("[10:20]", 2)]
[TestCase("[", 1)]
[TestCase("[,", 1)]
[TestCase("{", 1)]
[TestCase("{,", 1)]
[TestCase("{", 1)]
[TestCase("{[", 1)]
[TestCase("{{", 1)]
[TestCase("{0", 1)]
[TestCase("{null", 1)]
[TestCase("{false", 1)]
[TestCase("{true", 1)]
[TestCase("}", 0)]
[TestCase("]", 0)]
[TestCase(",", 0)]
[TestCase("'foo' 'bar'", 1)]
[TestCase(":", 0)]
[TestCase("'foo", 0)] // Incomplete string
[TestCase("{ 'foo' }", 2)]
[TestCase("{ x:1", 1)] // Property names must be quoted
[TestCase("{]", 1)]
[TestCase("[}", 1)]
[TestCase("[1,", 2)]
[TestCase("{'x':0]", 3)]
[TestCase("{ 'foo': }", 2)]
[TestCase("{ 'foo':'bar', }", 3)]
public void InvalidStructure(string json, int expectedValidTokens)
{
// Note: we don't test that the earlier tokens are exactly as expected,
// partly because that's hard to parameterize.
var reader = new StringReader(json.Replace('\'', '"'));
var tokenizer = JsonTokenizer.FromTextReader(reader);
for (int i = 0; i < expectedValidTokens; i++)
{
Assert.IsNotNull(tokenizer.Next());
}
Assert.Throws<InvalidJsonException>(() => tokenizer.Next());
}
[Test]
public void ArrayMixedType()
{
AssertTokens("[1, 'foo', null, false, true, [2], {'x':'y' }]",
JsonToken.StartArray,
JsonToken.Value(1),
JsonToken.Value("foo"),
JsonToken.Null,
JsonToken.False,
JsonToken.True,
JsonToken.StartArray,
JsonToken.Value(2),
JsonToken.EndArray,
JsonToken.StartObject,
JsonToken.Name("x"),
JsonToken.Value("y"),
JsonToken.EndObject,
JsonToken.EndArray);
}
[Test]
public void ObjectMixedType()
{
AssertTokens(@"{'a': 1, 'b': 'bar', 'c': null, 'd': false, 'e': true,
'f': [2], 'g': {'x':'y' }}",
JsonToken.StartObject,
JsonToken.Name("a"),
JsonToken.Value(1),
JsonToken.Name("b"),
JsonToken.Value("bar"),
JsonToken.Name("c"),
JsonToken.Null,
JsonToken.Name("d"),
JsonToken.False,
JsonToken.Name("e"),
JsonToken.True,
JsonToken.Name("f"),
JsonToken.StartArray,
JsonToken.Value(2),
JsonToken.EndArray,
JsonToken.Name("g"),
JsonToken.StartObject,
JsonToken.Name("x"),
JsonToken.Value("y"),
JsonToken.EndObject,
JsonToken.EndObject);
}
[Test]
public void NextAfterEndDocumentThrows()
{
var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null"));
Assert.AreEqual(JsonToken.Null, tokenizer.Next());
Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
}
[Test]
public void CanPushBackEndDocument()
{
var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null"));
Assert.AreEqual(JsonToken.Null, tokenizer.Next());
Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
tokenizer.PushBack(JsonToken.EndDocument);
Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
}
/// <summary>
/// Asserts that the specified JSON is tokenized into the given sequence of tokens.
/// All apostrophes are first converted to double quotes, allowing any tests
/// that don't need to check actual apostrophe handling to use apostrophes in the JSON, avoiding
/// messy string literal escaping. The "end document" token is not specified in the list of
/// expected tokens, but is implicit.
/// </summary>
private static void AssertTokens(string json, params JsonToken[] expectedTokens)
{
AssertTokensNoReplacement(json.Replace('\'', '"'), expectedTokens);
}
/// <summary>
/// Asserts that the specified JSON is tokenized into the given sequence of tokens.
/// Unlike <see cref="AssertTokens(string, JsonToken[])"/>, this does not perform any character
/// replacement on the specified JSON, and should be used when the text contains apostrophes which
/// are expected to be used *as* apostrophes. The "end document" token is not specified in the list of
/// expected tokens, but is implicit.
/// </summary>
private static void AssertTokensNoReplacement(string json, params JsonToken[] expectedTokens)
{
var reader = new StringReader(json);
var tokenizer = JsonTokenizer.FromTextReader(reader);
for (int i = 0; i < expectedTokens.Length; i++)
{
var actualToken = tokenizer.Next();
if (actualToken == JsonToken.EndDocument)
{
Assert.Fail("Expected {0} but reached end of token stream", expectedTokens[i]);
}
Assert.AreEqual(expectedTokens[i], actualToken);
}
var finalToken = tokenizer.Next();
if (finalToken != JsonToken.EndDocument)
{
Assert.Fail("Expected token stream to be exhausted; received {0}", finalToken);
}
}
private static void AssertThrowsAfter(string json, params JsonToken[] expectedTokens)
{
var reader = new StringReader(json);
var tokenizer = JsonTokenizer.FromTextReader(reader);
for (int i = 0; i < expectedTokens.Length; i++)
{
var actualToken = tokenizer.Next();
if (actualToken == JsonToken.EndDocument)
{
Assert.Fail("Expected {0} but reached end of document", expectedTokens[i]);
}
Assert.AreEqual(expectedTokens[i], actualToken);
}
Assert.Throws<InvalidJsonException>(() => tokenizer.Next());
}
}
}
| {
"content_hash": "d173049a66e4d69066db6dd3e1527c25",
"timestamp": "",
"source": "github",
"line_count": 409,
"max_line_length": 116,
"avg_line_length": 40.54767726161369,
"alnum_prop": 0.567776169802219,
"repo_name": "comran/SpartanBalloon2016",
"id": "a0a62227684904418945b4bd404c92458293bc15",
"size": "16586",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "third_party/protobuf/csharp/src/Google.Protobuf.Test/JsonTokenizerTest.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "20347"
},
{
"name": "C++",
"bytes": "531514"
},
{
"name": "CSS",
"bytes": "3451"
},
{
"name": "HTML",
"bytes": "8557"
},
{
"name": "Python",
"bytes": "34373"
},
{
"name": "Ruby",
"bytes": "92070"
},
{
"name": "Shell",
"bytes": "1530"
}
],
"symlink_target": ""
} |
Action Launcher API
==================================
A simple API live wallpaper developers can use to allow [Action Launcher 3](2) to theme itself based on the current colors of your wallpaper.
<img src="screenshot.png" width="300">
Note: use of this API is only necessary for **live wallpapers** (not status wallpapers). This is due to Android not providing any APIs for apps to fetch Bitmap data about the current live wallpaper.
Usage
=====
1. Integrate the Action 3 API code into the `dependencies` section of your `build.gradle` file:
`compile 'com.actionlauncher:action3-api:1.+'`
<br><br>If you're not using Android Studio/gradle, you can add the [`action3-api.jar`][5] to your `/libs` folder, or copy the API [code][3] directly into your project.<br><br>
2. Add this code to your `AndroidManifest.xml` (inside the `Application` entry):
```
<service android:name="com.actionlauncher.api.LiveWallpaperSource"
android:label="LiveWallpaperSource"
android:exported="true">
<intent-filter>
<action android:name="com.actionlauncher.api.action.LiveWallpaperSource" />
</intent-filter>
</service>
```
3. In your application code, you will need a `Bitmap` instance of your live wallpaper. At the point in your code where you have this `Bitmap` instance, add the following:
```
Bitmap myBitmap = ...
try {
LiveWallpaperSource.with(context)
.setBitmapSynchronous(myBitmap)
.run();
} catch (OutOfMemoryError outOfMemoryError) {
// Palette generation was unable to process the Bitmap passed in to
// setBitmapSynchronous(). Consider using a smaller image.
// See ActionPalette.DEFAULT_RESIZE_BITMAP_MAX_DIMENSION
} catch (IllegalArgumentException illegalArgumentEx) {
// Raised during palette generation. Check your Bitmap.
} catch (IllegalStateException illegalStateException) {
// Raised during palette generation. Check your Bitmap.
}
```
<br>To test it all works:
* Load Action Launcher 3 (you *must* be using version 3.3 or later).
* Ensure your wallpaper is set as the live wallpaper.
* Ensure Action Launcher's wallpaper extraction mode is enabled (Settings -> Quicktheme -> Theme -> Wallpaper).
* As you're integrating the API, be sure to turn on Settings -> Help -> Advanced -> Live wallpaper API debug in Action Launcher 3. By doing so, you will enable a debug mode where pressing the voice search button on the search bar will trigger a request to your app for the latest `LiveWallpaperInfo` data.
Demo
====
The `main` app in this repository demonstrates the live wallpaper functionality. It is basically the main app from the [Android Live Wallpaper Hello World project](1). If you double-tap empty space on Action Launcher 3's home screen, the wallpaper image will change, and you items such as the search bar will have their colors updated as per the current wallpaper image in Action Launcher 3.
Check out the `LiveWallpaperSource.with()` call in `MuzeiBlurRenderer.java`.
Notes
=====
* Keep in mind that each time you call `LiveWallpaperSource.setBitmapSynchronous()`, a new palette will be generated. In order to not waste battery, you only want to make this call when you know there has been a meaninful visual change in your wallpaper app and Action Launcher's Quicktheme feature should be updated.
* This API includes a copy of API 22's Palette library from Support Library named `ActionPalette`[4]. It has been integrated directly into the ActionLauncherApi rather than as a dependency because:
* Many live-wallpaper developers are still using Eclipse, which has seemingly isn't well set up to use AARs.
* Makes the dependencies easier.
* It doesn't take much code size, so there's little harm in it.
3rd party examples
==================
The following Android apps make use of this API:
* [Minima Pro Live Wallpaper](https://play.google.com/store/apps/details?id=com.joko.minimapro)
* [TapDeck - Wallpaper Discovery](https://play.google.com/store/apps/details?id=io.tapdeck.android)
License
=======
Copyright 2015 Chris Lacy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
[1]: https://github.com/chrislacy/AndroidLiveWallpaperHelloWorld
[2]: https://play.google.com/store/apps/details?id=com.actionlauncher.playstore
[3]: https://github.com/chrislacy/ActionLauncherApi/tree/master/api/src/main/java
[4]: https://github.com/chrislacy/ActionLauncherApi/tree/master/api/src/main/java/com/actionlauncher/api/actionpalette
[5]: https://oss.sonatype.org/content/repositories/releases/com/actionlauncher/action3-api/1.1.0/action3-api-1.1.0.jar
| {
"content_hash": "ce3b530616998194c83c581ece782077",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 391,
"avg_line_length": 48.820754716981135,
"alnum_prop": 0.7342995169082126,
"repo_name": "dhootha/ActionLauncherApi",
"id": "595d38c2750c0337c9344ed3eb76b456c84519c0",
"size": "5175",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1732"
},
{
"name": "HTML",
"bytes": "892"
},
{
"name": "Java",
"bytes": "432206"
},
{
"name": "Python",
"bytes": "2517"
},
{
"name": "Shell",
"bytes": "1281"
}
],
"symlink_target": ""
} |
All URIs are relative to *https://apis.wso2.com/api/am/publisher/v3*
Method | HTTP request | Description
------------- | ------------- | -------------
[**addAPIMonetization**](ApiMonetizationApi.md#addAPIMonetization) | **POST** /apis/{apiId}/monetize | Configure Monetization for a Given API
[**getAPIMonetization**](ApiMonetizationApi.md#getAPIMonetization) | **GET** /apis/{apiId}/monetization | Get Monetization Status for each Tier in a Given API
[**getAPIRevenue**](ApiMonetizationApi.md#getAPIRevenue) | **GET** /apis/{apiId}/revenue | Get Total Revenue Details of a Given Monetized API with Meterd Billing
[**getSubscriptionUsage**](ApiMonetizationApi.md#getSubscriptionUsage) | **GET** /subscriptions/{subscriptionId}/usage | Get Details of a Pending Invoice for a Monetized Subscription with Metered Billing.
<a name="addAPIMonetization"></a>
# **addAPIMonetization**
> addAPIMonetization(apiId, apIMonetizationInfoDTO)
Configure Monetization for a Given API
This operation can be used to configure monetization for a given API.
### Example
```java
// Import classes:
import org.wso2.am.integration.clients.publisher.api.ApiClient;
import org.wso2.am.integration.clients.publisher.api.ApiException;
import org.wso2.am.integration.clients.publisher.api.Configuration;
import org.wso2.am.integration.clients.publisher.api.auth.*;
import org.wso2.am.integration.clients.publisher.api.models.*;
import org.wso2.am.integration.clients.publisher.api.v1.ApiMonetizationApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://apis.wso2.com/api/am/publisher/v3");
// Configure OAuth2 access token for authorization: OAuth2Security
OAuth OAuth2Security = (OAuth) defaultClient.getAuthentication("OAuth2Security");
OAuth2Security.setAccessToken("YOUR ACCESS TOKEN");
ApiMonetizationApi apiInstance = new ApiMonetizationApi(defaultClient);
String apiId = "apiId_example"; // String | **API ID** consisting of the **UUID** of the API.
APIMonetizationInfoDTO apIMonetizationInfoDTO = new APIMonetizationInfoDTO(); // APIMonetizationInfoDTO | Monetization data object
try {
apiInstance.addAPIMonetization(apiId, apIMonetizationInfoDTO);
} catch (ApiException e) {
System.err.println("Exception when calling ApiMonetizationApi#addAPIMonetization");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**apiId** | **String**| **API ID** consisting of the **UUID** of the API. |
**apIMonetizationInfoDTO** | [**APIMonetizationInfoDTO**](APIMonetizationInfoDTO.md)| Monetization data object |
### Return type
null (empty response body)
### Authorization
[OAuth2Security](../README.md#OAuth2Security)
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**201** | OK. Monetization status changed successfully. | - |
**400** | Bad Request. Invalid request or validation error. | - |
**404** | Not Found. The specified resource does not exist. | - |
**406** | Not Acceptable. The requested media type is not supported. | - |
<a name="getAPIMonetization"></a>
# **getAPIMonetization**
> getAPIMonetization(apiId)
Get Monetization Status for each Tier in a Given API
This operation can be used to get monetization status for each tier in a given API
### Example
```java
// Import classes:
import org.wso2.am.integration.clients.publisher.api.ApiClient;
import org.wso2.am.integration.clients.publisher.api.ApiException;
import org.wso2.am.integration.clients.publisher.api.Configuration;
import org.wso2.am.integration.clients.publisher.api.auth.*;
import org.wso2.am.integration.clients.publisher.api.models.*;
import org.wso2.am.integration.clients.publisher.api.v1.ApiMonetizationApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://apis.wso2.com/api/am/publisher/v3");
// Configure OAuth2 access token for authorization: OAuth2Security
OAuth OAuth2Security = (OAuth) defaultClient.getAuthentication("OAuth2Security");
OAuth2Security.setAccessToken("YOUR ACCESS TOKEN");
ApiMonetizationApi apiInstance = new ApiMonetizationApi(defaultClient);
String apiId = "apiId_example"; // String | **API ID** consisting of the **UUID** of the API.
try {
apiInstance.getAPIMonetization(apiId);
} catch (ApiException e) {
System.err.println("Exception when calling ApiMonetizationApi#getAPIMonetization");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**apiId** | **String**| **API ID** consisting of the **UUID** of the API. |
### Return type
null (empty response body)
### Authorization
[OAuth2Security](../README.md#OAuth2Security)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | OK. Monetization status for each tier returned successfully. | - |
**400** | Bad Request. Invalid request or validation error. | - |
**404** | Not Found. The specified resource does not exist. | - |
**406** | Not Acceptable. The requested media type is not supported. | - |
<a name="getAPIRevenue"></a>
# **getAPIRevenue**
> APIRevenueDTO getAPIRevenue(apiId)
Get Total Revenue Details of a Given Monetized API with Meterd Billing
This operation can be used to get details of total revenue details of a given monetized API with meterd billing.
### Example
```java
// Import classes:
import org.wso2.am.integration.clients.publisher.api.ApiClient;
import org.wso2.am.integration.clients.publisher.api.ApiException;
import org.wso2.am.integration.clients.publisher.api.Configuration;
import org.wso2.am.integration.clients.publisher.api.auth.*;
import org.wso2.am.integration.clients.publisher.api.models.*;
import org.wso2.am.integration.clients.publisher.api.v1.ApiMonetizationApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://apis.wso2.com/api/am/publisher/v3");
// Configure OAuth2 access token for authorization: OAuth2Security
OAuth OAuth2Security = (OAuth) defaultClient.getAuthentication("OAuth2Security");
OAuth2Security.setAccessToken("YOUR ACCESS TOKEN");
ApiMonetizationApi apiInstance = new ApiMonetizationApi(defaultClient);
String apiId = "apiId_example"; // String | **API ID** consisting of the **UUID** of the API.
try {
APIRevenueDTO result = apiInstance.getAPIRevenue(apiId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ApiMonetizationApi#getAPIRevenue");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**apiId** | **String**| **API ID** consisting of the **UUID** of the API. |
### Return type
[**APIRevenueDTO**](APIRevenueDTO.md)
### Authorization
[OAuth2Security](../README.md#OAuth2Security)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | OK. Details of a total revenue returned. | * ETag - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). <br> * Last-Modified - Date and time the resource has been modified the last time. Used by caches, or in conditional requests (Will be supported in future). <br> * Content-Type - The content type of the body. <br> |
**304** | Not Modified. Empty body because the client has already the latest version of the requested resource (Will be supported in future). | - |
**404** | Not Found. The specified resource does not exist. | - |
<a name="getSubscriptionUsage"></a>
# **getSubscriptionUsage**
> APIMonetizationUsageDTO getSubscriptionUsage(subscriptionId)
Get Details of a Pending Invoice for a Monetized Subscription with Metered Billing.
This operation can be used to get details of a pending invoice for a monetized subscription with meterd billing.
### Example
```java
// Import classes:
import org.wso2.am.integration.clients.publisher.api.ApiClient;
import org.wso2.am.integration.clients.publisher.api.ApiException;
import org.wso2.am.integration.clients.publisher.api.Configuration;
import org.wso2.am.integration.clients.publisher.api.auth.*;
import org.wso2.am.integration.clients.publisher.api.models.*;
import org.wso2.am.integration.clients.publisher.api.v1.ApiMonetizationApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://apis.wso2.com/api/am/publisher/v3");
// Configure OAuth2 access token for authorization: OAuth2Security
OAuth OAuth2Security = (OAuth) defaultClient.getAuthentication("OAuth2Security");
OAuth2Security.setAccessToken("YOUR ACCESS TOKEN");
ApiMonetizationApi apiInstance = new ApiMonetizationApi(defaultClient);
String subscriptionId = "subscriptionId_example"; // String | Subscription Id
try {
APIMonetizationUsageDTO result = apiInstance.getSubscriptionUsage(subscriptionId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ApiMonetizationApi#getSubscriptionUsage");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**subscriptionId** | **String**| Subscription Id |
### Return type
[**APIMonetizationUsageDTO**](APIMonetizationUsageDTO.md)
### Authorization
[OAuth2Security](../README.md#OAuth2Security)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | OK. Details of a pending invoice returned. | * ETag - Entity Tag of the response resource. Used by caches, or in conditional requests (Will be supported in future). <br> * Last-Modified - Date and time the resource has been modified the last time. Used by caches, or in conditional requests (Will be supported in future). <br> * Content-Type - The content type of the body. <br> |
**304** | Not Modified. Empty body because the client has already the latest version of the requested resource (Will be supported in future). | - |
**404** | Not Found. Requested Subscription does not exist. | - |
| {
"content_hash": "889528d4bd65cc208e7fd63896ae1b41",
"timestamp": "",
"source": "github",
"line_count": 288,
"max_line_length": 395,
"avg_line_length": 41.55555555555556,
"alnum_prop": 0.7027907754010695,
"repo_name": "wso2/product-apim",
"id": "6a3587d9437a1c2123d985f71eff7487953d5b0b",
"size": "11990",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/integration/tests-common/clients/publisher/docs/ApiMonetizationApi.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "34412"
},
{
"name": "CSS",
"bytes": "62967"
},
{
"name": "HTML",
"bytes": "19955"
},
{
"name": "Handlebars",
"bytes": "2861"
},
{
"name": "Java",
"bytes": "14978005"
},
{
"name": "JavaScript",
"bytes": "306906"
},
{
"name": "Jinja",
"bytes": "465120"
},
{
"name": "Jupyter Notebook",
"bytes": "4346"
},
{
"name": "Less",
"bytes": "199838"
},
{
"name": "Mustache",
"bytes": "71460"
},
{
"name": "Python",
"bytes": "39021"
},
{
"name": "Scala",
"bytes": "3419"
},
{
"name": "Shell",
"bytes": "45764"
},
{
"name": "XSLT",
"bytes": "8193"
}
],
"symlink_target": ""
} |
"""
AniColle Library
Collect your animes like a geek.
Database model and operations here.
Unlike the previous version, this version returns objects as results rather than dictionaries by default.
You can force convert it into a dict by using to_dict().
"""
from peewee import *
import re
from .seeker import seeker
from .config import config
import os
from json import loads as json_loads, dumps as json_dump
from pypinyin import lazy_pinyin, Style
run_mode = os.getenv('ANICOLLE_MODE') or 'default'
try:
config = config[run_mode]
# print("Running with", run_mode, "mode")
except KeyError :
print("No such running mode. Check your ANICOLLE_MODE system env please.")
exit()
db = SqliteDatabase(config.DATABASE)
class Bangumi(Model):
# `id` field is added automatically
name = TextField() # Bangumi name
cur_epi = IntegerField(default=0) # Currently viewing episode
on_air_epi = IntegerField(default=0) # (Placeholder)
on_air_day = IntegerField(default=0) # The on air weekday. [1-7] for Monday - Sunday, 0 for not on air, 8 for not fixed on air day.
seeker = TextField(default='[]')
'''
Seeker is a modularized part of the program which is used to seek new episode of a bangumi programatically.
Seekers are placed under `seeker` directory, and they are imported into this file as a dict named `seeker`.
Seeker data saved in database is a serialized array (in json format), as following shows:
[
{
"seeker": SEEKER_NAME,
"chk_key": SEEKER_CHECK_KEY
},
]
chk_key is used for calling the `seek` function of 'seeker', usually a search keyword of the specific bangumi.
For example, you want to download 'Tokyo Ghoul' from bilibili, then you should use "东京喰种" as a chk_key.
For more information on `chk_key`, please refer to our wiki.
'''
class Meta:
database = db
def to_dict(self):
return {
'id': self.id,
'name': self.name,
'cur_epi': self.cur_epi,
'on_air_epi': self.on_air_epi,
'on_air_day': self.on_air_day,
'seeker': self.seeker,
'name_pinyin': ''.join(lazy_pinyin(self.name, Style.FIRST_LETTER))
}
def dbInit():
db.connect()
db.create_tables([Bangumi], safe=True)
db.close()
def getAni( bid=-1, on_air_day=-1 ):
db.connect()
r = []
try:
if bid>=0:
# get a single record
r = Bangumi.get(Bangumi.id==bid).to_dict()
elif on_air_day>=0:
# get a set of records
for bgm in Bangumi.select().where(Bangumi.on_air_day==on_air_day):
r.append(bgm.to_dict())
else:
# get all records
for bgm in Bangumi.select().order_by(Bangumi.on_air_day):
r.append(bgm.to_dict())
return r
except Bangumi.DoesNotExist:
return None
finally:
db.close()
def create( name, cur_epi=0, on_air_day=0, seeker=[] ):
db.connect()
bgm = Bangumi(name=name, cur_epi=cur_epi, on_air_day=on_air_day, seeker=json_dump(seeker));
bgm.save()
db.close()
return bgm.to_dict()
def modify( bid, name=None, cur_epi=None, on_air_day=None, seeker=None ):
db.connect()
try:
bgm = Bangumi.get(Bangumi.id==bid)
if name:
bgm.name = name
if cur_epi:
bgm.cur_epi = int(cur_epi)
if on_air_day:
bgm.on_air_day = int(on_air_day)
if seeker:
bgm.seeker = json_dump(seeker)
bgm.save()
return bgm.to_dict()
except Bangumi.DoesNotExist:
return 0
finally:
db.close()
def remove(bid):
db.connect()
try:
bgm = Bangumi.get(Bangumi.id==bid)
bgm.delete_instance()
return 1
except Bangumi.DoesNotExist:
return 0
finally:
db.close()
def increase( bid ):
db.connect()
try:
bgm = Bangumi.get(Bangumi.id==bid)
bgm.cur_epi = bgm.cur_epi +1
bgm.save()
return bgm.to_dict()
except Bangumi.DoesNotExist:
return 0
finally:
db.close()
def decrease( bid ):
db.connect()
try:
bgm = Bangumi.get(Bangumi.id==bid)
bgm.cur_epi = bgm.cur_epi -1
bgm.save()
return bgm.to_dict()
except Bangumi.DoesNotExist:
return 0
finally:
db.close()
def chkup(bid, episode=None):
def getParams(chk_key):
pattern = "\s+--params:(.*)$"
match = re.search(pattern, chk_key)
if not match:
return chk_key, None
else:
params_str = match.group(1)
params = str(params_str).split(",")
params = list(map(lambda e: str(e).strip(), params))
return chk_key, params
db.connect()
try:
bgm = Bangumi.get(Bangumi.id == bid)
except Bangumi.DoesNotExist:
return 0
else:
'''
Start of checking module
\/_\/_\/_\/_\/_\/_\/_\/_\/
'''
if episode is None or episode == '':
episode = bgm.cur_epi+1 # Check current episode +1
else:
episode = int(episode)
r = []
bgm_seeker_data = json_loads(bgm.seeker)
for seeker_seed in bgm_seeker_data:
try:
if not seeker_seed['chk_key']:
continue
chk_key, params = getParams(seeker_seed['chk_key'])
# Maybe we need some new names. This can be confusable.
seek_result = seeker[seeker_seed['seeker']].seek(
seeker_seed['chk_key'], episode, params)
if type(seek_result) == list:
r = r+seek_result
except KeyError:
print("[WARN] Seeker named", seeker_seed['seeker'],
"not found. (Not registered?)")
return r
'''
_/\_/\_/\_/\_/\_/\_/\_/\_
End of checking module
'''
finally:
db.close()
| {
"content_hash": "8cddd25576e65d3925667789cc731ae8",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 138,
"avg_line_length": 28.96208530805687,
"alnum_prop": 0.5576828669612175,
"repo_name": "chienius/anicolle",
"id": "97655b2a29a8340713f930d7e0d0464dfd8082e9",
"size": "6165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "anicolle/core.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "16612"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.