text stringlengths 2 1.04M | meta dict |
|---|---|
package net.ripe.db.whois.update.handler;
import javax.annotation.concurrent.Immutable;
@Immutable
public class UpdateAbortedException extends RuntimeException {
}
| {
"content_hash": "7749e81fea9507620649cc208205456d",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 62,
"avg_line_length": 23.714285714285715,
"alnum_prop": 0.8373493975903614,
"repo_name": "8v060htwyc/whois",
"id": "449f10bf4c42af8b0898c0ba9439551619e8fb65",
"size": "166",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "whois-update/src/main/java/net/ripe/db/whois/update/handler/UpdateAbortedException.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "169705"
},
{
"name": "Groff",
"bytes": "2124"
},
{
"name": "Groovy",
"bytes": "4373417"
},
{
"name": "Java",
"bytes": "5276094"
},
{
"name": "Lex",
"bytes": "102258"
},
{
"name": "Makefile",
"bytes": "1903"
},
{
"name": "PLpgSQL",
"bytes": "1560"
},
{
"name": "Shell",
"bytes": "3405"
},
{
"name": "Yacc",
"bytes": "128522"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.diirt</groupId>
<artifactId>pvmanager-all</artifactId>
<version>3.0.0-SNAPSHOT</version>
</parent>
<artifactId>datasource-pva</artifactId>
<name>org.diirt.datasource.pva</name>
<dependencies>
<dependency>
<groupId>org.epics</groupId>
<artifactId>pvDataJava</artifactId>
<version>3.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.epics</groupId>
<artifactId>pvAccessJava</artifactId>
<version>3.1.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>datasource-vtype</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>datasource-extra</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>datasource-formula</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>service</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>epics</id>
<name>EPICS Repository</name>
<url>http://epics.sourceforge.net/maven2/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>eu.somatik.serviceloader-maven-plugin</groupId>
<artifactId>serviceloader-maven-plugin</artifactId>
<version>1.0.2</version>
<configuration>
<services>
<param>org.diirt.service.ServiceProvider</param>
</services>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "a50331296aae840023a443f5b22aaff3",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 204,
"avg_line_length": 36.467532467532465,
"alnum_prop": 0.5263532763532763,
"repo_name": "richardfearn/diirt",
"id": "017303a6bee6ce1059e0bd2cf8a0e62bd846997f",
"size": "2808",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pvmanager/pvmanager-pva/pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "74191"
},
{
"name": "GAP",
"bytes": "6519"
},
{
"name": "Java",
"bytes": "4176965"
},
{
"name": "JavaScript",
"bytes": "1716484"
},
{
"name": "Shell",
"bytes": "3421"
}
],
"symlink_target": ""
} |
Harmony.keypad = {}
Harmony.keypad.currentTactic = nil
Harmony.keypad.combatMode = false
Harmony.keypad.keysToDirections = {
["/"] = "in",
["*"] = "out",
["-"] = "up",
["+"] = "down",
["."] = "ih",
["0"] = "map",
["1"] = "sw",
["2"] = "s",
["3"] = "se",
["4"] = "w",
["5"] = "look",
["6"] = "e",
["7"] = "nw",
["8"] = "n",
["9"] = "ne",
}
Harmony.keypad.sprint = false
function Harmony.keypad.toggleKeypad()
if Harmony.keypad.combatMode then
Harmony.say("<yellow>Combat Keypad<reset> turned <red>off.")
else
Harmony.say("<yellow>Combat Keypad<reset> turned <green>on.")
end
Harmony.keypad.combatMode = not Harmony.keypad.combatMode
raiseEvent("Harmony.keypadChanged")
end
function Harmony.keypad.toggleSprint()
if Harmony.keypad.sprint then
Harmony.say("Keypad sprinting turned <red>off.")
else
Harmony.say("Keypad sprinting turned <green>on.")
end
Harmony.keypad.sprint = not Harmony.keypad.sprint
raiseEvent("Harmony.keypadSprintChanged")
end
function Harmony.keypad.processKey(key)
local ks = Harmony.keypad
if not Harmony.keypad.combatMode and key ~= "0" then
Harmony.keypad.sendDirection(key)
return
end
if not ks.currentTactic then
Harmony.say(("No tactic set! Sending direction."):format(key))
Harmony.keypad.sendDirection(key)
return
end
if ks.currentTactic[key] == nil then
Harmony.say(("Nothing bound to %s for combat, sending direction."):format(key))
Harmony.keypad.sendDirection(key)
return
end
if not Harmony.combat.currentTarget then
Harmony.say(("No target set! Sending direction."):format(key))
Harmony.keypad.sendDirection(key)
return
end
if type(ks.currentTactic[key]) == "string" then
local command = ks.currentTactic[key]:gsub("&tar", Harmony.combat.currentTarget.name)
send(command)
return
elseif type(ks.currentTactic[key]) == "function" then
local result = ks.currentTactic[key](Harmony.combat.currentTarget.name)
if result then send(result, true) end
return
elseif type(ks.currentTactic[key]) == "table" then
for _, string in ipairs(ks.currentTactic[key]) do
local command = string:gsub("&tar", Harmony.combat.currentTarget.name)
send(command)
end
return
end
end
function Harmony.keypad.sendDirection(dir)
if dir == "." then
Harmony.hunting.checkingIh = true
end
local sendCommands = {}
if Harmony.keypad.sprint and dir ~= "5" then
table.insert(sendCommands, "sprint")
end
table.insert(sendCommands, Harmony.keypad.keysToDirections[dir])
send(table.concat(sendCommands, " "))
end
| {
"content_hash": "1180af718c91f7a0ac344d25bddb88a0",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 89,
"avg_line_length": 25.26923076923077,
"alnum_prop": 0.6693302891933028,
"repo_name": "codeacula/achaea-harmony",
"id": "0619954b2dc093365ea014ba497254401c3ea991",
"size": "2628",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "keypad.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "135064"
}
],
"symlink_target": ""
} |
I implemented my solution to the challenge by using a set. To find the union for two linked lists, I iterated over both linked lists and added their items to a set. Then I create a new linked list from the items in the set. For the intersection, I iterate over one linked list and add its item to a set only if it exists in the second linked list. Then create a new linked list from the items in set.
### Efficiency
##### Time complexity
- The time taken to arrive at the union takes linear time; O(n)
- The time taken to arrive at the intersection takes linear time; O(n)
- The time taken to append an item in a `LinkedList` instance increases proportionally to the size of list; O(n)
- Overall time complexity; O(n²)
##### Space Complexity
- The space taken by my solution increases as the size of the linked lists passed in increases; O(n)
| {
"content_hash": "de0f082eb4a9638f012565881886cf5d",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 400,
"avg_line_length": 60.57142857142857,
"alnum_prop": 0.7570754716981132,
"repo_name": "manishbisht/Udacity",
"id": "b1f231d80ad7a4830a642983ca96825dcdf61372",
"size": "886",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Data Structures and Algorithms Nanodegree/P2 - Show Me the Data Structures/Problem 6 - Union and Intersection/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "109"
},
{
"name": "CSS",
"bytes": "110267"
},
{
"name": "Dockerfile",
"bytes": "1065"
},
{
"name": "HCL",
"bytes": "7094"
},
{
"name": "HTML",
"bytes": "200135"
},
{
"name": "Java",
"bytes": "1027"
},
{
"name": "JavaScript",
"bytes": "1175564"
},
{
"name": "Jupyter Notebook",
"bytes": "128263"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "138502"
},
{
"name": "SCSS",
"bytes": "3691"
},
{
"name": "Shell",
"bytes": "604"
},
{
"name": "Solidity",
"bytes": "158962"
},
{
"name": "TypeScript",
"bytes": "93953"
}
],
"symlink_target": ""
} |
layout: post
title: "Email notifications in GNUS"
date: 2016-10-06 20:00:00 +0530
categories: life
comments: true
---
I use [GNUS](http://gnus.org/) for my emails. I read/write emails from GNUS. It works and all, but now I need to know when an email arrives.
That means my setup has to change to do the following things:
1. Check for incoming emails periodically.
2. Generate notification if there is something new.
These notifications *mustn't* be distracting because we get emails from various mailing lists and the number can be huge.
Now, I [wrote](http://codingquark.com/emacs/2015/12/05/setting-up-gnus-in-emacs.html) about setting up GNUS a while ago and since then I've switched to [offlineimap](http://www.offlineimap.org/) + GNUS configuration.
That means, I don't have to wait till GNUS checks for mails. Offlineimap keeps checking for emails from the server, and GNUS checks the local directories for the emails.
To accomplish the first task, here's what we have to do:
```elisp
(gnus-demon-add-handler 'gnus-demon-scan-news 1 t)
````
Put this in your load path, and GNUS will keep checking for new emails every 1 minute. To know more, see [this](https://www.emacswiki.org/emacs/GNUSDemon).
Now for the second task. We need [gnus-notify+](https://www.emacswiki.org/emacs-en/gnus-notify+.el). Load this file (`require` it) in your config.
Add the following hooks:
```elisp
(add-hook 'gnus-summary-exit-hook 'gnus-notify+)
(add-hook 'gnus-group-catchup-group-hook 'gnus-notify+)
(add-hook 'mail-notify-pre-hook 'gnus-notify+)
````
This small package adds a new entry to our modeline which looks like this:

Neat!
PS: Yes, I have 1533 unread mails. Don't panic.
Good thing about gnus-notify+ is that it doesn't create *intrusive* notifications. There is one more entry in your modeline, you can keep an eye on it and decide to ignore it.
You can modify GNUS-notify+ to notify you only about selected groups as well.
*Edit*
Our fellow emacsing wgreenhouse suggested some smart things!
There's `display-time-mode` which shows time and can also check if there have been new files inserted under a directory. And this is done far faster because we are on local system. So, if GNUS checks for mails every 2 minutes, and we get notified via gnus-notify+ after 2 more minutes there is some delay.
What we shall now do is that we will tell `display-time-mode` about one important directory where our emails arrive and we want to get notified immediately if GNUS has not received it yet but offlineimap knows about it. When GNUS reads the emails, notification from display-time-mode is removed.
```elisp
(display-time-mode) ;; turn the mode on
(setq display-time-format "") ;; Hide the date, we have other clocks
(setq display-time-mail-directory "~/Mail/Account/INBOX/new") ;; important directory
(setq read-mail-command 'gnus) ;; when clicked (ewwww), open gnus
(add-hook 'gnus-group-mode-hook 'display-time-event-handler) ;; force timer update when gnus receives the emails
````
Thanks to wgreenhouse, we now get notified for important emails timely.
Next I would like to find out how to get these notifications to differentiate between accounts and groups. That is, something like `[GNUS: Office: 3, emacs: 50, Personal: 2]` or something on these lines.
Got suggestions for improvements? Sure, please share over [Twitter](https://twitter.com/codingquark) or email.
| {
"content_hash": "7f07d8233e57ddc910766b94f62ff7f4",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 305,
"avg_line_length": 52.86153846153846,
"alnum_prop": 0.7616414435389989,
"repo_name": "codingquark/codingquark.github.io",
"id": "b9c1127f6ba1ff9e28a3992724a6444326caa7e5",
"size": "3440",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2016-10-06-email-notifications-gnus.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "7196"
},
{
"name": "Ruby",
"bytes": "131"
},
{
"name": "SCSS",
"bytes": "14041"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Mon Nov 26 17:22:24 MSK 2012 -->
<TITLE>
Uses of Interface org.apache.poi.sl.usermodel.TextBox (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2012-11-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.apache.poi.sl.usermodel.TextBox (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/sl/usermodel/TextBox.html" title="interface in org.apache.poi.sl.usermodel"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/sl/usermodel/\class-useTextBox.html" target="_top"><B>FRAMES</B></A>
<A HREF="TextBox.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>org.apache.poi.sl.usermodel.TextBox</B></H2>
</CENTER>
No usage of org.apache.poi.sl.usermodel.TextBox
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/sl/usermodel/TextBox.html" title="interface in org.apache.poi.sl.usermodel"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/sl/usermodel/\class-useTextBox.html" target="_top"><B>FRAMES</B></A>
<A HREF="TextBox.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2012 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
| {
"content_hash": "1a0b797f8e3fbcbbf2b67bd5a859b5d6",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 226,
"avg_line_length": 42.585034013605444,
"alnum_prop": 0.5931309904153355,
"repo_name": "brenthand/Panda",
"id": "bde34f6e5613ec394a632e91cf33da2feb305c0c",
"size": "6260",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "poi-3.9/docs/apidocs/org/apache/poi/sl/usermodel/class-use/TextBox.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "16091"
},
{
"name": "Java",
"bytes": "17953"
}
],
"symlink_target": ""
} |
//====================================================================================================================//
// File: qcan_server_memeory.hpp //
// Description: QCAN classes - CAN server //
// //
// Copyright (C) MicroControl GmbH & Co. KG //
// 53844 Troisdorf - Germany //
// www.microcontrol.net //
// //
//--------------------------------------------------------------------------------------------------------------------//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the //
// following conditions are met: //
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions, the following //
// disclaimer and the referenced file 'LICENSE'. //
// 2. 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. //
// 3. Neither the name of MicroControl nor the names of its contributors may be used to endorse or promote products //
// derived from this software without specific prior written permission. //
// //
// 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. //
// //
//====================================================================================================================//
/*--------------------------------------------------------------------------------------------------------------------*\
** Include files **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
#include "qcan_defs.hpp"
/*--------------------------------------------------------------------------------------------------------------------*\
** Definitions **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
#define QCAN_MEMORY_KEY "QCAN_SERVER_SHARED_KEY"
/*--------------------------------------------------------------------------------------------------------------------*\
** Structures **
** **
\*--------------------------------------------------------------------------------------------------------------------*/
typedef struct Server_s {
uint32_t ulVersionMajor;
uint32_t ulVersionMinor;
} Server_ts;
typedef struct Network_s {
uint32_t ulVersionMajor;
uint32_t ulVersionMinor;
} Network_ts;
typedef struct ServerSettings_s {
Server_ts tsServer;
Network_ts atsNetwork[QCAN_NETWORK_MAX];
} ServerSettings_ts;
| {
"content_hash": "788a0242d048df14435187c11527b5aa",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 120,
"avg_line_length": 82.03125,
"alnum_prop": 0.27390476190476193,
"repo_name": "JoTid/CANpie",
"id": "4f6e40cb83b578d82ad00dca3ad4767a7bcfa101",
"size": "5250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/qcan/qcan_server_memory.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1816"
},
{
"name": "C",
"bytes": "580757"
},
{
"name": "C++",
"bytes": "1054376"
},
{
"name": "Makefile",
"bytes": "16403"
},
{
"name": "Objective-C",
"bytes": "47189"
},
{
"name": "Prolog",
"bytes": "1153"
},
{
"name": "QMake",
"bytes": "55893"
},
{
"name": "Shell",
"bytes": "848"
}
],
"symlink_target": ""
} |
"""This module is deprecated. Please use `airflow.providers.databricks.hooks.databricks`."""
import warnings
# pylint: disable=unused-import
from airflow.providers.databricks.hooks.databricks import ( # noqa
CANCEL_RUN_ENDPOINT, GET_RUN_ENDPOINT, RESTART_CLUSTER_ENDPOINT, RUN_LIFE_CYCLE_STATES, RUN_NOW_ENDPOINT,
START_CLUSTER_ENDPOINT, SUBMIT_RUN_ENDPOINT, TERMINATE_CLUSTER_ENDPOINT, USER_AGENT_HEADER,
DatabricksHook, RunState,
)
warnings.warn(
"This module is deprecated. Please use `airflow.providers.databricks.hooks.databricks`.",
DeprecationWarning, stacklevel=2
)
| {
"content_hash": "684cf857b774e98b61bc1889501dedb0",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 109,
"avg_line_length": 39.86666666666667,
"alnum_prop": 0.7725752508361204,
"repo_name": "wileeam/airflow",
"id": "3c610e316c21aef4add7d0c700646411e19ba55a",
"size": "1385",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "airflow/contrib/hooks/databricks_hook.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13715"
},
{
"name": "Dockerfile",
"bytes": "17179"
},
{
"name": "HTML",
"bytes": "148281"
},
{
"name": "JavaScript",
"bytes": "25233"
},
{
"name": "Jupyter Notebook",
"bytes": "2933"
},
{
"name": "Mako",
"bytes": "1339"
},
{
"name": "Python",
"bytes": "9763694"
},
{
"name": "Shell",
"bytes": "221331"
},
{
"name": "TSQL",
"bytes": "879"
}
],
"symlink_target": ""
} |
@import url(../../Source/Widgets/widgets.css);
@import url(../../Source/Widgets/lighter.css);
html {
height: 100%;
}
body {
height: 100%;
width: 100%;
margin: 0;
overflow: hidden;
padding: 0;
background: #000;
}
.fullWindow {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
margin: 0;
overflow: hidden;
padding: 0;
font-family: sans-serif;
}
.loadingIndicator {
display: block;
position: absolute;
top: 50%;
left: 50%;
margin-top: -33px;
margin-left: -33px;
width: 66px;
height: 66px;
background-position: center;
background-repeat: no-repeat;
background-image: url(Images/ajax-loader.gif);
}
| {
"content_hash": "745c26a42573a9c8a728acda644f4ebd",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 50,
"avg_line_length": 17.585365853658537,
"alnum_prop": 0.5908460471567267,
"repo_name": "NaderCHASER/cesium",
"id": "9345e863194ea95cec38c229c5b3071f49aa2a2c",
"size": "721",
"binary": false,
"copies": "21",
"ref": "refs/heads/master",
"path": "Apps/CesiumViewer/CesiumViewer.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "659131"
},
{
"name": "GLSL",
"bytes": "215615"
},
{
"name": "HTML",
"bytes": "1926325"
},
{
"name": "JavaScript",
"bytes": "23413825"
},
{
"name": "Shell",
"bytes": "291"
}
],
"symlink_target": ""
} |
$.fn[plugin] = function(option, args) {
var result = [];
this.each(function() {
var $this, data, options;
$this = $(this);
data = $this.data(plugin);
options = typeof option === 'object' && option;
if (!data) {
result = $this.data(plugin, (data = new Superslides(this, options)));
}
if (typeof option === "string") {
result = data[option];
if (typeof result === 'function') {
result = result.call(data, args);
return result;
}
}
});
return result;
};
$.fn[plugin].fx = {};
| {
"content_hash": "ac321369d445a101eab38d92000777f4",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 75,
"avg_line_length": 20.703703703703702,
"alnum_prop": 0.5313059033989267,
"repo_name": "flashadicts/superslides",
"id": "97af12cc3757f706841e0b15431a48fd5321911f",
"size": "588",
"binary": false,
"copies": "9",
"ref": "refs/heads/0.6-stable",
"path": "src/plugin.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6851"
},
{
"name": "HTML",
"bytes": "14932"
},
{
"name": "JavaScript",
"bytes": "103317"
}
],
"symlink_target": ""
} |
namespace quiche {
template <typename T> using QuicheOptionalImpl = absl::optional<T>;
} // namespace quiche
| {
"content_hash": "b8f9ba536fbe8591cbf19b742faa1bac",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 67,
"avg_line_length": 22.2,
"alnum_prop": 0.7477477477477478,
"repo_name": "eklitzke/envoy",
"id": "7cc2237ca3e3a601b4058f0ce292e8f7046652e1",
"size": "372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/extensions/quic_listeners/quiche/platform/quiche_optional_impl.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "21685"
},
{
"name": "C++",
"bytes": "18065395"
},
{
"name": "Dockerfile",
"bytes": "245"
},
{
"name": "Emacs Lisp",
"bytes": "966"
},
{
"name": "Go",
"bytes": "695"
},
{
"name": "PowerShell",
"bytes": "5725"
},
{
"name": "PureBasic",
"bytes": "472"
},
{
"name": "Python",
"bytes": "381045"
},
{
"name": "Rust",
"bytes": "892"
},
{
"name": "Shell",
"bytes": "109058"
},
{
"name": "Starlark",
"bytes": "1088951"
},
{
"name": "Thrift",
"bytes": "748"
}
],
"symlink_target": ""
} |
require File.expand_path('../helper', __FILE__)
class EnvTest < Faraday::TestCase
def setup
@conn = Faraday.new :url => 'http://sushi.com/api',
:headers => {'Mime-Version' => '1.0'},
:request => {:oauth => {:consumer_key => 'anonymous'}}
@conn.options.timeout = 3
@conn.options.open_timeout = 5
@conn.ssl.verify = false
@conn.proxy 'http://proxy.com'
end
def test_request_create_stores_method
env = make_env(:get)
assert_equal :get, env.method
end
def test_request_create_stores_uri
env = make_env do |req|
req.url 'foo.json', 'a' => 1
end
assert_equal 'http://sushi.com/api/foo.json?a=1', env.url.to_s
end
def test_request_create_stores_uri_with_anchor
env = make_env do |req|
req.url 'foo.json?b=2&a=1#qqq'
end
assert_equal 'http://sushi.com/api/foo.json?a=1&b=2', env.url.to_s
end
def test_request_create_stores_headers
env = make_env do |req|
req['Server'] = 'Faraday'
end
headers = env.request_headers
assert_equal '1.0', headers['mime-version']
assert_equal 'Faraday', headers['server']
end
def test_request_create_stores_body
env = make_env do |req|
req.body = 'hi'
end
assert_equal 'hi', env.body
end
def test_global_request_options
env = make_env
assert_equal 3, env.request.timeout
assert_equal 5, env.request.open_timeout
end
def test_per_request_options
env = make_env do |req|
req.options.timeout = 10
req.options.boundary = 'boo'
req.options.oauth[:consumer_secret] = 'xyz'
end
assert_equal 10, env.request.timeout
assert_equal 5, env.request.open_timeout
assert_equal 'boo', env.request.boundary
oauth_expected = {:consumer_secret => 'xyz', :consumer_key => 'anonymous'}
assert_equal oauth_expected, env.request.oauth
end
def test_request_create_stores_ssl_options
env = make_env
assert_equal false, env.ssl.verify
end
def test_request_create_stores_proxy_options
env = make_env
assert_equal 'proxy.com', env.request.proxy.host
end
def test_custom_members_are_retained
env = make_env
env[:foo] = "custom 1"
env[:bar] = :custom_2
env2 = Faraday::Env.from(env)
assert_equal "custom 1", env2[:foo]
assert_equal :custom_2, env2[:bar]
env2[:baz] = "custom 3"
assert_nil env[:baz]
end
private
def make_env(method = :get, connection = @conn, &block)
request = connection.build_request(method, &block)
request.to_env(connection)
end
end
class HeadersTest < Faraday::TestCase
def setup
@headers = Faraday::Utils::Headers.new
end
def test_normalizes_different_capitalizations
@headers['Content-Type'] = 'application/json'
assert_equal ['Content-Type'], @headers.keys
assert_equal 'application/json', @headers['Content-Type']
assert_equal 'application/json', @headers['CONTENT-TYPE']
assert_equal 'application/json', @headers['content-type']
assert @headers.include?('content-type')
@headers['content-type'] = 'application/xml'
assert_equal ['Content-Type'], @headers.keys
assert_equal 'application/xml', @headers['Content-Type']
assert_equal 'application/xml', @headers['CONTENT-TYPE']
assert_equal 'application/xml', @headers['content-type']
end
def test_fetch_key
@headers['Content-Type'] = 'application/json'
block_called = false
assert_equal 'application/json', @headers.fetch('content-type') { block_called = true }
assert_equal 'application/json', @headers.fetch('Content-Type')
assert_equal 'application/json', @headers.fetch('CONTENT-TYPE')
assert_equal 'application/json', @headers.fetch(:content_type)
assert_equal false, block_called
assert_equal 'default', @headers.fetch('invalid', 'default')
assert_equal false, @headers.fetch('invalid', false)
assert_nil @headers.fetch('invalid', nil)
assert_equal 'Invalid key', @headers.fetch('Invalid') { |key| "#{key} key" }
expected_error = defined?(KeyError) ? KeyError : IndexError
assert_raises(expected_error) { @headers.fetch('invalid') }
end
def test_delete_key
@headers['Content-Type'] = 'application/json'
assert_equal 1, @headers.size
assert @headers.include?('content-type')
assert_equal 'application/json', @headers.delete('content-type')
assert_equal 0, @headers.size
assert !@headers.include?('content-type')
assert_equal nil, @headers.delete('content-type')
end
def test_parse_response_headers_leaves_http_status_line_out
@headers.parse("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n")
assert_equal %w(Content-Type), @headers.keys
end
def test_parse_response_headers_parses_lower_cased_header_name_and_value
@headers.parse("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n")
assert_equal 'text/html', @headers['content-type']
end
def test_parse_response_headers_parses_lower_cased_header_name_and_value_with_colon
@headers.parse("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nLocation: http://sushi.com/\r\n\r\n")
assert_equal 'http://sushi.com/', @headers['location']
end
def test_parse_response_headers_parses_blank_lines
@headers.parse("HTTP/1.1 200 OK\r\n\r\nContent-Type: text/html\r\n\r\n")
assert_equal 'text/html', @headers['content-type']
end
end
class ResponseTest < Faraday::TestCase
def setup
@env = Faraday::Env.from \
:status => 404, :body => 'yikes',
:response_headers => {'Content-Type' => 'text/plain'}
@response = Faraday::Response.new @env
end
def test_finished
assert @response.finished?
end
def test_error_on_finish
assert_raises RuntimeError do
@response.finish({})
end
end
def test_body_is_parsed_on_finish
response = Faraday::Response.new
response.on_complete { |env| env[:body] = env[:body].upcase }
response.finish(@env)
assert_equal "YIKES", response.body
end
def test_response_body_is_available_during_on_complete
response = Faraday::Response.new
response.on_complete { |env| env[:body] = response.body.upcase }
response.finish(@env)
assert_equal "YIKES", response.body
end
def test_env_in_on_complete_is_identical_to_response_env
response = Faraday::Response.new
callback_env = nil
response.on_complete { |env| callback_env = env }
response.finish({})
assert_same response.env, callback_env
end
def test_not_success
assert !@response.success?
end
def test_status
assert_equal 404, @response.status
end
def test_body
assert_equal 'yikes', @response.body
end
def test_headers
assert_equal 'text/plain', @response.headers['Content-Type']
assert_equal 'text/plain', @response['content-type']
end
def test_apply_request
@response.apply_request :body => 'a=b', :method => :post
assert_equal 'yikes', @response.body
assert_equal :post, @response.env[:method]
end
def test_marshal
@response = Faraday::Response.new
@response.on_complete { }
@response.finish @env.merge(:params => 'moo')
loaded = Marshal.load Marshal.dump(@response)
assert_nil loaded.env[:params]
assert_equal %w[body response_headers status], loaded.env.keys.map { |k| k.to_s }.sort
end
def test_hash
hash = @response.to_hash
assert_kind_of Hash, hash
assert_equal @env.to_hash, hash
assert_equal hash[:status], @response.status
assert_equal hash[:response_headers], @response.headers
assert_equal hash[:body], @response.body
end
end
| {
"content_hash": "3b15f13b05a425855283afc9302f9125",
"timestamp": "",
"source": "github",
"line_count": 253,
"max_line_length": 103,
"avg_line_length": 29.893280632411066,
"alnum_prop": 0.6678566706333465,
"repo_name": "davoclavo/faraday",
"id": "c8efb8c1de960d6d03e073322e45818c14d803df",
"size": "7563",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/env_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "205661"
},
{
"name": "Shell",
"bytes": "5338"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "7e4e8b76999ddc019f580c75f7c302d0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "35df6f482cdc38af1f235a3e97cb6f15f9833d73",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pinophyta/Pinopsida/Pinales/Pinaceae/Abies/Abies firma/ Syn. Abies bifida/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef TIME_UTIL_H
#define TIME_UTIL_H
#include <sys/time.h> /* for struct timeval */
/* Returns -1 if tv1<tv2, 1 if tv1>tv2, 0 if they're equal. */
int timeval_cmp(const struct timeval *tv1, const struct timeval *tv2);
/* Returns tv1-tv2 in milliseconds. */
int timeval_diff_msecs(const struct timeval *tv1, const struct timeval *tv2);
/* Returns tv1-tv2 in microseconds. */
long long timeval_diff_usecs(const struct timeval *tv1,
const struct timeval *tv2);
/* Wrapper to strftime() */
const char *t_strflocaltime(const char *fmt, time_t t) ATTR_STRFTIME(1);
#endif
| {
"content_hash": "a8ccb559724a52691326830639ec7477",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 77,
"avg_line_length": 34.1764705882353,
"alnum_prop": 0.7091222030981067,
"repo_name": "jkerihuel/dovecot",
"id": "2738a74f1a4a1dbeb924cc9c866cbd46b7f1689f",
"size": "581",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "src/lib/time-util.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9630460"
},
{
"name": "C++",
"bytes": "60393"
},
{
"name": "Logos",
"bytes": "3470"
},
{
"name": "Objective-C",
"bytes": "10755"
},
{
"name": "Perl",
"bytes": "8159"
},
{
"name": "Python",
"bytes": "1626"
},
{
"name": "Shell",
"bytes": "10564"
}
],
"symlink_target": ""
} |
'use strict';
var toArray = require('es5-ext/array/to-array')
, Database = require('../../../')
, Event = require('../../../_setup/event');
module.exports = function (a) {
var db = new Database(), obj = new db.Object(), iterator, data;
db.Object.prototype.$getOwn('test').multiple = true;
obj.test = ['raz', 2, 'trzy', 4];
iterator = obj.test.values();
obj.test.add('pięć');
obj.test.delete(2);
a.deep(toArray(iterator), data = ['raz', 'trzy', 4, 'pięć'], "Modified");
a.deep(toArray(obj.test), data, "Default iterator");
db.DateTime.extend('Foo', {
step: { value: 1000 * 60 * 60 * 24 },
_validateCreate_: { value: function (value/*[, mth[, d[, h]]]*/) {
var l = arguments.length, year, month, day;
if (!l) {
value = new Date();
year = value.getFullYear();
month = value.getMonth();
day = value.getDate();
value.setUTCFullYear(year);
value.setUTCMonth(month);
value.setUTCDate(day);
} else if (l === 1) {
value = new Date(value);
} else {
value = new Date(Date.UTC(value, arguments[1], (l > 2) ? arguments[2] : 1,
(l > 3) ? arguments[3] : 0));
}
return [this.database.DateTime.validate.call(this, value)];
} },
normalize: { value: function (value/*, descriptor*/) {
var year, month, date;
if (!value) return this.database.DateTime.normalize.apply(this, arguments);
if (value instanceof this) return this.database.DateTime.normalize.apply(this, arguments);
if (Object.prototype.toString.call(value) !== '[object Date]') {
return this.database.DateTime.normalize.apply(this, arguments);
}
year = value.getFullYear();
month = value.getMonth();
date = value.getDate();
value = new Date(value);
value.setUTCFullYear(year);
value.setUTCMonth(month);
value.setUTCDate(date);
return this.database.DateTime.normalize.call(this, value, arguments[1]);
} },
validate: { value: function (value/*, descriptor*/) {
var year, month, date;
if (!value) return this.database.DateTime.validate.apply(this, arguments);
if (value instanceof this) return this.database.DateTime.validate.apply(this, arguments);
if (Object.prototype.toString.call(value) !== '[object Date]') {
return this.database.DateTime.validate.apply(this, arguments);
}
year = value.getFullYear();
month = value.getMonth();
date = value.getDate();
value = new Date(value);
value.setUTCFullYear(year);
value.setUTCMonth(month);
value.setUTCDate(date);
return this.database.DateTime.validate.call(this, value, arguments[1]);
} }
});
db.Object.prototype.define('dates', {
multiple: true,
type: db.Foo
});
obj = db.objects.unserialize('Object#/dates*41420070400000');
new Event(obj, true, 123); //jslint: ignore
a(db.Object.prototype.dates.first instanceof db.Foo, true);
};
| {
"content_hash": "0588d5d5997d39a735a1fcd69272a45d",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 93,
"avg_line_length": 35.1375,
"alnum_prop": 0.6488794023479189,
"repo_name": "medikoo/dbjs",
"id": "29a6166c2b96e9567d6ef02156ffbf9b9bb83bc9",
"size": "2815",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/_setup/2.multiple-item/iterator.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "480524"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/onechiporenko/ember-models-table)
[](https://www.codacy.com/app/cv_github/ember-models-table)
[](https://emberobserver.com/addons/ember-models-table)
[](http://badge.fury.io/js/ember-models-table)
[](http://doge.mit-license.org)
[](https://www.npmjs.com/package/ember-models-table)
## Install
```bash
ember install ember-models-table
```
## Usage
See [Demo](http://onechiporenko.github.io/ember-models-table/)
## Requirements
* Twitter Bootstrap should be installed | {
"content_hash": "a6ee192467a5d6697f138d98dff2206e",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 147,
"avg_line_length": 45.476190476190474,
"alnum_prop": 0.7382198952879581,
"repo_name": "kosijer84/ember-models-table",
"id": "949f2c7ff46e23b8e7bc4c959537dffcca341488",
"size": "977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1816"
},
{
"name": "HTML",
"bytes": "54533"
},
{
"name": "JavaScript",
"bytes": "180501"
},
{
"name": "Shell",
"bytes": "416"
}
],
"symlink_target": ""
} |
/**
* @file
* Navigation Styling
*/
/*
* Markup generated by theme_menu_tree().
*/
ul li.expanded {
*list-style-image: url(../images/menu-expanded.png);
list-style-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHAQMAAAD+nMWQAAAABlBMVEX///8AAABVwtN+AAAAAXRSTlMAQObYZgAAABJJREFUeJxj+MdQw2DBIMAABgAUsAHD3c3BpwAAAABJRU5ErkJggg==');
list-style-type: circle;
}
ul li.collapsed {
*list-style-image: url(../images/menu-collapsed.png); /* LTR */
list-style-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHAQMAAAD+nMWQAAAABlBMVEX///8AAABVwtN+AAAAAXRSTlMAQObYZgAAABFJREFUCB1jVmCGQClmEWYOAAZ8AMy3HPLXAAAAAElFTkSuQmCC'); /* LTR */
list-style-type: disc;
}
ul li.leaf {
*list-style-image: url(../images/menu-leaf.png);
list-style-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHBAMAAAA2fErgAAAAD1BMVEX///+/v7+Li4sAAADAwMBFvsw8AAAAAXRSTlMAQObYZgAAAB1JREFUCFtjYAADYwMGBmYVZSDhKAwkFJWhYiAAAB2+Aa/9ugeaAAAAAElFTkSuQmCC');
list-style-type: square;
}
/*
* The active item in a Drupal menu
*/
li a.active {
color: #000;
}
/*
* Navigation bar
*/
#navigation {
/* overflow: hidden; */ /* Sometimes you want to prevent overlapping with main div. */
}
#navigation .block {
margin-bottom: 0;
}
#navigation .block-menu .block-title,
#navigation .block-menu-block .block-title {
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px);
}
#navigation ul.links, /* Main menu and secondary menu links */
#navigation ul.menu { /* Menu block links */
margin: 0;
padding: 0;
text-align: left; /* LTR */
}
#navigation ul.links li,
#navigation ul.menu li { /* A simple method to get navigation links to appear in one line. */
float: left; /* LTR */
padding: 0 2px 0 0; /* LTR */
list-style-type: none;
list-style-image: none;
}
.region-navigation {
}
/*
* Main menu and Secondary menu links
*/
#block-system-main-menu {
float: left;
position: relative;
display: inline-block;
}
#block-system-main-menu li.last span.muchomenu-parent-title {
display: none;
}
#block-system-main-menu .muchomenu-bin-3 {
list-style: none;
float: left;
z-index: 900000;
width: 225px;
position: absolute;
right: 145px;
display: inline !important;
top: 1em;
font-size: .75em;
display: inline-block;
}
#block-system-main-menu .panel-display .bryant-flipped {
padding: 0;
border: none;
border-radius: 0;
display: inline;
float: left;
z-index: 300000;
width: 225px;
height: 75px;
}
#block-system-main-menu a, #block-system-main-menu a:visited {
text-transform: uppercase;
position: relative;
top: 42px;
font-size: 0.8em;
font-weight: bolder;
text-decoration: none;
color: #383d41;
}
#block-system-main-menu a:hover, #block-system-main-menu a:active {
text-transform: uppercase;
position: relative;
top: 42px;
font-size: 0.8em;
font-weight: bolder;
text-decoration: none;
color: #d42126;
}
#block-system-main-menu ul.menu {
padding: 0;
margin: 0;
display: inline;
position: relative;
right: 0;
top: 0.5em;
float: right;
overflow:visible;
}
#block-system-main-menu li.leaf {
display: inline-block;
margin: 0 auto;
padding: 0 2em;
vertical-align: top;
min-height: 72px;
background: white;
background:
-moz-linear-gradient(45deg, transparent 5px, #ffffff 5px),
-moz-linear-gradient(135deg, transparent 5px, #ffffff 5px),
-moz-linear-gradient(225deg, #fffffft 5px, #ffffff 5px),
-moz-linear-gradient(315deg, #ffffff 5px, #ffffff 5px);
background:
-o-linear-gradient(45deg, transparent 5px, #ffffff 5px),
-o-linear-gradient(135deg, transparent 5px, #ffffff 5px),
-o-linear-gradient(225deg, #ffffff 5px, #ffffff 5px),
-o-linear-gradient(315deg, #fffffft 5px, #ffffff 5px);
background:
-webkit-linear-gradient(45deg, transparent 5px, #ffffff 5px),
-webkit-linear-gradient(135deg, transparent 5px, #ffffff 5px),
-webkit-linear-gradient(225deg, #ffffff 5px, #ffffff 5px),
-webkit-linear-gradient(315deg, #ffffff 5px, #ffffff 5px);
background-position: bottom left, bottom right, top left, top right;
-moz-background-size: 50% 50%;
-webkit-background-size: 50% 50%;
background-size: 50% 50%;
background-repeat: no-repeat;
}
#block-system-main-menu li.first.leaf {
background-image: url('../images/discover_off.png');
background-size: 4.5em;
background-repeat: no-repeat;
background-position: 50% 50%;
}
#block-system-main-menu li.first.leaf:hover {
background-image: url('../images/discover.png');
background-size: 5em;
background-repeat: no-repeat;
background-position: 50% 50%;
}
#block-system-main-menu li.leaf {
background-image: url('../images/shop_off.png');
background-size: 4em;
background-repeat: no-repeat;
background-position: 50% 50%;
}
#block-system-main-menu li.leaf:hover {
background-image: url('../images/shop.png');
background-size: 4.5em;
background-repeat: no-repeat;
background-position: 50% 50%;
}
#block-system-main-menu li.last.leaf {
background-image: url('../images/create_off.png');
background-size: 2.25em;
background-repeat: no-repeat;
background-position: 50% 50%;
}
#block-system-main-menu li.last.leaf:hover {
background-image: url('../images/create.png');
background-size: 2.75em;
background-repeat: no-repeat;
background-position: 50% 50%;
}
#block-panels-mini-user-menu {
display: inline-block;
background: #d42126;
font-size: 0.8em;
min-height: 75px;
padding: 0;
margin: 0;
float: left;
top: 0;
right: 0;
width: auto;
min-width: 200px;
position: relative;
left: 2em;
}
#block-panels-mini-user-menu .panel-display.bryant-flipped .bryant-flipped-content-container {
margin-bottom: 0 !important;
margin: 0;
padding: 0;
}
#block-panels-mini-user-menu .panel-display.bryant-flipped .bryant-flipped-content-inner {
margin-right: 0 !important;
margin: 0;
padding: 0;
}
#block-panels-mini-user-menu .panel-display.bryant-flipped .bryant-flipped-content {
width: auto;
height: 75px;
padding: 0;
margin: 0;
float: left;
}
#block-panels-mini-user-menu .panel-display.bryant-flipped .bryant-flipped-sidebar {
width: 25%;
padding: 0;
margin: 0;
float: right;
}
#block-panels-mini-user-menu ul.menu {
padding: 0.5em 0 0 0.5em;
margin: 0;
list-style: none;
}
#block-panels-mini-user-menu ul.menu li.first ul.menu {
padding: 0;
}
#block-panels-mini-user-menu ul.menu li.first ul.menu li {
list-style: none;
}
#block-panels-mini-user-menu a,
block-panels-mini-user-menu a:visited {
text-align: center;
text-decoration: none;
padding: 0;
top: 0;
position: relative;
color: #393d41;
}
#block-panels-mini-user-menu a:hover {
color: #f2f4f5;
}
#block-panels-mini-user-menu ul.menu {
position: relative;
width: auto;
list-style: none;
margin: 0;
padding: 0 0 0 1em;
}
#block-panels-mini-user-menu li {
background: #d42126;
padding: 0;
min-height: 0;
line-height: 16px;
margin: 0;
background-position: center center;
background-repeat: repeat;
border: 0;
list-style: none;
}
#block-panels-mini-user-menu div ul.menu li.menu-mlid-1691 ul.menu a,
#block-panels-mini-user-menu div ul.menu li.menu-mlid-1691 ul.menu a:link,
#block-panels-mini-user-menu div ul.menu li.menu-mlid-1691 ul.menu a:visited {
color: white;
text-decoration: none;
line-height: 0.7em;
text-align: left;
list-style: none;
}
#block-panels-mini-user-menu div ul.menu li.menu-mlid-1691 ul.menu a: {
color: #393d41;
}
#block-panels-mini-user-menu div ul.menu li.menu-mlid-1691 a,
#block-panels-mini-user-menu div ul.menu li.menu-mlid-1691 a:link,
#block-panels-mini-user-menu div ul.menu li.menu-mlid-1691 a:visted {
color: #393d41;
}
#block-panels-mini-user-menu div ul.menu li.menu-mlid-1691 a:hover {
color: white !important;
}
#block-panels-mini-user-menu a.link-badge-wrapper span {
display: inline !important;
}
#block-panels-mini-user-menu .pane-user-picture {
position: relative;
float: right;
right: 1em;
top: 1em;
max-width: 100px;
}
/** tabs tabs tabs ***/
#content ul.tabs,
#content ul.tabs {
border-bottom: 0;
margin: 0 1em;
padding: 0;
background-color: #616467;
}
#content ul.tabs li {
-moz-border-radius-topleft: 0;
-webkit-border-top-left-radius: 0;
-ms-border-top-left-radius: 0;
-o-border-top-left-radius: 0;
border-top-left-radius: 0;
-moz-border-radius-topright: 0;
-webkit-border-top-right-radius: 0;
-ms-border-top-right-radius: 0;
-o-border-top-right-radius: 0;
border-top-right-radius: 0;
text-shadow: none;
border: 0;
border-bottom: 0;
margin: 0;
}
#content ul.tabs li.active {
border-bottom: none;
margin-bottom: 0;
}
#content ul.tabs a:link,
#content ul.tabs a:visited {
border: 0;
background-color: inherit;
color: white;
text-transform: uppercase;
letter-spacing: 0.2em;
padding: 0.5em 1em;
-moz-border-radius-topleft: 0;
-webkit-border-top-left-radius: 0;
-ms-border-top-left-radius: 0;
-o-border-top-left-radius: 0;
border-top-left-radius: 0;
-moz-border-radius-topright: 0;
-webkit-border-top-right-radius: 0;
-ms-border-top-right-radius: 0;
-o-border-top-right-radius: 0;
border-top-right-radius: 0;
-webkit-transition: background-color none;
-moz-transition: background-color none;
-ms-transition: background-color none;
-o-transition: background-color none;
transition: background-color none;
}
#content ul.tabs a:hover {
color: #df2126;
}
#content ul.tabs a.active {
background-color: white;
background-image: none;
text-transform: uppercase;
color: #393d41;
}
| {
"content_hash": "9b1e5b07851ee9b974af4dc2cddd48e6",
"timestamp": "",
"source": "github",
"line_count": 402,
"max_line_length": 218,
"avg_line_length": 23.86318407960199,
"alnum_prop": 0.7022829146252476,
"repo_name": "justadropofwater/spaceblues.com",
"id": "bc9220ff4745003a4a8148e69ad89a8c83a9def1",
"size": "9593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sites/all/themes/zen_spaceblues/css/navigation.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7006"
},
{
"name": "JavaScript",
"bytes": "6626191"
},
{
"name": "PHP",
"bytes": "9045022"
},
{
"name": "Python",
"bytes": "175988"
},
{
"name": "Ruby",
"bytes": "14576"
},
{
"name": "Shell",
"bytes": "60901"
}
],
"symlink_target": ""
} |
package com.wisape.android.cordova;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import org.apache.cordova.CordovaResourceApi;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Build;
import android.os.Environment;
import android.util.Base64;
import android.net.Uri;
import android.content.Context;
import android.content.Intent;
public class LocalFilesystem extends Filesystem {
private final Context context;
public LocalFilesystem(String name, Context context, CordovaResourceApi resourceApi, File fsRoot) {
super(Uri.fromFile(fsRoot).buildUpon().appendEncodedPath("").build(), name, resourceApi);
this.context = context;
}
public String filesystemPathForFullPath(String fullPath) {
return new File(rootUri.getPath(), fullPath).toString();
}
@Override
public String filesystemPathForURL(LocalFilesystemURL url) {
return filesystemPathForFullPath(url.path);
}
private String fullPathForFilesystemPath(String absolutePath) {
if (absolutePath != null && absolutePath.startsWith(rootUri.getPath())) {
return absolutePath.substring(rootUri.getPath().length() - 1);
}
return null;
}
@Override
public Uri toNativeUri(LocalFilesystemURL inputURL) {
return nativeUriForFullPath(inputURL.path);
}
@Override
public LocalFilesystemURL toLocalUri(Uri inputURL) {
if (!"file".equals(inputURL.getScheme())) {
return null;
}
File f = new File(inputURL.getPath());
// Removes and duplicate /s (e.g. file:///a//b/c)
Uri resolvedUri = Uri.fromFile(f);
String rootUriNoTrailingSlash = rootUri.getEncodedPath();
rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
return null;
}
String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
// Strip leading slash
if (!subPath.isEmpty()) {
subPath = subPath.substring(1);
}
Uri.Builder b = new Uri.Builder()
.scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
.authority("localhost")
.path(name);
if (!subPath.isEmpty()) {
b.appendEncodedPath(subPath);
}
if (f.isDirectory() || inputURL.getPath().endsWith("/")) {
// Add trailing / for directories.
b.appendEncodedPath("");
}
return LocalFilesystemURL.parse(b.build());
}
@Override
public LocalFilesystemURL URLforFilesystemPath(String path) {
return localUrlforFullPath(fullPathForFilesystemPath(path));
}
@Override
public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
boolean create = false;
boolean exclusive = false;
if (options != null) {
create = options.optBoolean("create");
if (create) {
exclusive = options.optBoolean("exclusive");
}
}
// Check for a ":" character in the file to line up with BB and iOS
if (path.contains(":")) {
throw new EncodingException("This path has an invalid \":\" in it.");
}
LocalFilesystemURL requestedURL;
// Check whether the supplied path is absolute or relative
if (directory && !path.endsWith("/")) {
path += "/";
}
if (path.startsWith("/")) {
requestedURL = localUrlforFullPath(normalizePath(path));
} else {
requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
}
File fp = new File(this.filesystemPathForURL(requestedURL));
if (create) {
if (exclusive && fp.exists()) {
throw new FileExistsException("create/exclusive fails");
}
if (directory) {
fp.mkdir();
} else {
fp.createNewFile();
}
if (!fp.exists()) {
throw new FileExistsException("create fails");
}
}
else {
if (!fp.exists()) {
throw new FileNotFoundException("path does not exist");
}
if (directory) {
if (fp.isFile()) {
throw new TypeMismatchException("path doesn't exist or is file");
}
} else {
if (fp.isDirectory()) {
throw new TypeMismatchException("path doesn't exist or is directory");
}
}
}
// Return the directory
return makeEntryForURL(requestedURL);
}
@Override
public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException {
File fp = new File(filesystemPathForURL(inputURL));
// You can't delete a directory that is not empty
if (fp.isDirectory() && fp.list().length > 0) {
throw new InvalidModificationException("You can't delete a directory that is not empty.");
}
return fp.delete();
}
@Override
public boolean exists(LocalFilesystemURL inputURL) {
File fp = new File(filesystemPathForURL(inputURL));
return fp.exists();
}
@Override
public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException {
File directory = new File(filesystemPathForURL(inputURL));
return removeDirRecursively(directory);
}
protected boolean removeDirRecursively(File directory) throws FileExistsException {
if (directory.isDirectory()) {
for (File file : directory.listFiles()) {
removeDirRecursively(file);
}
}
if (!directory.delete()) {
throw new FileExistsException("could not delete: " + directory.getName());
} else {
return true;
}
}
@Override
public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
File fp = new File(filesystemPathForURL(inputURL));
if (!fp.exists()) {
// The directory we are listing doesn't exist so we should fail.
throw new FileNotFoundException();
}
File[] files = fp.listFiles();
if (files == null) {
// inputURL is a directory
return null;
}
LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
for (int i = 0; i < files.length; i++) {
entries[i] = URLforFilesystemPath(files[i].getPath());
}
return entries;
}
@Override
public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
File file = new File(filesystemPathForURL(inputURL));
if (!file.exists()) {
throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
}
JSONObject metadata = new JSONObject();
try {
// Ensure that directories report a size of 0
metadata.put("size", file.isDirectory() ? 0 : file.length());
metadata.put("type", resourceApi.getMimeType(Uri.fromFile(file)));
metadata.put("name", file.getName());
metadata.put("fullPath", inputURL.path);
metadata.put("lastModifiedDate", file.lastModified());
} catch (JSONException e) {
return null;
}
return metadata;
}
private void copyFile(Filesystem srcFs, LocalFilesystemURL srcURL, File destFile, boolean move) throws IOException, InvalidModificationException, NoModificationAllowedException {
if (move) {
String realSrcPath = srcFs.filesystemPathForURL(srcURL);
if (realSrcPath != null) {
File srcFile = new File(realSrcPath);
if (srcFile.renameTo(destFile)) {
return;
}
// Trying to rename the file failed. Possibly because we moved across file system on the device.
}
}
CordovaResourceApi.OpenForReadResult offr = resourceApi.openForRead(srcFs.toNativeUri(srcURL));
copyResource(offr, new FileOutputStream(destFile));
if (move) {
srcFs.removeFileAtLocalURL(srcURL);
}
}
private void copyDirectory(Filesystem srcFs, LocalFilesystemURL srcURL, File dstDir, boolean move) throws IOException, NoModificationAllowedException, InvalidModificationException, FileExistsException {
if (move) {
String realSrcPath = srcFs.filesystemPathForURL(srcURL);
if (realSrcPath != null) {
File srcDir = new File(realSrcPath);
// If the destination directory already exists and is empty then delete it. This is according to spec.
if (dstDir.exists()) {
if (dstDir.list().length > 0) {
throw new InvalidModificationException("directory is not empty");
}
dstDir.delete();
}
// Try to rename the directory
if (srcDir.renameTo(dstDir)) {
return;
}
// Trying to rename the file failed. Possibly because we moved across file system on the device.
}
}
if (dstDir.exists()) {
if (dstDir.list().length > 0) {
throw new InvalidModificationException("directory is not empty");
}
} else {
if (!dstDir.mkdir()) {
// If we can't create the directory then fail
throw new NoModificationAllowedException("Couldn't create the destination directory");
}
}
LocalFilesystemURL[] children = srcFs.listChildren(srcURL);
for (LocalFilesystemURL childLocalUrl : children) {
File target = new File(dstDir, new File(childLocalUrl.path).getName());
if (childLocalUrl.isDirectory) {
copyDirectory(srcFs, childLocalUrl, target, false);
} else {
copyFile(srcFs, childLocalUrl, target, false);
}
}
if (move) {
srcFs.recursiveRemoveFileAtLocalURL(srcURL);
}
}
@Override
public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
// Check to see if the destination directory exists
String newParent = this.filesystemPathForURL(destURL);
File destinationDir = new File(newParent);
if (!destinationDir.exists()) {
// The destination does not exist so we should fail.
throw new FileNotFoundException("The source does not exist");
}
// Figure out where we should be copying to
final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL, srcURL.isDirectory);
Uri dstNativeUri = toNativeUri(destinationURL);
Uri srcNativeUri = srcFs.toNativeUri(srcURL);
// Check to see if source and destination are the same file
if (dstNativeUri.equals(srcNativeUri)) {
throw new InvalidModificationException("Can't copy onto itself");
}
if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
throw new InvalidModificationException("Source URL is read-only (cannot move)");
}
File destFile = new File(dstNativeUri.getPath());
if (destFile.exists()) {
if (!srcURL.isDirectory && destFile.isDirectory()) {
throw new InvalidModificationException("Can't copy/move a file to an existing directory");
} else if (srcURL.isDirectory && destFile.isFile()) {
throw new InvalidModificationException("Can't copy/move a directory to an existing file");
}
}
if (srcURL.isDirectory) {
// E.g. Copy /sdcard/myDir to /sdcard/myDir/backup
if (dstNativeUri.toString().startsWith(srcNativeUri.toString() + '/')) {
throw new InvalidModificationException("Can't copy directory into itself");
}
copyDirectory(srcFs, srcURL, destFile, move);
} else {
copyFile(srcFs, srcURL, destFile, move);
}
return makeEntryForURL(destinationURL);
}
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
boolean append = false;
if (offset > 0) {
this.truncateFileAtURL(inputURL, offset);
append = true;
}
byte[] rawData;
if (isBinary) {
rawData = Base64.decode(data, Base64.DEFAULT);
} else {
rawData = data.getBytes();
}
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
try
{
byte buff[] = new byte[rawData.length];
String absolutePath = filesystemPathForURL(inputURL);
FileOutputStream out = new FileOutputStream(absolutePath, append);
try {
in.read(buff, 0, buff.length);
out.write(buff, 0, rawData.length);
out.flush();
} finally {
// Always close the output
out.close();
}
if (isPublicDirectory(absolutePath)) {
broadcastNewFile(Uri.fromFile(new File(absolutePath)));
}
}
catch (NullPointerException e)
{
// This is a bug in the Android implementation of the Java Stack
NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
throw realException;
}
return rawData.length;
}
private boolean isPublicDirectory(String absolutePath) {
// TODO: should expose a way to scan app's private files (maybe via a flag).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Lollipop has a bug where SD cards are null.
for (File f : context.getExternalMediaDirs()) {
if(f != null && absolutePath.startsWith(f.getAbsolutePath())) {
return true;
}
}
}
String extPath = Environment.getExternalStorageDirectory().getAbsolutePath();
return absolutePath.startsWith(extPath);
}
/**
* Send broadcast of new file so files appear over MTP
*/
private void broadcastNewFile(Uri nativeUri) {
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, nativeUri);
context.sendBroadcast(intent);
}
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
File file = new File(filesystemPathForURL(inputURL));
if (!file.exists()) {
throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
}
RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
try {
if (raf.length() >= size) {
FileChannel channel = raf.getChannel();
channel.truncate(size);
return size;
}
return raf.length();
} finally {
raf.close();
}
}
@Override
public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
String path = filesystemPathForURL(inputURL);
File file = new File(path);
return file.exists();
}
// This is a copy & paste from CordovaResource API that is required since CordovaResourceApi
// has a bug pre-4.0.0.
// TODO: Once cordova-android@4.0.0 is released, delete this copy and make the plugin depend on
// 4.0.0 with an engine tag.
private static void copyResource(CordovaResourceApi.OpenForReadResult input, OutputStream outputStream) throws IOException {
try {
InputStream inputStream = input.inputStream;
if (inputStream instanceof FileInputStream && outputStream instanceof FileOutputStream) {
FileChannel inChannel = ((FileInputStream)input.inputStream).getChannel();
FileChannel outChannel = ((FileOutputStream)outputStream).getChannel();
long offset = 0;
long length = input.length;
if (input.assetFd != null) {
offset = input.assetFd.getStartOffset();
}
// transferFrom()'s 2nd arg is a relative position. Need to set the absolute
// position first.
inChannel.position(offset);
outChannel.transferFrom(inChannel, 0, length);
} else {
final int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
for (;;) {
int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
if (bytesRead <= 0) {
break;
}
outputStream.write(buffer, 0, bytesRead);
}
}
} finally {
input.inputStream.close();
if (outputStream != null) {
outputStream.close();
}
}
}
}
| {
"content_hash": "4b39e2a82de1062bc391f303235adbcd",
"timestamp": "",
"source": "github",
"line_count": 488,
"max_line_length": 206,
"avg_line_length": 38.028688524590166,
"alnum_prop": 0.5890182131695226,
"repo_name": "WisapeAgency/WisapeAndroid",
"id": "64f08e4d04c303366723fa92f66da13af421b450",
"size": "19434",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/src/main/java/com/wisape/android/cordova/LocalFilesystem.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "12529"
},
{
"name": "C++",
"bytes": "1170"
},
{
"name": "CSS",
"bytes": "37332"
},
{
"name": "HTML",
"bytes": "164795"
},
{
"name": "Java",
"bytes": "1953310"
},
{
"name": "JavaScript",
"bytes": "416715"
},
{
"name": "Makefile",
"bytes": "332"
}
],
"symlink_target": ""
} |
using System.Web.UI.WebControls;
namespace Uncas.EBS.UI.Controls
{
/// <summary>
/// A radio button list with the status options.
/// </summary>
public class StatusOptions : RadioButtonList
{
/// <summary>
/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
/// </summary>
protected override void CreateChildControls()
{
base.CreateChildControls();
if (this.Items.Count == 0)
{
var openItem = new ListItem
(Resources.Phrases.Open, "1");
openItem.Selected = true;
this.Items.Add(openItem);
this.Items.Add(new ListItem
(Resources.Phrases.Closed, "2"));
this.Items.Add(new ListItem
(Resources.Phrases.All, "0"));
}
this.AutoPostBack = true;
this.RepeatDirection = RepeatDirection.Horizontal;
}
}
} | {
"content_hash": "d85fe0cc2252131bf1986b253a3fb795",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 204,
"avg_line_length": 35.121212121212125,
"alnum_prop": 0.547886108714409,
"repo_name": "uncas/hibes",
"id": "8a94788b7f11418fb09e5cb5a920077865b13894",
"size": "1161",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Uncas.EBS.UI/Controls/StatusOptions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "57858"
},
{
"name": "C#",
"bytes": "397848"
},
{
"name": "Python",
"bytes": "4206"
},
{
"name": "Shell",
"bytes": "338"
}
],
"symlink_target": ""
} |
using DataCenter.Localization;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Localization;
namespace DataCenter.Permissions
{
public class DataCenterPermissionDefinitionProvider : PermissionDefinitionProvider
{
public override void Define(IPermissionDefinitionContext context)
{
var myGroup = context.AddGroup(DataCenterPermissions.GroupName);
//Define your own permissions here. Example:
//myGroup.AddPermission(DataCenterPermissions.MyPermission1, L("Permission:MyPermission1"));
}
private static LocalizableString L(string name)
{
return LocalizableString.Create<DataCenterResource>(name);
}
}
}
| {
"content_hash": "d32f6dd93a44d1b9839831add55afb64",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 104,
"avg_line_length": 32.81818181818182,
"alnum_prop": 0.7105263157894737,
"repo_name": "xin2015/DataCenter",
"id": "0d5a6d2f0b22c886d2096fcec27217793ae8350b",
"size": "724",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DataCenter.Application.Contracts/Permissions/DataCenterPermissionDefinitionProvider.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "102"
},
{
"name": "C#",
"bytes": "213596"
},
{
"name": "CSS",
"bytes": "413907"
},
{
"name": "HTML",
"bytes": "98139"
},
{
"name": "JavaScript",
"bytes": "3948860"
},
{
"name": "PHP",
"bytes": "6147"
}
],
"symlink_target": ""
} |
import offices from '../data/offices.json';
export default function() {
return offices;
} | {
"content_hash": "a446b9956141bf0e3b1650ee98a2429f",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 43,
"avg_line_length": 18.4,
"alnum_prop": 0.717391304347826,
"repo_name": "leapon/office-finder",
"id": "516c7941a376f7ddcf5fc93602c95c4e4b0c6de6",
"size": "92",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/reducers/reducer_offices.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7137"
},
{
"name": "HTML",
"bytes": "13590"
},
{
"name": "JavaScript",
"bytes": "58028"
}
],
"symlink_target": ""
} |
package org.waveprotocol.wave.model.conversation;
import org.waveprotocol.wave.model.wave.SourcesEvents;
/**
* Extends {@link Manifest} to provide events that can be listened to.
*
* @author anorth@google.com (Alex North)
*/
interface ObservableManifest extends Manifest, SourcesEvents<ObservableManifest.Listener> {
/**
* Receives events on a {@link Manifest}.
*/
interface Listener {
/**
* Notifies this listener that the manifest anchor has changed.
*
* @param oldAnchor the old anchor values
* @param newAnchor the new anchor values
*/
void onAnchorChanged(AnchorData oldAnchor, AnchorData newAnchor);
}
// Covariant specialisations.
@Override
ObservableManifestThread getRootThread();
}
| {
"content_hash": "5c3b0bf574aec9829bbb918add4fc885",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 91,
"avg_line_length": 25.1,
"alnum_prop": 0.7184594953519257,
"repo_name": "Grasia/swellrt",
"id": "3cfaa937e6e10b1682e489a09aa7f280240247e5",
"size": "1561",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "wave/src/main/java/org/waveprotocol/wave/model/conversation/ObservableManifest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1893"
},
{
"name": "CSS",
"bytes": "133405"
},
{
"name": "Dockerfile",
"bytes": "1106"
},
{
"name": "HTML",
"bytes": "199097"
},
{
"name": "Java",
"bytes": "13662385"
},
{
"name": "JavaScript",
"bytes": "520586"
},
{
"name": "Shell",
"bytes": "7549"
},
{
"name": "Smalltalk",
"bytes": "23006"
}
],
"symlink_target": ""
} |
namespace llvm {
class RISCVSubtarget;
namespace RISCVISD {
enum NodeType : unsigned {
FIRST_NUMBER = ISD::BUILTIN_OP_END,
RET_FLAG,
URET_FLAG,
SRET_FLAG,
MRET_FLAG,
CALL,
SELECT_CC,
BuildPairF64,
SplitF64,
TAIL,
// RV64I shifts, directly matching the semantics of the named RISC-V
// instructions.
SLLW,
SRAW,
SRLW,
// 32-bit operations from RV64M that can't be simply matched with a pattern
// at instruction selection time.
DIVW,
DIVUW,
REMUW,
// FPR32<->GPR transfer operations for RV64. Needed as an i32<->f32 bitcast
// is not legal on RV64. FMV_W_X_RV64 matches the semantics of the FMV.W.X.
// FMV_X_ANYEXTW_RV64 is similar to FMV.X.W but has an any-extended result.
// This is a more convenient semantic for producing dagcombines that remove
// unnecessary GPR->FPR->GPR moves.
FMV_W_X_RV64,
FMV_X_ANYEXTW_RV64,
// READ_CYCLE_WIDE - A read of the 64-bit cycle CSR on a 32-bit target
// (returns (Lo, Hi)). It takes a chain operand.
READ_CYCLE_WIDE
};
}
class RISCVTargetLowering : public TargetLowering {
const RISCVSubtarget &Subtarget;
public:
explicit RISCVTargetLowering(const TargetMachine &TM,
const RISCVSubtarget &STI);
bool getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I,
MachineFunction &MF,
unsigned Intrinsic) const override;
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty,
unsigned AS,
Instruction *I = nullptr) const override;
bool isLegalICmpImmediate(int64_t Imm) const override;
bool isLegalAddImmediate(int64_t Imm) const override;
bool isTruncateFree(Type *SrcTy, Type *DstTy) const override;
bool isTruncateFree(EVT SrcVT, EVT DstVT) const override;
bool isZExtFree(SDValue Val, EVT VT2) const override;
bool isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const override;
bool hasBitPreservingFPLogic(EVT VT) const override;
// Provide custom lowering hooks for some operations.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override;
void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
SelectionDAG &DAG) const override;
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override;
unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
const APInt &DemandedElts,
const SelectionDAG &DAG,
unsigned Depth) const override;
// This method returns the name of a target specific DAG node.
const char *getTargetNodeName(unsigned Opcode) const override;
ConstraintType getConstraintType(StringRef Constraint) const override;
unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const override;
std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
StringRef Constraint, MVT VT) const override;
void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
std::vector<SDValue> &Ops,
SelectionDAG &DAG) const override;
MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr &MI,
MachineBasicBlock *BB) const override;
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
EVT VT) const override;
bool convertSetCCLogicToBitwiseLogic(EVT VT) const override {
return VT.isScalarInteger();
}
bool shouldInsertFencesForAtomic(const Instruction *I) const override {
return isa<LoadInst>(I) || isa<StoreInst>(I);
}
Instruction *emitLeadingFence(IRBuilder<> &Builder, Instruction *Inst,
AtomicOrdering Ord) const override;
Instruction *emitTrailingFence(IRBuilder<> &Builder, Instruction *Inst,
AtomicOrdering Ord) const override;
ISD::NodeType getExtendForAtomicOps() const override {
return ISD::SIGN_EXTEND;
}
bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const override {
if (DAG.getMachineFunction().getFunction().hasMinSize())
return false;
return true;
}
bool isDesirableToCommuteWithShift(const SDNode *N,
CombineLevel Level) const override;
/// If a physical register, this returns the register that receives the
/// exception address on entry to an EH pad.
unsigned
getExceptionPointerRegister(const Constant *PersonalityFn) const override;
/// If a physical register, this returns the register that receives the
/// exception typeid on entry to a landing pad.
unsigned
getExceptionSelectorRegister(const Constant *PersonalityFn) const override;
bool shouldExtendTypeInLibCall(EVT Type) const override;
/// Returns the register with the specified architectural or ABI name. This
/// method is necessary to lower the llvm.read_register.* and
/// llvm.write_register.* intrinsics. Allocatable registers must be reserved
/// with the clang -ffixed-xX flag for access to be allowed.
Register getRegisterByName(const char *RegName, LLT VT,
const MachineFunction &MF) const override;
private:
void analyzeInputArgs(MachineFunction &MF, CCState &CCInfo,
const SmallVectorImpl<ISD::InputArg> &Ins,
bool IsRet) const;
void analyzeOutputArgs(MachineFunction &MF, CCState &CCInfo,
const SmallVectorImpl<ISD::OutputArg> &Outs,
bool IsRet, CallLoweringInfo *CLI) const;
// Lower incoming arguments, copy physregs into vregs
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv,
bool IsVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
const SDLoc &DL, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const override;
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF,
bool IsVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
LLVMContext &Context) const override;
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL,
SelectionDAG &DAG) const override;
SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI,
SmallVectorImpl<SDValue> &InVals) const override;
bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
Type *Ty) const override {
return true;
}
template <class NodeTy>
SDValue getAddr(NodeTy *N, SelectionDAG &DAG, bool IsLocal = true) const;
SDValue getStaticTLSAddr(GlobalAddressSDNode *N, SelectionDAG &DAG,
bool UseGOT) const;
SDValue getDynamicTLSAddr(GlobalAddressSDNode *N, SelectionDAG &DAG) const;
bool shouldConsiderGEPOffsetSplit() const override { return true; }
SDValue lowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerBlockAddress(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerConstantPool(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerSELECT(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerVASTART(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerShiftLeftParts(SDValue Op, SelectionDAG &DAG) const;
SDValue lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, bool IsSRA) const;
bool isEligibleForTailCallOptimization(
CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
const SmallVector<CCValAssign, 16> &ArgLocs) const;
TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const override;
virtual Value *emitMaskedAtomicRMWIntrinsic(
IRBuilder<> &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const override;
TargetLowering::AtomicExpansionKind
shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CI) const override;
virtual Value *
emitMaskedAtomicCmpXchgIntrinsic(IRBuilder<> &Builder, AtomicCmpXchgInst *CI,
Value *AlignedAddr, Value *CmpVal,
Value *NewVal, Value *Mask,
AtomicOrdering Ord) const override;
/// Generate error diagnostics if any register used by CC has been marked
/// reserved.
void validateCCReservedRegs(
const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
MachineFunction &MF) const;
};
}
#endif
| {
"content_hash": "603ac9cd6cd43f31a9a931542aa8b93a",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 80,
"avg_line_length": 43.60287081339713,
"alnum_prop": 0.676725556896741,
"repo_name": "google/swiftshader",
"id": "b2ad75d670249f07a2f3ad643281851f5a2c935f",
"size": "9867",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "third_party/llvm-10.0/llvm/lib/Target/RISCV/RISCVISelLowering.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2466203"
},
{
"name": "C++",
"bytes": "8028101"
},
{
"name": "CMake",
"bytes": "43610"
},
{
"name": "Emacs Lisp",
"bytes": "4621"
},
{
"name": "Lex",
"bytes": "29718"
},
{
"name": "Makefile",
"bytes": "27584"
},
{
"name": "Objective-C++",
"bytes": "4408"
},
{
"name": "Shell",
"bytes": "2227"
},
{
"name": "Yacc",
"bytes": "68515"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_11) on Mon Mar 17 10:51:56 PDT 2014 -->
<title>BoxPreview</title>
<meta name="date" content="2014-03-17">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="BoxPreview";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/BoxPreview.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/box/boxjavalibv2/dao/BoxObjectFallBackTest.html" title="class in com.box.boxjavalibv2.dao"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../com/box/boxjavalibv2/dao/BoxRealTimeServer.html" title="class in com.box.boxjavalibv2.dao"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/box/boxjavalibv2/dao/BoxPreview.html" target="_top">Frames</a></li>
<li><a href="BoxPreview.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.box.boxjavalibv2.dao</div>
<h2 title="Class BoxPreview" class="title">Class BoxPreview</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../../com/box/boxjavalibv2/dao/BoxBase.html" title="class in com.box.boxjavalibv2.dao">com.box.boxjavalibv2.dao.BoxBase</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html" title="class in com.box.boxjavalibv2.dao">com.box.boxjavalibv2.dao.BoxObject</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../com/box/boxjavalibv2/dao/BoxBigPayloadObject.html" title="class in com.box.boxjavalibv2.dao">com.box.boxjavalibv2.dao.BoxBigPayloadObject</a></li>
<li>
<ul class="inheritance">
<li>com.box.boxjavalibv2.dao.BoxPreview</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../com/box/boxjavalibv2/dao/IBoxParcelable.html" title="interface in com.box.boxjavalibv2.dao">IBoxParcelable</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">BoxPreview</span>
extends <a href="../../../../com/box/boxjavalibv2/dao/BoxBigPayloadObject.html" title="class in com.box.boxjavalibv2.dao">BoxBigPayloadObject</a></pre>
<div class="block">Preview of a file.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#MAX_HEIGHT">MAX_HEIGHT</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#MAX_WIDTH">MAX_WIDTH</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#MIN_HEIGHT">MIN_HEIGHT</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#MIN_WIDTH">MIN_WIDTH</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#PAGE">PAGE</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#BoxPreview()">BoxPreview</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Integer</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#getFirstPage()">getFirstPage</a></strong>()</code>
<div class="block">Get the first page number.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.Integer</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#getLastPage()">getLastPage</a></strong>()</code>
<div class="block">Get the last page number.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Integer</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#getNumPages()">getNumPages</a></strong>()</code>
<div class="block">Get number of pages.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#setFirstPage(java.lang.Integer)">setFirstPage</a></strong>(java.lang.Integer firstPage)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../com/box/boxjavalibv2/dao/BoxPreview.html#setLastPage(int)">setLastPage</a></strong>(int lastPage)</code>
<div class="block">Set the last page number.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.box.boxjavalibv2.dao.BoxBigPayloadObject">
<!-- -->
</a>
<h3>Methods inherited from class com.box.boxjavalibv2.dao.<a href="../../../../com/box/boxjavalibv2/dao/BoxBigPayloadObject.html" title="class in com.box.boxjavalibv2.dao">BoxBigPayloadObject</a></h3>
<code><a href="../../../../com/box/boxjavalibv2/dao/BoxBigPayloadObject.html#getContent()">getContent</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxBigPayloadObject.html#getContentLength()">getContentLength</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxBigPayloadObject.html#setContent(java.io.InputStream)">setContent</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxBigPayloadObject.html#setContentLength(double)">setContentLength</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxBigPayloadObject.html#writeToParcel(com.box.boxjavalibv2.dao.IBoxParcelWrapper, int)">writeToParcel</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_com.box.boxjavalibv2.dao.BoxObject">
<!-- -->
</a>
<h3>Methods inherited from class com.box.boxjavalibv2.dao.<a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html" title="class in com.box.boxjavalibv2.dao">BoxObject</a></h3>
<code><a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html#contains(java.lang.String)">contains</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html#equals(java.lang.Object)">equals</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html#extraProperties()">extraProperties</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html#getExtraData(java.lang.String)">getExtraData</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html#getValue(java.lang.String)">getValue</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html#handleUnknown(java.lang.String, java.lang.Object)">handleUnknown</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html#hashCode()">hashCode</a>, <a href="../../../../com/box/boxjavalibv2/dao/BoxObject.html#put(java.lang.String, java.lang.Object)">put</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="MIN_WIDTH">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>MIN_WIDTH</h4>
<pre>public static final java.lang.String MIN_WIDTH</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.box.boxjavalibv2.dao.BoxPreview.MIN_WIDTH">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="MIN_HEIGHT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>MIN_HEIGHT</h4>
<pre>public static final java.lang.String MIN_HEIGHT</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.box.boxjavalibv2.dao.BoxPreview.MIN_HEIGHT">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="MAX_WIDTH">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>MAX_WIDTH</h4>
<pre>public static final java.lang.String MAX_WIDTH</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.box.boxjavalibv2.dao.BoxPreview.MAX_WIDTH">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="MAX_HEIGHT">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>MAX_HEIGHT</h4>
<pre>public static final java.lang.String MAX_HEIGHT</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.box.boxjavalibv2.dao.BoxPreview.MAX_HEIGHT">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="PAGE">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PAGE</h4>
<pre>public static final java.lang.String PAGE</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../constant-values.html#com.box.boxjavalibv2.dao.BoxPreview.PAGE">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="BoxPreview()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>BoxPreview</h4>
<pre>public BoxPreview()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="setFirstPage(java.lang.Integer)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setFirstPage</h4>
<pre>public void setFirstPage(java.lang.Integer firstPage)</pre>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>firstPage</code> - first page number</dd></dl>
</li>
</ul>
<a name="getFirstPage()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getFirstPage</h4>
<pre>public java.lang.Integer getFirstPage()</pre>
<div class="block">Get the first page number.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the first page number.</dd></dl>
</li>
</ul>
<a name="setLastPage(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setLastPage</h4>
<pre>public void setLastPage(int lastPage)</pre>
<div class="block">Set the last page number.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>lastPage</code> - last page number</dd></dl>
</li>
</ul>
<a name="getLastPage()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getLastPage</h4>
<pre>public java.lang.Integer getLastPage()</pre>
<div class="block">Get the last page number.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the last page number</dd></dl>
</li>
</ul>
<a name="getNumPages()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getNumPages</h4>
<pre>public java.lang.Integer getNumPages()</pre>
<div class="block">Get number of pages.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>number of pages</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/BoxPreview.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/box/boxjavalibv2/dao/BoxObjectFallBackTest.html" title="class in com.box.boxjavalibv2.dao"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../com/box/boxjavalibv2/dao/BoxRealTimeServer.html" title="class in com.box.boxjavalibv2.dao"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/box/boxjavalibv2/dao/BoxPreview.html" target="_top">Frames</a></li>
<li><a href="BoxPreview.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "e606e61b66b139a4edfaf2a69d141405",
"timestamp": "",
"source": "github",
"line_count": 452,
"max_line_length": 862,
"avg_line_length": 39.25,
"alnum_prop": 0.6497378952708416,
"repo_name": "shelsonjava/box-java-sdk-v2",
"id": "1fab05aafc086a255ded1170c1c8390af956f6b9",
"size": "17741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "javadoc/com/box/boxjavalibv2/dao/BoxPreview.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "737981"
},
{
"name": "Shell",
"bytes": "1413"
}
],
"symlink_target": ""
} |
"""
Esercizio 1: ricerca dei percorsi dei file a partire da una cartella
python3 23_03_es1.py <cartella_di_partenza>
"""
import os
import sys
import pathlib
import stat
def insert_dict(dictlink, key, value):
"""
Inserisce un nuovo elemento nel dizionario rispettando il default
"""
if key not in dictlink:
dictlink[key] = list()
dictlink[key].append(value)
def main():
"""
Funzione principale, analizza gli input, calcola gli output, fa tutto lei
"""
if len(sys.argv) < 2:
print("Please provide the directory to analyze")
return
elif len(sys.argv) > 2:
print("Too many arguments, please provide only the directory")
return
elif not pathlib.Path(sys.argv[1]).is_dir():
print("Provide a valid path, please")
return
rootdir = pathlib.Path(sys.argv[1])
allfiles = [str(pathfile) for pathfile in rootdir.glob('**/*')]
dictlinks = dict()
for pathfile in allfiles:
inodenum = os.stat(pathfile, follow_symlinks=True)[stat.ST_INO]
if os.path.islink(pathfile):
insert_dict(dictlinks, inodenum, "s " + pathfile)
else:
insert_dict(dictlinks, inodenum, "h " + pathfile)
for keyval in dictlinks:
for pathval in sorted(dictlinks[keyval]):
print(pathval)
print("##########################")
if __name__ == '__main__':
main()
| {
"content_hash": "bd912e94cf8a374f1e9904da880609cd",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 77,
"avg_line_length": 28.959183673469386,
"alnum_prop": 0.6102889358703312,
"repo_name": "sb00nk/PythonExercises",
"id": "212dd8a58dfb985a587916989bfe2380afe6a785",
"size": "1419",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "23_03_es1.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "19044"
}
],
"symlink_target": ""
} |
export * from './account.component'; | {
"content_hash": "8011a6e816e4f23dcc7858e270dab60a",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 36,
"avg_line_length": 36,
"alnum_prop": 0.7222222222222222,
"repo_name": "aroget/ng2-stripe-frontend",
"id": "16ea742cdf20769ddb6bfa1a2fd677c374e84977",
"size": "36",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/+pages/account/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11122"
},
{
"name": "HTML",
"bytes": "6141"
},
{
"name": "JavaScript",
"bytes": "13640"
},
{
"name": "TypeScript",
"bytes": "29328"
}
],
"symlink_target": ""
} |
<phpunit backupGlobals="true"
backupStaticAttributes="false"
cacheTokens="false"
colors="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
forceCoversAnnotation="false"
mapTestClassNameToCoveredClassName="false"
printerClass="PHPUnit_TextUI_ResultPrinter"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"
timeoutForSmallTests="1"
timeoutForMediumTests="10"
timeoutForLargeTests="60"
strict="false"
verbose="false">
<testsuites>
<testsuite>
<directory>src/Gradwell/SMSAPI/Test</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-html" target="build/coverage/" charset="UTF-8" highlight="false" lowUpperBound="35" highLowerBound="70"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
<filter>
<blacklist>
<directory>vendor/</directory>
</blacklist>
</filter>
</phpunit>
| {
"content_hash": "af84622d4996e7b01e1af5a5293793ff",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 133,
"avg_line_length": 34.37837837837838,
"alnum_prop": 0.6297169811320755,
"repo_name": "punkstar/gradwell_smsapi",
"id": "0bcb9e490756d4c75d5b68ce88edf0751faf0e56",
"size": "1272",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "phpunit.xml",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package regexodus.regex;
/**
* @test
* @summary tests RegExp framework
* @author Mike McCloskey
* @bug 4481568 4482696 4495089 4504687 4527731 4599621 4631553 4619345
* 4630911 4672616 4711773 4727935 4750573 4792284 4803197 4757029 4808962
* 4872664 4803179 4892980 4900747 4945394 4938995 4979006 4994840 4997476
* 5013885 5003322 4988891 5098443 5110268 6173522 4829857 5027748 6376940
* 6358731 6178785 6284152 6231989 6497148 6486934 6233084 6504326 6635133
* 6350801 6676425 6878475 6919132 6931676 6948903 7014645 7039066
*/
import regexodus.between.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.io.*;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* This is a test class created to check the operation of
* the Pattern and Matcher classes.
*/
public class RegExTest {
private static Random generator = new Random();
private static boolean failure = false;
private static int failCount = 0;
/**
* Main to interpret arguments and run several tests.
*
*/
public static void main(String[] args) throws Exception {
// Most of the tests are in a file
processFile("TestCases.txt");
//processFile("PerlCases.txt");
//processFile("BMPTestCases.txt");
//processFile("SupplementaryTestCases.txt");
// These test many randomly generated char patterns
bm();
slice();
// These are hard to put into the file
escapes();
blankInput();
// Substitition tests on randomly generated sequences
globalSubstitute();
stringbufferSubstitute();
substitutionBasher();
// Canonical Equivalence
ceTest();
// Anchors
anchorTest();
// boolean match calls
matchesTest();
lookingAtTest();
// Pattern API
patternMatchesTest();
// Misc
lookbehindTest();
nullArgumentTest();
backRefTest();
groupCaptureTest();
caretTest();
charClassTest();
emptyPatternTest();
findIntTest();
group0Test();
longPatternTest();
octalTest();
ampersandTest();
negationTest();
splitTest();
appendTest();
caseFoldingTest();
commentsTest();
unixLinesTest();
replaceFirstTest();
gTest();
zTest();
serializeTest();
reluctantRepetitionTest();
multilineDollarTest();
dollarAtEndTest();
caretBetweenTerminatorsTest();
//javaCharClassTest();
nonCaptureRepetitionTest();
notCapturedGroupCurlyMatchTest();
escapedSegmentTest();
literalPatternTest();
literalReplacementTest();
regionTest();
toStringTest();
negatedCharClassTest();
findFromTest();
//boundsTest();
unicodeWordBoundsTest();
caretAtEndTest();
wordSearchTest();
//hitEndTest();
toMatchResultTest();
//surrogatesInClassTest();
namedGroupCaptureTest();
//nonBmpClassComplementTest();
unicodePropertiesTest();
//unicodeHexNotationTest();
unicodeClassesTest();
if (failure)
throw new RuntimeException("Failure in the RE handling.");
else
System.err.println("OKAY: All tests passed.");
}
// Utility functions
private static String getRandomAlphaString(int length) {
StringBuffer buf = new StringBuffer(length);
for (int i=0; i<length; i++) {
char randChar = (char)(97 + generator.nextInt(26));
buf.append(randChar);
}
return buf.toString();
}
private static void check(Matcher m, String expected) {
m.find();
if (!m.group().equals(expected))
failCount++;
}
private static void check(Matcher m, String result, boolean expected) {
m.find();
if (m.group().equals(result) != expected)
failCount++;
}
private static void check(Pattern p, String s, boolean expected) {
if (p.matcher(s).find() != expected)
failCount++;
}
private static void check(String p, String s, boolean expected) {
Matcher matcher = Pattern.compile(p).matcher(s);
if (matcher.find() != expected)
failCount++;
}
private static void check(String p, char c, boolean expected) {
String propertyPattern = expected ? "\\p" + p : "\\P" + p;
Pattern pattern = Pattern.compile(propertyPattern);
char[] ca = new char[1]; ca[0] = c;
Matcher matcher = pattern.matcher(new String(ca));
if (!matcher.find())
failCount++;
}
private static void check(String p, int codePoint, boolean expected) {
String propertyPattern = expected ? "\\p" + p : "\\P" + p;
Pattern pattern = Pattern.compile(propertyPattern);
char[] ca = Character.toChars(codePoint);
Matcher matcher = pattern.matcher(new String(ca));
if (!matcher.find())
failCount++;
}
private static void check(String p, int flag, String input, String s,
boolean expected)
{
Pattern pattern = Pattern.compile(p, flag);
Matcher matcher = pattern.matcher(input);
if (expected)
check(matcher, s, expected);
else
check(pattern, input, false);
}
private static void report(String testName) {
int spacesToAdd = 30 - testName.length();
StringBuffer paddedNameBuffer = new StringBuffer(testName);
for (int i=0; i<spacesToAdd; i++)
paddedNameBuffer.append(" ");
String paddedName = paddedNameBuffer.toString();
System.err.println(paddedName + ": " +
(failCount==0 ? "Passed":"Failed("+failCount+")"));
if (failCount > 0)
failure = true;
failCount = 0;
}
/**
* Converts ASCII alphabet characters [A-Za-z] in the given 's' to
* supplementary characters. This method does NOT fully take care
* of the regex syntax.
*/
private static String toSupplementaries(String s) {
int length = s.length();
StringBuffer sb = new StringBuffer(length * 2);
for (int i = 0; i < length; ) {
char c = s.charAt(i++);
if (c == '\\') {
sb.append(c);
if (i < length) {
c = s.charAt(i++);
sb.append(c);
if (c == 'u') {
// assume no syntax error
sb.append(s.charAt(i++));
sb.append(s.charAt(i++));
sb.append(s.charAt(i++));
sb.append(s.charAt(i++));
}
}
//} else if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
// sb.append('\ud800').append((char)('\udc00'+c));
} else {
sb.append(c);
}
}
return sb.toString();
}
// Regular expression tests
// This is for bug 6178785
// Test if an expected NPE gets thrown when passing in a null argument
private static boolean check(Runnable test) {
try {
test.run();
failCount++;
return false;
} catch (NullPointerException npe) {
return true;
}
}
private static void nullArgumentTest() {
check(new Runnable() { public void run() { Pattern.compile(null); }});
check(new Runnable() { public void run() { Pattern.matches(null, null); }});
check(new Runnable() { public void run() { Pattern.matches("xyz", null);}});
check(new Runnable() { public void run() { Pattern.quote(null);}});
check(new Runnable() { public void run() { Pattern.compile("xyz").split(null);}});
check(new Runnable() { public void run() { Pattern.compile("xyz").matcher(null);}});
final Matcher m = Pattern.compile("xyz").matcher("xyz");
m.matches();
check(new Runnable() { public void run() { m.appendTail(null);}});
check(new Runnable() { public void run() { m.replaceAll(null);}});
check(new Runnable() { public void run() { m.replaceFirst(null);}});
check(new Runnable() { public void run() { m.appendReplacement(null, null);}});
check(new Runnable() { public void run() { m.reset(null);}});
check(new Runnable() { public void run() { Matcher.quoteReplacement(null);}});
//check(new Runnable() { public void run() { m.usePattern(null);}});
report("Null Argument");
}
// This is for bug6635133
// Test if surrogate pair in Unicode escapes can be handled correctly.
private static void surrogatesInClassTest() throws Exception {
Pattern pattern = Pattern.compile("[\\ud834\\udd21-\\ud834\\udd24]");
Matcher matcher = pattern.matcher("\ud834\udd22");
if (!matcher.find())
failCount++;
}
// This is for bug 4988891
// Test toMatchResult to see that it is a copy of the Matcher
// that is not affected by subsequent operations on the original
private static void toMatchResultTest() throws Exception {
Pattern pattern = Pattern.compile("squid");
Matcher matcher = pattern.matcher(
"agiantsquidofdestinyasmallsquidoffate");
matcher.find();
int matcherStart1 = matcher.start();
MatchResult mr = matcher.toMatchResult();
if (mr == matcher)
failCount++;
int resultStart1 = mr.start();
if (matcherStart1 != resultStart1)
failCount++;
matcher.find();
int matcherStart2 = matcher.start();
int resultStart2 = mr.start();
if (matcherStart2 == resultStart2)
failCount++;
if (resultStart1 != resultStart2)
failCount++;
MatchResult mr2 = matcher.toMatchResult();
if (mr == mr2)
failCount++;
if (mr2.start() != matcherStart2)
failCount++;
report("toMatchResult is a copy");
}
// This is for bug 5013885
// Must test a slice to see if it reports hitEnd correctly
private static void hitEndTest() throws Exception {
// Basic test of Slice node
Pattern p = Pattern.compile("^squidattack");
Matcher m = p.matcher("squack");
m.find();
if (m.hitEnd())
failCount++;
m.reset("squid");
m.find();
if (!m.hitEnd())
failCount++;
// Test Slice, SliceA and SliceU nodes
for (int i=0; i<3; i++) {
int flags = 0;
if (i==1) flags = Pattern.CASE_INSENSITIVE;
if (i==2) flags = Pattern.UNICODE_CASE;
p = Pattern.compile("^abc", flags);
m = p.matcher("ad");
m.find();
if (m.hitEnd())
failCount++;
m.reset("ab");
m.find();
if (!m.hitEnd())
failCount++;
}
// Test Boyer-Moore node
p = Pattern.compile("catattack");
m = p.matcher("attack");
m.find();
if (!m.hitEnd())
failCount++;
p = Pattern.compile("catattack");
m = p.matcher("attackattackattackcatatta");
m.find();
if (!m.hitEnd())
failCount++;
report("hitEnd from a Slice");
}
// This is for bug 4997476
// It is weird code submitted by customer demonstrating a regression
private static void wordSearchTest() throws Exception {
String testString = new String("word1 word2 word3");
Pattern p = Pattern.compile("\\b");
Matcher m = p.matcher(testString);
int position = 0;
int start = 0;
while (m.find(position)) {
start = m.start();
if (start == testString.length())
break;
if (m.find(start+1)) {
position = m.start();
} else {
position = testString.length();
}
if (testString.substring(start, position).equals(" "))
continue;
if (!testString.substring(start, position-1).startsWith("word"))
failCount++;
}
report("Customer word search");
}
// This is for bug 4994840
private static void caretAtEndTest() throws Exception {
// Problem only occurs with multiline patterns
// containing a beginning-of-line caret "^" followed
// by an expression that also matches the empty string.
Pattern pattern = Pattern.compile("^x?", Pattern.MULTILINE);
Matcher matcher = pattern.matcher("\r");
matcher.find();
matcher.find();
report("Caret at end");
}
// This test is for 4979006
// Check to see if word boundary construct properly handles unicode
// non spacing marks
private static void unicodeWordBoundsTest() throws Exception {
String spaces = " ";
String wordChar = "a";
String nsm = "\u030a";
assert (Character.getType('\u030a') == Character.NON_SPACING_MARK);
Pattern pattern = Pattern.compile("\\b");
Matcher matcher = pattern.matcher("");
// S=other B=word character N=non spacing mark .=word boundary
// SS.BB.SS
String input = spaces + wordChar + wordChar + spaces;
twoFindIndexes(input, matcher, 2, 4);
// SS.BBN.SS
input = spaces + wordChar +wordChar + nsm + spaces;
twoFindIndexes(input, matcher, 2, 5);
// SS.BN.SS
input = spaces + wordChar + nsm + spaces;
twoFindIndexes(input, matcher, 2, 4);
// SS.BNN.SS
input = spaces + wordChar + nsm + nsm + spaces;
twoFindIndexes(input, matcher, 2, 5);
// SSN.BB.SS
input = spaces + nsm + wordChar + wordChar + spaces;
twoFindIndexes(input, matcher, 3, 5);
// SS.BNB.SS
input = spaces + wordChar + nsm + wordChar + spaces;
twoFindIndexes(input, matcher, 2, 5);
// SSNNSS
input = spaces + nsm + nsm + spaces;
matcher.reset(input);
if (matcher.find())
failCount++;
// SSN.BBN.SS
input = spaces + nsm + wordChar + wordChar + nsm + spaces;
twoFindIndexes(input, matcher, 3, 6);
report("Unicode word boundary");
}
private static void twoFindIndexes(String input, Matcher matcher, int a,
int b) throws Exception
{
matcher.reset(input);
matcher.find();
if (matcher.start() != a)
failCount++;
matcher.find();
if (matcher.start() != b)
failCount++;
}
// This test is for 6284152
static void check(String regex, String input, String[] expected) {
List<String> result = new ArrayList<String>();
try
{
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
while (m.find()) {
result.add(m.group());
}
if (!Arrays.asList(expected).equals(result))
failCount++;
}catch (Exception e) {
failCount++;
}
}
private static void lookbehindTest() throws Exception {
//Positive
check("(?<=%.{0,5})foo\\d",
"%foo1\n%bar foo2\n%bar foo3\n%blahblah foo4\nfoo5",
new String[]{"foo1", "foo2", "foo3"});
//boundary at end of the lookbehind sub-regex should work consistently
//with the boundary just after the lookbehind sub-regex
check("(?<=.*\\b)foo", "abcd foo", new String[]{"foo"});
check("(?<=.*)\\bfoo", "abcd foo", new String[]{"foo"});
check("(?<!abc )\\bfoo", "abc foo", new String[0]);
check("(?<!abc \\b)foo", "abc foo", new String[0]);
//Negative
check("(?<!%.{0,5})foo\\d",
"%foo1\n%bar foo2\n%bar foo3\n%blahblah foo4\nfoo5",
new String[] {"foo4", "foo5"});
//Positive greedy
check("(?<=%b{1,4})foo", "%bbbbfoo", new String[] {"foo"});
//Positive reluctant
check("(?<=%b{1,4}?)foo", "%bbbbfoo", new String[] {"foo"});
//supplementary
check("(?<=%b{1,4})fo\ud800\udc00o", "%bbbbfo\ud800\udc00o",
new String[] {"fo\ud800\udc00o"});
check("(?<=%b{1,4}?)fo\ud800\udc00o", "%bbbbfo\ud800\udc00o",
new String[] {"fo\ud800\udc00o"});
check("(?<!%b{1,4})fo\ud800\udc00o", "%afo\ud800\udc00o",
new String[] {"fo\ud800\udc00o"});
check("(?<!%b{1,4}?)fo\ud800\udc00o", "%afo\ud800\udc00o",
new String[] {"fo\ud800\udc00o"});
report("Lookbehind");
}
// This test is for 4938995
// Check to see if weak region boundaries are transparent to
// lookahead and lookbehind constructs
private static void boundsTest() throws Exception {
String fullMessage = "catdogcat";
Pattern pattern = Pattern.compile("(?<=cat)dog(?=cat)");
Matcher matcher = pattern.matcher("catdogca");
matcher.useTransparentBounds(true);
if (matcher.find())
failCount++;
matcher.reset("atdogcat");
if (matcher.find())
failCount++;
matcher.reset(fullMessage);
if (!matcher.find())
failCount++;
matcher.reset(fullMessage);
matcher.region(0,9);
if (!matcher.find())
failCount++;
matcher.reset(fullMessage);
matcher.region(0,6);
if (!matcher.find())
failCount++;
matcher.reset(fullMessage);
matcher.region(3,6);
if (!matcher.find())
failCount++;
matcher.useTransparentBounds(false);
if (matcher.find())
failCount++;
// Negative lookahead/lookbehind
pattern = Pattern.compile("(?<!cat)dog(?!cat)");
matcher = pattern.matcher("dogcat");
matcher.useTransparentBounds(true);
matcher.region(0,3);
if (matcher.find())
failCount++;
matcher.reset("catdog");
matcher.region(3,6);
if (matcher.find())
failCount++;
matcher.useTransparentBounds(false);
matcher.reset("dogcat");
matcher.region(0,3);
if (!matcher.find())
failCount++;
matcher.reset("catdog");
matcher.region(3,6);
if (!matcher.find())
failCount++;
report("Region bounds transparency");
}
// This test is for 4945394
private static void findFromTest() throws Exception {
String message = "This is 40 $0 message.";
Pattern pat = Pattern.compile("\\$0");
Matcher match = pat.matcher(message);
if (!match.find())
failCount++;
if (match.find())
failCount++;
if (match.find())
failCount++;
report("Check for alternating find");
}
// This test is for 4872664 and 4892980
private static void negatedCharClassTest() throws Exception {
Pattern pattern = Pattern.compile("[^>]");
Matcher matcher = pattern.matcher("\u203A");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("[^fr]");
matcher = pattern.matcher("a");
if (!matcher.find())
failCount++;
matcher.reset("\u203A");
if (!matcher.find())
failCount++;
String s = "for";
String result[] = s.split("[^fr]");
if (!result[0].equals("f"))
failCount++;
if (!result[1].equals("r"))
failCount++;
s = "f\u203Ar";
result = s.split("[^fr]");
if (!result[0].equals("f"))
failCount++;
if (!result[1].equals("r"))
failCount++;
// Test adding to bits, subtracting a node, then adding to bits again
pattern = Pattern.compile("[^f\u203Ar]");
matcher = pattern.matcher("a");
if (!matcher.find())
failCount++;
matcher.reset("f");
if (matcher.find())
failCount++;
matcher.reset("\u203A");
if (matcher.find())
failCount++;
matcher.reset("r");
if (matcher.find())
failCount++;
matcher.reset("\u203B");
if (!matcher.find())
failCount++;
// Test subtracting a node, adding to bits, subtracting again
pattern = Pattern.compile("[^\u203Ar\u203B]");
matcher = pattern.matcher("a");
if (!matcher.find())
failCount++;
matcher.reset("\u203A");
if (matcher.find())
failCount++;
matcher.reset("r");
if (matcher.find())
failCount++;
matcher.reset("\u203B");
if (matcher.find())
failCount++;
matcher.reset("\u203C");
if (!matcher.find())
failCount++;
report("Negated Character Class");
}
// This test is for 4628291
private static void toStringTest() throws Exception {
Pattern pattern = Pattern.compile("b+");
if (pattern.toString() != "b+")
failCount++;
Matcher matcher = pattern.matcher("aaabbbccc");
String matcherString = matcher.toString(); // unspecified
matcher.find();
matcherString = matcher.toString(); // unspecified
matcher.region(0,3);
matcherString = matcher.toString(); // unspecified
matcher.reset();
matcherString = matcher.toString(); // unspecified
report("toString");
}
// This test is for 4808962
private static void literalPatternTest() throws Exception {
int flags = Pattern.LITERAL;
Pattern pattern = Pattern.compile("abc\\t$^", flags);
check(pattern, "abc\\t$^", true);
pattern = Pattern.compile(Pattern.quote("abc\\t$^"));
check(pattern, "abc\\t$^", true);
pattern = Pattern.compile("\\Qa^$bcabc\\E", flags);
check(pattern, "\\Qa^$bcabc\\E", true);
check(pattern, "a^$bcabc", false);
pattern = Pattern.compile("\\\\Q\\\\E");
check(pattern, "\\Q\\E", true);
pattern = Pattern.compile("\\Qabc\\Eefg\\\\Q\\\\Ehij");
check(pattern, "abcefg\\Q\\Ehij", true);
pattern = Pattern.compile("\\\\\\Q\\\\E");
check(pattern, "\\\\\\\\", true);
pattern = Pattern.compile(Pattern.quote("\\Qa^$bcabc\\E"));
check(pattern, "\\Qa^$bcabc\\E", true);
check(pattern, "a^$bcabc", false);
pattern = Pattern.compile(Pattern.quote("\\Qabc\\Edef"));
check(pattern, "\\Qabc\\Edef", true);
check(pattern, "abcdef", false);
pattern = Pattern.compile(Pattern.quote("abc\\Edef"));
check(pattern, "abc\\Edef", true);
check(pattern, "abcdef", false);
pattern = Pattern.compile(Pattern.quote("\\E"));
check(pattern, "\\E", true);
pattern = Pattern.compile("((((abc.+?:)", flags);
check(pattern, "((((abc.+?:)", true);
flags |= Pattern.MULTILINE;
pattern = Pattern.compile("^cat$", flags);
check(pattern, "abc^cat$def", true);
check(pattern, "cat", false);
flags |= Pattern.CASE_INSENSITIVE;
pattern = Pattern.compile("abcdef", flags);
check(pattern, "ABCDEF", true);
check(pattern, "AbCdEf", true);
flags |= Pattern.DOTALL;
pattern = Pattern.compile("a...b", flags);
check(pattern, "A...b", true);
check(pattern, "Axxxb", false);
flags |= Pattern.CANON_EQ;
Pattern p = Pattern.compile("testa\u030a", flags);
check(pattern, "testa\u030a", false);
check(pattern, "test\u00e5", false);
// Supplementary character test
flags = Pattern.LITERAL;
pattern = Pattern.compile(toSupplementaries("abc\\t$^"), flags);
check(pattern, toSupplementaries("abc\\t$^"), true);
pattern = Pattern.compile(Pattern.quote(toSupplementaries("abc\\t$^")));
check(pattern, toSupplementaries("abc\\t$^"), true);
pattern = Pattern.compile(toSupplementaries("\\Qa^$bcabc\\E"), flags);
check(pattern, toSupplementaries("\\Qa^$bcabc\\E"), true);
check(pattern, toSupplementaries("a^$bcabc"), false);
pattern = Pattern.compile(Pattern.quote(toSupplementaries("\\Qa^$bcabc\\E")));
check(pattern, toSupplementaries("\\Qa^$bcabc\\E"), true);
check(pattern, toSupplementaries("a^$bcabc"), false);
pattern = Pattern.compile(Pattern.quote(toSupplementaries("\\Qabc\\Edef")));
check(pattern, toSupplementaries("\\Qabc\\Edef"), true);
check(pattern, toSupplementaries("abcdef"), false);
pattern = Pattern.compile(Pattern.quote(toSupplementaries("abc\\Edef")));
check(pattern, toSupplementaries("abc\\Edef"), true);
check(pattern, toSupplementaries("abcdef"), false);
pattern = Pattern.compile(toSupplementaries("((((abc.+?:)"), flags);
check(pattern, toSupplementaries("((((abc.+?:)"), true);
flags |= Pattern.MULTILINE;
pattern = Pattern.compile(toSupplementaries("^cat$"), flags);
check(pattern, toSupplementaries("abc^cat$def"), true);
check(pattern, toSupplementaries("cat"), false);
flags |= Pattern.DOTALL;
// note: this is case-sensitive.
pattern = Pattern.compile(toSupplementaries("a...b"), flags);
check(pattern, toSupplementaries("a...b"), true);
check(pattern, toSupplementaries("axxxb"), false);
flags |= Pattern.CANON_EQ;
String t = toSupplementaries("test");
p = Pattern.compile(t + "a\u030a", flags);
check(pattern, t + "a\u030a", false);
check(pattern, t + "\u00e5", false);
report("Literal pattern");
}
// This test is for 4803179
// This test is also for 4808962, replacement parts
private static void literalReplacementTest() throws Exception {
int flags = Pattern.LITERAL;
Pattern pattern = Pattern.compile("abc", flags);
Matcher matcher = pattern.matcher("zzzabczzz");
String replaceTest = "$0";
String result = matcher.replaceAll(replaceTest);
if (!result.equals("zzzabczzz"))
failCount++;
matcher.reset();
String literalReplacement = matcher.quoteReplacement(replaceTest);
result = matcher.replaceAll(literalReplacement);
if (!result.equals("zzz$0zzz"))
failCount++;
matcher.reset();
replaceTest = "\\t$\\$";
literalReplacement = matcher.quoteReplacement(replaceTest);
result = matcher.replaceAll(literalReplacement);
if (!result.equals("zzz\\t$\\$zzz"))
failCount++;
// Supplementary character test
pattern = Pattern.compile(toSupplementaries("abc"), flags);
matcher = pattern.matcher(toSupplementaries("zzzabczzz"));
replaceTest = "$0";
result = matcher.replaceAll(replaceTest);
if (!result.equals(toSupplementaries("zzzabczzz")))
failCount++;
matcher.reset();
literalReplacement = matcher.quoteReplacement(replaceTest);
result = matcher.replaceAll(literalReplacement);
if (!result.equals(toSupplementaries("zzz$0zzz")))
failCount++;
matcher.reset();
replaceTest = "\\t$\\$";
literalReplacement = matcher.quoteReplacement(replaceTest);
result = matcher.replaceAll(literalReplacement);
if (!result.equals(toSupplementaries("zzz\\t$\\$zzz")))
failCount++;
report("Literal replacement");
}
// This test is for 4757029
private static void regionTest() throws Exception {
Pattern pattern = Pattern.compile("abc");
Matcher matcher = pattern.matcher("abcdefabc");
matcher.region(0,9);
if (!matcher.find())
failCount++;
if (!matcher.find())
failCount++;
matcher.region(0,3);
if (!matcher.find())
failCount++;
matcher.region(3,6);
if (matcher.find())
failCount++;
matcher.region(0,2);
if (matcher.find())
failCount++;
expectRegionFail(matcher, 1, -1);
expectRegionFail(matcher, -1, -1);
expectRegionFail(matcher, -1, 1);
expectRegionFail(matcher, 5, 3);
expectRegionFail(matcher, 5, 12);
expectRegionFail(matcher, 12, 12);
pattern = Pattern.compile("^abc$");
matcher = pattern.matcher("zzzabczzz");
matcher.region(0,9);
if (matcher.find())
failCount++;
matcher.region(3,6);
if (!matcher.find())
failCount++;
matcher.region(3,6);
/*
matcher.useAnchoringBounds(false);
if (matcher.find())
failCount++;
*/
// Supplementary character test
/*
pattern = Pattern.compile(toSupplementaries("abc"));
matcher = pattern.matcher(toSupplementaries("abcdefabc"));
matcher.region(0,9*2);
if (!matcher.find())
failCount++;
if (!matcher.find())
failCount++;
matcher.region(0,3*2);
if (!matcher.find())
failCount++;
matcher.region(1,3*2);
if (matcher.find())
failCount++;
matcher.region(3*2,6*2);
if (matcher.find())
failCount++;
matcher.region(0,2*2);
if (matcher.find())
failCount++;
matcher.region(0,2*2+1);
if (matcher.find())
failCount++;
expectRegionFail(matcher, 1*2, -1);
expectRegionFail(matcher, -1, -1);
expectRegionFail(matcher, -1, 1*2);
expectRegionFail(matcher, 5*2, 3*2);
expectRegionFail(matcher, 5*2, 12*2);
expectRegionFail(matcher, 12*2, 12*2);
pattern = Pattern.compile(toSupplementaries("^abc$"));
matcher = pattern.matcher(toSupplementaries("zzzabczzz"));
matcher.region(0,9*2);
if (matcher.find())
failCount++;
matcher.region(3*2,6*2);
if (!matcher.find())
failCount++;
matcher.region(3*2+1,6*2);
if (matcher.find())
failCount++;
matcher.region(3*2,6*2-1);
if (matcher.find())
failCount++;
matcher.region(3*2,6*2);
matcher.useAnchoringBounds(false);
if (matcher.find())
failCount++;
*/
report("Regions");
}
private static void expectRegionFail(Matcher matcher, int index1,
int index2)
{
try {
matcher.region(index1, index2);
failCount++;
} catch (IndexOutOfBoundsException ioobe) {
// Correct result
} catch (IllegalStateException ise) {
// Correct result
}
}
// This test is for 4803197
private static void escapedSegmentTest() throws Exception {
Pattern pattern = Pattern.compile("\\Qdir1\\dir2\\E");
check(pattern, "dir1\\dir2", true);
pattern = Pattern.compile("\\Qdir1\\dir2\\\\E");
check(pattern, "dir1\\dir2\\", true);
pattern = Pattern.compile("(\\Qdir1\\dir2\\\\E)");
check(pattern, "dir1\\dir2\\", true);
// Supplementary character test
pattern = Pattern.compile(toSupplementaries("\\Qdir1\\dir2\\E"));
check(pattern, toSupplementaries("dir1\\dir2"), true);
pattern = Pattern.compile(toSupplementaries("\\Qdir1\\dir2")+"\\\\E");
check(pattern, toSupplementaries("dir1\\dir2\\"), true);
pattern = Pattern.compile(toSupplementaries("(\\Qdir1\\dir2")+"\\\\E)");
check(pattern, toSupplementaries("dir1\\dir2\\"), true);
report("Escaped segment");
}
// This test is for 4792284
private static void nonCaptureRepetitionTest() throws Exception {
String input = "abcdefgh;";
String[] patterns = new String[] {
"(?:\\w{4}?)+;", // lazy repetition - OK
"(?:\\w{4})+;",
"(?:\\w{8})*;",
"(?:\\w{2}){2,4};",
"(?:\\w{4}){2,};", // only matches the
".*?(?:\\w{5})+;", // specified minimum
".*?(?:\\w{9})*;", // number of reps - OK
"(?:\\w{4})+?;", // lazy repetition - OK
//"(?:\\w{4})++;", // possessive repetition - NOT OK
"(?:\\w{2,}?)+;", // non-deterministic - OK
"(\\w{4})+;", // capturing group - OK
};
for (int i = 0; i < patterns.length; i++) {
// Check find()
check(patterns[i], 0, input, input, true);
// Check matches()
Pattern p = Pattern.compile(patterns[i]);
Matcher m = p.matcher(input);
if (m.matches()) {
if (!m.group(0).equals(input))
failCount++;
} else {
failCount++;
}
}
report("Non capturing repetition");
}
// This test is for 6358731
private static void notCapturedGroupCurlyMatchTest() throws Exception {
Pattern pattern = Pattern.compile("(abc)+|(abcd)+");
Matcher matcher = pattern.matcher("abcd");
if (!matcher.matches() ||
matcher.group(1) != null ||
!matcher.group(2).equals("abcd")) {
failCount++;
}
report("Not captured GroupCurly");
}
// This test is for 4706545
private static void javaCharClassTest() throws Exception {
for (int i=0; i<1000; i++) {
char c = (char)generator.nextInt();
check("{javaLowerCase}", c, Character.isLowerCase(c));
check("{javaUpperCase}", c, Character.isUpperCase(c));
check("{javaUpperCase}+", c, Character.isUpperCase(c));
check("{javaTitleCase}", c, Character.isTitleCase(c));
check("{javaDigit}", c, Character.isDigit(c));
check("{javaDefined}", c, Character.isDefined(c));
check("{javaLetter}", c, Character.isLetter(c));
check("{javaLetterOrDigit}", c, Character.isLetterOrDigit(c));
check("{javaJavaIdentifierStart}", c,
Character.isJavaIdentifierStart(c));
check("{javaJavaIdentifierPart}", c,
Character.isJavaIdentifierPart(c));
check("{javaUnicodeIdentifierStart}", c,
Character.isUnicodeIdentifierStart(c));
check("{javaUnicodeIdentifierPart}", c,
Character.isUnicodeIdentifierPart(c));
check("{javaIdentifierIgnorable}", c,
Character.isIdentifierIgnorable(c));
check("{javaSpaceChar}", c, Character.isSpaceChar(c));
check("{javaWhitespace}", c, Character.isWhitespace(c));
check("{javaISOControl}", c, Character.isISOControl(c));
check("{javaMirrored}", c, Character.isMirrored(c));
}
// Supplementary character test
for (int i=0; i<1000; i++) {
int c = generator.nextInt(Character.MAX_CODE_POINT
- Character.MIN_SUPPLEMENTARY_CODE_POINT)
+ Character.MIN_SUPPLEMENTARY_CODE_POINT;
check("{javaLowerCase}", c, Character.isLowerCase(c));
check("{javaUpperCase}", c, Character.isUpperCase(c));
check("{javaUpperCase}+", c, Character.isUpperCase(c));
check("{javaTitleCase}", c, Character.isTitleCase(c));
check("{javaDigit}", c, Character.isDigit(c));
check("{javaDefined}", c, Character.isDefined(c));
check("{javaLetter}", c, Character.isLetter(c));
check("{javaLetterOrDigit}", c, Character.isLetterOrDigit(c));
check("{javaJavaIdentifierStart}", c,
Character.isJavaIdentifierStart(c));
check("{javaJavaIdentifierPart}", c,
Character.isJavaIdentifierPart(c));
check("{javaUnicodeIdentifierStart}", c,
Character.isUnicodeIdentifierStart(c));
check("{javaUnicodeIdentifierPart}", c,
Character.isUnicodeIdentifierPart(c));
check("{javaIdentifierIgnorable}", c,
Character.isIdentifierIgnorable(c));
check("{javaSpaceChar}", c, Character.isSpaceChar(c));
check("{javaWhitespace}", c, Character.isWhitespace(c));
check("{javaISOControl}", c, Character.isISOControl(c));
check("{javaMirrored}", c, Character.isMirrored(c));
}
report("Java character classes");
}
// This test is for 4523620
/*
private static void numOccurrencesTest() throws Exception {
Pattern pattern = Pattern.compile("aaa");
if (pattern.numOccurrences("aaaaaa", false) != 2)
failCount++;
if (pattern.numOccurrences("aaaaaa", true) != 4)
failCount++;
pattern = Pattern.compile("^");
if (pattern.numOccurrences("aaaaaa", false) != 1)
failCount++;
if (pattern.numOccurrences("aaaaaa", true) != 1)
failCount++;
report("Number of Occurrences");
}
*/
// This test is for 4776374
private static void caretBetweenTerminatorsTest() throws Exception {
int flags1 = Pattern.DOTALL;
int flags2 = Pattern.DOTALL | Pattern.UNIX_LINES;
int flags3 = Pattern.DOTALL | Pattern.UNIX_LINES | Pattern.MULTILINE;
int flags4 = Pattern.DOTALL | Pattern.MULTILINE;
check("^....", flags1, "test\ntest", "test", true);
check(".....^", flags1, "test\ntest", "test", false);
check(".....^", flags1, "test\n", "test", false);
check("....^", flags1, "test\r\n", "test", false);
check("^....", flags2, "test\ntest", "test", true);
check("....^", flags2, "test\ntest", "test", false);
check(".....^", flags2, "test\n", "test", false);
check("....^", flags2, "test\r\n", "test", false);
check("^....", flags3, "test\ntest", "test", true);
check(".....^", flags3, "test\ntest", "test\n", true);
check(".....^", flags3, "test\u0085test", "test\u0085", false);
check(".....^", flags3, "test\n", "test", false);
check(".....^", flags3, "test\r\n", "test", false);
check("......^", flags3, "test\r\ntest", "test\r\n", true);
check("^....", flags4, "test\ntest", "test", true);
check(".....^", flags3, "test\ntest", "test\n", true);
check(".....^", flags4, "test\u0085test", "test\u0085", true);
check(".....^", flags4, "test\n", "test\n", false);
check(".....^", flags4, "test\r\n", "test\r", false);
// Supplementary character test
String t = toSupplementaries("test");
check("^....", flags1, t+"\n"+t, t, true);
check(".....^", flags1, t+"\n"+t, t, false);
check(".....^", flags1, t+"\n", t, false);
check("....^", flags1, t+"\r\n", t, false);
check("^....", flags2, t+"\n"+t, t, true);
check("....^", flags2, t+"\n"+t, t, false);
check(".....^", flags2, t+"\n", t, false);
check("....^", flags2, t+"\r\n", t, false);
check("^....", flags3, t+"\n"+t, t, true);
check(".....^", flags3, t+"\n"+t, t+"\n", true);
check(".....^", flags3, t+"\u0085"+t, t+"\u0085", false);
check(".....^", flags3, t+"\n", t, false);
check(".....^", flags3, t+"\r\n", t, false);
check("......^", flags3, t+"\r\n"+t, t+"\r\n", true);
check("^....", flags4, t+"\n"+t, t, true);
check(".....^", flags3, t+"\n"+t, t+"\n", true);
check(".....^", flags4, t+"\u0085"+t, t+"\u0085", true);
check(".....^", flags4, t+"\n", t+"\n", false);
check(".....^", flags4, t+"\r\n", t+"\r", false);
report("Caret between terminators");
}
// This test is for 4727935
private static void dollarAtEndTest() throws Exception {
int flags1 = Pattern.DOTALL;
int flags2 = Pattern.DOTALL | Pattern.UNIX_LINES;
int flags3 = Pattern.DOTALL | Pattern.MULTILINE;
check("....$", flags1, "test\n", "test", true);
check("....$", flags1, "test\r\n", "test", true);
check(".....$", flags1, "test\n", "test\n", true);
check(".....$", flags1, "test\u0085", "test\u0085", true);
check("....$", flags1, "test\u0085", "test", true);
check("....$", flags2, "test\n", "test", true);
check(".....$", flags2, "test\n", "test\n", true);
check(".....$", flags2, "test\u0085", "test\u0085", true);
check("....$", flags2, "test\u0085", "est\u0085", true);
check("....$.blah", flags3, "test\nblah", "test\nblah", true);
check(".....$.blah", flags3, "test\n\nblah", "test\n\nblah", true);
check("....$blah", flags3, "test\nblah", "!!!!", false);
check(".....$blah", flags3, "test\nblah", "!!!!", false);
// Supplementary character test
String t = toSupplementaries("test");
String b = toSupplementaries("blah");
check("....$", flags1, t+"\n", t, true);
check("....$", flags1, t+"\r\n", t, true);
check(".....$", flags1, t+"\n", t+"\n", true);
check(".....$", flags1, t+"\u0085", t+"\u0085", true);
check("....$", flags1, t+"\u0085", t, true);
check("....$", flags2, t+"\n", t, true);
check(".....$", flags2, t+"\n", t+"\n", true);
check(".....$", flags2, t+"\u0085", t+"\u0085", true);
check("....$", flags2, t+"\u0085", toSupplementaries("est\u0085"), true);
check("....$."+b, flags3, t+"\n"+b, t+"\n"+b, true);
check(".....$."+b, flags3, t+"\n\n"+b, t+"\n\n"+b, true);
check("....$"+b, flags3, t+"\n"+b, "!!!!", false);
check(".....$"+b, flags3, t+"\n"+b, "!!!!", false);
report("Dollar at End");
}
// This test is for 4711773
private static void multilineDollarTest() throws Exception {
Pattern findCR = Pattern.compile("$", Pattern.MULTILINE);
Matcher matcher = findCR.matcher("first bit\nsecond bit");
matcher.find();
if (matcher.start(0) != 9)
failCount++;
matcher.find();
if (matcher.start(0) != 20)
failCount++;
// Supplementary character test
matcher = findCR.matcher(toSupplementaries("first bit\n second bit")); // double BMP chars
matcher.find();
if (matcher.start(0) != 9*2)
failCount++;
matcher.find();
if (matcher.start(0) != 20*2)
failCount++;
report("Multiline Dollar");
}
private static void reluctantRepetitionTest() throws Exception {
Pattern p = Pattern.compile("1(\\s\\S+?){1,3}?[\\s,]2");
check(p, "1 word word word 2", true);
check(p, "1 wor wo w 2", true);
check(p, "1 word word 2", true);
check(p, "1 word 2", true);
check(p, "1 wo w w 2", true);
check(p, "1 wo w 2", true);
check(p, "1 wor w 2", true);
p = Pattern.compile("([a-z])+?c");
Matcher m = p.matcher("ababcdefdec");
check(m, "ababc");
// Supplementary character test
p = Pattern.compile(toSupplementaries("([a-z])+?c"));
m = p.matcher(toSupplementaries("ababcdefdec"));
check(m, toSupplementaries("ababc"));
report("Reluctant Repetition");
}
private static void serializeTest() throws Exception {
String patternStr = "(b)";
String matchStr = "b";
Pattern pattern = Pattern.compile(patternStr);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(pattern);
oos.close();
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(baos.toByteArray()));
Pattern serializedPattern = (Pattern)ois.readObject();
ois.close();
Matcher matcher = serializedPattern.matcher(matchStr);
if (!matcher.matches())
failCount++;
if (matcher.groupCount() != 1)
failCount++;
report("Serialization");
}
private static void gTest() {
Pattern pattern = Pattern.compile("\\G\\w");
Matcher matcher = pattern.matcher("abc#x#x");
matcher.find();
matcher.find();
matcher.find();
if (matcher.find())
failCount++;
pattern = Pattern.compile("\\GA*");
matcher = pattern.matcher("1A2AA3");
matcher.find();
if (matcher.find())
failCount++;
pattern = Pattern.compile("\\GA*");
matcher = pattern.matcher("1A2AA3");
if (!matcher.find(1))
failCount++;
matcher.find();
if (matcher.find())
failCount++;
report("\\G");
}
private static void zTest() {
Pattern pattern = Pattern.compile("foo\\Z");
// Positives
check(pattern, "foo\u0085", true);
check(pattern, "foo\u2028", true);
check(pattern, "foo\u2029", true);
check(pattern, "foo\n", true);
check(pattern, "foo\r", true);
check(pattern, "foo\r\n", true);
// Negatives
check(pattern, "fooo", false);
check(pattern, "foo\n\r", false);
pattern = Pattern.compile("foo\\Z", Pattern.UNIX_LINES);
// Positives
check(pattern, "foo", true);
check(pattern, "foo\n", true);
// Negatives
check(pattern, "foo\r", false);
check(pattern, "foo\u0085", false);
check(pattern, "foo\u2028", false);
check(pattern, "foo\u2029", false);
report("\\Z");
}
private static void replaceFirstTest() {
Pattern pattern = Pattern.compile("(ab)(c*)");
Matcher matcher = pattern.matcher("abccczzzabcczzzabccc");
if (!matcher.replaceFirst("test").equals("testzzzabcczzzabccc"))
failCount++;
matcher.reset("zzzabccczzzabcczzzabccczzz");
if (!matcher.replaceFirst("test").equals("zzztestzzzabcczzzabccczzz"))
failCount++;
matcher.reset("zzzabccczzzabcczzzabccczzz");
String result = matcher.replaceFirst("$1");
if (!result.equals("zzzabzzzabcczzzabccczzz"))
failCount++;
matcher.reset("zzzabccczzzabcczzzabccczzz");
result = matcher.replaceFirst("$2");
if (!result.equals("zzzccczzzabcczzzabccczzz"))
failCount++;
pattern = Pattern.compile("a*");
matcher = pattern.matcher("aaaaaaaaaa");
if (!matcher.replaceFirst("test").equals("test"))
failCount++;
pattern = Pattern.compile("a+");
matcher = pattern.matcher("zzzaaaaaaaaaa");
if (!matcher.replaceFirst("test").equals("zzztest"))
failCount++;
// Supplementary character test
pattern = Pattern.compile(toSupplementaries("(ab)(c*)"));
matcher = pattern.matcher(toSupplementaries("abccczzzabcczzzabccc"));
if (!matcher.replaceFirst(toSupplementaries("test"))
.equals(toSupplementaries("testzzzabcczzzabccc")))
failCount++;
matcher.reset(toSupplementaries("zzzabccczzzabcczzzabccczzz"));
if (!matcher.replaceFirst(toSupplementaries("test")).
equals(toSupplementaries("zzztestzzzabcczzzabccczzz")))
failCount++;
matcher.reset(toSupplementaries("zzzabccczzzabcczzzabccczzz"));
result = matcher.replaceFirst("$1");
if (!result.equals(toSupplementaries("zzzabzzzabcczzzabccczzz")))
failCount++;
matcher.reset(toSupplementaries("zzzabccczzzabcczzzabccczzz"));
result = matcher.replaceFirst("$2");
if (!result.equals(toSupplementaries("zzzccczzzabcczzzabccczzz")))
failCount++;
pattern = Pattern.compile(toSupplementaries("a*"));
matcher = pattern.matcher(toSupplementaries("aaaaaaaaaa"));
if (!matcher.replaceFirst(toSupplementaries("test")).equals(toSupplementaries("test")))
failCount++;
pattern = Pattern.compile(toSupplementaries("a+"));
matcher = pattern.matcher(toSupplementaries("zzzaaaaaaaaaa"));
if (!matcher.replaceFirst(toSupplementaries("test")).equals(toSupplementaries("zzztest")))
failCount++;
report("Replace First");
}
private static void unixLinesTest() {
Pattern pattern = Pattern.compile(".*");
Matcher matcher = pattern.matcher("aa\u2028blah");
matcher.find();
if (!matcher.group(0).equals("aa"))
failCount++;
pattern = Pattern.compile(".*", Pattern.UNIX_LINES);
matcher = pattern.matcher("aa\u2028blah");
matcher.find();
if (!matcher.group(0).equals("aa\u2028blah"))
failCount++;
pattern = Pattern.compile("[az]$",
Pattern.MULTILINE | Pattern.UNIX_LINES);
matcher = pattern.matcher("aa\u2028zz");
check(matcher, "a\u2028", false);
// Supplementary character test
pattern = Pattern.compile(".*");
matcher = pattern.matcher(toSupplementaries("aa\u2028blah"));
matcher.find();
if (!matcher.group(0).equals(toSupplementaries("aa")))
failCount++;
pattern = Pattern.compile(".*", Pattern.UNIX_LINES);
matcher = pattern.matcher(toSupplementaries("aa\u2028blah"));
matcher.find();
if (!matcher.group(0).equals(toSupplementaries("aa\u2028blah")))
failCount++;
pattern = Pattern.compile(toSupplementaries("[az]$"),
Pattern.MULTILINE | Pattern.UNIX_LINES);
matcher = pattern.matcher(toSupplementaries("aa\u2028zz"));
check(matcher, toSupplementaries("a\u2028"), false);
report("Unix Lines");
}
private static void commentsTest() {
int flags = Pattern.COMMENTS;
Pattern pattern = Pattern.compile("aa \\# aa", flags);
Matcher matcher = pattern.matcher("aa#aa");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("aa # blah", flags);
matcher = pattern.matcher("aa");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("aa blah", flags);
matcher = pattern.matcher("aablah");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("aa # blah blech ", flags);
matcher = pattern.matcher("aa");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("aa # blah\n ", flags);
matcher = pattern.matcher("aa");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("aa # blah\nbc # blech", flags);
matcher = pattern.matcher("aabc");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("aa # blah\nbc# blech", flags);
matcher = pattern.matcher("aabc");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("aa # blah\nbc\\# blech", flags);
matcher = pattern.matcher("aabc#blech");
if (!matcher.matches())
failCount++;
// Supplementary character test
pattern = Pattern.compile(toSupplementaries("aa \\# aa"), flags);
matcher = pattern.matcher(toSupplementaries("aa#aa"));
if (!matcher.matches())
failCount++;
pattern = Pattern.compile(toSupplementaries("aa # blah"), flags);
matcher = pattern.matcher(toSupplementaries("aa"));
if (!matcher.matches())
failCount++;
pattern = Pattern.compile(toSupplementaries("aa blah"), flags);
matcher = pattern.matcher(toSupplementaries("aablah"));
if (!matcher.matches())
failCount++;
pattern = Pattern.compile(toSupplementaries("aa # blah blech "), flags);
matcher = pattern.matcher(toSupplementaries("aa"));
if (!matcher.matches())
failCount++;
pattern = Pattern.compile(toSupplementaries("aa # blah\n "), flags);
matcher = pattern.matcher(toSupplementaries("aa"));
if (!matcher.matches())
failCount++;
pattern = Pattern.compile(toSupplementaries("aa # blah\nbc # blech"), flags);
matcher = pattern.matcher(toSupplementaries("aabc"));
if (!matcher.matches())
failCount++;
pattern = Pattern.compile(toSupplementaries("aa # blah\nbc# blech"), flags);
matcher = pattern.matcher(toSupplementaries("aabc"));
if (!matcher.matches())
failCount++;
pattern = Pattern.compile(toSupplementaries("aa # blah\nbc\\# blech"), flags);
matcher = pattern.matcher(toSupplementaries("aabc#blech"));
if (!matcher.matches())
failCount++;
report("Comments");
}
private static void caseFoldingTest() { // bug 4504687
int flags = Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
Pattern pattern = Pattern.compile("aa", flags);
Matcher matcher = pattern.matcher("ab");
if (matcher.matches())
failCount++;
pattern = Pattern.compile("aA", flags);
matcher = pattern.matcher("ab");
if (matcher.matches())
failCount++;
pattern = Pattern.compile("aa", flags);
matcher = pattern.matcher("aB");
if (matcher.matches())
failCount++;
matcher = pattern.matcher("Ab");
if (matcher.matches())
failCount++;
// ASCII "a"
// Latin-1 Supplement "a" + grave
// Cyrillic "a"
String[] patterns = new String[] {
//single
"a", "\u00e0", "\u0430",
//slice
"ab", "\u00e0\u00e1", "\u0430\u0431",
//class single
"[a]", "[\u00e0]", "[\u0430]",
//class range
"[a-b]", "[\u00e0-\u00e5]", "[\u0430-\u0431]",
//back reference
"(a)\\1", "(\u00e0)\\1", "(\u0430)\\1"
};
String[] texts = new String[] {
"A", "\u00c0", "\u0410",
"AB", "\u00c0\u00c1", "\u0410\u0411",
"A", "\u00c0", "\u0410",
"B", "\u00c2", "\u0411",
"aA", "\u00e0\u00c0", "\u0430\u0410"
};
boolean[] expected = new boolean[] {
true, false, false,
true, false, false,
true, false, false,
true, false, false,
true, false, false
};
flags = Pattern.CASE_INSENSITIVE;
for (int i = 0; i < patterns.length; i++) {
pattern = Pattern.compile(patterns[i], flags);
matcher = pattern.matcher(texts[i]);
if (matcher.matches() != expected[i]) {
System.out.println("<1> Failed at " + i);
failCount++;
}
}
flags = Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
for (int i = 0; i < patterns.length; i++) {
pattern = Pattern.compile(patterns[i], flags);
matcher = pattern.matcher(texts[i]);
if (!matcher.matches()) {
System.out.println("<2> Failed at " + i);
failCount++;
}
}
// flag unicode_case alone should do nothing
flags = Pattern.UNICODE_CASE;
for (int i = 0; i < patterns.length; i++) {
pattern = Pattern.compile(patterns[i], flags);
matcher = pattern.matcher(texts[i]);
if (matcher.matches()) {
System.out.println("<3> Failed at " + i);
failCount++;
}
}
// Special cases: i, I, u+0131 and u+0130
flags = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE;
pattern = Pattern.compile("[h-j]+", flags);
if (!pattern.matcher("\u0131\u0130").matches())
failCount++;
report("Case Folding");
}
private static void appendTest() {
Pattern pattern = Pattern.compile("(ab)(cd)");
Matcher matcher = pattern.matcher("abcd");
String result = matcher.replaceAll("$2$1");
if (!result.equals("cdab"))
failCount++;
String s1 = "Swap all: first = 123, second = 456";
String s2 = "Swap one: first = 123, second = 456";
String r = "$3$2$1";
pattern = Pattern.compile("([a-z]+)( *= *)([0-9]+)");
matcher = pattern.matcher(s1);
result = matcher.replaceAll(r);
if (!result.equals("Swap all: 123 = first, 456 = second"))
failCount++;
matcher = pattern.matcher(s2);
if (matcher.find()) {
StringBuffer sb = new StringBuffer();
matcher.appendReplacement(sb, r);
matcher.appendTail(sb);
result = sb.toString();
if (!result.equals("Swap one: 123 = first, second = 456"))
failCount++;
}
// Supplementary character test
pattern = Pattern.compile(toSupplementaries("(ab)(cd)"));
matcher = pattern.matcher(toSupplementaries("abcd"));
result = matcher.replaceAll("$2$1");
if (!result.equals(toSupplementaries("cdab")))
failCount++;
s1 = toSupplementaries("Swap all: first = 123, second = 456");
s2 = toSupplementaries("Swap one: first = 123, second = 456");
r = toSupplementaries("$3$2$1");
pattern = Pattern.compile(toSupplementaries("([a-z]+)( *= *)([0-9]+)"));
matcher = pattern.matcher(s1);
result = matcher.replaceAll(r);
if (!result.equals(toSupplementaries("Swap all: 123 = first, 456 = second")))
failCount++;
matcher = pattern.matcher(s2);
if (matcher.find()) {
StringBuffer sb = new StringBuffer();
matcher.appendReplacement(sb, r);
matcher.appendTail(sb);
result = sb.toString();
if (!result.equals(toSupplementaries("Swap one: 123 = first, second = 456")))
failCount++;
}
report("Append");
}
private static void splitTest() {
Pattern pattern = Pattern.compile(":");
String[] result = pattern.split("foo:and:boo", 2);
if (!result[0].equals("foo"))
failCount++;
if (!result[1].equals("and:boo"))
failCount++;
// Supplementary character test
Pattern patternX = Pattern.compile(toSupplementaries("X"));
result = patternX.split(toSupplementaries("fooXandXboo"), 2);
if (!result[0].equals(toSupplementaries("foo")))
failCount++;
if (!result[1].equals(toSupplementaries("andXboo")))
failCount++;
CharBuffer cb = CharBuffer.allocate(100);
cb.put("foo:and:boo");
cb.flip();
result = pattern.split(cb);
if (!result[0].equals("foo"))
failCount++;
if (!result[1].equals("and"))
failCount++;
if (!result[2].equals("boo"))
failCount++;
// Supplementary character test
CharBuffer cbs = CharBuffer.allocate(100);
cbs.put(toSupplementaries("fooXandXboo"));
cbs.flip();
result = patternX.split(cbs);
if (!result[0].equals(toSupplementaries("foo")))
failCount++;
if (!result[1].equals(toSupplementaries("and")))
failCount++;
if (!result[2].equals(toSupplementaries("boo")))
failCount++;
String source = "0123456789";
for (int limit=-2; limit<3; limit++) {
for (int x=0; x<10; x++) {
result = source.split(Integer.toString(x), limit);
int expectedLength = limit < 1 ? 2 : limit;
if ((limit == 0) && (x == 9)) {
// expected dropping of ""
if (result.length != 1)
failCount++;
if (!result[0].equals("012345678")) {
failCount++;
}
} else {
if (result.length != expectedLength) {
failCount++;
}
if (!result[0].equals(source.substring(0,x))) {
if (limit != 1) {
failCount++;
} else {
if (!result[0].equals(source.substring(0,10))) {
failCount++;
}
}
}
if (expectedLength > 1) { // Check segment 2
if (!result[1].equals(source.substring(x+1,10)))
failCount++;
}
}
}
}
// Check the case for no match found
for (int limit=-2; limit<3; limit++) {
result = source.split("e", limit);
if (result.length != 1)
failCount++;
if (!result[0].equals(source))
failCount++;
}
// Check the case for limit == 0, source = "";
source = "";
result = source.split("e", 0);
if (result.length != 1)
failCount++;
if (!result[0].equals(source))
failCount++;
report("Split");
}
private static void negationTest() {
Pattern pattern = Pattern.compile("[\\[@^]+");
Matcher matcher = pattern.matcher("@@@@[[[[^^^^");
if (!matcher.find())
failCount++;
if (!matcher.group(0).equals("@@@@[[[[^^^^"))
failCount++;
pattern = Pattern.compile("[@\\[^]+");
matcher = pattern.matcher("@@@@[[[[^^^^");
if (!matcher.find())
failCount++;
if (!matcher.group(0).equals("@@@@[[[[^^^^"))
failCount++;
pattern = Pattern.compile("[@\\[^@]+");
matcher = pattern.matcher("@@@@[[[[^^^^");
if (!matcher.find())
failCount++;
if (!matcher.group(0).equals("@@@@[[[[^^^^"))
failCount++;
pattern = Pattern.compile("\\)");
matcher = pattern.matcher("xxx)xxx");
if (!matcher.find())
failCount++;
report("Negation");
}
private static void ampersandTest() {
Pattern pattern = Pattern.compile("[&@]+");
check(pattern, "@@@@&&&&", true);
pattern = Pattern.compile("[@&]+");
check(pattern, "@@@@&&&&", true);
pattern = Pattern.compile("[@\\&]+");
check(pattern, "@@@@&&&&", true);
report("Ampersand");
}
private static void octalTest() throws Exception {
Pattern pattern = Pattern.compile("\\u0007");
Matcher matcher = pattern.matcher("\u0007");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("\\07");
matcher = pattern.matcher("\u0007");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("\\007");
matcher = pattern.matcher("\u0007");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("\\0007");
matcher = pattern.matcher("\u0007");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("\\040");
matcher = pattern.matcher("\u0020");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("\\0403");
matcher = pattern.matcher("\u00203");
if (!matcher.matches())
failCount++;
pattern = Pattern.compile("\\0103");
matcher = pattern.matcher("\u0043");
if (!matcher.matches())
failCount++;
report("Octal");
}
private static void longPatternTest() throws Exception {
try {
Pattern pattern = Pattern.compile(
"a 32-character-long pattern xxxx");
pattern = Pattern.compile("a 33-character-long pattern xxxxx");
pattern = Pattern.compile("a thirty four character long regex");
StringBuffer patternToBe = new StringBuffer(101);
for (int i=0; i<100; i++)
patternToBe.append((char)(97 + i%26));
pattern = Pattern.compile(patternToBe.toString());
} catch (PatternSyntaxException e) {
failCount++;
}
// Supplementary character test
try {
Pattern pattern = Pattern.compile(
toSupplementaries("a 32-character-long pattern xxxx"));
pattern = Pattern.compile(toSupplementaries("a 33-character-long pattern xxxxx"));
pattern = Pattern.compile(toSupplementaries("a thirty four character long regex"));
StringBuffer patternToBe = new StringBuffer(101*2);
for (int i=0; i<100; i++)
patternToBe.append(Character.toChars(Character.MIN_SUPPLEMENTARY_CODE_POINT
+ 97 + i%26));
pattern = Pattern.compile(patternToBe.toString());
} catch (PatternSyntaxException e) {
failCount++;
}
report("LongPattern");
}
private static void group0Test() throws Exception {
Pattern pattern = Pattern.compile("(tes)ting");
Matcher matcher = pattern.matcher("testing");
check(matcher, "testing");
matcher.reset("testing");
if (matcher.lookingAt()) {
if (!matcher.group(0).equals("testing"))
failCount++;
} else {
failCount++;
}
matcher.reset("testing");
if (matcher.matches()) {
if (!matcher.group(0).equals("testing"))
failCount++;
} else {
failCount++;
}
pattern = Pattern.compile("(tes)ting");
matcher = pattern.matcher("testing");
if (matcher.lookingAt()) {
if (!matcher.group(0).equals("testing"))
failCount++;
} else {
failCount++;
}
pattern = Pattern.compile("^(tes)ting");
matcher = pattern.matcher("testing");
if (matcher.matches()) {
if (!matcher.group(0).equals("testing"))
failCount++;
} else {
failCount++;
}
// Supplementary character test
pattern = Pattern.compile(toSupplementaries("(tes)ting"));
matcher = pattern.matcher(toSupplementaries("testing"));
check(matcher, toSupplementaries("testing"));
matcher.reset(toSupplementaries("testing"));
if (matcher.lookingAt()) {
if (!matcher.group(0).equals(toSupplementaries("testing")))
failCount++;
} else {
failCount++;
}
matcher.reset(toSupplementaries("testing"));
if (matcher.matches()) {
if (!matcher.group(0).equals(toSupplementaries("testing")))
failCount++;
} else {
failCount++;
}
pattern = Pattern.compile(toSupplementaries("(tes)ting"));
matcher = pattern.matcher(toSupplementaries("testing"));
if (matcher.lookingAt()) {
if (!matcher.group(0).equals(toSupplementaries("testing")))
failCount++;
} else {
failCount++;
}
pattern = Pattern.compile(toSupplementaries("^(tes)ting"));
matcher = pattern.matcher(toSupplementaries("testing"));
if (matcher.matches()) {
if (!matcher.group(0).equals(toSupplementaries("testing")))
failCount++;
} else {
failCount++;
}
report("Group0");
}
private static void findIntTest() throws Exception {
Pattern p = Pattern.compile("blah");
Matcher m = p.matcher("zzzzblahzzzzzblah");
boolean result = m.find(2);
if (!result)
failCount++;
p = Pattern.compile("$");
m = p.matcher("1234567890");
result = m.find(10);
if (!result)
failCount++;
try {
result = m.find(11);
failCount++;
} catch (IndexOutOfBoundsException e) {
// correct result
}
// Supplementary character test
p = Pattern.compile(toSupplementaries("blah"));
m = p.matcher(toSupplementaries("zzzzblahzzzzzblah"));
result = m.find(2);
if (!result)
failCount++;
report("FindInt");
}
private static void emptyPatternTest() throws Exception {
Pattern p = Pattern.compile("");
Matcher m = p.matcher("foo");
// Should find empty pattern at beginning of input
boolean result = m.find();
if (result != true)
failCount++;
if (m.start() != 0)
failCount++;
// Should not match entire input if input is not empty
m.reset();
result = m.matches();
if (result == true)
failCount++;
try {
m.start(0);
failCount++;
} catch (IllegalStateException e) {
// Correct result
}
// Should match entire input if input is empty
m.reset("");
result = m.matches();
if (result != true)
failCount++;
result = Pattern.matches("", "");
if (result != true)
failCount++;
result = Pattern.matches("", "foo");
if (result == true)
failCount++;
report("EmptyPattern");
}
private static void charClassTest() throws Exception {
Pattern pattern = Pattern.compile("blah[ab]]blech");
check(pattern, "blahb]blech", true);
pattern = Pattern.compile("[abc[def]]");
check(pattern, "b", true);
// Supplementary character tests
pattern = Pattern.compile(toSupplementaries("blah[ab]]blech"));
check(pattern, toSupplementaries("blahb]blech"), true);
pattern = Pattern.compile(toSupplementaries("[abc[def]]"));
check(pattern, toSupplementaries("b"), true);
try {
// u00ff when UNICODE_CASE
pattern = Pattern.compile("[ab\u00ffcd]",
Pattern.CASE_INSENSITIVE|
Pattern.UNICODE_CASE);
check(pattern, "ab\u00ffcd", true);
check(pattern, "Ab\u0178Cd", true);
// u00b5 when UNICODE_CASE
pattern = Pattern.compile("[ab\u00b5cd]",
Pattern.CASE_INSENSITIVE|
Pattern.UNICODE_CASE);
check(pattern, "ab\u00b5cd", true);
check(pattern, "Ab\u039cCd", true);
} catch (Exception e) { failCount++; }
/* Special cases
(1)LatinSmallLetterLongS u+017f
(2)LatinSmallLetterDotlessI u+0131
(3)LatineCapitalLetterIWithDotAbove u+0130
(4)KelvinSign u+212a
(5)AngstromSign u+212b
*/
int flags = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE;
pattern = Pattern.compile("[sik\u00c5]+", flags);
if (!pattern.matcher("\u017f\u0130\u0131\u212a\u212b").matches())
failCount++;
report("CharClass");
}
private static void caretTest() throws Exception {
Pattern pattern = Pattern.compile("\\w*");
Matcher matcher = pattern.matcher("a#bc#def##g");
check(matcher, "a");
check(matcher, "");
check(matcher, "bc");
check(matcher, "");
check(matcher, "def");
check(matcher, "");
check(matcher, "");
check(matcher, "g");
check(matcher, "");
if (matcher.find())
failCount++;
pattern = Pattern.compile("^\\w*");
matcher = pattern.matcher("a#bc#def##g");
check(matcher, "a");
if (matcher.find())
failCount++;
pattern = Pattern.compile("\\w");
matcher = pattern.matcher("abc##x");
check(matcher, "a");
check(matcher, "b");
check(matcher, "c");
check(matcher, "x");
if (matcher.find())
failCount++;
pattern = Pattern.compile("^\\w");
matcher = pattern.matcher("abc##x");
check(matcher, "a");
if (matcher.find())
failCount++;
pattern = Pattern.compile("\\A\\p{Alpha}{3}");
matcher = pattern.matcher("abcdef-ghi\njklmno");
check(matcher, "abc");
if (matcher.find())
failCount++;
pattern = Pattern.compile("^\\p{Alpha}{3}", Pattern.MULTILINE);
matcher = pattern.matcher("abcdef-ghi\njklmno");
check(matcher, "abc");
check(matcher, "jkl");
if (matcher.find())
failCount++;
pattern = Pattern.compile("^", Pattern.MULTILINE);
matcher = pattern.matcher("this is some text");
String result = matcher.replaceAll("X");
if (!result.equals("Xthis is some text"))
failCount++;
pattern = Pattern.compile("^");
matcher = pattern.matcher("this is some text");
result = matcher.replaceAll("X");
if (!result.equals("Xthis is some text"))
failCount++;
pattern = Pattern.compile("^", Pattern.MULTILINE | Pattern.UNIX_LINES);
matcher = pattern.matcher("this is some text\n");
result = matcher.replaceAll("X");
if (!result.equals("Xthis is some text\n"))
failCount++;
report("Caret");
}
private static void groupCaptureTest() throws Exception {
// Independent group
Pattern pattern = Pattern.compile("x+(?>y+)z+");
Matcher matcher = pattern.matcher("xxxyyyzzz");
matcher.find();
try {
String blah = matcher.group(1);
failCount++;
} catch (IndexOutOfBoundsException ioobe) {
// Good result
}
// Pure group
pattern = Pattern.compile("x+(?:y+)z+");
matcher = pattern.matcher("xxxyyyzzz");
matcher.find();
try {
String blah = matcher.group(1);
failCount++;
} catch (IndexOutOfBoundsException ioobe) {
// Good result
}
// Supplementary character tests
// Independent group
pattern = Pattern.compile(toSupplementaries("x+(?>y+)z+"));
matcher = pattern.matcher(toSupplementaries("xxxyyyzzz"));
matcher.find();
try {
String blah = matcher.group(1);
failCount++;
} catch (IndexOutOfBoundsException ioobe) {
// Good result
}
// Pure group
pattern = Pattern.compile(toSupplementaries("x+(?:y+)z+"));
matcher = pattern.matcher(toSupplementaries("xxxyyyzzz"));
matcher.find();
try {
String blah = matcher.group(1);
failCount++;
} catch (IndexOutOfBoundsException ioobe) {
// Good result
}
report("GroupCapture");
}
private static void backRefTest() throws Exception {
Pattern pattern = Pattern.compile("(a*)bc\\1");
check(pattern, "zzzaabcazzz", true);
pattern = Pattern.compile("(a*)bc\\1");
check(pattern, "zzzaabcaazzz", true);
pattern = Pattern.compile("(abc)(def)\\1");
check(pattern, "abcdefabc", true);
pattern = Pattern.compile("(abc)(def)\\3");
check(pattern, "abcdefabc", false);
try {
for (int i = 1; i < 10; i++) {
// Make sure backref 1-9 are always accepted
pattern = Pattern.compile("abcdef\\" + i);
// and fail to match if the target group does not exit
check(pattern, "abcdef", false);
}
} catch(PatternSyntaxException e) {
failCount++;
}
pattern = Pattern.compile("(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)\\11");
check(pattern, "abcdefghija", false);
check(pattern, "abcdefghija1", true);
pattern = Pattern.compile("(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)\\11");
check(pattern, "abcdefghijkk", true);
pattern = Pattern.compile("(a)bcdefghij\\11");
check(pattern, "abcdefghija1", true);
// Supplementary character tests
pattern = Pattern.compile(toSupplementaries("(a*)bc\\1"));
check(pattern, toSupplementaries("zzzaabcazzz"), true);
pattern = Pattern.compile(toSupplementaries("(a*)bc\\1"));
check(pattern, toSupplementaries("zzzaabcaazzz"), true);
pattern = Pattern.compile(toSupplementaries("(abc)(def)\\1"));
check(pattern, toSupplementaries("abcdefabc"), true);
pattern = Pattern.compile(toSupplementaries("(abc)(def)\\3"));
check(pattern, toSupplementaries("abcdefabc"), false);
pattern = Pattern.compile(toSupplementaries("(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)\\11"));
check(pattern, toSupplementaries("abcdefghija"), false);
check(pattern, toSupplementaries("abcdefghija1"), true);
pattern = Pattern.compile(toSupplementaries("(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)\\11"));
check(pattern, toSupplementaries("abcdefghijkk"), true);
report("BackRef");
}
/**
* Unicode Technical Report #18, section 2.6 End of Line
* There is no empty line to be matched in the sequence \u000D\u000A
* but there is an empty line in the sequence \u000A\u000D.
*/
private static void anchorTest() throws Exception {
Pattern p = Pattern.compile("^.*$", Pattern.MULTILINE);
Matcher m = p.matcher("blah1\r\nblah2");
m.find();
m.find();
if (!m.group().equals("blah2"))
failCount++;
m.reset("blah1\n\rblah2");
m.find();
m.find();
m.find();
if (!m.group().equals("blah2"))
failCount++;
// Test behavior of $ with \r\n at end of input
p = Pattern.compile(".+$");
m = p.matcher("blah1\r\n");
if (!m.find())
failCount++;
if (!m.group().equals("blah1"))
failCount++;
if (m.find())
failCount++;
// Test behavior of $ with \r\n at end of input in multiline
p = Pattern.compile(".+$", Pattern.MULTILINE);
m = p.matcher("blah1\r\n");
if (!m.find())
failCount++;
if (m.find())
failCount++;
// Test for $ recognition of \u0085 for bug 4527731
p = Pattern.compile(".+$", Pattern.MULTILINE);
m = p.matcher("blah1\u0085");
if (!m.find())
failCount++;
// Supplementary character test
p = Pattern.compile("^.*$", Pattern.MULTILINE);
m = p.matcher(toSupplementaries("blah1\r\nblah2"));
m.find();
m.find();
if (!m.group().equals(toSupplementaries("blah2")))
failCount++;
m.reset(toSupplementaries("blah1\n\rblah2"));
m.find();
m.find();
m.find();
if (!m.group().equals(toSupplementaries("blah2")))
failCount++;
// Test behavior of $ with \r\n at end of input
p = Pattern.compile(".+$");
m = p.matcher(toSupplementaries("blah1\r\n"));
if (!m.find())
failCount++;
if (!m.group().equals(toSupplementaries("blah1")))
failCount++;
if (m.find())
failCount++;
// Test behavior of $ with \r\n at end of input in multiline
p = Pattern.compile(".+$", Pattern.MULTILINE);
m = p.matcher(toSupplementaries("blah1\r\n"));
if (!m.find())
failCount++;
if (m.find())
failCount++;
// Test for $ recognition of \u0085 for bug 4527731
p = Pattern.compile(".+$", Pattern.MULTILINE);
m = p.matcher(toSupplementaries("blah1\u0085"));
if (!m.find())
failCount++;
report("Anchors");
}
/**
* A basic sanity test of Matcher.lookingAt().
*/
private static void lookingAtTest() throws Exception {
Pattern p = Pattern.compile("(ab)(c*)");
Matcher m = p.matcher("abccczzzabcczzzabccc");
if (!m.lookingAt())
failCount++;
if (!m.group().equals(m.group(0)))
failCount++;
m = p.matcher("zzzabccczzzabcczzzabccczzz");
if (m.lookingAt())
failCount++;
// Supplementary character test
p = Pattern.compile(toSupplementaries("(ab)(c*)"));
m = p.matcher(toSupplementaries("abccczzzabcczzzabccc"));
if (!m.lookingAt())
failCount++;
if (!m.group().equals(m.group(0)))
failCount++;
m = p.matcher(toSupplementaries("zzzabccczzzabcczzzabccczzz"));
if (m.lookingAt())
failCount++;
report("Looking At");
}
/**
* A basic sanity test of Matcher.matches().
*/
private static void matchesTest() throws Exception {
// matches()
Pattern p = Pattern.compile("ulb(c*)");
Matcher m = p.matcher("ulbcccccc");
if (!m.matches())
failCount++;
// find() but not matches()
m.reset("zzzulbcccccc");
if (m.matches())
failCount++;
// lookingAt() but not matches()
m.reset("ulbccccccdef");
if (m.matches())
failCount++;
// matches()
p = Pattern.compile("a|ad");
m = p.matcher("ad");
if (!m.matches())
failCount++;
// Supplementary character test
// matches()
p = Pattern.compile(toSupplementaries("ulb(c*)"));
m = p.matcher(toSupplementaries("ulbcccccc"));
if (!m.matches())
failCount++;
// find() but not matches()
m.reset(toSupplementaries("zzzulbcccccc"));
if (m.matches())
failCount++;
// lookingAt() but not matches()
m.reset(toSupplementaries("ulbccccccdef"));
if (m.matches())
failCount++;
// matches()
p = Pattern.compile(toSupplementaries("a|ad"));
m = p.matcher(toSupplementaries("ad"));
if (!m.matches())
failCount++;
report("Matches");
}
/**
* A basic sanity test of Pattern.matches().
*/
private static void patternMatchesTest() throws Exception {
// matches()
if (!Pattern.matches(toSupplementaries("ulb(c*)"),
toSupplementaries("ulbcccccc")))
failCount++;
// find() but not matches()
if (Pattern.matches(toSupplementaries("ulb(c*)"),
toSupplementaries("zzzulbcccccc")))
failCount++;
// lookingAt() but not matches()
if (Pattern.matches(toSupplementaries("ulb(c*)"),
toSupplementaries("ulbccccccdef")))
failCount++;
// Supplementary character test
// matches()
if (!Pattern.matches(toSupplementaries("ulb(c*)"),
toSupplementaries("ulbcccccc")))
failCount++;
// find() but not matches()
if (Pattern.matches(toSupplementaries("ulb(c*)"),
toSupplementaries("zzzulbcccccc")))
failCount++;
// lookingAt() but not matches()
if (Pattern.matches(toSupplementaries("ulb(c*)"),
toSupplementaries("ulbccccccdef")))
failCount++;
report("Pattern Matches");
}
/**
* Canonical equivalence testing. Tests the ability of the engine
* to match sequences that are not explicitly specified in the
* pattern when they are considered equivalent by the Unicode Standard.
*/
private static void ceTest() throws Exception {
// Decomposed char outside char classes
Pattern p = Pattern.compile("testa\u030a", Pattern.CANON_EQ);
Matcher m = p.matcher("test\u00e5");
if (!m.matches())
failCount++;
m.reset("testa\u030a");
if (!m.matches())
failCount++;
// Composed char outside char classes
p = Pattern.compile("test\u00e5", Pattern.CANON_EQ);
m = p.matcher("test\u00e5");
if (!m.matches())
failCount++;
m.reset("testa\u030a");
if (!m.find())
failCount++;
// Decomposed char inside a char class
p = Pattern.compile("test[abca\u030a]", Pattern.CANON_EQ);
m = p.matcher("test\u00e5");
if (!m.find())
failCount++;
m.reset("testa\u030a");
if (!m.find())
failCount++;
// Composed char inside a char class
p = Pattern.compile("test[abc\u00e5def\u00e0]", Pattern.CANON_EQ);
m = p.matcher("test\u00e5");
if (!m.find())
failCount++;
m.reset("testa\u0300");
if (!m.find())
failCount++;
m.reset("testa\u030a");
if (!m.find())
failCount++;
// Marks that cannot legally change order and be equivalent
p = Pattern.compile("testa\u0308\u0300", Pattern.CANON_EQ);
check(p, "testa\u0308\u0300", true);
check(p, "testa\u0300\u0308", false);
// Marks that can legally change order and be equivalent
p = Pattern.compile("testa\u0308\u0323", Pattern.CANON_EQ);
check(p, "testa\u0308\u0323", true);
check(p, "testa\u0323\u0308", true);
// Test all equivalences of the sequence a\u0308\u0323\u0300
p = Pattern.compile("testa\u0308\u0323\u0300", Pattern.CANON_EQ);
check(p, "testa\u0308\u0323\u0300", true);
check(p, "testa\u0323\u0308\u0300", true);
check(p, "testa\u0308\u0300\u0323", true);
check(p, "test\u00e4\u0323\u0300", true);
check(p, "test\u00e4\u0300\u0323", true);
/*
* The following canonical equivalence tests don't work. Bug id: 4916384.
*
// Decomposed hangul (jamos)
p = Pattern.compile("\u1100\u1161", Pattern.CANON_EQ);
m = p.matcher("\u1100\u1161");
if (!m.matches())
failCount++;
m.reset("\uac00");
if (!m.matches())
failCount++;
// Composed hangul
p = Pattern.compile("\uac00", Pattern.CANON_EQ);
m = p.matcher("\u1100\u1161");
if (!m.matches())
failCount++;
m.reset("\uac00");
if (!m.matches())
failCount++;
// Decomposed supplementary outside char classes
p = Pattern.compile("test\ud834\uddbc\ud834\udd6f", Pattern.CANON_EQ);
m = p.matcher("test\ud834\uddc0");
if (!m.matches())
failCount++;
m.reset("test\ud834\uddbc\ud834\udd6f");
if (!m.matches())
failCount++;
// Composed supplementary outside char classes
p = Pattern.compile("test\ud834\uddc0", Pattern.CANON_EQ);
m.reset("test\ud834\uddbc\ud834\udd6f");
if (!m.matches())
failCount++;
m = p.matcher("test\ud834\uddc0");
if (!m.matches())
failCount++;
*/
report("Canonical Equivalence");
}
/**
* A basic sanity test of Matcher.replaceAll().
*/
private static void globalSubstitute() throws Exception {
// Global substitution with a literal
Pattern p = Pattern.compile("(ab)(c*)");
Matcher m = p.matcher("abccczzzabcczzzabccc");
if (!m.replaceAll("test").equals("testzzztestzzztest"))
failCount++;
m.reset("zzzabccczzzabcczzzabccczzz");
if (!m.replaceAll("test").equals("zzztestzzztestzzztestzzz"))
failCount++;
// Global substitution with groups
m.reset("zzzabccczzzabcczzzabccczzz");
String result = m.replaceAll("$1");
if (!result.equals("zzzabzzzabzzzabzzz"))
failCount++;
// Supplementary character test
// Global substitution with a literal
p = Pattern.compile(toSupplementaries("(ab)(c*)"));
m = p.matcher(toSupplementaries("abccczzzabcczzzabccc"));
if (!m.replaceAll(toSupplementaries("test")).
equals(toSupplementaries("testzzztestzzztest")))
failCount++;
m.reset(toSupplementaries("zzzabccczzzabcczzzabccczzz"));
if (!m.replaceAll(toSupplementaries("test")).
equals(toSupplementaries("zzztestzzztestzzztestzzz")))
failCount++;
// Global substitution with groups
m.reset(toSupplementaries("zzzabccczzzabcczzzabccczzz"));
result = m.replaceAll("$1");
if (!result.equals(toSupplementaries("zzzabzzzabzzzabzzz")))
failCount++;
report("Global Substitution");
}
/**
* Tests the usage of Matcher.appendReplacement() with literal
* and group substitutions.
*/
private static void stringbufferSubstitute() throws Exception {
// SB substitution with literal
String blah = "zzzblahzzz";
Pattern p = Pattern.compile("blah");
Matcher m = p.matcher(blah);
StringBuffer result = new StringBuffer();
try {
m.appendReplacement(result, "blech");
failCount++;
} catch (IllegalStateException e) {
}
m.find();
m.appendReplacement(result, "blech");
if (!result.toString().equals("zzzblech"))
failCount++;
m.appendTail(result);
if (!result.toString().equals("zzzblechzzz"))
failCount++;
// SB substitution with groups
blah = "zzzabcdzzz";
p = Pattern.compile("(ab)(cd)*");
m = p.matcher(blah);
result = new StringBuffer();
try {
m.appendReplacement(result, "$1");
failCount++;
} catch (IllegalStateException e) {
}
m.find();
m.appendReplacement(result, "$1");
if (!result.toString().equals("zzzab"))
failCount++;
m.appendTail(result);
if (!result.toString().equals("zzzabzzz"))
failCount++;
// SB substitution with 3 groups
blah = "zzzabcdcdefzzz";
p = Pattern.compile("(ab)(cd)*(ef)");
m = p.matcher(blah);
result = new StringBuffer();
try {
m.appendReplacement(result, "$1w$2w$3");
failCount++;
} catch (IllegalStateException e) {
}
m.find();
m.appendReplacement(result, "$1w$2w$3");
if (!result.toString().equals("zzzabwcdwef"))
failCount++;
m.appendTail(result);
if (!result.toString().equals("zzzabwcdwefzzz"))
failCount++;
// SB substitution with groups and three matches
// skipping middle match
blah = "zzzabcdzzzabcddzzzabcdzzz";
p = Pattern.compile("(ab)(cd*)");
m = p.matcher(blah);
result = new StringBuffer();
try {
m.appendReplacement(result, "$1");
failCount++;
} catch (IllegalStateException e) {
}
m.find();
m.appendReplacement(result, "$1");
if (!result.toString().equals("zzzab"))
failCount++;
m.find();
m.find();
m.appendReplacement(result, "$2");
if (!result.toString().equals("zzzabzzzabcddzzzcd"))
failCount++;
m.appendTail(result);
if (!result.toString().equals("zzzabzzzabcddzzzcdzzz"))
failCount++;
// Check to make sure escaped $ is ignored
blah = "zzzabcdcdefzzz";
p = Pattern.compile("(ab)(cd)*(ef)");
m = p.matcher(blah);
result = new StringBuffer();
m.find();
m.appendReplacement(result, "$1w\\$2w$3");
if (!result.toString().equals("zzzabw$2wef"))
failCount++;
m.appendTail(result);
if (!result.toString().equals("zzzabw$2wefzzz"))
failCount++;
// Check to make sure a reference to nonexistent group causes error
blah = "zzzabcdcdefzzz";
p = Pattern.compile("(ab)(cd)*(ef)");
m = p.matcher(blah);
result = new StringBuffer();
m.find();
try {
m.appendReplacement(result, "$1w$5w$3");
failCount++;
} catch (IndexOutOfBoundsException ioobe) {
// Correct result
}
// Check double digit group references
blah = "zzz123456789101112zzz";
p = Pattern.compile("(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)");
m = p.matcher(blah);
result = new StringBuffer();
m.find();
m.appendReplacement(result, "$1w$11w$3");
if (!result.toString().equals("zzz1w11w3"))
failCount++;
// Check to make sure it backs off $15 to $1 if only three groups
blah = "zzzabcdcdefzzz";
p = Pattern.compile("(ab)(cd)*(ef)");
m = p.matcher(blah);
result = new StringBuffer();
m.find();
m.appendReplacement(result, "$1w$15w$3");
if (!result.toString().equals("zzzabwab5wef"))
failCount++;
// Supplementary character test
// SB substitution with literal
blah = toSupplementaries("zzzblahzzz");
p = Pattern.compile(toSupplementaries("blah"));
m = p.matcher(blah);
result = new StringBuffer();
try {
m.appendReplacement(result, toSupplementaries("blech"));
failCount++;
} catch (IllegalStateException e) {
}
m.find();
m.appendReplacement(result, toSupplementaries("blech"));
if (!result.toString().equals(toSupplementaries("zzzblech")))
failCount++;
m.appendTail(result);
if (!result.toString().equals(toSupplementaries("zzzblechzzz")))
failCount++;
// SB substitution with groups
blah = toSupplementaries("zzzabcdzzz");
p = Pattern.compile(toSupplementaries("(ab)(cd)*"));
m = p.matcher(blah);
result = new StringBuffer();
try {
m.appendReplacement(result, "$1");
failCount++;
} catch (IllegalStateException e) {
}
m.find();
m.appendReplacement(result, "$1");
if (!result.toString().equals(toSupplementaries("zzzab")))
failCount++;
m.appendTail(result);
if (!result.toString().equals(toSupplementaries("zzzabzzz")))
failCount++;
// SB substitution with 3 groups
blah = toSupplementaries("zzzabcdcdefzzz");
p = Pattern.compile(toSupplementaries("(ab)(cd)*(ef)"));
m = p.matcher(blah);
result = new StringBuffer();
try {
m.appendReplacement(result, toSupplementaries("$1w$2w$3"));
failCount++;
} catch (IllegalStateException e) {
}
m.find();
m.appendReplacement(result, toSupplementaries("$1w$2w$3"));
if (!result.toString().equals(toSupplementaries("zzzabwcdwef")))
failCount++;
m.appendTail(result);
if (!result.toString().equals(toSupplementaries("zzzabwcdwefzzz")))
failCount++;
// SB substitution with groups and three matches
// skipping middle match
blah = toSupplementaries("zzzabcdzzzabcddzzzabcdzzz");
p = Pattern.compile(toSupplementaries("(ab)(cd*)"));
m = p.matcher(blah);
result = new StringBuffer();
try {
m.appendReplacement(result, "$1");
failCount++;
} catch (IllegalStateException e) {
}
m.find();
m.appendReplacement(result, "$1");
if (!result.toString().equals(toSupplementaries("zzzab")))
failCount++;
m.find();
m.find();
m.appendReplacement(result, "$2");
if (!result.toString().equals(toSupplementaries("zzzabzzzabcddzzzcd")))
failCount++;
m.appendTail(result);
if (!result.toString().equals(toSupplementaries("zzzabzzzabcddzzzcdzzz")))
failCount++;
// Check to make sure escaped $ is ignored
blah = toSupplementaries("zzzabcdcdefzzz");
p = Pattern.compile(toSupplementaries("(ab)(cd)*(ef)"));
m = p.matcher(blah);
result = new StringBuffer();
m.find();
m.appendReplacement(result, toSupplementaries("$1w\\$2w$3"));
if (!result.toString().equals(toSupplementaries("zzzabw$2wef")))
failCount++;
m.appendTail(result);
if (!result.toString().equals(toSupplementaries("zzzabw$2wefzzz")))
failCount++;
// Check to make sure a reference to nonexistent group causes error
blah = toSupplementaries("zzzabcdcdefzzz");
p = Pattern.compile(toSupplementaries("(ab)(cd)*(ef)"));
m = p.matcher(blah);
result = new StringBuffer();
m.find();
try {
m.appendReplacement(result, toSupplementaries("$1w$5w$3"));
failCount++;
} catch (IndexOutOfBoundsException ioobe) {
// Correct result
}
// Check double digit group references
blah = toSupplementaries("zzz123456789101112zzz");
p = Pattern.compile("(1)(2)(3)(4)(5)(6)(7)(8)(9)(10)(11)");
m = p.matcher(blah);
result = new StringBuffer();
m.find();
m.appendReplacement(result, toSupplementaries("$1w$11w$3"));
if (!result.toString().equals(toSupplementaries("zzz1w11w3")))
failCount++;
// Check to make sure it backs off $15 to $1 if only three groups
blah = toSupplementaries("zzzabcdcdefzzz");
p = Pattern.compile(toSupplementaries("(ab)(cd)*(ef)"));
m = p.matcher(blah);
result = new StringBuffer();
m.find();
m.appendReplacement(result, toSupplementaries("$1w$15w$3"));
if (!result.toString().equals(toSupplementaries("zzzabwab5wef")))
failCount++;
// Check nothing has been appended into the output buffer if
// the replacement string triggers IllegalArgumentException.
p = Pattern.compile("(abc)");
m = p.matcher("abcd");
result = new StringBuffer();
m.find();
try {
m.appendReplacement(result, ("xyz$g"));
failCount++;
} catch (IllegalArgumentException iae) {
if (result.length() != 0)
failCount++;
}
report("SB Substitution");
}
/*
* 5 groups of characters are created to make a substitution string.
* A base string will be created including random lead chars, the
* substitution string, and random trailing chars.
* A pattern containing the 5 groups is searched for and replaced with:
* random group + random string + random group.
* The results are checked for correctness.
*/
private static void substitutionBasher() {
for (int runs = 0; runs<1000; runs++) {
// Create a base string to work in
int leadingChars = generator.nextInt(10);
StringBuffer baseBuffer = new StringBuffer(100);
String leadingString = getRandomAlphaString(leadingChars);
baseBuffer.append(leadingString);
// Create 5 groups of random number of random chars
// Create the string to substitute
// Create the pattern string to search for
StringBuffer bufferToSub = new StringBuffer(25);
StringBuffer bufferToPat = new StringBuffer(50);
String[] groups = new String[5];
for(int i=0; i<5; i++) {
int aGroupSize = generator.nextInt(5)+1;
groups[i] = getRandomAlphaString(aGroupSize);
bufferToSub.append(groups[i]);
bufferToPat.append('(');
bufferToPat.append(groups[i]);
bufferToPat.append(')');
}
String stringToSub = bufferToSub.toString();
String pattern = bufferToPat.toString();
// Place sub string into working string at random index
baseBuffer.append(stringToSub);
// Append random chars to end
int trailingChars = generator.nextInt(10);
String trailingString = getRandomAlphaString(trailingChars);
baseBuffer.append(trailingString);
String baseString = baseBuffer.toString();
// Create test pattern and matcher
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(baseString);
// Reject candidate if pattern happens to start early
m.find();
if (m.start() < leadingChars)
continue;
// Reject candidate if more than one match
if (m.find())
continue;
// Construct a replacement string with :
// random group + random string + random group
StringBuffer bufferToRep = new StringBuffer();
int groupIndex1 = generator.nextInt(5);
bufferToRep.append("$" + (groupIndex1 + 1));
String randomMidString = getRandomAlphaString(5);
bufferToRep.append(randomMidString);
int groupIndex2 = generator.nextInt(5);
bufferToRep.append("$" + (groupIndex2 + 1));
String replacement = bufferToRep.toString();
// Do the replacement
String result = m.replaceAll(replacement);
// Construct expected result
StringBuffer bufferToRes = new StringBuffer();
bufferToRes.append(leadingString);
bufferToRes.append(groups[groupIndex1]);
bufferToRes.append(randomMidString);
bufferToRes.append(groups[groupIndex2]);
bufferToRes.append(trailingString);
String expectedResult = bufferToRes.toString();
// Check results
if (!result.equals(expectedResult))
failCount++;
}
report("Substitution Basher");
}
/**
* Checks the handling of some escape sequences that the Pattern
* class should process instead of the java compiler. These are
* not in the file because the escapes should be be processed
* by the Pattern class when the regex is compiled.
*/
private static void escapes() throws Exception {
Pattern p = Pattern.compile("\\043");
Matcher m = p.matcher("#");
if (!m.find())
failCount++;
p = Pattern.compile("\\x23");
m = p.matcher("#");
if (!m.find())
failCount++;
p = Pattern.compile("\\u0023");
m = p.matcher("#");
if (!m.find())
failCount++;
report("Escape sequences");
}
/**
* Checks the handling of blank input situations. These
* tests are incompatible with my test file format.
*/
private static void blankInput() throws Exception {
Pattern p = Pattern.compile("abc", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("");
if (m.find())
failCount++;
p = Pattern.compile("a*", Pattern.CASE_INSENSITIVE);
m = p.matcher("");
if (!m.find())
failCount++;
p = Pattern.compile("abc");
m = p.matcher("");
if (m.find())
failCount++;
p = Pattern.compile("a*");
m = p.matcher("");
if (!m.find())
failCount++;
report("Blank input");
}
/**
* Tests the Boyer-Moore pattern matching of a character sequence
* on randomly generated patterns.
*/
private static void bm() throws Exception {
doBnM('a');
report("Boyer Moore (ASCII)");
doBnM(Character.MIN_SUPPLEMENTARY_CODE_POINT - 10);
report("Boyer Moore (Supplementary)");
}
private static void doBnM(int baseCharacter) throws Exception {
int achar=0;
for (int i=0; i<100; i++) {
// Create a short pattern to search for
int patternLength = generator.nextInt(7) + 4;
StringBuffer patternBuffer = new StringBuffer(patternLength);
for (int x=0; x<patternLength; x++) {
int ch = baseCharacter + generator.nextInt(26);
if (Character.isSupplementaryCodePoint(ch)) {
patternBuffer.append(Character.toChars(ch));
} else {
patternBuffer.append((char)ch);
}
}
String pattern = patternBuffer.toString();
Pattern p = Pattern.compile(pattern);
// Create a buffer with random ASCII chars that does
// not match the sample
String toSearch = null;
StringBuffer s = null;
Matcher m = p.matcher("");
do {
s = new StringBuffer(100);
for (int x=0; x<100; x++) {
int ch = baseCharacter + generator.nextInt(26);
if (Character.isSupplementaryCodePoint(ch)) {
s.append(Character.toChars(ch));
} else {
s.append((char)ch);
}
}
toSearch = s.toString();
m.reset(toSearch);
} while (m.find());
// Insert the pattern at a random spot
int insertIndex = generator.nextInt(99);
if (Character.isLowSurrogate(s.charAt(insertIndex)))
insertIndex++;
s = s.insert(insertIndex, pattern);
toSearch = s.toString();
// Make sure that the pattern is found
m.reset(toSearch);
if (!m.find())
failCount++;
// Make sure that the match text is the pattern
if (!m.group().equals(pattern))
failCount++;
// Make sure match occured at insertion point
if (m.start() != insertIndex)
failCount++;
}
}
/**
* Tests the matching of slices on randomly generated patterns.
* The Boyer-Moore optimization is not done on these patterns
* because it uses unicode case folding.
*/
private static void slice() throws Exception {
doSlice(Character.MAX_VALUE);
report("Slice");
doSlice(Character.MAX_CODE_POINT);
report("Slice (Supplementary)");
}
private static void doSlice(int maxCharacter) throws Exception {
Random generator = new Random();
int achar=0;
for (int i=0; i<100; i++) {
// Create a short pattern to search for
int patternLength = generator.nextInt(7) + 4;
StringBuffer patternBuffer = new StringBuffer(patternLength);
for (int x=0; x<patternLength; x++) {
int randomChar = 0;
while (!Character.isLetterOrDigit(randomChar))
randomChar = generator.nextInt(maxCharacter);
if (Character.isSupplementaryCodePoint(randomChar)) {
patternBuffer.append(Character.toChars(randomChar));
} else {
patternBuffer.append((char) randomChar);
}
}
String pattern = patternBuffer.toString();
Pattern p = Pattern.compile(pattern, Pattern.UNICODE_CASE);
// Create a buffer with random chars that does not match the sample
String toSearch = null;
StringBuffer s = null;
Matcher m = p.matcher("");
do {
s = new StringBuffer(100);
for (int x=0; x<100; x++) {
int randomChar = 0;
while (!Character.isLetterOrDigit(randomChar))
randomChar = generator.nextInt(maxCharacter);
if (Character.isSupplementaryCodePoint(randomChar)) {
s.append(Character.toChars(randomChar));
} else {
s.append((char) randomChar);
}
}
toSearch = s.toString();
m.reset(toSearch);
} while (m.find());
// Insert the pattern at a random spot
int insertIndex = generator.nextInt(99);
if (Character.isLowSurrogate(s.charAt(insertIndex)))
insertIndex++;
s = s.insert(insertIndex, pattern);
toSearch = s.toString();
// Make sure that the pattern is found
m.reset(toSearch);
if (!m.find())
failCount++;
// Make sure that the match text is the pattern
if (!m.group().equals(pattern))
failCount++;
// Make sure match occured at insertion point
if (m.start() != insertIndex)
failCount++;
}
}
private static void explainFailure(String pattern, String data,
String expected, String actual) {
System.err.println("----------------------------------------");
System.err.println("Pattern = "+pattern);
System.err.println("Data = "+data);
System.err.println("Expected = " + expected);
System.err.println("Actual = " + actual);
}
private static void explainFailure(String pattern, String data,
Throwable t) {
System.err.println("----------------------------------------");
System.err.println("Pattern = "+pattern);
System.err.println("Data = "+data);
t.printStackTrace(System.err);
}
// Testing examples from a file
/**
* Goes through the file "TestCases.txt" and creates many patterns
* described in the file, matching the patterns against input lines in
* the file, and comparing the results against the correct results
* also found in the file. The file format is described in comments
* at the head of the file.
*/
private static void processFile(String fileName) throws Exception {
File testCases = new File(System.getProperty("test.src", "."),
fileName);
InputStream in = RegExTest.class.getClassLoader().getResourceAsStream(fileName);
//new FileInputStream(testCases);
BufferedReader r = new BufferedReader(new InputStreamReader(in));
// Process next test case.
String aLine;
while((aLine = r.readLine()) != null) {
// Read a line for pattern
String patternString = grabLine(r);
if(patternString == null)
break;
Pattern p = null;
try {
p = compileTestPattern(patternString);
} catch (Exception e) {
String dataString = grabLine(r);
String expectedResult = grabLine(r);
if (expectedResult.startsWith("error"))
continue;
explainFailure(patternString, dataString, e);
failCount++;
continue;
}
// Read a line for input string
String dataString = grabLine(r);
Matcher m = p.matcher(dataString);
StringBuffer result = new StringBuffer();
// Check for IllegalStateExceptions before a match
failCount += preMatchInvariants(m);
boolean found = m.find();
if (found)
failCount += postTrueMatchInvariants(m);
else
failCount += postFalseMatchInvariants(m);
if (found) {
result.append("true ");
result.append(m.group(0) + " ");
} else {
result.append("false ");
}
result.append(m.groupCount());
if (found) {
for (int i=1; i<m.groupCount()+1; i++)
if (m.group(i) != null)
result.append(" " +m.group(i));
}
// Read a line for the expected result
String expectedResult = grabLine(r);
if (!result.toString().equals(expectedResult)) {
explainFailure(patternString, dataString, expectedResult, result.toString());
failCount++;
}
}
report(fileName);
}
private static int preMatchInvariants(Matcher m) {
int failCount = 0;
try {
m.start();
failCount++;
} catch (IllegalStateException ise) {}
try {
m.end();
failCount++;
} catch (IllegalStateException ise) {}
try {
m.group();
failCount++;
} catch (IllegalStateException ise) {}
return failCount;
}
private static int postFalseMatchInvariants(Matcher m) {
int failCount = 0;
try {
m.group();
failCount++;
} catch (IllegalStateException ise) {}
try {
m.start();
failCount++;
} catch (IllegalStateException ise) {}
try {
m.end();
failCount++;
} catch (IllegalStateException ise) {}
return failCount;
}
private static int postTrueMatchInvariants(Matcher m) {
int failCount = 0;
//assert(m.start() = m.start(0);
if (m.start() != m.start(0))
failCount++;
//assert(m.end() = m.end(0);
if (m.start() != m.start(0))
failCount++;
//assert(m.group() = m.group(0);
if (!m.group().equals(m.group(0)))
failCount++;
try {
m.group(50);
failCount++;
} catch (IndexOutOfBoundsException ise) {}
return failCount;
}
private static Pattern compileTestPattern(String patternString) {
if (!patternString.startsWith("'")) {
return Pattern.compile(patternString);
}
int break1 = patternString.lastIndexOf("'");
String flagString = patternString.substring(
break1+1, patternString.length());
patternString = patternString.substring(1, break1);
if (flagString.equals("i"))
return Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
if (flagString.equals("m"))
return Pattern.compile(patternString, Pattern.MULTILINE);
return Pattern.compile(patternString);
}
/**
* Reads a line from the input file. Keeps reading lines until a non
* empty non comment line is read. If the line contains a \n then
* these two characters are replaced by a newline char. If a \\uxxxx
* sequence is read then the sequence is replaced by the unicode char.
*/
private static String grabLine(BufferedReader r) throws Exception {
int index = 0;
String line = r.readLine();
if(line == null) return line;
while (line.startsWith("//") || line.length() < 1) {
line = r.readLine();
if(line == null) return line;
}
while ((index = line.indexOf("\\n")) != -1) {
StringBuffer temp = new StringBuffer(line);
temp.replace(index, index+2, "\n");
line = temp.toString();
}
while ((index = line.indexOf("\\u")) != -1) {
StringBuffer temp = new StringBuffer(line);
String value = temp.substring(index+2, index+6);
char aChar = (char)Integer.parseInt(value, 16);
String unicodeChar = "" + aChar;
temp.replace(index, index+6, unicodeChar);
line = temp.toString();
}
return line;
}
private static void check(Pattern p, String s, String g, String expected) {
Matcher m = p.matcher(s);
m.find();
if (!m.group(g).equals(expected))
failCount++;
}
private static void checkReplaceFirst(String p, String s, String r, String expected)
{
if (!expected.equals(Pattern.compile(p)
.matcher(s)
.replaceFirst(r)))
failCount++;
}
private static void checkReplaceAll(String p, String s, String r, String expected)
{
if (!expected.equals(Pattern.compile(p)
.matcher(s)
.replaceAll(r)))
failCount++;
}
private static void checkExpectedFail(String p) {
try {
Pattern.compile(p);
} catch (regexodus.PatternSyntaxException pse) {
//pse.printStackTrace();
return;
}
failCount++;
}
private static void checkExpectedFail(Matcher m, String g) {
m.find();
try {
m.group(g);
} catch (IllegalArgumentException iae) {
//iae.printStackTrace();
return;
} catch (NullPointerException npe) {
return;
}
failCount++;
}
private static void namedGroupCaptureTest() throws Exception {
check(Pattern.compile("x+(?<gname>y+)z+"),
"xxxyyyzzz",
"gname",
"yyy");
check(Pattern.compile("x+(?<gname8>y+)z+"),
"xxxyyyzzz",
"gname8",
"yyy");
//backref
Pattern pattern = Pattern.compile("(a*)bc\\1");
check(pattern, "zzzaabcazzz", true); // found "abca"
check(Pattern.compile("(?<gname>a*)bc\\k<gname>"),
"zzzaabcaazzz", true);
check(Pattern.compile("(?<gname>abc)(def)\\k<gname>"),
"abcdefabc", true);
check(Pattern.compile("(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(?<gname>k)\\k<gname>"),
"abcdefghijkk", true);
// Supplementary character tests
check(Pattern.compile("(?<gname>" + toSupplementaries("a*)bc") + "\\k<gname>"),
toSupplementaries("zzzaabcazzz"), true);
check(Pattern.compile("(?<gname>" + toSupplementaries("a*)bc") + "\\k<gname>"),
toSupplementaries("zzzaabcaazzz"), true);
check(Pattern.compile("(?<gname>" + toSupplementaries("abc)(def)") + "\\k<gname>"),
toSupplementaries("abcdefabc"), true);
check(Pattern.compile(toSupplementaries("(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)") +
"(?<gname>" +
toSupplementaries("k)") + "\\k<gname>"),
toSupplementaries("abcdefghijkk"), true);
check(Pattern.compile("x+(?<gname>y+)z+\\k<gname>"),
"xxxyyyzzzyyy",
"gname",
"yyy");
//replaceFirst/All
checkReplaceFirst("(?<gn>ab)(c*)",
"abccczzzabcczzzabccc",
"${gn}",
"abzzzabcczzzabccc");
checkReplaceAll("(?<gn>ab)(c*)",
"abccczzzabcczzzabccc",
"${gn}",
"abzzzabzzzab");
checkReplaceFirst("(?<gn>ab)(c*)",
"zzzabccczzzabcczzzabccczzz",
"${gn}",
"zzzabzzzabcczzzabccczzz");
checkReplaceAll("(?<gn>ab)(c*)",
"zzzabccczzzabcczzzabccczzz",
"${gn}",
"zzzabzzzabzzzabzzz");
checkReplaceFirst("(?<gn1>ab)(?<gn2>c*)",
"zzzabccczzzabcczzzabccczzz",
"${gn2}",
"zzzccczzzabcczzzabccczzz");
checkReplaceAll("(?<gn1>ab)(?<gn2>c*)",
"zzzabccczzzabcczzzabccczzz",
"${gn2}",
"zzzccczzzcczzzccczzz");
//toSupplementaries("(ab)(c*)"));
checkReplaceFirst("(?<gn1>" + toSupplementaries("ab") +
")(?<gn2>" + toSupplementaries("c") + "*)",
toSupplementaries("abccczzzabcczzzabccc"),
"${gn1}",
toSupplementaries("abzzzabcczzzabccc"));
checkReplaceAll("(?<gn1>" + toSupplementaries("ab") +
")(?<gn2>" + toSupplementaries("c") + "*)",
toSupplementaries("abccczzzabcczzzabccc"),
"${gn1}",
toSupplementaries("abzzzabzzzab"));
checkReplaceFirst("(?<gn1>" + toSupplementaries("ab") +
")(?<gn2>" + toSupplementaries("c") + "*)",
toSupplementaries("abccczzzabcczzzabccc"),
"${gn2}",
toSupplementaries("ccczzzabcczzzabccc"));
checkReplaceAll("(?<gn1>" + toSupplementaries("ab") +
")(?<gn2>" + toSupplementaries("c") + "*)",
toSupplementaries("abccczzzabcczzzabccc"),
"${gn2}",
toSupplementaries("ccczzzcczzzccc"));
checkReplaceFirst("(?<dog>Dog)AndCat",
"zzzDogAndCatzzzDogAndCatzzz",
"${dog}",
"zzzDogzzzDogAndCatzzz");
checkReplaceAll("(?<dog>Dog)AndCat",
"zzzDogAndCatzzzDogAndCatzzz",
"${dog}",
"zzzDogzzzDogzzz");
// backref in Matcher & String
if (!"abcdefghij".replaceFirst("cd(?<gn>ef)gh", "${gn}").equals("abefij") ||
!"abbbcbdbefgh".replaceAll("(?<gn>[a-e])b", "${gn}").equals("abcdefgh"))
failCount++;
// negative
checkExpectedFail("(?<groupnamehasnoascii.in>abc)(def)");
checkExpectedFail("(?<groupnamehasnoascii_in>abc)(def)");
checkExpectedFail("(?<6groupnamestartswithdigit>abc)(def)");
checkExpectedFail("(?<gname>abc)(def)\\k<gnameX>");
checkExpectedFail("(?<gname>abc)(?<gname>def)\\k<gnameX>");
checkExpectedFail(Pattern.compile("(?<gname>abc)(def)").matcher("abcdef"),
"gnameX");
checkExpectedFail(Pattern.compile("(?<gname>abc)(def)").matcher("abcdef"),
null);
report("NamedGroupCapture");
}
// This is for bug 6969132
private static void nonBmpClassComplementTest() throws Exception {
Pattern p = Pattern.compile("\\P{Lu}");
Matcher m = p.matcher(new String(new int[] {0x1d400}, 0, 1));
if (m.find() && m.start() == 1)
failCount++;
// from a unicode category
p = Pattern.compile("\\P{Lu}");
m = p.matcher(new String(new int[] {0x1d400}, 0, 1));
if (m.find())
failCount++;
if (!m.hitEnd())
failCount++;
// block
p = Pattern.compile("\\P{InMathematicalAlphanumericSymbols}");
m = p.matcher(new String(new int[] {0x1d400}, 0, 1));
if (m.find() && m.start() == 1)
failCount++;
report("NonBmpClassComplement");
}
private static void unicodePropertiesTest() throws Exception {
// different forms
if (!Pattern.compile("\\p{IsLu}").matcher("A").matches() ||
!Pattern.compile("\\p{Lu}").matcher("A").matches() ||
/*
!Pattern.compile("\\p{gc=Lu}").matcher("A").matches() ||
!Pattern.compile("\\p{general_category=Lu}").matcher("A").matches() ||
!Pattern.compile("\\p{IsLatin}").matcher("B").matches() ||
!Pattern.compile("\\p{sc=Latin}").matcher("B").matches() ||
!Pattern.compile("\\p{script=Latin}").matcher("B").matches() ||
*/
!Pattern.compile("\\p{InBasicLatin}").matcher("c").matches() /* ||
!Pattern.compile("\\p{blk=BasicLatin}").matcher("c").matches() ||
!Pattern.compile("\\p{block=BasicLatin}").matcher("c").matches() */)
failCount++;
/*
Matcher common = Pattern.compile("\\p{script=Common}").matcher("");
Matcher unknown = Pattern.compile("\\p{IsUnknown}").matcher("");
Matcher lastSM = common;
Character.UnicodeScript lastScript = Character.UnicodeScript.of(0);
Matcher latin = Pattern.compile("\\p{block=basic_latin}").matcher("");
Matcher greek = Pattern.compile("\\p{InGreek}").matcher("");
Matcher lastBM = latin;
Character.UnicodeBlock lastBlock = Character.UnicodeBlock.of(0);
for (int cp = 1; cp < Character.MAX_CODE_POINT; cp++) {
if (cp >= 0x30000 && (cp & 0x70) == 0){
continue; // only pick couple code points, they are the same
}
// Unicode Script
Character.UnicodeScript script = Character.UnicodeScript.of(cp);
Matcher m;
String str = new String(Character.toChars(cp));
if (script == lastScript) {
m = lastSM;
m.reset(str);
} else {
m = Pattern.compile("\\p{Is" + script.name() + "}").matcher(str);
}
if (!m.matches()) {
failCount++;
}
Matcher other = (script == Character.UnicodeScript.COMMON)? unknown : common;
other.reset(str);
if (other.matches()) {
failCount++;
}
lastSM = m;
lastScript = script;
// Unicode Block
Character.UnicodeBlock block = Character.UnicodeBlock.of(cp);
if (block == null) {
//System.out.printf("Not a Block: cp=%x%n", cp);
continue;
}
if (block == lastBlock) {
m = lastBM;
m.reset(str);
} else {
m = Pattern.compile("\\p{block=" + block.toString() + "}").matcher(str);
}
if (!m.matches()) {
failCount++;
}
other = (block == Character.UnicodeBlock.BASIC_LATIN)? greek : latin;
other.reset(str);
if (other.matches()) {
failCount++;
}
lastBM = m;
lastBlock = block;
}
*/
report("unicodeProperties");
}
private static void unicodeHexNotationTest() throws Exception {
// negative
checkExpectedFail("\\x{-23}");
checkExpectedFail("\\x{110000}");
checkExpectedFail("\\x{}");
checkExpectedFail("\\x{AB[ef]");
// codepoint
check("^\\x{1033c}$", "\uD800\uDF3C", true);
check("^\\xF0\\x90\\x8C\\xBC$", "\uD800\uDF3C", false);
check("^\\x{D800}\\x{DF3c}+$", "\uD800\uDF3C", false);
check("^\\xF0\\x90\\x8C\\xBC$", "\uD800\uDF3C", false);
// in class
check("^[\\x{D800}\\x{DF3c}]+$", "\uD800\uDF3C", false);
check("^[\\xF0\\x90\\x8C\\xBC]+$", "\uD800\uDF3C", false);
check("^[\\x{D800}\\x{DF3C}]+$", "\uD800\uDF3C", false);
check("^[\\x{DF3C}\\x{D800}]+$", "\uD800\uDF3C", false);
check("^[\\x{D800}\\x{DF3C}]+$", "\uDF3C\uD800", true);
check("^[\\x{DF3C}\\x{D800}]+$", "\uDF3C\uD800", true);
for (int cp = 0; cp <= 0x10FFFF; cp++) {
String s = "A" + new String(Character.toChars(cp)) + "B";
String hexUTF16 = (cp <= 0xFFFF)? String.format("\\u%04x", cp)
: String.format("\\u%04x\\u%04x",
(int) Character.toChars(cp)[0],
(int) Character.toChars(cp)[1]);
String hexCodePoint = "\\x{" + Integer.toHexString(cp) + "}";
if (!Pattern.matches("A" + hexUTF16 + "B", s))
failCount++;
if (!Pattern.matches("A[" + hexUTF16 + "]B", s))
failCount++;
if (!Pattern.matches("A" + hexCodePoint + "B", s))
failCount++;
if (!Pattern.matches("A[" + hexCodePoint + "]B", s))
failCount++;
}
report("unicodeHexNotation");
}
private static void unicodeClassesTest() throws Exception {
Matcher lower = Pattern.compile("\\p{Lower}").matcher("");
Matcher upper = Pattern.compile("\\p{Upper}").matcher("");
Matcher ASCII = Pattern.compile("\\p{ASCII}").matcher("");
Matcher alpha = Pattern.compile("\\p{Alpha}").matcher("");
Matcher digit = Pattern.compile("\\p{Digit}").matcher("");
Matcher alnum = Pattern.compile("\\p{Alnum}").matcher("");
Matcher punct = Pattern.compile("\\p{Punct}").matcher("");
Matcher graph = Pattern.compile("\\p{Graph}").matcher("");
Matcher print = Pattern.compile("\\p{Print}").matcher("");
Matcher blank = Pattern.compile("\\p{Blank}").matcher("");
Matcher cntrl = Pattern.compile("\\p{Cntrl}").matcher("");
Matcher xdigit = Pattern.compile("\\p{XDigit}").matcher("");
Matcher space = Pattern.compile("\\p{Space}").matcher("");
Matcher bound = Pattern.compile("\\b").matcher("");
Matcher word = Pattern.compile("\\w+").matcher("");
// UNICODE_CHARACTER_CLASS
Matcher lowerU = Pattern.compile("\\p{Lower}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher upperU = Pattern.compile("\\p{Upper}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher ASCIIU = Pattern.compile("\\p{ASCII}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher alphaU = Pattern.compile("\\p{Alpha}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher digitU = Pattern.compile("\\p{Digit}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher alnumU = Pattern.compile("\\p{Alnum}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher punctU = Pattern.compile("\\p{Punct}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher graphU = Pattern.compile("\\p{Graph}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher printU = Pattern.compile("\\p{Print}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher blankU = Pattern.compile("\\p{Blank}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher cntrlU = Pattern.compile("\\p{Cntrl}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher xdigitU = Pattern.compile("\\p{XDigit}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher spaceU = Pattern.compile("\\p{Space}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher boundU = Pattern.compile("\\b", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher wordU = Pattern.compile("\\w", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
// embedded flag (?U)
//Matcher lowerEU = Pattern.compile("(?U)\\p{Lower}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
//Matcher graphEU = Pattern.compile("(?U)\\p{Graph}", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
//Matcher wordEU = Pattern.compile("(?U)\\w", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
Matcher bwb = Pattern.compile("\\b\\w\\b").matcher("");
Matcher bwbU = Pattern.compile("\\b\\w+\\b", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
//Matcher bwbEU = Pattern.compile("(?U)\\b\\w+\\b", Pattern.UNICODE_CHARACTER_CLASS).matcher("");
// properties
/*
Matcher lowerP = Pattern.compile("\\p{IsLowerCase}").matcher("");
Matcher upperP = Pattern.compile("\\p{IsUpperCase}").matcher("");
Matcher titleP = Pattern.compile("\\p{IsTitleCase}").matcher("");
Matcher letterP = Pattern.compile("\\p{IsLetter}").matcher("");
Matcher alphaP = Pattern.compile("\\p{IsAlphabetic}").matcher("");
Matcher ideogP = Pattern.compile("\\p{IsIdeographic}").matcher("");
Matcher cntrlP = Pattern.compile("\\p{IsControl}").matcher("");
Matcher spaceP = Pattern.compile("\\p{IsWhiteSpace}").matcher("");
Matcher definedP = Pattern.compile("\\p{IsAssigned}").matcher("");
Matcher nonCCPP = Pattern.compile("\\p{IsNoncharacterCodePoint}").matcher("");
*/
// javaMethod
/*
Matcher lowerJ = Pattern.compile("\\p{javaLowerCase}").matcher("");
Matcher upperJ = Pattern.compile("\\p{javaUpperCase}").matcher("");
Matcher alphaJ = Pattern.compile("\\p{javaAlphabetic}").matcher("");
Matcher ideogJ = Pattern.compile("\\p{javaIdeographic}").matcher("");
*/
for (int cp = 1; cp < 0x30000; cp++) {
String str = new String(Character.toChars(cp));
int type = Character.getType(cp);
if (// lower
POSIX_ASCII.isLower(cp) != lower.reset(str).matches() ||
Character.isLowerCase(cp) != lowerU.reset(str).matches() ||
//Character.isLowerCase(cp) != lowerP.reset(str).matches() ||
//Character.isLowerCase(cp) != lowerEU.reset(str).matches()||
//Character.isLowerCase(cp) != lowerJ.reset(str).matches()||
// upper
POSIX_ASCII.isUpper(cp) != upper.reset(str).matches() ||
POSIX_Unicode.isUpper(cp) != upperU.reset(str).matches() ||
//Character.isUpperCase(cp) != upperP.reset(str).matches() ||
//Character.isUpperCase(cp) != upperJ.reset(str).matches() ||
// alpha
POSIX_ASCII.isAlpha(cp) != alpha.reset(str).matches() ||
POSIX_Unicode.isAlpha(cp) != alphaU.reset(str).matches() ||
//Character.isAlphabetic(cp)!= alphaP.reset(str).matches() ||
//Character.isAlphabetic(cp)!= alphaJ.reset(str).matches() ||
// digit
POSIX_ASCII.isDigit(cp) != digit.reset(str).matches() ||
Character.isDigit(cp) != digitU.reset(str).matches() ||
// alnum
POSIX_ASCII.isAlnum(cp) != alnum.reset(str).matches() ||
POSIX_Unicode.isAlnum(cp) != alnumU.reset(str).matches() ||
// punct
POSIX_ASCII.isPunct(cp) != punct.reset(str).matches() ||
POSIX_Unicode.isPunct(cp) != punctU.reset(str).matches() ||
// graph
POSIX_ASCII.isGraph(cp) != graph.reset(str).matches() ||
POSIX_Unicode.isGraph(cp) != graphU.reset(str).matches() ||
//POSIX_Unicode.isGraph(cp) != graphEU.reset(str).matches()||
// blank
POSIX_ASCII.isType(cp, POSIX_ASCII.BLANK)
!= blank.reset(str).matches() ||
POSIX_Unicode.isBlank(cp) != blankU.reset(str).matches() ||
// print
POSIX_ASCII.isPrint(cp) != print.reset(str).matches() ||
POSIX_Unicode.isPrint(cp) != printU.reset(str).matches() ||
// cntrl
POSIX_ASCII.isCntrl(cp) != cntrl.reset(str).matches() ||
POSIX_Unicode.isCntrl(cp) != cntrlU.reset(str).matches() ||
//(Character.CONTROL == type) != cntrlP.reset(str).matches() ||
// hexdigit
POSIX_ASCII.isHexDigit(cp) != xdigit.reset(str).matches() ||
POSIX_Unicode.isHexDigit(cp) != xdigitU.reset(str).matches() ||
// space
POSIX_ASCII.isSpace(cp) != space.reset(str).matches() ||
POSIX_Unicode.isSpace(cp) != spaceU.reset(str).matches() ||
//POSIX_Unicode.isSpace(cp) != spaceP.reset(str).matches() ||
// word
POSIX_ASCII.isWord(cp) != word.reset(str).matches() ||
POSIX_Unicode.isWord(cp) != wordU.reset(str).matches() ||
//POSIX_Unicode.isWord(cp) != wordEU.reset(str).matches()||
// bwordb
POSIX_ASCII.isWord(cp) != bwb.reset(str).matches() ||
POSIX_Unicode.isWord(cp) != bwbU.reset(str).matches() /*||
// properties
Character.isTitleCase(cp) != titleP.reset(str).matches() ||
Character.isLetter(cp) != letterP.reset(str).matches()||
Character.isIdeographic(cp) != ideogP.reset(str).matches() ||
Character.isIdeographic(cp) != ideogJ.reset(str).matches() ||
(Character.UNASSIGNED == type) == definedP.reset(str).matches() ||
POSIX_Unicode.isNoncharacterCodePoint(cp) != nonCCPP.reset(str).matches()*/)
failCount++;
}
// bounds/word align
twoFindIndexes(" \u0180sherman\u0400 ", bound, 1, 10);
if (!bwbU.reset("\u0180sherman\u0400").matches())
failCount++;
twoFindIndexes(" \u0180sh\u0345erman\u0400 ", bound, 1, 11);
if (!bwbU.reset("\u0180sh\u0345erman\u0400").matches())
failCount++;
twoFindIndexes(" \u0724\u0739\u0724 ", bound, 1, 4);
if (!bwbU.reset("\u0724\u0739\u0724").matches())
failCount++;
//if (!bwbEU.reset("\u0724\u0739\u0724").matches())
// failCount++;
report("unicodePredefinedClasses");
}
}
| {
"content_hash": "fec5381a0c8646f2ea3c67e7df26a076",
"timestamp": "",
"source": "github",
"line_count": 3809,
"max_line_length": 108,
"avg_line_length": 36.33342084536624,
"alnum_prop": 0.5331300489905632,
"repo_name": "tommyettinger/RegExodus",
"id": "bcbb084ef2fb022944ddffbfe971130326e03d15",
"size": "139606",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "etc/regexodus/test/regexodus/regex/RegExTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "955073"
},
{
"name": "JavaScript",
"bytes": "10691"
}
],
"symlink_target": ""
} |
import re
from enum import Enum
from knack.log import get_logger
from knack.util import CLIError
from msrestazure.azure_exceptions import CloudError
from azure.cli.core.azclierror import (
ArgumentUsageError,
BadRequestError,
InvalidArgumentValueError,
RequiredArgumentMissingError,
ResourceNotFoundError,
UnclassifiedUserFault
)
from azure.cli.core.commands import LongRunningOperation
from azure.cli.core.util import sdk_no_wait
from azure.cli.core.profiles._shared import AZURE_API_PROFILES, ResourceType
from azure.mgmt.iothub.models import (IotHubSku,
AccessRights,
ArmIdentity,
CertificateDescription,
CertificateProperties,
CertificateVerificationDescription,
CloudToDeviceProperties,
IotHubDescription,
IotHubSkuInfo,
SharedAccessSignatureAuthorizationRule,
IotHubProperties,
EventHubProperties,
EventHubConsumerGroupBodyDescription,
EventHubConsumerGroupName,
FailoverInput,
FeedbackProperties,
ManagedIdentity,
MessagingEndpointProperties,
OperationInputs,
EnrichmentProperties,
RoutingEventHubProperties,
RoutingServiceBusQueueEndpointProperties,
RoutingServiceBusTopicEndpointProperties,
RoutingStorageContainerProperties,
RouteProperties,
RoutingMessage,
StorageEndpointProperties,
TestRouteInput,
TestAllRoutesInput)
from azure.mgmt.iothubprovisioningservices.models import (CertificateBodyDescription,
ProvisioningServiceDescription,
IotDpsPropertiesDescription,
IotHubDefinitionDescription,
IotDpsSkuInfo,
IotDpsSku,
OperationInputs as DpsOperationInputs,
SharedAccessSignatureAuthorizationRuleAccessRightsDescription,
VerificationCodeRequest)
from azure.mgmt.iotcentral.models import (AppSkuInfo,
App)
from azure.cli.command_modules.iot._constants import SYSTEM_ASSIGNED_IDENTITY
from azure.cli.command_modules.iot.shared import EndpointType, EncodingFormat, RenewKeyType, AuthenticationType, IdentityType
from azure.cli.command_modules.iot._client_factory import resource_service_factory
from azure.cli.command_modules.iot._client_factory import iot_hub_service_factory
from azure.cli.command_modules.iot._utils import open_certificate, generate_key
logger = get_logger(__name__)
# Identity types
SYSTEM_ASSIGNED = 'SystemAssigned'
NONE_IDENTITY = 'None'
# CUSTOM TYPE
class KeyType(Enum):
primary = 'primary'
secondary = 'secondary'
# This is a work around to simplify the permission parameter for access policy creation, and also align with the other
# command modules.
# The original AccessRights enum is a combination of below four basic access rights.
# In order to avoid asking for comma- & space-separated strings from the user, a space-separated list is supported for
# assigning multiple permissions.
# The underlying IoT SDK should handle this. However it isn't right now. Remove this after it is fixed in IoT SDK.
class SimpleAccessRights(Enum):
registry_read = AccessRights.registry_read.value
registry_write = AccessRights.registry_write.value
service_connect = AccessRights.service_connect.value
device_connect = AccessRights.device_connect.value
# CUSTOM METHODS FOR DPS
def iot_dps_list(client, resource_group_name=None):
if resource_group_name is None:
return client.iot_dps_resource.list_by_subscription()
return client.iot_dps_resource.list_by_resource_group(resource_group_name)
def iot_dps_get(client, dps_name, resource_group_name=None):
if resource_group_name is None:
return _get_iot_dps_by_name(client, dps_name, resource_group_name)
return client.iot_dps_resource.get(dps_name, resource_group_name)
def iot_dps_create(cmd, client, dps_name, resource_group_name, location=None, sku=IotDpsSku.s1.value, unit=1, tags=None, enable_data_residency=None):
cli_ctx = cmd.cli_ctx
_check_dps_name_availability(client.iot_dps_resource, dps_name)
location = _ensure_location(cli_ctx, resource_group_name, location)
dps_property = IotDpsPropertiesDescription(enable_data_residency=enable_data_residency)
dps_description = ProvisioningServiceDescription(location=location,
properties=dps_property,
sku=IotDpsSkuInfo(name=sku, capacity=unit),
tags=tags)
return client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps_description)
def iot_dps_update(client, dps_name, parameters, resource_group_name=None, tags=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
if tags is not None:
parameters.tags = tags
return client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, parameters)
def iot_dps_delete(client, dps_name, resource_group_name=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
return client.iot_dps_resource.begin_delete(dps_name, resource_group_name)
# DPS policy methods
def iot_dps_policy_list(client, dps_name, resource_group_name=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
return client.iot_dps_resource.list_keys(dps_name, resource_group_name)
def iot_dps_policy_get(client, dps_name, access_policy_name, resource_group_name=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
return client.iot_dps_resource.list_keys_for_key_name(dps_name, access_policy_name, resource_group_name)
def iot_dps_policy_create(
cmd,
client,
dps_name,
access_policy_name,
rights,
resource_group_name=None,
primary_key=None,
secondary_key=None,
no_wait=False
):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
dps_access_policies = []
dps_access_policies.extend(iot_dps_policy_list(client, dps_name, resource_group_name))
if _does_policy_exist(dps_access_policies, access_policy_name):
raise BadRequestError("Access policy {} already exists.".format(access_policy_name))
dps = iot_dps_get(client, dps_name, resource_group_name)
access_policy_rights = _convert_rights_to_access_rights(rights)
dps_access_policies.append(SharedAccessSignatureAuthorizationRuleAccessRightsDescription(
key_name=access_policy_name, rights=access_policy_rights, primary_key=primary_key, secondary_key=secondary_key))
dps.properties.authorization_policies = dps_access_policies
if no_wait:
return client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps)
LongRunningOperation(cmd.cli_ctx)(client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps))
return iot_dps_policy_get(client, dps_name, access_policy_name, resource_group_name)
def iot_dps_policy_update(
cmd,
client,
dps_name,
access_policy_name,
resource_group_name=None,
primary_key=None,
secondary_key=None,
rights=None,
no_wait=False
):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
dps_access_policies = []
dps_access_policies.extend(iot_dps_policy_list(client, dps_name, resource_group_name))
if not _does_policy_exist(dps_access_policies, access_policy_name):
raise ResourceNotFoundError("Access policy {} doesn't exist.".format(access_policy_name))
for policy in dps_access_policies:
if policy.key_name == access_policy_name:
if primary_key is not None:
policy.primary_key = primary_key
if secondary_key is not None:
policy.secondary_key = secondary_key
if rights is not None:
policy.rights = _convert_rights_to_access_rights(rights)
dps = iot_dps_get(client, dps_name, resource_group_name)
dps.properties.authorization_policies = dps_access_policies
if no_wait:
return client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps)
LongRunningOperation(cmd.cli_ctx)(client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps))
return iot_dps_policy_get(client, dps_name, access_policy_name, resource_group_name)
def iot_dps_policy_delete(cmd, client, dps_name, access_policy_name, resource_group_name=None, no_wait=False):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
dps_access_policies = []
dps_access_policies.extend(iot_dps_policy_list(client, dps_name, resource_group_name))
if not _does_policy_exist(dps_access_policies, access_policy_name):
raise ResourceNotFoundError("Access policy {0} doesn't exist.".format(access_policy_name))
updated_policies = [p for p in dps_access_policies if p.key_name.lower() != access_policy_name.lower()]
dps = iot_dps_get(client, dps_name, resource_group_name)
dps.properties.authorization_policies = updated_policies
if no_wait:
return client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps)
LongRunningOperation(cmd.cli_ctx)(client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps))
return iot_dps_policy_list(client, dps_name, resource_group_name)
# DPS linked hub methods
def iot_dps_linked_hub_list(client, dps_name, resource_group_name=None):
dps = iot_dps_get(client, dps_name, resource_group_name)
return dps.properties.iot_hubs
def iot_dps_linked_hub_get(cmd, client, dps_name, linked_hub, resource_group_name=None):
if '.' not in linked_hub:
hub_client = iot_hub_service_factory(cmd.cli_ctx)
linked_hub = _get_iot_hub_hostname(hub_client, linked_hub)
dps = iot_dps_get(client, dps_name, resource_group_name)
for hub in dps.properties.iot_hubs:
if hub.name == linked_hub:
return hub
raise ResourceNotFoundError("Linked hub '{0}' does not exist. Use 'iot dps linked-hub show to see all linked hubs.".format(linked_hub))
def iot_dps_linked_hub_create(
cmd,
client,
dps_name,
hub_name=None,
hub_resource_group=None,
connection_string=None,
location=None,
resource_group_name=None,
apply_allocation_policy=None,
allocation_weight=None,
no_wait=False
):
if not any([connection_string, hub_name]):
raise RequiredArgumentMissingError("Please provide the IoT Hub name or connection string.")
if not connection_string:
# Get the connection string for the hub
hub_client = iot_hub_service_factory(cmd.cli_ctx)
connection_string = iot_hub_show_connection_string(
hub_client, hub_name=hub_name, resource_group_name=hub_resource_group
)['connectionString']
if not location:
# Parse out hub name from connection string if needed
if not hub_name:
try:
hub_name = re.search(r"hostname=(.[^\;\.]+)?", connection_string, re.IGNORECASE).group(1)
except AttributeError:
raise InvalidArgumentValueError("Please provide a valid IoT Hub connection string.")
hub_client = iot_hub_service_factory(cmd.cli_ctx)
location = iot_hub_get(cmd, hub_client, hub_name=hub_name, resource_group_name=hub_resource_group).location
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
dps = iot_dps_get(client, dps_name, resource_group_name)
dps.properties.iot_hubs.append(IotHubDefinitionDescription(connection_string=connection_string,
location=location,
apply_allocation_policy=apply_allocation_policy,
allocation_weight=allocation_weight))
if no_wait:
return client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps)
LongRunningOperation(cmd.cli_ctx)(client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps))
return iot_dps_linked_hub_list(client, dps_name, resource_group_name)
def iot_dps_linked_hub_update(cmd, client, dps_name, linked_hub, resource_group_name=None, apply_allocation_policy=None,
allocation_weight=None, no_wait=False):
if '.' not in linked_hub:
hub_client = iot_hub_service_factory(cmd.cli_ctx)
linked_hub = _get_iot_hub_hostname(hub_client, linked_hub)
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
dps_linked_hubs = []
dps_linked_hubs.extend(iot_dps_linked_hub_list(client, dps_name, resource_group_name))
if not _is_linked_hub_existed(dps_linked_hubs, linked_hub):
raise ResourceNotFoundError("Access policy {0} doesn't exist.".format(linked_hub))
for hub in dps_linked_hubs:
if hub.name == linked_hub:
if apply_allocation_policy is not None:
hub.apply_allocation_policy = apply_allocation_policy
if allocation_weight is not None:
hub.allocation_weight = allocation_weight
dps = iot_dps_get(client, dps_name, resource_group_name)
dps.properties.iot_hubs = dps_linked_hubs
if no_wait:
return client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps)
LongRunningOperation(cmd.cli_ctx)(client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps))
return iot_dps_linked_hub_get(cmd, client, dps_name, linked_hub, resource_group_name)
def iot_dps_linked_hub_delete(cmd, client, dps_name, linked_hub, resource_group_name=None, no_wait=False):
if '.' not in linked_hub:
hub_client = iot_hub_service_factory(cmd.cli_ctx)
linked_hub = _get_iot_hub_hostname(hub_client, linked_hub)
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
dps_linked_hubs = []
dps_linked_hubs.extend(iot_dps_linked_hub_list(client, dps_name, resource_group_name))
if not _is_linked_hub_existed(dps_linked_hubs, linked_hub):
raise ResourceNotFoundError("Linked hub {0} doesn't exist.".format(linked_hub))
updated_hubs = [p for p in dps_linked_hubs if p.name.lower() != linked_hub.lower()]
dps = iot_dps_get(client, dps_name, resource_group_name)
dps.properties.iot_hubs = updated_hubs
if no_wait:
return client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps)
LongRunningOperation(cmd.cli_ctx)(client.iot_dps_resource.begin_create_or_update(resource_group_name, dps_name, dps))
return iot_dps_linked_hub_list(client, dps_name, resource_group_name)
# DPS certificate methods
def iot_dps_certificate_list(client, dps_name, resource_group_name=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
return client.dps_certificate.list(resource_group_name, dps_name)
def iot_dps_certificate_get(client, dps_name, certificate_name, resource_group_name=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
return client.dps_certificate.get(certificate_name, resource_group_name, dps_name)
def iot_dps_certificate_create(client, dps_name, certificate_name, certificate_path, resource_group_name=None, is_verified=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
cert_list = client.dps_certificate.list(resource_group_name, dps_name)
for cert in cert_list.value:
if cert.name == certificate_name:
raise CLIError("Certificate '{0}' already exists. Use 'iot dps certificate update'"
" to update an existing certificate.".format(certificate_name))
certificate = open_certificate(certificate_path)
if not certificate:
raise CLIError("Error uploading certificate '{0}'.".format(certificate_path))
cert_description = CertificateBodyDescription(certificate=certificate, is_verified=is_verified)
return client.dps_certificate.create_or_update(resource_group_name, dps_name, certificate_name, cert_description)
def iot_dps_certificate_update(client, dps_name, certificate_name, certificate_path, etag, resource_group_name=None, is_verified=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
cert_list = client.dps_certificate.list(resource_group_name, dps_name)
for cert in cert_list.value:
if cert.name == certificate_name:
certificate = open_certificate(certificate_path)
if not certificate:
raise CLIError("Error uploading certificate '{0}'.".format(certificate_path))
cert_description = CertificateBodyDescription(certificate=certificate, is_verified=is_verified)
return client.dps_certificate.create_or_update(resource_group_name, dps_name, certificate_name, cert_description, etag)
raise CLIError("Certificate '{0}' does not exist. Use 'iot dps certificate create' to create a new certificate."
.format(certificate_name))
def iot_dps_certificate_delete(client, dps_name, certificate_name, etag, resource_group_name=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
return client.dps_certificate.delete(resource_group_name, etag, dps_name, certificate_name)
def iot_dps_certificate_gen_code(client, dps_name, certificate_name, etag, resource_group_name=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
return client.dps_certificate.generate_verification_code(certificate_name, etag, resource_group_name, dps_name)
def iot_dps_certificate_verify(client, dps_name, certificate_name, certificate_path, etag, resource_group_name=None):
resource_group_name = _ensure_dps_resource_group_name(client, resource_group_name, dps_name)
certificate = open_certificate(certificate_path)
if not certificate:
raise CLIError("Error uploading certificate '{0}'.".format(certificate_path))
request = VerificationCodeRequest(certificate=certificate)
return client.dps_certificate.verify_certificate(certificate_name, etag, resource_group_name, dps_name, request)
# CUSTOM METHODS
def iot_hub_certificate_list(client, hub_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.certificates.list_by_iot_hub(resource_group_name, hub_name)
def iot_hub_certificate_get(client, hub_name, certificate_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.certificates.get(resource_group_name, hub_name, certificate_name)
def iot_hub_certificate_create(client, hub_name, certificate_name, certificate_path, resource_group_name=None, is_verified=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
# Get list of certs
cert_list = client.certificates.list_by_iot_hub(resource_group_name, hub_name)
for cert in cert_list.value:
if cert.name == certificate_name:
raise CLIError("Certificate '{0}' already exists. Use 'iot hub certificate update'"
" to update an existing certificate.".format(certificate_name))
certificate = open_certificate(certificate_path)
if not certificate:
raise CLIError("Error uploading certificate '{0}'.".format(certificate_path))
cert_properties = CertificateProperties(certificate=certificate, is_verified=is_verified)
if AZURE_API_PROFILES["latest"][ResourceType.MGMT_IOTHUB] in client.profile.label:
cert_description = CertificateDescription(properties=cert_properties)
return client.certificates.create_or_update(resource_group_name, hub_name, certificate_name, cert_description)
return client.certificates.create_or_update(resource_group_name, hub_name, certificate_name, cert_properties)
def iot_hub_certificate_update(client, hub_name, certificate_name, certificate_path, etag, resource_group_name=None, is_verified=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
cert_list = client.certificates.list_by_iot_hub(resource_group_name, hub_name)
for cert in cert_list.value:
if cert.name == certificate_name:
certificate = open_certificate(certificate_path)
if not certificate:
raise CLIError("Error uploading certificate '{0}'.".format(certificate_path))
cert_properties = CertificateProperties(certificate=certificate, is_verified=is_verified)
if AZURE_API_PROFILES["latest"][ResourceType.MGMT_IOTHUB] in client.profile.label:
cert_description = CertificateDescription(properties=cert_properties)
return client.certificates.create_or_update(resource_group_name, hub_name, certificate_name, cert_description, etag)
return client.certificates.create_or_update(resource_group_name, hub_name, certificate_name, cert_properties, etag)
raise CLIError("Certificate '{0}' does not exist. Use 'iot hub certificate create' to create a new certificate."
.format(certificate_name))
def iot_hub_certificate_delete(client, hub_name, certificate_name, etag, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.certificates.delete(resource_group_name, hub_name, certificate_name, etag)
def iot_hub_certificate_gen_code(client, hub_name, certificate_name, etag, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.certificates.generate_verification_code(resource_group_name, hub_name, certificate_name, etag)
def iot_hub_certificate_verify(client, hub_name, certificate_name, certificate_path, etag, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
certificate = open_certificate(certificate_path)
if not certificate:
raise CLIError("Error uploading certificate '{0}'.".format(certificate_path))
certificate_verify_body = CertificateVerificationDescription(certificate=certificate)
return client.certificates.verify(resource_group_name, hub_name, certificate_name, etag, certificate_verify_body)
def iot_hub_create(cmd, client, hub_name, resource_group_name, location=None,
sku=IotHubSku.s1.value,
unit=1,
partition_count=4,
retention_day=1,
c2d_ttl=1,
c2d_max_delivery_count=10,
disable_local_auth=None,
disable_device_sas=None,
disable_module_sas=None,
enable_data_residency=None,
feedback_lock_duration=5,
feedback_ttl=1,
feedback_max_delivery_count=10,
enable_fileupload_notifications=False,
fileupload_notification_lock_duration=5,
fileupload_notification_max_delivery_count=10,
fileupload_notification_ttl=1,
fileupload_storage_connectionstring=None,
fileupload_storage_container_name=None,
fileupload_sas_ttl=1,
fileupload_storage_authentication_type=None,
fileupload_storage_container_uri=None,
fileupload_storage_identity=None,
min_tls_version=None,
tags=None,
system_identity=None,
user_identities=None,
identity_role=None,
identity_scopes=None):
from datetime import timedelta
cli_ctx = cmd.cli_ctx
if enable_fileupload_notifications:
if not fileupload_storage_connectionstring or not fileupload_storage_container_name:
raise RequiredArgumentMissingError('Please specify storage endpoint (storage connection string and storage container name).')
if fileupload_storage_connectionstring and not fileupload_storage_container_name:
raise RequiredArgumentMissingError('Please mention storage container name.')
if fileupload_storage_container_name and not fileupload_storage_connectionstring:
raise RequiredArgumentMissingError('Please mention storage connection string.')
identity_based_file_upload = fileupload_storage_authentication_type and fileupload_storage_authentication_type == AuthenticationType.IdentityBased.value
if not identity_based_file_upload and fileupload_storage_identity:
raise RequiredArgumentMissingError('In order to set a fileupload storage identity, please set file upload storage authentication (--fsa) to IdentityBased')
if identity_based_file_upload or fileupload_storage_identity:
# Not explicitly setting fileupload_storage_identity assumes system-assigned managed identity for file upload
if fileupload_storage_identity in [None, SYSTEM_ASSIGNED_IDENTITY] and not system_identity:
raise ArgumentUsageError('System managed identity [--mi-system-assigned] must be enabled in order to use managed identity for file upload')
if fileupload_storage_identity and fileupload_storage_identity != SYSTEM_ASSIGNED_IDENTITY and not user_identities:
raise ArgumentUsageError('User identity [--mi-user-assigned] must be added in order to use it for file upload')
location = _ensure_location(cli_ctx, resource_group_name, location)
sku = IotHubSkuInfo(name=sku, capacity=unit)
event_hub_dic = {}
event_hub_dic['events'] = EventHubProperties(retention_time_in_days=retention_day,
partition_count=partition_count)
feedback_Properties = FeedbackProperties(lock_duration_as_iso8601=timedelta(seconds=feedback_lock_duration),
ttl_as_iso8601=timedelta(hours=feedback_ttl),
max_delivery_count=feedback_max_delivery_count)
cloud_to_device_properties = CloudToDeviceProperties(max_delivery_count=c2d_max_delivery_count,
default_ttl_as_iso8601=timedelta(hours=c2d_ttl),
feedback=feedback_Properties)
msg_endpoint_dic = {}
msg_endpoint_dic['fileNotifications'] = MessagingEndpointProperties(max_delivery_count=fileupload_notification_max_delivery_count,
ttl_as_iso8601=timedelta(hours=fileupload_notification_ttl),
lock_duration_as_iso8601=timedelta(seconds=fileupload_notification_lock_duration))
storage_endpoint_dic = {}
storage_endpoint_dic['$default'] = StorageEndpointProperties(
sas_ttl_as_iso8601=timedelta(hours=fileupload_sas_ttl),
connection_string=fileupload_storage_connectionstring if fileupload_storage_connectionstring else '',
container_name=fileupload_storage_container_name if fileupload_storage_container_name else '',
authentication_type=fileupload_storage_authentication_type if fileupload_storage_authentication_type else None,
container_uri=fileupload_storage_container_uri if fileupload_storage_container_uri else '',
identity=ManagedIdentity(user_assigned_identity=fileupload_storage_identity) if fileupload_storage_identity else None)
properties = IotHubProperties(event_hub_endpoints=event_hub_dic,
messaging_endpoints=msg_endpoint_dic,
storage_endpoints=storage_endpoint_dic,
cloud_to_device=cloud_to_device_properties,
min_tls_version=min_tls_version,
enable_data_residency=enable_data_residency,
disable_local_auth=disable_local_auth,
disable_device_sas=disable_device_sas,
disable_module_sas=disable_module_sas)
properties.enable_file_upload_notifications = enable_fileupload_notifications
hub_description = IotHubDescription(location=location,
sku=sku,
properties=properties,
tags=tags)
if (system_identity or user_identities):
hub_description.identity = _build_identity(system=bool(system_identity), identities=user_identities)
if bool(identity_role) ^ bool(identity_scopes):
raise RequiredArgumentMissingError('At least one scope (--scopes) and one role (--role) required for system-assigned managed identity role assignment')
def identity_assignment(lro):
try:
from azure.cli.core.commands.arm import assign_identity
instance = lro.resource().as_dict()
identity = instance.get("identity")
if identity:
principal_id = identity.get("principal_id")
if principal_id:
hub_description.identity.principal_id = principal_id
for scope in identity_scopes:
assign_identity(cmd.cli_ctx, lambda: hub_description, lambda hub: hub_description, identity_role=identity_role, identity_scope=scope)
except CloudError as e:
raise e
create = client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub_description, polling=True)
if identity_role and identity_scopes:
create.add_done_callback(identity_assignment)
return create
def iot_hub_get(cmd, client, hub_name, resource_group_name=None):
cli_ctx = cmd.cli_ctx
if resource_group_name is None:
return _get_iot_hub_by_name(client, hub_name)
if not _ensure_resource_group_existence(cli_ctx, resource_group_name):
raise CLIError("Resource group '{0}' could not be found.".format(resource_group_name))
name_availability = client.iot_hub_resource.check_name_availability(OperationInputs(name=hub_name))
if name_availability is not None and name_availability.name_available:
raise CLIError("An IotHub '{0}' under resource group '{1}' was not found."
.format(hub_name, resource_group_name))
return client.iot_hub_resource.get(resource_group_name, hub_name)
def iot_hub_list(client, resource_group_name=None):
if resource_group_name is None:
return client.iot_hub_resource.list_by_subscription()
return client.iot_hub_resource.list_by_resource_group(resource_group_name)
def update_iot_hub_custom(instance,
sku=None,
unit=None,
retention_day=None,
c2d_ttl=None,
c2d_max_delivery_count=None,
disable_local_auth=None,
disable_device_sas=None,
disable_module_sas=None,
feedback_lock_duration=None,
feedback_ttl=None,
feedback_max_delivery_count=None,
enable_fileupload_notifications=None,
fileupload_notification_lock_duration=None,
fileupload_notification_max_delivery_count=None,
fileupload_notification_ttl=None,
fileupload_storage_connectionstring=None,
fileupload_storage_container_name=None,
fileupload_sas_ttl=None,
fileupload_storage_authentication_type=None,
fileupload_storage_container_uri=None,
fileupload_storage_identity=None,
tags=None):
from datetime import timedelta
if tags is not None:
instance.tags = tags
if sku is not None:
instance.sku.name = sku
if unit is not None:
instance.sku.capacity = unit
if retention_day is not None:
instance.properties.event_hub_endpoints['events'].retention_time_in_days = retention_day
if c2d_ttl is not None:
instance.properties.cloud_to_device.default_ttl_as_iso8601 = timedelta(hours=c2d_ttl)
if c2d_max_delivery_count is not None:
instance.properties.cloud_to_device.max_delivery_count = c2d_max_delivery_count
if feedback_lock_duration is not None:
duration = timedelta(seconds=feedback_lock_duration)
instance.properties.cloud_to_device.feedback.lock_duration_as_iso8601 = duration
if feedback_ttl is not None:
instance.properties.cloud_to_device.feedback.ttl_as_iso8601 = timedelta(hours=feedback_ttl)
if feedback_max_delivery_count is not None:
instance.properties.cloud_to_device.feedback.max_delivery_count = feedback_max_delivery_count
if enable_fileupload_notifications is not None:
instance.properties.enable_file_upload_notifications = enable_fileupload_notifications
if fileupload_notification_lock_duration is not None:
lock_duration = timedelta(seconds=fileupload_notification_lock_duration)
instance.properties.messaging_endpoints['fileNotifications'].lock_duration_as_iso8601 = lock_duration
if fileupload_notification_max_delivery_count is not None:
count = fileupload_notification_max_delivery_count
instance.properties.messaging_endpoints['fileNotifications'].max_delivery_count = count
if fileupload_notification_ttl is not None:
ttl = timedelta(hours=fileupload_notification_ttl)
instance.properties.messaging_endpoints['fileNotifications'].ttl_as_iso8601 = ttl
# only bother with $default storage endpoint checking if modifying fileupload params
if any([
fileupload_storage_connectionstring, fileupload_storage_container_name, fileupload_sas_ttl,
fileupload_storage_authentication_type, fileupload_storage_container_uri, fileupload_storage_identity]):
default_storage_endpoint = instance.properties.storage_endpoints.get('$default', None)
# no default storage endpoint, either recreate with existing params or throw an error
if not default_storage_endpoint:
if not all([fileupload_storage_connectionstring, fileupload_storage_container_name]):
raise UnclassifiedUserFault('This hub has no default storage endpoint for file upload.\n'
'Please recreate your default storage endpoint by running '
'`az iot hub update --name {hub_name} --fcs {storage_connection_string} --fc {storage_container_name}`')
default_storage_endpoint = StorageEndpointProperties(container_name=fileupload_storage_container_name, connection_string=fileupload_storage_connectionstring)
# if setting a fileupload storage identity or changing fileupload to identity-based
if fileupload_storage_identity or fileupload_storage_authentication_type == AuthenticationType.IdentityBased.value:
_validate_fileupload_identity(instance, fileupload_storage_identity)
instance.properties.storage_endpoints['$default'] = _process_fileupload_args(
default_storage_endpoint,
fileupload_storage_connectionstring,
fileupload_storage_container_name,
fileupload_sas_ttl,
fileupload_storage_authentication_type,
fileupload_storage_container_uri,
fileupload_storage_identity,
)
# sas token authentication switches
if disable_local_auth is not None:
instance.properties.disable_local_auth = disable_local_auth
if disable_device_sas is not None:
instance.properties.disable_device_sas = disable_device_sas
if disable_module_sas is not None:
instance.properties.disable_module_sas = disable_module_sas
return instance
def iot_hub_update(client, hub_name, parameters, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, parameters, {'IF-MATCH': parameters.etag}, polling=True)
def iot_hub_delete(client, hub_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.begin_delete(resource_group_name, hub_name, polling=True)
# pylint: disable=inconsistent-return-statements
def iot_hub_show_connection_string(client, hub_name=None, resource_group_name=None, policy_name='iothubowner',
key_type=KeyType.primary.value, show_all=False):
if hub_name is None:
hubs = iot_hub_list(client, resource_group_name)
if hubs is None:
raise CLIError("No IoT Hub found.")
def conn_str_getter(h):
return _get_hub_connection_string(client, h.name, h.additional_properties['resourcegroup'], policy_name, key_type, show_all)
return [{'name': h.name, 'connectionString': conn_str_getter(h)} for h in hubs]
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
conn_str = _get_hub_connection_string(client, hub_name, resource_group_name, policy_name, key_type, show_all)
return {'connectionString': conn_str if show_all else conn_str[0]}
def _get_hub_connection_string(client, hub_name, resource_group_name, policy_name, key_type, show_all):
policies = []
if show_all:
policies.extend(iot_hub_policy_list(client, hub_name, resource_group_name))
else:
policies.append(iot_hub_policy_get(client, hub_name, policy_name, resource_group_name))
hostname = _get_iot_hub_hostname(client, hub_name)
conn_str_template = 'HostName={};SharedAccessKeyName={};SharedAccessKey={}'
return [conn_str_template.format(hostname,
p.key_name,
p.secondary_key if key_type == KeyType.secondary else p.primary_key) for p in policies]
def iot_hub_sku_list(client, hub_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.get_valid_skus(resource_group_name, hub_name)
def iot_hub_consumer_group_create(client, hub_name, consumer_group_name, resource_group_name=None, event_hub_name='events'):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
consumer_group_body = EventHubConsumerGroupBodyDescription(properties=EventHubConsumerGroupName(name=consumer_group_name))
# Fix for breaking change argument in track 1 SDK method.
from azure.cli.core.util import get_arg_list
create_cg_op = client.iot_hub_resource.create_event_hub_consumer_group
if "consumer_group_body" not in get_arg_list(create_cg_op):
return create_cg_op(resource_group_name, hub_name, event_hub_name, consumer_group_name)
return create_cg_op(resource_group_name, hub_name, event_hub_name, consumer_group_name, consumer_group_body=consumer_group_body)
def iot_hub_consumer_group_list(client, hub_name, resource_group_name=None, event_hub_name='events'):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.list_event_hub_consumer_groups(resource_group_name, hub_name, event_hub_name)
def iot_hub_consumer_group_get(client, hub_name, consumer_group_name, resource_group_name=None, event_hub_name='events'):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.get_event_hub_consumer_group(resource_group_name, hub_name, event_hub_name, consumer_group_name)
def iot_hub_consumer_group_delete(client, hub_name, consumer_group_name, resource_group_name=None, event_hub_name='events'):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.delete_event_hub_consumer_group(resource_group_name, hub_name, event_hub_name, consumer_group_name)
def iot_hub_identity_assign(cmd, client, hub_name, system_identity=None, user_identities=None, identity_role=None, identity_scopes=None, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
def getter():
return iot_hub_get(cmd, client, hub_name, resource_group_name)
def setter(hub):
if user_identities and not hub.identity.user_assigned_identities:
hub.identity.user_assigned_identities = {}
if user_identities:
for identity in user_identities:
hub.identity.user_assigned_identities[identity] = hub.identity.user_assigned_identities.get(identity, {}) if hub.identity.user_assigned_identities else {}
has_system_identity = hub.identity.type in [IdentityType.system_assigned_user_assigned.value, IdentityType.system_assigned.value]
if system_identity or has_system_identity:
hub.identity.type = IdentityType.system_assigned_user_assigned.value if hub.identity.user_assigned_identities else IdentityType.system_assigned.value
else:
hub.identity.type = IdentityType.user_assigned.value if hub.identity.user_assigned_identities else IdentityType.none.value
poller = client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
return LongRunningOperation(cmd.cli_ctx)(poller)
if bool(identity_role) ^ bool(identity_scopes):
raise RequiredArgumentMissingError('At least one scope (--scopes) and one role (--role) required for system-managed identity role assignment.')
if not system_identity and not user_identities:
raise RequiredArgumentMissingError('No identities provided to assign. Please provide system (--system) or user-assigned identities (--user).')
if identity_role and identity_scopes:
from azure.cli.core.commands.arm import assign_identity
for scope in identity_scopes:
hub = assign_identity(cmd.cli_ctx, getter, setter, identity_role=identity_role, identity_scope=scope)
return hub.identity
result = setter(getter())
return result.identity
def iot_hub_identity_show(cmd, client, hub_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
return hub.identity
def iot_hub_identity_remove(cmd, client, hub_name, system_identity=None, user_identities=None, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
hub_identity = hub.identity
if not system_identity and user_identities is None:
raise RequiredArgumentMissingError('No identities provided to remove. Please provide system (--system) or user-assigned identities (--user).')
# Turn off system managed identity
if system_identity:
if hub_identity.type not in [
IdentityType.system_assigned.value,
IdentityType.system_assigned_user_assigned.value
]:
raise ArgumentUsageError('Hub {} is not currently using a system-assigned identity'.format(hub_name))
hub_identity.type = IdentityType.user_assigned if hub.identity.type in [IdentityType.user_assigned.value, IdentityType.system_assigned_user_assigned.value] else IdentityType.none.value
if user_identities:
# loop through user_identities to remove
for identity in user_identities:
if not hub_identity.user_assigned_identities[identity]:
raise ArgumentUsageError('Hub {0} is not currently using a user-assigned identity with id: {1}'.format(hub_name, identity))
del hub_identity.user_assigned_identities[identity]
if not hub_identity.user_assigned_identities:
del hub_identity.user_assigned_identities
elif isinstance(user_identities, list):
del hub_identity.user_assigned_identities
if hub_identity.type in [
IdentityType.system_assigned.value,
IdentityType.system_assigned_user_assigned.value
]:
hub_identity.type = IdentityType.system_assigned_user_assigned.value if getattr(hub_identity, 'user_assigned_identities', None) else IdentityType.system_assigned.value
else:
hub_identity.type = IdentityType.user_assigned.value if getattr(hub_identity, 'user_assigned_identities', None) else IdentityType.none.value
hub.identity = hub_identity
if not getattr(hub.identity, 'user_assigned_identities', None):
hub.identity.user_assigned_identities = None
poller = client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
lro = LongRunningOperation(cmd.cli_ctx)(poller)
return lro.identity
def iot_hub_policy_list(client, hub_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.list_keys(resource_group_name, hub_name)
def iot_hub_policy_get(client, hub_name, policy_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.get_keys_for_key_name(resource_group_name, hub_name, policy_name)
def iot_hub_policy_create(cmd, client, hub_name, policy_name, permissions, resource_group_name=None):
rights = _convert_perms_to_access_rights(permissions)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
policies = []
policies.extend(iot_hub_policy_list(client, hub_name, hub.additional_properties['resourcegroup']))
if _does_policy_exist(policies, policy_name):
raise CLIError("Policy {0} already existed.".format(policy_name))
policies.append(SharedAccessSignatureAuthorizationRule(key_name=policy_name, rights=rights))
hub.properties.authorization_policies = policies
return client.iot_hub_resource.begin_create_or_update(hub.additional_properties['resourcegroup'], hub_name, hub, {'IF-MATCH': hub.etag})
def iot_hub_policy_delete(cmd, client, hub_name, policy_name, resource_group_name=None):
import copy
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
policies = iot_hub_policy_list(client, hub_name, hub.additional_properties['resourcegroup'])
if not _does_policy_exist(copy.deepcopy(policies), policy_name):
raise CLIError("Policy {0} not found.".format(policy_name))
updated_policies = [p for p in policies if p.key_name.lower() != policy_name.lower()]
hub.properties.authorization_policies = updated_policies
return client.iot_hub_resource.begin_create_or_update(hub.additional_properties['resourcegroup'], hub_name, hub, {'IF-MATCH': hub.etag})
def iot_hub_policy_key_renew(cmd, client, hub_name, policy_name, regenerate_key, resource_group_name=None, no_wait=False):
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
policies = []
policies.extend(iot_hub_policy_list(client, hub_name, hub.additional_properties['resourcegroup']))
if not _does_policy_exist(policies, policy_name):
raise CLIError("Policy {0} not found.".format(policy_name))
updated_policies = [p for p in policies if p.key_name.lower() != policy_name.lower()]
requested_policy = [p for p in policies if p.key_name.lower() == policy_name.lower()]
if regenerate_key == RenewKeyType.Primary.value:
requested_policy[0].primary_key = generate_key()
if regenerate_key == RenewKeyType.Secondary.value:
requested_policy[0].secondary_key = generate_key()
if regenerate_key == RenewKeyType.Swap.value:
temp = requested_policy[0].primary_key
requested_policy[0].primary_key = requested_policy[0].secondary_key
requested_policy[0].secondary_key = temp
updated_policies.append(SharedAccessSignatureAuthorizationRule(key_name=requested_policy[0].key_name,
rights=requested_policy[0].rights,
primary_key=requested_policy[0].primary_key,
secondary_key=requested_policy[0].secondary_key))
hub.properties.authorization_policies = updated_policies
if no_wait:
return client.iot_hub_resource.begin_create_or_update(hub.additional_properties['resourcegroup'], hub_name, hub, {'IF-MATCH': hub.etag})
LongRunningOperation(cmd.cli_ctx)(client.iot_hub_resource.begin_create_or_update(hub.additional_properties['resourcegroup'], hub_name, hub, {'IF-MATCH': hub.etag}))
return iot_hub_policy_get(client, hub_name, policy_name, resource_group_name)
def _does_policy_exist(policies, policy_name):
policy_set = {p.key_name.lower() for p in policies}
return policy_name.lower() in policy_set
def iot_hub_get_quota_metrics(client, hub_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
iotHubQuotaMetricCollection = []
iotHubQuotaMetricCollection.extend(client.iot_hub_resource.get_quota_metrics(resource_group_name, hub_name))
for quotaMetric in iotHubQuotaMetricCollection:
if quotaMetric.name == 'TotalDeviceCount':
quotaMetric.max_value = 'Unlimited'
return iotHubQuotaMetricCollection
def iot_hub_get_stats(client, hub_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
return client.iot_hub_resource.get_stats(resource_group_name, hub_name)
def validate_authentication_type_input(endpoint_type, connection_string=None, authentication_type=None, endpoint_uri=None, entity_path=None):
is_keyBased = (AuthenticationType.KeyBased.value == authentication_type) or (authentication_type is None)
has_connection_string = (connection_string is not None)
if is_keyBased and not has_connection_string:
raise CLIError("Please provide a connection string '--connection-string/-c'")
has_endpoint_uri = (endpoint_uri is not None)
has_endpoint_uri_and_path = (has_endpoint_uri) and (entity_path is not None)
if EndpointType.AzureStorageContainer.value == endpoint_type.lower() and not has_endpoint_uri:
raise CLIError("Please provide an endpoint uri '--endpoint-uri'")
if not has_endpoint_uri_and_path:
raise CLIError("Please provide an endpoint uri '--endpoint-uri' and entity path '--entity-path'")
def iot_hub_routing_endpoint_create(cmd, client, hub_name, endpoint_name, endpoint_type,
endpoint_resource_group, endpoint_subscription_id,
connection_string=None, container_name=None, encoding=None,
resource_group_name=None, batch_frequency=300, chunk_size_window=300,
file_name_format='{iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}',
authentication_type=None, endpoint_uri=None, entity_path=None,
identity=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
if identity and authentication_type != AuthenticationType.IdentityBased.value:
raise ArgumentUsageError("In order to use an identity for authentication, you must select --auth-type as 'identityBased'")
if EndpointType.EventHub.value == endpoint_type.lower():
hub.properties.routing.endpoints.event_hubs.append(
RoutingEventHubProperties(
connection_string=connection_string,
name=endpoint_name,
subscription_id=endpoint_subscription_id,
resource_group=endpoint_resource_group,
authentication_type=authentication_type,
endpoint_uri=endpoint_uri,
entity_path=entity_path,
identity=ManagedIdentity(user_assigned_identity=identity) if identity and identity not in [IdentityType.none.value, SYSTEM_ASSIGNED_IDENTITY] else None
)
)
elif EndpointType.ServiceBusQueue.value == endpoint_type.lower():
hub.properties.routing.endpoints.service_bus_queues.append(
RoutingServiceBusQueueEndpointProperties(
connection_string=connection_string,
name=endpoint_name,
subscription_id=endpoint_subscription_id,
resource_group=endpoint_resource_group,
authentication_type=authentication_type,
endpoint_uri=endpoint_uri,
entity_path=entity_path,
identity=ManagedIdentity(user_assigned_identity=identity) if identity and identity not in [IdentityType.none.value, SYSTEM_ASSIGNED_IDENTITY] else None
)
)
elif EndpointType.ServiceBusTopic.value == endpoint_type.lower():
hub.properties.routing.endpoints.service_bus_topics.append(
RoutingServiceBusTopicEndpointProperties(
connection_string=connection_string,
name=endpoint_name,
subscription_id=endpoint_subscription_id,
resource_group=endpoint_resource_group,
authentication_type=authentication_type,
endpoint_uri=endpoint_uri,
entity_path=entity_path,
identity=ManagedIdentity(user_assigned_identity=identity) if identity and identity not in [IdentityType.none.value, SYSTEM_ASSIGNED_IDENTITY] else None
)
)
elif EndpointType.AzureStorageContainer.value == endpoint_type.lower():
if not container_name:
raise CLIError("Container name is required.")
hub.properties.routing.endpoints.storage_containers.append(
RoutingStorageContainerProperties(
connection_string=connection_string,
name=endpoint_name,
subscription_id=endpoint_subscription_id,
resource_group=endpoint_resource_group,
container_name=container_name,
encoding=encoding.lower() if encoding else EncodingFormat.AVRO.value,
file_name_format=file_name_format,
batch_frequency_in_seconds=batch_frequency,
max_chunk_size_in_bytes=(chunk_size_window * 1048576),
authentication_type=authentication_type,
endpoint_uri=endpoint_uri,
identity=ManagedIdentity(user_assigned_identity=identity) if identity and identity not in [IdentityType.none.value, SYSTEM_ASSIGNED_IDENTITY] else None
)
)
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
def iot_hub_routing_endpoint_list(cmd, client, hub_name, endpoint_type=None, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
if not endpoint_type:
return hub.properties.routing.endpoints
if EndpointType.EventHub.value == endpoint_type.lower():
return hub.properties.routing.endpoints.event_hubs
if EndpointType.ServiceBusQueue.value == endpoint_type.lower():
return hub.properties.routing.endpoints.service_bus_queues
if EndpointType.ServiceBusTopic.value == endpoint_type.lower():
return hub.properties.routing.endpoints.service_bus_topics
if EndpointType.AzureStorageContainer.value == endpoint_type.lower():
return hub.properties.routing.endpoints.storage_containers
def iot_hub_routing_endpoint_show(cmd, client, hub_name, endpoint_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
for event_hub in hub.properties.routing.endpoints.event_hubs:
if event_hub.name.lower() == endpoint_name.lower():
return event_hub
for service_bus_queue in hub.properties.routing.endpoints.service_bus_queues:
if service_bus_queue.name.lower() == endpoint_name.lower():
return service_bus_queue
for service_bus_topic in hub.properties.routing.endpoints.service_bus_topics:
if service_bus_topic.name.lower() == endpoint_name.lower():
return service_bus_topic
for storage_container in hub.properties.routing.endpoints.storage_containers:
if storage_container.name.lower() == endpoint_name.lower():
return storage_container
raise CLIError("No endpoint found.")
def iot_hub_routing_endpoint_delete(cmd, client, hub_name, endpoint_name=None, endpoint_type=None, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
hub.properties.routing.endpoints = _delete_routing_endpoints(endpoint_name, endpoint_type, hub.properties.routing.endpoints)
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
def iot_hub_route_create(cmd, client, hub_name, route_name, source_type, endpoint_name, enabled=None, condition=None,
resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
hub.properties.routing.routes.append(
RouteProperties(
source=source_type,
name=route_name,
endpoint_names=endpoint_name.split(),
condition=('true' if condition is None else condition),
is_enabled=(True if enabled is None else enabled)
)
)
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
def iot_hub_route_list(cmd, client, hub_name, source_type=None, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
if source_type:
return [route for route in hub.properties.routing.routes if route.source.lower() == source_type.lower()]
return hub.properties.routing.routes
def iot_hub_route_show(cmd, client, hub_name, route_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
for route in hub.properties.routing.routes:
if route.name.lower() == route_name.lower():
return route
raise CLIError("No route found.")
def iot_hub_route_delete(cmd, client, hub_name, route_name=None, source_type=None, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
if not route_name and not source_type:
hub.properties.routing.routes = []
if route_name:
hub.properties.routing.routes = [route for route in hub.properties.routing.routes
if route.name.lower() != route_name.lower()]
if source_type:
hub.properties.routing.routes = [route for route in hub.properties.routing.routes
if route.source.lower() != source_type.lower()]
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
def iot_hub_route_update(cmd, client, hub_name, route_name, source_type=None, endpoint_name=None, enabled=None,
condition=None, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
updated_route = next((route for route in hub.properties.routing.routes
if route.name.lower() == route_name.lower()), None)
if updated_route:
updated_route.source = updated_route.source if source_type is None else source_type
updated_route.endpoint_names = updated_route.endpoint_names if endpoint_name is None else endpoint_name.split()
updated_route.condition = updated_route.condition if condition is None else condition
updated_route.is_enabled = updated_route.is_enabled if enabled is None else enabled
else:
raise CLIError("No route found.")
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
def iot_hub_route_test(cmd, client, hub_name, route_name=None, source_type=None, body=None, app_properties=None,
system_properties=None, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
route_message = RoutingMessage(
body=body,
app_properties=app_properties,
system_properties=system_properties
)
if route_name:
route = iot_hub_route_show(cmd, client, hub_name, route_name, resource_group_name)
test_route_input = TestRouteInput(
message=route_message,
twin=None,
route=route
)
return client.iot_hub_resource.test_route(hub_name, resource_group_name, test_route_input)
test_all_routes_input = TestAllRoutesInput(
routing_source=source_type,
message=route_message,
twin=None
)
return client.iot_hub_resource.test_all_routes(hub_name, resource_group_name, test_all_routes_input)
def iot_message_enrichment_create(cmd, client, hub_name, key, value, endpoints, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
if hub.properties.routing.enrichments is None:
hub.properties.routing.enrichments = []
hub.properties.routing.enrichments.append(EnrichmentProperties(key=key, value=value, endpoint_names=endpoints))
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
def iot_message_enrichment_update(cmd, client, hub_name, key, value, endpoints, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
to_update = next((endpoint for endpoint in hub.properties.routing.enrichments if endpoint.key == key), None)
if to_update:
to_update.key = key
to_update.value = value
to_update.endpoint_names = endpoints
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
raise CLIError('No message enrichment with that key exists')
def iot_message_enrichment_delete(cmd, client, hub_name, key, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
to_remove = next((endpoint for endpoint in hub.properties.routing.enrichments if endpoint.key == key), None)
if to_remove:
hub.properties.routing.enrichments.remove(to_remove)
return client.iot_hub_resource.begin_create_or_update(resource_group_name, hub_name, hub, {'IF-MATCH': hub.etag})
raise CLIError('No message enrichment with that key exists')
def iot_message_enrichment_list(cmd, client, hub_name, resource_group_name=None):
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
return hub.properties.routing.enrichments
def iot_hub_devicestream_show(cmd, client, hub_name, resource_group_name=None):
from azure.cli.core.commands.client_factory import get_mgmt_service_client
resource_group_name = _ensure_hub_resource_group_name(client, resource_group_name, hub_name)
# DeviceStreams property is still in preview, so until GA we need to use a preview API-version
client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_IOTHUB, api_version='2019-07-01-preview')
hub = client.iot_hub_resource.get(resource_group_name, hub_name)
return hub.properties.device_streams
def iot_hub_manual_failover(cmd, client, hub_name, resource_group_name=None, no_wait=False):
hub = iot_hub_get(cmd, client, hub_name, resource_group_name)
resource_group_name = hub.additional_properties['resourcegroup']
failover_region = next(x.location for x in hub.properties.locations if x.role.lower() == 'secondary')
failover_input = FailoverInput(failover_region=failover_region)
if no_wait:
return client.iot_hub.begin_manual_failover(hub_name, resource_group_name, failover_input)
LongRunningOperation(cmd.cli_ctx)(client.iot_hub.begin_manual_failover(hub_name, resource_group_name, failover_input))
return iot_hub_get(cmd, client, hub_name, resource_group_name)
def _get_iot_hub_by_name(client, hub_name):
all_hubs = iot_hub_list(client)
if all_hubs is None:
raise CLIError("No IoT Hub found in current subscription.")
try:
target_hub = next(x for x in all_hubs if hub_name.lower() == x.name.lower())
except StopIteration:
raise CLIError("No IoT Hub found with name {} in current subscription.".format(hub_name))
return target_hub
def _get_iot_hub_hostname(client, hub_name):
# Intermediate fix to support domains beyond azure-devices.net properly
hub = _get_iot_hub_by_name(client, hub_name)
return hub.properties.host_name
def _ensure_resource_group_existence(cli_ctx, resource_group_name):
resource_group_client = resource_service_factory(cli_ctx).resource_groups
return resource_group_client.check_existence(resource_group_name)
def _ensure_hub_resource_group_name(client, resource_group_name, hub_name):
if resource_group_name is None:
return _get_iot_hub_by_name(client, hub_name).additional_properties['resourcegroup']
return resource_group_name
# Convert permission list to AccessRights from IoT SDK.
def _convert_perms_to_access_rights(perm_list):
perm_set = set(perm_list) # remove duplicate
sorted_perm_list = sorted(perm_set)
perm_key = '_'.join(sorted_perm_list)
access_rights_mapping = {
'registryread': AccessRights.registry_read,
'registrywrite': AccessRights.registry_write,
'serviceconnect': AccessRights.service_connect,
'deviceconnect': AccessRights.device_connect,
'registryread_registrywrite': AccessRights.registry_read_registry_write,
'registryread_serviceconnect': AccessRights.registry_read_service_connect,
'deviceconnect_registryread': AccessRights.registry_read_device_connect,
'registrywrite_serviceconnect': AccessRights.registry_write_service_connect,
'deviceconnect_registrywrite': AccessRights.registry_write_device_connect,
'deviceconnect_serviceconnect': AccessRights.service_connect_device_connect,
'registryread_registrywrite_serviceconnect': AccessRights.registry_read_registry_write_service_connect,
'deviceconnect_registryread_registrywrite': AccessRights.registry_read_registry_write_device_connect,
'deviceconnect_registryread_serviceconnect': AccessRights.registry_read_service_connect_device_connect,
'deviceconnect_registrywrite_serviceconnect': AccessRights.registry_write_service_connect_device_connect,
'deviceconnect_registryread_registrywrite_serviceconnect': AccessRights.registry_read_registry_write_service_connect_device_connect
}
return access_rights_mapping[perm_key]
def _is_linked_hub_existed(hubs, hub_name):
hub_set = {h.name.lower() for h in hubs}
return hub_name.lower() in hub_set
def _get_iot_dps_by_name(client, dps_name, resource_group=None):
all_dps = iot_dps_list(client, resource_group)
if all_dps is None:
raise CLIError("No DPS found in current subscription.")
try:
target_dps = next(x for x in all_dps if dps_name.lower() == x.name.lower())
except StopIteration:
raise CLIError("No DPS found with name {} in current subscription.".format(dps_name))
return target_dps
def _ensure_dps_resource_group_name(client, resource_group_name, dps_name):
if resource_group_name is None:
return _get_iot_dps_by_name(client, dps_name).additional_properties['resourcegroup']
return resource_group_name
def _check_dps_name_availability(iot_dps_resource, dps_name):
name_availability = iot_dps_resource.check_provisioning_service_name_availability(DpsOperationInputs(name=dps_name))
if name_availability is not None and not name_availability.name_available:
raise CLIError(name_availability.message)
def _convert_rights_to_access_rights(right_list):
right_set = set(right_list) # remove duplicate
return ",".join(list(right_set))
def _delete_routing_endpoints(endpoint_name, endpoint_type, endpoints):
if endpoint_type:
if EndpointType.ServiceBusQueue.value == endpoint_type.lower():
endpoints.service_bus_queues = []
elif EndpointType.ServiceBusTopic.value == endpoint_type.lower():
endpoints.service_bus_topics = []
elif EndpointType.AzureStorageContainer.value == endpoint_type.lower():
endpoints.storage_containers = []
elif EndpointType.EventHub.value == endpoint_type.lower():
endpoints.event_hubs = []
if endpoint_name:
if any(e.name.lower() == endpoint_name.lower() for e in endpoints.service_bus_queues):
sbq_endpoints = [e for e in endpoints.service_bus_queues if e.name.lower() != endpoint_name.lower()]
endpoints.service_bus_queues = sbq_endpoints
elif any(e.name.lower() == endpoint_name.lower() for e in endpoints.service_bus_topics):
sbt_endpoints = [e for e in endpoints.service_bus_topics if e.name.lower() != endpoint_name.lower()]
endpoints.service_bus_topics = sbt_endpoints
elif any(e.name.lower() == endpoint_name.lower() for e in endpoints.storage_containers):
sc_endpoints = [e for e in endpoints.storage_containers if e.name.lower() != endpoint_name.lower()]
endpoints.storage_containers = sc_endpoints
elif any(e.name.lower() == endpoint_name.lower() for e in endpoints.event_hubs):
eh_endpoints = [e for e in endpoints.event_hubs if e.name.lower() != endpoint_name.lower()]
endpoints.event_hubs = eh_endpoints
if not endpoint_type and not endpoint_name:
endpoints.service_bus_queues = []
endpoints.service_bus_topics = []
endpoints.storage_containers = []
endpoints.event_hubs = []
return endpoints
def iot_central_app_create(
cmd, client, app_name, resource_group_name, subdomain, sku="ST2",
location=None, template=None, display_name=None, no_wait=False, mi_system_assigned=False
):
cli_ctx = cmd.cli_ctx
location = _ensure_location(cli_ctx, resource_group_name, location)
display_name = _ensure_display_name(app_name, display_name)
appSku = AppSkuInfo(name=sku)
appid = {"type": "SystemAssigned"} if mi_system_assigned else None
app = App(subdomain=subdomain,
location=location,
display_name=display_name,
sku=appSku,
template=template,
identity=appid)
return sdk_no_wait(no_wait, client.apps.begin_create_or_update, resource_group_name, app_name, app)
def iot_central_app_get(client, app_name, resource_group_name=None):
if resource_group_name is None:
return _get_iot_central_app_by_name(client, app_name)
return client.apps.get(resource_group_name, app_name)
def iot_central_app_delete(client, app_name, resource_group_name, no_wait=False):
return sdk_no_wait(no_wait, client.apps.begin_delete, resource_group_name, app_name)
def iot_central_app_list(client, resource_group_name=None):
if resource_group_name is None:
return client.apps.list_by_subscription()
return client.apps.list_by_resource_group(resource_group_name)
def iot_central_app_update(client, app_name, parameters, resource_group_name):
return client.apps.begin_create_or_update(resource_group_name, app_name, parameters)
def iot_central_app_assign_identity(client, app_name, system_assigned=False, resource_group_name=None):
app = iot_central_app_get(client, app_name, resource_group_name)
if system_assigned:
app.identity.type = SYSTEM_ASSIGNED
poller = iot_central_app_update(client, app_name, app, resource_group_name)
return poller.result().identity
def iot_central_app_remove_identity(client, app_name, system_assigned=False, resource_group_name=None):
app = iot_central_app_get(client, app_name, resource_group_name)
if system_assigned and (app.identity.type.upper() == SYSTEM_ASSIGNED.upper()):
app.identity.type = NONE_IDENTITY
poller = iot_central_app_update(client, app_name, app, resource_group_name)
return poller.result().identity
def iot_central_app_show_identity(client, app_name, resource_group_name=None):
app = iot_central_app_get(client, app_name, resource_group_name)
return app.identity
def _ensure_location(cli_ctx, resource_group_name, location):
"""Check to see if a location was provided. If not,
fall back to the resource group location.
:param object cli_ctx: CLI Context
:param str resource_group_name: Resource group name
:param str location: Location to create the resource
"""
if location is None:
resource_group_client = resource_service_factory(cli_ctx).resource_groups
return resource_group_client.get(resource_group_name).location
return location
def _ensure_display_name(app_name, display_name):
if not display_name or display_name.isspace():
return app_name
return display_name
def _get_iot_central_app_by_name(client, app_name):
"""Search the current subscription for an app with the given name.
:param object client: IoTCentralClient
:param str app_name: App name to search for
"""
all_apps = iot_central_app_list(client)
if all_apps is None:
raise CLIError(
"No IoT Central application found in current subscription.")
try:
target_app = next(
x for x in all_apps if app_name.lower() == x.name.lower())
except StopIteration:
raise CLIError(
"No IoT Central application found with name {} in current subscription.".format(app_name))
return target_app
def get_private_link_resource(client, name=None, connection_id=None, resource_group_name=None, group_id=None):
if resource_group_name and name and group_id:
return client.private_links.get(resource_group_name=resource_group_name,
resource_name=name,
group_id=group_id)
if connection_id:
id_list = connection_id.split('/')
resource_group_name = id_list[id_list.index('resourceGroups') + 1]
name = id_list[id_list.index('iotApps') + 1]
group_id = id_list[id_list.index('privateLinkResources') + 1]
return client.private_links.get(resource_group_name=resource_group_name,
resource_name=name,
group_id=group_id)
raise RequiredArgumentMissingError(
"Must provide private link resource ID or resource name, resource group, and group id.")
def list_private_link_resource(client, app_name=None, connection_id=None, resource_group_name=None, source_type=None):
if app_name and resource_group_name and source_type:
if source_type.lower() != 'microsoft.iotcentral/iotapps':
raise InvalidArgumentValueError(
"Resource type must be Microsoft.IoTCentral/iotApps")
elif connection_id:
id_list = connection_id.split('/')
if id_list[id_list.index('providers') + 1].lower() != 'microsoft.iotcentral':
raise InvalidArgumentValueError(
"Type must be Microsoft.IoTCentral/iotApps")
resource_group_name = id_list[id_list.index('resourceGroups') + 1]
app_name = id_list[id_list.index('iotApps') + 1]
else:
raise RequiredArgumentMissingError(
"Must provide private endpoint connection resource ID or resource name, resource group, and resource type.")
return client.private_links.list(resource_group_name, app_name)
def show_private_endpoint_connection(client, resource_group_name=None, connection_id=None, account_name=None, private_endpoint_connection_name=None):
return get_private_endpoint_connection(client=client,
resource_group_name=resource_group_name,
connection_id=connection_id,
account_name=account_name,
private_endpoint_connection_name=private_endpoint_connection_name,
return_args=False)
def list_private_endpoint_connection(client, resource_group_name=None, connection_id=None, account_name=None):
if connection_id:
id_list = connection_id.split('/')
if id_list[id_list.index('providers') + 1].lower() != 'microsoft.iotcentral':
raise InvalidArgumentValueError(
"Type must be Microsoft.IoTCentral/iotApps")
resource_group_name = id_list[id_list.index('resourceGroups') + 1]
account_name = id_list[id_list.index('iotApps') + 1]
if resource_group_name is None or account_name is None:
raise RequiredArgumentMissingError(
"Must provide private endpoint connection resource ID or resource name, resource group, and resource type.")
return client.private_endpoint_connections.list(resource_group_name, account_name)
def get_private_endpoint_connection(client, resource_group_name=None, connection_id=None, account_name=None, private_endpoint_connection_name=None, return_args=False):
if resource_group_name and account_name and private_endpoint_connection_name:
output = client.private_endpoint_connections.get(resource_group_name=resource_group_name,
resource_name=account_name,
private_endpoint_connection_name=private_endpoint_connection_name)
if return_args is False:
return output
return [output, resource_group_name, account_name, private_endpoint_connection_name]
if connection_id:
id_list = connection_id.split('/')
resource_group_name = id_list[id_list.index('resourceGroups') + 1]
account_name = id_list[id_list.index('iotApps') + 1]
private_endpoint_connection_name = id_list[id_list.index('privateEndpointConnections') + 1]
output = client.private_endpoint_connections.get(resource_group_name=resource_group_name,
resource_name=account_name,
private_endpoint_connection_name=private_endpoint_connection_name)
if return_args is False:
return output
return [output, resource_group_name, account_name, private_endpoint_connection_name]
raise RequiredArgumentMissingError(
"Account name, resource group, and private endpoint connection name are required unless id is specified.")
def _update_private_endpoint_connection_status(client, resource_group_name, account_name, connection_id, private_endpoint_connection_name, is_approved=True, description=None): # pylint: disable=unused-argument
from azure.core.exceptions import HttpResponseError
getInfoArr = get_private_endpoint_connection(client,
resource_group_name=resource_group_name,
connection_id=connection_id,
account_name=account_name,
private_endpoint_connection_name=private_endpoint_connection_name,
return_args=True)
private_endpoint_connection = getInfoArr[0]
rg = getInfoArr[1]
acc_name = getInfoArr[2]
pec_name = getInfoArr[3]
old_status = private_endpoint_connection.private_link_service_connection_state.status
new_status = "Approved" if is_approved else "Rejected"
private_endpoint_connection.private_link_service_connection_state.status = new_status
private_endpoint_connection.private_link_service_connection_state.description = description
try:
return client.private_endpoint_connections.begin_create(resource_group_name=rg,
resource_name=acc_name,
private_endpoint_connection=private_endpoint_connection,
private_endpoint_connection_name=pec_name)
except HttpResponseError as ex:
if ex.response.status_code == 400:
if new_status == "Approved" and old_status == "Rejected":
raise CLIError(ex.response, "You cannot approve the connection request after rejection. Please create "
"a new connection for approval.")
if new_status == "Approved" and old_status == "Approved":
raise CLIError(ex.response, "Your connection is already approved. No need to approve again.")
raise ex
def approve_private_endpoint_connection(client, resource_group_name=None, account_name=None, private_endpoint_connection_name=None, connection_id=None, description=None):
return _update_private_endpoint_connection_status(client,
resource_group_name=resource_group_name,
account_name=account_name,
connection_id=connection_id,
private_endpoint_connection_name=private_endpoint_connection_name,
description=description)
def reject_private_endpoint_connection(client, resource_group_name=None, account_name=None, private_endpoint_connection_name=None, connection_id=None, description=None):
return _update_private_endpoint_connection_status(client,
resource_group_name=resource_group_name,
account_name=account_name,
connection_id=connection_id,
is_approved=False,
private_endpoint_connection_name=private_endpoint_connection_name,
description=description)
def delete_private_endpoint_connection(client, resource_group_name=None, account_name=None, private_endpoint_connection_name=None, connection_id=None):
getInfoArr = get_private_endpoint_connection(client,
resource_group_name=resource_group_name,
connection_id=connection_id,
account_name=account_name,
private_endpoint_connection_name=private_endpoint_connection_name,
return_args=True)
rg = getInfoArr[1]
acc_name = getInfoArr[2]
pec_name = getInfoArr[3]
# private_endpoint_connection.private_link_service_connection_state.status = new_status
# private_endpoint_connection.private_link_service_connection_state.description = description
return client.private_endpoint_connections.begin_delete(resource_group_name=rg,
resource_name=acc_name,
private_endpoint_connection_name=pec_name)
def _process_fileupload_args(
default_storage_endpoint,
fileupload_storage_connectionstring=None,
fileupload_storage_container_name=None,
fileupload_sas_ttl=None,
fileupload_storage_authentication_type=None,
fileupload_storage_container_uri=None,
fileupload_storage_identity=None,
):
from datetime import timedelta
if fileupload_storage_authentication_type and fileupload_storage_authentication_type == AuthenticationType.IdentityBased.value:
default_storage_endpoint.authentication_type = AuthenticationType.IdentityBased.value
if fileupload_storage_container_uri:
default_storage_endpoint.container_uri = fileupload_storage_container_uri
elif fileupload_storage_authentication_type and fileupload_storage_authentication_type == AuthenticationType.KeyBased.value:
default_storage_endpoint.authentication_type = AuthenticationType.KeyBased.value
default_storage_endpoint.identity = None
elif fileupload_storage_authentication_type is not None:
default_storage_endpoint.authentication_type = None
default_storage_endpoint.container_uri = None
# TODO - remove connection string and set containerURI once fileUpload SAS URL is enabled
if fileupload_storage_connectionstring is not None and fileupload_storage_container_name is not None:
default_storage_endpoint.connection_string = fileupload_storage_connectionstring
default_storage_endpoint.container_name = fileupload_storage_container_name
elif fileupload_storage_connectionstring is not None:
raise RequiredArgumentMissingError('Please mention storage container name.')
elif fileupload_storage_container_name is not None:
raise RequiredArgumentMissingError('Please mention storage connection string.')
if fileupload_sas_ttl is not None:
default_storage_endpoint.sas_ttl_as_iso8601 = timedelta(hours=fileupload_sas_ttl)
# Fix for identity/authentication-type params missing on hybrid profile api
if hasattr(default_storage_endpoint, 'authentication_type'):
# If we are now (or will be) using fsa=identity AND we've set a new identity
if default_storage_endpoint.authentication_type == AuthenticationType.IdentityBased.value and fileupload_storage_identity:
# setup new fsi
default_storage_endpoint.identity = ManagedIdentity(
user_assigned_identity=fileupload_storage_identity) if fileupload_storage_identity not in [IdentityType.none.value, SYSTEM_ASSIGNED_IDENTITY] else None
# otherwise - let them know they need identity-based auth enabled
elif fileupload_storage_identity:
raise ArgumentUsageError('In order to set a file upload storage identity, you must set the file upload storage authentication type (--fsa) to IdentityBased')
return default_storage_endpoint
def _validate_fileupload_identity(instance, fileupload_storage_identity):
instance_identity = _get_hub_identity_type(instance)
# if hub has no identity
if not instance_identity or instance_identity == IdentityType.none.value:
raise ArgumentUsageError('Hub has no identity assigned, please assign a system or user-assigned managed identity to use for file-upload with `az iot hub identity assign`')
has_system_identity = instance_identity in [IdentityType.system_assigned.value, IdentityType.system_assigned_user_assigned.value]
has_user_identity = instance_identity in [IdentityType.user_assigned.value, IdentityType.system_assigned_user_assigned.value]
# if changing storage identity to '[system]'
if fileupload_storage_identity in [None, SYSTEM_ASSIGNED_IDENTITY]:
if not has_system_identity:
raise ArgumentUsageError('System managed identity must be enabled in order to use managed identity for file upload')
# if changing to user identity and hub has no user identities
elif fileupload_storage_identity and not has_user_identity:
raise ArgumentUsageError('User identity {} must be added to hub in order to use it for file upload'.format(fileupload_storage_identity))
def _get_hub_identity_type(instance):
identity = getattr(instance, 'identity', {})
return getattr(identity, 'type', None)
def _build_identity(system=False, identities=None):
identity_type = IdentityType.none.value
if not (system or identities):
return ArmIdentity(type=identity_type)
if system:
identity_type = IdentityType.system_assigned.value
user_identities = list(identities) if identities else None
if user_identities and identity_type == IdentityType.system_assigned.value:
identity_type = IdentityType.system_assigned_user_assigned.value
elif user_identities:
identity_type = IdentityType.user_assigned.value
identity = ArmIdentity(type=identity_type)
if user_identities:
identity.user_assigned_identities = {i: {} for i in user_identities} # pylint: disable=not-an-iterable
return identity
| {
"content_hash": "05499451ea105c2ed3fde1d3f30b88ed",
"timestamp": "",
"source": "github",
"line_count": 1660,
"max_line_length": 210,
"avg_line_length": 55.76144578313253,
"alnum_prop": 0.6766669547556285,
"repo_name": "yugangw-msft/azure-cli",
"id": "678605da12485347c5b123681ed2df29534c1807",
"size": "93037",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/azure-cli/azure/cli/command_modules/iot/custom.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "5355"
},
{
"name": "Batchfile",
"bytes": "14110"
},
{
"name": "Bicep",
"bytes": "1679"
},
{
"name": "C#",
"bytes": "1971"
},
{
"name": "C++",
"bytes": "275"
},
{
"name": "Dockerfile",
"bytes": "8427"
},
{
"name": "HTML",
"bytes": "794"
},
{
"name": "JavaScript",
"bytes": "1404"
},
{
"name": "Jupyter Notebook",
"bytes": "389"
},
{
"name": "PowerShell",
"bytes": "1781"
},
{
"name": "Python",
"bytes": "24270340"
},
{
"name": "Rich Text Format",
"bytes": "12032"
},
{
"name": "Roff",
"bytes": "1036959"
},
{
"name": "Shell",
"bytes": "56023"
},
{
"name": "TSQL",
"bytes": "1145"
}
],
"symlink_target": ""
} |
package io.enmasse.systemtest.soak;
import io.enmasse.address.model.Address;
import io.enmasse.address.model.AddressSpace;
import io.enmasse.address.model.AddressSpaceBuilder;
import io.enmasse.systemtest.TestTag;
import io.enmasse.systemtest.UserCredentials;
import io.enmasse.systemtest.bases.isolated.ITestBaseIsolated;
import io.enmasse.systemtest.bases.soak.SoakTestBase;
import io.enmasse.systemtest.logs.CustomLogger;
import io.enmasse.systemtest.model.addressspace.AddressSpacePlans;
import io.enmasse.systemtest.model.addressspace.AddressSpaceType;
import io.enmasse.systemtest.utils.AddressUtils;
import io.enmasse.systemtest.utils.TestUtils;
import io.fabric8.kubernetes.api.model.Pod;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Tag(TestTag.ISOLATED)
class RestartTest extends SoakTestBase implements ITestBaseIsolated {
private static Logger log = CustomLogger.getLogger();
private ScheduledExecutorService deleteService;
@BeforeEach
void setUp() {
deleteService = Executors.newSingleThreadScheduledExecutor();
}
@AfterEach
void tearDownRestart() {
if (deleteService != null) {
deleteService.shutdownNow();
}
}
@Test
void testRandomDeletePods() throws Exception {
UserCredentials user = new UserCredentials("test-user", "passsswooooord");
AddressSpace standard = new AddressSpaceBuilder()
.withNewMetadata()
.withName("ttest-restart-standard")
.withNamespace(kubernetes.getInfraNamespace())
.endMetadata()
.withNewSpec()
.withType(AddressSpaceType.STANDARD.toString())
.withPlan(AddressSpacePlans.STANDARD_UNLIMITED)
.withNewAuthenticationService()
.withName("standard-authservice")
.endAuthenticationService()
.endSpec()
.build();
AddressSpace brokered = new AddressSpaceBuilder()
.withNewMetadata()
.withName("test-restart-brokered")
.withNamespace(kubernetes.getInfraNamespace())
.endMetadata()
.withNewSpec()
.withType(AddressSpaceType.BROKERED.toString())
.withPlan(AddressSpacePlans.BROKERED)
.withNewAuthenticationService()
.withName("standard-authservice")
.endAuthenticationService()
.endSpec()
.build();
isolatedResourcesManager.createAddressSpaceList(standard, brokered);
resourcesManager.createOrUpdateUser(brokered, user);
resourcesManager.createOrUpdateUser(standard, user);
List<Address> brokeredAddresses = AddressUtils.getAllBrokeredAddresses(brokered);
List<Address> standardAddresses = AddressUtils.getAllStandardAddresses(standard);
resourcesManager.setAddresses(brokeredAddresses.toArray(new Address[0]));
resourcesManager.setAddresses(standardAddresses.toArray(new Address[0]));
getClientUtils().assertCanConnect(brokered, user, brokeredAddresses, resourcesManager);
getClientUtils().assertCanConnect(standard, user, standardAddresses, resourcesManager);
//set up restart scheduler
deleteService.scheduleAtFixedRate(() -> {
log.info("............................................................");
log.info("............................................................");
log.info("..........Scheduler will pick pod and delete them...........");
List<Pod> pods = kubernetes.listPods();
int podNum = new Random(System.currentTimeMillis()).nextInt(pods.size() - 1);
kubernetes.deletePod(environment.namespace(), pods.get(podNum).getMetadata().getName());
log.info("............................................................");
log.info("............................................................");
log.info("............................................................");
}, 5, 25, TimeUnit.SECONDS);
runTestInLoop(60, () ->
assertSystemWorks(brokered, standard, user, brokeredAddresses, standardAddresses));
}
private void assertSystemWorks(AddressSpace brokered, AddressSpace standard, UserCredentials existingUser,
List<Address> brAddresses, List<Address> stAddresses) throws Exception {
log.info("Check if system works");
TestUtils.runUntilPass(60, () -> resourcesManager.getAddressSpace(brokered.getMetadata().getName()));
TestUtils.runUntilPass(60, () -> resourcesManager.getAddressSpace(standard.getMetadata().getName()));
TestUtils.runUntilPass(60, () -> resourcesManager.createOrUpdateUser(brokered, new UserCredentials("jenda", "cenda")));
TestUtils.runUntilPass(60, () -> resourcesManager.createOrUpdateUser(standard, new UserCredentials("jura", "fura")));
TestUtils.runUntilPass(60, () -> {
getClientUtils().assertCanConnect(brokered, existingUser, brAddresses, resourcesManager);
return true;
});
TestUtils.runUntilPass(60, () -> {
getClientUtils().assertCanConnect(standard, existingUser, stAddresses, resourcesManager);
return true;
});
}
}
| {
"content_hash": "69b50daac2b70fa2ecfd0a1fa976689b",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 127,
"avg_line_length": 46.333333333333336,
"alnum_prop": 0.6380066678364625,
"repo_name": "jenmalloy/enmasse",
"id": "08437885d8a4aac19aad00ac2c575d44e0ddbc6e",
"size": "5843",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "systemtests/src/test/java/io/enmasse/systemtest/soak/RestartTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "946"
},
{
"name": "Dockerfile",
"bytes": "8306"
},
{
"name": "Go",
"bytes": "1208268"
},
{
"name": "Groovy",
"bytes": "8925"
},
{
"name": "HTML",
"bytes": "3345"
},
{
"name": "Java",
"bytes": "4217294"
},
{
"name": "JavaScript",
"bytes": "922369"
},
{
"name": "Makefile",
"bytes": "23788"
},
{
"name": "Python",
"bytes": "6730"
},
{
"name": "Ragel",
"bytes": "3778"
},
{
"name": "Shell",
"bytes": "73871"
},
{
"name": "TSQL",
"bytes": "2790"
},
{
"name": "TypeScript",
"bytes": "407558"
},
{
"name": "XSLT",
"bytes": "11077"
},
{
"name": "Yacc",
"bytes": "5306"
}
],
"symlink_target": ""
} |
//---------------------------------------------------------------------
// <copyright file="GraphBasedDataGenerator.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace System.Data.Test.Astoria
{
public class GraphBasedDataGenerator : IDataGenerator
{
#region constructor
public GraphBasedDataGenerator(Workspace w, IDataInserter inserter)
{
#if !ClientSKUFramework
if (!(w is InMemoryWorkspace || w is NonClrWorkspace))
throw new NotSupportedException("GraphBasedDataGenerator is not supported for workspaces other than InMemory and NonClr");
#endif
_workspace = w;
Done = false;
DataInserter = inserter;
Done = false;
}
#endregion
#region private fields
private const int _maxEntitiesToInsert = 5;
private const int _collectionSize = 5;
private Workspace _workspace;
private List<ResourceType> _usedTypes = new List<ResourceType>();
private Dictionary<ResourceContainer, KeyExpressions> _existingKeyMap = new Dictionary<ResourceContainer, KeyExpressions>();
private Dictionary<KeyExpression, KeyedResourceInstance> _existingEntityMap = new Dictionary<KeyExpression, KeyedResourceInstance>();
#endregion
#region IDataGenerator Members
public bool Done
{
get;
internal set;
}
public IDataInserter DataInserter
{
get;
set;
}
public bool SkipAssociations
{
get;
set;
}
public void Run()
{
if (_workspace.Settings.SkipDataPopulation)
{
AstoriaTestLog.WriteLineIgnore("Skipping GraphBasedDataGenerator.SendData() due to workspace settings");
return;
}
bool oldLoggingValue = _workspace.Settings.SuppressTrivialLogging;
_workspace.Settings.SuppressTrivialLogging = true;
List<ResourceContainer> containers = _workspace.ServiceContainer.ResourceContainers.Where(rc => !(rc is ServiceOperation)).ToList();
foreach (ResourceContainer container in containers)
{
if (!this.Skip(container))
{
int addCount;
int graphDepth = this.GraphDepth(container.BaseType);
if (graphDepth > _maxEntitiesToInsert)
addCount = 1;
else
addCount = _maxEntitiesToInsert - graphDepth + 1;
System.Diagnostics.Debug.WriteLine(container.BaseType.Name + ": " + graphDepth.ToString(), ", " + addCount.ToString());
this.InsertData(container, addCount);
}
}
DataInserter.Close();
Done = true;
_workspace.Settings.SuppressTrivialLogging = oldLoggingValue;
}
public KeyExpression GetRandomGeneratedKey(ResourceContainer container, ResourceType type)
{
KeyExpressions keys;
if (!_existingKeyMap.TryGetValue(container, out keys))
return null;
if (type == null)
return keys.Choose();
return keys.Where(k => k.ResourceType == type).Choose();
}
public KeyExpressions GetAllGeneratedKeys(ResourceContainer container, ResourceType type)
{
KeyExpressions keys;
if (!_existingKeyMap.TryGetValue(container, out keys))
return new KeyExpressions();
if (type == null)
return keys;
return new KeyExpressions(keys.Where(k => k.ResourceType == type));
}
#endregion
#region private helper methods
private int GraphDepth(ResourceType resourceType)
{
_usedTypes.Clear();
return GraphDepth(resourceType, _usedTypes);
}
private int GraphDepth(ResourceType resourceType, List<ResourceType> usedTypes)
{
foreach (ResourceProperty property in resourceType.Properties.OfType<ResourceProperty>())
{
if (property.IsNavigation)
{
ResourceType propertyType;
if( property.Type is CollectionType)
propertyType = (property.Type as CollectionType).SubType as ResourceType;
else
propertyType = property.Type as ResourceType;
if (!usedTypes.Contains(propertyType))
{
usedTypes.Add(propertyType);
GraphDepth(propertyType, usedTypes);
}
}
}
if (usedTypes.Count() == 0)
return 1;
return usedTypes.Count();
}
private void InsertData(ResourceContainer container, int count)
{
ResourceContainer currentContainer;
ResourceType currentType;
KeyExpression currentKey;
KeyedResourceInstance currentEntity;
KeyedResourceInstance parentEntity;
Queue<object[]> queue = new Queue<object[]>();
foreach (ResourceType resourceType in container.ResourceTypes)
{
if (resourceType.Facets.AbstractType)
continue;
for (int i = 0; i < count; i++)
{
if (CreateKeyedResourceInstance(container, resourceType, out currentKey, out currentEntity))
{
DataInserter.AddEntity(currentKey, currentEntity);
queue.Enqueue(new object[] { currentKey, currentEntity, null });
}
}
}
HashSet<ResourceType> typesAdded = new HashSet<ResourceType>();
while (queue.Count > 0)
{
object[] current = queue.Dequeue();
currentKey = current[0] as KeyExpression;
currentEntity = current[1] as KeyedResourceInstance;
parentEntity = current[2] as KeyedResourceInstance;
currentContainer = currentKey.ResourceContainer;
currentType = currentKey.ResourceType;
typesAdded.Add(currentType);
foreach (ResourceProperty property in currentType.Properties.OfType<ResourceProperty>().Where(p => p.IsNavigation))
{
ResourceContainer propertyResourceContainer = container.FindDefaultRelatedContainer(property);
ResourceType propertyResourceType = property.OtherAssociationEnd.ResourceType;
List<ResourceType> possibleTypes = new List<ResourceType>() { propertyResourceType };
possibleTypes.AddRange(propertyResourceType.DerivedTypes);
int typeOffset = AstoriaTestProperties.Random.Next(possibleTypes.Count);
bool collection = (property.Type is CollectionType);
int linked = 1;
if (collection)
linked = Math.Max(possibleTypes.Count, 2);
if (!collection && parentEntity != null && parentEntity.TypeName == propertyResourceType.Name)
{
DataInserter.AddAssociation(currentEntity, property, parentEntity);
continue;
}
for (int i = 0; i < linked; i++)
{
ResourceType typeToAdd = possibleTypes[(i + typeOffset) % possibleTypes.Count];
if (!typesAdded.Contains(typeToAdd))
{
// add and link new entity
KeyedResourceInstance childEntity;
KeyExpression childKey;
if (CreateKeyedResourceInstance(propertyResourceContainer, typeToAdd, out childKey, out childEntity))
{
// add new entity
DataInserter.AddEntity(childKey, childEntity);
// add it to the queue
queue.Enqueue(new object[] { childKey, childEntity, currentEntity });
// add to collection
DataInserter.AddAssociation(currentEntity, property, childEntity);
}
}
else if (property.OtherAssociationEnd.Multiplicity == Multiplicity.Many)
{
// link existing entity
ResourceContainer otherContainer = container.FindDefaultRelatedContainer(property);
KeyExpression otherKey = this.GetRandomGeneratedKey(otherContainer, typeToAdd);
if (otherKey != null)
{
KeyedResourceInstance otherEntity;
if (_existingEntityMap.TryGetValue(otherKey, out otherEntity))
DataInserter.AddAssociation(currentEntity, property, otherEntity);
}
}
}
// end of this property
}
// end of this entity
}
DataInserter.Flush();
}
private bool CreateKeyedResourceInstance(ResourceContainer container, ResourceType resourceType, out KeyExpression key, out KeyedResourceInstance newResource)
{
int retryCount = 5;
if (!_existingKeyMap.Keys.Contains(container))
_existingKeyMap.Add(container, new KeyExpressions());
newResource = resourceType.CreateRandomResource(container, new KeyExpressions(), false); // should not make request
key = newResource.ResourceInstanceKey.CreateKeyExpression(container, resourceType);
while (_existingKeyMap[container].Contains(key) && retryCount > 0)
{
newResource.ResourceInstanceKey = ResourceInstanceUtil.CreateUniqueKey(container, resourceType, new KeyExpressions(), new KeyExpressions());
key = newResource.ResourceInstanceKey.CreateKeyExpression(container, resourceType);
retryCount--;
}
if (retryCount == 0)
{
newResource = null;
key = null;
return false;
}
_existingKeyMap[container].Add(key);
_existingEntityMap[key] = newResource;
return true;
}
private bool Skip(ResourceContainer container)
{
return false;
}
#endregion
}
}
| {
"content_hash": "6b5524a51f4d1af314968b7f9c15b821",
"timestamp": "",
"source": "github",
"line_count": 298,
"max_line_length": 166,
"avg_line_length": 39.171140939597315,
"alnum_prop": 0.5252291613124304,
"repo_name": "cxlove/odata.net",
"id": "897b24eb36be4f6d42601ee4d11548c399f8162c",
"size": "11675",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "test/FunctionalTests/Framework/Workspaces/WorkspaceLibrary/GraphBasedDataGenerator.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "6954"
},
{
"name": "Batchfile",
"bytes": "1588"
},
{
"name": "C#",
"bytes": "77235476"
},
{
"name": "HTML",
"bytes": "9302"
},
{
"name": "PowerShell",
"bytes": "13389"
},
{
"name": "Visual Basic",
"bytes": "7824314"
},
{
"name": "XSLT",
"bytes": "19962"
}
],
"symlink_target": ""
} |
use strs_tools as TheModule;
mod inc;
| {
"content_hash": "cb81891e88c03c74d34cbfb17555dae2",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 28,
"avg_line_length": 19,
"alnum_prop": 0.7631578947368421,
"repo_name": "Wandalen/wTools",
"id": "d00a576dec6f00ba726db7dfb2f70640cb458d83",
"size": "69",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rust/test/string/strs_tools_tests.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6031"
},
{
"name": "Rust",
"bytes": "923146"
}
],
"symlink_target": ""
} |
package com.swallow.core.utils;
import com.google.common.collect.Lists;
import com.swallow.core.constant.MathConstant;
import org.junit.Assert;
import org.junit.Test;
/**
* @author disobedient 2018-01-07 22:43
*/
public class ListUtilsTest {
@Test
public void isEmpty() {
Assert.assertTrue(ListUtils.isEmpty(Lists.newArrayList()));
Assert.assertFalse(ListUtils.isEmpty(Lists.newArrayList(MathConstant.ONE)));
}
} | {
"content_hash": "84ed3d32842215c3e4adae7c02b38610",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 84,
"avg_line_length": 24.72222222222222,
"alnum_prop": 0.7303370786516854,
"repo_name": "zhuzaixiaoshulin/swallow",
"id": "5a3da3bd764696aa75abe1031e47c12e88418a47",
"size": "445",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/swallow/core/utils/ListUtilsTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "50619"
}
],
"symlink_target": ""
} |
import { QuestionBase } from '../question-base';
export class OverUnderQuestion extends QuestionBase<string> {
type = 'over-under';
median: number;
constructor(options: {} = {}) {
super(options);
this.median = options['median'] || [];
}
}
| {
"content_hash": "ab56fe5190603444196db89ae2150ac2",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 61,
"avg_line_length": 23.363636363636363,
"alnum_prop": 0.642023346303502,
"repo_name": "briguyd/prop-bets",
"id": "9a84c2d2b343b2436dfd37e063ab36c78b1e13d5",
"size": "257",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/questions/over-under-question/over-under-question.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "152"
},
{
"name": "HTML",
"bytes": "1785"
},
{
"name": "JavaScript",
"bytes": "1884"
},
{
"name": "TypeScript",
"bytes": "16520"
}
],
"symlink_target": ""
} |
<h2>Calendar </h2>
<p>Future functionality</p> | {
"content_hash": "930c01a1c27c4208cffaa6ea3c42f788",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 27,
"avg_line_length": 23,
"alnum_prop": 0.717391304347826,
"repo_name": "montgomeryce/HAViC",
"id": "0589958bad3a59f252336077eb4a193f12e33038",
"size": "46",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/app/components/calendar-view/calendar-view.component.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2611"
},
{
"name": "HTML",
"bytes": "7329"
},
{
"name": "JavaScript",
"bytes": "1996"
},
{
"name": "TypeScript",
"bytes": "39992"
}
],
"symlink_target": ""
} |
#ifndef CQTabSplitSplitterHandle_H
#define CQTabSplitSplitterHandle_H
#include <QSplitter>
class CQTabSplitSplitter;
/*!
* \brief custom splitter handler for CQTabSplitSplitter
*/
class CQTabSplitSplitterHandle : public QSplitterHandle {
Q_OBJECT
Q_PROPERTY(int barSize READ barSize WRITE setBarSize)
public:
CQTabSplitSplitterHandle(Qt::Orientation orient, CQTabSplitSplitter *splitter);
CQTabSplitSplitter *splitter() const { return splitter_; }
//! get/set bar size
int barSize() const { return barSize_; }
void setBarSize(int i) { barSize_ = i; }
//! handle context menu event
void contextMenuEvent(QContextMenuEvent *e) override;
//! handle double click menu event (auto fit)
void mouseDoubleClickEvent(QMouseEvent *) override;
//! paint handle
void paintEvent(QPaintEvent *) override;
//! handle generic event (for hover)
bool event(QEvent *event) override;
//! return size hint
QSize sizeHint() const override;
private slots:
void tabSlot();
void splitSlot();
void fitAllSlot();
private:
CQTabSplitSplitter *splitter_ { nullptr }; //!< parent splitter
int barSize_ { 8 }; //!< bar size
bool hover_ { false }; //!< is hover
};
#endif
| {
"content_hash": "d5cce9b08721d2d16f6cc9f3a65c5b1c",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 81,
"avg_line_length": 24.49019607843137,
"alnum_prop": 0.6949559647718174,
"repo_name": "colinw7/CQUtil",
"id": "fddaeb68fd42f7590277fba9718d9a41d958099d",
"size": "1249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/CQTabSplitSplitterHandle.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "28777"
},
{
"name": "C++",
"bytes": "1859273"
},
{
"name": "Makefile",
"bytes": "104"
},
{
"name": "QMake",
"bytes": "7409"
},
{
"name": "Shell",
"bytes": "87"
}
],
"symlink_target": ""
} |
"""
AUTO-GENERATED BY `scripts/generate_protocol.py` using `data/browser_protocol.json`
and `data/js_protocol.json` as inputs! Please do not modify this file.
"""
import logging
from typing import Any, Optional, Union
from chromewhip.helpers import PayloadMixin, BaseEvent, ChromeTypeBase
log = logging.getLogger(__name__)
from chromewhip.protocol import page as Page
class Testing(PayloadMixin):
""" Testing domain is a dumping ground for the capabilities requires for browser or app testing that do not fit other
domains.
"""
@classmethod
def generateTestReport(cls,
message: Union['str'],
group: Optional['str'] = None,
):
"""Generates a report for testing.
:param message: Message to be displayed in the report.
:type message: str
:param group: Specifies the endpoint group to deliver the report to.
:type group: str
"""
return (
cls.build_send_payload("generateTestReport", {
"message": message,
"group": group,
}),
None
)
| {
"content_hash": "6f1ad6947b0b4384eef63da5f3b27d6d",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 121,
"avg_line_length": 32.27777777777778,
"alnum_prop": 0.6075731497418244,
"repo_name": "chuckus/chromewhip",
"id": "010839aeddb6fc580438c259bcecbea9c1b0722e",
"size": "1215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chromewhip/protocol/testing.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1951"
},
{
"name": "JavaScript",
"bytes": "261"
},
{
"name": "Makefile",
"bytes": "229"
},
{
"name": "Python",
"bytes": "2227857"
},
{
"name": "Shell",
"bytes": "2787"
}
],
"symlink_target": ""
} |
namespace formulate.app.Forms.Fields.Header
{
/// <summary>
/// Configuation required by <see cref="HeaderField"/>.
/// </summary>
public class HeaderConfiguration
{
/// <summary>
/// Gets or sets the text.
/// </summary>
public string Text { get; set; }
}
}
| {
"content_hash": "0a97935d12fa539849067fbb83be45f0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 59,
"avg_line_length": 24.307692307692307,
"alnum_prop": 0.5537974683544303,
"repo_name": "rhythmagency/formulate",
"id": "e63478f7c12ecf213aa885b588f1934c1be7f72f",
"size": "318",
"binary": false,
"copies": "1",
"ref": "refs/heads/v3/master",
"path": "src/formulate.app/Forms/Fields/Header/HeaderConfiguration.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "2203"
},
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "C#",
"bytes": "617212"
},
{
"name": "HTML",
"bytes": "105873"
},
{
"name": "JavaScript",
"bytes": "380893"
},
{
"name": "SCSS",
"bytes": "14746"
}
],
"symlink_target": ""
} |
// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef VOYACOIN_CRYPTO_HMAC_SHA256_H
#define VOYACOIN_CRYPTO_HMAC_SHA256_H
#include "crypto/sha256.h"
#include <stdint.h>
#include <stdlib.h>
/** A hasher class for HMAC-SHA-512. */
class CHMAC_SHA256
{
private:
CSHA256 outer;
CSHA256 inner;
public:
static const size_t OUTPUT_SIZE = 32;
CHMAC_SHA256(const unsigned char* key, size_t keylen);
CHMAC_SHA256& Write(const unsigned char* data, size_t len)
{
inner.Write(data, len);
return *this;
}
void Finalize(unsigned char hash[OUTPUT_SIZE]);
};
#endif // VOYACOIN_CRYPTO_HMAC_SHA256_H
| {
"content_hash": "7af243f4c0e085699810e8d7c3f73e9b",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 70,
"avg_line_length": 24.21875,
"alnum_prop": 0.6980645161290323,
"repo_name": "Voyacoin/Voyacoin",
"id": "2c6d6af1516f4d6090c535ab89b8c8495e3795c7",
"size": "775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/crypto/hmac_sha256.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "7411"
},
{
"name": "Assembly",
"bytes": "7639"
},
{
"name": "C",
"bytes": "338063"
},
{
"name": "C++",
"bytes": "3507076"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "2101"
},
{
"name": "Makefile",
"bytes": "61694"
},
{
"name": "Objective-C",
"bytes": "3109"
},
{
"name": "Objective-C++",
"bytes": "7184"
},
{
"name": "Protocol Buffer",
"bytes": "2312"
},
{
"name": "Python",
"bytes": "207784"
},
{
"name": "Shell",
"bytes": "42780"
}
],
"symlink_target": ""
} |
import styled from 'styled-components';
const H1 = styled.h1`
font-size: ${props => props.theme.h1.fontSize};
margin: ${props => props.theme.h1.margin};
padding: ${props => props.theme.h1.padding};
text-align: ${props => props.theme.h1.textAlign};
`;
export default H1;
| {
"content_hash": "1de586613952c92147da8800507440b1",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 51,
"avg_line_length": 28,
"alnum_prop": 0.6785714285714286,
"repo_name": "angeloocana/angeloocana",
"id": "818b433417784c6f315eb3c3c98503f8107f7191",
"size": "280",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/components/H1.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6744"
},
{
"name": "HTML",
"bytes": "12374"
},
{
"name": "JavaScript",
"bytes": "191212"
},
{
"name": "Vim Script",
"bytes": "516"
}
],
"symlink_target": ""
} |
package org.apache.tools.ant.taskdefs.optional;
import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.regexp.RegexpMatcherFactory;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.Properties;
/**
* Tests the EchoProperties task.
*
* @created 17-Jan-2002
* @since Ant 1.5
*/
public class EchoPropertiesTest extends BuildFileTest {
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/";
private static final String GOOD_OUTFILE = "test.properties";
private static final String GOOD_OUTFILE_XML = "test.xml";
private static final String PREFIX_OUTFILE = "test-prefix.properties";
private static final String TEST_VALUE = "isSet";
public EchoPropertiesTest(String name) {
super(name);
}
public void setUp() {
configureProject(TASKDEFS_DIR + "echoproperties.xml");
project.setProperty( "test.property", TEST_VALUE );
}
public void tearDown() {
executeTarget("cleanup");
}
public void testEchoToLog() {
expectLogContaining("testEchoToLog", "test.property="+TEST_VALUE);
}
public void testEchoWithEmptyPrefixToLog() {
expectLogContaining("testEchoWithEmptyPrefixToLog", "test.property="+TEST_VALUE);
}
public void testReadBadFile() {
expectBuildExceptionContaining( "testReadBadFile",
"srcfile is a directory", "srcfile is a directory!" );
}
public void testReadBadFileFail() {
expectBuildExceptionContaining( "testReadBadFile",
"srcfile is a directory", "srcfile is a directory!" );
}
public void testReadBadFileNoFail() {
expectLog( "testReadBadFileNoFail", "srcfile is a directory!" );
}
public void testEchoToBadFile() {
expectBuildExceptionContaining( "testEchoToBadFile",
"destfile is a directory", "destfile is a directory!" );
}
public void testEchoToBadFileFail() {
expectBuildExceptionContaining( "testEchoToBadFileFail",
"destfile is a directory", "destfile is a directory!" );
}
public void testEchoToBadFileNoFail() {
expectLog( "testEchoToBadFileNoFail", "destfile is a directory!");
}
public void testEchoToGoodFile() throws Exception {
executeTarget( "testEchoToGoodFile" );
assertGoodFile();
}
public void testEchoToGoodFileXml() throws Exception {
executeTarget( "testEchoToGoodFileXml" );
// read in the file
File f = createRelativeFile( GOOD_OUTFILE_XML );
FileReader fr = new FileReader( f );
try {
BufferedReader br = new BufferedReader( fr );
String read = null;
while ( (read = br.readLine()) != null) {
if (read.indexOf("<property name=\"test.property\" value=\""+TEST_VALUE+"\" />") >= 0) {
// found the property we set - it's good.
return;
}
}
fail( "did not encounter set property in generated file." );
} finally {
try {
fr.close();
} catch(IOException e) {}
}
}
public void testEchoToGoodFileFail() throws Exception {
executeTarget( "testEchoToGoodFileFail" );
assertGoodFile();
}
public void testEchoToGoodFileNoFail() throws Exception {
executeTarget( "testEchoToGoodFileNoFail" );
assertGoodFile();
}
public void testEchoPrefix() throws Exception {
testEchoPrefixVarious("testEchoPrefix");
}
public void testEchoPrefixAsPropertyset() throws Exception {
testEchoPrefixVarious("testEchoPrefixAsPropertyset");
}
public void testEchoPrefixAsNegatedPropertyset() throws Exception {
testEchoPrefixVarious("testEchoPrefixAsNegatedPropertyset");
}
public void testEchoPrefixAsDoublyNegatedPropertyset() throws Exception {
testEchoPrefixVarious("testEchoPrefixAsDoublyNegatedPropertyset");
}
public void testWithPrefixAndRegex() throws Exception {
expectSpecificBuildException("testWithPrefixAndRegex",
"The target must fail with prefix and regex attributes set",
"Please specify either prefix or regex, but not both");
}
public void testWithEmptyPrefixAndRegex() throws Exception {
expectLogContaining("testEchoWithEmptyPrefixToLog", "test.property="+TEST_VALUE);
}
public void testWithRegex() throws Exception {
if (!RegexpMatcherFactory.regexpMatcherPresent(project)) {
System.out.println("Test 'testWithRegex' skipped because no regexp matcher is present.");
return;
}
executeTarget("testWithRegex");
assertDebuglogContaining("ant.home=");
}
private void testEchoPrefixVarious(String target) throws Exception {
executeTarget(target);
Properties props = loadPropFile(PREFIX_OUTFILE);
assertEquals("prefix didn't include 'a.set' property",
"true", props.getProperty("a.set"));
assertNull("prefix failed to filter out property 'b.set'",
props.getProperty("b.set"));
}
protected Properties loadPropFile(String relativeFilename)
throws IOException {
File f = createRelativeFile( relativeFilename );
Properties props=new Properties();
InputStream in=null;
try {
in=new BufferedInputStream(new FileInputStream(f));
props.load(in);
} finally {
if(in!=null) {
try { in.close(); } catch(IOException e) {}
}
}
return props;
}
protected void assertGoodFile() throws Exception {
File f = createRelativeFile( GOOD_OUTFILE );
assertTrue(
"Did not create "+f.getAbsolutePath(),
f.exists() );
Properties props=loadPropFile(GOOD_OUTFILE);
props.list(System.out);
assertEquals("test property not found ",
TEST_VALUE, props.getProperty("test.property"));
/*
// read in the file
FileReader fr = new FileReader( f );
try {
BufferedReader br = new BufferedReader( fr );
String read = null;
while ( (read = br.readLine()) != null)
{
if (read.indexOf("test.property" + TEST_VALUE) >= 0)
{
// found the property we set - it's good.
return;
}
}
fail( "did not encounter set property in generated file." );
} finally {
try { fr.close(); } catch(IOException e) {}
}
*/
}
protected String toAbsolute( String filename ) {
return createRelativeFile( filename ).getAbsolutePath();
}
protected File createRelativeFile( String filename ) {
if (filename.equals( "." )) {
return getProjectDir();
}
// else
return new File( getProjectDir(), filename );
}
}
| {
"content_hash": "f3257de6145ddfbd626fd5fe96a668d9",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 104,
"avg_line_length": 30.733050847457626,
"alnum_prop": 0.6212601682062595,
"repo_name": "Mayo-WE01051879/mayosapp",
"id": "d62c8cc1645f893126537f2b68727d08246eb426",
"size": "8069",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Build/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "27841"
},
{
"name": "CSS",
"bytes": "6179"
},
{
"name": "GAP",
"bytes": "36428"
},
{
"name": "HTML",
"bytes": "2189621"
},
{
"name": "Java",
"bytes": "8854706"
},
{
"name": "JavaScript",
"bytes": "34849"
},
{
"name": "Perl",
"bytes": "9844"
},
{
"name": "Python",
"bytes": "3299"
},
{
"name": "Shell",
"bytes": "25265"
},
{
"name": "XSLT",
"bytes": "371927"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="//cdn.authentiq.io/authentiqjs/latest/authentiq.js"
class="authentiq-snippet"
data-provider-uri="{{ provider_uri }}"
data-client-id="{{ client_id }}"
data-redirect-uri="{{ redirect_uri }}"
data-state="{{ state }}"
data-display="{{ display }}"
data-response-type="code"></script>
{# redirect page to /index only when display=page #}
{% if display == 'page' %}
<script>
window.location.replace({{ redirect_to|tojson }});
</script>
{% endif %}
</head>
<body>
</body>
</html>
| {
"content_hash": "8bb92dd2528fac628e1a6123420d6ff6",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 66,
"avg_line_length": 25.5,
"alnum_prop": 0.5625942684766214,
"repo_name": "AuthentiqID/examples-flask",
"id": "68fc6660ec386d2f8bb7215c1dc67152bf2c7607",
"size": "663",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/authorized.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2201"
},
{
"name": "Python",
"bytes": "28410"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=562433
-->
<head>
<title>Test for Bug 562433</title>
<script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=562433">Mozilla Bug 562433</a>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script type="application/javascript">
/** Test for Bug 562433 **/
var w = window.open("");
// The new window's location.host and location.hostname must be the empty
// string (instead of throwing an exception)
is(w.location.host, "", 'w.location.host should be ""');
is(w.location.hostname, "", 'w.location.hostname should be ""');
w.close();
</script>
</pre>
</body>
</html>
| {
"content_hash": "39d8ae8355da5524430575a049ad6dfd",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 100,
"avg_line_length": 25.142857142857142,
"alnum_prop": 0.6772727272727272,
"repo_name": "wilebeast/FireFox-OS",
"id": "1500ee1136fda356a36f31245bdfa508c554854c",
"size": "880",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "B2G/gecko/dom/tests/mochitest/bugs/test_bug562433.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package main.nl.uva.validation.type;
import main.nl.uva.parser.expression.BinaryExpression;
import main.nl.uva.parser.expression.Expression;
import main.nl.uva.ui.element.DeclarationUI;
import main.nl.uva.ui.types.MoneyUI;
import main.nl.uva.ui.types.ValueUI;
public class Money extends Value {
private double _value;
public Money() {
this(0.0d);
}
public Money(final double value) {
super(Value.Type.MONEY);
_value = value;
}
public void setValue(final double value) {
_value = value;
}
public double getValue() {
return _value;
}
@Override
public Value calculateValueWith(final Expression right, final BinaryExpression expression) {
return right.getValue().calculateValueWith(this, expression);
}
@Override
public Value calculateValueWith(final Bool left, final BinaryExpression expression) {
return expression.calculateValue(left, this);
}
@Override
public Value calculateValueWith(final Money left, final BinaryExpression expression) {
return expression.calculateValue(left, this);
}
@Override
public Value calculateValueWith(final Text left, final BinaryExpression expression) {
return expression.calculateValue(left, this);
}
@Override
public ValueUI getLayout(final DeclarationUI parent) {
return new MoneyUI(parent, this);
}
@Override
public boolean applyValueTo(final Value type) {
return type.acceptType(this);
}
@Override
public boolean acceptType(final Money type) {
_value = type._value;
return true;
}
@Override
public String toString() {
return "Money: " + _value;
}
}
| {
"content_hash": "93c19ee9d068218e537e7a2dccede0e7",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 96,
"avg_line_length": 24.9,
"alnum_prop": 0.6706827309236948,
"repo_name": "software-engineering-amsterdam/poly-ql",
"id": "2fb3f0890531a5f7ca6c04e13215b07bcdf42e08",
"size": "1743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PhilippBeau/Parser/src/main/nl/uva/validation/type/Money.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "59975"
},
{
"name": "Batchfile",
"bytes": "451"
},
{
"name": "C#",
"bytes": "505581"
},
{
"name": "CSS",
"bytes": "6060"
},
{
"name": "CodeQL",
"bytes": "2151"
},
{
"name": "F#",
"bytes": "321742"
},
{
"name": "GAP",
"bytes": "21011"
},
{
"name": "HTML",
"bytes": "85"
},
{
"name": "Java",
"bytes": "2703336"
},
{
"name": "JavaScript",
"bytes": "34725"
},
{
"name": "Makefile",
"bytes": "190"
},
{
"name": "PHP",
"bytes": "3079"
},
{
"name": "Python",
"bytes": "51874"
},
{
"name": "Shell",
"bytes": "176"
},
{
"name": "TeX",
"bytes": "1950"
},
{
"name": "Visual Basic .NET",
"bytes": "1223"
},
{
"name": "Yacc",
"bytes": "1387"
}
],
"symlink_target": ""
} |
package net.runelite.api.mixins;
import java.lang.annotation.Documented;
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.METHOD)
@Documented
public @interface MethodHook
{
String value();
boolean end() default false;
}
| {
"content_hash": "a4f119ede3e97ee0e43303ff74d61b4a",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 44,
"avg_line_length": 21.88888888888889,
"alnum_prop": 0.8121827411167513,
"repo_name": "abelbriggs1/runelite",
"id": "5caeca83369b6c5c53a9dbf3fc42fca496936edc",
"size": "1773",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "runelite-mixins/src/main/java/net/runelite/api/mixins/MethodHook.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "GLSL",
"bytes": "41919"
},
{
"name": "HTML",
"bytes": "7055"
},
{
"name": "Java",
"bytes": "9389009"
},
{
"name": "Shell",
"bytes": "327"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.21006.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LEMP3.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| {
"content_hash": "b31bca98a25e6d7ba1022ca3db0657b3",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 151,
"avg_line_length": 36.2,
"alnum_prop": 0.5616942909760589,
"repo_name": "SLP-KBIT/LEMP3",
"id": "afdbd5bc86586040d8c38f684a736466e005bc7f",
"size": "1088",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LEMP3/Properties/Settings.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "20122"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<!-- Generated by HsColour, http://code.haskell.org/~malcolm/hscolour/ -->
<title>Control/Monad/ST/Strict.hs</title>
<link type='text/css' rel='stylesheet' href='hscolour.css' />
</head>
<body>
<pre><a name="line-1"></a><span class='hs-comment'>{-# LANGUAGE Safe #-}</span>
<a name="line-2"></a>
<a name="line-3"></a><span class='hs-comment'>-----------------------------------------------------------------------------</span>
<a name="line-4"></a><span class='hs-comment'>-- |</span>
<a name="line-5"></a><span class='hs-comment'>-- Module : Control.Monad.ST.Strict</span>
<a name="line-6"></a><span class='hs-comment'>-- Copyright : (c) The University of Glasgow 2001</span>
<a name="line-7"></a><span class='hs-comment'>-- License : BSD-style (see the file libraries/base/LICENSE)</span>
<a name="line-8"></a><span class='hs-comment'>--</span>
<a name="line-9"></a><span class='hs-comment'>-- Maintainer : libraries@haskell.org</span>
<a name="line-10"></a><span class='hs-comment'>-- Stability : provisional</span>
<a name="line-11"></a><span class='hs-comment'>-- Portability : non-portable (requires universal quantification for runST)</span>
<a name="line-12"></a><span class='hs-comment'>--</span>
<a name="line-13"></a><span class='hs-comment'>-- The strict ST monad (re-export of "Control.Monad.ST")</span>
<a name="line-14"></a><span class='hs-comment'>--</span>
<a name="line-15"></a><span class='hs-comment'>-----------------------------------------------------------------------------</span>
<a name="line-16"></a>
<a name="line-17"></a><span class='hs-keyword'>module</span> <span class='hs-conid'>Control</span><span class='hs-varop'>.</span><span class='hs-conid'>Monad</span><span class='hs-varop'>.</span><span class='hs-conid'>ST</span><span class='hs-varop'>.</span><span class='hs-conid'>Strict</span> <span class='hs-layout'>(</span>
<a name="line-18"></a> <span class='hs-keyword'>module</span> <span class='hs-conid'>Control</span><span class='hs-varop'>.</span><span class='hs-conid'>Monad</span><span class='hs-varop'>.</span><span class='hs-conid'>ST</span>
<a name="line-19"></a> <span class='hs-layout'>)</span> <span class='hs-keyword'>where</span>
<a name="line-20"></a>
<a name="line-21"></a><span class='hs-keyword'>import</span> <span class='hs-conid'>Control</span><span class='hs-varop'>.</span><span class='hs-conid'>Monad</span><span class='hs-varop'>.</span><span class='hs-conid'>ST</span>
<a name="line-22"></a>
</pre></body>
</html>
| {
"content_hash": "3d3fa69fda4f9112b002b498d6a02995",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 327,
"avg_line_length": 80.81818181818181,
"alnum_prop": 0.6111736032995876,
"repo_name": "nmattia/halytics",
"id": "645ab07bb777582411aeb142e2970e9924912075",
"size": "2667",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "docs/base-4.8.2.0/src/Control-Monad-ST-Strict.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "33813"
},
{
"name": "Shell",
"bytes": "1032"
}
],
"symlink_target": ""
} |
namespace Tempest{
class LightCollection : public AbstractLightCollection {
public:
template< class L >
class Pack: public AbstractLightCollection::Pack<L> {
public:
virtual int size() const {
return data.size();
}
virtual void resize( int s, const L& l = L() ) {
data.resize(s, l);
}
virtual const L& operator [] ( int id ) const{
return data[id];
}
virtual L& operator [] ( int id ) {
return data[id];
}
virtual void push_back( const L& l ){
return data.push_back(l);
}
virtual void pop_back(){
return data.pop_back();
}
std::vector<L> data;
};
virtual const DirectionLights& direction() const;
virtual DirectionLights& direction();
private:
Pack<DirectionLight> dir;
};
}
#endif // LIGHTCOLLECTION_H
| {
"content_hash": "9a6d7b80bc19f1a9a21a8d204f05662c",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 57,
"avg_line_length": 21.58139534883721,
"alnum_prop": 0.5377155172413793,
"repo_name": "enotio/Tempest",
"id": "ca31e5727a3067fa9b0ac8476c4836a63b49bf73",
"size": "1043",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tempest/scene/lightcollection.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "209674"
},
{
"name": "C++",
"bytes": "997335"
},
{
"name": "CSS",
"bytes": "26404"
},
{
"name": "Java",
"bytes": "10502"
},
{
"name": "Makefile",
"bytes": "3047"
},
{
"name": "Objective-C",
"bytes": "387"
},
{
"name": "Objective-C++",
"bytes": "50885"
},
{
"name": "QML",
"bytes": "1647"
},
{
"name": "QMake",
"bytes": "11871"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>Taxon API Test Page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <script src="/bower_components/requirejs/require.js"></script> -->
<script src="require.js"></script>
<!-- <script src="require-config.js"></script> -->
</head>
<body>
<div id='result'></div>
<script>
'use strict';
// Configuration family fun time
require.config({
baseUrl: 'http://localhost:8888/proxy/http://localhost:8000/',
catchError: false,
onError: function (err) {
alert("RequireJS Error:" + err);
},
paths: {
// External Dependencies
// ----------------------
jquery: 'bower_components/jquery/jquery',
underscore: 'bower_components/underscore/underscore',
bluebird: 'bower_components/bluebird/bluebird',
bootstrap: 'bower_components/bootstrap/js/bootstrap',
bootstrap_css: 'bower_components/bootstrap/css/bootstrap',
'font-awesome': 'bower_components/font-awesome/css/font-awesome',
thrift: 'bower_components/thrift-binary-protocol/thrift-core',
thrift_transport_xhr: 'bower_components/thrift-binary-protocol/thrift-transport-xhr',
thrift_protocol_binary: 'bower_components/thrift-binary-protocol/thrift-protocol-binary',
text: 'bower_components/requirejs-text/text',
yaml: 'bower_components/require-yaml/yaml',
'js-yaml': 'bower_components/js-yaml/js-yaml',
css: 'bower_components/require-css/css',
// NB the taxon thrift libraries are generated, wrapped, and installed
// by grunt tasks.
taxon_types: 'js/thrift/taxon/taxon_types',
taxon_service: 'js/thrift/taxon/thrift_service',
// The main product
kb_data_taxon: 'js/Taxon',
kb_common_html: 'bower_components/kbase-common-js/html',
kb_common_cookie: 'bower_components/kbase-common-js/cookie',
kb_common_logger: 'bower_components/kbase-common-js/logger',
kb_common_session: 'bower_components/kbase-common-js/session'
},
shim: {
bootstrap: {
deps: ['jquery', 'css!bootstrap_css']
}
},
map: {
'*': {
'css': 'css',
'promise': 'bluebird'
}
}
});
// Do something stupid and ridiculous
requirejs(['kb_data_taxon'], function(Taxon){
var taxon = Taxon({ ref: "993/674615/1",
url: "http://localhost:8888/proxy/http://localhost:9101",
token: "",
timeout: 6000})
taxon.getScientificName()
.then(function(name) {
console.log("Scientific name: ", name)
document.getElementById('result').innerHTML = name
})
});
</script>
</body> | {
"content_hash": "3cf9342893c2d8e274d12462cfa60b01",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 101,
"avg_line_length": 39.05263157894737,
"alnum_prop": 0.5673854447439353,
"repo_name": "mlhenderson/data_api",
"id": "ba9b19abbce2aa895f709f6b58cda00ade247e17",
"size": "2968",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "jslib/runtime/build/test1.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9594"
},
{
"name": "HTML",
"bytes": "77123"
},
{
"name": "JavaScript",
"bytes": "594489"
},
{
"name": "Jupyter Notebook",
"bytes": "5342297"
},
{
"name": "Makefile",
"bytes": "10254"
},
{
"name": "Perl",
"bytes": "681703"
},
{
"name": "Python",
"bytes": "659006"
},
{
"name": "Shell",
"bytes": "4628"
},
{
"name": "Thrift",
"bytes": "45335"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Component\Form\Extension\DependencyInjection;
use Symfony\Component\Form\FormExtensionInterface;
use Symfony\Component\Form\FormTypeGuesserChain;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DependencyInjectionExtension implements FormExtensionInterface
{
private $container;
private $typeServiceIds;
private $guesserServiceIds;
private $guesser;
private $guesserLoaded = false;
public function __construct(ContainerInterface $container,
array $typeServiceIds, array $typeExtensionServiceIds,
array $guesserServiceIds)
{
$this->container = $container;
$this->typeServiceIds = $typeServiceIds;
$this->typeExtensionServiceIds = $typeExtensionServiceIds;
$this->guesserServiceIds = $guesserServiceIds;
}
public function getType($name)
{
if (!isset($this->typeServiceIds[$name])) {
throw new \InvalidArgumentException(sprintf('The field type "%s" is not registered with the service container.', $name));
}
$type = $this->container->get($this->typeServiceIds[$name]);
if ($type->getName() !== $name) {
throw new \InvalidArgumentException(
sprintf('The type name specified for the service "%s" does not match the actual name. Expected "%s", given "%s"',
$this->typeServiceIds[$name],
$name,
$type->getName()
));
}
return $type;
}
public function hasType($name)
{
return isset($this->typeServiceIds[$name]);
}
public function getTypeExtensions($name)
{
$extensions = array();
if (isset($this->typeExtensionServiceIds[$name])) {
foreach ($this->typeExtensionServiceIds[$name] as $serviceId) {
$extensions[] = $this->container->get($serviceId);
}
}
return $extensions;
}
public function hasTypeExtensions($name)
{
return isset($this->typeExtensionServiceIds[$name]);
}
public function getTypeGuesser()
{
if (!$this->guesserLoaded) {
$this->guesserLoaded = true;
$guessers = array();
foreach ($this->guesserServiceIds as $serviceId) {
$guessers[] = $this->container->get($serviceId);
}
if (count($guessers) > 0) {
$this->guesser = new FormTypeGuesserChain($guessers);
}
}
return $this->guesser;
}
}
| {
"content_hash": "2e7ec7854b102a1e093bd61c13463911",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 133,
"avg_line_length": 28.731182795698924,
"alnum_prop": 0.5793413173652695,
"repo_name": "WCORP/just2",
"id": "fdcc83726fe09900f7fabd00d032a331ca6d239a",
"size": "2908",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/symfony/symfony/src/Symfony/Component/Form/Extension/DependencyInjection/DependencyInjectionExtension.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1017310"
},
{
"name": "PHP",
"bytes": "405326"
}
],
"symlink_target": ""
} |
package org.synyx.urlaubsverwaltung.core.mail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.synyx.urlaubsverwaltung.core.settings.MailSettings;
import java.util.Arrays;
import java.util.List;
/**
* Sends mails using {@link JavaMailSenderImpl}.
*
* @author Aljona Murygina - murygina@synyx.de
*/
@Service
class MailSender {
private static final Logger LOG = LoggerFactory.getLogger(MailSender.class);
private final JavaMailSenderImpl mailSender;
@Autowired
MailSender(@Qualifier("javaMailSender") JavaMailSenderImpl mailSender) {
this.mailSender = mailSender;
}
/**
* Send a mail with the given subject and text to the given recipients.
*
* @param mailSettings contains settings that should be used to send mails
* @param recipients mail addresses where the mail should be sent to
* @param subject mail subject
* @param text mail body
*/
void sendEmail(MailSettings mailSettings, List<String> recipients, String subject, String text) {
if (recipients != null && !recipients.isEmpty()) {
SimpleMailMessage mailMessage = new SimpleMailMessage();
String[] addressTo = new String[recipients.size()];
for (int i = 0; i < recipients.size(); i++) {
addressTo[i] = recipients.get(i);
}
mailMessage.setFrom(mailSettings.getFrom());
mailMessage.setTo(addressTo);
mailMessage.setSubject(subject);
mailMessage.setText(text);
send(mailMessage, mailSettings);
}
}
private void send(SimpleMailMessage message, MailSettings mailSettings) {
try {
if (mailSettings.isActive()) {
this.mailSender.setHost(mailSettings.getHost());
this.mailSender.setPort(mailSettings.getPort());
this.mailSender.setUsername(mailSettings.getUsername());
this.mailSender.setPassword(mailSettings.getPassword());
this.mailSender.send(message);
for (String recipient : message.getTo()) {
LOG.info("Sent email to {}", recipient);
}
} else {
for (String recipient : message.getTo()) {
LOG.info("No email configuration to send email to {}", recipient);
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("To={}\n\nSubject={}\n\nText={}",
Arrays.toString(message.getTo()), message.getSubject(), message.getText());
}
} catch (MailException ex) {
for (String recipient : message.getTo()) {
LOG.error("Sending email to {} failed", recipient, ex);
}
}
}
}
| {
"content_hash": "17a0446b63d1694691d101e08d148d69",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 101,
"avg_line_length": 33.58510638297872,
"alnum_prop": 0.6262274311054798,
"repo_name": "Intera/urlaubsverwaltung",
"id": "49603685a3e6f036e5fe5e1c6391899ca4da8276",
"size": "3157",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/synyx/urlaubsverwaltung/core/mail/MailSender.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "223702"
},
{
"name": "Dockerfile",
"bytes": "305"
},
{
"name": "FreeMarker",
"bytes": "11473"
},
{
"name": "Java",
"bytes": "1760809"
},
{
"name": "JavaScript",
"bytes": "332383"
},
{
"name": "Shell",
"bytes": "341"
}
],
"symlink_target": ""
} |
%{
version: "1.0.0",
title: "Pattern Matching",
excerpt: """
_Pattern matching_ è un aspetto fondamentale di Elixir, permette di abbinare semplici valori, strutture dati e funzioni. In questa lezione inizieremo a vedere come viene usato il pattern matching.
"""
}
---
## Operatore match
Se pronto ad essere spiazzato? In Elixir, l'operatore `=` è in realtà un operatore match. Tramite l'operatore match possiamo assegnare ed abbinare valori, simile al segno uguale in algebra. Scrivendolo, transforma l'intera espressione in un'equazione ed Elixir deve abbinare i valori sulla sinistra a quelli della destra. Se l'operazione ha successo, Elixir genera i valori dell'equazione, altrimenti, genera un errore. Diamo uno sguardo:
```elixir
iex> x = 1
1
```
Ora proviamo un semplice abbinamento:
```elixir
iex> 1 = x
1
iex> 2 = x
** (MatchError) no match of right hand side value: 1
```
Ora proviamo con una delle collezioni che conosciamo:
```elixir
# Liste
iex> list = [1, 2, 3]
[1, 2, 3]
iex> [1, 2, 3] = list
[1, 2, 3]
iex> [] = list
** (MatchError) no match of right hand side value: [1, 2, 3]
iex> [1 | tail] = list
[1, 2, 3]
iex> tail
[2, 3]
iex> [2|_] = list
** (MatchError) no match of right hand side value: [1, 2, 3]
# Tuple
iex> {:ok, value} = {:ok, "Successful!"}
{:ok, "Successful!"}
iex> value
"Successful!"
iex> {:ok, value} = {:error}
** (MatchError) no match of right hand side value: {:error}
```
## Operator pin
Abbiamo appena imparato che l'operatore match gestisce l'assegnazione quando la parte sinistra dell'abbinamento include una variabile. In alcuni casi questo comportamento, cambiare l'abbinamento di una variabile, non è desiderabile. Per queste situazioni, abbiamo l'operatore pin `^`.
Quando _fissiamo_ (_pin_) una variabile, abbiniamo il valore esistente invece di cambiare l'abbinamento con un nuovo valore. Vediamo come funziona:
```elixir
iex> x = 1
1
iex> ^x = 2
** (MatchError) no match of right hand side value: 2
iex> {x, ^x} = {2, 1}
{2, 1}
iex> x
2
```
Elixir 1.2 ha introdotto il supporto per usare l'operatore pin per le chiavi delle mappe e nelle clausole delle funzioni:
```elixir
iex> key = "hello"
"hello"
iex> %{^key => value} = %{"hello" => "world"}
%{"hello" => "world"}
iex> value
"world"
iex> %{^key => value} = %{:hello => "world"}
** (MatchError) no match of right hand side value: %{hello: "world"}
```
Un esempio di _pinning_ in una clausola di una funzione:
```elixir
iex> greeting = "Hello"
"Hello"
iex> greet = fn
...> (^greeting, name) -> "Hi #{name}"
...> (greeting, name) -> "#{greeting}, #{name}"
...> end
#Function<12.54118792/2 in :erl_eval.expr/5>
iex> greet.("Hello", "Sean")
"Hi Sean"
iex> greet.("Mornin'", "Sean")
"Mornin', Sean"
```
Da notare il fatto la riassegnazione di `greeting` nell'esempio `"Mornin'"`, la riassegnazione succede solo dentro la funzione. Fuori dalla funzione `greeting` contiente ancora il valore di `"Hello"`.
| {
"content_hash": "9cd498f606ee86aeb56f36d6f8b21f8c",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 438,
"avg_line_length": 29.03960396039604,
"alnum_prop": 0.6870098874872145,
"repo_name": "doomspork/elixir_school",
"id": "1078ea92eca06c2b48f05de9fc377efbd9db0ff6",
"size": "2937",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lessons/it/basics/pattern_matching.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "26198"
},
{
"name": "HTML",
"bytes": "5189"
},
{
"name": "JavaScript",
"bytes": "423"
},
{
"name": "Ruby",
"bytes": "1985"
}
],
"symlink_target": ""
} |
package v1alpha1
import (
"fmt"
"strings"
datav1alpha1 "github.com/Alluxio/alluxio/api/v1alpha1"
"github.com/Alluxio/alluxio/pkg/common"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
/**
* construct ddc runtime for the dataset
*/
func constructRuntimeForDataset(dataset datav1alpha1.Dataset) (runtime datav1alpha1.Runtime, err error) {
// Use the same name for dataset and cache runtime
// we will support default value in k8s 1.16
// https://github.com/kubernetes-sigs/controller-tools/pull/323/files
runtimeType := dataset.Spec.Runtime
if runtimeType == "" {
runtimeType = common.DefaultDDCRuntime
}
runtime = datav1alpha1.Runtime{
ObjectMeta: metav1.ObjectMeta{
Name: dataset.Name,
Namespace: dataset.Namespace,
},
Spec: datav1alpha1.RuntimeSpec{
Type: runtimeType,
TemplateFileName: fmt.Sprintf("%s-%s-template", dataset.Name, strings.ToLower(runtimeType)),
},
Status: datav1alpha1.RuntimeStatus{},
}
return runtime, nil
}
| {
"content_hash": "414fc72149f6060fcb46ec503160a0c8",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 105,
"avg_line_length": 26.07894736842105,
"alnum_prop": 0.7295660948536832,
"repo_name": "EvilMcJerkface/alluxio",
"id": "2fdec989c137f86a5f6908d1b63a262e63e5e17b",
"size": "1503",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "integration/kubernetes/operator/alluxio/pkg/controllers/dataset/v1alpha1/helper.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10148"
},
{
"name": "Dockerfile",
"bytes": "2050"
},
{
"name": "Go",
"bytes": "24668"
},
{
"name": "HTML",
"bytes": "3412"
},
{
"name": "Java",
"bytes": "10000810"
},
{
"name": "JavaScript",
"bytes": "2801"
},
{
"name": "Python",
"bytes": "11471"
},
{
"name": "Roff",
"bytes": "5797"
},
{
"name": "Ruby",
"bytes": "22472"
},
{
"name": "Shell",
"bytes": "152128"
},
{
"name": "TypeScript",
"bytes": "257808"
}
],
"symlink_target": ""
} |
#pragma once
#include <chrono>
#include "oqpi/empty_layer.hpp"
#include "oqpi/synchronization/sync_common.hpp"
namespace oqpi { namespace itfc {
//----------------------------------------------------------------------------------------------
template
<
// Platform specific implementation for semaphores
typename _Impl
// Augmentation layer, needs to be templated and inherit from the implementation
, template<typename> typename _Layer
>
class semaphore
: public std::conditional<is_empty_layer<_Layer>::value, _Impl, _Layer<_Impl>>::type
{
public:
//------------------------------------------------------------------------------------------
// Whether the event has augmented layer(s) or not
static constexpr auto is_lean = is_empty_layer<_Layer>::value;
// The platform specific implementation
using semaphore_impl = _Impl;
// The actual base type taking into account the presence or absence of augmentation layer(s)
using base_type = typename std::conditional_t<is_lean, semaphore_impl, _Layer<semaphore_impl>>;
// The actual type
using self_type = semaphore<semaphore_impl, _Layer>;
// Native handle
using native_handle_type = typename semaphore_impl::native_handle_type;
public:
//------------------------------------------------------------------------------------------
semaphore(int32_t initCount = 0, int32_t maxCount = 0x7fffffff)
: base_type(initCount, maxCount)
{}
//------------------------------------------------------------------------------------------
explicit semaphore(const std::string &name, int32_t initCount = 0, int32_t maxCount = 0x7fffffff)
: base_type(name, sync_object_creation_options::open_or_create, initCount, maxCount)
{}
//------------------------------------------------------------------------------------------
semaphore(const std::string &name, sync_object_creation_options creationOption, int32_t initCount = 0, int32_t maxCount = 0x7fffffff)
: base_type(name, creationOption, initCount, maxCount)
{}
public:
//------------------------------------------------------------------------------------------
// Movable
semaphore(self_type &&rhs)
: base_type(std::move(*(base_type *)&rhs))
{}
//------------------------------------------------------------------------------------------
inline self_type& operator =(self_type &&rhs)
{
if (this != &rhs)
{
base_type::operator =(std::move(rhs));
}
return (*this);
}
//------------------------------------------------------------------------------------------
// Not copyable
semaphore(const self_type &) = delete;
self_type& operator =(const self_type &) = delete;
public:
//------------------------------------------------------------------------------------------
// User interface
native_handle_type getNativeHandle() const { return base_type::getNativeHandle(); }
bool isValid() const { return base_type::isValid(); }
void notify(int32_t count) { return base_type::notify(count); }
void notifyOne() { return notify(1); }
void notifyAll() { return base_type::notifyAll(); }
bool tryWait() { return base_type::tryWait(); }
bool wait() { return base_type::wait(); }
//------------------------------------------------------------------------------------------
template<typename _Rep, typename _Period>
inline bool waitFor(const std::chrono::duration<_Rep, _Period>& relTime)
{
return base_type::waitFor(relTime);
}
//------------------------------------------------------------------------------------------
template<typename _Clock, typename _Duration>
inline bool waitUntil(const std::chrono::time_point<_Clock, _Duration>& absTime)
{
return waitFor(absTime - _Clock::now());
}
};
} /*itfc*/ } /*oqpi*/
| {
"content_hash": "c4fa086c021946d0fad095022ef10ed1",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 141,
"avg_line_length": 46.714285714285715,
"alnum_prop": 0.41022280471821754,
"repo_name": "H-EAL/oqpi",
"id": "bf93a9ca116b93f1ca1f4a5347da0f3e53b935d2",
"size": "4578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/oqpi/synchronization/interface/interface_semaphore.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1022291"
},
{
"name": "CMake",
"bytes": "1397"
}
],
"symlink_target": ""
} |
package com.plugin.commons.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.plugin.R;
import com.plugin.commons.model.NewsInfoModel;
public class NewsImgListAdapter extends ZhKdBaseAdapter<NewsInfoModel> {
private Context context;
public NewsImgListAdapter(Context context, List<NewsInfoModel> data){
this.context = context;
this.dataList = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final NewsInfoModel imgList = dataList.get(position);
View rowView =convertView;// viewMap.get(cmsList.getId()+""+position);
final NewListItemCache viewCache;
if (rowView == null) {
rowView = LayoutInflater.from(context).inflate(R.layout.item_newscomment, null);
viewCache = new NewListItemCache(rowView,null,context,imgList.getId()+"");
viewCache.getTv_rpname();
viewCache.getTv_time();
viewCache.getTv_desc();
viewCache.getIv_image();
rowView.setTag(viewCache);
// viewMap.put(cmsList.getId()+""+position, rowView);
} else {
viewCache = (NewListItemCache) rowView.getTag();
}
// //解决卡顿的问题
// if(!FuncUtil.isEmpty(cmsList.getUserphoto())){
// ComApp.getInstance().getFinalBitmap().display(viewCache.getIv_image(), cmsList.getUserphoto());
// }
// viewCache.getTv_rpname().setText(cmsList.getUsername());
// viewCache.getTv_time().setText(cmsList.getCreatetime());
// viewCache.getTv_desc().setText(cmsList.getContent());
return rowView;
}
}
| {
"content_hash": "19d28cc8acef3c556b7319a9658d561b",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 100,
"avg_line_length": 33.132075471698116,
"alnum_prop": 0.657744874715262,
"repo_name": "zhanggh/andr_puligins",
"id": "dd3c60818a358d75c16c017a8fa44c28c5c4c469",
"size": "1770",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library_common/src/com/plugin/commons/adapter/NewsImgListAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2002060"
}
],
"symlink_target": ""
} |
/*
* @author max
*/
package com.intellij.psi.stubs;
import org.jetbrains.annotations.NotNull;
public class StubTree extends ObjectStubTree<StubElement<?>> {
public StubTree(@NotNull final PsiFileStub root) {
this(root, true);
}
public StubTree(@NotNull final PsiFileStub root, final boolean withBackReference) {
super((ObjectStubBase)root, withBackReference);
}
@NotNull
@Override
public PsiFileStub getRoot() {
return (PsiFileStub)myRoot;
}
}
| {
"content_hash": "e691dffba9007e5938700582259dd9a0",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 85,
"avg_line_length": 19.24,
"alnum_prop": 0.7214137214137214,
"repo_name": "romankagan/DDBWorkbench",
"id": "36a855d6458c5ce933175303ad8f325a18594e21",
"size": "1081",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "platform/core-impl/src/com/intellij/psi/stubs/StubTree.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "C",
"bytes": "174330"
},
{
"name": "C#",
"bytes": "390"
},
{
"name": "C++",
"bytes": "85270"
},
{
"name": "CSS",
"bytes": "102018"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "FLUX",
"bytes": "57"
},
{
"name": "Groovy",
"bytes": "1899897"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "128604770"
},
{
"name": "JavaScript",
"bytes": "123045"
},
{
"name": "Objective-C",
"bytes": "19702"
},
{
"name": "Perl",
"bytes": "6549"
},
{
"name": "Python",
"bytes": "17759911"
},
{
"name": "Ruby",
"bytes": "1213"
},
{
"name": "Shell",
"bytes": "45691"
},
{
"name": "TeX",
"bytes": "60798"
},
{
"name": "XSLT",
"bytes": "113531"
}
],
"symlink_target": ""
} |
<!--Auto Complete Button component code -->
<div ng-controller="autocompleteCtrl">
<div class="row">
<div class="col-md-12 ol-md-12">
<h4>Auto Complete Search</h4>
<div class="vmf-autocomplete-input vmf-autocomplete-search" vmf-autocomplete-input type="psearch" name="userForm" model="user.psearch" search-model="data.list" hint="Search All Downloads" clear-text-length="3" psearch-callback="user.psearchCallback"></div>
</div>
</div>
<h4 class="clearfix">Auto Complete on a form field</h4>
<div class="row">
<label class="col-md-3 formLabel formLabelLineHeight">Normal Search box</label>
<div class="col-md-4">
<div class="vmf-autocomplete-input" vmf-autocomplete-input type="psearch" theme="normal" name="userForm" model="user.psearch1" search-model="data.list" hint="Search All Downloads" clear-text-length="3" psearch-callback="user.psearchCallback"></div>
</div>
</div>
</div> | {
"content_hash": "9e2451d5b530a91d4ab40888b62fc96b",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 268,
"avg_line_length": 49.1,
"alnum_prop": 0.6680244399185336,
"repo_name": "anandharshan/Web-components-DD",
"id": "199f8a17eb513474a6fdc17c17683ab7993bb107",
"size": "982",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev/modules/autocomplete/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1815115"
},
{
"name": "HTML",
"bytes": "320313"
},
{
"name": "JavaScript",
"bytes": "4817472"
}
],
"symlink_target": ""
} |
require "ostruct"
require "bls_api/month"
module BLS_API
class Series
include BLS_API::Destringify
attr_reader :id
def initialize(raw_series)
@id = raw_series["seriesID"]
begin
@raw_series = self.destringify_series(raw_series)
rescue ArgumentError
# Series was already destringified _and_ it was using Floats.
@raw_series = raw_series
end
end
# Public: Return catalog information for this series if available.
#
# Returns an OpenStruct if possible; returns nil if no catalog information
# was received.
def catalog
return nil unless @raw_series.include?("catalog")
return @catalog unless @catalog.nil?
@catalog = OpenStruct.new(@raw_series["catalog"])
end
# Public: Return information for the given month.
#
# year - An Integer representing the year for which to retrieve data.
# month - An Integer representing the month (1 = January) for which to
# retrieve data.
#
# Returns a BLS_API::Month.
def get_month(year, month)
self.monthly # Ensure we've converted all months.
@months.detect do |parsed_month|
parsed_month.year == year && parsed_month.month == month
end
end
# Public: Return information for all months.
#
# Returns an Array of BLS_API::Months.
def monthly
return @months unless @months.nil?
@months = @raw_series["data"].map do |month_data|
BLS_API::Month.new(month_data)
end
@months.sort!.reverse!
end
end
end
| {
"content_hash": "7f705da65b2c5f9ff7eee60b64ef7889",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 78,
"avg_line_length": 27.982142857142858,
"alnum_prop": 0.6381620931716656,
"repo_name": "associatedpress/bls_api",
"id": "75139a90d1f66483553d7b9664b061a982fd2d58",
"size": "1567",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/bls_api/series.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "37726"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
test_description="Test API security"
. lib/test-lib.sh
test_init_ipfs
# by default, we don't let you load arbitrary ipfs objects through the api,
# because this would open up the api to scripting vulnerabilities.
# only the webui objects are allowed.
# if you know what you're doing, go ahead and pass --unrestricted-api.
test_launch_ipfs_daemon
test_expect_success "Gateway on API unavailable" '
HASH=$(echo "testing" | ipfs add -q)
test_curl_resp_http_code "http://127.0.0.1:$API_PORT/ipfs/$HASH" "HTTP/1.1 404 Not Found"
'
test_kill_ipfs_daemon
test_launch_ipfs_daemon --unrestricted-api
test_expect_success "Gateway on --unrestricted-api API available" '
HASH=$(echo "testing" | ipfs add -q)
test_curl_resp_http_code "http://127.0.0.1:$API_PORT/ipfs/$HASH" "HTTP/1.1 200 OK"
'
test_kill_ipfs_daemon
test_done
| {
"content_hash": "9f304fe150d4dbbe210a8fff1d076fa8",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 91,
"avg_line_length": 31.807692307692307,
"alnum_prop": 0.7291414752116082,
"repo_name": "OpenBazaar/go-ipfs",
"id": "137f99a950ec412b7464850403ee06171a8d669c",
"size": "942",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "test/sharness/t0400-api-security.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "3442"
},
{
"name": "Go",
"bytes": "1454986"
},
{
"name": "Groovy",
"bytes": "4922"
},
{
"name": "Makefile",
"bytes": "19376"
},
{
"name": "PureBasic",
"bytes": "29"
},
{
"name": "Python",
"bytes": "788"
},
{
"name": "Shell",
"bytes": "327423"
}
],
"symlink_target": ""
} |
package org.kaazing.gateway.resource.address.rtmp;
import java.net.URI;
import org.kaazing.gateway.resource.address.ResourceAddress;
public class RtmpResourceAddress extends ResourceAddress {
static final String TRANSPORT_NAME = "rtmp";
private static final long serialVersionUID = 1L;
RtmpResourceAddress(URI original, URI resource) {
super(original, resource);
}
}
| {
"content_hash": "4f8d3333835d52c46d47a68a09e2ea71",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 60,
"avg_line_length": 21.263157894736842,
"alnum_prop": 0.7425742574257426,
"repo_name": "michaelcretzman/gateway",
"id": "f653f0d339b202b9478f418099f1682db4b3e009",
"size": "1287",
"binary": false,
"copies": "7",
"ref": "refs/heads/develop",
"path": "resource.address/rtmp/src/main/java/org/kaazing/gateway/resource/address/rtmp/RtmpResourceAddress.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2250"
},
{
"name": "HTML",
"bytes": "38948"
},
{
"name": "Java",
"bytes": "10470249"
},
{
"name": "JavaScript",
"bytes": "3868"
},
{
"name": "Shell",
"bytes": "5534"
},
{
"name": "XSLT",
"bytes": "5493"
}
],
"symlink_target": ""
} |
package mts
//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// AudioStreamListInQueryMediaListByURL is a nested struct in mts response
type AudioStreamListInQueryMediaListByURL struct {
AudioStream []AudioStream `json:"AudioStream" xml:"AudioStream"`
}
| {
"content_hash": "0b685b41d8b2325c5cf50a9e65838e8f",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 84,
"avg_line_length": 42.523809523809526,
"alnum_prop": 0.780515117581187,
"repo_name": "xiaozhu36/terraform-provider",
"id": "7e4046654d104db15df96eb5495d33dea56dd331",
"size": "893",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/mts/struct_audio_stream_list_in_query_media_list_by_url.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2195403"
},
{
"name": "HCL",
"bytes": "818"
},
{
"name": "HTML",
"bytes": "40750"
},
{
"name": "Makefile",
"bytes": "1899"
},
{
"name": "Shell",
"bytes": "1341"
}
],
"symlink_target": ""
} |
package it.cosenonjaviste.demomv2m.core.currencyconverter4;
import android.databinding.ObservableBoolean;
import android.support.annotation.NonNull;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import it.cosenonjaviste.demomv2m.R;
import it.cosenonjaviste.demomv2m.core.MessageManager;
import it.cosenonjaviste.mv2m.rx.RxViewModel;
import it.cosenonjaviste.mv2m.rx.SchedulerManager;
import rx.functions.Action1;
public class CurrencyConverterViewModel extends RxViewModel<Void, CurrencyConverterModel> {
private RateLoader rateLoader;
private MessageManager messageManager;
public final ObservableBoolean loading = new ObservableBoolean();
public CurrencyConverterViewModel(RateLoader rateLoader, MessageManager messageManager, SchedulerManager schedulerManager) {
super(schedulerManager);
this.rateLoader = rateLoader;
this.messageManager = messageManager;
}
@NonNull @Override public CurrencyConverterModel createModel() {
return new CurrencyConverterModel();
}
public void calculate() {
String inputString = model.input.get();
try {
final float input = Float.parseFloat(inputString);
subscribe(
new Action1<Boolean>() {
@Override public void call(Boolean b) {
loading.set(b);
}
},
rateLoader.loadRate(),
new Action1<Float>() {
@Override public void call(Float rate) {
DecimalFormat decimalFormat = new DecimalFormat("0.00", DecimalFormatSymbols.getInstance(Locale.US));
model.output.set(decimalFormat.format(input * rate));
}
}, new Action1<Throwable>() {
@Override public void call(Throwable throwable) {
messageManager.showMessage(activityHolder, R.string.error_loading_rate);
}
});
} catch (NumberFormatException e) {
messageManager.showMessage(activityHolder, R.string.conversion_error);
}
}
}
| {
"content_hash": "f67662cc3c43f5718fea03240766ff42",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 129,
"avg_line_length": 37.916666666666664,
"alnum_prop": 0.6281318681318682,
"repo_name": "fabioCollini/mv2m",
"id": "e07516a814941347f0ebfdee99ea2bd65976ab9b",
"size": "2875",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo/src/main/java/it/cosenonjaviste/demomv2m/core/currencyconverter4/CurrencyConverterViewModel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "153150"
}
],
"symlink_target": ""
} |
import {AmpStoryHint} from '../amp-story-hint';
import {Services} from '../../../../src/services';
const NOOP = () => {};
describes.fakeWin('amp-story hint layer', {}, env => {
let win;
let ampStoryHint;
beforeEach(() => {
win = env.win;
sandbox.stub(Services, 'vsyncFor').callsFake(
() => ({mutate: task => task()}));
sandbox.stub(Services, 'timerFor').callsFake(
() => ({delay: NOOP, cancel: NOOP}));
ampStoryHint = new AmpStoryHint(win);
});
it('should build the UI', () => {
expect(ampStoryHint.buildHintContainer()).to.not.be.null;
});
it('should be able to show navigation help overlay', () => {
const hideAfterTimeoutStub =
sandbox.stub(ampStoryHint, 'hideAfterTimeout').callsFake(NOOP);
const hintContainer = ampStoryHint.buildHintContainer();
ampStoryHint.showNavigationOverlay();
expect(hintContainer.className).to.contain('show-navigation-overlay');
expect(hintContainer.className).to.not.contain('show-first-page-overlay');
expect(hintContainer.className).to.not.contain('i-amphtml-hidden');
expect(hideAfterTimeoutStub).to.be.calledOnce;
});
it('should be able to show no previous page help overlay', () => {
const hideAfterTimeoutStub =
sandbox.stub(ampStoryHint, 'hideAfterTimeout').callsFake(NOOP);
const hintContainer = ampStoryHint.buildHintContainer();
ampStoryHint.showFirstPageHintOverlay();
expect(hintContainer.className).to.contain('show-first-page-overlay');
expect(hintContainer.className).to.not.contain('show-navigation-overlay');
expect(hintContainer.className).to.not.contain('i-amphtml-hidden');
expect(hideAfterTimeoutStub).to.be.calledOnce;
});
it('should be able to hide shown hint', () => {
const hintContainer = ampStoryHint.buildHintContainer();
ampStoryHint.showNavigationOverlay();
ampStoryHint.hideAllNavigationHint();
expect(hintContainer.className).to.contain('i-amphtml-hidden');
});
});
| {
"content_hash": "3e3b039f8013adf5a75ad628768e95c3",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 78,
"avg_line_length": 31.234375,
"alnum_prop": 0.6858429214607303,
"repo_name": "shawnbuso/amphtml",
"id": "68783d21119aa8cdfdf36ed4af757685fd0eb698",
"size": "2626",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "extensions/amp-story/0.1/test/test-amp-story-hint.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "174156"
},
{
"name": "Go",
"bytes": "7459"
},
{
"name": "HTML",
"bytes": "993937"
},
{
"name": "Java",
"bytes": "36670"
},
{
"name": "JavaScript",
"bytes": "9025125"
},
{
"name": "Python",
"bytes": "75748"
},
{
"name": "Ruby",
"bytes": "13754"
},
{
"name": "Shell",
"bytes": "6942"
},
{
"name": "Yacc",
"bytes": "22292"
}
],
"symlink_target": ""
} |
from mistral.db.v2.sqlalchemy import models
from mistral.engine import tasks
from mistral.tests.unit import base
from mistral.workflow import states
# TODO(rakhmerov): This test is a legacy of the previous 'with-items'
# implementation when most of its logic was in with_items.py module.
# It makes sense to add more test for various methods of WithItemsTask.
class WithItemsTaskTest(base.BaseTest):
@staticmethod
def get_action_ex(accepted, state, index):
return models.ActionExecution(
accepted=accepted,
state=state,
runtime_context={'index': index}
)
def test_get_next_indices(self):
# Task execution for running 6 items with concurrency=3.
task_ex = models.TaskExecution(
spec={
'action': 'myaction'
},
runtime_context={
'with_items': {
'capacity': 3,
'count': 6
}
},
action_executions=[],
workflow_executions=[]
)
task = tasks.WithItemsTask(None, None, None, {}, task_ex)
# Set 3 items: 2 success and 1 error unaccepted.
task_ex.action_executions += [
self.get_action_ex(True, states.SUCCESS, 0),
self.get_action_ex(True, states.SUCCESS, 1),
self.get_action_ex(False, states.ERROR, 2)
]
# Then call get_indices and expect [2, 3, 4].
indexes = task._get_next_indexes()
self.assertListEqual([2, 3, 4], indexes)
| {
"content_hash": "c12de4cde106045dcf044d0fdeb7ae6e",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 71,
"avg_line_length": 32.5625,
"alnum_prop": 0.581573896353167,
"repo_name": "StackStorm/mistral",
"id": "9ba5dda565b9de6571b3252cfc148db853e335dc",
"size": "2172",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mistral/tests/unit/engine/test_with_items_task.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1494"
},
{
"name": "Mako",
"bytes": "951"
},
{
"name": "Python",
"bytes": "2249335"
},
{
"name": "Shell",
"bytes": "31326"
}
],
"symlink_target": ""
} |
VMWareTasks
===========

The VMWare SDK, specifically VixCOM, offers a rich set of programmable interfaces that enable developers to drive virtual machines programmatically with an asynchronous, job-based programming model. Unfortunately that turns out to be too complicated for most scenarios where developers want to use a simple object-oriented interface for common VMWare virtual machine automation tasks. The VMWareTasks is a commercial-grade library that implements this simple interface and makes programming against virtual machines a no-brainer.
VMWareTasks contains a complete VixCOM wrapper Vestris.VMWareLib (Vestris.VMWareLib.dll) and a library Vestris.VMWareLib.Tools (Vestris.VMWareTools.dll) that implements additional commonly needed functionality or addresses known VixCOM API limitations.
VMWareTasks exposes a C# interface, a COM-enabled interface for script clients, a Java bridge for Java programs and a set of MSBuild tasks.
Resources
---------
* [Need Help? VMWareTasks Google Group](http://groups.google.com/group/vmwaretasks)
* [Need VixCOM Help? VMWare Communities](http://communities.vmware.com/community/vmtn/developer/forums/automationapi)
* [Latest Stable Release - 1.7](http://code.dblock.org/downloads/vmwaretasks/VMWareTasks-1.7.zip)
* [Downlod VixCOM 1.11](https://my.vmware.com/group/vmware/get-download?downloadGroup=VIX-API-1110) (you will need to login)
* [VixCOM API 1.11 Reference](http://www.vmware.com/support/developer/vix-api/vix111_reference/index2.html)
Prerequisites
-------------
In order to use the library you must install the following VMWare software.
* VMWare VIX. This is the SDK, obtained from [http://www.vmware.com/download/sdk/vmauto.html](http://www.vmware.com/download/sdk/vmauto.html). Version 1.6.2 or newer is required for VI support. Version 1.8.0 or newer is required for VMWare Player support.
* Either VMWare Workstation 6.5.2 or later, VMWare Server 2.0, VMWare Player 3.0 or 3.1, a Virtual Infrastructure environment (eg. ESXi) or VSphere 4.0 or 4.1.
Getting Started (C#)
--------------------
Download the latest version of this library [here](http://code.dblock.org/downloads/vmwaretasks/VMWareTasks-1.7.zip). Add a reference to `Vestris.VMWareLib.dll` to your project and a `using`.
``` csharp
using Vestris.VMWareLib;
```
You can now connect to a local VMWare Workstation, local or remote VMWare Server or a remote ESX server and perform VMWare client and server tasks. The following example creates, restores, powers on and removes a snapshot on a VMWare Workstation host.
``` csharp
// declare a virtual host
using (VMWareVirtualHost virtualHost = new VMWareVirtualHost())
{
// connect to a local VMWare Workstation virtual host
virtualHost.ConnectToVMWareWorkstation();
// open an existing virtual machine
using (VMWareVirtualMachine virtualMachine = virtualHost.Open(@"C:\Virtual Machines\xp\xp.vmx"))
{
// power on this virtual machine
virtualMachine.PowerOn();
// login to the virtual machine
virtualMachine.LoginInGuest("Administrator", "password");
// wait for VMWare Tools
virtualMachine.WaitForToolsInGuest();
// run notepad
virtualMachine.RunProgramInGuest("notepad.exe", string.Empty);
// create a new snapshot
string name = "New Snapshot";
// take a snapshot at the current state
VMWareSnapshot createdSnapshot = virtualMachine.Snapshots.CreateSnapshot(name, "test snapshot");
createdSnapshot.Dispose();
// find the newly created snapshot
using (VMWareSnapshot foundSnapshot = virtualMachine.Snapshots.GetNamedSnapshot(name))
{
// revert to the new snapshot
foundSnapshot.RevertToSnapshot();
// delete snapshot
foundSnapshot.RemoveSnapshot();
}
// power off
virtualMachine.PowerOff();
}
}
```
The following example creates, restores, powers on and removes a snapshot on a local VMWare Server 2.x host. VMWare Server 2.x generally behaves like an ESX host, replace "localhost" with a real host name to make a remote connection.
``` csharp
// declare a virtual host
using (VMWareVirtualHost virtualHost = new VMWareVirtualHost())
{
// connect to a local VMWare Server 2.x virtual host
virtualHost.ConnectToVMWareVIServer("localhost:8333", "vmuser", "password");
// open an existing virtual machine
using (VMWareVirtualMachine virtualMachine = virtualHost.Open(@"[standard] xp/xp.vmx"))
{
// power on this virtual machine
virtualMachine.PowerOn();
// wait for VMWare Tools
virtualMachine.WaitForToolsInGuest();
// login to the virtual machine
virtualMachine.LoginInGuest("Administrator", "password");
// run notepad
virtualMachine.RunProgramInGuest("notepad.exe", string.Empty);
// create a new snapshot
string name = "New Snapshot";
// take a snapshot at the current state
virtualMachine.Snapshots.CreateSnapshot(name, "test snapshot");
// power off
virtualMachine.PowerOff();
// find the newly created snapshot
using (VMWareSnapshot snapshot = virtualMachine.Snapshots.GetNamedSnapshot(name))
{
// revert to the new snapshot
snapshot.RevertToSnapshot();
// delete snapshot
snapshot.RemoveSnapshot();
}
}
}
```
The following example creates, restores, powers on and removes a snapshot on a remote VMWare ESX host.
``` csharp
// declare a virtual host
using (VMWareVirtualHost virtualHost = new VMWareVirtualHost())
{
// connect to a remove (VMWare ESX) virtual machine
virtualHost.ConnectToVMWareVIServer("esx.mycompany.com", "vmuser", "password");
// open an existing virtual machine
using (VMWareVirtualMachine virtualMachine = virtualHost.Open("[storage] testvm/testvm.vmx"))
{
// power on this virtual machine
virtualMachine.PowerOn();
// wait for VMWare Tools
virtualMachine.WaitForToolsInGuest();
// login to the virtual machine
virtualMachine.LoginInGuest("Administrator", "password");
// run notepad
virtualMachine.RunProgramInGuest("notepad.exe", string.Empty);
// create a new snapshot
string name = "New Snapshot";
// take a snapshot at the current state
virtualMachine.Snapshots.CreateSnapshot(name, "test snapshot");
// power off
virtualMachine.PowerOff();
// find the newly created snapshot
using (VMWareSnapshot snapshot = virtualMachine.Snapshots.GetNamedSnapshot(name))
{
// revert to the new snapshot
snapshot.RevertToSnapshot();
// delete snapshot
snapshot.RemoveSnapshot();
}
}
}
```
Note, that because VMWare VixCOM is a native 32-bit application, ensure that the platform target for your program is *x86* and not *Any CPU*.
Most VMWareTasks objects are IDisposable and should be wrapped in a using construct or properly disposed of before calling `VMWareVirtualHost::Disconnect`. Failure to dispose of all objects, including snapshots and hosts may result in an access violation when VixCOM.dll is unloaded. This is particularly true when working with VMWare ESX 4.
Contributing
------------
This project started as a [CodeProject Article](http://www.codeproject.com/Articles/31961/Automating-VMWare-Tasks-in-C-with-the-VIX-API) and grew with the help of many contributors. Fork the project. Make your feature addition or bug fix with tests. Send a pull request. Bonus points for topic branches.
Copyright and License
---------------------
MIT License, see [LICENSE](https://github.com/dblock/vmwaretasks/blob/master/LICENSE.md) for details.
(c) 2009-2012 [Daniel Doubrovkine, Vestris Inc.](http://code.dblock.org) and [Contributors](https://github.com/dblock/vmwaretasks/blob/master/CHANGELOG.md)
| {
"content_hash": "88f1287a32c9ebc534fd52dbb6c8b32e",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 529,
"avg_line_length": 47.49707602339181,
"alnum_prop": 0.7138635803989165,
"repo_name": "dblock/vmwaretasks",
"id": "d321d93e3350844f714d55ee34b5438cafc7d323",
"size": "8122",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "21627"
},
{
"name": "Batchfile",
"bytes": "17965"
},
{
"name": "C",
"bytes": "117423"
},
{
"name": "C#",
"bytes": "422698"
},
{
"name": "C++",
"bytes": "73666"
},
{
"name": "CSS",
"bytes": "75111"
},
{
"name": "HTML",
"bytes": "99588"
},
{
"name": "Java",
"bytes": "1811"
},
{
"name": "JavaScript",
"bytes": "159715"
},
{
"name": "PowerShell",
"bytes": "25649"
},
{
"name": "Visual Basic",
"bytes": "1367"
},
{
"name": "XSLT",
"bytes": "1103384"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe Open::Dojo::Apprentice do
let(:apprentice) { create :apprentice }
describe 'young apprentice' do
let(:apprentice) { build :apprentice }
it 'has 1 dan' do
expect(apprentice.rank).to eq(1)
end
end
describe 'ranking' do
it "manimum kyu is 30" do
expect(build :apprentice, rank: 31).not_to be_valid
end
it "maximum kyu is 1" do
expect(build :apprentice, rank: 0).not_to be_valid
end
context 'when lesson is completted' do
let!(:apprentice) { create :apprentice }
it 'get next kyu descending'
end
end
describe '#get_all_uncompleted_lessons'
end
| {
"content_hash": "c0e798732e82052317f30373e8db8c2c",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 57,
"avg_line_length": 21.193548387096776,
"alnum_prop": 0.649923896499239,
"repo_name": "Tensho/open-dojo",
"id": "54bda7ed6f786a4b2f0521ab0cf74b3b345726b6",
"size": "657",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/open/dojo/apprentice_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "5523"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
/**
* @title WET-BOEW Tables
* @overview Integrates the DataTables plugin into WET providing searching, sorting, filtering, pagination and other advanced features for tables.
* @license wet-boew.github.io/wet-boew/License-en.html / wet-boew.github.io/wet-boew/Licence-fr.html
* @author @jeresiv
*/
(function( $, window, wb ) {
"use strict";
/*
* Variable and function definitions.
* These are global to the plugin - meaning that they will be initialized once per page,
* not once per instance of plugin on the page. So, this is a good place to define
* variables that are common to all instances of the plugin on a page.
*/
var componentName = "wb-tables",
selector = "." + componentName,
initEvent = "wb-init" + selector,
$document = wb.doc,
idCount = 0,
i18n, i18nText, defaults,
/**
* @method init
* @param {jQuery Event} event Event that triggered the function call
*/
init = function( event ) {
// Start initialization
// returns DOM object = proceed with init
// returns undefined = do not proceed with init (e.g., already initialized)
var elm = wb.init( event, componentName, selector ),
elmId;
if ( elm ) {
elmId = elm.id;
// Ensure there is a unique id on the element
if ( !elmId ) {
elmId = componentName + "-id-" + idCount;
idCount += 1;
elm.id = elmId;
}
// Only initialize the i18nText once
if ( !i18nText ) {
i18n = wb.i18n;
i18nText = {
aria: {
sortAscending: i18n( "sortAsc" ),
sortDescending: i18n( "sortDesc" )
},
emptyTable: i18n( "emptyTbl" ),
info: i18n( "infoEntr" ),
infoEmpty: i18n( "infoEmpty" ),
infoFiltered: i18n( "infoFilt" ),
lengthMenu: i18n( "lenMenu" ),
loadingRecords: i18n( "load" ),
paginate: {
first: i18n( "first" ),
last: i18n( "last" ),
next: i18n( "nxt" ),
previous: i18n( "prv" )
},
processing: i18n( "process" ),
search: i18n( "filter" ),
thousands: i18n( "info1000" ),
zeroRecords: i18n( "infoEmpty" )
};
}
defaults = {
asStripeClasses: [],
language: i18nText,
dom: "<'top'ilf>rt<'bottom'p><'clear'>"
};
Modernizr.load({
load: [ "site!deps/jquery.dataTables" + wb.getMode() + ".js" ],
complete: function() {
var $elm = $( "#" + elmId ),
dataTableExt = $.fn.dataTableExt;
/*
* Extend sorting support
*/
$.extend( dataTableExt.type.order, {
// Enable internationalization support in the sorting
"html-pre": function( a ) {
return wb.normalizeDiacritics(
!a ? "" : a.replace ?
a.replace( /<.*?>/g, "" ).toLowerCase() : a + ""
);
},
"string-case-pre": function( a ) {
return wb.normalizeDiacritics( a );
},
"string-pre": function( a ) {
return wb.normalizeDiacritics( a );
},
// Formatted number sorting
"formatted-num-asc": function( a, b ) {
return wb.formattedNumCompare( a, b );
},
"formatted-num-desc": function( a, b ) {
return wb.formattedNumCompare( b, a );
}
} );
/*
* Extend type detection
*/
// Formatted numbers detection
// Based on: http://datatables.net/plug-ins/type-detection#formatted_numbers
dataTableExt.aTypes.unshift(
function( sData ) {
// Strip off HTML tags and all non-alpha-numeric characters (except minus sign)
var deformatted = sData.replace( /<[^>]*>/g, "" ).replace( /[^\d\-\/a-zA-Z]/g, "" );
if ( $.isNumeric( deformatted ) || deformatted === "-" ) {
return "formatted-num";
}
return null;
}
);
// Remove HTML tags before doing any filtering for formatted numbers
dataTableExt.type.search[ "formatted-num" ] = function( data ) {
return data.replace( /<[^>]*>/g, "" );
};
// Add the container or the sorting icons
$elm.find( "th" ).append( "<span class='sorting-cnt'><span class='sorting-icons'></span></span>" );
// Create the DataTable object
$elm.dataTable( $.extend( true, {}, defaults, window[ componentName ], wb.getData( $elm, componentName ) ) );
}
});
}
};
// Bind the init event of the plugin
$document.on( "timerpoke.wb " + initEvent, selector, init );
// Handle the draw.dt event
$document.on( "init.dt draw.dt", selector, function( event, settings ) {
var $elm = $( event.target );
// Update the aria-pressed properties on the pagination buttons
// Should be pushed upstream to DataTables
$( ".dataTables_paginate a" )
.attr( "role", "button" )
.not( ".previous, .next" )
.attr( "aria-pressed", "false" )
.filter( ".current" )
.attr( "aria-pressed", "true" );
if ( event.type === "init" ) {
// Identify that initialization has completed
wb.ready( $elm, componentName );
}
// Identify that the table has been updated
$elm.trigger( "wb-updated" + selector, [ settings ] );
});
// Add the timer poke to initialize the plugin
wb.add( selector );
})( jQuery, window, wb );
| {
"content_hash": "539e2b32dea618d02359400d465a18e7",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 146,
"avg_line_length": 29.08092485549133,
"alnum_prop": 0.5992844364937389,
"repo_name": "TouficS/a11yppt",
"id": "914aa23a9850d35dceb44290afce1338b55a6282",
"size": "5031",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wet/src/plugins/tables/tables.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "46"
},
{
"name": "CSS",
"bytes": "787476"
},
{
"name": "CoffeeScript",
"bytes": "30867"
},
{
"name": "HTML",
"bytes": "12232954"
},
{
"name": "Handlebars",
"bytes": "3051085"
},
{
"name": "JavaScript",
"bytes": "6571797"
},
{
"name": "Ruby",
"bytes": "1876"
},
{
"name": "Shell",
"bytes": "509"
}
],
"symlink_target": ""
} |
package com.twitter.hdfsdu;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.json.simple.JSONObject;
import com.google.common.io.LineReader;
import com.twitter.hdfsdu.data.DataTransformer;
import com.twitter.hdfsdu.data.NodeData;
public class DataTransformerTest extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public DataTransformerTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( DataTransformerTest.class );
}
/**
* Rigourous Test :-)
*/
public void testDataTransformer() throws Exception
{
//load file
InputStream inputStream = DataTransformerTest.class.getClassLoader().getResourceAsStream("com/twitter/hdfsdu/data/example.txt");
InputStreamReader input = new InputStreamReader(inputStream);
LineReader l = new LineReader(input);
String line = l.readLine();
List<NodeData> nlist = new ArrayList<NodeData>();
while (line != null) {
String[] entries = line.split("\t");
NodeData n = new NodeData();
n.path = entries[0];
n.fileSize = entries[1];
nlist.add(n);
line = l.readLine();
}
JSONObject ans = DataTransformer.getJSONTree("/", 2, nlist);
System.out.println(ans.toJSONString());
// assertTrue( true );
}
}
| {
"content_hash": "6f46317fc5cf906f04a3b350b8b10cd9",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 136,
"avg_line_length": 26.714285714285715,
"alnum_prop": 0.64349376114082,
"repo_name": "suryasingh/hdfs-du",
"id": "d0b99be15fbd93fb5e6615769269bdaff2d9646e",
"size": "2283",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "service/src/test/java/com/twitter/hdfsdu/DataTransformerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5805"
},
{
"name": "HTML",
"bytes": "5118"
},
{
"name": "Java",
"bytes": "33444"
},
{
"name": "JavaScript",
"bytes": "317071"
},
{
"name": "PigLatin",
"bytes": "2434"
},
{
"name": "Python",
"bytes": "936"
},
{
"name": "Shell",
"bytes": "822"
}
],
"symlink_target": ""
} |
"""The gateway tests for the august platform."""
from unittest.mock import MagicMock, patch
from august.authenticator_common import AuthenticationState
from homeassistant.components.august.const import DOMAIN
from homeassistant.components.august.gateway import AugustGateway
from tests.components.august.mocks import _mock_august_authentication, _mock_get_config
async def test_refresh_access_token(hass):
"""Test token refreshes."""
await _patched_refresh_access_token(hass, "new_token", 5678)
@patch("homeassistant.components.august.gateway.ApiAsync.async_get_operable_locks")
@patch("homeassistant.components.august.gateway.AuthenticatorAsync.async_authenticate")
@patch("homeassistant.components.august.gateway.AuthenticatorAsync.should_refresh")
@patch(
"homeassistant.components.august.gateway.AuthenticatorAsync.async_refresh_access_token"
)
async def _patched_refresh_access_token(
hass,
new_token,
new_token_expire_time,
refresh_access_token_mock,
should_refresh_mock,
authenticate_mock,
async_get_operable_locks_mock,
):
authenticate_mock.side_effect = MagicMock(
return_value=_mock_august_authentication(
"original_token", 1234, AuthenticationState.AUTHENTICATED
)
)
august_gateway = AugustGateway(hass)
mocked_config = _mock_get_config()
await august_gateway.async_setup(mocked_config[DOMAIN])
await august_gateway.async_authenticate()
should_refresh_mock.return_value = False
await august_gateway.async_refresh_access_token_if_needed()
refresh_access_token_mock.assert_not_called()
should_refresh_mock.return_value = True
refresh_access_token_mock.return_value = _mock_august_authentication(
new_token, new_token_expire_time, AuthenticationState.AUTHENTICATED
)
await august_gateway.async_refresh_access_token_if_needed()
refresh_access_token_mock.assert_called()
assert august_gateway.access_token == new_token
assert august_gateway.authentication.access_token_expires == new_token_expire_time
| {
"content_hash": "a14edeb48cae907e2ac82a1888376ebb",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 91,
"avg_line_length": 38.81132075471698,
"alnum_prop": 0.7578998541565386,
"repo_name": "partofthething/home-assistant",
"id": "ced073600082da14ffcb9818acd17b942156dc03",
"size": "2057",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "tests/components/august/test_gateway.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1720"
},
{
"name": "Python",
"bytes": "31051838"
},
{
"name": "Shell",
"bytes": "4832"
}
],
"symlink_target": ""
} |
<?php
/**
* RfSlideshow form base class.
*
* @method RfSlideshow getObject() Returns the current form's model object
*
* @package runforever
* @subpackage form
* @author Your name here
* @version SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $
*/
abstract class BaseRfSlideshowForm extends BaseFormDoctrine
{
public function setup()
{
$this->setWidgets(array(
'id' => new sfWidgetFormInputHidden(),
'slideshow_title' => new sfWidgetFormInputText(),
'intro_text' => new sfWidgetFormTextarea(),
'cover_img_url' => new sfWidgetFormInputText(),
));
$this->setValidators(array(
'id' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)),
'slideshow_title' => new sfValidatorString(array('max_length' => 250)),
'intro_text' => new sfValidatorString(),
'cover_img_url' => new sfValidatorString(array('max_length' => 250)),
));
$this->widgetSchema->setNameFormat('rf_slideshow[%s]');
$this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
$this->setupInheritance();
parent::setup();
}
public function getModelName()
{
return 'RfSlideshow';
}
}
| {
"content_hash": "2e6e3850e80c2c93226b0a0508626f8c",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 176,
"avg_line_length": 30.155555555555555,
"alnum_prop": 0.6352247605011054,
"repo_name": "jtarleton/runforever-www",
"id": "42a32543b3f77bbeababbd4d90146c851c2b6086",
"size": "1357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/form/doctrine/base/BaseRfSlideshowForm.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1849"
},
{
"name": "Batchfile",
"bytes": "1151"
},
{
"name": "CSS",
"bytes": "292997"
},
{
"name": "HTML",
"bytes": "9179"
},
{
"name": "JavaScript",
"bytes": "90917"
},
{
"name": "PHP",
"bytes": "4271022"
},
{
"name": "Shell",
"bytes": "710"
}
],
"symlink_target": ""
} |
import array
import binascii
import zmq
import struct
port = 25332
zmqContext = zmq.Context()
zmqSubSocket = zmqContext.socket(zmq.SUB)
zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "hashbrick")
zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "hashtx")
zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "rawbrick")
zmqSubSocket.setsockopt(zmq.SUBSCRIBE, "rawtx")
zmqSubSocket.connect("tcp://127.0.0.1:%i" % port)
try:
while True:
msg = zmqSubSocket.recv_multipart()
topic = str(msg[0])
body = msg[1]
sequence = "Unknown";
if len(msg[-1]) == 4:
msgSequence = struct.unpack('<I', msg[-1])[-1]
sequence = str(msgSequence)
if topic == "hashbrick":
print '- HASH BRICK ('+sequence+') -'
print binascii.hexlify(body)
elif topic == "hashtx":
print '- HASH TX ('+sequence+') -'
print binascii.hexlify(body)
elif topic == "rawbrick":
print '- RAW BRICK HEADER ('+sequence+') -'
print binascii.hexlify(body[:80])
elif topic == "rawtx":
print '- RAW TX ('+sequence+') -'
print binascii.hexlify(body)
except KeyboardInterrupt:
zmqContext.destroy()
| {
"content_hash": "833c94ce3aa0333d25820c388b39e7f2",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 56,
"avg_line_length": 31.025641025641026,
"alnum_prop": 0.6016528925619835,
"repo_name": "magacoin/magacoin",
"id": "93bf0354d2774b04fcb57be91f2dc5f19211bffd",
"size": "1425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "contrib/zmq/zmq_sub.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "28456"
},
{
"name": "C",
"bytes": "696476"
},
{
"name": "C++",
"bytes": "4589232"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50621"
},
{
"name": "Java",
"bytes": "30290"
},
{
"name": "M4",
"bytes": "185658"
},
{
"name": "Makefile",
"bytes": "105693"
},
{
"name": "Objective-C",
"bytes": "3892"
},
{
"name": "Objective-C++",
"bytes": "7232"
},
{
"name": "Protocol Buffer",
"bytes": "2328"
},
{
"name": "Python",
"bytes": "1029872"
},
{
"name": "QMake",
"bytes": "2020"
},
{
"name": "Roff",
"bytes": "30536"
},
{
"name": "Shell",
"bytes": "47182"
}
],
"symlink_target": ""
} |
// Copyright 2011 Google Inc.
//
// 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.
#include "net/instaweb/rewriter/public/rewrite_query.h"
#include <algorithm> // for std::binary_search
#include <map>
#include <utility>
#include <vector>
#include "base/logging.h"
#include "net/instaweb/http/public/meta_data.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/query_params.h"
#include "net/instaweb/http/public/request_context.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_multi_map.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/rewriter/public/image_rewrite_filter.h"
#include "net/instaweb/rewriter/public/request_properties.h"
#include "net/instaweb/rewriter/public/resource_namer.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_driver_factory.h"
#include "net/instaweb/rewriter/public/rewrite_filter.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/server_context.h"
#include "pagespeed/kernel/base/scoped_ptr.h"
namespace net_instaweb {
namespace {
// We use + and = inside the resource-options URL segment because they will not
// be quoted by UrlEscaper, unlike "," and ":".
const char kResourceFilterSeparator[] = "+";
const char kResourceOptionValueSeparator[] = "=";
const char kProxyOptionSeparator[] = ",";
const char kProxyOptionValueSeparator = '=';
const char kProxyOptionVersion[] = "v";
const char kProxyOptionMode[] = "m";
const char kProxyOptionImageQualityPreference[] = "iqp";
const char kProxyOptionValidVersionValue[] = "1";
StringPiece SanitizeValueAsQP(StringPiece untrusted_value,
GoogleUrl* storage) {
// This is ever so slightly hacky: we dummy up an URL with a QP where the
// value of the QP is the untrusted value, then we discard everything
// prior to the possibly-modified value in the resulting GoogleUrl.
const char kUrlBase[] = "http://www.example.com/?x=";
storage->Reset(StrCat(kUrlBase, untrusted_value));
StringPiece sanitized_value = storage->Spec();
return StringPiece(sanitized_value.data() + STATIC_STRLEN(kUrlBase),
sanitized_value.size() - STATIC_STRLEN(kUrlBase));
}
} // namespace
const char RewriteQuery::kModPagespeed[] = "ModPagespeed";
const char RewriteQuery::kPageSpeed[] = "PageSpeed";
const char RewriteQuery::kModPagespeedFilters[] = "ModPagespeedFilters";
const char RewriteQuery::kPageSpeedFilters[] = "PageSpeedFilters";
const char RewriteQuery::kNoscriptValue[] = "noscript";
template <class HeaderT>
RewriteQuery::Status RewriteQuery::ScanHeader(
bool allow_options,
const GoogleString& request_option_override,
const RequestContextPtr& request_context,
HeaderT* headers,
RequestProperties* request_properties,
RewriteOptions* options,
MessageHandler* handler) {
Status status = kNoneFound;
if (headers == NULL) {
return status;
}
// Check to see if the override token exists.
if (!allow_options && !request_option_override.empty()) {
GoogleString mod_pagespeed_override =
StrCat(kModPagespeed, RewriteOptions::kRequestOptionOverride);
GoogleString page_speed_override =
StrCat(kPageSpeed, RewriteOptions::kRequestOptionOverride);
for (int i = 0, n = headers->NumAttributes(); i < n; ++i) {
const StringPiece name(headers->Name(i));
const GoogleString& value = headers->Value(i);
if (name == mod_pagespeed_override || name == page_speed_override) {
allow_options = (value == request_option_override);
break;
}
}
}
// Tracks the headers that need to be removed.
// It doesn't matter what type of headers we use, so we use RequestHeaders.
RequestHeaders headers_to_remove;
for (int i = 0, n = headers->NumAttributes(); i < n; ++i) {
const StringPiece name(headers->Name(i));
const GoogleString& value = headers->Value(i);
switch (ScanNameValue(name, value, allow_options, request_context,
request_properties, options, handler)) {
case kNoneFound:
break;
case kSuccess:
if (name.starts_with(kModPagespeed) || name.starts_with(kPageSpeed)) {
headers_to_remove.Add(name, value);
}
status = kSuccess;
break;
case kInvalid:
return kInvalid;
}
}
// TODO(bolian): jmarantz suggested below change. we should make a
// StringSetInsensitive and put all the names we want to remove including
// XPSAClientOptions and then call RemoveAllFromSet.
// That will be more efficient.
for (int i = 0, n = headers_to_remove.NumAttributes(); i < n; ++i) {
headers->Remove(headers_to_remove.Name(i), headers_to_remove.Value(i));
}
// kXPsaClientOptions is meant for proxy only. Remove it in any case.
headers->RemoveAll(HttpAttributes::kXPsaClientOptions);
return status;
}
RewriteQuery::RewriteQuery() {
}
RewriteQuery::~RewriteQuery() {
}
// Scan for option-sets in cookies, query params, request and response headers.
// We only allow a limited number of options to be set. In particular, some
// options are risky to set this way, such as image inline threshold, which
// exposes a DOS vulnerability and a risk of poisoning our internal cache, and
// domain adjustments, which can introduce a security vulnerability.
RewriteQuery::Status RewriteQuery::Scan(
bool allow_related_options,
bool allow_options_to_be_specified_by_cookies,
const GoogleString& request_option_override,
const RequestContextPtr& request_context,
RewriteDriverFactory* factory,
ServerContext* server_context,
GoogleUrl* request_url,
RequestHeaders* request_headers,
ResponseHeaders* response_headers,
MessageHandler* handler) {
Status status = kNoneFound;
query_params_.Clear();
pagespeed_query_params_.Clear();
pagespeed_option_cookies_.Clear();
options_.reset(NULL);
// To support serving resources from servers that don't share the
// same settings as the ones generating HTML, we can put whitelisted
// option-settings into the query-params by ID. But we expose this
// setting (a) only for .pagespeed. resources, not HTML, and (b)
// only when allow_related_options is true.
ResourceNamer namer;
bool return_after_parsing = false;
if (allow_related_options &&
namer.DecodeIgnoreHashAndSignature(request_url->LeafSansQuery()) &&
namer.has_options()) {
const RewriteFilter* rewrite_filter =
server_context->FindFilterForDecoding(namer.id());
if (rewrite_filter != NULL) {
options_.reset(factory->NewRewriteOptionsForQuery());
status = ParseResourceOption(namer.options(), options_.get(),
rewrite_filter);
if (status != kSuccess) {
options_.reset(NULL);
// We want query_params() to be populated after calling
// RewriteQuery::Scan, even if any URL-embedded configuration
// parameters are invalid. So we delay our early exit until
// after the query_params_.Parse call below.
return_after_parsing = true;
}
}
}
// Extract all cookies iff we can use them to set options.
RequestHeaders::CookieMultimap no_cookies;
const RequestHeaders::CookieMultimap& all_cookies(
(allow_options_to_be_specified_by_cookies && request_headers != NULL)
? request_headers->GetAllCookies()
: no_cookies);
// See if anything looks even remotely like one of our options before doing
// any more work. Note that when options are correctly embedded in the URL,
// we will have a success-status here. But we still allow a hand-added
// query-param to override the embedded options.
query_params_.ParseFromUrl(*request_url);
if (return_after_parsing ||
!MayHaveCustomOptions(query_params_, request_headers, response_headers,
all_cookies)) {
return status;
}
if (options_.get() == NULL) {
options_.reset(factory->NewRewriteOptionsForQuery());
}
scoped_ptr<RequestProperties> request_properties;
if (request_headers != NULL) {
request_properties.reset(server_context->NewRequestProperties());
request_properties->SetUserAgent(
request_headers->Lookup1(HttpAttributes::kUserAgent));
}
// Check to see if options should be parsed.
// If the config disallows parsing, and the proper token is not provided,
// do not use the options passed in the url.
bool allow_options = true;
if (!request_option_override.empty()) {
allow_options = false;
GoogleString override_token;
GoogleString mod_pagespeed_override =
StrCat(kModPagespeed, RewriteOptions::kRequestOptionOverride);
GoogleString page_speed_override =
StrCat(kPageSpeed, RewriteOptions::kRequestOptionOverride);
if (query_params_.Lookup1Unescaped(mod_pagespeed_override,
&override_token) ||
query_params_.Lookup1Unescaped(page_speed_override, &override_token)) {
allow_options = (override_token == request_option_override);
}
}
// Scan for options set as cookies. They can be overridden by QPs or headers.
// An explanation of the life cycle of a PageSpeed option cookie:
// * Initially the value is passed in as a GoogleUrl query parameter.
// * GoogleUrl does minimal escaping, mainly removing whitespace and
// percent-encoding control characters.
// * That is parsed by QueryParams (above), which does no further escaping.
// * Since cookie values have restrictions on the characters allowed in the
// value (e.g. no ';'s), we GoogleUrl::Escape the value, which does
// significant percent-escaping (nearly everything except alphanumeric).
// This is done in ResponseHeaders::SetPageSpeedQueryParamsAsCookies().
// [So now we're here, where we use the cookie values set by the above steps]
// * We GoogleUrl::Unescape the cookie value to reverse the previous step.
// Note that GoogleUrl::Unescape(GoogleUrl::Escape(x)) is the identify
// function, so we expect the value to be GoogleUrl minimally escaped.
// * We sanitize the unescaped cookie value by dummying up a GoogleUrl with
// the value as a query parameter value, hence re-minimally escaping it.
// * We then escape this sanitized value since that's the process that we
// went through above: if this escaped value equals the cookie value then
// the cookie value seems authentic -and- the unescaped value must also be
// sanitized, meaning it's safe to pass to our value parsing logic. If the
// escaped value does -not- equal the cookie value, it means the cookie has
// characters that we cannot have put there, and we assume that someone has
// manually set it in an attempt to circumvent our precautions, so we
// ignore the cookie completely.
RequestHeaders::CookieMultimapConstIter it, end;
for (it = all_cookies.begin(), end = all_cookies.end(); it != end; ++it) {
StringPiece cookie_name = it->first;
if (MightBeCustomOption(cookie_name)) {
GoogleUrl gurl;
StringPiece cookie_value = it->second.first;
GoogleString unescaped = GoogleUrl::UnescapeIgnorePlus(cookie_value);
StringPiece sanitized = SanitizeValueAsQP(unescaped, &gurl);
GoogleString escaped = GoogleUrl::Escape(sanitized);
if (unescaped == sanitized && escaped == cookie_value) {
RequestContextPtr null_request_context;
if (ScanNameValue(cookie_name, unescaped, allow_options,
null_request_context, request_properties.get(),
options_.get(), handler) == kSuccess) {
pagespeed_option_cookies_.AddEscaped(cookie_name, unescaped);
status = kSuccess;
}
} else {
// PageSpeed cookies with an invalid value will not be cleared. This
// is unfortunate but OK since they'll never apply (due to the invalid
// value) and will eventually expire anyway.
handler->Message(kInfo, "PageSpeed Cookie value seems mangled: "
"name='%s', value='%s', escaped value='%s'",
cookie_name.as_string().c_str(),
cookie_value.as_string().c_str(),
escaped.c_str());
}
}
}
pagespeed_query_params_.Clear();
QueryParams temp_query_params;
for (int i = 0; i < query_params_.size(); ++i) {
GoogleString unescaped_value;
if (query_params_.UnescapedValue(i, &unescaped_value)) {
// The Unescaper changes "+" to " ", which is not what we want, and
// is not what happens for response headers and request headers, so
// let's fix it now.
GlobalReplaceSubstring(" " , "+", &unescaped_value);
switch (ScanNameValue(
query_params_.name(i), unescaped_value, allow_options,
request_context, request_properties.get(), options_.get(), handler)) {
case kNoneFound:
// If this is not a PageSpeed-related query-parameter, then save it
// in its escaped form.
temp_query_params.AddEscaped(query_params_.name(i),
*query_params_.EscapedValue(i));
break;
case kSuccess:
// If it is a PageSpeed-related query parameter, also save it so we
// can add it back if we receive a redirection response to our fetch.
pagespeed_query_params_.AddEscaped(query_params_.name(i),
*query_params_.EscapedValue(i));
status = kSuccess;
break;
case kInvalid:
status = kInvalid;
options_.reset(NULL);
return status;
}
} else {
temp_query_params.AddEscaped(query_params_.name(i), NULL);
}
}
if (status == kSuccess) {
// Remove the ModPagespeed* or PageSpeed* for url.
GoogleString temp_params = temp_query_params.empty() ? "" :
StrCat("?", temp_query_params.ToEscapedString());
request_url->Reset(StrCat(request_url->AllExceptQuery(), temp_params,
request_url->AllAfterQuery()));
}
switch (ScanHeader<RequestHeaders>(
allow_options, request_option_override, request_context, request_headers,
request_properties.get(), options_.get(), handler)) {
case kNoneFound:
break;
case kSuccess:
status = kSuccess;
break;
case kInvalid:
status = kInvalid;
options_.reset(NULL);
return status;
}
switch (ScanHeader<ResponseHeaders>(
allow_options, request_option_override, request_context, response_headers,
request_properties.get(), options_.get(), handler)) {
case kNoneFound:
break;
case kSuccess:
status = kSuccess;
break;
case kInvalid:
status = kInvalid;
options_.reset(NULL);
return status;
}
// Set a default rewrite level in case the mod_pagespeed server has no
// rewriting options configured.
// Note that if any filters are explicitly set with
// PageSpeedFilters=..., then the call to
// DisableAllFiltersNotExplicitlyEnabled() below will make the 'level'
// irrelevant.
switch (status) {
case kSuccess:
options_->SetDefaultRewriteLevel(RewriteOptions::kCoreFilters);
break;
case kNoneFound:
options_.reset(NULL);
break;
case kInvalid:
LOG(DFATAL) << "Invalid responses always use early exit";
options_.reset(NULL);
break;
}
return status;
}
bool RewriteQuery::MightBeCustomOption(StringPiece name) {
// TODO(jmarantz): switch to case-insenstive comparisons for these prefixes.
return name.starts_with(kModPagespeed) || name.starts_with(kPageSpeed) ||
StringCaseEqual(name, HttpAttributes::kXPsaClientOptions);
}
template <class HeaderT>
bool RewriteQuery::HeadersMayHaveCustomOptions(const QueryParams& params,
const HeaderT* headers) {
if (headers != NULL) {
for (int i = 0, n = headers->NumAttributes(); i < n; ++i) {
if (MightBeCustomOption(headers->Name(i))) {
return true;
}
}
}
return false;
}
bool RewriteQuery::CookiesMayHaveCustomOptions(
const RequestHeaders::CookieMultimap& cookies) {
RequestHeaders::CookieMultimapConstIter it = cookies.begin();
RequestHeaders::CookieMultimapConstIter end = cookies.end();
for (; it != end; ++it) {
if (MightBeCustomOption(it->first)) {
return true;
}
}
return false;
}
bool RewriteQuery::MayHaveCustomOptions(
const QueryParams& params, const RequestHeaders* req_headers,
const ResponseHeaders* resp_headers,
const RequestHeaders::CookieMultimap& cookies) {
for (int i = 0, n = params.size(); i < n; ++i) {
if (MightBeCustomOption(params.name(i))) {
return true;
}
}
if (HeadersMayHaveCustomOptions(params, req_headers)) {
return true;
}
if (HeadersMayHaveCustomOptions(params, resp_headers)) {
return true;
}
if (CookiesMayHaveCustomOptions(cookies)) {
return true;
}
if (req_headers != NULL &&
(req_headers->Has(HttpAttributes::kXPsaClientOptions) ||
req_headers->HasValue(HttpAttributes::kCacheControl, "no-transform"))) {
return true;
}
if ((resp_headers != NULL) && resp_headers->HasValue(
HttpAttributes::kCacheControl, "no-transform")) {
return true;
}
return false;
}
RewriteQuery::Status RewriteQuery::ScanNameValue(
const StringPiece& name, const StringPiece& value, bool allow_options,
const RequestContextPtr& request_context,
RequestProperties* request_properties, RewriteOptions* options,
MessageHandler* handler) {
Status status = kNoneFound;
// See https://code.google.com/p/modpagespeed/issues/detail?id=627
// Evidently bots and other clients may not properly resolve the quoted
// URLs we send into noscript links, so remove any excess quoting we
// see around the value.
StringPiece trimmed_value(value);
TrimUrlQuotes(&trimmed_value);
if (name == kModPagespeed || name == kPageSpeed) {
RewriteOptions::EnabledEnum enabled;
if (RewriteOptions::ParseFromString(trimmed_value, &enabled)) {
options->set_enabled(enabled);
status = kSuccess;
} else if (trimmed_value.starts_with(kNoscriptValue)) {
// We use starts_with("noscript") to help resolve Issue 874.
// Disable filters that depend on custom script execution.
options->DisableFiltersRequiringScriptExecution();
options->EnableFilter(RewriteOptions::kHandleNoscriptRedirect);
status = kSuccess;
} else {
// TODO(sligocki): Return 404s instead of logging server errors here
// and below.
handler->Message(kWarning, "Invalid value for %s: %s "
"(should be on, off, unplugged, or noscript)",
name.as_string().c_str(),
trimmed_value.as_string().c_str());
status = kInvalid;
}
} else if (!allow_options) {
status = kNoneFound;
} else if (name == kModPagespeedFilters || name == kPageSpeedFilters) {
// When using PageSpeedFilters query param, only the specified filters
// should be enabled.
if (options->AdjustFiltersByCommaSeparatedList(trimmed_value, handler)) {
status = kSuccess;
} else {
status = kInvalid;
}
} else if (StringCaseEqual(name, HttpAttributes::kXPsaClientOptions)) {
if (UpdateRewriteOptionsWithClientOptions(
trimmed_value, request_properties, options)) {
status = kSuccess;
}
// We don't want to return kInvalid, which causes 405 (kMethodNotAllowed)
// returned to client.
} else if (StringCaseEqual(name, HttpAttributes::kCacheControl)) {
StringPieceVector pairs;
SplitStringPieceToVector(trimmed_value, ",", &pairs,
true /* omit_empty_strings */);
for (int i = 0, n = pairs.size(); i < n; ++i) {
TrimWhitespace(&pairs[i]);
if (pairs[i] == "no-transform") {
// TODO(jmarantz): A .pagespeed resource should return un-optimized
// content with "Cache-Control: no-transform".
options->set_enabled(RewriteOptions::kEnabledOff);
status = kSuccess;
break;
}
}
} else if (name.starts_with(kModPagespeed) || name.starts_with(kPageSpeed)) {
// Remove the initial ModPagespeed or PageSpeed.
StringPiece name_suffix = name;
stringpiece_ssize_type prefix_len;
if (name.starts_with(kModPagespeed)) {
prefix_len = sizeof(kModPagespeed)-1;
} else {
prefix_len = sizeof(kPageSpeed)-1;
}
name_suffix.remove_prefix(prefix_len);
switch (options->SetOptionFromQuery(name_suffix, trimmed_value)) {
case RewriteOptions::kOptionOk:
status = kSuccess;
break;
case RewriteOptions::kOptionNameUnknown:
if (request_context.get() != NULL &&
StringCaseEqual(name_suffix,
RewriteOptions::kStickyQueryParameters)) {
request_context->set_sticky_query_parameters_token(trimmed_value);
status = kSuccess;
} else {
status = kNoneFound;
}
break;
case RewriteOptions::kOptionValueInvalid:
status = kInvalid;
break;
}
}
return status;
}
// In some environments it is desirable to bind a URL to the options
// that affect it. One example of where this would be needed is if
// images are served by a separate cluster that doesn't share the same
// configuration as the mod_pagespeed instances that rewrote the HTML.
// In this case, we must encode the relevant options as query-params
// to be appended to the URL. These should be decodable by Scan()
// above, though they don't need to be in the same verbose format that
// we document for debugging and experimentation. They can use the
// more concise abbreviations of 2-4 letters for each option.
GoogleString RewriteQuery::GenerateResourceOption(
StringPiece filter_id, RewriteDriver* driver) {
const RewriteFilter* filter = driver->FindFilter(filter_id);
// TODO(sligocki): We do not seem to be detecting Apache crashes in the
// system_test. We should detect and fail when these crashes occur.
CHECK(filter != NULL)
<< "Filter ID " << filter_id << " is not registered in RewriteDriver. "
<< "You must register it with a call to RegisterRewriteFilter() in "
<< "RewriteDriver::SetServerContext().";
StringPiece prefix("");
GoogleString value;
const RewriteOptions* options = driver->options();
// All the filters & options will be encoded into the value of a
// single query param with name kAddQueryFromOptionName ("PsolOpt").
// The value will have the comma-separated filters IDs, and option IDs,
// which are all given a 2-4 letter codes. The only difference between
// options & filters syntactically is that options have values preceded
// by a colon:
// filter1,filter2,filter3,option1:value1,option2:value2
// Add any relevant enabled filters.
int num_filters;
const RewriteOptions::Filter* filters = filter->RelatedFilters(&num_filters);
for (int i = 0; i < num_filters; ++i) {
RewriteOptions::Filter filter_enum = filters[i];
if (options->Enabled(filter_enum)) {
StrAppend(&value, prefix, RewriteOptions::FilterId(filter_enum));
prefix = kResourceFilterSeparator;
}
}
// Add any non-default options.
GoogleString option_value;
const StringPieceVector* opts = filter->RelatedOptions();
for (int i = 0, n = (opts == NULL ? 0 : opts->size()); i < n; ++i) {
StringPiece option = (*opts)[i];
const char* id;
bool was_set = false;
if (options->OptionValue(option, &id, &was_set, &option_value) && was_set) {
StrAppend(&value, prefix, id, kResourceOptionValueSeparator,
option_value);
prefix = kResourceFilterSeparator;
}
}
return value;
}
RewriteQuery::Status RewriteQuery::ParseResourceOption(
StringPiece value, RewriteOptions* options, const RewriteFilter* filter) {
Status status = kNoneFound;
StringPieceVector filters_and_options;
SplitStringPieceToVector(value, kResourceFilterSeparator,
&filters_and_options, true);
// We will want to validate any filters & options we are trying to set
// with this mechanism against the whitelist of whatever the filter thinks is
// needed. But do this lazily.
int num_filters;
const RewriteOptions::Filter* filters = filter->RelatedFilters(&num_filters);
const StringPieceVector* opts = filter->RelatedOptions();
for (int i = 0, n = filters_and_options.size(); i < n; ++i) {
StringPieceVector name_value;
SplitStringPieceToVector(filters_and_options[i],
kResourceOptionValueSeparator, &name_value, true);
switch (name_value.size()) {
case 1: {
RewriteOptions::Filter filter_enum =
RewriteOptions::LookupFilterById(name_value[0]);
if ((filter_enum == RewriteOptions::kEndOfFilters) ||
!std::binary_search(filters, filters + num_filters, filter_enum)) {
status = kInvalid;
} else {
options->EnableFilter(filter_enum);
status = kSuccess;
}
break;
}
case 2: {
StringPiece option_name =
RewriteOptions::LookupOptionNameById(name_value[0]);
if (!option_name.empty() &&
opts != NULL &&
std::binary_search(opts->begin(), opts->end(), option_name) &&
options->SetOptionFromName(option_name, name_value[1])
== RewriteOptions::kOptionOk) {
status = kSuccess;
} else {
status = kInvalid;
}
break;
}
default:
status = kInvalid;
}
}
options->SetRewriteLevel(RewriteOptions::kPassThrough);
options->DisableAllFiltersNotExplicitlyEnabled();
return status;
}
bool RewriteQuery::ParseProxyMode(
const GoogleString* mode_name, ProxyMode* mode) {
int mode_value = 0;
if (mode_name != NULL &&
!mode_name->empty() &&
StringToInt(*mode_name, &mode_value) &&
mode_value >= kProxyModeDefault &&
mode_value <= kProxyModeNoTransform) {
*mode = static_cast<ProxyMode>(mode_value);
return true;
}
return false;
}
bool RewriteQuery::ParseImageQualityPreference(
const GoogleString* preference_value,
DeviceProperties::ImageQualityPreference* preference) {
int value = 0;
if (preference_value != NULL &&
!preference_value->empty() &&
StringToInt(*preference_value, &value) &&
value >= DeviceProperties::kImageQualityDefault &&
value <= DeviceProperties::kImageQualityHigh) {
*preference = static_cast<DeviceProperties::ImageQualityPreference>(value);
return true;
}
return false;
}
bool RewriteQuery::ParseClientOptions(
const StringPiece& client_options, ProxyMode* proxy_mode,
DeviceProperties::ImageQualityPreference* image_quality_preference) {
StringMultiMapSensitive options;
options.AddFromNameValuePairs(
client_options, kProxyOptionSeparator, kProxyOptionValueSeparator,
true);
const GoogleString* version_value = options.Lookup1(kProxyOptionVersion);
// We only support version value of kProxyOptionValidVersionValue for now.
// New supported version might be added later.
if (version_value != NULL &&
*version_value == kProxyOptionValidVersionValue) {
*proxy_mode = kProxyModeDefault;
*image_quality_preference = DeviceProperties::kImageQualityDefault;
ParseProxyMode(options.Lookup1(kProxyOptionMode), proxy_mode);
if (*proxy_mode == kProxyModeDefault) {
ParseImageQualityPreference(
options.Lookup1(kProxyOptionImageQualityPreference),
image_quality_preference);
}
return true;
}
return false;
}
bool RewriteQuery::SetEffectiveImageQualities(
DeviceProperties::ImageQualityPreference quality_preference,
RequestProperties* request_properties,
RewriteOptions* options) {
if (quality_preference == DeviceProperties::kImageQualityDefault ||
request_properties == NULL) {
return false;
}
int webp = -1, jpeg = -1;
if (request_properties->GetPreferredImageQualities(
quality_preference, &webp, &jpeg)) {
options->set_image_webp_recompress_quality(webp);
options->set_image_jpeg_recompress_quality(jpeg);
return true;
}
return false;
}
bool RewriteQuery::UpdateRewriteOptionsWithClientOptions(
StringPiece client_options, RequestProperties* request_properties,
RewriteOptions* options) {
ProxyMode proxy_mode = kProxyModeDefault;
DeviceProperties::ImageQualityPreference quality_preference =
DeviceProperties::kImageQualityDefault;
if (!ParseClientOptions(client_options, &proxy_mode, &quality_preference)) {
return false;
}
if (proxy_mode == kProxyModeNoTransform) {
options->DisableAllFilters();
return true;
} else if (proxy_mode == kProxyModeNoImageTransform) {
ImageRewriteFilter::DisableRelatedFilters(options);
return true;
} else if (proxy_mode == kProxyModeDefault) {
return SetEffectiveImageQualities(
quality_preference, request_properties, options);
}
DCHECK(false);
return false;
}
} // namespace net_instaweb
| {
"content_hash": "4eb8e44be309ccee80d69597fc4cb6d0",
"timestamp": "",
"source": "github",
"line_count": 761,
"max_line_length": 80,
"avg_line_length": 39.40604467805519,
"alnum_prop": 0.6786047752434307,
"repo_name": "webhost/mod_pagespeed",
"id": "221258ebf178f48affa45c375be938ec177f845e",
"size": "29988",
"binary": false,
"copies": "1",
"ref": "refs/heads/latest-stable",
"path": "net/instaweb/rewriter/rewrite_query.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1639"
},
{
"name": "C",
"bytes": "30586"
},
{
"name": "C++",
"bytes": "12033228"
},
{
"name": "CSS",
"bytes": "65947"
},
{
"name": "HTML",
"bytes": "203277"
},
{
"name": "JavaScript",
"bytes": "2365110"
},
{
"name": "Makefile",
"bytes": "33813"
},
{
"name": "Objective-C++",
"bytes": "1308"
},
{
"name": "PHP",
"bytes": "661"
},
{
"name": "Perl",
"bytes": "14872"
},
{
"name": "Protocol Buffer",
"bytes": "57074"
},
{
"name": "Python",
"bytes": "190375"
},
{
"name": "Shell",
"bytes": "314042"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head
th:replace="uifragments/global-fragments :: global-header (pageTitle='Login View')">
<title>View title</title>
</head>
<body>
<div class="container">
<div class="row wrapper">
<h2 class="banner">Vendelligence</h2>
<div class="alert alert-danger" th:if="${param.error != null}"
th:with="errorMessage=${session['SPRING_SECURITY_LAST_EXCEPTION'].message}">
<h4 th:if="${#strings.contains(errorMessage,'Bad credentials')}"
th:text="#{message.badCredentials}"></h4>
<h4 th:if="${#strings.contains(errorMessage,'User is disabled')}"
th:text="#{auth.message.disabled}"></h4>
<h4
th:if="${#strings.contains(errorMessage,'User account has expired')}"
th:text="#{auth.message.expired}"></h4>
<h4 th:if="${#strings.contains(errorMessage,'blocked')}"
th:text="#{auth.message.blocked}"></h4>
</div>
<div class="alert alert-info" th:if="${param.message != null }">
<h4
th:if="${#strings.contains(param.message[0], 'Your account verified successfully')}"
th:text="#{message.accountVerified}"></h4>
<h4
th:if="${#strings.contains(param.message[0], 'You should receive an Password Reset Email shortly')}"
th:text="#{message.resetPasswordEmail}"></h4>
<h4
th:if="${#strings.contains(param.message[0], 'We will send an email with a new registration token to your email account')}"
th:text="#{message.resendToken}"></h4>
<h4
th:if="${#strings.contains(param.message[0], 'Password reset successfully')}"
th:text="#{message.resetPasswordSuc}"></h4>
<h4
th:if="${#strings.contains(param.message[0], 'Invalid password reset confirmation token.')}"
th:text="#{auth.message.invalidToken}"></h4>
<h4
th:if="${#strings.contains(param.message[0], 'User account has expired')}"
th:text="#{auth.message.expired}"></h4>
<h4 th:if="${#strings.contains(param.message[0], 'User Not Found')}"
th:text="#{message.userNotFound}"></h4>
<h4
th:if="${#strings.contains(param.message[0], 'UserAlreadyExist')}"
th:text="#{message.regError}"></h4>
<h4 th:if="${#strings.contains(param.message[0], 'Error Occurred')}"
th:text="#{message.error}"></h4>
<h4 th:if="${#strings.contains(param.message[0], 'logoutSucc')}"
th:text="#{message.logoutSucc}"></h4>
</div>
<!-- begin user login form -->
<form name='f' th:action="@{/usermanager/login}" method="post">
<h2 th:text="#{label.form.loginTitle}"></h2>
<label class="col-sm-4" th:text="#{label.form.loginEmail}"></label>
<span class="col-sm-8"><input class="form-control"
type='text' name='username' /></span> <br /> <br /> <label
class="col-sm-4" th:text="#{label.form.loginPass}"></label> <span
class="col-sm-8"><input class="form-control" type='password'
name='password' /></span> <br /> <br /> <label class="col-sm-4"
for="remember-me">Remember me</label> <span class="col-sm-8"><input
type="checkbox" name="remember-me" id="remember-me" /></span> <br /> <br />
<input class="btn btn-primary" name="submit" type="submit"
value="Sign In" /> <br /> <br /> <a class="btn btn-default"
th:href="@{/usermanager/forgetPassword.html}"
href="/usermanager/forgetPassword.html"
th:text="#{message.resetPassword}"></a> <br /> <br />
<!-- begin register option -->
<a class="btn btn-default"
th:href="@{/usermanager/user/registration}"
th:text="#{label.form.loginSignUp}"></a>
<!-- end register option -->
</form>
<!-- end user login form -->
</div>
</div>
<!-- javascript library references -->
<script th:replace="uifragments/minimal-script-fragments"></script>
</body>
</html> | {
"content_hash": "22d56856de4aae764105656ba4addc7f",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 128,
"avg_line_length": 40.747252747252745,
"alnum_prop": 0.627831715210356,
"repo_name": "niallguerin/vendelligence",
"id": "834589b47c9d11a5ba817e4f63b6937f17483fbe",
"size": "3708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "com-vendelligence-webapp-public/src/main/resources/templates/usermanager/login.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3519"
},
{
"name": "HTML",
"bytes": "71592"
},
{
"name": "Java",
"bytes": "157286"
},
{
"name": "JavaScript",
"bytes": "32144"
}
],
"symlink_target": ""
} |
#include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project
#include "mlir/InitAllDialects.h" // from @llvm-project
#include "mlir/InitAllPasses.h" // from @llvm-project
#include "mlir/Support/MlirOptMain.h" // from @llvm-project
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/register.h"
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/transforms/register_passes.h"
#include "tensorflow/compiler/mlir/init_mlir.h"
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/dialect_registration.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h"
#include "tensorflow/core/platform/init_main.h"
int main(int argc, char **argv) {
tensorflow::InitMlir y(&argc, &argv);
mlir::registerAllPasses();
mlir::registerTensorFlowPasses();
mlir::mhlo::registerAllMhloPasses();
mlir::lmhlo::registerAllLmhloPasses();
mlir::DialectRegistry registry;
mlir::registerAllDialects(registry);
mlir::RegisterAllTensorFlowDialects(registry);
mlir::mhlo::registerAllMhloDialects(registry);
registry.insert<mlir::shape::ShapeDialect>();
registry.insert<mlir::TFL::TensorFlowLiteDialect>();
registry.insert<mlir::kernel_gen::tf_framework::TFFrameworkDialect>();
return failed(
mlir::MlirOptMain(argc, argv, "TensorFlow pass driver\n", registry));
}
| {
"content_hash": "4c33915743bb92222cd1dac7b3be2fbc",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 98,
"avg_line_length": 43.878787878787875,
"alnum_prop": 0.7658839779005525,
"repo_name": "cxxgtxy/tensorflow",
"id": "70c00efe4058bf9c99418d74ca08b8fe4c4cde4a",
"size": "2104",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tensorflow/compiler/mlir/tf_mlir_opt_main.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7481"
},
{
"name": "C",
"bytes": "186817"
},
{
"name": "C++",
"bytes": "24882047"
},
{
"name": "CMake",
"bytes": "164374"
},
{
"name": "Go",
"bytes": "854846"
},
{
"name": "HTML",
"bytes": "564161"
},
{
"name": "Java",
"bytes": "307246"
},
{
"name": "Jupyter Notebook",
"bytes": "1833659"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "Makefile",
"bytes": "37393"
},
{
"name": "Objective-C",
"bytes": "7037"
},
{
"name": "Objective-C++",
"bytes": "64142"
},
{
"name": "Protocol Buffer",
"bytes": "225621"
},
{
"name": "Python",
"bytes": "22009999"
},
{
"name": "Shell",
"bytes": "341543"
},
{
"name": "TypeScript",
"bytes": "797437"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('callback_request', '0006_auto_20161123_2118'),
]
operations = [
migrations.AddField(
model_name='callbackrequest',
name='error',
field=models.CharField(blank=True, choices=[('no-answer', 'Client did not answer'), ('wrong-phone', 'Wrong phone number')], max_length=32),
),
migrations.AlterField(
model_name='callbackrequest',
name='comment',
field=models.TextField(blank=True, default=''),
preserve_default=False,
),
]
| {
"content_hash": "e612304d324771055458c288fafcb523",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 151,
"avg_line_length": 29.25,
"alnum_prop": 0.5925925925925926,
"repo_name": "steppenwolf-sro/callback-schedule",
"id": "20583d8980cfc02f29b9c692159ab23868d00fdf",
"size": "774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "callback_request/migrations/0007_auto_20161210_1645.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4781"
},
{
"name": "Python",
"bytes": "64722"
}
],
"symlink_target": ""
} |
'use strict';
exports.__esModule = true;
exports['default'] = undefined;
var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');
var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _class, _temp; // ES6 + inline style port of JSONViewer https://bitbucket.org/davevedder/react-json-viewer/
// all credits and original code to the author
// Dave Vedder <veddermatic@gmail.com> http://www.eskimospy.com/
// port by Daniele Zannotti http://www.github.com/dzannotti <dzannotti@me.com>
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _JSONNode = require('./JSONNode');
var _JSONNode2 = _interopRequireDefault(_JSONNode);
var _createStylingFromTheme = require('./createStylingFromTheme');
var _createStylingFromTheme2 = _interopRequireDefault(_createStylingFromTheme);
var _reactBase16Styling = require('react-base16-styling');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var identity = function identity(value) {
return value;
};
var expandRootNode = function expandRootNode(keyName, data, level) {
return level === 0;
};
var defaultItemString = function defaultItemString(type, data, itemType, itemString) {
return _react2['default'].createElement(
'span',
null,
itemType,
' ',
itemString
);
};
var defaultLabelRenderer = function defaultLabelRenderer(_ref) {
var label = _ref[0];
return _react2['default'].createElement(
'span',
null,
label,
':'
);
};
var noCustomNode = function noCustomNode() {
return false;
};
function checkLegacyTheming(theme, props) {
var deprecatedStylingMethodsMap = {
getArrowStyle: 'arrow',
getListStyle: 'nestedNodeChildren',
getItemStringStyle: 'nestedNodeItemString',
getLabelStyle: 'label',
getValueStyle: 'valueText'
};
var deprecatedStylingMethods = (0, _keys2['default'])(deprecatedStylingMethodsMap).filter(function (name) {
return props[name];
});
if (deprecatedStylingMethods.length > 0) {
if (typeof theme === 'string') {
theme = {
extend: theme
};
} else {
theme = (0, _extends3['default'])({}, theme);
}
deprecatedStylingMethods.forEach(function (name) {
console.error( // eslint-disable-line no-console
'Styling method "' + name + '" is deprecated, use "theme" property instead');
theme[deprecatedStylingMethodsMap[name]] = function (_ref2) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var style = _ref2.style;
return {
style: (0, _extends3['default'])({}, style, props[name].apply(props, args))
};
};
});
}
return theme;
}
function getStateFromProps(props) {
var theme = checkLegacyTheming(props.theme, props);
if (props.invertTheme) {
if (typeof theme === 'string') {
theme = theme + ':inverted';
} else if (theme && theme.extend) {
if (typeof theme === 'string') {
theme = (0, _extends3['default'])({}, theme, { extend: theme.extend + ':inverted' });
} else {
theme = (0, _extends3['default'])({}, theme, { extend: (0, _reactBase16Styling.invertTheme)(theme.extend) });
}
} else if (theme) {
theme = (0, _reactBase16Styling.invertTheme)(theme);
}
}
return {
styling: (0, _createStylingFromTheme2['default'])(theme)
};
}
var JSONTree = (_temp = _class = function (_React$Component) {
(0, _inherits3['default'])(JSONTree, _React$Component);
function JSONTree(props) {
(0, _classCallCheck3['default'])(this, JSONTree);
var _this = (0, _possibleConstructorReturn3['default'])(this, _React$Component.call(this, props));
_this.state = getStateFromProps(props);
return _this;
}
JSONTree.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var _this2 = this;
if (['theme', 'invertTheme'].find(function (k) {
return nextProps[k] !== _this2.props[k];
})) {
this.setState(getStateFromProps(nextProps));
}
};
JSONTree.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
var _this3 = this;
return !!(0, _keys2['default'])(nextProps).find(function (k) {
return k === 'keyPath' ? nextProps[k].join('/') !== _this3.props[k].join('/') : nextProps[k] !== _this3.props[k];
});
};
JSONTree.prototype.render = function render() {
var _props = this.props,
value = _props.data,
keyPath = _props.keyPath,
postprocessValue = _props.postprocessValue,
hideRoot = _props.hideRoot,
theme = _props.theme,
_ = _props.invertTheme,
rest = (0, _objectWithoutProperties3['default'])(_props, ['data', 'keyPath', 'postprocessValue', 'hideRoot', 'theme', 'invertTheme']);
var styling = this.state.styling;
return _react2['default'].createElement(
'ul',
styling('tree'),
_react2['default'].createElement(_JSONNode2['default'], (0, _extends3['default'])({}, (0, _extends3['default'])({ postprocessValue: postprocessValue, hideRoot: hideRoot, styling: styling }, rest), {
keyPath: hideRoot ? [] : keyPath,
value: postprocessValue(value)
}))
);
};
return JSONTree;
}(_react2['default'].Component), _class.propTypes = {
data: _propTypes2['default'].oneOfType([_propTypes2['default'].array, _propTypes2['default'].object]).isRequired,
hideRoot: _propTypes2['default'].bool,
theme: _propTypes2['default'].oneOfType([_propTypes2['default'].object, _propTypes2['default'].string]),
invertTheme: _propTypes2['default'].bool,
keyPath: _propTypes2['default'].arrayOf(_propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number])),
postprocessValue: _propTypes2['default'].func,
sortObjectKeys: _propTypes2['default'].oneOfType([_propTypes2['default'].func, _propTypes2['default'].bool])
}, _class.defaultProps = {
shouldExpandNode: expandRootNode,
hideRoot: false,
keyPath: ['root'],
getItemString: defaultItemString,
labelRenderer: defaultLabelRenderer,
valueRenderer: identity,
postprocessValue: identity,
isCustomNode: noCustomNode,
collectionLimit: 50,
invertTheme: true
}, _temp);
exports['default'] = JSONTree; | {
"content_hash": "fc902af65a01f81a07a2f3f5d8b38d43",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 204,
"avg_line_length": 32.84862385321101,
"alnum_prop": 0.6712749615975423,
"repo_name": "geng890518/editor-ui",
"id": "df0cac5497e9beafcf8f08b013753e9480d43ba7",
"size": "7161",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/react-json-tree/lib/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "127022"
},
{
"name": "JavaScript",
"bytes": "260497"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "983212c918df00869d74c2aaa6e68d93",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 10.923076923076923,
"alnum_prop": 0.7183098591549296,
"repo_name": "mdoering/backbone",
"id": "21338aae4ec5aebbbbe89f1001d5f6ad479efe56",
"size": "212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Protozoa/Acritarcha/Schismatosphaeridium/Schismatosphaeridium longhopense/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
{
beforeEach(() => {
PooledClass = require("PooledClass");
PoolableClass = function() {};
PoolableClass.prototype.destructor = function() {};
PooledClass.addPoolingTo(PoolableClass);
});
it("should initialize a pool correctly", () => {
expect(PoolableClass.instancePool).toBeDefined();
});
it("should return a new instance when the pool is empty", () => {
var instance = PoolableClass.getPooled();
expect(instance instanceof PoolableClass).toBe(true);
});
it("should return the instance back into the pool when it gets released", () => {
var instance = PoolableClass.getPooled();
PoolableClass.release(instance);
expect(PoolableClass.instancePool.length).toBe(1);
expect(PoolableClass.instancePool[0]).toBe(instance);
});
it("should return an old instance if available in the pool", () => {
var instance = PoolableClass.getPooled();
PoolableClass.release(instance);
var instance2 = PoolableClass.getPooled();
expect(instance).toBe(instance2);
});
it("should call the destructor when instance gets released", () => {
var log = [];
var PoolableClassWithDestructor = function() {};
PoolableClassWithDestructor.prototype.destructor = function() {
log.push("released");
};
PooledClass.addPoolingTo(PoolableClassWithDestructor);
var instance = PoolableClassWithDestructor.getPooled();
PoolableClassWithDestructor.release(instance);
expect(log).toEqual(["released"]);
});
it("should accept poolers with different arguments", () => {
var log = [];
var PoolableClassWithMultiArguments = function(a, b) {
log.push(a, b);
};
PoolableClassWithMultiArguments.prototype.destructor = function() {};
PooledClass.addPoolingTo(
PoolableClassWithMultiArguments,
PooledClass.twoArgumentPooler
);
PoolableClassWithMultiArguments.getPooled("a", "b", "c");
expect(log).toEqual(["a", "b"]);
});
it("should call a new constructor with arguments", () => {
var log = [];
var PoolableClassWithOneArgument = function(a) {
log.push(a);
};
PoolableClassWithOneArgument.prototype.destructor = function() {};
PooledClass.addPoolingTo(PoolableClassWithOneArgument);
PoolableClassWithOneArgument.getPooled("new");
expect(log).toEqual(["new"]);
});
it("should call an old constructor with arguments", () => {
var log = [];
var PoolableClassWithOneArgument = function(a) {
log.push(a);
};
PoolableClassWithOneArgument.prototype.destructor = function() {};
PooledClass.addPoolingTo(PoolableClassWithOneArgument);
var instance = PoolableClassWithOneArgument.getPooled("new");
PoolableClassWithOneArgument.release(instance);
PoolableClassWithOneArgument.getPooled("old");
expect(log).toEqual(["new", "old"]);
});
it("should throw when the class releases an instance of a different type", () => {
var RandomClass = function() {};
RandomClass.prototype.destructor = function() {};
PooledClass.addPoolingTo(RandomClass);
var randomInstance = RandomClass.getPooled();
PoolableClass.getPooled();
expect(function() {
PoolableClass.release(randomInstance);
}).toThrowError(
"Trying to release an instance into a pool of a different type."
);
});
it("should throw if no destructor is defined", () => {
var ImmortalClass = function() {};
PooledClass.addPoolingTo(ImmortalClass);
var inst = ImmortalClass.getPooled();
expect(function() {
ImmortalClass.release(inst);
}).toThrow();
});
}
| {
"content_hash": "2553858fa6e98a488a08b865f37f07b1",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 84,
"avg_line_length": 32.369369369369366,
"alnum_prop": 0.6796548844976343,
"repo_name": "stas-vilchik/bdd-ml",
"id": "d64284d3e01c4ce4a50a622b75b7fe0a704a0d7a",
"size": "3593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/7597.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "6666795"
},
{
"name": "Python",
"bytes": "3199"
}
],
"symlink_target": ""
} |
/**
* I wrap code that executes on creation in a self-executing function just to
* keep it organised, not to protect global scope like it would in alloy.js
*/
(function constructor(args) {
$.navWin.open();
})(arguments[0] || {});
function onListViewItemclick(e) {
// We've set the items special itemId-property to the controller name
var controllerName = e.itemId;
// Which we use to create the controller, get the window and open it in the navigation window
// See lib/xp.ui.js to see how we emulate this component for Android
$.navWin.openWindow(Alloy.createController(controllerName).getView());
} | {
"content_hash": "2e0440fa601201130aa562ae6b3126f8",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 94,
"avg_line_length": 32.36842105263158,
"alnum_prop": 0.734959349593496,
"repo_name": "appcelerator-developer-relations/appc-sample-ti500",
"id": "f097dec8baa056cb86754747404344447fc65c67",
"size": "615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "15276"
},
{
"name": "Python",
"bytes": "5251"
}
],
"symlink_target": ""
} |
#include <MWidgetCreator>
#include <MWidget>
#include <MGridLayoutPolicy>
#include <MCancelEvent>
#include <libmeegochat/meegochataccount.h>
#include "contactlistitem.h"
M_REGISTER_WIDGET(ContactListItem);
ContactListItem::ContactListItem(MWidget *parent) :
MListItem(parent),
mActDelContact(0),
mActOpenPeople(0),
mPressed(false)
{
setObjectName("contactListItem");
/* MLayout *hLayout = new MLayout();
MLinearLayoutPolicy *hPolicy = new MLinearLayoutPolicy(hLayout,
Qt::Horizontal);
MLayout *vLayout = new MLayout();
MLinearLayoutPolicy *vPolicy = new MLinearLayoutPolicy(vLayout,
Qt::Vertical);
*/
MLayout *layout = new MLayout();
MGridLayoutPolicy *gPolicy = new MGridLayoutPolicy(layout);
mContactPic = new MImageWidget();
mContactPic->setImage("icon-m-content-avatar-placeholder");
mContactPic->setObjectName("contactListItemPic");
mContactPic->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// hPolicy->addItem(mContactPic, Qt::AlignCenter);
gPolicy->addItem(mContactPic, 0, 0, 2, 1, Qt::AlignHCenter | Qt::AlignTop);
mContactStatusPic = new MImageWidget();
mContactStatusPic->setObjectName("contactListItemStatusPic");
mContactStatusPic->setSizePolicy(QSizePolicy::Fixed,
QSizePolicy::Expanding);
// hPolicy->addItem(mContactStatusPic, Qt::AlignCenter);
gPolicy->addItem(mContactStatusPic, 0, 1);
mContactName = new MLabel("");
mContactName->setTextElide(false);
mContactName->setObjectName("contactListItemName");
mContactName->setSizePolicy(QSizePolicy::Expanding,
QSizePolicy::Expanding);
// hPolicy->addItem(mContactName, Qt::AlignLeft);
gPolicy->addItem(mContactName, 0, 2, Qt::AlignLeft);
mContactStatusMsg = new MLabel("");
mContactStatusMsg->setTextElide(true);
mContactStatusMsg->setObjectName("contactListItemStatusMsg");
mContactStatusMsg->setSizePolicy(QSizePolicy::Expanding,
QSizePolicy::Expanding);
// hPolicy->addItem(mContactStatusMsg, Qt::AlignLeft);
gPolicy->addItem(mContactStatusMsg, 1, 2, Qt::AlignLeft);
// hLayout->setPolicy(hPolicy);
layout->setPolicy(gPolicy);
/*MStylableWidget *spacer = new MStylableWidget();
spacer->setObjectName("dialogItemSpacer");
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
vPolicy->addItem(hLayout);
//vPolicy->addItem(spacer);
vLayout->setPolicy(vPolicy);*/
setLayout(layout);
}
void ContactListItem::onActDelContactClicked()
{
mContact->removeContact();
}
void ContactListItem::onActOpenPeopleClicked()
{
mContact->openPeople();
}
void ContactListItem::setName(QString contactName)
{
//Set contact name
mContactName->setText(contactName);
}
void ContactListItem::setStatus()
{
mContactStatusPic->setImage(Acct::mapAccountStatusToIconName(mContact->getStatus()), QSize(24, 24));
}
void ContactListItem::setAvatar(QPixmap *avatar)
{
QPixmap qpm;
if (!avatar) {
mContactPic->setImage("icon-m-content-avatar-placeholder");
return;
}
if (avatar->height() > avatar->width())
qpm = avatar->scaledToHeight(48);
else
qpm = avatar->scaledToWidth(48);
mContactPic->setPixmap(qpm);
}
void ContactListItem::setContact(ChatContact *contact)
{
mContact = contact;
setName(mContact->getName());
setStatus();
setStatusMsg(mContact->getStatusMsg());
setAvatar(mContact->getAvatar());
if (mContact->getQContact() && !mActOpenPeople) {
//% "View Contact Details"
mActOpenPeople = new MAction(qtTrId("action_view_contact_details"), this);
this->addAction(mActOpenPeople);
connect(mActOpenPeople,
SIGNAL(triggered()),
this,
SLOT(onActOpenPeopleClicked()));
}
if (!mActDelContact) {
//% "Delete Contact"
mActDelContact = new MAction(qtTrId("action_delete_contact"), this);
this->addAction(mActDelContact);
connect(mActDelContact,
SIGNAL(triggered()),
this,
SLOT(onActDelContactClicked()));
}
}
void ContactListItem::setStatusMsg(QString contactStatusMsg)
{
//Set status message
if (contactStatusMsg.isEmpty() || contactStatusMsg.isNull())
mContactStatusMsg->setText(" ");
else
mContactStatusMsg->setText(contactStatusMsg);
}
void ContactListItem::mousePressEvent(QGraphicsSceneMouseEvent *ev)
{
mPressed = true;
style().setModePressed();
update();
ev->accept();
}
void ContactListItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *ev)
{
if (mPressed) {
mPressed = false;
style().setModeDefault();
update();
ev->accept();
emit clicked();
} else {
ev->ignore();
}
}
void ContactListItem::cancelEvent(MCancelEvent *ev)
{
mPressed = false;
style().setModeDefault();
update();
ev->accept();
}
| {
"content_hash": "0090b02f1da850e4fc9cb24f3deef987",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 104,
"avg_line_length": 28.456043956043956,
"alnum_prop": 0.6528287314153312,
"repo_name": "dudochkin-victor/handset-chat",
"id": "a5fa15089abcdb672db536aa9ca1831177fd7cdb",
"size": "5478",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/contactlistitem.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "105793"
},
{
"name": "Prolog",
"bytes": "2826"
}
],
"symlink_target": ""
} |
import { ARTICLES } from '$redux/action-types'
const filters = (state = {}, action) => {
switch (action.type) {
case ARTICLES.FILTER_OPTION_CHANGE:
var s = Object.assign({}, state)
s[action.label] = action.value
return s
default:
return state
}
}
export default filters
| {
"content_hash": "5d250671ff8ae94884e4e9fe3cc08ebf",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 46,
"avg_line_length": 22,
"alnum_prop": 0.6233766233766234,
"repo_name": "ucev/blog",
"id": "44526afb962ed2b5f3d1e9566a6e9cb0060b21ca",
"size": "308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/redux/reducers/articles/filters.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3022"
},
{
"name": "HTML",
"bytes": "510"
},
{
"name": "JavaScript",
"bytes": "253086"
},
{
"name": "Pug",
"bytes": "20835"
},
{
"name": "SCSS",
"bytes": "44059"
},
{
"name": "Shell",
"bytes": "405"
}
],
"symlink_target": ""
} |
layout: tag_archive
tag: popp
---
| {
"content_hash": "cf0d8e1c862e914a3a34d868e3c5e7d1",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 19,
"avg_line_length": 11.333333333333334,
"alnum_prop": 0.6764705882352942,
"repo_name": "ihomeautomate/ihomeautomate.github.io",
"id": "4fc34c53bca5f6f948090560c758dba567f3eaea",
"size": "38",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tag/popp/index.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "46116"
},
{
"name": "HTML",
"bytes": "33171"
},
{
"name": "JavaScript",
"bytes": "13636"
},
{
"name": "Ruby",
"bytes": "2507"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#21282C"
android:layout_height="match_parent">
<ImageView
android:id="@+id/btn_back"
android:src="@drawable/btn_back"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="Imagen"
android:layout_toRightOf="@+id/btn_back"
android:textColor="@android:color/white"
android:textSize="20sp"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/commit"
android:background="@drawable/action_btn"
android:minHeight="1dp"
android:minWidth="1dp"
android:layout_marginRight="16dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textColor="@color/default_text_color"
android:textSize="14sp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:text="@string/selectedw"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
| {
"content_hash": "0c1f54032337134d8438f0aeb9f5522c",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 74,
"avg_line_length": 35.883720930232556,
"alnum_prop": 0.6519766688269605,
"repo_name": "asvanpelt/MultiImageSelector",
"id": "e7551a7a4b5f8e388c0ae6cb4931b8bbf3d22f32",
"size": "1543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "multi-image-selector/src/main/res/layout/cmp_customer_actionbar.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "51016"
}
],
"symlink_target": ""
} |
package cz.muni.fi.civ.newohybat.persistence.services.impl;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import cz.muni.fi.civ.newohybat.persistence.dao.iface.TileDAO;
import cz.muni.fi.civ.newohybat.persistence.entities.Tile;
import cz.muni.fi.civ.newohybat.persistence.services.iface.TileService;
@Stateless
public class TileServiceImpl implements TileService {
@Inject
private TileDAO dao;
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Tile create(Tile tile) {
return dao.create(tile);
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void update(Tile tile) {
dao.update(tile);
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void delete(Tile tile) {
dao.delete(tile);
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Tile getById(Long id) {
return dao.getById(id);
}
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public List<Tile> getAll() {
return dao.getAll();
}
public Tile getByPosition(Long x, Long y) {
return dao.getByPosition(x,y);
}
public Map<Long, List<Tile>> getTilesInRectangle(Long topLeftX,
Long topLeftY, Long bottomRightX, Long bottomRightY) {
return dao.getTilesInRectangle(topLeftX, topLeftY, bottomRightX, bottomRightY);
}
}
| {
"content_hash": "eb0fe3bec7e9f27c8e53d175ac9037c8",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 81,
"avg_line_length": 24.916666666666668,
"alnum_prop": 0.7531772575250836,
"repo_name": "newohybat/civ",
"id": "59f740a4302a3ad5aadfe6ec2a3ae9d8b08eee4e",
"size": "1495",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "civ-persistence/src/main/java/cz/muni/fi/civ/newohybat/persistence/services/impl/TileServiceImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "713511"
}
],
"symlink_target": ""
} |
/*
* MinIO Cloud Storage, (C) 2017 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package auth
import (
"encoding/json"
"testing"
"time"
)
func TestExpToInt64(t *testing.T) {
testCases := []struct {
exp interface{}
expectedFailure bool
}{
{"", true},
{"-1", true},
{"1574812326", false},
{1574812326, false},
{int64(1574812326), false},
{int(1574812326), false},
{uint(1574812326), false},
{uint64(1574812326), false},
{json.Number("1574812326"), false},
{1574812326.000, false},
{time.Duration(3) * time.Minute, false},
}
for _, testCase := range testCases {
testCase := testCase
t.Run("", func(t *testing.T) {
_, err := ExpToInt64(testCase.exp)
if err != nil && !testCase.expectedFailure {
t.Errorf("Expected success but got failure %s", err)
}
if err == nil && testCase.expectedFailure {
t.Error("Expected failure but got success")
}
})
}
}
func TestIsAccessKeyValid(t *testing.T) {
testCases := []struct {
accessKey string
expectedResult bool
}{
{alphaNumericTable[:accessKeyMinLen], true},
{alphaNumericTable[:accessKeyMinLen+1], true},
{alphaNumericTable[:accessKeyMinLen-1], false},
}
for i, testCase := range testCases {
result := IsAccessKeyValid(testCase.accessKey)
if result != testCase.expectedResult {
t.Fatalf("test %v: expected: %v, got: %v", i+1, testCase.expectedResult, result)
}
}
}
func TestIsSecretKeyValid(t *testing.T) {
testCases := []struct {
secretKey string
expectedResult bool
}{
{alphaNumericTable[:secretKeyMinLen], true},
{alphaNumericTable[:secretKeyMinLen+1], true},
{alphaNumericTable[:secretKeyMinLen-1], false},
}
for i, testCase := range testCases {
result := IsSecretKeyValid(testCase.secretKey)
if result != testCase.expectedResult {
t.Fatalf("test %v: expected: %v, got: %v", i+1, testCase.expectedResult, result)
}
}
}
func TestGetNewCredentials(t *testing.T) {
cred, err := GetNewCredentials()
if err != nil {
t.Fatalf("Failed to get a new credential")
}
if !cred.IsValid() {
t.Fatalf("Failed to get new valid credential")
}
if len(cred.AccessKey) != accessKeyMaxLen {
t.Fatalf("access key length: expected: %v, got: %v", secretKeyMaxLen, len(cred.AccessKey))
}
if len(cred.SecretKey) != secretKeyMaxLen {
t.Fatalf("secret key length: expected: %v, got: %v", secretKeyMaxLen, len(cred.SecretKey))
}
}
func TestCreateCredentials(t *testing.T) {
testCases := []struct {
accessKey string
secretKey string
valid bool
expectedErr error
}{
// Valid access and secret keys with minimum length.
{alphaNumericTable[:accessKeyMinLen], alphaNumericTable[:secretKeyMinLen], true, nil},
// Valid access and/or secret keys are longer than minimum length.
{alphaNumericTable[:accessKeyMinLen+1], alphaNumericTable[:secretKeyMinLen+1], true, nil},
// Smaller access key.
{alphaNumericTable[:accessKeyMinLen-1], alphaNumericTable[:secretKeyMinLen], false, ErrInvalidAccessKeyLength},
// Smaller secret key.
{alphaNumericTable[:accessKeyMinLen], alphaNumericTable[:secretKeyMinLen-1], false, ErrInvalidSecretKeyLength},
}
for i, testCase := range testCases {
cred, err := CreateCredentials(testCase.accessKey, testCase.secretKey)
if err != nil {
if testCase.expectedErr == nil {
t.Fatalf("test %v: error: expected = <nil>, got = %v", i+1, err)
}
if testCase.expectedErr.Error() != err.Error() {
t.Fatalf("test %v: error: expected = %v, got = %v", i+1, testCase.expectedErr, err)
}
} else {
if testCase.expectedErr != nil {
t.Fatalf("test %v: error: expected = %v, got = <nil>", i+1, testCase.expectedErr)
}
if !cred.IsValid() {
t.Fatalf("test %v: got invalid credentials", i+1)
}
}
}
}
func TestCredentialsEqual(t *testing.T) {
cred, err := GetNewCredentials()
if err != nil {
t.Fatalf("Failed to get a new credential")
}
cred2, err := GetNewCredentials()
if err != nil {
t.Fatalf("Failed to get a new credential")
}
testCases := []struct {
cred Credentials
ccred Credentials
expectedResult bool
}{
// Same Credentialss.
{cred, cred, true},
// Empty credentials to compare.
{cred, Credentials{}, false},
// Empty credentials.
{Credentials{}, cred, false},
// Two different credentialss
{cred, cred2, false},
// Access key is different in credentials to compare.
{cred, Credentials{AccessKey: "myuser", SecretKey: cred.SecretKey}, false},
// Secret key is different in credentials to compare.
{cred, Credentials{AccessKey: cred.AccessKey, SecretKey: "mypassword"}, false},
}
for i, testCase := range testCases {
result := testCase.cred.Equal(testCase.ccred)
if result != testCase.expectedResult {
t.Fatalf("test %v: expected: %v, got: %v", i+1, testCase.expectedResult, result)
}
}
}
| {
"content_hash": "2db78ef4a36f87edd00237a5296f2888",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 113,
"avg_line_length": 29.607734806629836,
"alnum_prop": 0.6807240156745662,
"repo_name": "fwessels/minio",
"id": "4577bef96a6aef07adf6cb3de253e6f1dd050dd5",
"size": "5359",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "pkg/auth/credentials_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "51736"
},
{
"name": "Dockerfile",
"bytes": "941"
},
{
"name": "Go",
"bytes": "4795943"
},
{
"name": "HTML",
"bytes": "2242"
},
{
"name": "JavaScript",
"bytes": "277190"
},
{
"name": "Makefile",
"bytes": "3797"
},
{
"name": "Shell",
"bytes": "41050"
}
],
"symlink_target": ""
} |
import unittest
from libsaas import http
from libsaas.filters import auth
class BasicAuthTestCase(unittest.TestCase):
def test_simple(self):
auth_filter = auth.BasicAuth('user', 'pass')
req = http.Request('GET', 'http://example.net/')
auth_filter(req)
self.assertEqual(req.headers['Authorization'], 'Basic dXNlcjpwYXNz')
def test_unicode(self):
# try both a unicode and a bytes parameter
_lambda = b'\xce\xbb'
_ulambda = _lambda.decode('utf-8')
auth_bytes = auth.BasicAuth('user', _lambda)
auth_unicode = auth.BasicAuth('user', _ulambda)
auth_mixed = auth.BasicAuth(_lambda, _ulambda)
expected_bytes = 'Basic dXNlcjrOuw=='
expected_unicode = expected_bytes
expected_mixed = 'Basic zrs6zrs='
for auth_filter, expected in ((auth_bytes, expected_bytes),
(auth_unicode, expected_unicode),
(auth_mixed, expected_mixed)):
req = http.Request('GET', 'http://example.net/')
auth_filter(req)
self.assertEqual(req.headers['Authorization'], expected)
| {
"content_hash": "9911d5cb65e26de35d3a75bfc5751f41",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 76,
"avg_line_length": 32.833333333333336,
"alnum_prop": 0.5930626057529611,
"repo_name": "ducksboard/libsaas",
"id": "c59071625e151f70b55c3654646a1fd975fc3cd0",
"size": "1182",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "test/test_basic_auth.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "954078"
}
],
"symlink_target": ""
} |
package com.vaadin.tests.components.ui;
import static org.junit.Assert.assertTrue;
import java.util.Locale;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import com.vaadin.tests.tb3.MultiBrowserTest;
/**
* Test to check auto-generated style name for UI div and overlays div.
*
* @author Vaadin Ltd
*/
public class UIAutoGeneratedStyleNameTest extends MultiBrowserTest {
@Test
public void testUiStyleName() {
openTestURL();
assertTrue("UI div element doesn't contain autogenerated style name",
containsStyle(getDriver().findElement(By.className("v-app")),
UIAutoGeneratedStyleName.class.getSimpleName()
.toLowerCase(Locale.ROOT)));
assertTrue(
"Overlays div element doesn't contain autogenerated style name",
containsStyle(
getDriver().findElement(
By.className("v-overlay-container")),
UIAutoGeneratedStyleName.class.getSimpleName()
.toLowerCase(Locale.ROOT)));
}
private boolean containsStyle(WebElement element, String style) {
return element.getAttribute("class").contains(style);
}
}
| {
"content_hash": "f1f6a578e6dc9b561c875d9d5942447f",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 80,
"avg_line_length": 31.357142857142858,
"alnum_prop": 0.6294608959757023,
"repo_name": "Darsstar/framework",
"id": "3f7ab9c0981b88eb232c3ec2079a29de6b8d7e78",
"size": "1912",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "uitest/src/test/java/com/vaadin/tests/components/ui/UIAutoGeneratedStyleNameTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "751129"
},
{
"name": "HTML",
"bytes": "104675"
},
{
"name": "Java",
"bytes": "24247164"
},
{
"name": "JavaScript",
"bytes": "131503"
},
{
"name": "Python",
"bytes": "33975"
},
{
"name": "Shell",
"bytes": "14720"
},
{
"name": "Smarty",
"bytes": "175"
}
],
"symlink_target": ""
} |
@implementation UIButton (EdgeInsets)
- (void)layoutButtonWithEdgeInsetsStyle:(ButtonEdgeInsetsStyle)style imageTitlespace:(CGFloat)space {
CGFloat imageViewWidth = CGRectGetWidth(self.imageView.frame);
CGFloat labelWidth = CGRectGetWidth(self.titleLabel.frame);
if (labelWidth == 0) {
CGSize titleSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:self.titleLabel.font}];
labelWidth = titleSize.width;
}
CGFloat imageInsetsTop = 0.0f;
CGFloat imageInsetsLeft = 0.0f;
CGFloat imageInsetsBottom = 0.0f;
CGFloat imageInsetsRight = 0.0f;
CGFloat titleInsetsTop = 0.0f;
CGFloat titleInsetsLeft = 0.0f;
CGFloat titleInsetsBottom = 0.0f;
CGFloat titleInsetsRight = 0.0f;
switch (style) {
case ButtonEdgeInsetsStyleImageRight:
{
space = space * 0.5;
imageInsetsLeft = labelWidth + space;
imageInsetsRight = -imageInsetsLeft;
titleInsetsLeft = - (imageViewWidth + space);
titleInsetsRight = -titleInsetsLeft;
}
break;
case ButtonEdgeInsetsStyleImageLeft:
{
space = space * 0.5;
imageInsetsLeft = -space;
imageInsetsRight = -imageInsetsLeft;
titleInsetsLeft = space;
titleInsetsRight = -titleInsetsLeft;
}
break;
case ButtonEdgeInsetsStyleImageBottom:
{
CGFloat imageHeight = CGRectGetHeight(self.imageView.frame);
CGFloat labelHeight = CGRectGetHeight(self.titleLabel.frame);
CGFloat buttonHeight = CGRectGetHeight(self.frame);
CGFloat boundsCentery = (imageHeight + space + labelHeight) * 0.5;
CGFloat centerX_button = CGRectGetMidX(self.bounds); // bounds
CGFloat centerX_titleLabel = CGRectGetMidX(self.titleLabel.frame);
CGFloat centerX_image = CGRectGetMidX(self.imageView.frame);
CGFloat imageBottomY = CGRectGetMaxY(self.imageView.frame);
CGFloat titleTopY = CGRectGetMinY(self.titleLabel.frame);
imageInsetsTop = buttonHeight - (buttonHeight * 0.5 - boundsCentery) - imageBottomY;
imageInsetsLeft = centerX_button - centerX_image;
imageInsetsRight = - imageInsetsLeft;
imageInsetsBottom = - imageInsetsTop;
titleInsetsTop = (buttonHeight * 0.5 - boundsCentery) - titleTopY;
titleInsetsLeft = -(centerX_titleLabel - centerX_button);
titleInsetsRight = - titleInsetsLeft;
titleInsetsBottom = - titleInsetsTop;
}
break;
case ButtonEdgeInsetsStyleImageTop:
{
CGFloat imageHeight = CGRectGetHeight(self.imageView.frame);
CGFloat labelHeight = CGRectGetHeight(self.titleLabel.frame);
CGFloat buttonHeight = CGRectGetHeight(self.frame);
CGFloat boundsCentery = (imageHeight + space + labelHeight) * 0.5;
CGFloat centerX_button = CGRectGetMidX(self.bounds); // bounds
CGFloat centerX_titleLabel = CGRectGetMidX(self.titleLabel.frame);
CGFloat centerX_image = CGRectGetMidX(self.imageView.frame);
CGFloat imageTopY = CGRectGetMinY(self.imageView.frame);
CGFloat titleBottom = CGRectGetMaxY(self.titleLabel.frame);
imageInsetsTop = (buttonHeight * 0.5 - boundsCentery) - imageTopY;
imageInsetsLeft = centerX_button - centerX_image;
imageInsetsRight = - imageInsetsLeft;
imageInsetsBottom = - imageInsetsTop;
titleInsetsTop = buttonHeight - (buttonHeight * 0.5 - boundsCentery) - titleBottom;
titleInsetsLeft = -(centerX_titleLabel - centerX_button);
titleInsetsRight = - titleInsetsLeft;
titleInsetsBottom = - titleInsetsTop;
}
break;
default:
break;
}
self.imageEdgeInsets = UIEdgeInsetsMake(imageInsetsTop, imageInsetsLeft, imageInsetsBottom, imageInsetsRight);
self.titleEdgeInsets = UIEdgeInsetsMake(titleInsetsTop, titleInsetsLeft, titleInsetsBottom, titleInsetsRight);
}
@end
| {
"content_hash": "579676720531dd67a7c3dfbdb433f940",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 114,
"avg_line_length": 41.57142857142857,
"alnum_prop": 0.6240549828178694,
"repo_name": "CenterY/UIButtonEdgeInsets",
"id": "a8f0bc1bb8987dd85475f5e59c5765db16de5d37",
"size": "4540",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "UIButton+EdgeInsets.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "10943"
}
],
"symlink_target": ""
} |
Mongo Connector for API Hero
| {
"content_hash": "8834345c29296f24da2d3ada3a4167e3",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 28,
"avg_line_length": 29,
"alnum_prop": 0.8275862068965517,
"repo_name": "vancarney/apihero-module-socketio",
"id": "209b559e57c3b8a0c76aea9407ae8bc5ff73eccc",
"size": "66",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "test/server/node_modules/loopback-connector-apihero-mongodb/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "18160"
},
{
"name": "JavaScript",
"bytes": "194926"
}
],
"symlink_target": ""
} |
import {configure} from "./../../src/index";
import MaterializeCssOptions from "./../../src/index";
class ConfigStub {
private resources: Array<string> = [];
public globalResources(resources) {
this.resources = resources;
}
}
describe("the Aurelia Materialize CSS configuration with the option enableAttributes true", () => {
let sut;
beforeEach(() => {
sut = new ConfigStub();
let options = new MaterializeCssOptions();
options.enableAttributes = true;
options.enableElements = false;
configure(sut, options);
});
it("must register the collapsible attribute", () => {
expect(sut.resources)
.toContain("./javascript/collapsible/collapsibleAttribute");
});
it("must register the collapsible body attribute", () => {
expect(sut.resources)
.toContain("./javascript/collapsible/collapsibleBodyAttribute");
});
it("must register the collapsible header attribute", () => {
expect(sut.resources)
.toContain("./javascript/collapsible/collapsibleHeaderAttribute");
});
it("must register the dropdown attribute", () => {
expect(sut.resources)
.toContain("./javascript/dropdown/dropdownAttribute");
});
it("must register the dropdown divider attribute", () => {
expect(sut.resources)
.toContain("./javascript/dropdown/dropdownDividerAttribute");
});
it("must register the media boxed attribute", () => {
expect(sut.resources)
.toContain("./javascript/media/boxedAttribute");
});
it("must register the modals modal-trigger attribute", () => {
expect(sut.resources)
.toContain("./javascript/modals/modalTriggerAttribute");
});
it("must register the pushpin attribute", () => {
expect(sut.resources)
.toContain("./javascript/pushpin/pushpinAttribute");
});
it("must register the scrollspy attribute", () => {
expect(sut.resources)
.toContain("./javascript/scrollspy/scrollspyAttribute");
});
it("must register the badge attribute", () => {
expect(sut.resources)
.toContain("./components/badge/badgeAttribute");
});
it("must register the breadcrumb attribute", () => {
expect(sut.resources)
.toContain("./components/breadcrumbs/breadcrumbAttribute");
});
it("must register the breadcrumbs attribute", () => {
expect(sut.resources)
.toContain("./components/breadcrumbs/breadcrumbsAttribute");
});
it("must register the button attribute", () => {
expect(sut.resources)
.toContain("./components/button/buttonAttribute");
});
it("must register the card attribute", () => {
expect(sut.resources)
.toContain("./components/card/cardAttribute");
});
it("must register the cardTitle attribute", () => {
expect(sut.resources)
.toContain("./components/card/cardTitleAttribute");
});
it("must register the cardAction attribute", () => {
expect(sut.resources)
.toContain("./components/card/cardActionAttribute");
});
it("must register the cardImage attribute", () => {
expect(sut.resources)
.toContain("./components/card/cardImageAttribute");
});
it("must register the cardReveal attribute", () => {
expect(sut.resources)
.toContain("./components/card/cardRevealAttribute");
});
it("must register the cardPanel attribute", () => {
expect(sut.resources)
.toContain("./components/card/cardPanelAttribute");
});
it("must register the select (forms) attribute", () => {
expect(sut.resources)
.toContain("./components/forms/selectAttribute");
});
it("must register the pickadate (forms) attribute", () => {
expect(sut.resources)
.toContain("./components/forms/pickadateAttribute");
});
it("must register the icon attribute", () => {
expect(sut.resources)
.toContain("./components/icon/iconAttribute");
});
});
describe("the Aurelia Materialize CSS configuration with the option enableAttributes false", () => {
let sut;
beforeEach(() => {
sut = new ConfigStub();
let options = new MaterializeCssOptions();
options.enableAttributes = false;
configure(sut, options);
});
it("must no register the collapsible attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/collapsible/collapsibleAttribute");
});
it("must not register the collapsible body attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/collapsible/collapsibleBodyAttribute");
});
it("must not register the collapsible header attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/collapsible/collapsibleHeaderAttribute");
});
it("must register the dropdown attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/dropdown/dropdownAttribute");
});
it("must register the dropdown divider attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/dropdown/dropdownDividerAttribute");
});
it("must not register the media boxed attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/media/boxedAttribute");
});
it("must not register the modals modal-trigger attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/modals/modalTriggerAttribute");
});
it("must not register the pushpin attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/pushpin/pushpinAttribute");
});
it("must not register the scrollspy attribute", () => {
expect(sut.resources)
.not.toContain("./javascript/scrollspy/scrollspyAttribute");
});
it("must not register the badge attribute", () => {
expect(sut.resources)
.not.toContain("./components/badge/badgeAttribute");
});
it("must not register the breadcrumb attribute", () => {
expect(sut.resources)
.not.toContain("./components/breadcrumbs/breadcrumbAttribute");
});
it("must not register the breadcrumbs attribute", () => {
expect(sut.resources)
.not.toContain("./components/breadcrumbs/breadcrumbsAttribute");
});
it("must not register the button attribute", () => {
expect(sut.resources)
.not.toContain("./components/button/buttonAttribute");
});
it("must register the card attribute", () => {
expect(sut.resources)
.not.toContain("./components/card/cardAttribute");
});
it("must register the cardTitle attribute", () => {
expect(sut.resources)
.not.toContain("./components/card/cardTitleAttribute");
});
it("must register the cardAction attribute", () => {
expect(sut.resources)
.not.toContain("./components/card/cardActionAttribute");
});
it("must register the cardImage attribute", () => {
expect(sut.resources)
.not.toContain("./components/card/cardImageAttribute");
});
it("must not register the cardReveal attribute", () => {
expect(sut.resources)
.not.toContain("./components/card/cardRevealAttribute");
});
it("must not register the cardPanel attribute", () => {
expect(sut.resources)
.not.toContain("./components/card/cardPanelAttribute");
});
it("must not register the select (forms) attribute", () => {
expect(sut.resources)
.not.toContain("./components/forms/selectAttribute");
});
it("must not register the pickadate (forms) attribute", () => {
expect(sut.resources)
.not.toContain("./components/forms/pickadateAttribute");
});
it("must not register the icon attribute", () => {
expect(sut.resources)
.not.toContain("./components/icon/iconAttribute");
});
});
describe("the Aurelia Materialize CSS configuration with the option enableElements true", () => {
let sut;
beforeEach(() => {
sut = new ConfigStub();
let options = new MaterializeCssOptions();
options.enableElements = true;
configure(sut, options);
});
it("must register the collapsible element", () => {
expect(sut.resources)
.toContain("./javascript/collapsible/collapsibleElement");
});
it("must register the collapsible body element", () => {
expect(sut.resources)
.toContain("./javascript/collapsible/collapsibleBodyElement");
});
it("must register the collapsible header element", () => {
expect(sut.resources)
.toContain("./javascript/collapsible/collapsibleHeaderElement");
});
it("must register the collapsible item element", () => {
expect(sut.resources)
.toContain("./javascript/collapsible/collapsibleItemElement");
});
it("must register the dropdown element", () => {
expect(sut.resources)
.toContain("./javascript/dropdown/dropdownElement");
});
it("must register the dropdown divider element", () => {
expect(sut.resources)
.toContain("./javascript/dropdown/dropdownDividerElement");
});
it("must register the dropdown item element", () => {
expect(sut.resources)
.toContain("./javascript/dropdown/dropdownItemElement");
});
it("must register the media slide element", () => {
expect(sut.resources)
.toContain("./javascript/media/slideElement");
});
it("must register the media slider element", () => {
expect(sut.resources)
.toContain("./javascript/media/sliderElement");
});
it("must register the modals modal-content element", () => {
expect(sut.resources)
.toContain("./javascript/modals/modalContentElement");
});
it("must register the modals modal element", () => {
expect(sut.resources)
.toContain("./javascript/modals/modalElement");
});
it("must register the modals modal-footer element", () => {
expect(sut.resources)
.toContain("./javascript/modals/modalFooterElement");
});
it("must register the pushin element", () => {
expect(sut.resources)
.toContain("./javascript/pushpin/pushpinElement");
});
it("must register the scrollspy element", () => {
expect(sut.resources)
.toContain("./javascript/scrollspy/scrollspyElement");
});
it("must register the badge element", () => {
expect(sut.resources)
.toContain("./components/badge/badgeElement");
});
it("must register the breadcrumb element", () => {
expect(sut.resources)
.toContain("./components/breadcrumbs/breadcrumbElement");
});
it("must register the breadcrumbs element", () => {
expect(sut.resources)
.toContain("./components/breadcrumbs/breadcrumbsElement");
});
it("must register the button element", () => {
expect(sut.resources)
.toContain("./components/button/buttonElement");
});
it("must register the card element", () => {
expect(sut.resources)
.toContain("./components/card/cardElement");
});
it("must register the cardTitle element", () => {
expect(sut.resources)
.toContain("./components/card/cardTitleElement");
});
it("must register the cardAction element", () => {
expect(sut.resources)
.toContain("./components/card/cardActionElement");
});
it("must register the cardImage element", () => {
expect(sut.resources)
.toContain("./components/card/cardImageElement");
});
it("must register the cardReveal element", () => {
expect(sut.resources)
.toContain("./components/card/cardRevealElement");
});
it("must register the cardPanel element", () => {
expect(sut.resources)
.toContain("./components/card/cardPanelElement");
});
it("must register the icon element", () => {
expect(sut.resources)
.toContain("./components/icon/iconElement");
});
it("must register the collection element", () => {
expect(sut.resources)
.toContain("./components/collections/collectionElement");
});
it("must register the collection header element", () => {
expect(sut.resources)
.toContain("./components/collections/collectionHeaderElement");
});
it("must register the collection item element", () => {
expect(sut.resources)
.toContain("./components/collections/collectionItemElement");
});
it("must register the link collection element", () => {
expect(sut.resources)
.toContain("./components/collections/linkCollectionElement");
});
it("must register the collection link item element", () => {
expect(sut.resources)
.toContain("./components/collections/collectionLinkItemElement");
});
});
describe("the Aurelia Materialize CSS configuration with the option enableElements false", () => {
let sut;
beforeEach(() => {
sut = new ConfigStub();
let options = new MaterializeCssOptions();
options.enableElements = false;
configure(sut, options);
});
it("must not register the collapsible element", () => {
expect(sut.resources)
.not.toContain("./javascript/collapsible/collapsibleElement");
});
it("must not register the collapsible body element", () => {
expect(sut.resources)
.not.toContain("./javascript/collapsible/collapsibleBodyElement");
});
it("must not register the collapsible header element", () => {
expect(sut.resources)
.not.toContain("./javascript/collapsible/collapsibleHeaderElement");
});
it("must not register the collapsible item element", () => {
expect(sut.resources)
.not.toContain("./javascript/collapsible/collapsibleItemElement");
});
it("must register the dropdown element", () => {
expect(sut.resources)
.not.toContain("./javascript/dropdown/dropdownElement");
});
it("must register the dropdown divider element", () => {
expect(sut.resources)
.not.toContain("./javascript/dropdown/dropdownDividerElement");
});
it("must register the dropdown item element", () => {
expect(sut.resources)
.not.toContain("./javascript/dropdown/dropdownItemElement");
});
it("must not register the media slide element", () => {
expect(sut.resources)
.not.toContain("./javascript/media/slideElement");
});
it("must not register the media slider element", () => {
expect(sut.resources)
.not.toContain("./javascript/media/sliderElement");
});
it("must not register the modals modal-content element", () => {
expect(sut.resources)
.not.toContain("./javascript/modals/modalContentElement");
});
it("must not register the modals modal element", () => {
expect(sut.resources)
.not.toContain("./javascript/modals/modalElement");
});
it("must not register the modals modal-footer element", () => {
expect(sut.resources)
.not.toContain("./javascript/modals/modalFooterElement");
});
it("must not register the pushin element", () => {
expect(sut.resources)
.not.toContain("./javascript/pushpin/pushpinElement");
});
it("must not register the scrollspy element", () => {
expect(sut.resources)
.not.toContain("./javascript/scrollspy/scrollspyElement");
});
it("must not register the badge element", () => {
expect(sut.resources)
.not.toContain("./components/badge/badgeElement");
});
it("must not register the breadcrumb element", () => {
expect(sut.resources)
.not.toContain("./components/breadcrumbs/breadcrumbElement");
});
it("must not register the breadcrumbs element", () => {
expect(sut.resources)
.not.toContain("./components/breadcrumbs/breadcrumbsElement");
});
it("must not register the button element", () => {
expect(sut.resources)
.not.toContain("./components/button/buttonElement");
});
it("must not register the card element", () => {
expect(sut.resources)
.not.toContain("./components/card/cardElement");
});
it("must not register the cardTitle element", () => {
expect(sut.resources)
.not.toContain("./components/card/cardTitleElement");
});
it("must not register the cardAction element", () => {
expect(sut.resources)
.not.toContain("./components/card/cardActionElement");
});
it("must not register the cardImage element", () => {
expect(sut.resources)
.not.toContain("./components/card/cardImageElement");
});
it("must not register the cardReveal element", () => {
expect(sut.resources)
.not.toContain("./components/card/cardRevealElement");
});
it("must not register the cardPanel element", () => {
expect(sut.resources)
.not.toContain("./components/card/cardPanelElement");
});
it("must not register the icon element", () => {
expect(sut.resources)
.not.toContain("./components/icon/iconElement");
});
it("must not register the collection element", () => {
expect(sut.resources)
.not.toContain("./components/collections/collectionElement");
});
it("must not register the collection header element", () => {
expect(sut.resources)
.not.toContain("./components/collections/collectionHeaderElement");
});
it("must not register the collection item element", () => {
expect(sut.resources)
.not.toContain("./components/collections/collectionItemElement");
});
it("must not register the link collection element", () => {
expect(sut.resources)
.not.toContain("./components/collections/linkCollectionElement");
});
it("must not register the collection link item element", () => {
expect(sut.resources)
.not.toContain("./components/collections/collectionLinkItemElement");
});
}); | {
"content_hash": "b80e5961aec1b04279632e8076b972a5",
"timestamp": "",
"source": "github",
"line_count": 576,
"max_line_length": 100,
"avg_line_length": 32.802083333333336,
"alnum_prop": 0.6008256589393458,
"repo_name": "eriklieben/aurelia-materialize-css",
"id": "64e3e7048af8dbda21e1905eebc4cf117a653077",
"size": "18894",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/unit/configure.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "14802"
},
{
"name": "TypeScript",
"bytes": "174373"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.transfer.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.transfer.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ImportSshPublicKeyResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ImportSshPublicKeyResultJsonUnmarshaller implements Unmarshaller<ImportSshPublicKeyResult, JsonUnmarshallerContext> {
public ImportSshPublicKeyResult unmarshall(JsonUnmarshallerContext context) throws Exception {
ImportSshPublicKeyResult importSshPublicKeyResult = new ImportSshPublicKeyResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return importSshPublicKeyResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("ServerId", targetDepth)) {
context.nextToken();
importSshPublicKeyResult.setServerId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("SshPublicKeyId", targetDepth)) {
context.nextToken();
importSshPublicKeyResult.setSshPublicKeyId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("UserName", targetDepth)) {
context.nextToken();
importSshPublicKeyResult.setUserName(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return importSshPublicKeyResult;
}
private static ImportSshPublicKeyResultJsonUnmarshaller instance;
public static ImportSshPublicKeyResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ImportSshPublicKeyResultJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "e0ef915638a4b65e9f8c45733b40d6a4",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 136,
"avg_line_length": 39.32394366197183,
"alnum_prop": 0.6518624641833811,
"repo_name": "aws/aws-sdk-java",
"id": "f2e2e20805aab17b5250519a617b9ff2afadc6a9",
"size": "3372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-transfer/src/main/java/com/amazonaws/services/transfer/model/transform/ImportSshPublicKeyResultJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/* global describe test expect */
const batch = require('./batch');
const report = require('../mock/report');
const updatedReport = require('../mock/emptyReport');
describe('report batch', () => {
test('should update a batch of fields', () => {
const fields = [
{
key: 'one',
value: 1,
},
{
key: 'two',
value: 2,
},
{
key: 'three',
value: 3,
},
];
batch(report, fields);
expect(updatedReport.one).toBe(1);
expect(updatedReport.two).toBe(2);
expect(updatedReport.three).toBe(3);
});
});
| {
"content_hash": "183628a603f0215eea439a299bc7c161",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 53,
"avg_line_length": 21.428571428571427,
"alnum_prop": 0.52,
"repo_name": "montacasa/crawler-xml-filters",
"id": "a1f531abb105cd3214f2d82fd1c0fb240c478179",
"size": "600",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/reporter/batch/batch.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "57181"
}
],
"symlink_target": ""
} |
const net = require('net');
const fs = require('fs');
const bundlePath = '../../app/assets/webpack/';
let bundleFileName = 'server-bundle.js';
let currentArg;
class Handler {
constructor() {
this.queue = [];
this.initialized = false;
}
initialize() {
console.log(`Processing ${this.queue.length} pending requests`);
let callback;
// eslint-disable-next-line no-cond-assign
while (callback = this.queue.pop()) {
callback();
}
this.initialized = true;
}
handle(connection) {
const callback = () => {
const terminator = '\r\n\0';
let request = '';
connection.setEncoding('utf8');
connection.on('data', (data) => {
console.log(`Processing chunk: ${data}`);
request += data;
if (data.slice(-terminator.length) === terminator) {
request = request.slice(0, -terminator.length);
// eslint-disable-next-line no-eval
const response = eval(request);
connection.write(`${response}${terminator}`);
request = '';
}
});
};
if (this.initialized) {
callback();
} else {
this.queue.push(callback);
}
}
}
const handler = new Handler();
process.argv.forEach((val) => {
if (val[0] === '-') {
currentArg = val.slice(1);
return;
}
if (currentArg === 's') {
bundleFileName = val;
}
});
function loadBundle() {
if (handler.initialized) {
console.log('Reloading server bundle must be implemented by restarting the node process!');
return;
}
/* eslint-disable */
require(bundlePath + bundleFileName);
/* eslint-enable */
console.log(`Loaded server bundle: ${bundlePath}${bundleFileName}`);
handler.initialize();
}
try {
fs.mkdirSync(bundlePath);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
} else {
loadBundle();
}
}
fs.watchFile(bundlePath + bundleFileName, (curr) => {
if (curr && curr.blocks && curr.blocks > 0) {
loadBundle();
}
});
const unixServer = net.createServer((connection) => {
handler.handle(connection);
});
unixServer.listen('node.sock');
process.on('SIGINT', () => {
unixServer.close();
process.exit();
});
| {
"content_hash": "1e503ff5e9016f2ebd3983184d9757d0",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 95,
"avg_line_length": 20.83809523809524,
"alnum_prop": 0.5882084095063985,
"repo_name": "lrosskamp/makealist-public",
"id": "bb57bc194f4530d94178e34853965c27dea00712",
"size": "2188",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/cache/ruby/2.3.0/gems/react_on_rails-8.0.0/lib/generators/react_on_rails/templates/node/base/client/node/server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "673"
},
{
"name": "HTML",
"bytes": "61223"
},
{
"name": "JavaScript",
"bytes": "122729"
},
{
"name": "Ruby",
"bytes": "188742"
}
],
"symlink_target": ""
} |
require 'active_support'
require 'active_support/core_ext'
class SprintStatistics
def initialize(access_token, milestone_string = nil)
@access_token = access_token
@milestone_string = milestone_string
end
def find_milestone_in_repo(repo, milestone = @milestone_string)
client.milestones(repo, :state => "all").detect { |m| m.title.start_with?(milestone) }
end
def current_milestone
@current_milestone ||= find_milestone_in_repo("ManageIQ/manageiq")
end
def previous_milestone
@previous_milestone ||= begin
current_milestone_number = current_milestone.title.match(/Sprint (\d+)/)[1].to_i
previous_milestone_number = current_milestone_number - 1
find_milestone_in_repo("ManageIQ/manageiq", "Sprint #{previous_milestone_number}")
end
end
def sprint_range
@sprint_range ||= ((previous_milestone.due_on.utc.midnight + 1.day)..(current_milestone.due_on.utc.midnight + 1.day))
end
def default_repos
@default_repos ||= project_names_from_org("ManageIQ").to_a + ["Ansible/ansible_tower_client_ruby"]
end
def client
@client ||= begin
require 'octokit'
Octokit.configure do |c|
c.auto_paginate = true
c.middleware = Faraday::RackBuilder.new do |builder|
if ENV['DEBUG']
builder.use(
Class.new(Faraday::Response::Middleware) do
def on_complete(env)
api_calls_remaining = env.response_headers['x-ratelimit-remaining']
STDOUT.puts "DEBUG: Executed #{env.method.to_s.upcase} #{env.url} ... api calls remaining #{api_calls_remaining}"
end
end
)
end
builder.use Octokit::Response::RaiseError
builder.use Octokit::Response::FeedParser
builder.adapter Faraday.default_adapter
end
end
Octokit::Client.new(:access_token => @access_token)
end
end
def fetch(collection, *args)
options = args.extract_options!
client.send(collection, *args, options)
end
def issues(repo, options = {})
fetch(:issues, repo, options)
end
def pull_requests(repo, options = {})
# client.pull_requests doesn't honor milestone filter, so use client.issues instead
issues(repo, options).select(&:pull_request?)
end
def project_names_from_org(org)
fetch(:repositories, org).reject { |r| r.archived? || r.fork? }.collect(&:full_name)
end
def raw_pull_requests(repo, options = {})
fetch(:pull_requests, repo, options)
end
end
| {
"content_hash": "baae8f2987b3945ca0ad5955ef8d89c9",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 131,
"avg_line_length": 30.98780487804878,
"alnum_prop": 0.6462022825659189,
"repo_name": "gmcculloug/sprint_statistics",
"id": "41c28a40bd0b4178311ce2691da564471b6ae6ae",
"size": "2541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sprint_statistics.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "11493"
}
],
"symlink_target": ""
} |
#include "tscore/AcidPtr.h"
const int READLOCKCOUNT = 61; // a prime larger than number of readers
AcidPtrMutex &
AcidPtrMutexGet(void const *ptr)
{
static LockPool<AcidPtrMutex> read_locks(READLOCKCOUNT);
static_assert(sizeof(void *) == sizeof(size_t));
return read_locks.getMutex(reinterpret_cast<size_t>(ptr));
}
const int WRITELOCKCOUNT = 31; // a prime larger than number of writers
AcidCommitMutex &
AcidCommitMutexGet(void const *ptr)
{
static LockPool<AcidCommitMutex> write_locks(WRITELOCKCOUNT);
static_assert(sizeof(void *) == sizeof(size_t));
return write_locks.getMutex(reinterpret_cast<size_t>(ptr));
}
| {
"content_hash": "2bd68248523daaa9a6bdaeeb43bacce2",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 71,
"avg_line_length": 27.608695652173914,
"alnum_prop": 0.7464566929133858,
"repo_name": "bryancall/trafficserver",
"id": "5c793609e7ee21c8ad1be0a2249ef1bae6a3bdf5",
"size": "1522",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "src/tscore/AcidPtr.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1402820"
},
{
"name": "C++",
"bytes": "15545891"
},
{
"name": "CMake",
"bytes": "19248"
},
{
"name": "Dockerfile",
"bytes": "6693"
},
{
"name": "Java",
"bytes": "9881"
},
{
"name": "Lua",
"bytes": "63183"
},
{
"name": "M4",
"bytes": "197455"
},
{
"name": "Makefile",
"bytes": "240525"
},
{
"name": "Objective-C",
"bytes": "3722"
},
{
"name": "Perl",
"bytes": "128281"
},
{
"name": "Python",
"bytes": "1151937"
},
{
"name": "SWIG",
"bytes": "25971"
},
{
"name": "Shell",
"bytes": "169276"
},
{
"name": "Vim Script",
"bytes": "192"
}
],
"symlink_target": ""
} |
package org.apache.pluto.driver;
import org.apache.pluto.driver.util.RenderData;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* @author Neil Griffin
*/
public class PartialActionResponse extends HttpServletResponseWrapper {
private String contentType;
private PrintWriter printWriter;
private StringWriter stringWriter;
public PartialActionResponse(HttpServletResponse response) {
super(response);
this.stringWriter = new StringWriter();
this.printWriter = new PrintWriter(stringWriter);
}
public RenderData getRenderData() {
return new RenderData(stringWriter.toString(), contentType);
}
@Override
public PrintWriter getWriter() throws IOException {
return printWriter;
}
@Override
public void setContentLength(int contentLength) {
// no-op
}
@Override
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
| {
"content_hash": "33c76cbb512f86b2cce3809438e01df8",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 71,
"avg_line_length": 21.893617021276597,
"alnum_prop": 0.7842565597667639,
"repo_name": "apache/portals-pluto",
"id": "7212a4ae7a24ec4deb3ba84aa98bcdf701ba5bd6",
"size": "1831",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pluto-portal-driver/src/main/java/org/apache/pluto/driver/PartialActionResponse.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "898"
},
{
"name": "CSS",
"bytes": "38272"
},
{
"name": "HTML",
"bytes": "17705"
},
{
"name": "Java",
"bytes": "16436890"
},
{
"name": "JavaScript",
"bytes": "629755"
},
{
"name": "XSLT",
"bytes": "14962"
}
],
"symlink_target": ""
} |
welecom to My Blog! | {
"content_hash": "ec81b1d58d3baa5bc6fd4aa52f114c40",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 19,
"avg_line_length": 19,
"alnum_prop": 0.7894736842105263,
"repo_name": "shuaica/shuaica.github.io",
"id": "787e63f54bd6f7f3a2075528fbe9caadb76294d1",
"size": "36",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "57288"
},
{
"name": "HTML",
"bytes": "53799"
},
{
"name": "JavaScript",
"bytes": "15166"
}
],
"symlink_target": ""
} |
({
testUndefined: {
test: function(component){
this.whatItIs(component, "Undefined", false);
}
},
testTrue: {
attributes : {thang : true},
test: function(component){
this.whatItIs(component, "true", true);
}
},
testFalse: {
attributes : {thang : false},
test: function(component){
this.whatItIs(component, "false", false);
}
},
testLiterals: {
test: function(component){
$A.test.assertNull($A.test.getElementByClass("itIsLiterallyFalse"), "Literal false didn't evaluate as false");
$A.test.assertNotNull($A.test.getElementByClass("itIsLiterallyNotFalse"), "Literal true evaluated as false");
}
},
// TODO(W-1419175): onchange events don't fire across function expressions
_testRerender: {
attributes : {thang : true},
test: function(component){
this.whatItIs(component, "Testing Renrender: true", true);
component.set("v.thang", false);
$A.rerender(component);
this.whatItIs(component, "Testing Rerender: false", false);
}
},
whatItIs : function(component, name, value){
if (!value) {
$A.test.assertNotNull($A.test.getElementByClass("itIsFalse"), name+" didn't evaluate as false");
$A.test.assertNull($A.test.getElementByClass("itIsTrue"), name+" evaluated as true");
}else{
$A.test.assertNotNull($A.test.getElementByClass("itIsTrue"), name+" didn't evaluate as true");
$A.test.assertNull($A.test.getElementByClass("itIsFalse"), name+" evaluated as false");
}
}
})
| {
"content_hash": "2a24792f6882d70e7f7939fdea0f98e9",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 122,
"avg_line_length": 34.18,
"alnum_prop": 0.5833820947922762,
"repo_name": "madmax983/aura",
"id": "a18227e3a5903e101cf3b13e07d88f835ee5b612",
"size": "2320",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aura-components/src/test/components/ifTest/testIf/testIfTest.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "782982"
},
{
"name": "GAP",
"bytes": "10087"
},
{
"name": "HTML",
"bytes": "3296233"
},
{
"name": "Java",
"bytes": "9575906"
},
{
"name": "JavaScript",
"bytes": "26838648"
},
{
"name": "PHP",
"bytes": "3345441"
},
{
"name": "Python",
"bytes": "9744"
},
{
"name": "Shell",
"bytes": "20356"
},
{
"name": "XSLT",
"bytes": "1579"
}
],
"symlink_target": ""
} |
module Mosaic
# Used to build a response for sinatra to serve
class Response
attr_accessor :content, :layout, :response_code, :view_format, :output_format
attr_reader :request
def initialize(request)
@view_format = :erb
@output_format = :html
@layout = :'layouts/application'
@request = request
@response_code = 200
end
end
end | {
"content_hash": "a4057212ec228ccd21a5ff1015b054f2",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 81,
"avg_line_length": 25.6,
"alnum_prop": 0.6484375,
"repo_name": "Arcath/mosaic",
"id": "4b0f5dbb5916e6bc0c5916489d4fcef5623af8bb",
"size": "384",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/mosaic/response.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "13634"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hbase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.TestChoreService.ScheduledChoreSamples.CountingChore;
import org.apache.hadoop.hbase.TestChoreService.ScheduledChoreSamples.DoNothingChore;
import org.apache.hadoop.hbase.TestChoreService.ScheduledChoreSamples.FailInitialChore;
import org.apache.hadoop.hbase.TestChoreService.ScheduledChoreSamples.SampleStopper;
import org.apache.hadoop.hbase.TestChoreService.ScheduledChoreSamples.SleepingChore;
import org.apache.hadoop.hbase.TestChoreService.ScheduledChoreSamples.SlowChore;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(SmallTests.class)
public class TestChoreService {
private final Log LOG = LogFactory.getLog(this.getClass());
/**
* A few ScheduledChore samples that are useful for testing with ChoreService
*/
public static class ScheduledChoreSamples {
/**
* Straight forward stopper implementation that is used by default when one is not provided
*/
public static class SampleStopper implements Stoppable {
private boolean stopped = false;
@Override
public void stop(String why) {
stopped = true;
}
@Override
public boolean isStopped() {
return stopped;
}
}
/**
* Sleeps for longer than the scheduled period. This chore always misses its scheduled periodic
* executions
*/
public static class SlowChore extends ScheduledChore {
public SlowChore(String name, int period) {
this(name, new SampleStopper(), period);
}
public SlowChore(String name, Stoppable stopper, int period) {
super(name, stopper, period);
}
@Override
protected boolean initialChore() {
try {
Thread.sleep(getPeriod() * 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
@Override
protected void chore() {
try {
Thread.sleep(getPeriod() * 2);
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}
/**
* Lightweight ScheduledChore used primarily to fill the scheduling queue in tests
*/
public static class DoNothingChore extends ScheduledChore {
public DoNothingChore(String name, int period) {
super(name, new SampleStopper(), period);
}
public DoNothingChore(String name, Stoppable stopper, int period) {
super(name, stopper, period);
}
@Override
protected void chore() {
// DO NOTHING
}
}
public static class SleepingChore extends ScheduledChore {
private int sleepTime;
public SleepingChore(String name, int chorePeriod, int sleepTime) {
this(name, new SampleStopper(), chorePeriod, sleepTime);
}
public SleepingChore(String name, Stoppable stopper, int period, int sleepTime) {
super(name, stopper, period);
this.sleepTime = sleepTime;
}
@Override
protected boolean initialChore() {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
@Override
protected void chore() {
try {
Thread.sleep(sleepTime);
} catch (Exception e) {
System.err.println(e.getStackTrace());
}
}
}
public static class CountingChore extends ScheduledChore {
private int countOfChoreCalls;
private boolean outputOnTicks = false;
public CountingChore(String name, int period) {
this(name, new SampleStopper(), period);
}
public CountingChore(String name, Stoppable stopper, int period) {
this(name, stopper, period, false);
}
public CountingChore(String name, Stoppable stopper, int period,
final boolean outputOnTicks) {
super(name, stopper, period);
this.countOfChoreCalls = 0;
this.outputOnTicks = outputOnTicks;
}
@Override
protected boolean initialChore() {
countOfChoreCalls++;
if (outputOnTicks) outputTickCount();
return true;
}
@Override
protected void chore() {
countOfChoreCalls++;
if (outputOnTicks) outputTickCount();
}
private void outputTickCount() {
System.out.println("Chore: " + getName() + ". Count of chore calls: " + countOfChoreCalls);
}
public int getCountOfChoreCalls() {
return countOfChoreCalls;
}
public boolean isOutputtingOnTicks() {
return outputOnTicks;
}
public void setOutputOnTicks(boolean o) {
outputOnTicks = o;
}
}
/**
* A Chore that will try to execute the initial chore a few times before succeeding. Once the
* initial chore is complete the chore cancels itself
*/
public static class FailInitialChore extends ScheduledChore {
private int numberOfFailures;
private int failureThreshold;
/**
* @param failThreshold Number of times the Chore fails when trying to execute initialChore
* before succeeding.
*/
public FailInitialChore(String name, int period, int failThreshold) {
this(name, new SampleStopper(), period, failThreshold);
}
public FailInitialChore(String name, Stoppable stopper, int period, int failThreshold) {
super(name, stopper, period);
numberOfFailures = 0;
failureThreshold = failThreshold;
}
@Override
protected boolean initialChore() {
if (numberOfFailures < failureThreshold) {
numberOfFailures++;
return false;
} else {
return true;
}
}
@Override
protected void chore() {
assertTrue(numberOfFailures == failureThreshold);
cancel(false);
}
}
}
@Test (timeout=20000)
public void testInitialChorePrecedence() throws InterruptedException {
ChoreService service = ChoreService.getInstance("testInitialChorePrecedence");
final int period = 100;
final int failureThreshold = 5;
try {
ScheduledChore chore = new FailInitialChore("chore", period, failureThreshold);
service.scheduleChore(chore);
int loopCount = 0;
boolean brokeOutOfLoop = false;
while (!chore.isInitialChoreComplete() && chore.isScheduled()) {
Thread.sleep(failureThreshold * period);
loopCount++;
if (loopCount > 3) {
brokeOutOfLoop = true;
break;
}
}
assertFalse(brokeOutOfLoop);
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testCancelChore() throws InterruptedException {
final int period = 100;
ScheduledChore chore1 = new DoNothingChore("chore1", period);
ChoreService service = ChoreService.getInstance("testCancelChore");
try {
service.scheduleChore(chore1);
assertTrue(chore1.isScheduled());
chore1.cancel(true);
assertFalse(chore1.isScheduled());
assertTrue(service.getNumberOfScheduledChores() == 0);
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testScheduledChoreConstruction() {
final String NAME = "chore";
final int PERIOD = 100;
final long VALID_DELAY = 0;
final long INVALID_DELAY = -100;
final TimeUnit UNIT = TimeUnit.NANOSECONDS;
ScheduledChore chore1 =
new ScheduledChore(NAME, new SampleStopper(), PERIOD, VALID_DELAY, UNIT) {
@Override
protected void chore() {
// DO NOTHING
}
};
assertEquals("Name construction failed", chore1.getName(), NAME);
assertEquals("Period construction failed", chore1.getPeriod(), PERIOD);
assertEquals("Initial Delay construction failed", chore1.getInitialDelay(), VALID_DELAY);
assertEquals("TimeUnit construction failed", chore1.getTimeUnit(), UNIT);
ScheduledChore invalidDelayChore =
new ScheduledChore(NAME, new SampleStopper(), PERIOD, INVALID_DELAY, UNIT) {
@Override
protected void chore() {
// DO NOTHING
}
};
assertEquals("Initial Delay should be set to 0 when invalid", 0,
invalidDelayChore.getInitialDelay());
}
@Test (timeout=20000)
public void testChoreServiceConstruction() throws InterruptedException {
final int corePoolSize = 10;
final int defaultCorePoolSize = ChoreService.MIN_CORE_POOL_SIZE;
ChoreService customInit = new ChoreService("testChoreServiceConstruction_custom", corePoolSize);
try {
assertEquals(corePoolSize, customInit.getCorePoolSize());
} finally {
shutdownService(customInit);
}
ChoreService defaultInit = new ChoreService("testChoreServiceConstruction_default");
try {
assertEquals(defaultCorePoolSize, defaultInit.getCorePoolSize());
} finally {
shutdownService(defaultInit);
}
ChoreService invalidInit = new ChoreService("testChoreServiceConstruction_invalid", -10);
try {
assertEquals(defaultCorePoolSize, invalidInit.getCorePoolSize());
} finally {
shutdownService(invalidInit);
}
}
@Test (timeout=20000)
public void testFrequencyOfChores() throws InterruptedException {
final int period = 100;
// Small delta that acts as time buffer (allowing chores to complete if running slowly)
final int delta = 5;
ChoreService service = ChoreService.getInstance("testFrequencyOfChores");
CountingChore chore = new CountingChore("countingChore", period);
try {
service.scheduleChore(chore);
Thread.sleep(10 * period + delta);
assertTrue(chore.getCountOfChoreCalls() == 11);
Thread.sleep(10 * period);
assertTrue(chore.getCountOfChoreCalls() == 21);
} finally {
shutdownService(service);
}
}
public void shutdownService(ChoreService service) throws InterruptedException {
service.shutdown();
while (!service.isTerminated()) {
Thread.sleep(100);
}
}
@Test (timeout=20000)
public void testForceTrigger() throws InterruptedException {
final int period = 100;
final int delta = 5;
ChoreService service = ChoreService.getInstance("testForceTrigger");
CountingChore chore = new CountingChore("countingChore", period);
try {
service.scheduleChore(chore);
Thread.sleep(10 * period + delta);
assertTrue(chore.getCountOfChoreCalls() == 11);
// Force five runs of the chore to occur, sleeping between triggers to ensure the
// chore has time to run
chore.triggerNow();
Thread.sleep(delta);
chore.triggerNow();
Thread.sleep(delta);
chore.triggerNow();
Thread.sleep(delta);
chore.triggerNow();
Thread.sleep(delta);
chore.triggerNow();
Thread.sleep(delta);
assertTrue(chore.getCountOfChoreCalls() == 16);
Thread.sleep(10 * period + delta);
assertTrue(chore.getCountOfChoreCalls() == 26);
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testCorePoolIncrease() throws InterruptedException {
final int initialCorePoolSize = 3;
ChoreService service = new ChoreService("testCorePoolIncrease", initialCorePoolSize);
try {
assertEquals("Should have a core pool of size: " + initialCorePoolSize, initialCorePoolSize,
service.getCorePoolSize());
final int slowChorePeriod = 100;
SlowChore slowChore1 = new SlowChore("slowChore1", slowChorePeriod);
SlowChore slowChore2 = new SlowChore("slowChore2", slowChorePeriod);
SlowChore slowChore3 = new SlowChore("slowChore3", slowChorePeriod);
service.scheduleChore(slowChore1);
service.scheduleChore(slowChore2);
service.scheduleChore(slowChore3);
Thread.sleep(slowChorePeriod * 10);
assertEquals("Should not create more pools than scheduled chores", 3,
service.getCorePoolSize());
SlowChore slowChore4 = new SlowChore("slowChore4", slowChorePeriod);
service.scheduleChore(slowChore4);
Thread.sleep(slowChorePeriod * 10);
assertEquals("Chores are missing their start time. Should expand core pool size", 4,
service.getCorePoolSize());
SlowChore slowChore5 = new SlowChore("slowChore5", slowChorePeriod);
service.scheduleChore(slowChore5);
Thread.sleep(slowChorePeriod * 10);
assertEquals("Chores are missing their start time. Should expand core pool size", 5,
service.getCorePoolSize());
} finally {
shutdownService(service);
}
}
@Test(timeout = 30000)
public void testCorePoolDecrease() throws InterruptedException {
final int initialCorePoolSize = 3;
ChoreService service = new ChoreService("testCorePoolDecrease", initialCorePoolSize);
final int chorePeriod = 100;
try {
// Slow chores always miss their start time and thus the core pool size should be at least as
// large as the number of running slow chores
SlowChore slowChore1 = new SlowChore("slowChore1", chorePeriod);
SlowChore slowChore2 = new SlowChore("slowChore2", chorePeriod);
SlowChore slowChore3 = new SlowChore("slowChore3", chorePeriod);
service.scheduleChore(slowChore1);
service.scheduleChore(slowChore2);
service.scheduleChore(slowChore3);
Thread.sleep(chorePeriod * 10);
assertEquals("Should not create more pools than scheduled chores",
service.getNumberOfScheduledChores(), service.getCorePoolSize());
SlowChore slowChore4 = new SlowChore("slowChore4", chorePeriod);
service.scheduleChore(slowChore4);
Thread.sleep(chorePeriod * 10);
assertEquals("Chores are missing their start time. Should expand core pool size",
service.getNumberOfScheduledChores(), service.getCorePoolSize());
SlowChore slowChore5 = new SlowChore("slowChore5", chorePeriod);
service.scheduleChore(slowChore5);
Thread.sleep(chorePeriod * 10);
assertEquals("Chores are missing their start time. Should expand core pool size",
service.getNumberOfScheduledChores(), service.getCorePoolSize());
assertEquals(service.getNumberOfChoresMissingStartTime(), 5);
// Now we begin to cancel the chores that caused an increase in the core thread pool of the
// ChoreService. These cancellations should cause a decrease in the core thread pool.
slowChore5.cancel();
Thread.sleep(chorePeriod * 10);
assertEquals(Math.max(ChoreService.MIN_CORE_POOL_SIZE, service.getNumberOfScheduledChores()),
service.getCorePoolSize());
assertEquals(service.getNumberOfChoresMissingStartTime(), 4);
slowChore4.cancel();
Thread.sleep(chorePeriod * 10);
assertEquals(Math.max(ChoreService.MIN_CORE_POOL_SIZE, service.getNumberOfScheduledChores()),
service.getCorePoolSize());
assertEquals(service.getNumberOfChoresMissingStartTime(), 3);
slowChore3.cancel();
Thread.sleep(chorePeriod * 10);
assertEquals(Math.max(ChoreService.MIN_CORE_POOL_SIZE, service.getNumberOfScheduledChores()),
service.getCorePoolSize());
assertEquals(service.getNumberOfChoresMissingStartTime(), 2);
slowChore2.cancel();
Thread.sleep(chorePeriod * 10);
assertEquals(Math.max(ChoreService.MIN_CORE_POOL_SIZE, service.getNumberOfScheduledChores()),
service.getCorePoolSize());
assertEquals(service.getNumberOfChoresMissingStartTime(), 1);
slowChore1.cancel();
Thread.sleep(chorePeriod * 10);
assertEquals(Math.max(ChoreService.MIN_CORE_POOL_SIZE, service.getNumberOfScheduledChores()),
service.getCorePoolSize());
assertEquals(service.getNumberOfChoresMissingStartTime(), 0);
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testNumberOfRunningChores() throws InterruptedException {
ChoreService service = new ChoreService("testNumberOfRunningChores");
final int period = 100;
final int sleepTime = 5;
try {
DoNothingChore dn1 = new DoNothingChore("dn1", period);
DoNothingChore dn2 = new DoNothingChore("dn2", period);
DoNothingChore dn3 = new DoNothingChore("dn3", period);
DoNothingChore dn4 = new DoNothingChore("dn4", period);
DoNothingChore dn5 = new DoNothingChore("dn5", period);
service.scheduleChore(dn1);
service.scheduleChore(dn2);
service.scheduleChore(dn3);
service.scheduleChore(dn4);
service.scheduleChore(dn5);
Thread.sleep(sleepTime);
assertEquals("Scheduled chore mismatch", 5, service.getNumberOfScheduledChores());
dn1.cancel();
Thread.sleep(sleepTime);
assertEquals("Scheduled chore mismatch", 4, service.getNumberOfScheduledChores());
dn2.cancel();
dn3.cancel();
dn4.cancel();
Thread.sleep(sleepTime);
assertEquals("Scheduled chore mismatch", 1, service.getNumberOfScheduledChores());
dn5.cancel();
Thread.sleep(sleepTime);
assertEquals("Scheduled chore mismatch", 0, service.getNumberOfScheduledChores());
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testNumberOfChoresMissingStartTime() throws InterruptedException {
ChoreService service = new ChoreService("testNumberOfChoresMissingStartTime");
final int period = 100;
final int sleepTime = 5 * period;
try {
// Slow chores sleep for a length of time LONGER than their period. Thus, SlowChores
// ALWAYS miss their start time since their execution takes longer than their period
SlowChore sc1 = new SlowChore("sc1", period);
SlowChore sc2 = new SlowChore("sc2", period);
SlowChore sc3 = new SlowChore("sc3", period);
SlowChore sc4 = new SlowChore("sc4", period);
SlowChore sc5 = new SlowChore("sc5", period);
service.scheduleChore(sc1);
service.scheduleChore(sc2);
service.scheduleChore(sc3);
service.scheduleChore(sc4);
service.scheduleChore(sc5);
Thread.sleep(sleepTime);
assertEquals(5, service.getNumberOfChoresMissingStartTime());
sc1.cancel();
Thread.sleep(sleepTime);
assertEquals(4, service.getNumberOfChoresMissingStartTime());
sc2.cancel();
sc3.cancel();
sc4.cancel();
Thread.sleep(sleepTime);
assertEquals(1, service.getNumberOfChoresMissingStartTime());
sc5.cancel();
Thread.sleep(sleepTime);
assertEquals(0, service.getNumberOfChoresMissingStartTime());
} finally {
shutdownService(service);
}
}
/**
* ChoreServices should never have a core pool size that exceeds the number of chores that have
* been scheduled with the service. For example, if 4 ScheduledChores are scheduled with a
* ChoreService, the number of threads in the ChoreService's core pool should never exceed 4
*/
@Test (timeout=20000)
public void testMaximumChoreServiceThreads() throws InterruptedException {
ChoreService service = new ChoreService("testMaximumChoreServiceThreads");
final int period = 100;
final int sleepTime = 5 * period;
try {
// Slow chores sleep for a length of time LONGER than their period. Thus, SlowChores
// ALWAYS miss their start time since their execution takes longer than their period.
// Chores that miss their start time will trigger the onChoreMissedStartTime callback
// in the ChoreService. This callback will try to increase the number of core pool
// threads.
SlowChore sc1 = new SlowChore("sc1", period);
SlowChore sc2 = new SlowChore("sc2", period);
SlowChore sc3 = new SlowChore("sc3", period);
SlowChore sc4 = new SlowChore("sc4", period);
SlowChore sc5 = new SlowChore("sc5", period);
service.scheduleChore(sc1);
service.scheduleChore(sc2);
service.scheduleChore(sc3);
service.scheduleChore(sc4);
service.scheduleChore(sc5);
Thread.sleep(sleepTime);
assertTrue(service.getCorePoolSize() <= service.getNumberOfScheduledChores());
SlowChore sc6 = new SlowChore("sc6", period);
SlowChore sc7 = new SlowChore("sc7", period);
SlowChore sc8 = new SlowChore("sc8", period);
SlowChore sc9 = new SlowChore("sc9", period);
SlowChore sc10 = new SlowChore("sc10", period);
service.scheduleChore(sc6);
service.scheduleChore(sc7);
service.scheduleChore(sc8);
service.scheduleChore(sc9);
service.scheduleChore(sc10);
Thread.sleep(sleepTime);
assertTrue(service.getCorePoolSize() <= service.getNumberOfScheduledChores());
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testChangingChoreServices() throws InterruptedException {
final int period = 100;
final int sleepTime = 10;
ChoreService service1 = new ChoreService("testChangingChoreServices_1");
ChoreService service2 = new ChoreService("testChangingChoreServices_2");
ScheduledChore chore = new DoNothingChore("sample", period);
try {
assertFalse(chore.isScheduled());
assertFalse(service1.isChoreScheduled(chore));
assertFalse(service2.isChoreScheduled(chore));
assertTrue(chore.getChoreServicer() == null);
service1.scheduleChore(chore);
Thread.sleep(sleepTime);
assertTrue(chore.isScheduled());
assertTrue(service1.isChoreScheduled(chore));
assertFalse(service2.isChoreScheduled(chore));
assertFalse(chore.getChoreServicer() == null);
service2.scheduleChore(chore);
Thread.sleep(sleepTime);
assertTrue(chore.isScheduled());
assertFalse(service1.isChoreScheduled(chore));
assertTrue(service2.isChoreScheduled(chore));
assertFalse(chore.getChoreServicer() == null);
chore.cancel();
assertFalse(chore.isScheduled());
assertFalse(service1.isChoreScheduled(chore));
assertFalse(service2.isChoreScheduled(chore));
assertTrue(chore.getChoreServicer() == null);
} finally {
shutdownService(service1);
shutdownService(service2);
}
}
@Test (timeout=20000)
public void testTriggerNowFailsWhenNotScheduled() throws InterruptedException {
final int period = 100;
// Small sleep time buffer to allow CountingChore to complete
final int sleep = 5;
ChoreService service = new ChoreService("testTriggerNowFailsWhenNotScheduled");
CountingChore chore = new CountingChore("dn", period);
try {
assertFalse(chore.triggerNow());
assertTrue(chore.getCountOfChoreCalls() == 0);
service.scheduleChore(chore);
Thread.sleep(sleep);
assertEquals(1, chore.getCountOfChoreCalls());
Thread.sleep(period);
assertEquals(2, chore.getCountOfChoreCalls());
assertTrue(chore.triggerNow());
Thread.sleep(sleep);
assertTrue(chore.triggerNow());
Thread.sleep(sleep);
assertTrue(chore.triggerNow());
Thread.sleep(sleep);
assertEquals(5, chore.getCountOfChoreCalls());
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testStopperForScheduledChores() throws InterruptedException {
ChoreService service = ChoreService.getInstance("testStopperForScheduledChores");
Stoppable stopperForGroup1 = new SampleStopper();
Stoppable stopperForGroup2 = new SampleStopper();
final int period = 100;
final int delta = 10;
try {
ScheduledChore chore1_group1 = new DoNothingChore("c1g1", stopperForGroup1, period);
ScheduledChore chore2_group1 = new DoNothingChore("c2g1", stopperForGroup1, period);
ScheduledChore chore3_group1 = new DoNothingChore("c3g1", stopperForGroup1, period);
ScheduledChore chore1_group2 = new DoNothingChore("c1g2", stopperForGroup2, period);
ScheduledChore chore2_group2 = new DoNothingChore("c2g2", stopperForGroup2, period);
ScheduledChore chore3_group2 = new DoNothingChore("c3g2", stopperForGroup2, period);
service.scheduleChore(chore1_group1);
service.scheduleChore(chore2_group1);
service.scheduleChore(chore3_group1);
service.scheduleChore(chore1_group2);
service.scheduleChore(chore2_group2);
service.scheduleChore(chore3_group2);
Thread.sleep(delta);
Thread.sleep(10 * period);
assertTrue(chore1_group1.isScheduled());
assertTrue(chore2_group1.isScheduled());
assertTrue(chore3_group1.isScheduled());
assertTrue(chore1_group2.isScheduled());
assertTrue(chore2_group2.isScheduled());
assertTrue(chore3_group2.isScheduled());
stopperForGroup1.stop("test stopping group 1");
Thread.sleep(period);
assertFalse(chore1_group1.isScheduled());
assertFalse(chore2_group1.isScheduled());
assertFalse(chore3_group1.isScheduled());
assertTrue(chore1_group2.isScheduled());
assertTrue(chore2_group2.isScheduled());
assertTrue(chore3_group2.isScheduled());
stopperForGroup2.stop("test stopping group 2");
Thread.sleep(period);
assertFalse(chore1_group1.isScheduled());
assertFalse(chore2_group1.isScheduled());
assertFalse(chore3_group1.isScheduled());
assertFalse(chore1_group2.isScheduled());
assertFalse(chore2_group2.isScheduled());
assertFalse(chore3_group2.isScheduled());
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testShutdownCancelsScheduledChores() throws InterruptedException {
final int period = 100;
ChoreService service = new ChoreService("testShutdownCancelsScheduledChores");
ScheduledChore successChore1 = new DoNothingChore("sc1", period);
ScheduledChore successChore2 = new DoNothingChore("sc2", period);
ScheduledChore successChore3 = new DoNothingChore("sc3", period);
try {
assertTrue(service.scheduleChore(successChore1));
assertTrue(successChore1.isScheduled());
assertTrue(service.scheduleChore(successChore2));
assertTrue(successChore2.isScheduled());
assertTrue(service.scheduleChore(successChore3));
assertTrue(successChore3.isScheduled());
} finally {
shutdownService(service);
}
assertFalse(successChore1.isScheduled());
assertFalse(successChore2.isScheduled());
assertFalse(successChore3.isScheduled());
}
@Test (timeout=20000)
public void testShutdownWorksWhileChoresAreExecuting() throws InterruptedException {
final int period = 100;
final int sleep = 5 * period;
ChoreService service = new ChoreService("testShutdownWorksWhileChoresAreExecuting");
ScheduledChore slowChore1 = new SleepingChore("sc1", period, sleep);
ScheduledChore slowChore2 = new SleepingChore("sc2", period, sleep);
ScheduledChore slowChore3 = new SleepingChore("sc3", period, sleep);
try {
assertTrue(service.scheduleChore(slowChore1));
assertTrue(service.scheduleChore(slowChore2));
assertTrue(service.scheduleChore(slowChore3));
Thread.sleep(sleep / 2);
shutdownService(service);
assertFalse(slowChore1.isScheduled());
assertFalse(slowChore2.isScheduled());
assertFalse(slowChore3.isScheduled());
assertTrue(service.isShutdown());
Thread.sleep(5);
assertTrue(service.isTerminated());
} finally {
shutdownService(service);
}
}
@Test (timeout=20000)
public void testShutdownRejectsNewSchedules() throws InterruptedException {
final int period = 100;
ChoreService service = new ChoreService("testShutdownRejectsNewSchedules");
ScheduledChore successChore1 = new DoNothingChore("sc1", period);
ScheduledChore successChore2 = new DoNothingChore("sc2", period);
ScheduledChore successChore3 = new DoNothingChore("sc3", period);
ScheduledChore failChore1 = new DoNothingChore("fc1", period);
ScheduledChore failChore2 = new DoNothingChore("fc2", period);
ScheduledChore failChore3 = new DoNothingChore("fc3", period);
try {
assertTrue(service.scheduleChore(successChore1));
assertTrue(successChore1.isScheduled());
assertTrue(service.scheduleChore(successChore2));
assertTrue(successChore2.isScheduled());
assertTrue(service.scheduleChore(successChore3));
assertTrue(successChore3.isScheduled());
} finally {
shutdownService(service);
}
assertFalse(service.scheduleChore(failChore1));
assertFalse(failChore1.isScheduled());
assertFalse(service.scheduleChore(failChore2));
assertFalse(failChore2.isScheduled());
assertFalse(service.scheduleChore(failChore3));
assertFalse(failChore3.isScheduled());
}
}
| {
"content_hash": "a73bdf4bebdf44e5714a6670e9f55282",
"timestamp": "",
"source": "github",
"line_count": 839,
"max_line_length": 100,
"avg_line_length": 34.656734207389746,
"alnum_prop": 0.689961137668948,
"repo_name": "ibmsoe/hbase",
"id": "1496dc7111ce921ac8620514e4f45b1ad69d4647",
"size": "29883",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.1.1-power",
"path": "hbase-common/src/test/java/org/apache/hadoop/hbase/TestChoreService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "351"
},
{
"name": "C",
"bytes": "28617"
},
{
"name": "C++",
"bytes": "770077"
},
{
"name": "CMake",
"bytes": "10933"
},
{
"name": "CSS",
"bytes": "38865"
},
{
"name": "HTML",
"bytes": "70900"
},
{
"name": "Java",
"bytes": "24494486"
},
{
"name": "JavaScript",
"bytes": "2694"
},
{
"name": "Makefile",
"bytes": "1409"
},
{
"name": "PHP",
"bytes": "413443"
},
{
"name": "Perl",
"bytes": "383793"
},
{
"name": "Protocol Buffer",
"bytes": "129208"
},
{
"name": "Python",
"bytes": "535753"
},
{
"name": "Ruby",
"bytes": "468412"
},
{
"name": "Shell",
"bytes": "201911"
},
{
"name": "Thrift",
"bytes": "39026"
},
{
"name": "XSLT",
"bytes": "5116"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.