code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/**
* @license
* Copyright (c) 2017 Google Inc. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Code distributed by Google as part of this project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import { Strategy } from '../strategizer.js';
export declare class CreateHandleGroup extends Strategy {
generate(inputParams: any): any;
}
| PolymerLabs/arcs-live | build/planning/strategies/create-handle-group.d.ts | TypeScript | bsd-3-clause | 480 |
// Copyright (c) 2006-2008 Max-Planck-Institute Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s) : Michael Hemmer <hemmer@mpi-inf.mpg.de>
//
// =============================================================================
#ifndef CGAL_PRIMES_H
#define CGAL_PRIMES_H
#include <CGAL/basic.h>
namespace CGAL {
namespace internal {
CGAL_EXPORT extern const int primes[2000];
static inline
int get_next_lower_prime(int current_prime){
bool is_prime = false;
int i;
CGAL_precondition_msg(current_prime != 2 ," primes definitely exhausted ");
if((current_prime <= 7) && (current_prime > 2)){
if(current_prime <= 5){
if(current_prime == 3)
return 2;
return 3;
}
return 5;
}
for(i=current_prime-2;(i>1 && !is_prime);i=i-2){
int r = 1;
for(int j=3; (j <= i/2 && (r != 0)); j++){
r = i % j;
// std::cout<<"i " <<i<<std::endl;
// std::cout<<"j " <<j<<std::endl;
// std::cout<<"i%j " <<i%j<<std::endl;
if(j==i/2 && r != 0)
is_prime = true;
}
}
// CGAL_precondition_msg(is_prime," primes definitely exhausted ");
return i+2;
}
}
}
#ifdef CGAL_HEADER_ONLY
#include <CGAL/primes_impl.h>
#endif // CGAL_HEADER_ONLY
#endif // CGAL_PRIMES_H
| hlzz/dotfiles | graphics/cgal/Modular_arithmetic/include/CGAL/primes.h | C | bsd-3-clause | 1,987 |
almacen
=======
Sistema basico de almacen
| sandyrod/almacen | README.md | Markdown | bsd-3-clause | 43 |
<!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.5.0_18) on Tue Jul 07 10:40:17 PDT 2009 -->
<TITLE>
TransactionXMLAdapter
</TITLE>
<META NAME="keywords" CONTENT="apollo.dataadapter.gamexml.TransactionXMLAdapter class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="TransactionXMLAdapter";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= 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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</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">
<A HREF="../../../apollo/dataadapter/gamexml/GAMESave.html" title="class in apollo.dataadapter.gamexml"><B>PREV CLASS</B></A>
<A HREF="../../../apollo/dataadapter/gamexml/XMLParser.html" title="class in apollo.dataadapter.gamexml"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?apollo/dataadapter/gamexml/TransactionXMLAdapter.html" target="_top"><B>FRAMES</B></A>
<A HREF="TransactionXMLAdapter.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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
apollo.dataadapter.gamexml</FONT>
<BR>
Class TransactionXMLAdapter</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>apollo.dataadapter.gamexml.TransactionXMLAdapter</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>TransactionXMLAdapter</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
This class is used to save and load Transaction objects into XML file.
<P>
<P>
<DL>
<DT><B>Author:</B></DT>
<DD>wgm</DD>
</DL>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../apollo/dataadapter/gamexml/TransactionXMLAdapter.html#EXT_NAME">EXT_NAME</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected static org.apache.log4j.Logger</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../apollo/dataadapter/gamexml/TransactionXMLAdapter.html#logger">logger</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../apollo/dataadapter/gamexml/TransactionXMLAdapter.html#TransactionXMLAdapter()">TransactionXMLAdapter</A></B>()</CODE>
<BR>
Default constructor.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../apollo/dataadapter/gamexml/TransactionXMLAdapter.html#loadTransactions(java.lang.String, apollo.datamodel.CurationSet, apollo.dataadapter.CurationState)">loadTransactions</A></B>(java.lang.String fileName,
<A HREF="../../../apollo/datamodel/CurationSet.html" title="class in apollo.datamodel">CurationSet</A> curation,
<A HREF="../../../apollo/dataadapter/CurationState.html" title="class in apollo.dataadapter">CurationState</A> cs)</CODE>
<BR>
Loads (new) transactions from a transaction file (transaction file name is derived from
XML filename supplied to this method).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../apollo/dataadapter/gamexml/TransactionXMLAdapter.html#save(java.util.List)">save</A></B>(java.util.List transactions)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../apollo/dataadapter/gamexml/TransactionXMLAdapter.html#save(java.util.List, boolean)">save</A></B>(java.util.List transactions,
boolean writingSeparateFile)</CODE>
<BR>
Save a list of Transaction objects into a file.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../apollo/dataadapter/gamexml/TransactionXMLAdapter.html#setFileName(java.lang.String)">setFileName</A></B>(java.lang.String annotFileName)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../apollo/dataadapter/gamexml/TransactionXMLAdapter.html#setWriter(java.io.Writer)">setWriter</A></B>(java.io.Writer writer)</CODE>
<BR>
If writing to a game file GAMESave passes in the writer for the file</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="logger"><!-- --></A><H3>
logger</H3>
<PRE>
protected static final org.apache.log4j.Logger <B>logger</B></PRE>
<DL>
<DL>
</DL>
</DL>
<HR>
<A NAME="EXT_NAME"><!-- --></A><H3>
EXT_NAME</H3>
<PRE>
public static final java.lang.String <B>EXT_NAME</B></PRE>
<DL>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#apollo.dataadapter.gamexml.TransactionXMLAdapter.EXT_NAME">Constant Field Values</A></DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="TransactionXMLAdapter()"><!-- --></A><H3>
TransactionXMLAdapter</H3>
<PRE>
public <B>TransactionXMLAdapter</B>()</PRE>
<DL>
<DD>Default constructor.
<P>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="setWriter(java.io.Writer)"><!-- --></A><H3>
setWriter</H3>
<PRE>
public void <B>setWriter</B>(java.io.Writer writer)</PRE>
<DL>
<DD>If writing to a game file GAMESave passes in the writer for the file
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setFileName(java.lang.String)"><!-- --></A><H3>
setFileName</H3>
<PRE>
public void <B>setFileName</B>(java.lang.String annotFileName)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="loadTransactions(java.lang.String, apollo.datamodel.CurationSet, apollo.dataadapter.CurationState)"><!-- --></A><H3>
loadTransactions</H3>
<PRE>
public static void <B>loadTransactions</B>(java.lang.String fileName,
<A HREF="../../../apollo/datamodel/CurationSet.html" title="class in apollo.datamodel">CurationSet</A> curation,
<A HREF="../../../apollo/dataadapter/CurationState.html" title="class in apollo.dataadapter">CurationState</A> cs)
throws java.io.IOException</PRE>
<DL>
<DD>Loads (new) transactions from a transaction file (transaction file name is derived from
XML filename supplied to this method).
Needs to be static because it's called from static methods. Is this bad?
sets curations transactions
<P>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="save(java.util.List)"><!-- --></A><H3>
save</H3>
<PRE>
public void <B>save</B>(java.util.List transactions)
throws java.io.IOException</PRE>
<DL>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="save(java.util.List, boolean)"><!-- --></A><H3>
save</H3>
<PRE>
public void <B>save</B>(java.util.List transactions,
boolean writingSeparateFile)
throws java.io.IOException</PRE>
<DL>
<DD>Save a list of Transaction objects into a file.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>transactions</CODE> - a list of Transactions to be saved<DD><CODE>writingSeparateFile</CODE> - if true writes header & closes Writer when done
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</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">
<A HREF="../../../apollo/dataadapter/gamexml/GAMESave.html" title="class in apollo.dataadapter.gamexml"><B>PREV CLASS</B></A>
<A HREF="../../../apollo/dataadapter/gamexml/XMLParser.html" title="class in apollo.dataadapter.gamexml"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?apollo/dataadapter/gamexml/TransactionXMLAdapter.html" target="_top"><B>FRAMES</B></A>
<A HREF="TransactionXMLAdapter.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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| genome-vendor/apollo | javadoc/apollo/dataadapter/gamexml/TransactionXMLAdapter.html | HTML | bsd-3-clause | 15,863 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.states — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.tvalues" href="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.tvalues.html" />
<link rel="prev" title="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.sse" href="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.sse.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.states" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.0</span>
<span class="md-header-nav__topic"> statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.states </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.html" class="md-tabs__link">statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.states.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-statespace-dynamic-factor-dynamicfactorresults-states--page-root">statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.states<a class="headerlink" href="#generated-statsmodels-tsa-statespace-dynamic-factor-dynamicfactorresults-states--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt id="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.states">
<em class="property">property </em><code class="sig-prename descclassname">DynamicFactorResults.</code><code class="sig-name descname">states</code><a class="headerlink" href="#statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.states" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.sse.html" title="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.sse"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.sse </span>
</div>
</a>
<a href="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.tvalues.html" title="statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.tvalues"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.tvalues </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Aug 27, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | statsmodels/statsmodels.github.io | v0.12.0/generated/statsmodels.tsa.statespace.dynamic_factor.DynamicFactorResults.states.html | HTML | bsd-3-clause | 18,090 |
{% from 'macros/datetime.html' import render_date %}
{% from 'macros/icons.html' import render_icon %}
<h2>{{ _('Personal Data') }} <a class="button button--compact" href="{{ url_for('.details_update_form') }}" title="{{ _('Change personal data') }}">{{ render_icon('edit') }}</a></h2>
<table>
<tr>
<td>
<div class="mb">
<div class="data-label">{{ _('Name') }}</div>
<div class="data-value">{{ detail.full_name|fallback }}</div>
</div>
</td>
<td>
<div class="mb">
<div class="data-label">{{ _('Date of birth') }}</div>
<div class="data-value">
{%- if detail.date_of_birth -%}
{{ render_date(detail.date_of_birth, smart=False) }}
{%- else -%}
{{ _('not given')|dim }}
{%- endif -%}
</div>
</div>
</td>
</tr>
<tr>
<td>
<div class="data-label">{{ _('Address') }}</div>
<div class="data-value">
{%- if detail.street or detail.zip_code or detail.city or detail.country %}
{%- if detail.street %}{{ detail.street }}<br>{% endif -%}
{%- if detail.zip_code %}{{ detail.zip_code }} {% endif %}
{%- if detail.city %}{{ detail.city }}{% endif -%}
{%- if detail.country %}<br>{{ detail.country }}{% endif -%}
{%- else -%}
{{ _('not given')|dim }}
{%- endif -%}
</div>
</td>
<td>
<div class="data-label">{{ _('Phone number') }}</div>
<div class="data-value">{{ detail.phone_number|fallback }}</div>
</td>
</tr>
</table>
| homeworkprod/byceps | byceps/blueprints/site/user/settings/templates/site/user/settings/_details_personal.html | HTML | bsd-3-clause | 1,630 |
/*
Copyright (c) 2000-2022, Board of Trustees of Leland Stanford Jr. University,
All rights reserved.
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 and the following disclaimer.
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 the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lockss.tdb;
import java.io.*;
import java.util.*;
import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
/**
* Temporary until a few things are in lockss-util or similar.
*/
public class TdbUtil {
// See Constants
public static final String ENCODING_UTF_8 = "UTF-8";
// See PluginManager
public static String generateAuId(String pluginId, Map<String, String> params) {
return pluginId.replace('.', '|') + "&" + propsToCanonicalEncodedString(params);
}
// See PropUtil
protected static String propsToCanonicalEncodedString(Map<String, String> params) {
if (params == null || params.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
SortedSet<String> sortedKeys = new TreeSet<String>(params.keySet());
for (Iterator<String> it = sortedKeys.iterator() ; it.hasNext() ; ) {
String key = it.next().toString();
sb.append(encode(key));
sb.append("~");
sb.append(encode(params.get(key).toString()));
if (it.hasNext()) {
sb.append("&");
}
}
return sb.toString();
}
// See PropKeyEncoder
public static String encode(String str) {
int maxBytesPerChar = 10;
StringBuffer out = new StringBuffer(str.length());
UnsynchronizedByteArrayOutputStream buf = new UnsynchronizedByteArrayOutputStream(maxBytesPerChar);
OutputStreamWriter writer = new OutputStreamWriter(buf);
for (int i = 0, len = str.length(); i < len; i++) {
int c = (int)str.charAt(i);
if (DONTNEEDENCODING.get(c)) {
if (c == ' ') {
c = '+';
}
out.append((char)c);
} else {
// convert to external encoding before hex conversion
try {
writer.write(c);
writer.flush();
} catch(IOException e) {
buf.reset();
continue;
}
byte[] ba = buf.toByteArray();
for (int j = 0; j < ba.length; j++) {
out.append('%');
char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
// converting to use uppercase letter as part of
// the hex value if ch is a letter.
if (Character.isLetter(ch)) {
ch -= CASEDIFF;
}
out.append(ch);
ch = Character.forDigit(ba[j] & 0xF, 16);
if (Character.isLetter(ch)) {
ch -= CASEDIFF;
}
out.append(ch);
}
buf.reset();
}
}
return out.toString();
}
// See PropKeyEncoder
private static BitSet DONTNEEDENCODING;
// See PropKeyEncoder
static {
DONTNEEDENCODING = new BitSet(256);
int i;
for (i = 'a'; i <= 'z'; i++) {
DONTNEEDENCODING.set(i);
}
for (i = 'A'; i <= 'Z'; i++) {
DONTNEEDENCODING.set(i);
}
for (i = '0'; i <= '9'; i++) {
DONTNEEDENCODING.set(i);
}
DONTNEEDENCODING.set(' '); /* encoding a space to a + is done in the encode() method */
DONTNEEDENCODING.set('-');
DONTNEEDENCODING.set('_');
DONTNEEDENCODING.set('*');
}
// See PropKeyEncoder
private static final int CASEDIFF = ('a' - 'A');
}
| lockss/lockss-daemon | src/org/lockss/tdb/TdbUtil.java | Java | bsd-3-clause | 4,685 |
/* Copyright 2013, Peter A. Bigot
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the software nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** @file
*
* @brief Version data and documentation for embtextf library
*
* @homepage http://github.com/pabigot/embtextf
* @copyright Copyright 2013, Peter A. Bigot. Licensed under <a href="http://www.opensource.org/licenses/BSD-3-Clause">BSD-3-Clause</a>
*/
#ifndef EMBTEXTF_VERSION_H
#define EMBTEXTF_VERSION_H
/** Version of the embtextf library. This is a monotonically
* non-decreasing integer value suitable for ordinal comparisons. */
#define EMBTEXTF_VERSION 20130609
#endif /* EMBTEXTF_VERSION_H */
| pabigot/embtextf | include/embtextf/version.h | C | bsd-3-clause | 2,088 |
<?php
/**
* Created by PhpStorm.
* User: leijiao
* Date: 16/3/10
* Time: 下午1:47
*/
//echo 'http://localhost/vcos/backend/web/index.php?r=forum/default/index';
echo '<pre>';
echo \Yii::t('app', 'Hello');
echo "<br />";
echo \Yii::t('app', '你好');
| vin120/vcos | backend/modules/controlcenter/views/default/index.php | PHP | bsd-3-clause | 259 |
import json
from django.test.utils import override_settings
import pytest
from pyquery import PyQuery
from fjord.base import views
from fjord.base.tests import (
LocalizingClient,
TestCase,
AnalyzerProfileFactory,
reverse
)
from fjord.base.views import IntentionalException
from fjord.search.tests import ElasticTestCase
class TestAbout(TestCase):
client_class = LocalizingClient
def test_about_view(self):
resp = self.client.get(reverse('about-view'))
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'about.html')
class TestLoginFailure(TestCase):
def test_login_failure_view(self):
resp = self.client.get(reverse('login-failure'))
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'login_failure.html')
resp = self.client.get(reverse('login-failure'), {'mobile': 1})
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'mobile/login_failure.html')
# Note: This needs to be an ElasticTestCase because the view does ES
# stuff.
class TestMonitorView(ElasticTestCase):
def test_monitor_view(self):
"""Tests for the monitor view."""
# TODO: When we add a mocking framework, we can mock this
# properly.
test_memcached = views.test_memcached
try:
with self.settings(
SHOW_STAGE_NOTICE=True,
CACHES={
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # noqa
'LOCATION': ['localhost:11211', 'localhost2:11211']
}
}):
# Mock the test_memcached function so it always returns
# True.
views.test_memcached = lambda host, port: True
# TODO: Replace when we get a mock library.
def mock_rabbitmq():
class MockRabbitMQ(object):
def connect(self):
return True
return lambda *a, **kw: MockRabbitMQ()
views.establish_connection = mock_rabbitmq()
# Request /services/monitor and make sure it returns
# HTTP 200 and that there aren't errors on the page.
resp = self.client.get(reverse('services-monitor'))
errors = [line for line in resp.content.splitlines()
if 'ERROR' in line]
assert resp.status_code == 200, '%s != %s (%s)' % (
resp.status_code, 200, repr(errors))
finally:
views.test_memcached = test_memcached
class TestFileNotFound(TestCase):
client_class = LocalizingClient
def test_404(self):
request = self.client.get('/a/path/that/should/never/exist')
assert request.status_code == 404
self.assertTemplateUsed(request, '404.html')
class TestServerError(TestCase):
@override_settings(SHOW_STAGE_NOTICE=True)
def test_500(self):
with pytest.raises(IntentionalException):
self.client.get('/services/throw-error')
class TestRobots(TestCase):
def test_robots(self):
resp = self.client.get('/robots.txt')
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'robots.txt')
class TestContribute(TestCase):
def test_contribute(self):
resp = self.client.get('/contribute.json')
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'contribute.json')
def test_contribute_if_valid_json(self):
resp = self.client.get('/contribute.json')
# json.loads throws a ValueError when contribute.json is invalid JSON.
json.loads(resp.content)
class TestNewUserView(ElasticTestCase):
def setUp(self):
super(TestNewUserView, self).setUp()
jane = AnalyzerProfileFactory().user
self.jane = jane
def test_redirect_to_dashboard_if_anonymous(self):
# AnonymousUser shouldn't get to the new-user-view, so make
# sure they get redirected to the dashboard.
resp = self.client.get(reverse('new-user-view'), follow=True)
assert resp.status_code == 200
self.assertTemplateNotUsed('new_user.html')
self.assertTemplateUsed('analytics/dashboard.html')
def test_default_next_url(self):
self.client_login_user(self.jane)
resp = self.client.get(reverse('new-user-view'))
assert resp.status_code == 200
self.assertTemplateUsed('new_user.html')
# Pull out next link
pq = PyQuery(resp.content)
next_url = pq('#next-url-link')
assert next_url.attr['href'] == '/en-US/' # this is the dashboard
def test_valid_next_url(self):
self.client_login_user(self.jane)
url = reverse('new-user-view')
resp = self.client.get(url, {
'next': '/ou812' # stretches the meaning of 'valid'
})
assert resp.status_code == 200
self.assertTemplateUsed('new_user.html')
# Pull out next link which is naughty, so it should have been
# replaced with a dashboard link.
pq = PyQuery(resp.content)
next_url = pq('#next-url-link')
assert next_url.attr['href'] == '/ou812'
def test_sanitized_next_url(self):
self.client_login_user(self.jane)
url = reverse('new-user-view')
resp = self.client.get(url, {
'next': 'javascript:prompt%28document.cookie%29'
})
assert resp.status_code == 200
self.assertTemplateUsed('new_user.html')
# Pull out next link which is naughty, so it should have been
# replaced with a dashboard link.
pq = PyQuery(resp.content)
next_url = pq('#next-url-link')
assert next_url.attr['href'] == '/en-US/' # this is the dashboard
| Ritsyy/fjord | fjord/base/tests/test_views.py | Python | bsd-3-clause | 5,907 |
#ifndef ML_APPLICATION_H
#define ML_APPLICATION_H
#include <QApplication>
#include <QString>
class MeshLabApplication : public QApplication
{
public:
enum HW_ARCHITECTURE {HW_32BIT = 32,HW_64BIT = 64};
MeshLabApplication(int &argc, char *argv[]):QApplication(argc,argv){}
~MeshLabApplication(){}
bool notify(QObject * rec, QEvent * ev);
static const QString appName(){return tr("MeshLab"); }
static const QString architecturalSuffix(const HW_ARCHITECTURE hw) {return "_" + QString::number(int(hw)) + "bit";}
static const QString appArchitecturalName(const HW_ARCHITECTURE hw) {return appName() + architecturalSuffix(hw);}
static const QString appVer() {return tr("1.3.3"); }
static const QString completeName(const HW_ARCHITECTURE hw){return appArchitecturalName(hw) + " v" + appVer(); }
static const QString organization(){return tr("VCG");}
static const QString organizationHost() {return tr("http://vcg.isti.cnr.it");}
static const QString webSite() {return tr("http://meshlab.sourceforge.net/");}
static const QString downloadSite() {return tr("http://downloads.sourceforge.net/project/meshlab");}
static const QString downloadUpdatesSite() {return downloadSite() + tr("/updates");}
static const QString pluginsPathRegisterKeyName() {return tr("pluginsPath");}
static const QString versionRegisterKeyName() {return tr("version");}
static const QString wordSizeKeyName() {return tr("wordSize");}
};
#endif
| hlzz/dotfiles | graphics/meshlab/src/common/mlapplication.h | C | bsd-3-clause | 1,511 |
<form id="{$form.name}" name="{$form.name}">
<style>
{literal}
.form_icon{
float:left;
padding-right:12px;
}
h2{
line-height: 28px;
font-size: 18px;
font-weight: normal;
}
.system_name
{
background-image:url({/literal}{$resource_url}{literal}/oauth/images/system_name_bg.png);
background-repeat:no-repeat;
background-position:76px 10px;
width:200px;
height:65px;
}
.system_name h2
{
float:left;
display:block;
padding-top:28px;
padding-left:15px;
font-size:20px;
width:120px;
height:30px;
overflow:hidden;
}
p.input_row
{
height:26px;
}
table.system-block{
padding-bottom:20px;
padding-left:20px;
}
table.system-block .input_row{
background-color:#efefef;
margin-bottom:2px;
}
table.system-block .input_row label
{
color:#149BC8;
line-height:24px;
height:24px;
padding-left:8px;
margin-right:0px;
margin-left:2px;
margin-top:1px;
background-color:#ffffff;
display:block;
color:#666666;
}
table.system-block .input_row span
{
display:block;
border-bottom:1px solid #eeeeee;
float:left;
width:120px;
line-height:26px;
height:24px;
overflow:hidden;
padding-left:10px;
padding-right:10px;
}
.connect-icon{
background-image:url({/literal}{$resource_url}{literal}/oauth/images/icon_connect_bg.png);
background-repeat:no-repeat;
background-position:center 70px;
width:120px;
}
{/literal}
</style>
<div class="register-block-oauth-connect oauth-connect" >
<table><tr><td>
{if $form.icon !='' }
<div class="form_icon"><img src="{$form.icon}" border="0" /></div>
{/if}
<div style="float:left; width:400px;">
{if $form.title}
<h2>
{$form.title}
</h2>
{/if}
{if $form.description}
<p class="input_row" style="line-height:20px;padding-bottom:5px;">
<span>{$form.description}</span>
</p>
{else}
<div style="height:15px;"></div>
{/if}
</div>
</td></tr></table>
<div style="height:10px;"></div>
<table class="system-block">
<tr>
<td>
<div class="system_name">
<img src="{$app_url}/images/cubi_logo_large.png" height="65" style="float:left;" />
<h2>{$smarty.const.OPENBIZ_DEFAULT_SYSTEM_NAME}</h2>
</div>
<div style="padding-top:10px;">
<p class="input_row" >
<label style="width:60px; ">{$dataPanel.fld_local_user.label}</label>
<span>{$dataPanel.fld_local_user.element}</span>
</p>
<p class="input_row" >
<label style="width:60px; ">{$dataPanel.fld_local_email.label}</label>
<span>{$dataPanel.fld_local_email.element}</span>
</p>
</div>
</td>
<td class="connect-icon"></td>
<td >
<div style="height:60px;padding-top:5px;">
<img src="{$resource_url}/oauth/images/oauth_logo_{$dataPanel.fld_oauth_data.element.type}.png" />
</div>
<div style="padding-top:10px;">
<p class="input_row" >
<label style="width:60px; ">{$dataPanel.fld_oauth_user.label}</label>
<span>{$dataPanel.fld_oauth_user.element}</span>
</p>
<p class="input_row" >
<label style="width:60px; ">{$dataPanel.fld_oauth_location.label}</label>
<span>{$dataPanel.fld_oauth_location.element}</span>
</p>
</div>
</td>
</tr>
</table>
<div style="padding-left:25px; padding-bottom:15px;">
<div id='noticeDiv' class='noticeBox' >
<div>{t}You have sucessful connected above two accounts.{/t}</div>
</div>
</div>
<p class="input_row">
<label style="width:15px; text-align:right"></label>
{foreach item=elem from=$actionPanel}
{$elem.element}
{/foreach}
</p>
</div>
{literal}<script>try{_gaq.push(['_trackEvent', "Registration","SocialConnected"]);}catch(e){};</script>{/literal}
</form> | openbizx/cubix | modules/oauth/template/user_connect_finished.tpl.html | HTML | bsd-3-clause | 3,600 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_i3wm-formula
----------------------------------
Tests for `i3wm-formula` module.
"""
import unittest
from i3wm-formula import i3wm-formula
class TestI3wm-formula(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main() | westurner/i3wm-formula | tests/test_i3wm-formula.py | Python | bsd-3-clause | 407 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/merbivore_soft', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-merbivore-soft";
exports.cssText = "\
.ace-merbivore-soft .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-merbivore-soft .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-merbivore-soft .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-merbivore-soft .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-merbivore-soft .ace_scroller {\
background-color: #1C1C1C;\
}\
\
.ace-merbivore-soft .ace_text-layer {\
cursor: text;\
color: #E6E1DC;\
}\
\
.ace-merbivore-soft .ace_cursor {\
border-left: 1px solid #FFFFFF;\
}\
\
.ace-merbivore-soft .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #FFFFFF;\
}\
\
.ace-merbivore-soft .ace_marker-layer .ace_selection {\
background: #494949;\
}\
\
.ace-merbivore-soft .ace_marker-layer .ace_step {\
background: rgb(198, 219, 174);\
}\
\
.ace-merbivore-soft .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #404040;\
}\
\
.ace-merbivore-soft .ace_marker-layer .ace_active_line {\
background: #333435;\
}\
\
.ace-merbivore-soft .ace_marker-layer .ace_selected_word {\
border: 1px solid #494949;\
}\
\
.ace-merbivore-soft .ace_invisible {\
color: #404040;\
}\
\
.ace-merbivore-soft .ace_keyword, .ace-merbivore-soft .ace_meta {\
color:#FC803A;\
}\
\
.ace-merbivore-soft .ace_constant, .ace-merbivore-soft .ace_constant.ace_other {\
color:#68C1D8;\
}\
\
.ace-merbivore-soft .ace_constant.ace_character, {\
color:#68C1D8;\
}\
\
.ace-merbivore-soft .ace_constant.ace_character.ace_escape, {\
color:#68C1D8;\
}\
\
.ace-merbivore-soft .ace_constant.ace_language {\
color:#E1C582;\
}\
\
.ace-merbivore-soft .ace_constant.ace_library {\
color:#8EC65F;\
}\
\
.ace-merbivore-soft .ace_constant.ace_numeric {\
color:#7FC578;\
}\
\
.ace-merbivore-soft .ace_invalid {\
color:#FFFFFF;\
background-color:#FE3838;\
}\
\
.ace-merbivore-soft .ace_invalid.ace_deprecated {\
color:#FFFFFF;\
background-color:#FE3838;\
}\
\
.ace-merbivore-soft .ace_support.ace_constant {\
color:#8EC65F;\
}\
\
.ace-merbivore-soft .ace_fold {\
background-color: #FC803A;\
border-color: #E6E1DC;\
}\
\
.ace-merbivore-soft .ace_storage {\
color:#FC803A;\
}\
\
.ace-merbivore-soft .ace_string {\
color:#8EC65F;\
}\
\
.ace-merbivore-soft .ace_comment {\
font-style:italic;\
color:#AC4BB8;\
}\
\
.ace-merbivore-soft .ace_meta {\
font-style:italic;\
color:#AC4BB8;\
}\
\
.ace-merbivore-soft .ace_meta.ace_tag {\
color:#FC803A;\
}\
\
.ace-merbivore-soft .ace_entity.ace_other.ace_attribute-name {\
color:#EAF1A3;\
}\
\
.ace-merbivore-soft .ace_markup.ace_underline {\
text-decoration:underline;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| r3ap3r2004/spraycan | lib/assets/javascripts/spraycan/ace/theme-merbivore_soft-uncompressed.js | JavaScript | bsd-3-clause | 4,684 |
/*
* keynav - Keyboard navigation tool.
*
* XXX: Merge 'wininfo' and 'wininfo_history'. The latest history entry is the
* same as wininfo, so use that instead.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <X11/Xlib.h>
#include <X11/XKBlib.h>
#include <X11/Xresource.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/extensions/shape.h>
#include <X11/extensions/Xinerama.h>
#include <glib.h>
#include <cairo-xlib.h>
#ifdef PROFILE_THINGS
#include <time.h>
#endif
#include <xdo.h>
#include "keynav_version.h"
#ifndef GLOBAL_CONFIG_FILE
#define GLOBAL_CONFIG_FILE "/etc/keynavrc"
#endif /* GLOBAL_CONFIG_FILE */
extern char **environ;
char **g_argv;
#define ISACTIVE (appstate.active)
#define ISDRAGGING (appstate.dragging)
struct appstate {
int active;
int dragging;
int need_draw;
int need_moveresize;
enum { record_getkey, record_ing, record_off } recording;
int playback;
int grid_nav; /* 1 if grid nav is active */
enum { GRID_NAV_COL, GRID_NAV_ROW } grid_nav_state;
enum { GRID_LABEL_NONE, GRID_LABEL_AA } grid_label;
int grid_nav_col;
int grid_nav_row;
};
typedef enum { HANDLE_CONTINUE, HANDLE_STOP } handler_info_t;
typedef struct recording {
int keycode;
GPtrArray *commands;
} recording_t;
GPtrArray *recordings;
recording_t *active_recording = NULL;
char *recordings_filename = NULL;
typedef struct wininfo {
int x;
int y;
int w;
int h;
int grid_rows;
int grid_cols;
int border_thickness;
int center_cut_size;
int curviewport;
} wininfo_t;
typedef struct mouseinfo {
int x;
int y;
} mouseinfo_t;
typedef struct viewport {
int x;
int y;
int w;
int h;
int screen_num;
Screen *screen;
Window root;
} viewport_t;
static wininfo_t wininfo;
static mouseinfo_t mouseinfo;
static viewport_t *viewports;
static int nviewports = 0;
static int xinerama = 0;
static int daemonize = 0;
static int is_daemon = False;
static Display *dpy;
static Window zone;
XRectangle *clip_rectangles = NULL;
int nclip_rectangles = 0;
static GC canvas_gc;
static Pixmap canvas;
static cairo_surface_t *canvas_surface;
static cairo_t *canvas_cairo;
static Pixmap shape;
static cairo_surface_t *shape_surface;
static cairo_t *shape_cairo;
static xdo_t *xdo;
static struct appstate appstate = {
.active = 0,
.dragging = 0,
.recording = record_off,
.grid_nav = 0,
};
static int drag_button = 0;
static char drag_modkeys[128];
/* history tracking */
#define WININFO_MAXHIST (100)
static wininfo_t wininfo_history[WININFO_MAXHIST]; /* XXX: is 100 enough? */
static int wininfo_history_cursor = 0;
void defaults();
void cmd_cell_select(char *args);
void cmd_click(char *args);
void cmd_cursorzoom(char *args);
void cmd_cut_down(char *args);
void cmd_cut_left(char *args);
void cmd_cut_right(char *args);
void cmd_cut_up(char *args);
void cmd_daemonize(char *args);
void cmd_doubleclick(char *args);
void cmd_drag(char *args);
void cmd_end(char *args);
void cmd_grid(char *args);
void cmd_grid_nav(char *args);
void cmd_history_back(char *args);
void cmd_loadconfig(char *args);
void cmd_move_down(char *args);
void cmd_move_left(char *args);
void cmd_move_right(char *args);
void cmd_move_up(char *args);
void cmd_quit(char *args);
void cmd_record(char *args);
void cmd_playback(char *args);
void cmd_restart(char *args);
void cmd_shell(char *args);
void cmd_start(char *args);
void cmd_warp(char *args);
void cmd_windowzoom(char *args);
void update();
void correct_overflow();
void handle_keypress(XKeyEvent *e);
void handle_commands(char *commands);
void parse_config();
int parse_config_line(char *line);
void save_history_point();
void restore_history_point(int moves_ago);
void cell_select(int x, int y);
handler_info_t handle_recording(XKeyEvent *e);
handler_info_t handle_gridnav(XKeyEvent *e);
void query_screens();
void query_screen_xinerama();
void query_screen_normal();
int viewport_sort(const void *a, const void *b);
int query_current_screen();
int query_current_screen_xinerama();
int query_current_screen_normal();
void viewport_left();
void viewport_right();
int pointinrect(int px, int py, int rx, int ry, int rw, int rh);
int percent_of(int num, char *args, float default_val);
void sigchld(int sig);
void sighup(int sig);
void restart();
void recordings_save(const char *filename);
void parse_recordings(const char *filename);
void openpixel(Display *dpy, Window zone, mouseinfo_t *mouseinfo);
void closepixel(Display *dpy, Window zone, mouseinfo_t *mouseinfo);
typedef struct dispatch {
char *command;
void (*func)(char *args);
} dispatch_t;
dispatch_t dispatch[] = {
"cut-up", cmd_cut_up,
"cut-down", cmd_cut_down,
"cut-left", cmd_cut_left,
"cut-right", cmd_cut_right,
"move-up", cmd_move_up,
"move-down", cmd_move_down,
"move-left", cmd_move_left,
"move-right", cmd_move_right,
"cursorzoom", cmd_cursorzoom,
"windowzoom", cmd_windowzoom,
// Grid commands
"grid", cmd_grid,
"grid-nav", cmd_grid_nav,
"cell-select", cmd_cell_select,
// Mouse activity
"warp", cmd_warp,
"click", cmd_click,
"doubleclick", cmd_doubleclick,
"drag", cmd_drag,
// Other commands.
"loadconfig", cmd_loadconfig,
"daemonize", cmd_daemonize,
"sh", cmd_shell,
"start", cmd_start,
"end", cmd_end,
"history-back", cmd_history_back,
"quit", cmd_quit,
"restart", cmd_restart,
"record", cmd_record,
"playback", cmd_playback,
NULL, NULL,
};
typedef struct keybinding {
char *commands;
int keycode;
int mods;
} keybinding_t;
GPtrArray *keybindings = NULL;
int parse_keycode(char *keyseq) {
char *tokctx;
char *strptr;
char *tok;
char *last_tok;
char *dup;
int keycode = 0;
int keysym = 0;
strptr = dup = strdup(keyseq);
//printf("finding keycode for %s\n", keyseq);
while ((tok = strtok_r(strptr, "+", &tokctx)) != NULL) {
last_tok = tok;
strptr = NULL;
}
keysym = XStringToKeysym(last_tok);
if (keysym == NoSymbol) {
fprintf(stderr, "No keysym found for '%s' in sequence '%s'\n",
last_tok, keyseq);
/* At this point, we'll be returning 0 for keycode */
} else {
/* Valid keysym */
keycode = XKeysymToKeycode(dpy, keysym);
if (keycode == 0) {
fprintf(stderr, "Unable to lookup keycode for %s\n", last_tok);
}
}
free(dup);
return keycode;
}
int parse_mods(char *keyseq) {
char *tokctx;
char *strptr;
char *tok;
char *last_tok;
char *dup;
GPtrArray *mods;
int modmask = 0;
mods = g_ptr_array_new();
strptr = dup = strdup(keyseq);
while ((tok = strtok_r(strptr, "+", &tokctx)) != NULL) {
strptr = NULL;
g_ptr_array_add(mods, tok);
}
int i = 0;
/* Use all but the last token as modifiers */
const char **symbol_map = xdo_get_symbol_map();
for (i = 0; i < mods->len; i++) {
KeySym keysym = 0;
int j = 0;
const char *mod = g_ptr_array_index(mods, i);
for (j = 0; symbol_map[j] != NULL; j+=2) {
if (!strcasecmp(mod, symbol_map[j])) {
mod = symbol_map[j + 1];
}
}
keysym = XStringToKeysym(mod);
//printf("%s => %d\n", mod, keysym);
if ((keysym == XK_Shift_L) || (keysym == XK_Shift_R))
modmask |= ShiftMask;
if ((keysym == XK_Control_L) || (keysym == XK_Control_R))
modmask |= ControlMask;
if ((keysym == XK_Alt_L) || (keysym == XK_Alt_R))
modmask |= Mod1Mask;
if ((keysym == XK_Super_L) || (keysym == XK_Super_R)
|| (keysym == XK_Hyper_L) || (keysym == XK_Hyper_R))
modmask |= Mod4Mask;
/* 'xmodmap' will output the current modN:KeySym mappings */
}
free(dup);
g_ptr_array_free(mods, FALSE);
return modmask;
}
void addbinding(int keycode, int mods, char *commands) {
int i;
// Check if we already have a binding for this, if so, override it.
for (i = 0; i < keybindings->len; i++) {
keybinding_t *kbt = g_ptr_array_index(keybindings, i);
if (kbt->keycode == keycode && kbt->mods == mods) {
free(kbt->commands);
kbt->commands = strdup(commands);
return;
}
}
keybinding_t *keybinding = NULL;
keybinding = calloc(sizeof(keybinding_t), 1);
keybinding->commands = strdup(commands);
keybinding->keycode = keycode;
keybinding->mods = mods;
g_ptr_array_add(keybindings, keybinding);
if (!strncmp(commands, "start", 5)) {
int i = 0;
/* Grab on all screen root windows */
for (i = 0; i < ScreenCount(dpy); i++) {
Window root = RootWindow(dpy, i);
XGrabKey(dpy, keycode, mods, root, False, GrabModeAsync, GrabModeAsync);
XGrabKey(dpy, keycode, mods | LockMask, root, False, GrabModeAsync, GrabModeAsync);
XGrabKey(dpy, keycode, mods | Mod2Mask, root, False, GrabModeAsync, GrabModeAsync);
XGrabKey(dpy, keycode, mods | LockMask | Mod2Mask, root, False, GrabModeAsync, GrabModeAsync);
}
}
if (!strncmp(commands, "record", 6)) {
char *path = commands + 6;
char *newrecordingpath;
while (isspace(*path))
path++;
/* If args is nonempty, try to use it as the file to store recordings in */
if (path != NULL && path[0] != '\0') {
/* Handle ~/ swapping in for actual homedir */
if (!strncmp(path, "~/", 2)) {
asprintf(&newrecordingpath, "%s/%s", getenv("HOME"), path + 2);
} else {
newrecordingpath = strdup(path);
}
/* Fail if we try to set the record file to another name than we set
* previously */
if (recordings_filename != NULL
&& strcmp(recordings_filename, newrecordingpath)) {
free(newrecordingpath);
fprintf(stderr,
"Recordings file already set to '%s', you tried to\n"
"set it to '%s'. Keeping original value.\n",
recordings_filename, path);
} else {
recordings_filename = newrecordingpath;
parse_recordings(recordings_filename);
}
}
} /* special config handling for 'record' */
}
void parse_config_file(const char* file) {
FILE *fp = NULL;
#define LINEBUF_SIZE 512
char line[LINEBUF_SIZE];
int lineno = 0;
if (file[0] == '~') {
const char *homedir = getenv("HOME");
if (homedir != NULL) {
char *rcfile = NULL;
asprintf(&rcfile, "%s/%s", homedir, file + 1 /* skip first char '~' */);
parse_config_file(rcfile);
free(rcfile);
return;
} else {
fprintf(stderr,
"No HOME set in environment. Can't expand '%s' (fatal error)\n",
file);
/* This is fatal. */
exit(1);
}
} /* if file[0] == '~' */
fp = fopen(file, "r");
/* Silently ignore file read errors */
if (fp == NULL) {
//fprintf(stderr, "Error trying to open file for read '%s'\n", file);
//perror("Error");
return;
}
/* fopen succeeded */
while (fgets(line, LINEBUF_SIZE, fp) != NULL) {
lineno++;
/* Kill the newline */
*(line + strlen(line) - 1) = '\0';
if (parse_config_line(line) != 0) {
fprintf(stderr, "Error with config %s:%d: %s\n", file, lineno, line);
}
}
fclose(fp);
}
void parse_config() {
char *homedir;
keybindings = g_ptr_array_new();
recordings = g_ptr_array_new();
defaults();
parse_config_file(GLOBAL_CONFIG_FILE);
parse_config_file("~/.keynavrc");
}
void defaults() {
char *tmp;
int i;
char *default_config[] = {
"clear",
"ctrl+semicolon start",
"Escape end",
"ctrl+bracketleft end", /* for vi people who use ^[ */
"q record ~/.keynav_macros",
"shift+at playback",
"a history-back",
"h cut-left",
"j cut-down",
"k cut-up",
"l cut-right",
"shift+h move-left",
"shift+j move-down",
"shift+k move-up",
"shift+l move-right",
"space warp,click 1,end",
"Return warp,click 1,end",
"semicolon warp,end",
"w warp",
"t windowzoom",
"c cursorzoom 300 300",
"e end",
"1 click 1",
"2 click 2",
"3 click 3",
"ctrl+h cut-left",
"ctrl+j cut-down",
"ctrl+k cut-up",
"ctrl+l cut-right",
"y cut-left,cut-up",
"u cut-right,cut-up",
"b cut-left,cut-down",
"n cut-right,cut-down",
"shift+y move-left,move-up",
"shift+u move-right,move-up",
"shift+b move-left,move-down",
"shift+n move-right,move-down",
"ctrl+y cut-left,cut-up",
"ctrl+u cut-right,cut-up",
"ctrl+b cut-left,cut-down",
"ctrl+n cut-right,cut-down",
NULL,
};
for (i = 0; default_config[i]; i++) {
tmp = strdup(default_config[i]);
if (parse_config_line(tmp) != 0) {
fprintf(stderr, "Error with default config line %d: %s\n", i + 1, tmp);
}
free(tmp);
}
}
int parse_config_line(char *orig_line) {
/* syntax:
* keysequence cmd1,cmd2,cmd3
*
* ex:
* ctrl+semicolon start
* space warp
* semicolon warp,click
*/
char *line = strdup(orig_line);
char *tokctx;
char *keyseq;
int keycode, mods;
char *comment;
/* Ignore everything after a '#' */
comment = strchr(line, '#');
if (comment != NULL)
*comment = '\0';
/* Ignore leading whitespace */
while (isspace(*line))
line++;
/* Ignore empty lines */
if (*line == '\n' || *line == '\0')
return 0;
tokctx = line;
keyseq = strdup(strtok_r(line, " ", &tokctx));
/* A special config option that will clear all keybindings */
if (strcmp(keyseq, "clear") == 0) {
/* TODO(sissel): Make this a cmd_clear function */
/* Reset keybindings */
g_ptr_array_free(keybindings, TRUE);
keybindings = g_ptr_array_new();
} else if (strcmp(keyseq, "daemonize") == 0) {
handle_commands(keyseq);
} else if (strcmp(keyseq, "loadconfig") == 0) {
handle_commands(keyseq);
} else {
keycode = parse_keycode(keyseq);
if (keycode == 0) {
fprintf(stderr, "Problem parsing keysequence '%s'\n", keyseq);
return 1;
}
mods = parse_mods(keyseq);
/* FreeBSD sets 'tokctx' to NULL at end of string.
* glibc sets 'tokctx' to the next character (the '\0')
* Reported by Richard Kolkovich */
if (tokctx == NULL || *tokctx == '\0') {
fprintf(stderr, "Incomplete configuration line. Missing commands: '%s'\n", line);
return 1;
}
addbinding(keycode, mods, tokctx /* the remainder of the line */);
}
free(keyseq);
free(line);
return 0;
}
int percent_of(int num, char *args, float default_val) {
static float precision = 100000.0;
float pct = 0.0;
int value = 0;
/* Parse a float. If this fails, assume the default value */
if (sscanf(args, "%f", &pct) <= 0)
pct = default_val;
/* > 1, then it's not a percent, it's an absolute value. */
if (pct > 1.0)
return (int)pct;
value = (int)((num * (pct * precision)) / precision);
return value;
}
void updatecliprects(wininfo_t *info, XRectangle **rectangles, int *nrects) {
int rects = (info->grid_cols + 1) + (info->grid_rows + 1) /* grid lines */
+ (info->grid_cols * info->grid_rows); /* grid text boxes */
if (rects != nclip_rectangles) {
nclip_rectangles = rects;
clip_rectangles = realloc(clip_rectangles, nclip_rectangles * sizeof(XRectangle));
}
}
void updategrid(Window win, struct wininfo *info, int apply_clip, int draw) {
double w = info->w;
double h = info->h;
double cell_width;
double cell_height;
int i;
int rect = 0;
if (apply_clip) {
updatecliprects(info, &clip_rectangles, &nclip_rectangles);
memset(clip_rectangles, 0, nclip_rectangles * sizeof(XRectangle));
}
#ifdef PROFILE_THINGS
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
if (w <= 4 || h <= 4) {
cairo_new_path(canvas_cairo);
cairo_fill(canvas_cairo);
return;
}
//printf("updategrid: clip:%d, draw:%d\n", apply_clip, draw);
if (draw) {
cairo_new_path(canvas_cairo);
cairo_set_source_rgb(canvas_cairo, 1, 1, 1);
cairo_rectangle(canvas_cairo, 0, 0, w, h);
cairo_set_line_width(canvas_cairo, wininfo.border_thickness);
cairo_fill(canvas_cairo);
}
cell_width = (w / info->grid_cols);
cell_height = (h / info->grid_rows);
int x_total_offset = 0;
/* clip vertically */
for (i = 0; i <= info->grid_cols; i++) {
int x_off = 0;
if (i > 0) {
x_off = -info->border_thickness / 2;
}
if (i == info->grid_cols) {
x_total_offset = info->w - 1;
}
int x_w_off = 0;
if (i == 0 || i == info->grid_cols) {
x_w_off = info->border_thickness / 2;
}
cairo_move_to(canvas_cairo, x_total_offset + 1, 0);
cairo_line_to(canvas_cairo, x_total_offset + 1, info->h);
clip_rectangles[rect].x = x_total_offset + x_off;
clip_rectangles[rect].y = 0;
clip_rectangles[rect].width = info->border_thickness - x_w_off;
clip_rectangles[rect].height = info->h;
rect++;
x_total_offset += cell_width;
}
int y_total_offset = 0;
/* clip horizontally */
for (i = 0; i <= info->grid_rows; i++) {
int y_off = 0;
if (i > 0) {
y_off = -info->border_thickness / 2;
}
if (i == info->grid_rows) {
y_total_offset = info->h - 1;
}
int y_w_off = 0;
if (i == 0 || i == info->grid_rows) {
y_w_off = info->border_thickness / 2;
}
cairo_move_to(canvas_cairo, 0, y_total_offset + 1);
cairo_line_to(canvas_cairo, info->w, y_total_offset + 1);
clip_rectangles[rect].x = 0;
clip_rectangles[rect].y = y_total_offset + y_off;
clip_rectangles[rect].width = info->w;
clip_rectangles[rect].height = info->border_thickness - y_w_off;
rect++;
y_total_offset += cell_height;
}
cairo_path_t *path = cairo_copy_path(canvas_cairo);
#ifdef PROFILE_THINGS
clock_gettime(CLOCK_MONOTONIC, &end);
printf("updategrid pathbuild time: %ld.%09ld\n",
end.tv_sec - start.tv_sec,
end.tv_nsec - start.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
if (draw) {
cairo_set_source_rgba(canvas_cairo, 0, 0, 0, 1.0);
cairo_set_line_width(canvas_cairo, 1);
cairo_stroke(canvas_cairo);
#ifdef PROFILE_THINGS
XSync(dpy, False);
clock_gettime(CLOCK_MONOTONIC, &end);
printf("updategrid draw time: %ld.%09ld\n",
end.tv_sec - start.tv_sec,
end.tv_nsec - start.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
} /* if draw */
cairo_path_destroy(path);
}
void updategridtext(Window win, struct wininfo *info, int apply_clip, int draw) {
double w = info->w;
double h = info->h;
double cell_width;
double cell_height;
double x_off, y_off;
int row, col;
int rect = (info->grid_cols + 1 + info->grid_rows + 1); /* start at end of grid lines */
x_off = info->border_thickness / 2;
y_off = info->border_thickness / 2;
cairo_text_extents_t te;
#define FONTSIZE 18
if (draw) {
cairo_new_path(canvas_cairo);
cairo_select_font_face(canvas_cairo, "Courier", CAIRO_FONT_SLANT_NORMAL,
CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(canvas_cairo, FONTSIZE);
cairo_text_extents(canvas_cairo, "AA", &te);
}
w -= info->border_thickness;
h -= info->border_thickness;
cell_width = (w / info->grid_cols);
cell_height = (h / info->grid_rows);
h++;
w++;
//printf("bearing: %f,%f\n", te.x_bearing, te.y_bearing);
//printf("size: %f,%f\n", te.width, te.height);
char label[3] = "AA";
int row_selected = 0;
for (col = 0; col < info->grid_cols; col++) {
label[0] = 'A';
for (row = 0; row < info->grid_rows; row++) {
int rectwidth = te.width + 25;
int rectheight = te.height + 8;
int xpos = cell_width * col + x_off + (cell_width / 2);
int ypos = cell_height * row + y_off + (cell_height / 2);
row_selected = (appstate.grid_nav && appstate.grid_nav_row == row
&& appstate.grid_nav_state == GRID_NAV_COL);
//printf("Grid: %c%c\n", label[0], label[1]);
/* If the current column is the one selected by grid nav, use
* a different color */
//printf("Grid geom: %fx%f @ %d,%d\n",
//xpos - rectwidth / 2 + te.x_bearing / 2,
//ypos - rectheight / 2 + te.y_bearing / 2,
//rectwidth, rectheight);
cairo_rectangle(canvas_cairo,
xpos - rectwidth / 2 + te.x_bearing / 2,
ypos - rectheight / 2 + te.y_bearing / 2,
rectwidth, rectheight);
if (draw) {
cairo_path_t *pathcopy;
pathcopy = cairo_copy_path(canvas_cairo);
cairo_set_line_width(shape_cairo, 2);
if (row_selected) {
cairo_set_source_rgb(canvas_cairo, 0, .3, .3);
} else {
cairo_set_source_rgb(canvas_cairo, 0, .2, 0);
}
cairo_fill(canvas_cairo);
cairo_append_path(canvas_cairo, pathcopy);
cairo_set_source_rgb(canvas_cairo, .8, .8, 0);
cairo_stroke(canvas_cairo);
cairo_path_destroy(pathcopy);
if (row_selected) {
cairo_set_source_rgb(canvas_cairo, 1, 1, 1);
} else {
cairo_set_source_rgb(canvas_cairo, .8, .8, .8);
}
cairo_fill(canvas_cairo);
cairo_move_to(canvas_cairo, xpos - te.width / 2, ypos);
cairo_show_text(canvas_cairo, label);
}
if (apply_clip) {
clip_rectangles[rect].x = xpos - rectwidth / 2 + te.x_bearing / 2;
clip_rectangles[rect].y = ypos - rectheight / 2 + te.y_bearing / 2;
clip_rectangles[rect].width = rectwidth + 1;
clip_rectangles[rect].height = rectheight + 1;
rect++;
}
label[0]++;
}
label[1]++;
} /* Draw rectangles and text */
} /* void updategridtext */
void cmd_start(char *args) {
XSetWindowAttributes winattr;
int i;
int screen;
screen = query_current_screen();
wininfo.curviewport = screen;
appstate.grid_nav_row = -1;
appstate.grid_nav_col = -1;
wininfo.x = viewports[wininfo.curviewport].x;
wininfo.y = viewports[wininfo.curviewport].y;
wininfo.w = viewports[wininfo.curviewport].w;
wininfo.h = viewports[wininfo.curviewport].h;
/* Default start with 4 cells, 2x2 */
wininfo.grid_rows = 2;
wininfo.grid_cols = 2;
wininfo.border_thickness = 3;
wininfo.center_cut_size = 3;
if (ISACTIVE)
return;
int depth;
int grabstate;
int grabtries = 0;
/* This loop is to work around the following scenario:
* xbindkeys invokes XGrabKeyboard when you press a bound keystroke and
* doesn't Ungrab until you release a key.
* Example: (xbindkey '(Control semicolon) "keynav 'start, grid 2x2'")
* This will only invoke XUngrabKeyboard when you release 'semicolon'
*
* The problem is that keynav would be launched as soon as the keydown
* event 'control + semicolon' occurs, but we could only get the grab on
* the release.
*
* This sleepyloop will keep trying to grab the keyboard until it succeeds.
*
* Reported by Colin Shea
*/
grabstate = XGrabKeyboard(dpy, viewports[wininfo.curviewport].root, False,
GrabModeAsync, GrabModeAsync, CurrentTime);
while (grabstate != GrabSuccess) {
usleep(10000); /* sleep for 10ms */
grabstate = XGrabKeyboard(dpy, viewports[wininfo.curviewport].root, False,
GrabModeAsync, GrabModeAsync, CurrentTime);
grabtries += 1;
if (grabtries >= 20) {
fprintf(stderr, "XGrabKeyboard failed %d times, giving up...\n",
grabtries);
/* Returning from here will result in the appstate.active still
* being false. */
return;
}
}
//printf("Got grab!\n");
appstate.active = True;
appstate.need_draw = 1;
appstate.need_moveresize = 1;
if (zone == 0) { /* Create our window for the first time */
viewport_t *viewport = &(viewports[wininfo.curviewport]);
depth = viewports[wininfo.curviewport].screen->root_depth;
wininfo_history_cursor = 0;
zone = XCreateSimpleWindow(dpy, viewport->root,
wininfo.x, wininfo.y, wininfo.w, wininfo.h, 0, 0, 0);
xdo_set_window_class(xdo, zone, "keynav", "keynav");
canvas_gc = XCreateGC(dpy, zone, 0, NULL);
canvas = XCreatePixmap(dpy, zone, viewport->w, viewport->h,
viewport->screen->root_depth);
canvas_surface = cairo_xlib_surface_create(dpy, canvas,
viewport->screen->root_visual,
viewport->w, viewport->h);
canvas_cairo = cairo_create(canvas_surface);
cairo_set_antialias(canvas_cairo, CAIRO_ANTIALIAS_NONE);
cairo_set_line_cap(canvas_cairo, CAIRO_LINE_CAP_SQUARE);
shape = XCreatePixmap(dpy, zone, viewport->w, viewport->h, 1);
shape_surface = cairo_xlib_surface_create_for_bitmap(dpy, shape,
viewport->screen,
viewport->w,
viewport->h);
shape_cairo = cairo_create(shape_surface);
cairo_set_line_width(shape_cairo, wininfo.border_thickness);
cairo_set_antialias(canvas_cairo, CAIRO_ANTIALIAS_NONE);
cairo_set_line_cap(shape_cairo, CAIRO_LINE_CAP_SQUARE);
/* Tell the window manager not to manage us */
winattr.override_redirect = 1;
XChangeWindowAttributes(dpy, zone, CWOverrideRedirect, &winattr);
XSelectInput(dpy, zone, StructureNotifyMask | ExposureMask
| PointerMotionMask | LeaveWindowMask );
} /* if zone == 0 */
}
void cmd_end(char *args) {
if (!ISACTIVE)
return;
/* kill drag state too */
if (ISDRAGGING)
cmd_drag(NULL);
/* Stop recording if we're in that mode */
if (appstate.recording != record_off) {
cmd_record(NULL);
}
appstate.active = False;
XUnmapWindow(dpy, zone);
XDestroyWindow(dpy, zone);
XUngrabKeyboard(dpy, CurrentTime);
zone = 0;
}
void cmd_history_back(char *args) {
if (!ISACTIVE)
return;
restore_history_point(1);
}
void cmd_loadconfig(char *args) {
// Trim leading and trailing quotes if they exist
if (*args == '"') {
args++;
*(args + strlen(args) - 1) = '\0';
}
parse_config_file(args);
}
void cmd_shell(char *args) {
// Trim leading and trailing quotes if they exist
if (*args == '"') {
args++;
*(args + strlen(args) - 1) = '\0';
}
if (fork() == 0) { /* child */
int ret;
char *const shell = "/bin/sh";
char *const argv[4] = { shell, "-c", args, NULL };
//printf("Exec: %s\n", args);
//printf("Shell: %s\n", shell);
ret = execvp(shell, argv);
perror("execve");
exit(1);
}
}
void cmd_quit(char *args) {
exit(0);
}
void cmd_restart(char *args) {
restart();
}
void cmd_cut_up(char *args) {
if (!ISACTIVE)
return;
wininfo.h = percent_of(wininfo.h, args, .5);
}
void cmd_cut_down(char *args) {
if (!ISACTIVE)
return;
int orig = wininfo.h;
wininfo.h = percent_of(wininfo.h, args, .5);
wininfo.y += orig - wininfo.h;
}
void cmd_cut_left(char *args) {
if (!ISACTIVE)
return;
wininfo.w = percent_of(wininfo.w, args, .5);
}
void cmd_cut_right(char *args) {
int orig = wininfo.w;
if (!ISACTIVE)
return;
wininfo.w = percent_of(wininfo.w, args, .5);
wininfo.x += orig - wininfo.w;
}
void cmd_move_up(char *args) {
if (!ISACTIVE)
return;
wininfo.y -= percent_of(wininfo.h, args, 1);
}
void cmd_move_down(char *args) {
if (!ISACTIVE)
return;
wininfo.y += percent_of(wininfo.h, args, 1);
}
void cmd_move_left(char *args) {
if (!ISACTIVE)
return;
wininfo.x -= percent_of(wininfo.w, args, 1);
}
void cmd_move_right(char *args) {
if (!ISACTIVE)
return;
wininfo.x += percent_of(wininfo.w, args, 1);
}
void cmd_cursorzoom(char *args) {
int xradius = 0, yradius = 0, width = 0, height = 0;
int xloc, yloc;
if (!ISACTIVE)
return;
int count = sscanf(args, "%d %d", &width, &height);
if (count == 0) {
fprintf(stderr,
"Invalid usage of 'cursorzoom' (expected at least 1 argument)\n");
} else if (count == 1) {
/* If only one argument, assume we want a square. */
height = width;
}
xdo_get_mouse_location(xdo, &xloc, &yloc, NULL);
wininfo.x = xloc - (width / 2);
wininfo.y = yloc - (height / 2);
wininfo.w = width;
wininfo.h = height;
}
void cmd_windowzoom(char *args) {
Window curwin;
Window rootwin;
Window dummy_win;
int x, y;
unsigned int width, height, border_width, depth;
xdo_get_active_window(xdo, &curwin);
XGetGeometry(xdo->xdpy, curwin, &rootwin, &x, &y, &width, &height,
&border_width, &depth);
XTranslateCoordinates(xdo->xdpy, curwin, rootwin,
-border_width, -border_width, &x, &y, &dummy_win);
wininfo.x = x;
wininfo.y = y;
wininfo.w = width;
wininfo.h = height;
}
void cmd_warp(char *args) {
if (!ISACTIVE)
return;
int x, y;
x = wininfo.x + wininfo.w / 2;
y = wininfo.y + wininfo.h / 2;
if (mouseinfo.x != -1 && mouseinfo.y != -1) {
closepixel(dpy, zone, &mouseinfo);
}
/* Open pixels hould be relative to the window coordinates,
* not screen coordinates. */
mouseinfo.x = x - wininfo.x;
mouseinfo.y = y - wininfo.y;
openpixel(dpy, zone, &mouseinfo);
xdo_move_mouse(xdo, x, y, viewports[wininfo.curviewport].screen_num);
xdo_wait_for_mouse_move_to(xdo, x, y);
/* TODO(sissel): do we need to open again? */
openpixel(dpy, zone, &mouseinfo);
}
void cmd_click(char *args) {
if (!ISACTIVE)
return;
int button;
button = atoi(args);
if (button > 0)
xdo_click_window(xdo, CURRENTWINDOW, button);
else
fprintf(stderr, "Negative mouse button is invalid: %d\n", button);
}
void cmd_doubleclick(char *args) {
if (!ISACTIVE)
return;
cmd_click(args);
cmd_click(args);
}
void cmd_drag(char *args) {
if (!ISACTIVE)
return;
int button;
if (args == NULL) {
button = drag_button;
} else {
int count = sscanf(args, "%d %127s", &button, drag_modkeys);
if (count == 0) {
button = 1; /* Default to left mouse button */
drag_modkeys[0] = '\0';
} else if (count == 1) {
drag_modkeys[0] = '\0';
}
}
if (button <= 0) {
fprintf(stderr, "Negative or no mouse button given. Not valid. Button read was '%d'\n", button);
return;
}
drag_button = button;
if (ISDRAGGING) { /* End dragging */
appstate.dragging = False;
xdo_mouse_up(xdo, CURRENTWINDOW, button);
} else { /* Start dragging */
cmd_warp(NULL);
appstate.dragging = True;
xdo_send_keysequence_window_down(xdo, 0, drag_modkeys, 12000);
xdo_mouse_down(xdo, CURRENTWINDOW, button);
/* Sometimes we need to move a little to tell the app we're dragging */
/* TODO(sissel): Make this a 'mousewiggle' command */
xdo_move_mouse_relative(xdo, 1, 0);
xdo_move_mouse_relative(xdo, -1, 0);
XSync(xdo->xdpy, 0);
xdo_send_keysequence_window_up(xdo, 0, drag_modkeys, 12000);
}
}
void cmd_grid_nav(char *args) {
if (!strcmp("on", args)) {
appstate.grid_label = GRID_LABEL_AA;
} else if (!strcmp("off", args)) {
appstate.grid_label = GRID_LABEL_NONE;
} else if (!strcmp("toggle", args)) {
if (appstate.grid_label == GRID_LABEL_NONE) {
appstate.grid_label = GRID_LABEL_AA;
} else {
appstate.grid_label = GRID_LABEL_NONE;
}
}
/* Set state grid_nav if grid_label is anything but NONE */
if (appstate.grid_label == GRID_LABEL_NONE) {
appstate.grid_nav = 0;
} else {
appstate.grid_nav = 1;
appstate.grid_nav_state = GRID_NAV_ROW;
}
appstate.need_draw = 1;
}
void cmd_grid(char *args) {
int grid_cols, grid_rows;
// Try to parse 'NxN' where N is a number.
if (sscanf(args, "%dx%d", &grid_cols, &grid_rows) <= 0) {
// Otherwise, try parsing a number.
grid_cols = grid_rows = atoi(args);
}
if (grid_cols <= 0 || grid_rows <= 0) {
fprintf(stderr, "Invalid grid segmentation: %dx%d\n", grid_cols, grid_rows);
fprintf(stderr, "Grid x and y must both be greater than 0.\n");
return;
}
wininfo.grid_cols = grid_cols;
wininfo.grid_rows = grid_rows;
}
void cmd_cell_select(char *args) {
int row, col, z;
int cell_width, cell_height;
row = col = z = 0;
// Try to parse 'NxM' where N and M are a number.
if (sscanf(args, "%dx%d", &col, &row) < 2) {
// Otherwise, try parsing just number.
z = atoi(args);
}
// if z > 0, then this means we said "cell-select N"
if (z > 0) {
double dx = (double)z / (double)wininfo.grid_rows;
col = (z / wininfo.grid_rows);
if ( (double)col != dx ) {
col++;
}
row = (z % wininfo.grid_rows);
if ( 0 == row ) {
row = wininfo.grid_rows;
}
}
if (col <= 0 && row <= 0) {
fprintf(stderr, "Cell number cannot be zero or negative. I was given"
"columns=%d and rows=%d\n", col, row);
return;
}
if (col > wininfo.grid_cols && row > wininfo.grid_rows) {
fprintf(stderr, "The active grid is %dx%d, and you selected %dx%d which "
"does not exist.\n", wininfo.grid_cols, wininfo.grid_rows, col, row);
return;
}
// else, then we said cell-select NxM
// cell_selection is 0-based, so subtract 1.
cell_select(col - 1, row - 1);
}
void cell_select(int col, int row) {
//printf("cell_select: %d, %d\n", col, row);
wininfo.w = wininfo.w / wininfo.grid_cols;
wininfo.h = wininfo.h / wininfo.grid_rows;
wininfo.x = wininfo.x + (wininfo.w * (col));
wininfo.y = wininfo.y + (wininfo.h * (row));
}
void cmd_daemonize(char *args) {
if (!is_daemon) {
daemonize = 1;
}
}
void cmd_playback(char *args) {
appstate.playback = 1;
}
void cmd_record(char *args) {
char *filename;
if (!ISACTIVE)
return;
if (appstate.recording != record_off) {
appstate.recording = record_off;
g_ptr_array_add(recordings, (gpointer) active_recording);
/* Save to file */
if (recordings_filename != NULL) {
recordings_save(recordings_filename);
}
} else {
active_recording = calloc(sizeof(recording_t), 1);
active_recording->commands = g_ptr_array_new();
appstate.recording = record_getkey;
}
}
void update() {
if (!ISACTIVE)
return;
/* Fix keynav window boundaries if they exceed the screen */
correct_overflow();
if (wininfo.w <= 1 || wininfo.h <= 1) {
cmd_end(NULL);
return;
}
wininfo_t *previous = &(wininfo_history[wininfo_history_cursor - 1]);
//printf("window: %d,%d @ %d,%d\n", wininfo.w, wininfo.h, wininfo.x, wininfo.y);
//printf("previous: %d,%d @ %d,%d\n", previous->w, previous->h, previous->x, previous->y);
int draw = 0, move = 0, resize = 0, clip = 0;
if (previous->x != wininfo.x || previous->y != wininfo.y) {
move = 1;
}
if (previous->w != wininfo.w || previous->h != wininfo.h) {
clip = 1;
draw = 1;
resize = 1;
}
if (appstate.need_draw) {
clip = 1;
draw = 1;
appstate.need_draw = 0;
}
if (appstate.need_moveresize) {
move = 1;
resize = 1;
appstate.need_moveresize = 0;
}
//printf("move: %d, clip: %d, draw: %d, resize: %d\n", move, clip, draw, resize);
//clip = 0;
if (((clip || draw) + (move || resize)) > 1) {
/* more than one action to perform, unmap to hide move/draws
* to reduce flickering */
XUnmapWindow(dpy, zone);
}
if (clip || draw) {
updategrid(zone, &wininfo, clip, draw);
if (appstate.grid_label != GRID_LABEL_NONE) {
updategridtext(zone, &wininfo, clip, draw);
}
if (draw) {
XCopyArea(dpy, canvas, zone, canvas_gc, 0, 0, wininfo.w, wininfo.h, 0, 0);
}
if (clip) {
XShapeCombineRectangles(dpy, zone, ShapeBounding, 0, 0,
clip_rectangles, nclip_rectangles, ShapeSet, 0);
}
}
if (resize && move) {
//printf("=> %ld: %dx%d @ %d,%d\n", zone, wininfo.w, wininfo.h, wininfo.x,
//wininfo.y);
XMoveResizeWindow(dpy, zone, wininfo.x, wininfo.y, wininfo.w, wininfo.h);
/* Under Gnome3/GnomeShell, it seems to ignore this move+resize request
* unless we sync and sleep here. Sigh. Gnome is retarded. */
//XSync(dpy, 0);
//usleep(5000);
} else if (resize) {
XResizeWindow(dpy, zone, wininfo.w, wininfo.h);
} else if (move) {
XMoveWindow(dpy, zone, wininfo.x, wininfo.y);
}
XMapRaised(dpy, zone);
}
void correct_overflow() {
/* If the window is outside the boundaries of the screen, bump it back
* or, if possible, move it to the next screen */
if (wininfo.x < viewports[wininfo.curviewport].x)
viewport_left();
if (wininfo.x + wininfo.w >
viewports[wininfo.curviewport].x + viewports[wininfo.curviewport].w)
viewport_right();
/* Fix positioning if we went out of bounds (off the screen) */
if (wininfo.x < 0) {
wininfo.x = 0;
}
if (wininfo.x + wininfo.w >
viewports[wininfo.curviewport].x + viewports[wininfo.curviewport].w)
wininfo.x = viewports[wininfo.curviewport].x + viewports[wininfo.curviewport].w - wininfo.w;
/* XXX: We don't currently understand how to move around if displays are
* vertically stacked. */
if (wininfo.y < 0)
wininfo.y = 0;
if (wininfo.y + wininfo.h >
viewports[wininfo.curviewport].y + viewports[wininfo.curviewport].h)
wininfo.y = viewports[wininfo.curviewport].h - wininfo.h;
}
void viewport_right() {
int expand_w = 0, expand_h = 0;
/* Expand if the current window is the size of the current viewport */
//printf("right %d] %d,%d vs %d,%d\n", wininfo.curviewport,
//wininfo.w, wininfo.h,
//viewports[wininfo.curviewport].w, viewports[wininfo.curviewport].h);
if (wininfo.curviewport == nviewports - 1)
return;
if (wininfo.w == viewports[wininfo.curviewport].w)
expand_w = 1;
if (wininfo.h == viewports[wininfo.curviewport].h) {
expand_h = 1;
}
wininfo.curviewport++;
if ((expand_w) || wininfo.w > viewports[wininfo.curviewport].w) {
wininfo.w = viewports[wininfo.curviewport].w;
}
if ((expand_h) || wininfo.h > viewports[wininfo.curviewport].h) {
wininfo.h = viewports[wininfo.curviewport].h;
}
wininfo.x = viewports[wininfo.curviewport].x;
}
void viewport_left() {
int expand_w = 0, expand_h = 0;
/* Expand if the current window is the size of the current viewport */
//printf("left %d] %d,%d vs %d,%d\n", wininfo.curviewport,
//wininfo.w, wininfo.h,
//viewports[wininfo.curviewport].w, viewports[wininfo.curviewport].h);
if (wininfo.curviewport == 0)
return;
if (wininfo.w == viewports[wininfo.curviewport].w)
expand_w = 1;
if (wininfo.h == viewports[wininfo.curviewport].h) {
expand_h = 1;
}
wininfo.curviewport--;
if (expand_w || wininfo.w > viewports[wininfo.curviewport].w) {
wininfo.w = viewports[wininfo.curviewport].w;
}
if (expand_h || wininfo.h > viewports[wininfo.curviewport].h) {
wininfo.h = viewports[wininfo.curviewport].h;
}
wininfo.x = viewports[wininfo.curviewport].w - wininfo.w;
}
void handle_keypress(XKeyEvent *e) {
int i;
/* If a mouse button is pressed (like, when we're dragging),
* then the 'mods' will include values like Button1Mask.
* Let's remove those, as they cause breakage */
e->state &= ~(Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask);
/* Ignore LockMask (Numlock, etc) and Mod2Mask (shift, etc) */
e->state &= ~(LockMask | Mod2Mask);
/* Ignore different keyboard layouts (e.g. russian) */
e->state &= ~(1<<13);
if (appstate.recording == record_getkey) {
if (handle_recording(e) == HANDLE_STOP) {
return;
}
}
if (appstate.playback) {
/* Loop over known recordings */
for (i = 0; i < recordings->len; i++) {
recording_t *rec = g_ptr_array_index(recordings, i);
if (e->keycode == rec->keycode) {
int j = 0;
for (j = 0; j < rec->commands->len; j++) {
handle_commands(g_ptr_array_index(rec->commands, j));
}
break;
}
}
appstate.playback = 0;
return;
}
if (appstate.grid_nav) {
if (handle_gridnav(e) == HANDLE_STOP) {
return;
}
}
/* Loop over known keybindings */
for (i = 0; i < keybindings->len; i++) {
keybinding_t *kbt = g_ptr_array_index(keybindings, i);
int keycode = kbt->keycode;
int mods = kbt->mods;
char *commands = kbt->commands;
if ((keycode == e->keycode) && (mods == e->state)) {
handle_commands(commands);
}
}
} /* void handle_keypress */
handler_info_t handle_recording(XKeyEvent *e) {
int i;
appstate.recording = record_ing; /* start recording actions */
/* TODO(sissel): support keys with keystrokes like shift+a */
/* check existing recording keycodes if we need to override it */
for (i = 0; i < recordings->len; i++) {
recording_t *rec = (recording_t *) g_ptr_array_index(recordings, i);
if (rec->keycode == e->keycode) {
g_ptr_array_free(rec->commands, TRUE);
g_ptr_array_remove_index_fast(recordings, i);
i--; /* array removal will shift everything down one to make up for the
* loss we'll need to redo this index */
}
}
//printf("Recording as keycode:%d\n", e->keycode);
active_recording->keycode = e->keycode;
return HANDLE_CONTINUE;
}
handler_info_t handle_gridnav(XKeyEvent *e) {
int index = 0;
if (e->state & 0x2000) { /* ISO Level3 Shift */
index += 2;
}
if (e->state & ShiftMask) {
index += 1;
}
KeySym sym = XkbKeycodeToKeysym(dpy, e->keycode, 0, index);
char *key = XKeysymToString(sym);
if (sym == XK_Escape) {
cmd_grid_nav("off");
update();
return HANDLE_STOP;
}
if (!(strlen(key) == 1 && isalpha(*key))) {
return HANDLE_CONTINUE;
}
int val = tolower(*key) - 'a';
if (val < 0) {
return HANDLE_CONTINUE;
}
/* TODO(sissel): Only GRID_LABEL_AA supported right now */
if (appstate.grid_nav_state == GRID_NAV_COL) {
if (val >= wininfo.grid_cols) {
return HANDLE_CONTINUE; /* Invalid key in this grid, pass */
}
appstate.grid_nav_state = GRID_NAV_ROW;
appstate.grid_nav_col = val;
appstate.need_draw = 1;
update();
save_history_point();
/* We have a full set of coordinates now; select that grid position */
cell_select(appstate.grid_nav_col, appstate.grid_nav_row);
update();
save_history_point();
appstate.grid_nav_row = -1;
appstate.grid_nav_col = -1;
} else if (appstate.grid_nav_state == GRID_NAV_ROW) {
if (val >= wininfo.grid_rows) {
return HANDLE_CONTINUE; /* Invalid key in this grid, pass */
}
appstate.grid_nav_row = val;
appstate.grid_nav_state = GRID_NAV_COL;
appstate.need_draw = 1;
update();
save_history_point();
}
return HANDLE_STOP;
}
void handle_commands(char *commands) {
char *cmdcopy;
char *tokctx, *tok, *strptr;
//printf("Commands; %s\n", commands);
cmdcopy = strdup(commands);
strptr = cmdcopy;
while ((tok = strtok_r(strptr, ",", &tokctx)) != NULL) {
int i;
int found = 0;
strptr = NULL;
/* Ignore leading whitespace */
while (isspace(*tok))
tok++;
/* Record this command (if the command is not 'record') */
if (appstate.recording == record_ing && strncmp(tok, "record", 6)) {
//printf("Record: %s\n", tok);
g_ptr_array_add(active_recording->commands, (gpointer) strdup(tok));
}
for (i = 0; dispatch[i].command; i++) {
/* XXX: This approach means we can't have one command be a subset of
* another. For example, 'grid' and 'grid-foo' will fail because when you
* use 'grid-foo' it'll match 'grid' first.
* This hasn't been a problem yet...
*/
/* If this command starts with a dispatch function, call it */
size_t cmdlen = strcspn(tok, " \t");
if (!strncmp(tok, dispatch[i].command, cmdlen)) {
/* tok + len + 1 is
* "command arg1 arg2"
* ^^^^^^^^^ <-- this
*/
char *args = tok + cmdlen;
if (*args == '\0')
args = "";
else
args++;
found = 1;
dispatch[i].func(args);
}
}
if (!found)
fprintf(stderr, "No such command: '%s'\n", tok);
}
if (ISACTIVE) {
if (ISDRAGGING)
cmd_warp(NULL);
update();
save_history_point();
}
free(cmdcopy);
}
void save_history_point() {
/* If the history is full, drop the oldest entry */
while (wininfo_history_cursor >= WININFO_MAXHIST) {
int i;
for (i = 1; i < wininfo_history_cursor; i++) {
memcpy(&(wininfo_history[i - 1]),
&(wininfo_history[i]),
sizeof(wininfo_t));
}
wininfo_history_cursor--;
}
memcpy(&(wininfo_history[wininfo_history_cursor]),
&(wininfo),
sizeof(wininfo));
wininfo_history_cursor++;
}
void restore_history_point(int moves_ago) {
wininfo_history_cursor -= moves_ago + 1;
if (wininfo_history_cursor < 0) {
wininfo_history_cursor = 0;
}
wininfo_t *previous = &(wininfo_history[wininfo_history_cursor]);
memcpy(&wininfo, previous, sizeof(wininfo));
appstate.need_draw = 1;
appstate.need_moveresize = 1;
}
/* Sort viewports, left to right.
* This may perform undesirably for vertically-stacked viewports or
* for other odd configurations */
int viewport_sort(const void *a, const void *b) {
viewport_t *va = (viewport_t *)a;
viewport_t *vb = (viewport_t *)b;
return va->x - vb->x;
}
void query_screens() {
int dummyint;
if (XineramaQueryExtension(dpy, &dummyint, &dummyint)
&& XineramaIsActive(dpy)) {
xinerama = True;
query_screen_xinerama();
} else { /* No xinerama */
query_screen_normal();
}
qsort(viewports, nviewports, sizeof(viewport_t), viewport_sort);
}
void query_screen_xinerama() {
int i;
XineramaScreenInfo *screeninfo;
screeninfo = XineramaQueryScreens(dpy, &nviewports);
viewports = calloc(nviewports, sizeof(viewport_t));
for (i = 0; i < nviewports; i++) {
viewports[i].x = screeninfo[i].x_org;
viewports[i].y = screeninfo[i].y_org;
viewports[i].w = screeninfo[i].width;
viewports[i].h = screeninfo[i].height;
viewports[i].screen_num = 0;
viewports[i].screen = ScreenOfDisplay(dpy, 0);
viewports[i].root = DefaultRootWindow(dpy);
}
XFree(screeninfo);
}
void query_screen_normal() {
int i;
Screen *s;
nviewports = ScreenCount(dpy);
viewports = calloc(nviewports, sizeof(viewport_t));
for (i = 0; i < nviewports; i++) {
s = ScreenOfDisplay(dpy, i);
viewports[i].x = 0;
viewports[i].y = 0;
viewports[i].w = s->width;
viewports[i].h = s->height;
viewports[i].root = RootWindowOfScreen(s);
viewports[i].screen_num = i;
viewports[i].screen = s; }
}
int query_current_screen() {
int i;
if (xinerama) {
return query_current_screen_xinerama();
} else {
return query_current_screen_normal();
}
}
int query_current_screen_xinerama() {
int i = 0, dummyint;
unsigned int dummyuint;
int x, y;
Window dummywin;
Window root = viewports[0].root;
XQueryPointer(dpy, root, &dummywin, &dummywin,
&x, &y, &dummyint, &dummyint, &dummyuint);
/* Figure which display the cursor is on */
for (i = 0; i < nviewports; i++) {
if (pointinrect(x, y, viewports[i].x, viewports[i].y,
viewports[i].w, viewports[i].h)) {
return i;
}
}
return -1;
}
int query_current_screen_normal() {
int i = 0, dummyint;
unsigned int dummyuint;
int x, y;
Window dummywin;
Window root = viewports[0].root;
/* Query each Screen's root window to ask if the pointer is in it.
* I don't know of any other better way to ask what Screen is
* active (where is the cursor) */
for (i = 0; i < nviewports; i++) {
if (!XQueryPointer(dpy, viewports[i].root, &dummywin, &dummywin,
&x, &y, &dummyint, &dummyint, &dummyuint))
continue;
if (pointinrect(x, y, viewports[i].x, viewports[i].y,
viewports[i].w, viewports[i].h)) {
return i;
}
}
return -1;
}
int pointinrect(int px, int py, int rx, int ry, int rw, int rh) {
return (px >= rx)
&& (px <= rx + rw)
&& (py >= ry)
&& (py <= ry + rh);
}
void sigchld(int sig) {
int status;
while (waitpid(-1, &status, WNOHANG) > 0) {
/* Do nothing, but we needed to waitpid() to collect dead children */
}
}
void sighup(int sig) {
restart();
}
void restart() {
execvp(g_argv[0], g_argv);
}
void recordings_save(const char *filename) {
FILE *output = NULL;
int i = 0;
output = fopen(filename, "w");
if (output == NULL) {
fprintf(stderr, "Failure opening '%s' for write: %s\n", filename, strerror(errno));
return; /* Should we exit instead? */
}
for (i = 0; i < recordings->len; i++) {
int j;
recording_t *rec = g_ptr_array_index(recordings, i);
if (rec->commands->len == 0)
continue;
fprintf(output, "%d ", rec->keycode);
for (j = 0; j < rec->commands->len; j++) {
fprintf(output, "%s%s",
(char *) g_ptr_array_index(rec->commands, j),
(j + 1 < rec->commands->len ? ", " : ""));
}
fprintf(output, "\n");
}
fclose(output);
}
void parse_recordings(const char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL)
return;
static const int bufsize = 8192;
char line[bufsize];
/* fopen succeeded */
while (fgets(line, bufsize, fp) != NULL) {
/* Kill the newline */
*(line + strlen(line) - 1) = '\0';
int keycode = 0;
char *command = NULL;
keycode = atoi(line);
command = line + strcspn(line, " \t");
//printf("found recording: %d => %s\n", keycode, command);
recording_t *rec = NULL;
rec = calloc(sizeof(recording_t), 1);
rec->keycode = keycode;
rec->commands = g_ptr_array_new();
g_ptr_array_add(rec->commands, (gpointer) strdup(command));
g_ptr_array_add(recordings, (gpointer) rec);
}
fclose(fp);
}
void openpixel(Display *dpy, Window zone, mouseinfo_t *mouseinfo) {
XRectangle rect;
if (mouseinfo->x == -1 && mouseinfo->y == -1) {
return;
}
rect.x = mouseinfo->x;
rect.y = mouseinfo->y;
rect.width = 1;
rect.height = 1;
XShapeCombineRectangles(dpy, zone, ShapeBounding, 0, 0, &rect, 1,
ShapeSubtract, 0);
} /* void openpixel */
void closepixel(Display *dpy, Window zone, mouseinfo_t *mouseinfo) {
XRectangle rect;
if (mouseinfo->x == -1 && mouseinfo->y == -1) {
return;
}
rect.x = mouseinfo->x;
rect.y = mouseinfo->y;
rect.width = 1;
rect.height = 1;
XShapeCombineRectangles(dpy, zone, ShapeBounding, 0, 0, &rect, 1,
ShapeUnion, 0);
} /* void closepixel */
int main(int argc, char **argv) {
char *pcDisplay;
int ret;
const char *prog = argv[0];
g_argv = argv;
if ((pcDisplay = getenv("DISPLAY")) == NULL) {
fprintf(stderr, "Error: DISPLAY environment variable not set\n");
return EXIT_SUCCESS;
}
if ((dpy = XOpenDisplay(pcDisplay)) == NULL) {
fprintf(stderr, "Error: Can't open display: %s\n", pcDisplay);
return EXIT_SUCCESS;
}
if (argc > 1 && (!strcmp(argv[1], "version")
|| !strcmp(argv[1], "-v")
|| !strcmp(argv[1], "--version"))) {
printf("keynav %s\n", KEYNAV_VERSION);
return EXIT_SUCCESS;
}
signal(SIGCHLD, sigchld);
signal(SIGHUP, sighup);
signal(SIGUSR1, sighup);
xdo = xdo_new_with_opened_display(dpy, pcDisplay, False);
parse_config();
query_screens();
if (argc == 2) {
handle_commands(argv[1]);
} else if (argc > 2) {
fprintf(stderr, "Usage: %s [command string]\n", prog);
fprintf(stderr, "Did you quote your command string?\n");
fprintf(stderr, " Example: %s 'loadconfig mykeynavrc,daemonize'\n", prog);
return EXIT_FAILURE;
}
/* Sync with the X server.
* This ensure we errors about XGrabKey and other failures
* before we try to daemonize */
XSync(dpy, 0);
if (daemonize) {
printf("Daemonizing now...\n");
daemon(0, 0);
is_daemon = True;
}
while (1) {
XEvent e;
XNextEvent(dpy, &e);
switch (e.type) {
case KeyPress:
handle_keypress((XKeyEvent *)&e);
break;
/* MapNotify means the keynav window is now visible */
case MapNotify:
update();
break;
// Configure events mean the window was changed (size, property, etc)
case ConfigureNotify:
update();
break;
case Expose:
if (zone) {
XCopyArea(dpy, canvas, zone, canvas_gc, e.xexpose.x, e.xexpose.y,
e.xexpose.width, e.xexpose.height,
e.xexpose.x, e.xexpose.y);
}
break;
case MotionNotify:
if (mouseinfo.x != -1 && mouseinfo.y != -1) {
closepixel(dpy, zone, &mouseinfo);
}
mouseinfo.x = e.xmotion.x;
mouseinfo.y = e.xmotion.y;
openpixel(dpy, zone, &mouseinfo);
break;
// Ignorable events.
case GraphicsExpose:
case NoExpose:
case LeaveNotify: // Mouse left the window
case KeyRelease: // key was released
case DestroyNotify: // window was destroyed
case UnmapNotify: // window was unmapped (hidden)
case MappingNotify: // when keyboard mapping changes
break;
default:
printf("Unexpected X11 event: %d\n", e.type);
break;
}
}
xdo_free(xdo);
} /* int main */
| kovetskiy/keynav | keynav.c | C | bsd-3-clause | 53,493 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_long_calloc_53a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-53a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: calloc Allocate data using calloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_calloc_53
{
#ifndef OMITBAD
/* bad function declaration */
void badSink_b(long * data);
void bad()
{
long * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)calloc(100, sizeof(long));
if (data == NULL) {exit(-1);}
badSink_b(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_b(long * data);
static void goodG2B()
{
long * data;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory from the heap using new */
data = new long;
goodG2BSink_b(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink_b(long * data);
static void goodB2G()
{
long * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)calloc(100, sizeof(long));
if (data == NULL) {exit(-1);}
goodB2GSink_b(data);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_calloc_53; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s04/CWE762_Mismatched_Memory_Management_Routines__delete_long_calloc_53a.cpp | C++ | bsd-3-clause | 2,819 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com" rel="preconnect" crossorigin="">
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CRoboto+Mono:400,500,700&display=fallback">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.transition — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.statespace.kalman_smoother.SmootherResults" href="statsmodels.tsa.statespace.kalman_smoother.SmootherResults.html" />
<link rel="prev" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.timing_options" href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.timing_options.html" />
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.transition" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels 0.11.0</span>
<span class="md-header-nav__topic"> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.transition </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.html" class="md-tabs__link">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels 0.11.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.transition.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-transition--page-root">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.transition<a class="headerlink" href="#generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-transition--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="attribute">
<dt id="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.transition">
<code class="sig-prename descclassname">KalmanSmoother.</code><code class="sig-name descname">transition</code><em class="property"> = None</em><a class="headerlink" href="#statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.transition" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.timing_options.html" title="Material"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.timing_options </span>
</div>
</a>
<a href="statsmodels.tsa.statespace.kalman_smoother.SmootherResults.html" title="Admonition"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.kalman_smoother.SmootherResults </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Jan 22, 2020.
<br/>
Created using
<a href="http://sphinx-doc.org/">Sphinx</a> 2.3.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | statsmodels/statsmodels.github.io | v0.11.0/generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.transition.html | HTML | bsd-3-clause | 17,795 |
// Chemfiles, a modern library for chemistry file reading and writing
// Copyright (C) Guillaume Fraux and contributors -- BSD license
#include <chemfiles.h>
#include <stdlib.h>
int main() {
// [example]
CHFL_ATOM* atom = chfl_atom("Na");
if (atom == NULL) {
/* handle error */
}
chfl_atom_free(atom);
// [example]
return 0;
}
| lscalfi/chemfiles | tests/capi/doc/chfl_atom/chfl_atom.c | C | bsd-3-clause | 367 |
package nirays.com.airspy;
/**
* Created by kirant400 on 19/3/16.
*/
public class DateDayXAxisValueFormatter {
}
| kirant400/freshfreedom | client/airspy/app/src/main/java/nirays/com/airspy/DateDayXAxisValueFormatter.java | Java | bsd-3-clause | 116 |
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="../../compiled/full-debug-compile-config/medea.core-compiled.js"></script>
<script type="text/javascript">
// --------------------------------------------------------------------------------
function oninit(medea) {
var vp1 = medea.CreateViewport();
vp1.Renderer(medea.CreateForwardRenderer());
// Add the Spider model
var root = medea.RootNode();
var anchor = root.AddChild();
medea.LoadModules('sceneloader',function() {
medea.LoadSceneFromResource('remote:assimp_import_sample/TexturedSpider.obj.json', anchor, null, function(load_status) {
if (load_status == medea.SCENE_LOAD_STATUS_GEOMETRY_FINISHED) {
anchor.ScaleToFit();
}
});
});
// Add a plain ground to the scene to hide the end of the skydome.
// The standardmesh module provides utilities to procedurally
// generate simple geometries, such as planes or spheres.
//
// The material module is used to disable backface culling on
// the plane.
//
// Note that LoadModules([a, b]) is more efficient than two
// separate (chained) calls to LoadModules because a and b
// can be fetched in parallel.
medea.LoadModules(['standardmesh','material'], function() {
var mfloor = medea.CreateStandardMesh_Plane(
medea.CreateSimpleMaterialFromTexture('remote:labyrinth_sample/floor_texture.jpg')
);
mfloor.Material().Passes().forEach( function(p) {
p.CullFace(false) }
);
root.AddChild()
.Translate([0,-1,0])
.Scale(300)
.AddEntity(mfloor);
});
// Add the skydome itself - the skydome module will be asynchronously
// fetched unless it is compiled into medea.core-compiled.js.
//
// Once the module is available and initialized, we construct the
// skybox node and add it to the scenegraph. All further resources
// - shaders and the requested texture - are fetched asynchronously
// in the background.
medea.LoadModules('skydome',function() {
root.AddChild(medea.CreateSkydomeNode('remote:skydome_sample/midmorning/midmorning.png', 0.2));
});
var cam = medea.CreateCameraNode();
root.AddChild(cam);
vp1.Camera(cam);
cam.Translate([0,0,5]);
// Add a plain FPS-style camera controller
medea.LoadModules('camcontroller',function() {
var cc = medea.CreateCamController('fps');
cam.AddEntity(cc);
cc.Enable();
});
medea.SetDebugPanel(null);
medea.Start();
}
// --------------------------------------------------------------------------------
function run() {
var dep = ['debug','forwardrenderer', 'keycodes', 'input_handler'];
var config = {
dataroot: '../../data'
};
medealib.CreateContext("canvas",
config,
dep,
oninit,
function() {
alert('failed to initialize medea');
});
}
</script>
</head>
<body onload="run();">
<div style="margin-left: 300px;">Press ENTER to toggle scene. (Skydome from http://www.tutorialsforblender3d.com/Textures/Skys/Sky_Dome_1.html, free for non-commercial use)</div>
<canvas id="canvas" style="border: none;" width="1024" height="768"></canvas>
</body>
</html>
| acgessler/medea.js | samples/Skydome/Skydome.html | HTML | bsd-3-clause | 3,128 |
/**
* Copyright (C) 2002 Maynard Demmon, maynard@organic.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the names "Java Outline Editor", "JOE" nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.organic.maynard.outliner.actions;
import com.organic.maynard.outliner.*;
import com.organic.maynard.outliner.util.preferences.*;
import com.organic.maynard.outliner.util.undo.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Window;
import java.awt.datatransfer.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import com.organic.maynard.util.string.*;
/**
* @author $Author: maynardd $
* @version $Revision: 1.1 $, $Date: 2002/08/20 08:56:02 $
*/
public class EndAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
//System.out.println("EndAction");
OutlinerCellRendererImpl textArea = null;
boolean isIconFocused = true;
Component c = (Component) e.getSource();
if (c instanceof OutlineButton) {
textArea = ((OutlineButton) c).renderer;
} else if (c instanceof OutlineLineNumber) {
textArea = ((OutlineLineNumber) c).renderer;
} else if (c instanceof OutlineCommentIndicator) {
textArea = ((OutlineCommentIndicator) c).renderer;
} else if (c instanceof OutlinerCellRendererImpl) {
textArea = (OutlinerCellRendererImpl) c;
isIconFocused = false;
}
// Shorthand
Node node = textArea.node;
JoeTree tree = node.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
//System.out.println(e.getModifiers());
switch (e.getModifiers()) {
case 0:
if (isIconFocused) {
if (tree.getSelectedNodes().size() > 1) {
changeSelectionToNode(tree, layout);
} else {
changeFocusToTextArea(textArea, tree, layout);
}
} else {
end(node, tree, layout);
}
break;
}
}
// KeyFocusedMethods
public static void end(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
// Record the EditingNode, Mark and CursorPosition
tree.setCursorMarkPosition(currentNode.getValue().length());
tree.setCursorPosition(currentNode.getValue().length(), false);
tree.getDocument().setPreferredCaretPosition(currentNode.getValue().length());
// Redraw and Set Focus
layout.draw(currentNode, OutlineLayoutManager.TEXT);
}
// IconFocusedMethods
public static void changeSelectionToNode(JoeTree tree, OutlineLayoutManager layout) {
Node selectedNode = tree.getOldestInSelection();
// Update Selection
tree.clearSelection();
tree.addNodeToSelection(selectedNode);
// Record State
tree.setEditingNode(selectedNode);
tree.setCursorPosition(0);
tree.getDocument().setPreferredCaretPosition(0);
// Redraw and Set Focus
layout.draw(selectedNode, OutlineLayoutManager.ICON);
}
public static void changeFocusToTextArea(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) {
Node currentNode = textArea.node;
int index = textArea.getText().length();
tree.setCursorPosition(index);
tree.getDocument().setPreferredCaretPosition(index);
tree.setComponentFocus(OutlineLayoutManager.TEXT);
tree.clearSelection();
layout.draw(currentNode,OutlineLayoutManager.TEXT);
}
} | hashrock/JavaOutlineEditor | src/com/organic/maynard/outliner/actions/EndAction.java | Java | bsd-3-clause | 4,698 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>statsmodels.sandbox.regression.gmm.GMMResults.initialize — statsmodels v0.10.1 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.sandbox.regression.gmm.GMMResults.jtest" href="statsmodels.sandbox.regression.gmm.GMMResults.jtest.html" />
<link rel="prev" title="statsmodels.sandbox.regression.gmm.GMMResults.get_bse" href="statsmodels.sandbox.regression.gmm.GMMResults.get_bse.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/statsmodels_hybi_banner.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.sandbox.regression.gmm.GMMResults.jtest.html" title="statsmodels.sandbox.regression.gmm.GMMResults.jtest"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.sandbox.regression.gmm.GMMResults.get_bse.html" title="statsmodels.sandbox.regression.gmm.GMMResults.get_bse"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../gmm.html" >Generalized Method of Moments <code class="xref py py-mod docutils literal notranslate"><span class="pre">gmm</span></code></a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.sandbox.regression.gmm.GMMResults.html" accesskey="U">statsmodels.sandbox.regression.gmm.GMMResults</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-sandbox-regression-gmm-gmmresults-initialize">
<h1>statsmodels.sandbox.regression.gmm.GMMResults.initialize<a class="headerlink" href="#statsmodels-sandbox-regression-gmm-gmmresults-initialize" title="Permalink to this headline">¶</a></h1>
<p>method</p>
<dl class="method">
<dt id="statsmodels.sandbox.regression.gmm.GMMResults.initialize">
<code class="sig-prename descclassname">GMMResults.</code><code class="sig-name descname">initialize</code><span class="sig-paren">(</span><em class="sig-param">model</em>, <em class="sig-param">params</em>, <em class="sig-param">**kwd</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.sandbox.regression.gmm.GMMResults.initialize" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize (possibly re-initialize) a Results instance.</p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.sandbox.regression.gmm.GMMResults.get_bse.html"
title="previous chapter">statsmodels.sandbox.regression.gmm.GMMResults.get_bse</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.sandbox.regression.gmm.GMMResults.jtest.html"
title="next chapter">statsmodels.sandbox.regression.gmm.GMMResults.jtest</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.sandbox.regression.gmm.GMMResults.initialize.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2.
</div>
</body>
</html> | statsmodels/statsmodels.github.io | v0.10.1/generated/statsmodels.sandbox.regression.gmm.GMMResults.initialize.html | HTML | bsd-3-clause | 7,653 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__malloc_char_memcpy_33.cpp
Label Definition File: CWE124_Buffer_Underwrite__malloc.label.xml
Template File: sources-sink-33.tmpl.cpp
*/
/*
* @description
* CWE: 124 Buffer Underwrite
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: memcpy
* BadSink : Copy string to data using memcpy
* Flow Variant: 33 Data flow: use of a C++ reference to data within the same function
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_33
{
#ifndef OMITBAD
void bad()
{
char * data;
char * &dataRef = data;
data = NULL;
{
char * dataBuffer = (char *)malloc(100*sizeof(char));
if (dataBuffer == NULL) {exit(-1);}
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
}
{
char * data = dataRef;
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
memcpy(data, source, 100*sizeof(char));
/* Ensure the destination buffer is null terminated */
data[100-1] = '\0';
printLine(data);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by malloc() so can't safely call free() on it */
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
char * &dataRef = data;
data = NULL;
{
char * dataBuffer = (char *)malloc(100*sizeof(char));
if (dataBuffer == NULL) {exit(-1);}
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
{
char * data = dataRef;
{
char source[100];
memset(source, 'C', 100-1); /* fill with 'C's */
source[100-1] = '\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */
memcpy(data, source, 100*sizeof(char));
/* Ensure the destination buffer is null terminated */
data[100-1] = '\0';
printLine(data);
/* INCIDENTAL CWE-401: Memory Leak - data may not point to location
* returned by malloc() so can't safely call free() on it */
}
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE124_Buffer_Underwrite__malloc_char_memcpy_33; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE124_Buffer_Underwrite/s02/CWE124_Buffer_Underwrite__malloc_char_memcpy_33.cpp | C++ | bsd-3-clause | 3,780 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!--
二次曲线
例题:http://tinyurl.com/html5quadratic
context.moveTo(69, 263); //起始点
context.quadraticCurveTo(x1,y1,x2,y2) //控制点,终点
-->
<canvas id="canvas" width="500" height="500" style="border:1px solid #aaa;display:block;margin:50px auto;"></canvas>
<script>
//下边是arc属性
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
context.beginPath();
context.arc(50,50,40,40,0,2*Math.PI ); //这个是绘制圆,x,y,r,start,stop,anticlockwise(这个是顺时针false)
context.closePath();
context.fill();
</script>
<!--
三次曲线
例题:http://tinyurl.com/html5bezier
context.moveTo(x0, y0); //起始点
context.bezierCurveTo(x1,y1,x2,y2,x3,y3) //控制点,控制点,终点
-->
</body>
</html> | duolew/project-zhp | HTML5/Canvas/贝塞尔曲线.html | HTML | bsd-3-clause | 1,033 |
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E08000032'
addresses_name = 'parl.2017-06-08/Version 1/Democracy_Club__08June2017.tsvJune2017.tsv'
stations_name = 'parl.2017-06-08/Version 1/Democracy_Club__08June2017.tsvJune2017.tsv'
elections = ['parl.2017-06-08']
csv_delimiter = '\t'
| chris48s/UK-Polling-Stations | polling_stations/apps/data_collection/management/commands/import_bradford.py | Python | bsd-3-clause | 408 |
import os
import pytest
from datetime import time
from sport_systems import stats
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def response_1():
path = os.path.join(BASE_DIR, 'response-1.xml')
with open(path, 'rb') as fin:
data = fin.read()
return data
@pytest.fixture
def results_1():
return [
stats.Result(time=time(1, 10, 15), name='foo'),
stats.Result(time=time(1, 10, 20), name='foo'),
stats.Result(time=time(1, 20), name='foo'),
stats.Result(time=time(1, 30, 10), name='foo'),
stats.Result(time=time(1, 30, 15), name='foo'),
stats.Result(time=time(1, 30, 20), name='foo'),
]
| willcodefortea/sportssystems_crawler | tests/conftest.py | Python | bsd-3-clause | 672 |
{% extends "careers/base.html" %}
{% load crispy_forms_tags %}
{% if object %}
{% block head_title %}Careers-Modify Career{% endblock head_title %}
{% else %}
{% block head_title_new %}Careers-New Career{% endblock head_title_new %}
{% endif %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
{% if object %}
<h1>{% block updateheader %}<a href="{% url 'careers:list' %}">Careers</a> / Modify Career{% endblock updateheader %}</h1>
<form action="{% url 'careers:update' object.code %}" method="POST" class="horizontal-form" role="form">
{% else %}
<h1>{% block createheader %}<a href="{% url 'careers:list' %}">Careers</a> / Modify Career{% endblock createheader %}</h1>
<form action="{% url 'careers:create' %}" method="POST" class="horizontal-form" role="form">
{% endif %}
{% csrf_token %}
{{ form|crispy }}
<div class="control-group">
<div class="controls">
{% if object %}
<button type="submit" class="btn btn-primary">Modify</button>
{% else %}
<button type="submit" class="btn btn-primary">Add</button>
{% endif %}
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock content %} | LABETE/InstitutionalPortal | InstitutionalPortal/templates/careers/career_form.html | HTML | bsd-3-clause | 1,263 |
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "vizwindow.h"
#include "audio.hpp"
#include "fm.hpp"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(FMSynth &fm, QWidget *parent = 0);
~MainWindow();
private slots:
void on_button_trigger_clicked();
void on_volume_sliderMoved(int position);
void on_carrier_slider_sliderMoved(int position);
void on_modulating_slider_sliderMoved(int position);
void on_modulation_index_slider_sliderMoved(int position);
void on_carrier_textbox_editingFinished();
void on_modulating_textbox_editingFinished();
void on_modulation_index_textbox_editingFinished();
void on_scale_sliderMoved(int position);
private:
Ui::MainWindow *ui;
FMSynth &fmsynth;
VizWindow vizwindow {fmsynth};
AudioEngine audioEngine {fmsynth};
};
#endif // MAINWINDOW_H
| analoq/fmLab | mainwindow.h | C | bsd-3-clause | 942 |
package de.bwaldvogel.mongo.backend;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import de.bwaldvogel.mongo.MongoCollection;
import de.bwaldvogel.mongo.bson.Document;
import de.bwaldvogel.mongo.exception.CannotIndexParallelArraysError;
import de.bwaldvogel.mongo.exception.KeyConstraintError;
public abstract class Index<P> {
private final String name;
private final List<IndexKey> keys;
private final boolean sparse;
protected Index(String name, List<IndexKey> keys, boolean sparse) {
this.name = name;
this.keys = keys;
this.sparse = sparse;
}
protected boolean isSparse() {
return sparse;
}
public List<IndexKey> getKeys() {
return keys;
}
public boolean hasSameOptions(Index<?> other) {
return sparse == other.sparse;
}
public String getName() {
return name;
}
protected List<String> keys() {
return keys.stream()
.map(IndexKey::getKey)
.collect(Collectors.toList());
}
protected Set<String> keySet() {
return keys.stream()
.map(IndexKey::getKey)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public Set<KeyValue> getKeyValues(Document document) {
return getKeyValues(document, true);
}
Set<KeyValue> getKeyValues(Document document, boolean normalize) {
Map<String, Object> valuesPerKey = collectValuesPerKey(document);
if (normalize) {
valuesPerKey.replaceAll((key, value) -> Utils.normalizeValue(value));
}
List<Collection<Object>> collectionValues = valuesPerKey.values().stream()
.filter(value -> value instanceof Collection)
.map(value -> (Collection<Object>) value)
.collect(Collectors.toList());
if (collectionValues.size() > 0) {
validateHasNoParallelArrays(document);
return CollectionUtils.multiplyWithOtherElements(valuesPerKey.values(), collectionValues).stream()
.map(KeyValue::new)
.collect(StreamUtils.toLinkedHashSet());
} else {
return Collections.singleton(new KeyValue(valuesPerKey.values()));
}
}
private void validateHasNoParallelArrays(Document document) {
Set<List<String>> arrayPaths = new LinkedHashSet<>();
for (String key : keys()) {
List<String> pathToFirstCollection = getPathToFirstCollection(document, key);
if (pathToFirstCollection != null) {
arrayPaths.add(pathToFirstCollection);
}
}
if (arrayPaths.size() > 1) {
List<String> parallelArraysPaths = arrayPaths.stream()
.map(path -> path.get(path.size() - 1))
.collect(Collectors.toList());
throw new CannotIndexParallelArraysError(parallelArraysPaths);
}
}
private static List<String> getPathToFirstCollection(Document document, String key) {
List<String> fragments = Utils.splitPath(key);
List<String> remainingFragments = Utils.getTail(fragments);
return getPathToFirstCollection(document, remainingFragments, Collections.singletonList(fragments.get(0)));
}
private static List<String> getPathToFirstCollection(Document document, List<String> remainingFragments, List<String> path) {
Object value = Utils.getSubdocumentValue(document, Utils.joinPath(path));
if (value instanceof Collection) {
return path;
}
if (remainingFragments.isEmpty()) {
return null;
}
List<String> newPath = new ArrayList<>(path);
newPath.add(remainingFragments.get(0));
return getPathToFirstCollection(document, Utils.getTail(remainingFragments), newPath);
}
private Map<String, Object> collectValuesPerKey(Document document) {
Map<String, Object> valuesPerKey = new LinkedHashMap<>();
for (String key : keys()) {
Object value = Utils.getSubdocumentValueCollectionAware(document, key);
valuesPerKey.put(key, value);
}
return valuesPerKey;
}
private static Set<KeyValue> collectCollectionValues(List<Collection<?>> collectionValues) {
int size = collectionValues.get(0).size();
Set<KeyValue> keyValues = new LinkedHashSet<>();
for (int i = 0; i < size; i++) {
int pos = i;
List<Object> values = collectionValues.stream()
.map(collection -> CollectionUtils.getElementAtPosition(collection, pos))
.collect(Collectors.toList());
keyValues.add(new KeyValue(values));
}
return keyValues;
}
public abstract P getPosition(Document document);
public abstract void checkAdd(Document document, MongoCollection<P> collection);
public abstract void add(Document document, P position, MongoCollection<P> collection);
public abstract P remove(Document document);
public abstract boolean canHandle(Document query);
public abstract Iterable<P> getPositions(Document query);
public abstract long getCount();
public boolean isEmpty() {
return getCount() == 0;
}
public abstract long getDataSize();
public abstract void checkUpdate(Document oldDocument, Document newDocument, MongoCollection<P> collection);
public abstract void updateInPlace(Document oldDocument, Document newDocument, P position, MongoCollection<P> collection) throws KeyConstraintError;
protected boolean isCompoundIndex() {
return keys().size() > 1;
}
protected boolean nullAwareEqualsKeys(Document oldDocument, Document newDocument) {
Set<KeyValue> oldKeyValues = getKeyValues(oldDocument);
Set<KeyValue> newKeyValues = getKeyValues(newDocument);
return Utils.nullAwareEquals(oldKeyValues, newKeyValues);
}
public abstract void drop();
@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + getName() + "]";
}
}
| bwaldvogel/mongo-java-server | core/src/main/java/de/bwaldvogel/mongo/backend/Index.java | Java | bsd-3-clause | 6,291 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_
#define FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/tonic/converter/dart_converter.h"
namespace flutter {
struct LineMetrics {
const bool* hard_break;
// The final computed ascent and descent for the line. This can be impacted by
// the strut, height, scaling, as well as outlying runs that are very tall.
//
// The top edge is `baseline - ascent` and the bottom edge is `baseline +
// descent`. Ascent and descent are provided as positive numbers. Raw numbers
// for specific runs of text can be obtained in run_metrics_map. These values
// are the cumulative metrics for the entire line.
const double* ascent;
const double* descent;
const double* unscaled_ascent;
// Height of the line.
const double* height;
// Width of the line.
const double* width;
// The left edge of the line. The right edge can be obtained with `left +
// width`
const double* left;
// The y position of the baseline for this line from the top of the paragraph.
const double* baseline;
// Zero indexed line number.
const size_t* line_number;
LineMetrics();
LineMetrics(const bool* hard_break,
const double* ascent,
const double* descent,
const double* unscaled_ascent,
const double* height,
const double* width,
const double* left,
const double* baseline,
const size_t* line_number)
: hard_break(hard_break),
ascent(ascent),
descent(descent),
unscaled_ascent(unscaled_ascent),
height(height),
width(width),
left(left),
baseline(baseline),
line_number(line_number) {}
};
} // namespace flutter
namespace tonic {
template <>
struct DartConverter<flutter::LineMetrics> {
static Dart_Handle ToDart(const flutter::LineMetrics& val);
};
template <>
struct DartListFactory<flutter::LineMetrics> {
static Dart_Handle NewList(intptr_t length);
};
} // namespace tonic
#endif // FLUTTER_LIB_UI_TEXT_LINE_METRICS_H_
| mikejurka/engine | lib/ui/text/line_metrics.h | C | bsd-3-clause | 2,306 |
import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native';
import url from 'url';
import DevMenuContext from '../../DevMenuContext';
import * as DevMenuWebBrowser from '../../DevMenuWebBrowser';
import Colors from '../../constants/Colors';
import Endpoints from '../../constants/Endpoints';
import Button from '../Button';
import Loading from '../Loading';
import { StyledText } from '../Text';
export default function UnauthenticatedProfile() {
const context = React.useContext(DevMenuContext);
const [authenticationError, setAuthenticationError] = React.useState<string | null>(null);
const [isAuthenticating, setIsAuthenticating] = React.useState(false);
const mounted = React.useRef<boolean | null>(true);
React.useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const _handleAuthentication = async (urlPath: string) => {
if (isAuthenticating || !mounted.current) {
return;
}
setAuthenticationError(null);
setIsAuthenticating(true);
try {
const redirectBase = 'expo-dev-menu://auth';
const authSessionURL = `${
Endpoints.website.origin
}/${urlPath}?app_redirect_uri=${encodeURIComponent(redirectBase)}`;
const result = await DevMenuWebBrowser.openAuthSessionAsync(authSessionURL, redirectBase);
if (result.type === 'success') {
const resultURL = url.parse(result.url, true);
const sessionSecret = decodeURIComponent(resultURL.query['session_secret'] as string);
if (mounted.current) {
await context.setSession({ sessionSecret });
}
}
} catch (e) {
if (mounted.current) {
setAuthenticationError(e.message);
}
} finally {
if (mounted.current) {
setIsAuthenticating(false);
}
}
};
const _handleSignInPress = async () => {
await _handleAuthentication('login');
};
const _handleSignUpPress = async () => {
await _handleAuthentication('signup');
};
const title = 'Sign in to Continue';
const description = 'Sign in or create an Expo account to view your projects.';
if (isAuthenticating) {
return <Loading />;
}
return (
<View style={styles.contentContainer}>
<StyledText style={styles.titleText}>{title}</StyledText>
<StyledText
style={styles.descriptionText}
darkColor={Colors.dark.secondaryText}
lightColor={Colors.light.secondaryText}>
{description}
</StyledText>
<Button onPress={_handleSignInPress} tittle="Sign in to your account" />
<View style={{ marginBottom: 15 }} />
<Button onPress={_handleSignUpPress} tittle="Sign up for Expo" />
{authenticationError && (
<StyledText
style={styles.errorText}
darkColor={Colors.dark.error}
lightColor={Colors.light.error}>
Something went wrong when authenticating: {authenticationError}
</StyledText>
)}
</View>
);
}
const styles = StyleSheet.create({
contentContainer: {
paddingTop: 30,
alignItems: 'center',
justifyContent: 'center',
},
titleText: {
marginBottom: 15,
fontWeight: '400',
fontSize: 18,
},
descriptionText: {
textAlign: 'center',
marginHorizontal: 15,
marginBottom: 20,
...Platform.select({
ios: {
fontSize: 12,
lineHeight: 18,
},
android: {
fontSize: 14,
lineHeight: 20,
},
}),
},
errorText: {
textAlign: 'center',
marginHorizontal: 15,
marginTop: 20,
...Platform.select({
ios: {
fontSize: 15,
lineHeight: 20,
},
android: {
fontSize: 16,
lineHeight: 24,
},
}),
},
});
| exponent/exponent | packages/expo-dev-menu/app/components/profile/UnauthenticatedProfile.tsx | TypeScript | bsd-3-clause | 3,788 |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace app\components\widgets;
use app\assets\DatePickerAsset;
use Yii;
use yii\helpers\Html;
use yii\base\InvalidParamException;
/**
* DatePicker renders a `datepicker` jQuery UI widget.
*
* For example to use the datepicker with a [[\yii\base\Model|model]]:
*
* ```php
* echo DatePicker::widget([
* 'model' => $model,
* 'attribute' => 'from_date',
* //'language' => 'ru',
* //'dateFormat' => 'yyyy-MM-dd',
* ]);
* ```
*
* The following example will use the name property instead:
*
* ```php
* echo DatePicker::widget([
* 'name' => 'from_date',
* 'value' => $value,
* //'language' => 'ru',
* //'dateFormat' => 'yyyy-MM-dd',
* ]);
* ```
*
* You can also use this widget in an [[\yii\widgets\ActiveForm|ActiveForm]] using the [[\yii\widgets\ActiveField::widget()|widget()]]
* method, for example like this:
*
* ```php
* <?= $form->field($model, 'from_date')->widget(\yii\jui\DatePicker::classname(), [
* //'language' => 'ru',
* //'dateFormat' => 'yyyy-MM-dd',
* ]) ?>
* ```
*
* Note that and empty string (`''`) and `null` will result in an empty text field while `0` will be
* interpreted as a UNIX timestamp and result in a date displayed as `1970-01-01`.
* It is recommended to add a
* validation filter in your model that sets the value to `null` in case when no date has been entered:
*
* ```php
* [['from_date'], 'default', 'value' => null],
* ```
*
* @see http://api.jqueryui.com/datepicker/
* @author Alexander Kochetov <creocoder@gmail.com>
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class DatePicker extends InputWidget
{
/**
* @var string the locale ID (e.g. 'fr', 'de', 'en-GB') for the language to be used by the date picker.
* If this property is empty, then the current application language will be used.
*
* Since version 2.0.2 a fallback is used if the application language includes a locale part (e.g. `de-DE`) and the language
* file does not exist, it will fall back to using `de`.
*/
public $language;
/**
* @var boolean If true, shows the widget as an inline calendar and the input as a hidden field.
*/
public $inline = false;
/**
* @var array the HTML attributes for the container tag. This is only used when [[inline]] is true.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $containerOptions = [];
/**
* @var string the format string to be used for formatting the date value. This option will be used
* to populate the [[clientOptions|clientOption]] `dateFormat`.
* The value can be one of "short", "medium", "long", or "full", which represents a preset format of different lengths.
*
* It can also be a custom format as specified in the [ICU manual](http://userguide.icu-project.org/formatparse/datetime#TOC-Date-Time-Format-Syntax).
* Alternatively this can be a string prefixed with `php:` representing a format that can be recognized by the
* PHP [date()](http://php.net/manual/de/function.date.php)-function.
*
* For example:
*
* ```php
* 'MM/dd/yyyy' // date in ICU format
* 'php:m/d/Y' // the same date in PHP format
* ```
*
* If not set the default value will be taken from `Yii::$app->formatter->dateFormat`.
*/
public $dateFormat;
/**
* @var string the model attribute that this widget is associated with.
* The value of the attribute will be converted using [[\yii\i18n\Formatter::asDate()|`Yii::$app->formatter->asDate()`]]
* with the [[dateFormat]] if it is not null.
*/
public $attribute;
/**
* @var string the input value.
* This value will be converted using [[\yii\i18n\Formatter::asDate()|`Yii::$app->formatter->asDate()`]]
* with the [[dateFormat]] if it is not null.
*/
public $value;
public $clientOptions;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->inline && !isset($this->containerOptions['id'])) {
$this->containerOptions['id'] = $this->options['id'] . '-container';
}
$this->options['class'].="form-control";
if ($this->dateFormat === null) {
$this->dateFormat = Yii::$app->formatter->dateFormat;
}
}
/**
* Renders the widget.
*/
public function run()
{
echo $this->renderWidget() . "\n";
$containerID = $this->inline ? $this->containerOptions['id'] : $this->options['id'];
$this->clientOptions['rtl']=false;
$this->clientOptions['autoclose']=true;
$this->clientOptions['language']='zh-CN';
$this->clientOptions['format']='yyyy-mm-dd';
$this->registerClientOptions('datepicker', $containerID);
DatePickerAsset::register($this->getView());
}
/**
* Renders the DatePicker widget.
* @return string the rendering result.
*/
protected function renderWidget()
{
$contents = [];
// get formatted date value
if ($this->hasModel()) {
$value = Html::getAttributeValue($this->model, $this->attribute);
} else {
$value = $this->value;
}
if ($value !== null && $value !== '') {
// format value according to dateFormat
try {
$value = Yii::$app->formatter->asDate($value, $this->dateFormat);
} catch(InvalidParamException $e) {
// ignore exception and keep original value if it is not a valid date
}
}
$options = $this->options;
$options['value'] = $value;
if ($this->inline === false) {
// render a text input
if ($this->hasModel()) {
$contents[] = Html::activeTextInput($this->model, $this->attribute, $options);
} else {
$contents[] = Html::textInput($this->name, $value, $options);
}
} else {
// render an inline date picker with hidden input
if ($this->hasModel()) {
$contents[] = Html::activeHiddenInput($this->model, $this->attribute, $options);
} else {
$contents[] = Html::hiddenInput($this->name, $value, $options);
}
$this->clientOptions['defaultDate'] = $value;
$this->clientOptions['altField'] = '#' . $this->options['id'];
$contents[] = Html::tag('div', null, $this->containerOptions);
}
return implode("\n", $contents);
}
} | xiaohaoyong/AcarAdmin | components/widgets/DatePicker.php | PHP | bsd-3-clause | 6,784 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- This file documents the GNU Assembler "as".
Copyright (C) 1991-2014 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled "GNU Free Documentation License".
-->
<!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Using as: Symbol Other</title>
<meta name="description" content="Using as: Symbol Other">
<meta name="keywords" content="Using as: Symbol Other">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="AS-Index.html#AS-Index" rel="index" title="AS Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="a_002eout-Symbols.html#a_002eout-Symbols" rel="up" title="a.out Symbols">
<link href="COFF-Symbols.html#COFF-Symbols" rel="next" title="COFF Symbols">
<link href="Symbol-Desc.html#Symbol-Desc" rel="prev" title="Symbol Desc">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.indentedblock {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
div.smalllisp {margin-left: 3.2em}
kbd {font-style:oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:nowrap}
span.nolinebreak {white-space:nowrap}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="Symbol-Other"></a>
<div class="header">
<p>
Previous: <a href="Symbol-Desc.html#Symbol-Desc" accesskey="p" rel="prev">Symbol Desc</a>, Up: <a href="a_002eout-Symbols.html#a_002eout-Symbols" accesskey="u" rel="up">a.out Symbols</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="AS-Index.html#AS-Index" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Other"></a>
<h4 class="subsubsection">5.5.3.2 Other</h4>
<a name="index-other-attribute_002c-of-a_002eout-symbol"></a>
<p>This is an arbitrary 8-bit value. It means nothing to <code>as</code>.
</p>
</body>
</html>
| AlbandeCrevoisier/ldd-athens | gcc-linaro-4.9-2015.02-3-x86_64_arm-linux-gnueabihf/share/doc/as.html/Symbol-Other.html | HTML | bsd-3-clause | 3,257 |
<link rel="import" href="packages://ui-kit/widget/index.html">
<dom-module id="remote-debugging-panel">
<link rel="import" type="css" href="panel.css">
<template>
<editor-button nofocus on-click='setDebugPoint'>
断点
</editor-button>
<editor-button nofocus on-click='removeDebugPoint'>
去除断点
</editor-button>
<editor-button nofocus on-click='pause'>
暂停
</editor-button>
<editor-button nofocus on-click='resume'>
恢复
</editor-button>
</template>
<script type="text/javascript" src="panel.js"></script>
</dom-module>
| 2youyouo2/remote-debugging | panel/panel.html | HTML | bsd-3-clause | 606 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>statsmodels.regression.quantile_regression.QuantRegResults.prsquared — statsmodels 0.9.0 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.regression.quantile_regression.QuantRegResults.pvalues" href="statsmodels.regression.quantile_regression.QuantRegResults.pvalues.html" />
<link rel="prev" title="statsmodels.regression.quantile_regression.QuantRegResults.predict" href="statsmodels.regression.quantile_regression.QuantRegResults.predict.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/statsmodels_hybi_banner.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.regression.quantile_regression.QuantRegResults.pvalues.html" title="statsmodels.regression.quantile_regression.QuantRegResults.pvalues"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.regression.quantile_regression.QuantRegResults.predict.html" title="statsmodels.regression.quantile_regression.QuantRegResults.predict"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../regression.html" >Linear Regression</a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.regression.quantile_regression.QuantRegResults.html" accesskey="U">statsmodels.regression.quantile_regression.QuantRegResults</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-regression-quantile-regression-quantregresults-prsquared">
<h1>statsmodels.regression.quantile_regression.QuantRegResults.prsquared<a class="headerlink" href="#statsmodels-regression-quantile-regression-quantregresults-prsquared" title="Permalink to this headline">¶</a></h1>
<dl class="method">
<dt id="statsmodels.regression.quantile_regression.QuantRegResults.prsquared">
<code class="descclassname">QuantRegResults.</code><code class="descname">prsquared</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/regression/quantile_regression.html#QuantRegResults.prsquared"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.regression.quantile_regression.QuantRegResults.prsquared" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.regression.quantile_regression.QuantRegResults.predict.html"
title="previous chapter">statsmodels.regression.quantile_regression.QuantRegResults.predict</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.regression.quantile_regression.QuantRegResults.pvalues.html"
title="next chapter">statsmodels.regression.quantile_regression.QuantRegResults.pvalues</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.regression.quantile_regression.QuantRegResults.prsquared.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.4.
</div>
</body>
</html> | statsmodels/statsmodels.github.io | 0.9.0/generated/statsmodels.regression.quantile_regression.QuantRegResults.prsquared.html | HTML | bsd-3-clause | 6,844 |
from django.test import TestCase
from mock import Mock, patch
from paymentexpress.facade import Facade
from paymentexpress.gateway import AUTH, PURCHASE
from paymentexpress.models import OrderTransaction
from tests import (XmlTestingMixin, CARD_VISA, SAMPLE_SUCCESSFUL_RESPONSE,
SAMPLE_DECLINED_RESPONSE, SAMPLE_ERROR_RESPONSE)
from oscar.apps.payment.utils import Bankcard
from oscar.apps.payment.exceptions import (UnableToTakePayment,
InvalidGatewayRequestError)
class MockedResponseTestCase(TestCase):
def create_mock_response(self, body, status_code=200):
response = Mock()
response.content = body
response.text = body
response.status_code = status_code
return response
class FacadeTests(TestCase, XmlTestingMixin):
def setUp(self):
self.facade = Facade()
def test_zero_amount_raises_exception(self):
card = Bankcard(card_number=CARD_VISA,
expiry_date='1015',
name="Frankie", cvv="123",
start_date="1010")
with self.assertRaises(UnableToTakePayment):
self.facade.authorise('1000', 0, card)
def test_zero_amount_for_complete_raises_exception(self):
with self.assertRaises(UnableToTakePayment):
self.facade.complete('1000', 0, '1234')
def test_zero_amount_for_purchase_raises_exception(self):
with self.assertRaises(UnableToTakePayment):
self.facade.purchase('1000', 0)
def test_purchase_without_billing_id_or_card_raises_exception(self):
with self.assertRaises(ValueError):
self.facade.purchase('1000', 1.23)
def test_zero_amount_for_refund_raises_exception(self):
with self.assertRaises(UnableToTakePayment):
self.facade.refund('1000', 0, '1234')
def test_merchant_reference_format(self):
merchant_ref = self.facade._get_merchant_reference('1000', AUTH)
self.assertRegexpMatches(merchant_ref, r'^\d+_[A-Z]+_\d+_\d{4}$')
class FacadeSuccessfulResponseTests(MockedResponseTestCase):
dps_txn_ref = '000000030884cdc6'
dps_billing_id = '0000080023225598'
def setUp(self):
self.facade = Facade()
self.card = Bankcard(card_number=CARD_VISA,
expiry_date='1015',
name="Frankie", cvv="123",
start_date="1010")
def test_successful_call_returns_valid_dict(self):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_SUCCESSFUL_RESPONSE)
auth_dict = self.facade.authorise('1000', 1, self.card)
complete_dict = self.facade.complete('1000', 1.23,
self.dps_txn_ref)
refund_dict = self.facade.refund('1000', 1.23, '000000030884cdc6')
validate_dict = self.facade.validate(self.card)
response_dicts = (auth_dict, complete_dict, refund_dict,
validate_dict)
for response_dict in response_dicts:
self.assertEquals(self.dps_txn_ref,
response_dict['txn_reference'])
self.assertEquals(self.dps_billing_id,
response_dict['partner_reference'])
def test_purchase_with_billing_id_returns_valid_dict(self):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_SUCCESSFUL_RESPONSE)
txn_ref = self.facade.purchase('1000', 1.23, 'abc123')
self.assertEquals(self.dps_txn_ref, txn_ref['txn_reference'])
def test_purchase_with_bankcard_returns_valid_dict(self):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_SUCCESSFUL_RESPONSE)
txn_ref = self.facade.purchase('1000', 1.23, None, self.card)
self.assertEquals(self.dps_txn_ref, txn_ref['txn_reference'])
def test_successful_call_is_recorded(self):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_SUCCESSFUL_RESPONSE)
self.facade.authorise('10001', 10.25, self.card)
txn = OrderTransaction.objects.filter(order_number='10001')[0]
self.assertEquals(AUTH, txn.txn_type)
def test_empty_issue_date_is_allowed(self):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_SUCCESSFUL_RESPONSE)
card = Bankcard(card_number=CARD_VISA,
expiry_date='1015',
name="Frankie", cvv="123")
txn_ref = self.facade.authorise('1000', 1.23, card)
self.assertEquals(self.dps_txn_ref, txn_ref['txn_reference'])
class FacadeDeclinedResponseTests(MockedResponseTestCase):
def setUp(self):
self.facade = Facade()
self.card = Bankcard(card_number=CARD_VISA,
expiry_date='1015',
name="Frankie", cvv="123",
start_date="1010")
def test_declined_call_raises_an_exception(self):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_DECLINED_RESPONSE)
with self.assertRaises(UnableToTakePayment):
self.facade.authorise('1000', 1, self.card)
with self.assertRaises(UnableToTakePayment):
self.facade.complete('1000', 1.23, '000000030884cdc6')
with self.assertRaises(UnableToTakePayment):
self.facade.purchase('1000', 1.23, 'abc123')
with self.assertRaises(UnableToTakePayment):
self.facade.purchase('1000', 1.23, None, self.card)
with self.assertRaises(UnableToTakePayment):
self.facade.refund('1000', 1.23, '000000030884cdc6')
with self.assertRaises(UnableToTakePayment):
self.facade.validate(self.card)
def test_declined_call_is_recorded(self):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_DECLINED_RESPONSE)
try:
self.facade.purchase('1001', 10.24, None, self.card)
except Exception:
pass
txn = OrderTransaction.objects.filter(order_number='1001')[0]
self.assertIsNotNone(txn)
self.assertEquals(PURCHASE, txn.txn_type)
class FacadeErrorResponseTests(MockedResponseTestCase):
def setUp(self):
self.facade = Facade()
self.card = Bankcard(card_number=CARD_VISA,
expiry_date='1015',
name="Frankie", cvv="123",
start_date="1010")
def test_error_response_raises_invalid_gateway_request_exception(self):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_ERROR_RESPONSE)
with self.assertRaises(InvalidGatewayRequestError):
self.facade.purchase('1000', 10.24, None, self.card)
| django-oscar/django-oscar-paymentexpress | tests/facade_tests.py | Python | bsd-3-clause | 7,334 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
/**
* Extension ID of gallery app.
* @type {string}
* @const
*/
var GALLERY_APP_ID = 'nlkncpkkdoccmpiclbokaimcnedabhhm';
var gallery = new RemoteCallGallery(GALLERY_APP_ID);
/**
* Launches the gallery with the given entries.
*
* @param {string} testVolumeName Test volume name passed to the addEntries
* function. Either 'drive' or 'local'.
* @param {VolumeManagerCommon.VolumeType} volumeType Volume type.
* @param {Array<TestEntryInfo>} entries Entries to be parepared and passed to
* the application.
* @param {Array<TestEntryInfo>=} opt_selected Entries to be selected. Should
* be a sub-set of the entries argument.
* @return {Promise} Promise to be fulfilled with the data of the main element
* in the allery.
*/
function launch(testVolumeName, volumeType, entries, opt_selected) {
var entriesPromise = addEntries([testVolumeName], entries).then(function() {
var selectedEntries = opt_selected || entries;
var selectedEntryNames = selectedEntries.map(function(entry) {
return entry.nameText;
});
return gallery.callRemoteTestUtil(
'getFilesUnderVolume', null, [volumeType, selectedEntryNames]);
});
var appId = null;
var urls = [];
return entriesPromise.then(function(result) {
urls = result;
return gallery.callRemoteTestUtil('openGallery', null, [urls]);
}).then(function(windowId) {
chrome.test.assertTrue(!!windowId);
appId = windowId;
return gallery.waitForElement(appId, 'div.gallery');
}).then(function(args) {
return {
appId: appId,
mailElement: args[0],
urls: urls,
};
});
}
/**
* Namespace for test cases.
*/
var testcase = {};
/**
* When the FileManagerBrowserTest harness loads this test extension, request
* configuration and other details from that harness, including the test case
* name to run. Use the configuration/details to setup the test ennvironment,
* then run the test case using chrome.test.RunTests.
*/
window.addEventListener('load', function() {
var steps = [
// Request the guest mode state.
function() {
sendBrowserTestCommand({name: 'isInGuestMode'}, steps.shift());
},
// Request the root entry paths.
function(mode) {
if (JSON.parse(mode) != chrome.extension.inIncognitoContext) {
return;
}
sendBrowserTestCommand({name: 'getRootPaths'}, steps.shift());
},
// Request the test case name.
function(paths) {
var roots = JSON.parse(paths);
RootPath.DOWNLOADS = roots.downloads;
RootPath.DRIVE = roots.drive;
sendBrowserTestCommand({name: 'getTestName'}, steps.shift());
},
// Run the test case.
function(testCaseName) {
// Get the test function from testcase namespace testCaseName.
var test = testcase[testCaseName];
// Verify test is an unnamed (aka 'anonymous') Function.
if (!(test instanceof Function) || test.name) {
chrome.test.fail('[' + testCaseName + '] not found.');
return;
}
// Define the test case and its name for chrome.test logging.
test.generatedName = testCaseName;
var testCaseSymbol = Symbol(testCaseName);
var testCase = {
[testCaseSymbol] :() => {
return testPromiseAndApps(test(), [gallery]);
},
};
// Run the test.
chrome.test.runTests([testCase[testCaseSymbol]]);
}
];
steps.shift()();
});
| endlessm/chromium-browser | ui/file_manager/integration_tests/gallery/background.js | JavaScript | bsd-3-clause | 3,593 |
# Rocksdb Change Log
## Unreleased
### Public API Change
* Options::max_bytes_for_level_multiplier is now a double along with all getters and setters.
### New Features
* Add avoid_flush_during_shutdown option, which speeds up DB shutdown by not flushing unpersisted data (i.e. with disableWAL = true). Unpersisted data will be lost. The options is dynamically changeable.
## 4.13.0 (10/18/2016)
### Public API Change
* DB::GetOptions() reflect dynamic changed options (i.e. through DB::SetOptions()) and return copy of options instead of reference.
* Added Statistics::getAndResetTickerCount().
### New Features
* Add DB::SetDBOptions() to dynamic change base_background_compactions and max_background_compactions.
* Added Iterator::SeekForPrev(). This new API will seek to the last key that less than or equal to the target key.
## 4.12.0 (9/12/2016)
### Public API Change
* CancelAllBackgroundWork() flushes all memtables for databases containing writes that have bypassed the WAL (writes issued with WriteOptions::disableWAL=true) before shutting down background threads.
* Merge options source_compaction_factor, max_grandparent_overlap_bytes and expanded_compaction_factor into max_compaction_bytes.
* Remove ImmutableCFOptions.
* Add a compression type ZSTD, which can work with ZSTD 0.8.0 or up. Still keep ZSTDNotFinal for compatibility reasons.
### New Features
* Introduce NewClockCache, which is based on CLOCK algorithm with better concurrent performance in some cases. It can be used to replace the default LRU-based block cache and table cache. To use it, RocksDB need to be linked with TBB lib.
* Change ticker/histogram statistics implementations to accumulate data in thread-local storage, which improves CPU performance by reducing cache coherency costs. Callers of CreateDBStatistics do not need to change anything to use this feature.
* Block cache mid-point insertion, where index and filter block are inserted into LRU block cache with higher priority. The feature can be enabled by setting BlockBasedTableOptions::cache_index_and_filter_blocks_with_high_priority to true and high_pri_pool_ratio > 0 when creating NewLRUCache.
## 4.11.0 (8/1/2016)
### Public API Change
* options.memtable_prefix_bloom_huge_page_tlb_size => memtable_huge_page_size. When it is set, RocksDB will try to allocate memory from huge page for memtable too, rather than just memtable bloom filter.
### New Features
* A tool to migrate DB after options change. See include/rocksdb/utilities/option_change_migration.h.
* Add ReadOptions.background_purge_on_iterator_cleanup. If true, we avoid file deletion when destorying iterators.
## 4.10.0 (7/5/2016)
### Public API Change
* options.memtable_prefix_bloom_bits changes to options.memtable_prefix_bloom_bits_ratio and deprecate options.memtable_prefix_bloom_probes
* enum type CompressionType and PerfLevel changes from char to unsigned char. Value of all PerfLevel shift by one.
* Deprecate options.filter_deletes.
### New Features
* Add avoid_flush_during_recovery option.
* Add a read option background_purge_on_iterator_cleanup to avoid deleting files in foreground when destroying iterators. Instead, a job is scheduled in high priority queue and would be executed in a separate background thread.
* RepairDB support for column families. RepairDB now associates data with non-default column families using information embedded in the SST/WAL files (4.7 or later). For data written by 4.6 or earlier, RepairDB associates it with the default column family.
* Add options.write_buffer_manager which allows users to control total memtable sizes across multiple DB instances.
## 4.9.0 (6/9/2016)
### Public API changes
* Add bottommost_compression option, This option can be used to set a specific compression algorithm for the bottommost level (Last level containing files in the DB).
* Introduce CompactionJobInfo::compression, This field state the compression algorithm used to generate the output files of the compaction.
* Deprecate BlockBaseTableOptions.hash_index_allow_collision=false
* Deprecate options builder (GetOptions()).
### New Features
* Introduce NewSimCache() in rocksdb/utilities/sim_cache.h. This function creates a block cache that is able to give simulation results (mainly hit rate) of simulating block behavior with a configurable cache size.
## 4.8.0 (5/2/2016)
### Public API Change
* Allow preset compression dictionary for improved compression of block-based tables. This is supported for zlib, zstd, and lz4. The compression dictionary's size is configurable via CompressionOptions::max_dict_bytes.
* Delete deprecated classes for creating backups (BackupableDB) and restoring from backups (RestoreBackupableDB). Now, BackupEngine should be used for creating backups, and BackupEngineReadOnly should be used for restorations. For more details, see https://github.com/facebook/rocksdb/wiki/How-to-backup-RocksDB%3F
* Expose estimate of per-level compression ratio via DB property: "rocksdb.compression-ratio-at-levelN".
* Added EventListener::OnTableFileCreationStarted. EventListener::OnTableFileCreated will be called on failure case. User can check creation status via TableFileCreationInfo::status.
### New Features
* Add ReadOptions::readahead_size. If non-zero, NewIterator will create a new table reader which performs reads of the given size.
## 4.7.0 (4/8/2016)
### Public API Change
* rename options compaction_measure_io_stats to report_bg_io_stats and include flush too.
* Change some default options. Now default options will optimize for server-workloads. Also enable slowdown and full stop triggers for pending compaction bytes. These changes may cause sub-optimal performance or significant increase of resource usage. To avoid these risks, users can open existing RocksDB with options extracted from RocksDB option files. See https://github.com/facebook/rocksdb/wiki/RocksDB-Options-File for how to use RocksDB option files. Or you can call Options.OldDefaults() to recover old defaults. DEFAULT_OPTIONS_HISTORY.md will track change history of default options.
## 4.6.0 (3/10/2016)
### Public API Changes
* Change default of BlockBasedTableOptions.format_version to 2. It means default DB created by 4.6 or up cannot be opened by RocksDB version 3.9 or earlier.
* Added strict_capacity_limit option to NewLRUCache. If the flag is set to true, insert to cache will fail if no enough capacity can be free. Signature of Cache::Insert() is updated accordingly.
* Tickers [NUMBER_DB_NEXT, NUMBER_DB_PREV, NUMBER_DB_NEXT_FOUND, NUMBER_DB_PREV_FOUND, ITER_BYTES_READ] are not updated immediately. The are updated when the Iterator is deleted.
* Add monotonically increasing counter (DB property "rocksdb.current-super-version-number") that increments upon any change to the LSM tree.
### New Features
* Add CompactionPri::kMinOverlappingRatio, a compaction picking mode friendly to write amplification.
* Deprecate Iterator::IsKeyPinned() and replace it with Iterator::GetProperty() with prop_name="rocksdb.iterator.is.key.pinned"
## 4.5.0 (2/5/2016)
### Public API Changes
* Add a new perf context level between kEnableCount and kEnableTime. Level 2 now does not include timers for mutexes.
* Statistics of mutex operation durations will not be measured by default. If you want to have them enabled, you need to set Statistics::stats_level_ to kAll.
* DBOptions::delete_scheduler and NewDeleteScheduler() are removed, please use DBOptions::sst_file_manager and NewSstFileManager() instead
### New Features
* ldb tool now supports operations to non-default column families.
* Add kPersistedTier to ReadTier. This option allows Get and MultiGet to read only the persited data and skip mem-tables if writes were done with disableWAL = true.
* Add DBOptions::sst_file_manager. Use NewSstFileManager() in include/rocksdb/sst_file_manager.h to create a SstFileManager that can be used to track the total size of SST files and control the SST files deletion rate.
## 4.4.0 (1/14/2016)
### Public API Changes
* Change names in CompactionPri and add a new one.
* Deprecate options.soft_rate_limit and add options.soft_pending_compaction_bytes_limit.
* If options.max_write_buffer_number > 3, writes will be slowed down when writing to the last write buffer to delay a full stop.
* Introduce CompactionJobInfo::compaction_reason, this field include the reason to trigger the compaction.
* After slow down is triggered, if estimated pending compaction bytes keep increasing, slowdown more.
* Increase default options.delayed_write_rate to 2MB/s.
* Added a new parameter --path to ldb tool. --path accepts the name of either MANIFEST, SST or a WAL file. Either --db or --path can be used when calling ldb.
## 4.3.0 (12/8/2015)
### New Features
* CompactionFilter has new member function called IgnoreSnapshots which allows CompactionFilter to be called even if there are snapshots later than the key.
* RocksDB will now persist options under the same directory as the RocksDB database on successful DB::Open, CreateColumnFamily, DropColumnFamily, and SetOptions.
* Introduce LoadLatestOptions() in rocksdb/utilities/options_util.h. This function can construct the latest DBOptions / ColumnFamilyOptions used by the specified RocksDB intance.
* Introduce CheckOptionsCompatibility() in rocksdb/utilities/options_util.h. This function checks whether the input set of options is able to open the specified DB successfully.
### Public API Changes
* When options.db_write_buffer_size triggers, only the column family with the largest column family size will be flushed, not all the column families.
## 4.2.0 (11/9/2015)
### New Features
* Introduce CreateLoggerFromOptions(), this function create a Logger for provided DBOptions.
* Add GetAggregatedIntProperty(), which returns the sum of the GetIntProperty of all the column families.
* Add MemoryUtil in rocksdb/utilities/memory.h. It currently offers a way to get the memory usage by type from a list rocksdb instances.
### Public API Changes
* CompactionFilter::Context includes information of Column Family ID
* The need-compaction hint given by TablePropertiesCollector::NeedCompact() will be persistent and recoverable after DB recovery. This introduces a breaking format change. If you use this experimental feature, including NewCompactOnDeletionCollectorFactory() in the new version, you may not be able to directly downgrade the DB back to version 4.0 or lower.
* TablePropertiesCollectorFactory::CreateTablePropertiesCollector() now takes an option Context, containing the information of column family ID for the file being written.
* Remove DefaultCompactionFilterFactory.
## 4.1.0 (10/8/2015)
### New Features
* Added single delete operation as a more efficient way to delete keys that have not been overwritten.
* Added experimental AddFile() to DB interface that allow users to add files created by SstFileWriter into an empty Database, see include/rocksdb/sst_file_writer.h and DB::AddFile() for more info.
* Added support for opening SST files with .ldb suffix which enables opening LevelDB databases.
* CompactionFilter now supports filtering of merge operands and merge results.
### Public API Changes
* Added SingleDelete() to the DB interface.
* Added AddFile() to DB interface.
* Added SstFileWriter class.
* CompactionFilter has a new method FilterMergeOperand() that RocksDB applies to every merge operand during compaction to decide whether to filter the operand.
* We removed CompactionFilterV2 interfaces from include/rocksdb/compaction_filter.h. The functionality was deprecated already in version 3.13.
## 4.0.0 (9/9/2015)
### New Features
* Added support for transactions. See include/rocksdb/utilities/transaction.h for more info.
* DB::GetProperty() now accepts "rocksdb.aggregated-table-properties" and "rocksdb.aggregated-table-properties-at-levelN", in which case it returns aggregated table properties of the target column family, or the aggregated table properties of the specified level N if the "at-level" version is used.
* Add compression option kZSTDNotFinalCompression for people to experiment ZSTD although its format is not finalized.
* We removed the need for LATEST_BACKUP file in BackupEngine. We still keep writing it when we create new backups (because of backward compatibility), but we don't read it anymore.
### Public API Changes
* Removed class Env::RandomRWFile and Env::NewRandomRWFile().
* Renamed DBOptions.num_subcompactions to DBOptions.max_subcompactions to make the name better match the actual functionality of the option.
* Added Equal() method to the Comparator interface that can optionally be overwritten in cases where equality comparisons can be done more efficiently than three-way comparisons.
* Previous 'experimental' OptimisticTransaction class has been replaced by Transaction class.
## 3.13.0 (8/6/2015)
### New Features
* RollbackToSavePoint() in WriteBatch/WriteBatchWithIndex
* Add NewCompactOnDeletionCollectorFactory() in utilities/table_properties_collectors, which allows rocksdb to mark a SST file as need-compaction when it observes at least D deletion entries in any N consecutive entries in that SST file. Note that this feature depends on an experimental NeedCompact() API --- the result of this API will not persist after DB restart.
* Add DBOptions::delete_scheduler. Use NewDeleteScheduler() in include/rocksdb/delete_scheduler.h to create a DeleteScheduler that can be shared among multiple RocksDB instances to control the file deletion rate of SST files that exist in the first db_path.
### Public API Changes
* Deprecated WriteOptions::timeout_hint_us. We no longer support write timeout. If you really need this option, talk to us and we might consider returning it.
* Deprecated purge_redundant_kvs_while_flush option.
* Removed BackupEngine::NewBackupEngine() and NewReadOnlyBackupEngine() that were deprecated in RocksDB 3.8. Please use BackupEngine::Open() instead.
* Deprecated Compaction Filter V2. We are not aware of any existing use-cases. If you use this filter, your compile will break with RocksDB 3.13. Please let us know if you use it and we'll put it back in RocksDB 3.14.
* Env::FileExists now returns a Status instead of a boolean
* Add statistics::getHistogramString() to print detailed distribution of a histogram metric.
* Add DBOptions::skip_stats_update_on_db_open. When it is on, DB::Open() will run faster as it skips the random reads required for loading necessary stats from SST files to optimize compaction.
## 3.12.0 (7/2/2015)
### New Features
* Added experimental support for optimistic transactions. See include/rocksdb/utilities/optimistic_transaction.h for more info.
* Added a new way to report QPS from db_bench (check out --report_file and --report_interval_seconds)
* Added a cache for individual rows. See DBOptions::row_cache for more info.
* Several new features on EventListener (see include/rocksdb/listener.h):
- OnCompationCompleted() now returns per-compaciton job statistics, defined in include/rocksdb/compaction_job_stats.h.
- Added OnTableFileCreated() and OnTableFileDeleted().
* Add compaction_options_universal.enable_trivial_move to true, to allow trivial move while performing universal compaction. Trivial move will happen only when all the input files are non overlapping.
### Public API changes
* EventListener::OnFlushCompleted() now passes FlushJobInfo instead of a list of parameters.
* DB::GetDbIdentity() is now a const function. If this function is overridden in your application, be sure to also make GetDbIdentity() const to avoid compile error.
* Move listeners from ColumnFamilyOptions to DBOptions.
* Add max_write_buffer_number_to_maintain option
* DB::CompactRange()'s parameter reduce_level is changed to change_level, to allow users to move levels to lower levels if allowed. It can be used to migrate a DB from options.level_compaction_dynamic_level_bytes=false to options.level_compaction_dynamic_level_bytes.true.
* Change default value for options.compaction_filter_factory and options.compaction_filter_factory_v2 to nullptr instead of DefaultCompactionFilterFactory and DefaultCompactionFilterFactoryV2.
* If CancelAllBackgroundWork is called without doing a flush after doing loads with WAL disabled, the changes which haven't been flushed before the call to CancelAllBackgroundWork will be lost.
* WBWIIterator::Entry() now returns WriteEntry instead of `const WriteEntry&`
* options.hard_rate_limit is deprecated.
* When options.soft_rate_limit or options.level0_slowdown_writes_trigger is triggered, the way to slow down writes is changed to: write rate to DB is limited to to options.delayed_write_rate.
* DB::GetApproximateSizes() adds a parameter to allow the estimation to include data in mem table, with default to be not to include. It is now only supported in skip list mem table.
* DB::CompactRange() now accept CompactRangeOptions instead of multiple parameters. CompactRangeOptions is defined in include/rocksdb/options.h.
* CompactRange() will now skip bottommost level compaction for level based compaction if there is no compaction filter, bottommost_level_compaction is introduced in CompactRangeOptions to control when it's possible to skip bottommost level compaction. This mean that if you want the compaction to produce a single file you need to set bottommost_level_compaction to BottommostLevelCompaction::kForce.
* Add Cache.GetPinnedUsage() to get the size of memory occupied by entries that are in use by the system.
* DB:Open() will fail if the compression specified in Options is not linked with the binary. If you see this failure, recompile RocksDB with compression libraries present on your system. Also, previously our default compression was snappy. This behavior is now changed. Now, the default compression is snappy only if it's available on the system. If it isn't we change the default to kNoCompression.
* We changed how we account for memory used in block cache. Previously, we only counted the sum of block sizes currently present in block cache. Now, we count the actual memory usage of the blocks. For example, a block of size 4.5KB will use 8KB memory with jemalloc. This might decrease your memory usage and possibly decrease performance. Increase block cache size if you see this happening after an upgrade.
* Add BackupEngineImpl.options_.max_background_operations to specify the maximum number of operations that may be performed in parallel. Add support for parallelized backup and restore.
* Add DB::SyncWAL() that does a WAL sync without blocking writers.
## 3.11.0 (5/19/2015)
### New Features
* Added a new API Cache::SetCapacity(size_t capacity) to dynamically change the maximum configured capacity of the cache. If the new capacity is less than the existing cache usage, the implementation will try to lower the usage by evicting the necessary number of elements following a strict LRU policy.
* Added an experimental API for handling flashcache devices (blacklists background threads from caching their reads) -- NewFlashcacheAwareEnv
* If universal compaction is used and options.num_levels > 1, compact files are tried to be stored in none-L0 with smaller files based on options.target_file_size_base. The limitation of DB size when using universal compaction is greatly mitigated by using more levels. You can set num_levels = 1 to make universal compaction behave as before. If you set num_levels > 1 and want to roll back to a previous version, you need to compact all files to a big file in level 0 (by setting target_file_size_base to be large and CompactRange(<cf_handle>, nullptr, nullptr, true, 0) and reopen the DB with the same version to rewrite the manifest, and then you can open it using previous releases.
* More information about rocksdb background threads are available in Env::GetThreadList(), including the number of bytes read / written by a compaction job, mem-table size and current number of bytes written by a flush job and many more. Check include/rocksdb/thread_status.h for more detail.
### Public API changes
* TablePropertiesCollector::AddUserKey() is added to replace TablePropertiesCollector::Add(). AddUserKey() exposes key type, sequence number and file size up to now to users.
* DBOptions::bytes_per_sync used to apply to both WAL and table files. As of 3.11 it applies only to table files. If you want to use this option to sync WAL in the background, please use wal_bytes_per_sync
## 3.10.0 (3/24/2015)
### New Features
* GetThreadStatus() is now able to report detailed thread status, including:
- Thread Operation including flush and compaction.
- The stage of the current thread operation.
- The elapsed time in micros since the current thread operation started.
More information can be found in include/rocksdb/thread_status.h. In addition, when running db_bench with --thread_status_per_interval, db_bench will also report thread status periodically.
* Changed the LRU caching algorithm so that referenced blocks (by iterators) are never evicted. This change made parameter removeScanCountLimit obsolete. Because of that NewLRUCache doesn't take three arguments anymore. table_cache_remove_scan_limit option is also removed
* By default we now optimize the compilation for the compilation platform (using -march=native). If you want to build portable binary, use 'PORTABLE=1' before the make command.
* We now allow level-compaction to place files in different paths by
specifying them in db_paths along with the target_size.
Lower numbered levels will be placed earlier in the db_paths and higher
numbered levels will be placed later in the db_paths vector.
* Potentially big performance improvements if you're using RocksDB with lots of column families (100-1000)
* Added BlockBasedTableOptions.format_version option, which allows user to specify which version of block based table he wants. As a general guideline, newer versions have more features, but might not be readable by older versions of RocksDB.
* Added new block based table format (version 2), which you can enable by setting BlockBasedTableOptions.format_version = 2. This format changes how we encode size information in compressed blocks and should help with memory allocations if you're using Zlib or BZip2 compressions.
* MemEnv (env that stores data in memory) is now available in default library build. You can create it by calling NewMemEnv().
* Add SliceTransform.SameResultWhenAppended() to help users determine it is safe to apply prefix bloom/hash.
* Block based table now makes use of prefix bloom filter if it is a full fulter.
* Block based table remembers whether a whole key or prefix based bloom filter is supported in SST files. Do a sanity check when reading the file with users' configuration.
* Fixed a bug in ReadOnlyBackupEngine that deleted corrupted backups in some cases, even though the engine was ReadOnly
* options.level_compaction_dynamic_level_bytes, a feature to allow RocksDB to pick dynamic base of bytes for levels. With this feature turned on, we will automatically adjust max bytes for each level. The goal of this feature is to have lower bound on size amplification. For more details, see comments in options.h.
* Added an abstract base class WriteBatchBase for write batches
* Fixed a bug where we start deleting files of a dropped column families even if there are still live references to it
### Public API changes
* Deprecated skip_log_error_on_recovery and table_cache_remove_scan_count_limit options.
* Logger method logv with log level parameter is now virtual
### RocksJava
* Added compression per level API.
* MemEnv is now available in RocksJava via RocksMemEnv class.
* lz4 compression is now included in rocksjava static library when running `make rocksdbjavastatic`.
* Overflowing a size_t when setting rocksdb options now throws an IllegalArgumentException, which removes the necessity for a developer to catch these Exceptions explicitly.
## 3.9.0 (12/8/2014)
### New Features
* Add rocksdb::GetThreadList(), which in the future will return the current status of all
rocksdb-related threads. We will have more code instruments in the following RocksDB
releases.
* Change convert function in rocksdb/utilities/convenience.h to return Status instead of boolean.
Also add support for nested options in convert function
### Public API changes
* New API to create a checkpoint added. Given a directory name, creates a new
database which is an image of the existing database.
* New API LinkFile added to Env. If you implement your own Env class, an
implementation of the API LinkFile will have to be provided.
* MemTableRep takes MemTableAllocator instead of Arena
### Improvements
* RocksDBLite library now becomes smaller and will be compiled with -fno-exceptions flag.
## 3.8.0 (11/14/2014)
### Public API changes
* BackupEngine::NewBackupEngine() was deprecated; please use BackupEngine::Open() from now on.
* BackupableDB/RestoreBackupableDB have new GarbageCollect() methods, which will clean up files from corrupt and obsolete backups.
* BackupableDB/RestoreBackupableDB have new GetCorruptedBackups() methods which list corrupt backups.
### Cleanup
* Bunch of code cleanup, some extra warnings turned on (-Wshadow, -Wshorten-64-to-32, -Wnon-virtual-dtor)
### New features
* CompactFiles and EventListener, although they are still in experimental state
* Full ColumnFamily support in RocksJava.
## 3.7.0 (11/6/2014)
### Public API changes
* Introduce SetOptions() API to allow adjusting a subset of options dynamically online
* Introduce 4 new convenient functions for converting Options from string: GetColumnFamilyOptionsFromMap(), GetColumnFamilyOptionsFromString(), GetDBOptionsFromMap(), GetDBOptionsFromString()
* Remove WriteBatchWithIndex.Delete() overloads using SliceParts
* When opening a DB, if options.max_background_compactions is larger than the existing low pri pool of options.env, it will enlarge it. Similarly, options.max_background_flushes is larger than the existing high pri pool of options.env, it will enlarge it.
## 3.6.0 (10/7/2014)
### Disk format changes
* If you're using RocksDB on ARM platforms and you're using default bloom filter, there is a disk format change you need to be aware of. There are three steps you need to do when you convert to new release: 1. turn off filter policy, 2. compact the whole database, 3. turn on filter policy
### Behavior changes
* We have refactored our system of stalling writes. Any stall-related statistics' meanings are changed. Instead of per-write stall counts, we now count stalls per-epoch, where epochs are periods between flushes and compactions. You'll find more information in our Tuning Perf Guide once we release RocksDB 3.6.
* When disableDataSync=true, we no longer sync the MANIFEST file.
* Add identity_as_first_hash property to CuckooTable. SST file needs to be rebuilt to be opened by reader properly.
### Public API changes
* Change target_file_size_base type to uint64_t from int.
* Remove allow_thread_local. This feature was proved to be stable, so we are turning it always-on.
## 3.5.0 (9/3/2014)
### New Features
* Add include/utilities/write_batch_with_index.h, providing a utility class to query data out of WriteBatch when building it.
* Move BlockBasedTable related options to BlockBasedTableOptions from Options. Change corresponding JNI interface. Options affected include:
no_block_cache, block_cache, block_cache_compressed, block_size, block_size_deviation, block_restart_interval, filter_policy, whole_key_filtering. filter_policy is changed to shared_ptr from a raw pointer.
* Remove deprecated options: disable_seek_compaction and db_stats_log_interval
* OptimizeForPointLookup() takes one parameter for block cache size. It now builds hash index, bloom filter, and block cache.
### Public API changes
* The Prefix Extractor used with V2 compaction filters is now passed user key to SliceTransform::Transform instead of unparsed RocksDB key.
## 3.4.0 (8/18/2014)
### New Features
* Support Multiple DB paths in universal style compactions
* Add feature of storing plain table index and bloom filter in SST file.
* CompactRange() will never output compacted files to level 0. This used to be the case when all the compaction input files were at level 0.
* Added iterate_upper_bound to define the extent upto which the forward iterator will return entries. This will prevent iterating over delete markers and overwritten entries for edge cases where you want to break out the iterator anyways. This may improve performance in case there are a large number of delete markers or overwritten entries.
### Public API changes
* DBOptions.db_paths now is a vector of a DBPath structure which indicates both of path and target size
* NewPlainTableFactory instead of bunch of parameters now accepts PlainTableOptions, which is defined in include/rocksdb/table.h
* Moved include/utilities/*.h to include/rocksdb/utilities/*.h
* Statistics APIs now take uint32_t as type instead of Tickers. Also make two access functions getTickerCount and histogramData const
* Add DB property rocksdb.estimate-num-keys, estimated number of live keys in DB.
* Add DB::GetIntProperty(), which returns DB properties that are integer as uint64_t.
* The Prefix Extractor used with V2 compaction filters is now passed user key to SliceTransform::Transform instead of unparsed RocksDB key.
## 3.3.0 (7/10/2014)
### New Features
* Added JSON API prototype.
* HashLinklist reduces performance outlier caused by skewed bucket by switching data in the bucket from linked list to skip list. Add parameter threshold_use_skiplist in NewHashLinkListRepFactory().
* RocksDB is now able to reclaim storage space more effectively during the compaction process. This is done by compensating the size of each deletion entry by the 2X average value size, which makes compaction to be triggered by deletion entries more easily.
* Add TimeOut API to write. Now WriteOptions have a variable called timeout_hint_us. With timeout_hint_us set to non-zero, any write associated with this timeout_hint_us may be aborted when it runs longer than the specified timeout_hint_us, and it is guaranteed that any write completes earlier than the specified time-out will not be aborted due to the time-out condition.
* Add a rate_limiter option, which controls total throughput of flush and compaction. The throughput is specified in bytes/sec. Flush always has precedence over compaction when available bandwidth is constrained.
### Public API changes
* Removed NewTotalOrderPlainTableFactory because it is not used and implemented semantically incorrect.
## 3.2.0 (06/20/2014)
### Public API changes
* We removed seek compaction as a concept from RocksDB because:
1) It makes more sense for spinning disk workloads, while RocksDB is primarily designed for flash and memory,
2) It added some complexity to the important code-paths,
3) None of our internal customers were really using it.
Because of that, Options::disable_seek_compaction is now obsolete. It is still a parameter in Options, so it does not break the build, but it does not have any effect. We plan to completely remove it at some point, so we ask users to please remove this option from your code base.
* Add two parameters to NewHashLinkListRepFactory() for logging on too many entries in a hash bucket when flushing.
* Added new option BlockBasedTableOptions::hash_index_allow_collision. When enabled, prefix hash index for block-based table will not store prefix and allow hash collision, reducing memory consumption.
### New Features
* PlainTable now supports a new key encoding: for keys of the same prefix, the prefix is only written once. It can be enabled through encoding_type parameter of NewPlainTableFactory()
* Add AdaptiveTableFactory, which is used to convert from a DB of PlainTable to BlockBasedTabe, or vise versa. It can be created using NewAdaptiveTableFactory()
### Performance Improvements
* Tailing Iterator re-implemeted with ForwardIterator + Cascading Search Hint , see ~20% throughput improvement.
## 3.1.0 (05/21/2014)
### Public API changes
* Replaced ColumnFamilyOptions::table_properties_collectors with ColumnFamilyOptions::table_properties_collector_factories
### New Features
* Hash index for block-based table will be materialized and reconstructed more efficiently. Previously hash index is constructed by scanning the whole table during every table open.
* FIFO compaction style
## 3.0.0 (05/05/2014)
### Public API changes
* Added _LEVEL to all InfoLogLevel enums
* Deprecated ReadOptions.prefix and ReadOptions.prefix_seek. Seek() defaults to prefix-based seek when Options.prefix_extractor is supplied. More detail is documented in https://github.com/facebook/rocksdb/wiki/Prefix-Seek-API-Changes
* MemTableRepFactory::CreateMemTableRep() takes info logger as an extra parameter.
### New Features
* Column family support
* Added an option to use different checksum functions in BlockBasedTableOptions
* Added ApplyToAllCacheEntries() function to Cache
## 2.8.0 (04/04/2014)
* Removed arena.h from public header files.
* By default, checksums are verified on every read from database
* Change default value of several options, including: paranoid_checks=true, max_open_files=5000, level0_slowdown_writes_trigger=20, level0_stop_writes_trigger=24, disable_seek_compaction=true, max_background_flushes=1 and allow_mmap_writes=false
* Added is_manual_compaction to CompactionFilter::Context
* Added "virtual void WaitForJoin()" in class Env. Default operation is no-op.
* Removed BackupEngine::DeleteBackupsNewerThan() function
* Added new option -- verify_checksums_in_compaction
* Changed Options.prefix_extractor from raw pointer to shared_ptr (take ownership)
Changed HashSkipListRepFactory and HashLinkListRepFactory constructor to not take SliceTransform object (use Options.prefix_extractor implicitly)
* Added Env::GetThreadPoolQueueLen(), which returns the waiting queue length of thread pools
* Added a command "checkconsistency" in ldb tool, which checks
if file system state matches DB state (file existence and file sizes)
* Separate options related to block based table to a new struct BlockBasedTableOptions.
* WriteBatch has a new function Count() to return total size in the batch, and Data() now returns a reference instead of a copy
* Add more counters to perf context.
* Supports several more DB properties: compaction-pending, background-errors and cur-size-active-mem-table.
### New Features
* If we find one truncated record at the end of the MANIFEST or WAL files,
we will ignore it. We assume that writers of these records were interrupted
and that we can safely ignore it.
* A new SST format "PlainTable" is added, which is optimized for memory-only workloads. It can be created through NewPlainTableFactory() or NewTotalOrderPlainTableFactory().
* A new mem table implementation hash linked list optimizing for the case that there are only few keys for each prefix, which can be created through NewHashLinkListRepFactory().
* Merge operator supports a new function PartialMergeMulti() to allow users to do partial merges against multiple operands.
* Now compaction filter has a V2 interface. It buffers the kv-pairs sharing the same key prefix, process them in batches, and return the batched results back to DB. The new interface uses a new structure CompactionFilterContext for the same purpose as CompactionFilter::Context in V1.
* Geo-spatial support for locations and radial-search.
## 2.7.0 (01/28/2014)
### Public API changes
* Renamed `StackableDB::GetRawDB()` to `StackableDB::GetBaseDB()`.
* Renamed `WriteBatch::Data()` `const std::string& Data() const`.
* Renamed class `TableStats` to `TableProperties`.
* Deleted class `PrefixHashRepFactory`. Please use `NewHashSkipListRepFactory()` instead.
* Supported multi-threaded `EnableFileDeletions()` and `DisableFileDeletions()`.
* Added `DB::GetOptions()`.
* Added `DB::GetDbIdentity()`.
### New Features
* Added [BackupableDB](https://github.com/facebook/rocksdb/wiki/How-to-backup-RocksDB%3F)
* Implemented [TailingIterator](https://github.com/facebook/rocksdb/wiki/Tailing-Iterator), a special type of iterator that
doesn't create a snapshot (can be used to read newly inserted data)
and is optimized for doing sequential reads.
* Added property block for table, which allows (1) a table to store
its metadata and (2) end user to collect and store properties they
are interested in.
* Enabled caching index and filter block in block cache (turned off by default).
* Supported error report when doing manual compaction.
* Supported additional Linux platform flavors and Mac OS.
* Put with `SliceParts` - Variant of `Put()` that gathers output like `writev(2)`
* Bug fixes and code refactor for compatibility with upcoming Column
Family feature.
### Performance Improvements
* Huge benchmark performance improvements by multiple efforts. For example, increase in readonly QPS from about 530k in 2.6 release to 1.1 million in 2.7 [1]
* Speeding up a way RocksDB deleted obsolete files - no longer listing the whole directory under a lock -- decrease in p99
* Use raw pointer instead of shared pointer for statistics: [5b825d](https://github.com/facebook/rocksdb/commit/5b825d6964e26ec3b4bb6faa708ebb1787f1d7bd) -- huge increase in performance -- shared pointers are slow
* Optimized locking for `Get()` -- [1fdb3f](https://github.com/facebook/rocksdb/commit/1fdb3f7dc60e96394e3e5b69a46ede5d67fb976c) -- 1.5x QPS increase for some workloads
* Cache speedup - [e8d40c3](https://github.com/facebook/rocksdb/commit/e8d40c31b3cca0c3e1ae9abe9b9003b1288026a9)
* Implemented autovector, which allocates first N elements on stack. Most of vectors in RocksDB are small. Also, we never want to allocate heap objects while holding a mutex. -- [c01676e4](https://github.com/facebook/rocksdb/commit/c01676e46d3be08c3c140361ef1f5884f47d3b3c)
* Lots of efforts to move malloc, memcpy and IO outside of locks
| wenduo/rocksdb | HISTORY.md | Markdown | bsd-3-clause | 37,976 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/.
import os.path
import sys
from genshi.builder import tag
from trac.admin import IAdminCommandProvider, IAdminPanelProvider
from trac.config import ListOption
from trac.core import *
from trac.perm import IPermissionRequestor
from trac.util import as_bool, is_path_below
from trac.util.compat import any
from trac.util.text import breakable_path, normalize_whitespace, print_table, \
printout
from trac.util.translation import _, ngettext, tag_
from trac.versioncontrol import DbRepositoryProvider, RepositoryManager, \
is_default
from trac.web.chrome import Chrome, add_notice, add_warning
class VersionControlAdmin(Component):
"""trac-admin command provider for version control administration."""
implements(IAdminCommandProvider, IPermissionRequestor)
# IAdminCommandProvider methods
def get_admin_commands(self):
yield ('changeset added', '<repos> <rev> [rev] [...]',
"""Notify trac about changesets added to a repository
This command should be called from a post-commit hook. It will
trigger a cache update and notify components about the addition.
""",
self._complete_repos, self._do_changeset_added)
yield ('changeset modified', '<repos> <rev> [rev] [...]',
"""Notify trac about changesets modified in a repository
This command should be called from a post-revprop hook after
revision properties like the commit message, author or date
have been changed. It will trigger a cache update for the given
revisions and notify components about the change.
""",
self._complete_repos, self._do_changeset_modified)
yield ('repository list', '',
'List source repositories',
None, self._do_list)
yield ('repository resync', '<repos> [rev]',
"""Re-synchronize trac with repositories
When [rev] is specified, only that revision is synchronized.
Otherwise, the complete revision history is synchronized. Note
that this operation can take a long time to complete.
If synchronization gets interrupted, it can be resumed later
using the `sync` command.
To synchronize all repositories, specify "*" as the repository.
""",
self._complete_repos, self._do_resync)
yield ('repository sync', '<repos> [rev]',
"""Resume synchronization of repositories
Similar to `resync`, but doesn't clear the already synchronized
changesets. Useful for resuming an interrupted `resync`.
To synchronize all repositories, specify "*" as the repository.
""",
self._complete_repos, self._do_sync)
def get_reponames(self):
rm = RepositoryManager(self.env)
return [reponame or '(default)' for reponame
in rm.get_all_repositories()]
def _complete_repos(self, args):
if len(args) == 1:
return self.get_reponames()
def _do_changeset_added(self, reponame, *revs):
if is_default(reponame):
reponame = ''
rm = RepositoryManager(self.env)
rm.notify('changeset_added', reponame, revs)
def _do_changeset_modified(self, reponame, *revs):
if is_default(reponame):
reponame = ''
rm = RepositoryManager(self.env)
rm.notify('changeset_modified', reponame, revs)
def _do_list(self):
rm = RepositoryManager(self.env)
values = []
for (reponame, info) in sorted(rm.get_all_repositories().iteritems()):
alias = ''
if 'alias' in info:
alias = info['alias'] or '(default)'
values.append((reponame or '(default)', info.get('type', ''),
alias, info.get('dir', '')))
print_table(values, [_('Name'), _('Type'), _('Alias'), _('Directory')])
def _sync(self, reponame, rev, clean):
rm = RepositoryManager(self.env)
if reponame == '*':
if rev is not None:
raise TracError(_('Cannot synchronize a single revision '
'on multiple repositories'))
repositories = rm.get_real_repositories()
else:
if is_default(reponame):
reponame = ''
repos = rm.get_repository(reponame)
if repos is None:
raise TracError(_("Repository '%(repo)s' not found",
repo=reponame or '(default)'))
if rev is not None:
repos.sync_changeset(rev)
printout(_('%(rev)s resynced on %(reponame)s.', rev=rev,
reponame=repos.reponame or '(default)'))
return
repositories = [repos]
db = self.env.get_db_cnx()
for repos in sorted(repositories, key=lambda r: r.reponame):
printout(_('Resyncing repository history for %(reponame)s... ',
reponame=repos.reponame or '(default)'))
repos.sync(self._sync_feedback, clean=clean)
cursor = db.cursor()
cursor.execute("SELECT count(rev) FROM revision WHERE repos=%s",
(repos.id,))
for cnt, in cursor:
printout(ngettext('%(num)s revision cached.',
'%(num)s revisions cached.', num=cnt))
printout(_('Done.'))
def _sync_feedback(self, rev):
sys.stdout.write(' [%s]\r' % rev)
sys.stdout.flush()
def _do_resync(self, reponame, rev=None):
self._sync(reponame, rev, clean=True)
def _do_sync(self, reponame, rev=None):
self._sync(reponame, rev, clean=False)
# IPermissionRequestor methods
def get_permission_actions(self):
return [('VERSIONCONTROL_ADMIN', ['BROWSER_VIEW', 'CHANGESET_VIEW',
'FILE_VIEW', 'LOG_VIEW'])]
class RepositoryAdminPanel(Component):
"""Web admin panel for repository administration."""
implements(IAdminPanelProvider)
allowed_repository_dir_prefixes = ListOption('versioncontrol',
'allowed_repository_dir_prefixes', '',
doc="""Comma-separated list of allowed prefixes for repository
directories when adding and editing repositories in the repository
admin panel. If the list is empty, all repository directories are
allowed. (''since 0.12.1'')""")
# IAdminPanelProvider methods
def get_admin_panels(self, req):
if 'VERSIONCONTROL_ADMIN' in req.perm:
yield ('versioncontrol', _('Version Control'), 'repository',
_('Repositories'))
def render_admin_panel(self, req, category, page, path_info):
req.perm.require('VERSIONCONTROL_ADMIN')
# Retrieve info for all repositories
rm = RepositoryManager(self.env)
all_repos = rm.get_all_repositories()
db_provider = self.env[DbRepositoryProvider]
if path_info:
# Detail view
reponame = not is_default(path_info) and path_info or ''
info = all_repos.get(reponame)
if info is None:
raise TracError(_("Repository '%(repo)s' not found",
repo=path_info))
if req.method == 'POST':
if req.args.get('cancel'):
req.redirect(req.href.admin(category, page))
elif db_provider and req.args.get('save'):
# Modify repository
changes = {}
for field in db_provider.repository_attrs:
value = normalize_whitespace(req.args.get(field))
if (value is not None or field == 'hidden') \
and value != info.get(field):
changes[field] = value
if 'dir' in changes \
and not self._check_dir(req, changes['dir']):
changes = {}
if changes:
db_provider.modify_repository(reponame, changes)
add_notice(req, _('Your changes have been saved.'))
name = req.args.get('name')
resync = tag.tt('trac-admin $ENV repository resync "%s"'
% (name or '(default)'))
if 'dir' in changes:
msg = tag_('You should now run %(resync)s to '
'synchronize Trac with the repository.',
resync=resync)
add_notice(req, msg)
elif 'type' in changes:
msg = tag_('You may have to run %(resync)s to '
'synchronize Trac with the repository.',
resync=resync)
add_notice(req, msg)
if name and name != path_info and not 'alias' in info:
cset_added = tag.tt('trac-admin $ENV changeset '
'added "%s" $REV'
% (name or '(default)'))
msg = tag_('You will need to update your post-commit '
'hook to call %(cset_added)s with the new '
'repository name.', cset_added=cset_added)
add_notice(req, msg)
if changes:
req.redirect(req.href.admin(category, page))
Chrome(self.env).add_wiki_toolbars(req)
data = {'view': 'detail', 'reponame': reponame}
else:
# List view
if req.method == 'POST':
# Add a repository
if db_provider and req.args.get('add_repos'):
name = req.args.get('name')
type_ = req.args.get('type')
# Avoid errors when copy/pasting paths
dir = normalize_whitespace(req.args.get('dir', ''))
if name is None or type_ is None or not dir:
add_warning(req, _('Missing arguments to add a '
'repository.'))
elif self._check_dir(req, dir):
db_provider.add_repository(name, dir, type_)
name = name or '(default)'
add_notice(req, _('The repository "%(name)s" has been '
'added.', name=name))
resync = tag.tt('trac-admin $ENV repository resync '
'"%s"' % name)
msg = tag_('You should now run %(resync)s to '
'synchronize Trac with the repository.',
resync=resync)
add_notice(req, msg)
cset_added = tag.tt('trac-admin $ENV changeset '
'added "%s" $REV' % name)
msg = tag_('You should also set up a post-commit hook '
'on the repository to call %(cset_added)s '
'for each committed changeset.',
cset_added=cset_added)
add_notice(req, msg)
req.redirect(req.href.admin(category, page))
# Add a repository alias
elif db_provider and req.args.get('add_alias'):
name = req.args.get('name')
alias = req.args.get('alias')
if name is not None and alias is not None:
db_provider.add_alias(name, alias)
add_notice(req, _('The alias "%(name)s" has been '
'added.', name=name or '(default)'))
req.redirect(req.href.admin(category, page))
add_warning(req, _('Missing arguments to add an '
'alias.'))
# Refresh the list of repositories
elif req.args.get('refresh'):
req.redirect(req.href.admin(category, page))
# Remove repositories
elif db_provider and req.args.get('remove'):
sel = req.args.getlist('sel')
if sel:
for name in sel:
db_provider.remove_repository(name)
add_notice(req, _('The selected repositories have '
'been removed.'))
req.redirect(req.href.admin(category, page))
add_warning(req, _('No repositories were selected.'))
data = {'view': 'list'}
# Find repositories that are editable
db_repos = {}
if db_provider is not None:
db_repos = dict(db_provider.get_repositories())
# Prepare common rendering data
repositories = dict((reponame, self._extend_info(reponame, info.copy(),
reponame in db_repos))
for (reponame, info) in all_repos.iteritems())
types = sorted([''] + rm.get_supported_types())
data.update({'types': types, 'default_type': rm.repository_type,
'repositories': repositories})
return 'admin_repositories.html', data
def _extend_info(self, reponame, info, editable):
"""Extend repository info for rendering."""
info['name'] = reponame
if info.get('dir') is not None:
info['prettydir'] = breakable_path(info['dir']) or ''
info['hidden'] = as_bool(info.get('hidden'))
info['editable'] = editable
if not info.get('alias'):
try:
repos = RepositoryManager(self.env).get_repository(reponame)
youngest_rev = repos.get_youngest_rev()
info['rev'] = youngest_rev
info['display_rev'] = repos.display_rev(youngest_rev)
except Exception:
pass
return info
def _check_dir(self, req, dir):
"""Check that a repository directory is valid, and add a warning
message if not.
"""
if not os.path.isabs(dir):
add_warning(req, _('The repository directory must be an absolute '
'path.'))
return False
prefixes = [os.path.join(self.env.path, prefix)
for prefix in self.allowed_repository_dir_prefixes]
if prefixes and not any(is_path_below(dir, prefix)
for prefix in prefixes):
add_warning(req, _('The repository directory must be located '
'below one of the following directories: '
'%(dirs)s', dirs=', '.join(prefixes)))
return False
return True
| zjj/trac_hack | trac/versioncontrol/admin.py | Python | bsd-3-clause | 16,185 |
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gcimporter
import (
"go/build"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"go/types"
)
// skipSpecialPlatforms causes the test to be skipped for platforms where
// builders (build.golang.org) don't have access to compiled packages for
// import.
func skipSpecialPlatforms(t *testing.T) {
switch platform := runtime.GOOS + "-" + runtime.GOARCH; platform {
case "nacl-amd64p32",
"nacl-386",
"darwin-arm",
"darwin-arm64":
t.Skipf("no compiled packages available for import on %s", platform)
}
}
var gcPath string // Go compiler path
func init() {
if char, err := build.ArchChar(runtime.GOARCH); err == nil {
gcPath = filepath.Join(build.ToolDir, char+"g")
return
}
gcPath = "unknown-GOARCH-compiler"
}
func compile(t *testing.T, dirname, filename string) string {
cmd := exec.Command(gcPath, filename)
cmd.Dir = dirname
out, err := cmd.CombinedOutput()
if err != nil {
t.Logf("%s", out)
t.Fatalf("%s %s failed: %s", gcPath, filename, err)
}
archCh, _ := build.ArchChar(runtime.GOARCH)
// filename should end with ".go"
return filepath.Join(dirname, filename[:len(filename)-2]+archCh)
}
// Use the same global imports map for all tests. The effect is
// as if all tested packages were imported into a single package.
var imports = make(map[string]*types.Package)
func testPath(t *testing.T, path string) bool {
t0 := time.Now()
_, err := Import(imports, path)
if err != nil {
t.Errorf("testPath(%s): %s", path, err)
return false
}
t.Logf("testPath(%s): %v", path, time.Since(t0))
return true
}
const maxTime = 30 * time.Second
func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) {
dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir)
list, err := ioutil.ReadDir(dirname)
if err != nil {
t.Fatalf("testDir(%s): %s", dirname, err)
}
for _, f := range list {
if time.Now().After(endTime) {
t.Log("testing time used up")
return
}
switch {
case !f.IsDir():
// try extensions
for _, ext := range pkgExts {
if strings.HasSuffix(f.Name(), ext) {
name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension
if testPath(t, filepath.Join(dir, name)) {
nimports++
}
}
}
case f.IsDir():
nimports += testDir(t, filepath.Join(dir, f.Name()), endTime)
}
}
return
}
func TestImport(t *testing.T) {
// This package only handles gc export data.
if runtime.Compiler != "gc" {
t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
return
}
// On cross-compile builds, the path will not exist.
// Need to use GOHOSTOS, which is not available.
if _, err := os.Stat(gcPath); err != nil {
t.Skipf("skipping test: %v", err)
}
if outFn := compile(t, "testdata", "exports.go"); outFn != "" {
defer os.Remove(outFn)
}
nimports := 0
if testPath(t, "./testdata/exports") {
nimports++
}
nimports += testDir(t, "", time.Now().Add(maxTime)) // installed packages
t.Logf("tested %d imports", nimports)
}
var importedObjectTests = []struct {
name string
want string
}{
{"unsafe.Pointer", "type Pointer unsafe.Pointer"},
{"math.Pi", "const Pi untyped float"},
{"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"},
{"io.ReadWriter", "type ReadWriter interface{Read(p []byte) (n int, err error); Write(p []byte) (n int, err error)}"},
{"math.Sin", "func Sin(x float64) float64"},
// TODO(gri) add more tests
}
func TestImportedTypes(t *testing.T) {
skipSpecialPlatforms(t)
// This package only handles gc export data.
if runtime.Compiler != "gc" {
t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
return
}
for _, test := range importedObjectTests {
s := strings.Split(test.name, ".")
if len(s) != 2 {
t.Fatal("inconsistent test data")
}
importPath := s[0]
objName := s[1]
pkg, err := Import(imports, importPath)
if err != nil {
t.Error(err)
continue
}
obj := pkg.Scope().Lookup(objName)
if obj == nil {
t.Errorf("%s: object not found", test.name)
continue
}
got := types.ObjectString(pkg, obj)
if got != test.want {
t.Errorf("%s: got %q; want %q", test.name, got, test.want)
}
}
}
func TestIssue5815(t *testing.T) {
skipSpecialPlatforms(t)
// This package only handles gc export data.
if runtime.Compiler != "gc" {
t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
return
}
pkg, err := Import(make(map[string]*types.Package), "strings")
if err != nil {
t.Fatal(err)
}
scope := pkg.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if obj.Pkg() == nil {
t.Errorf("no pkg for %s", obj)
}
if tname, _ := obj.(*types.TypeName); tname != nil {
named := tname.Type().(*types.Named)
for i := 0; i < named.NumMethods(); i++ {
m := named.Method(i)
if m.Pkg() == nil {
t.Errorf("no pkg for %s", m)
}
}
}
}
}
// Smoke test to ensure that imported methods get the correct package.
func TestCorrectMethodPackage(t *testing.T) {
skipSpecialPlatforms(t)
// This package only handles gc export data.
if runtime.Compiler != "gc" {
t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
return
}
imports := make(map[string]*types.Package)
_, err := Import(imports, "net/http")
if err != nil {
t.Fatal(err)
}
mutex := imports["sync"].Scope().Lookup("Mutex").(*types.TypeName).Type()
mset := types.NewMethodSet(types.NewPointer(mutex)) // methods of *sync.Mutex
sel := mset.Lookup(nil, "Lock")
lock := sel.Obj().(*types.Func)
if got, want := lock.Pkg().Path(), "sync"; got != want {
t.Errorf("got package path %q; want %q", got, want)
}
}
| mk0x9/go | src/go/types/internal/gcimporter/gcimporter_test.go | GO | bsd-3-clause | 5,896 |
// Copyright 2012 The LevelDB-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package leveldb provides an ordered key/value store.
//
// BUG: This package is incomplete.
package leveldb
import (
"bytes"
"fmt"
"io"
"path/filepath"
"sort"
"code.google.com/p/leveldb-go/leveldb/db"
"code.google.com/p/leveldb-go/leveldb/memdb"
"code.google.com/p/leveldb-go/leveldb/record"
"code.google.com/p/leveldb-go/leveldb/table"
)
// TODO: document DB.
type DB struct {
dirname string
opts *db.Options
icmp internalKeyComparer
fileLock io.Closer
logFile db.File
log *record.Writer
versions versionSet
}
var _ db.DB = (*DB)(nil)
func (d *DB) Get(key []byte, opts *db.ReadOptions) ([]byte, error) {
panic("unimplemented")
}
func (d *DB) Set(key, value []byte, opts *db.WriteOptions) error {
panic("unimplemented")
}
func (d *DB) Delete(key []byte, opts *db.WriteOptions) error {
panic("unimplemented")
}
func (d *DB) Apply(batch Batch, opts *db.WriteOptions) error {
panic("unimplemented")
}
func (d *DB) Find(key []byte, opts *db.ReadOptions) db.Iterator {
panic("unimplemented")
}
func (d *DB) Close() error {
if d.fileLock == nil {
return nil
}
err := d.fileLock.Close()
d.fileLock = nil
return err
}
type fileNumAndName struct {
num uint64
name string
}
type fileNumAndNameSlice []fileNumAndName
func (p fileNumAndNameSlice) Len() int { return len(p) }
func (p fileNumAndNameSlice) Less(i, j int) bool { return p[i].num < p[j].num }
func (p fileNumAndNameSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// Open opens a LevelDB whose files live in the given directory.
func Open(dirname string, opts *db.Options) (*DB, error) {
d := &DB{
dirname: dirname,
opts: opts,
icmp: internalKeyComparer{opts.GetComparer()},
}
fs := opts.GetFileSystem()
// Lock the database directory.
err := fs.MkdirAll(dirname, 0755)
if err != nil {
return nil, err
}
fileLock, err := fs.Lock(dbFilename(dirname, fileTypeLock, 0))
if err != nil {
return nil, err
}
defer func() {
if fileLock != nil {
fileLock.Close()
}
}()
// TODO: add options for CreateIfMissing and ErrorIfExists, and check them here.
// Load the version set.
err = d.versions.load(dirname, opts)
if err != nil {
return nil, err
}
// Replay any newer log files than the ones named in the manifest.
var ve versionEdit
ls, err := fs.List(dirname)
if err != nil {
return nil, err
}
var logFiles fileNumAndNameSlice
for _, filename := range ls {
n := logFileNum(filename)
if n != 0 && (n >= d.versions.logNumber || n == d.versions.prevLogNumber) {
logFiles = append(logFiles, fileNumAndName{n, filename})
}
}
sort.Sort(logFiles)
for _, lf := range logFiles {
maxSeqNum, err := d.replayLogFile(&ve, fs, filepath.Join(dirname, lf.name))
if err != nil {
return nil, err
}
d.versions.markFileNumUsed(lf.num)
if d.versions.lastSequence < maxSeqNum {
d.versions.lastSequence = maxSeqNum
}
}
// Create an empty .log file.
ve.logNumber = d.versions.nextFileNum()
logFile, err := fs.Create(dbFilename(dirname, fileTypeLog, ve.logNumber))
if err != nil {
return nil, err
}
defer func() {
if logFile != nil {
logFile.Close()
}
}()
d.log = record.NewWriter(logFile)
// Write a new manifest to disk.
if err := d.versions.logAndApply(dirname, &ve); err != nil {
return nil, err
}
// TODO: delete obsolete files.
// TODO: maybe schedule compaction?
d.logFile, logFile = logFile, nil
d.fileLock, fileLock = fileLock, nil
return d, nil
}
func (d *DB) replayLogFile(ve *versionEdit, fs db.FileSystem, filename string) (maxSeqNum uint64, err error) {
file, err := fs.Open(filename)
if err != nil {
return 0, err
}
defer file.Close()
var (
mem *memdb.MemDB
batchBuf = new(bytes.Buffer)
ikeyBuf = make(internalKey, 512)
rr = record.NewReader(file)
)
for {
r, err := rr.Next()
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
_, err = io.Copy(batchBuf, r)
if err != nil {
return 0, err
}
if batchBuf.Len() < batchHeaderLen {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
b := Batch{batchBuf.Bytes()}
seqNum := b.seqNum()
seqNum1 := seqNum + uint64(b.count())
if maxSeqNum < seqNum1 {
maxSeqNum = seqNum1
}
if mem == nil {
mem = memdb.New(&db.Options{
Comparer: d.icmp,
})
}
t := b.iter()
for ; seqNum != seqNum1; seqNum++ {
kind, key, value, ok := t.next()
if !ok {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
// Convert seqNum, kind and key into an internalKey, and add that ikey/value
// pair to mem.
//
// TODO: instead of copying to an intermediate buffer (ikeyBuf), is it worth
// adding a SetTwoPartKey(db.TwoPartKey{key0, key1}, value, opts) method to
// memdb.MemDB? What effect does that have on the db.Comparer interface?
//
// The C++ LevelDB code does not need an intermediate copy because its memdb
// implementation is a private implementation detail, and copies each internal
// key component from the Batch format straight to the skiplist buffer.
//
// Go's LevelDB considers the memdb functionality to be useful in its own
// right, and so leveldb/memdb is a separate package that is usable without
// having to import the top-level leveldb package. That extra abstraction
// means that we need to copy to an intermediate buffer here, to reconstruct
// the complete internal key to pass to the memdb.
if n := len(ikeyBuf); n < len(key)+8 {
for {
n *= 2
if n >= len(key)+8 {
break
}
}
ikeyBuf = make(internalKey, n)
}
ikey := ikeyBuf[:len(key)+8]
copy(ikey, key)
ikey.encodeTrailer(kind, seqNum)
mem.Set(ikey, value, nil)
}
if len(t) != 0 {
return 0, fmt.Errorf("leveldb: corrupt log file %q", filename)
}
// TODO: if mem is large enough, write it to a level-0 table and set mem = nil.
batchBuf.Reset()
}
if mem != nil && !mem.Empty() {
meta, err := d.writeLevel0Table(fs, mem)
if err != nil {
return 0, err
}
ve.newFiles = append(ve.newFiles, newFileEntry{level: 0, meta: meta})
}
return maxSeqNum, nil
}
// firstError returns the first non-nil error of err0 and err1, or nil if both
// are nil.
func firstError(err0, err1 error) error {
if err0 != nil {
return err0
}
return err1
}
func (d *DB) writeLevel0Table(fs db.FileSystem, mem *memdb.MemDB) (meta fileMetadata, err error) {
meta.fileNum = d.versions.nextFileNum()
filename := dbFilename(d.dirname, fileTypeTable, meta.fileNum)
// TODO: add meta.fileNum to a set of 'pending outputs' so that a
// concurrent sweep of obsolete db files won't delete the fileNum file.
// It is the caller's responsibility to remove that fileNum from the
// set of pending outputs.
var (
file db.File
tw *table.Writer
iter db.Iterator
)
defer func() {
if iter != nil {
err = firstError(err, iter.Close())
}
if tw != nil {
err = firstError(err, tw.Close())
}
if file != nil {
err = firstError(err, file.Close())
}
if err != nil {
fs.Remove(filename)
meta = fileMetadata{}
}
}()
file, err = fs.Create(filename)
if err != nil {
return fileMetadata{}, err
}
tw = table.NewWriter(file, &db.Options{
Comparer: d.icmp,
})
iter = mem.Find(nil, nil)
iter.Next()
meta.smallest = internalKey(iter.Key()).clone()
for {
meta.largest = iter.Key()
if err1 := tw.Set(meta.largest, iter.Value(), nil); err1 != nil {
return fileMetadata{}, err1
}
if !iter.Next() {
break
}
}
meta.largest = meta.largest.clone()
if err1 := iter.Close(); err1 != nil {
iter = nil
return fileMetadata{}, err1
}
iter = nil
if err1 := tw.Close(); err1 != nil {
tw = nil
return fileMetadata{}, err1
}
tw = nil
// TODO: currently, closing a table.Writer closes its underlying file.
// We have to re-open the file to Sync or Stat it, which seems stupid.
file, err = fs.Open(filename)
if err != nil {
return fileMetadata{}, err
}
if err1 := file.Sync(); err1 != nil {
return fileMetadata{}, err1
}
if stat, err1 := file.Stat(); err1 != nil {
return fileMetadata{}, err1
} else {
size := stat.Size()
if size < 0 {
return fileMetadata{}, fmt.Errorf("leveldb: table file %q has negative size %d", filename, size)
}
meta.size = uint64(size)
}
// TODO: compaction stats.
return meta, nil
}
| xushiwei/leveldb-go | leveldb/leveldb.go | GO | bsd-3-clause | 8,519 |
/**
* Copyright (c) 2018, Łukasz Marcin Podkalicki <lpodkalicki@gmail.com>
*/
#ifndef _LIGHT_H_
#define _LIGHT_H_
void light_init(void);
#endif /* !_LIGHT_H_ */
| lpodkalicki/blog | esp8266/004_dance_lights_with_fft/light.h | C | bsd-3-clause | 168 |
from acoustics.decibel import *
def test_dbsum():
assert(abs(dbsum([10.0, 10.0]) - 13.0103) < 1e-5)
def test_dbmean():
assert(dbmean([10.0, 10.0]) == 10.0)
def test_dbadd():
assert(abs(dbadd(10.0, 10.0) - 13.0103) < 1e-5)
def test_dbsub():
assert(abs(dbsub(13.0103, 10.0) - 10.0) < 1e-5)
def test_dbmul():
assert(abs(dbmul(10.0, 2) - 13.0103) < 1e-5)
def test_dbdiv():
assert(abs(dbdiv(13.0103, 2) - 10.0) < 1e-5) | FRidh/python-acoustics | tests/test_decibel.py | Python | bsd-3-clause | 451 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/driver/backend_migrator.h"
#include <memory>
#include "base/run_loop.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "components/sync/base/model_type_test_util.h"
#include "components/sync/driver/data_type_manager_mock.h"
#include "components/sync/protocol/sync.pb.h"
#include "components/sync/syncable/directory.h"
#include "components/sync/syncable/test_user_share.h"
#include "components/sync/syncable/write_transaction.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::Eq;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::Return;
namespace syncer {
class SyncBackendMigratorTest : public testing::Test {
public:
SyncBackendMigratorTest() {}
~SyncBackendMigratorTest() override {}
void SetUp() override {
test_user_share_.SetUp();
Mock::VerifyAndClear(manager());
preferred_types_.Put(BOOKMARKS);
preferred_types_.Put(PREFERENCES);
preferred_types_.Put(AUTOFILL);
migrator_ = std::make_unique<BackendMigrator>(
"Profile0", test_user_share_.user_share(), manager(),
reconfigure_callback()->Get(), migration_done_callback()->Get());
SetUnsyncedTypes(ModelTypeSet());
}
void TearDown() override {
migrator_.reset();
test_user_share_.TearDown();
}
// Marks all types in |unsynced_types| as unsynced and all other
// types as synced.
void SetUnsyncedTypes(ModelTypeSet unsynced_types) {
WriteTransaction trans(FROM_HERE, test_user_share_.user_share());
for (int i = FIRST_REAL_MODEL_TYPE; i < ModelType::NUM_ENTRIES; ++i) {
ModelType type = ModelTypeFromInt(i);
sync_pb::DataTypeProgressMarker progress_marker;
if (!unsynced_types.Has(type)) {
progress_marker.set_token("dummy");
}
trans.GetDirectory()->SetDownloadProgress(type, progress_marker);
}
}
void SendConfigureDone(DataTypeManager::ConfigureStatus status,
ModelTypeSet requested_types) {
if (status == DataTypeManager::OK) {
DataTypeManager::ConfigureResult result(status, requested_types);
migrator_->OnConfigureDone(result);
} else {
DataTypeManager::ConfigureResult result(status, requested_types);
migrator_->OnConfigureDone(result);
}
base::RunLoop run_loop;
run_loop.RunUntilIdle();
}
DataTypeManagerMock* manager() { return &manager_; }
ModelTypeSet preferred_types() { return preferred_types_; }
base::MockCallback<base::RepeatingClosure>* reconfigure_callback() {
return &reconfigure_callback_;
}
base::MockCallback<base::RepeatingClosure>* migration_done_callback() {
return &migration_done_callback_;
}
BackendMigrator* migrator() { return migrator_.get(); }
private:
base::test::SingleThreadTaskEnvironment task_environment_;
ModelTypeSet preferred_types_;
NiceMock<DataTypeManagerMock> manager_;
NiceMock<base::MockCallback<base::RepeatingClosure>> reconfigure_callback_;
NiceMock<base::MockCallback<base::RepeatingClosure>> migration_done_callback_;
TestUserShare test_user_share_;
std::unique_ptr<BackendMigrator> migrator_;
};
class MockMigrationObserver : public MigrationObserver {
public:
~MockMigrationObserver() override {}
MOCK_METHOD0(OnMigrationStateChange, void());
};
// Test that in the normal case a migration does transition through each state
// and wind up back in IDLE.
TEST_F(SyncBackendMigratorTest, Sanity) {
EXPECT_CALL(*migration_done_callback(), Run()).Times(0);
MockMigrationObserver migration_observer;
migrator()->AddMigrationObserver(&migration_observer);
EXPECT_CALL(migration_observer, OnMigrationStateChange()).Times(4);
ModelTypeSet to_migrate, difference;
to_migrate.Put(PREFERENCES);
difference.Put(AUTOFILL);
difference.Put(BOOKMARKS);
EXPECT_CALL(*manager(), state())
.WillOnce(Return(DataTypeManager::CONFIGURED));
EXPECT_CALL(*manager(), PurgeForMigration(_));
EXPECT_CALL(*reconfigure_callback(), Run());
migrator()->MigrateTypes(to_migrate);
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
SetUnsyncedTypes(to_migrate);
SendConfigureDone(DataTypeManager::OK, difference);
EXPECT_EQ(BackendMigrator::REENABLING_TYPES, migrator()->state());
EXPECT_CALL(*migration_done_callback(), Run());
SetUnsyncedTypes(ModelTypeSet());
SendConfigureDone(DataTypeManager::OK, preferred_types());
EXPECT_EQ(BackendMigrator::IDLE, migrator()->state());
migrator()->RemoveMigrationObserver(&migration_observer);
}
// Test that in the normal case with Nigori a migration transitions through
// each state and wind up back in IDLE.
TEST_F(SyncBackendMigratorTest, MigrateNigori) {
EXPECT_CALL(*migration_done_callback(), Run()).Times(0);
ModelTypeSet to_migrate, difference;
to_migrate.Put(NIGORI);
difference.Put(AUTOFILL);
difference.Put(BOOKMARKS);
EXPECT_CALL(*manager(), state())
.WillOnce(Return(DataTypeManager::CONFIGURED));
EXPECT_CALL(*manager(), PurgeForMigration(_));
migrator()->MigrateTypes(to_migrate);
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
EXPECT_CALL(*reconfigure_callback(), Run());
SetUnsyncedTypes(to_migrate);
SendConfigureDone(DataTypeManager::OK, difference);
EXPECT_EQ(BackendMigrator::REENABLING_TYPES, migrator()->state());
EXPECT_CALL(*migration_done_callback(), Run());
SetUnsyncedTypes(ModelTypeSet());
SendConfigureDone(DataTypeManager::OK, preferred_types());
EXPECT_EQ(BackendMigrator::IDLE, migrator()->state());
}
// Test that the migrator waits for the data type manager to be idle before
// starting a migration.
TEST_F(SyncBackendMigratorTest, WaitToStart) {
ModelTypeSet to_migrate;
to_migrate.Put(PREFERENCES);
EXPECT_CALL(*manager(), state())
.WillOnce(Return(DataTypeManager::CONFIGURING));
EXPECT_CALL(*reconfigure_callback(), Run()).Times(0);
migrator()->MigrateTypes(to_migrate);
EXPECT_EQ(BackendMigrator::WAITING_TO_START, migrator()->state());
Mock::VerifyAndClearExpectations(manager());
EXPECT_CALL(*manager(), state())
.WillOnce(Return(DataTypeManager::CONFIGURED));
EXPECT_CALL(*manager(), PurgeForMigration(_));
SetUnsyncedTypes(ModelTypeSet());
SendConfigureDone(DataTypeManager::OK, ModelTypeSet());
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
}
// Test that the migrator can cope with a migration request while a migration
// is in progress.
TEST_F(SyncBackendMigratorTest, RestartMigration) {
ModelTypeSet to_migrate1, to_migrate2, to_migrate_union, bookmarks;
to_migrate1.Put(PREFERENCES);
to_migrate2.Put(AUTOFILL);
to_migrate_union.Put(PREFERENCES);
to_migrate_union.Put(AUTOFILL);
bookmarks.Put(BOOKMARKS);
EXPECT_CALL(*manager(), state())
.WillOnce(Return(DataTypeManager::CONFIGURED));
EXPECT_CALL(*manager(), PurgeForMigration(_)).Times(2);
migrator()->MigrateTypes(to_migrate1);
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
migrator()->MigrateTypes(to_migrate2);
const ModelTypeSet difference1 = Difference(preferred_types(), to_migrate1);
Mock::VerifyAndClearExpectations(manager());
EXPECT_CALL(*manager(), PurgeForMigration(_));
EXPECT_CALL(*reconfigure_callback(), Run());
SetUnsyncedTypes(to_migrate1);
SendConfigureDone(DataTypeManager::OK, difference1);
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
SetUnsyncedTypes(to_migrate_union);
SendConfigureDone(DataTypeManager::OK, bookmarks);
EXPECT_EQ(BackendMigrator::REENABLING_TYPES, migrator()->state());
}
// Test that an external invocation of Configure(...) during a migration results
// in a migration reattempt.
TEST_F(SyncBackendMigratorTest, InterruptedWhileDisablingTypes) {
ModelTypeSet to_migrate;
ModelTypeSet difference;
to_migrate.Put(PREFERENCES);
difference.Put(AUTOFILL);
difference.Put(BOOKMARKS);
EXPECT_CALL(*manager(), state())
.WillOnce(Return(DataTypeManager::CONFIGURED));
EXPECT_CALL(*manager(), PurgeForMigration(HasModelTypes(to_migrate)));
migrator()->MigrateTypes(to_migrate);
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
Mock::VerifyAndClearExpectations(manager());
EXPECT_CALL(*manager(), PurgeForMigration(HasModelTypes(to_migrate)));
SetUnsyncedTypes(ModelTypeSet());
SendConfigureDone(DataTypeManager::OK, preferred_types());
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
}
// Test that spurious OnConfigureDone events don't confuse the
// migrator while it's waiting for disabled types to have been purged
// from the sync db.
TEST_F(SyncBackendMigratorTest, WaitingForPurge) {
ModelTypeSet to_migrate, difference;
to_migrate.Put(PREFERENCES);
to_migrate.Put(AUTOFILL);
difference.Put(BOOKMARKS);
EXPECT_CALL(*manager(), state())
.WillOnce(Return(DataTypeManager::CONFIGURED));
EXPECT_CALL(*manager(), PurgeForMigration(_));
EXPECT_CALL(*reconfigure_callback(), Run());
migrator()->MigrateTypes(to_migrate);
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
SendConfigureDone(DataTypeManager::OK, difference);
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
ModelTypeSet prefs;
prefs.Put(PREFERENCES);
SetUnsyncedTypes(prefs);
SendConfigureDone(DataTypeManager::OK, difference);
EXPECT_EQ(BackendMigrator::DISABLING_TYPES, migrator()->state());
SetUnsyncedTypes(to_migrate);
SendConfigureDone(DataTypeManager::OK, difference);
EXPECT_EQ(BackendMigrator::REENABLING_TYPES, migrator()->state());
}
TEST_F(SyncBackendMigratorTest, ConfigureFailure) {
ModelTypeSet to_migrate;
to_migrate.Put(PREFERENCES);
EXPECT_CALL(*manager(), state())
.WillOnce(Return(DataTypeManager::CONFIGURED));
EXPECT_CALL(*manager(), PurgeForMigration(_));
migrator()->MigrateTypes(to_migrate);
SetUnsyncedTypes(ModelTypeSet());
SendConfigureDone(DataTypeManager::ABORTED, ModelTypeSet());
EXPECT_EQ(BackendMigrator::IDLE, migrator()->state());
}
} // namespace syncer
| endlessm/chromium-browser | components/sync/driver/backend_migrator_unittest.cc | C++ | bsd-3-clause | 10,274 |
// Copyright (c) 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_H_
#define QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_H_
#include <cstdint>
#include <memory>
#include <set>
#include "net/third_party/quiche/src/quic/core/qpack/qpack_decoder_stream_sender.h"
#include "net/third_party/quiche/src/quic/core/qpack/qpack_encoder_stream_receiver.h"
#include "net/third_party/quiche/src/quic/core/qpack/qpack_header_table.h"
#include "net/third_party/quiche/src/quic/core/qpack/qpack_progressive_decoder.h"
#include "net/third_party/quiche/src/quic/core/quic_types.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_export.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
namespace quic {
// QPACK decoder class. Exactly one instance should exist per QUIC connection.
// This class vends a new QpackProgressiveDecoder instance for each new header
// list to be encoded.
class QUIC_EXPORT_PRIVATE QpackDecoder
: public QpackEncoderStreamReceiver::Delegate,
public QpackProgressiveDecoder::BlockedStreamLimitEnforcer,
public QpackProgressiveDecoder::DecodingCompletedVisitor {
public:
// Interface for receiving notification that an error has occurred on the
// encoder stream. This MUST be treated as a connection error of type
// HTTP_QPACK_ENCODER_STREAM_ERROR.
class QUIC_EXPORT_PRIVATE EncoderStreamErrorDelegate {
public:
virtual ~EncoderStreamErrorDelegate() {}
virtual void OnEncoderStreamError(
quiche::QuicheStringPiece error_message) = 0;
};
QpackDecoder(uint64_t maximum_dynamic_table_capacity,
uint64_t maximum_blocked_streams,
EncoderStreamErrorDelegate* encoder_stream_error_delegate);
~QpackDecoder() override;
// Signal to the peer's encoder that a stream is reset. This lets the peer's
// encoder know that no more header blocks will be processed on this stream,
// therefore references to dynamic table entries shall not prevent their
// eviction.
// This method should be called regardless of whether a header block is being
// decoded on that stream, because a header block might be in flight from the
// peer.
// This method should be called every time a request or push stream is reset
// for any reason: for example, client cancels request, or a decoding error
// occurs and HeadersHandlerInterface::OnDecodingErrorDetected() is called.
// This method should also be called if the stream is reset by the peer,
// because the peer's encoder can only evict entries referenced by header
// blocks once it receives acknowledgement from this endpoint that the stream
// is reset.
// However, this method should not be called if the stream is closed normally
// using the FIN bit.
void OnStreamReset(QuicStreamId stream_id);
// QpackProgressiveDecoder::BlockedStreamLimitEnforcer implementation.
bool OnStreamBlocked(QuicStreamId stream_id) override;
void OnStreamUnblocked(QuicStreamId stream_id) override;
// QpackProgressiveDecoder::DecodingCompletedVisitor implementation.
void OnDecodingCompleted(QuicStreamId stream_id,
uint64_t required_insert_count) override;
// Factory method to create a QpackProgressiveDecoder for decoding a header
// block. |handler| must remain valid until the returned
// QpackProgressiveDecoder instance is destroyed or the decoder calls
// |handler->OnHeaderBlockEnd()|.
std::unique_ptr<QpackProgressiveDecoder> CreateProgressiveDecoder(
QuicStreamId stream_id,
QpackProgressiveDecoder::HeadersHandlerInterface* handler);
// QpackEncoderStreamReceiver::Delegate implementation
void OnInsertWithNameReference(bool is_static,
uint64_t name_index,
quiche::QuicheStringPiece value) override;
void OnInsertWithoutNameReference(quiche::QuicheStringPiece name,
quiche::QuicheStringPiece value) override;
void OnDuplicate(uint64_t index) override;
void OnSetDynamicTableCapacity(uint64_t capacity) override;
void OnErrorDetected(quiche::QuicheStringPiece error_message) override;
// delegate must be set if dynamic table capacity is not zero.
void set_qpack_stream_sender_delegate(QpackStreamSenderDelegate* delegate) {
decoder_stream_sender_.set_qpack_stream_sender_delegate(delegate);
}
QpackStreamReceiver* encoder_stream_receiver() {
return &encoder_stream_receiver_;
}
// True if any dynamic table entries have been referenced from a header block.
bool dynamic_table_entry_referenced() const {
return header_table_.dynamic_table_entry_referenced();
}
private:
EncoderStreamErrorDelegate* const encoder_stream_error_delegate_;
QpackEncoderStreamReceiver encoder_stream_receiver_;
QpackDecoderStreamSender decoder_stream_sender_;
QpackHeaderTable header_table_;
std::set<QuicStreamId> blocked_streams_;
const uint64_t maximum_blocked_streams_;
// Known Received Count is the number of insertions the encoder has received
// acknowledgement for (through Header Acknowledgement and Insert Count
// Increment instructions). The encoder must keep track of it in order to be
// able to send Insert Count Increment instructions. See
// https://quicwg.org/base-drafts/draft-ietf-quic-qpack.html#known-received-count.
uint64_t known_received_count_;
};
} // namespace quic
#endif // QUICHE_QUIC_CORE_QPACK_QPACK_DECODER_H_
| endlessm/chromium-browser | net/third_party/quiche/src/quic/core/qpack/qpack_decoder.h | C | bsd-3-clause | 5,610 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync_file_system/drive_backend_v1/drive_file_sync_service.h"
#include <algorithm>
#include "base/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/drive/drive_uploader.h"
#include "chrome/browser/drive/fake_drive_service.h"
#include "chrome/browser/sync_file_system/drive_backend_v1/api_util.h"
#include "chrome/browser/sync_file_system/drive_backend_v1/drive_file_sync_util.h"
#include "chrome/browser/sync_file_system/drive_backend_v1/drive_metadata_store.h"
#include "chrome/browser/sync_file_system/drive_backend_v1/fake_drive_service_helper.h"
#include "chrome/browser/sync_file_system/fake_remote_change_processor.h"
#include "chrome/browser/sync_file_system/local/canned_syncable_file_system.h"
#include "chrome/browser/sync_file_system/local/local_file_sync_context.h"
#include "chrome/browser/sync_file_system/local/local_file_sync_service.h"
#include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
#include "chrome/browser/sync_file_system/syncable_file_system_util.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/browser/fileapi/file_system_context.h"
#define FPL(path) FILE_PATH_LITERAL(path)
using content::BrowserThread;
using google_apis::GDataErrorCode;
using google_apis::ResourceEntry;
namespace sync_file_system {
using drive_backend::APIUtil;
using drive_backend::APIUtilInterface;
using drive_backend::FakeDriveServiceHelper;
namespace {
void SyncResultCallback(bool* done,
SyncStatusCode* status_out,
fileapi::FileSystemURL* url_out,
SyncStatusCode status,
const fileapi::FileSystemURL& url) {
EXPECT_FALSE(*done);
*status_out = status;
*url_out = url;
*done = true;
}
void SyncStatusResultCallback(bool* done,
SyncStatusCode* status_out,
SyncStatusCode status) {
EXPECT_FALSE(*done);
*status_out = status;
*done = true;
}
void DatabaseInitResultCallback(bool* done,
SyncStatusCode* status_out,
bool* created_out,
SyncStatusCode status,
bool created) {
EXPECT_FALSE(*done);
*status_out = status;
*created_out = created;
*done = true;
}
} // namespace
class DriveFileSyncServiceSyncTest : public testing::Test {
public:
DriveFileSyncServiceSyncTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
virtual ~DriveFileSyncServiceSyncTest() {
}
virtual void SetUp() OVERRIDE {
// TODO(tzik): Set up TestExtensionSystem to support simulated relaunch.
RegisterSyncableFileSystem();
local_sync_service_.reset(new LocalFileSyncService(&profile_));
fake_drive_service_ = new drive::FakeDriveService();
fake_drive_service_->Initialize("test_user@gmail.com");
ASSERT_TRUE(fake_drive_service_->LoadAccountMetadataForWapi(
"sync_file_system/account_metadata.json"));
ASSERT_TRUE(fake_drive_service_->LoadResourceListForWapi(
"gdata/root_feed.json"));
drive_uploader_ = new drive::DriveUploader(
fake_drive_service_, base::MessageLoopProxy::current().get());
fake_drive_helper_.reset(new FakeDriveServiceHelper(
fake_drive_service_, drive_uploader_));
bool done = false;
SyncStatusCode status = SYNC_STATUS_UNKNOWN;
bool created = false;
scoped_ptr<DriveMetadataStore> metadata_store(
new DriveMetadataStore(fake_drive_helper_->base_dir_path(),
base::MessageLoopProxy::current().get()));
metadata_store->Initialize(
base::Bind(&DatabaseInitResultCallback, &done, &status, &created));
FlushMessageLoop();
EXPECT_TRUE(done);
EXPECT_EQ(SYNC_STATUS_OK, status);
EXPECT_TRUE(created);
scoped_ptr<APIUtil> api_util(APIUtil::CreateForTesting(
fake_drive_helper_->base_dir_path().AppendASCII("tmp"),
scoped_ptr<drive::DriveServiceInterface>(fake_drive_service_),
scoped_ptr<drive::DriveUploaderInterface>(drive_uploader_)));
remote_sync_service_ = DriveFileSyncService::CreateForTesting(
&profile_,
fake_drive_helper_->base_dir_path(),
api_util.PassAs<APIUtilInterface>(),
metadata_store.Pass());
local_sync_service_->SetLocalChangeProcessor(remote_sync_service_.get());
remote_sync_service_->SetRemoteChangeProcessor(local_sync_service_.get());
}
virtual void TearDown() OVERRIDE {
drive_uploader_ = NULL;
fake_drive_service_ = NULL;
remote_sync_service_.reset();
local_sync_service_.reset();
FlushMessageLoop();
typedef std::map<GURL, CannedSyncableFileSystem*>::iterator iterator;
for (iterator itr = file_systems_.begin();
itr != file_systems_.end(); ++itr) {
itr->second->TearDown();
delete itr->second;
}
file_systems_.clear();
FlushMessageLoop();
RevokeSyncableFileSystem();
}
protected:
void RegisterOrigin(const GURL& origin) {
if (!ContainsKey(file_systems_, origin)) {
CannedSyncableFileSystem* file_system = new CannedSyncableFileSystem(
origin,
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO).get(),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
.get());
bool done = false;
SyncStatusCode status = SYNC_STATUS_UNKNOWN;
file_system->SetUp();
local_sync_service_->MaybeInitializeFileSystemContext(
origin, file_system->file_system_context(),
base::Bind(&SyncStatusResultCallback, &done, &status));
FlushMessageLoop();
EXPECT_TRUE(done);
EXPECT_EQ(SYNC_STATUS_OK, status);
file_system->backend()->sync_context()->
set_mock_notify_changes_duration_in_sec(0);
EXPECT_EQ(base::PLATFORM_FILE_OK, file_system->OpenFileSystem());
file_systems_[origin] = file_system;
}
bool done = false;
SyncStatusCode status = SYNC_STATUS_UNKNOWN;
remote_sync_service_->RegisterOrigin(
origin, base::Bind(&SyncStatusResultCallback, &done, &status));
FlushMessageLoop();
EXPECT_TRUE(done);
EXPECT_EQ(SYNC_STATUS_OK, status);
}
void AddLocalFolder(const GURL& origin,
const base::FilePath& path) {
ASSERT_TRUE(ContainsKey(file_systems_, origin));
EXPECT_EQ(base::PLATFORM_FILE_OK,
file_systems_[origin]->CreateDirectory(
CreateSyncableFileSystemURL(origin, path)));
}
void AddOrUpdateLocalFile(const GURL& origin,
const base::FilePath& path,
const std::string& content) {
fileapi::FileSystemURL url(CreateSyncableFileSystemURL(origin, path));
ASSERT_TRUE(ContainsKey(file_systems_, origin));
EXPECT_EQ(base::PLATFORM_FILE_OK, file_systems_[origin]->CreateFile(url));
int64 bytes_written = file_systems_[origin]->WriteString(url, content);
EXPECT_EQ(static_cast<int64>(content.size()), bytes_written);
FlushMessageLoop();
}
void UpdateLocalFile(const GURL& origin,
const base::FilePath& path,
const std::string& content) {
ASSERT_TRUE(ContainsKey(file_systems_, origin));
int64 bytes_written = file_systems_[origin]->WriteString(
CreateSyncableFileSystemURL(origin, path), content);
EXPECT_EQ(static_cast<int64>(content.size()), bytes_written);
FlushMessageLoop();
}
void RemoveLocal(const GURL& origin, const base::FilePath& path) {
ASSERT_TRUE(ContainsKey(file_systems_, origin));
EXPECT_EQ(base::PLATFORM_FILE_OK,
file_systems_[origin]->Remove(
CreateSyncableFileSystemURL(origin, path),
true /* recursive */));
FlushMessageLoop();
}
SyncStatusCode ProcessLocalChange() {
bool done = false;
SyncStatusCode status = SYNC_STATUS_UNKNOWN;
fileapi::FileSystemURL url;
local_sync_service_->ProcessLocalChange(
base::Bind(&SyncResultCallback, &done, &status, &url));
FlushMessageLoop();
EXPECT_TRUE(done);
if (status != SYNC_STATUS_NO_CHANGE_TO_SYNC)
local_sync_service_->ClearSyncFlagForURL(url);
return status;
}
SyncStatusCode ProcessRemoteChange() {
bool done = false;
SyncStatusCode status = SYNC_STATUS_UNKNOWN;
fileapi::FileSystemURL url;
remote_sync_service_->ProcessRemoteChange(
base::Bind(&SyncResultCallback, &done, &status, &url));
FlushMessageLoop();
EXPECT_TRUE(done);
if (status != SYNC_STATUS_NO_CHANGE_TO_SYNC)
local_sync_service_->ClearSyncFlagForURL(url);
return status;
}
SyncStatusCode ProcessChangesUntilDone() {
remote_sync_service_->OnNotificationReceived();
FlushMessageLoop();
SyncStatusCode local_sync_status;
SyncStatusCode remote_sync_status;
do {
local_sync_status = ProcessLocalChange();
if (local_sync_status != SYNC_STATUS_OK &&
local_sync_status != SYNC_STATUS_NO_CHANGE_TO_SYNC)
return local_sync_status;
remote_sync_status = ProcessRemoteChange();
if (remote_sync_status != SYNC_STATUS_OK &&
remote_sync_status != SYNC_STATUS_NO_CHANGE_TO_SYNC)
return remote_sync_status;
} while (local_sync_status != SYNC_STATUS_NO_CHANGE_TO_SYNC &&
remote_sync_status != SYNC_STATUS_NO_CHANGE_TO_SYNC);
return SYNC_STATUS_OK;
}
// Verifies local and remote files/folders are consistent.
// This function checks:
// - Each registered origin has corresponding remote folder.
// - Each local file/folder has corresponding remote one.
// - Each remote file/folder has corresponding local one.
// TODO(tzik): Handle conflict case. i.e. allow remote file has different
// file content if the corresponding local file conflicts to it.
void VerifyConsistency() {
std::string sync_root_folder_id;
GDataErrorCode error =
fake_drive_helper_->GetSyncRootFolderID(&sync_root_folder_id);
if (sync_root_folder_id.empty()) {
EXPECT_EQ(google_apis::HTTP_NOT_FOUND, error);
EXPECT_TRUE(file_systems_.empty());
return;
}
EXPECT_EQ(google_apis::HTTP_SUCCESS, error);
ScopedVector<ResourceEntry> remote_entries;
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->ListFilesInFolder(
sync_root_folder_id, &remote_entries));
std::map<std::string, const ResourceEntry*> origin_root_by_title;
for (ScopedVector<ResourceEntry>::iterator itr = remote_entries.begin();
itr != remote_entries.end();
++itr) {
const ResourceEntry& remote_entry = **itr;
EXPECT_FALSE(ContainsKey(origin_root_by_title, remote_entry.title()));
origin_root_by_title[remote_entry.title()] = *itr;
}
for (std::map<GURL, CannedSyncableFileSystem*>::const_iterator itr =
file_systems_.begin();
itr != file_systems_.end(); ++itr) {
const GURL& origin = itr->first;
SCOPED_TRACE(testing::Message() << "Verifying origin: " << origin);
CannedSyncableFileSystem* file_system = itr->second;
ASSERT_TRUE(ContainsKey(origin_root_by_title, origin.host()));
VerifyConsistencyForFolder(
origin, base::FilePath(),
origin_root_by_title[origin.host()]->resource_id(),
file_system);
}
}
void VerifyConsistencyForOrigin(const GURL& origin) {
std::string sync_root_folder_id;
ASSERT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->GetSyncRootFolderID(&sync_root_folder_id));
ASSERT_FALSE(sync_root_folder_id.empty());
ScopedVector<ResourceEntry> origin_folder;
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->SearchByTitle(
sync_root_folder_id, origin.host(), &origin_folder));
ASSERT_EQ(1u, origin_folder.size());
ASSERT_TRUE(ContainsKey(file_systems_, origin));
VerifyConsistencyForFolder(
origin, base::FilePath(),
origin_folder[0]->resource_id(),
file_systems_[origin]);
}
void VerifyConsistencyForFolder(const GURL& origin,
const base::FilePath& path,
const std::string& folder_id,
CannedSyncableFileSystem* file_system) {
SCOPED_TRACE(testing::Message() << "Verifying path: " << path.value());
ScopedVector<ResourceEntry> remote_entries;
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->ListFilesInFolder(
folder_id, &remote_entries));
std::map<std::string, const ResourceEntry*> remote_entry_by_title;
for (ScopedVector<ResourceEntry>::iterator itr = remote_entries.begin();
itr != remote_entries.end();
++itr) {
const ResourceEntry& remote_entry = **itr;
EXPECT_FALSE(ContainsKey(remote_entry_by_title, remote_entry.title()));
remote_entry_by_title[remote_entry.title()] = *itr;
}
fileapi::FileSystemURL url(CreateSyncableFileSystemURL(origin, path));
CannedSyncableFileSystem::FileEntryList local_entries;
EXPECT_EQ(base::PLATFORM_FILE_OK,
file_system->ReadDirectory(url, &local_entries));
for (CannedSyncableFileSystem::FileEntryList::iterator itr =
local_entries.begin();
itr != local_entries.end();
++itr) {
const fileapi::DirectoryEntry& local_entry = *itr;
fileapi::FileSystemURL entry_url(
CreateSyncableFileSystemURL(origin, path.Append(local_entry.name)));
std::string title = DriveFileSyncService::PathToTitle(entry_url.path());
ASSERT_TRUE(ContainsKey(remote_entry_by_title, title));
const ResourceEntry& remote_entry = *remote_entry_by_title[title];
if (local_entry.is_directory) {
ASSERT_TRUE(remote_entry.is_folder());
VerifyConsistencyForFolder(origin, entry_url.path(),
remote_entry.resource_id(),
file_system);
} else {
ASSERT_TRUE(remote_entry.is_file());
VerifyConsistencyForFile(origin, entry_url.path(),
remote_entry.resource_id(),
file_system);
}
remote_entry_by_title.erase(title);
}
EXPECT_TRUE(remote_entry_by_title.empty());
}
void VerifyConsistencyForFile(const GURL& origin,
const base::FilePath& path,
const std::string& file_id,
CannedSyncableFileSystem* file_system) {
fileapi::FileSystemURL url(CreateSyncableFileSystemURL(origin, path));
std::string file_content;
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->ReadFile(file_id, &file_content));
EXPECT_EQ(base::PLATFORM_FILE_OK,
file_system->VerifyFile(url, file_content));
}
void FlushMessageLoop() {
base::MessageLoop::current()->RunUntilIdle();
BrowserThread::GetBlockingPool()->FlushForTesting();
base::MessageLoop::current()->RunUntilIdle();
}
void TestInitialization();
void TestLocalToRemoteBasic();
void TestRemoteToLocalBasic();
void TestLocalFileUpdate();
void TestRemoteFileUpdate();
void TestLocalFileDeletion();
void TestRemoteFileDeletion();
content::TestBrowserThreadBundle thread_bundle_;
TestingProfile profile_;
drive::FakeDriveService* fake_drive_service_;
drive::DriveUploader* drive_uploader_;
scoped_ptr<FakeDriveServiceHelper> fake_drive_helper_;
std::map<GURL, CannedSyncableFileSystem*> file_systems_;
scoped_ptr<DriveFileSyncService> remote_sync_service_;
scoped_ptr<LocalFileSyncService> local_sync_service_;
private:
DISALLOW_COPY_AND_ASSIGN(DriveFileSyncServiceSyncTest);
};
void DriveFileSyncServiceSyncTest::TestInitialization() {
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistency();
}
void DriveFileSyncServiceSyncTest::TestLocalToRemoteBasic() {
const GURL kOrigin("chrome-extension://example");
RegisterOrigin(kOrigin);
AddOrUpdateLocalFile(kOrigin, base::FilePath(FPL("file")), "abcde");
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistency();
}
void DriveFileSyncServiceSyncTest::TestRemoteToLocalBasic() {
const GURL kOrigin("chrome-extension://example");
std::string sync_root_folder_id;
EXPECT_EQ(google_apis::HTTP_CREATED,
fake_drive_helper_->AddOrphanedFolder(
APIUtil::GetSyncRootDirectoryName(),
&sync_root_folder_id));
std::string origin_root_folder_id;
EXPECT_EQ(google_apis::HTTP_CREATED,
fake_drive_helper_->AddFolder(
sync_root_folder_id, kOrigin.host(), &origin_root_folder_id));
RegisterOrigin(kOrigin);
std::string file_id;
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->AddFile(
origin_root_folder_id, "file", "abcde", &file_id));
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistency();
}
void DriveFileSyncServiceSyncTest::TestLocalFileUpdate() {
const GURL kOrigin("chrome-extension://example");
const base::FilePath kPath(FPL("file"));
RegisterOrigin(kOrigin);
AddOrUpdateLocalFile(kOrigin, kPath, "abcde");
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistencyForOrigin(kOrigin);
UpdateLocalFile(kOrigin, kPath, "1234567890");
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistency();
}
void DriveFileSyncServiceSyncTest::TestRemoteFileUpdate() {
const GURL kOrigin("chrome-extension://example");
const base::FilePath kPath(FPL("file"));
const std::string kTitle(DriveFileSyncService::PathToTitle(kPath));
std::string sync_root_folder_id;
EXPECT_EQ(google_apis::HTTP_CREATED,
fake_drive_helper_->AddOrphanedFolder(
APIUtil::GetSyncRootDirectoryName(),
&sync_root_folder_id));
std::string origin_root_folder_id;
EXPECT_EQ(google_apis::HTTP_CREATED,
fake_drive_helper_->AddFolder(
sync_root_folder_id, kOrigin.host(), &origin_root_folder_id));
std::string remote_file_id;
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->AddFile(
origin_root_folder_id, kTitle, "abcde", &remote_file_id));
RegisterOrigin(kOrigin);
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistencyForOrigin(kOrigin);
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->UpdateFile(remote_file_id, "1234567890"));
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistency();
}
void DriveFileSyncServiceSyncTest::TestLocalFileDeletion() {
const GURL kOrigin("chrome-extension://example");
const base::FilePath kPath(FPL("file"));
RegisterOrigin(kOrigin);
AddOrUpdateLocalFile(kOrigin, kPath, "abcde");
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistencyForOrigin(kOrigin);
RemoveLocal(kOrigin, kPath);
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistency();
}
void DriveFileSyncServiceSyncTest::TestRemoteFileDeletion() {
const GURL kOrigin("chrome-extension://example");
const base::FilePath kPath(FPL("file"));
const std::string kTitle(DriveFileSyncService::PathToTitle(kPath));
std::string sync_root_folder_id;
EXPECT_EQ(google_apis::HTTP_CREATED,
fake_drive_helper_->AddOrphanedFolder(
APIUtil::GetSyncRootDirectoryName(),
&sync_root_folder_id));
std::string origin_root_folder_id;
EXPECT_EQ(google_apis::HTTP_CREATED,
fake_drive_helper_->AddFolder(
sync_root_folder_id, kOrigin.host(), &origin_root_folder_id));
std::string remote_file_id;
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->AddFile(
origin_root_folder_id, kTitle, "abcde", &remote_file_id));
RegisterOrigin(kOrigin);
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistencyForOrigin(kOrigin);
EXPECT_EQ(google_apis::HTTP_SUCCESS,
fake_drive_helper_->RemoveResource(remote_file_id));
EXPECT_EQ(SYNC_STATUS_OK, ProcessChangesUntilDone());
VerifyConsistency();
}
TEST_F(DriveFileSyncServiceSyncTest, InitializationTest) {
ASSERT_FALSE(IsDriveAPIDisabled());
TestInitialization();
}
TEST_F(DriveFileSyncServiceSyncTest, InitializationTest_WAPI) {
ScopedDisableDriveAPI disable_drive_api;
TestInitialization();
}
TEST_F(DriveFileSyncServiceSyncTest, LocalToRemoteBasicTest) {
ASSERT_FALSE(IsDriveAPIDisabled());
TestLocalToRemoteBasic();
}
TEST_F(DriveFileSyncServiceSyncTest, LocalToRemoteBasicTest_WAPI) {
ScopedDisableDriveAPI disable_drive_api;
TestLocalToRemoteBasic();
}
TEST_F(DriveFileSyncServiceSyncTest, RemoteToLocalBasicTest) {
ASSERT_FALSE(IsDriveAPIDisabled());
TestRemoteToLocalBasic();
}
TEST_F(DriveFileSyncServiceSyncTest, RemoteToLocalBasicTest_WAPI) {
ScopedDisableDriveAPI disable_drive_api;
TestRemoteToLocalBasic();
}
TEST_F(DriveFileSyncServiceSyncTest, LocalFileUpdateTest) {
ASSERT_FALSE(IsDriveAPIDisabled());
TestLocalFileUpdate();
}
TEST_F(DriveFileSyncServiceSyncTest, LocalFileUpdateTest_WAPI) {
ScopedDisableDriveAPI disable_drive_api;
TestLocalFileUpdate();
}
TEST_F(DriveFileSyncServiceSyncTest, RemoteFileUpdateTest) {
ASSERT_FALSE(IsDriveAPIDisabled());
TestRemoteFileUpdate();
}
TEST_F(DriveFileSyncServiceSyncTest, RemoteFileUpdateTest_WAPI) {
ScopedDisableDriveAPI disable_drive_api;
TestRemoteFileUpdate();
}
TEST_F(DriveFileSyncServiceSyncTest, LocalFileDeletionTest) {
ASSERT_FALSE(IsDriveAPIDisabled());
TestLocalFileDeletion();
}
TEST_F(DriveFileSyncServiceSyncTest, LocalFileDeletionTest_WAPI) {
ScopedDisableDriveAPI disable_drive_api;
TestLocalFileDeletion();
}
TEST_F(DriveFileSyncServiceSyncTest, RemoteFileDeletionTest) {
ASSERT_FALSE(IsDriveAPIDisabled());
TestRemoteFileDeletion();
}
TEST_F(DriveFileSyncServiceSyncTest, RemoteFileDeletionTest_WAPI) {
ScopedDisableDriveAPI disable_drive_api;
TestRemoteFileDeletion();
}
} // namespace sync_file_system
| mogoweb/chromium-crosswalk | chrome/browser/sync_file_system/drive_backend_v1/drive_file_sync_service_sync_unittest.cc | C++ | bsd-3-clause | 22,759 |
<a name="nn.convlayers.dok"></a>
# Convolutional layers #
A convolution is an integral that expresses the amount of overlap of one function `g` as it is shifted over another function `f`. It therefore "blends" one function with another. The neural network package supports convolution, pooling, subsampling and other relevant facilities. These are divided base on the dimensionality of the input and output [Tensors](https://github.com/torch/torch7/blob/master/doc/tensor.md#tensor):
* [Temporal Modules](#nn.TemporalModules) apply to sequences with a one-dimensional relationship
(e.g. sequences of words, phonemes and letters. Strings of some kind).
* [TemporalConvolution](#nn.TemporalConvolution) : a 1D convolution over an input sequence ;
* [TemporalSubSampling](#nn.TemporalSubSampling) : a 1D sub-sampling over an input sequence ;
* [TemporalMaxPooling](#nn.TemporalMaxPooling) : a 1D max-pooling operation over an input sequence ;
* [LookupTable](#nn.LookupTable) : a convolution of width `1`, commonly used for word embeddings ;
* [Spatial Modules](#nn.SpatialModules) apply to inputs with two-dimensional relationships (e.g. images):
* [SpatialConvolution](#nn.SpatialConvolution) : a 2D convolution over an input image ;
* [SpatialFullConvolution](#nn.SpatialFullConvolution) : a 2D full convolution over an input image ;
* [SpatialConvolutionLocal](#nn.SpatialConvolutionLocal) : a 2D locally-connected layer over an input image ;
* [SpatialSubSampling](#nn.SpatialSubSampling) : a 2D sub-sampling over an input image ;
* [SpatialMaxPooling](#nn.SpatialMaxPooling) : a 2D max-pooling operation over an input image ;
* [SpatialFractionalMaxPooling](#nn.SpatialFractionalMaxPooling) : a 2D fractional max-pooling operation over an input image ;
* [SpatialAveragePooling](#nn.SpatialAveragePooling) : a 2D average-pooling operation over an input image ;
* [SpatialAdaptiveMaxPooling](#nn.SpatialAdaptiveMaxPooling) : a 2D max-pooling operation which adapts its parameters dynamically such that the output is of fixed size ;
* [SpatialMaxUnpooling](#nn.SpatialMaxUnpooling) : a 2D max-unpooling operation ;
* [SpatialLPPooling](#nn.SpatialLPPooling) : computes the `p` norm in a convolutional manner on a set of input images ;
* [SpatialConvolutionMap](#nn.SpatialConvolutionMap) : a 2D convolution that uses a generic connection table ;
* [SpatialZeroPadding](#nn.SpatialZeroPadding) : padds a feature map with specified number of zeros ;
* [SpatialSubtractiveNormalization](#nn.SpatialSubtractiveNormalization) : a spatial subtraction operation on a series of 2D inputs using
* [SpatialCrossMapLRN](#nn.SpatialCrossMapLRN) : a spatial local response normalization between feature maps ;
* [SpatialBatchNormalization](#nn.SpatialBatchNormalization): mean/std normalization over the mini-batch inputs and pixels, with an optional affine transform that follows
a kernel for computing the weighted average in a neighborhood ;
* [SpatialUpsamplingNearest](#nn.SpatialUpSamplingNearest): A simple upsampler applied to every channel of the feature map.
* [Volumetric Modules](#nn.VolumetricModules) apply to inputs with three-dimensional relationships (e.g. videos) :
* [VolumetricConvolution](#nn.VolumetricConvolution) : a 3D convolution over an input video (a sequence of images) ;
* [VolumetricFullConvolution](#nn.VolumetricFullConvolution) : a 3D full convolution over an input video (a sequence of images) ;
* [VolumetricMaxPooling](#nn.VolumetricMaxPooling) : a 3D max-pooling operation over an input video.
* [VolumetricAveragePooling](#nn.VolumetricAveragePooling) : a 3D average-pooling operation over an input video.
* [VolumetricMaxUnpooling](#nn.VolumetricMaxUnpooling) : a 3D max-unpooling operation ;
<a name="nn.TemporalModules"></a>
## Temporal Modules ##
Excluding an optional first batch dimension, temporal layers expect a 2D Tensor as input. The
first dimension is the number of frames in the sequence (e.g. `nInputFrame`), the last dimension
is the number of features per frame (e.g. `inputFrameSize`). The output will normally have the same number
of dimensions, although the size of each dimension may change. These are commonly used for processing acoustic signals or sequences of words, i.e. in Natural Language Processing.
Note: The [LookupTable](#nn.LookupTable) is special in that while it does output a temporal Tensor of size `nOutputFrame x outputFrameSize`,
its input is a 1D Tensor of indices of size `nIndices`. Again, this is excluding the option first batch dimension.
<a name="nn.TemporalConvolution"></a>
## TemporalConvolution ##
```lua
module = nn.TemporalConvolution(inputFrameSize, outputFrameSize, kW, [dW])
```
Applies a 1D convolution over an input sequence composed of `nInputFrame` frames. The `input` tensor in
`forward(input)` is expected to be a 2D tensor (`nInputFrame x inputFrameSize`) or a 3D tensor (`nBatchFrame x nInputFrame x inputFrameSize`).
The parameters are the following:
* `inputFrameSize`: The input frame size expected in sequences given into `forward()`.
* `outputFrameSize`: The output frame size the convolution layer will produce.
* `kW`: The kernel width of the convolution
* `dW`: The step of the convolution. Default is `1`.
Note that depending of the size of your kernel, several (of the last)
frames of the sequence might be lost. It is up to the user to add proper padding frames in the input
sequences.
If the input sequence is a 2D tensor of dimension `nInputFrame x inputFrameSize`, the output sequence will be
`nOutputFrame x outputFrameSize` where
```lua
nOutputFrame = (nInputFrame - kW) / dW + 1
```
If the input sequence is a 3D tensor of dimension `nBatchFrame x nInputFrame x inputFrameSize`, the output sequence will be
`nBatchFrame x nOutputFrame x outputFrameSize`.
The parameters of the convolution can be found in `self.weight` (Tensor of
size `outputFrameSize x (inputFrameSize x kW) `) and `self.bias` (Tensor of
size `outputFrameSize`). The corresponding gradients can be found in
`self.gradWeight` and `self.gradBias`.
For a 2D input, the output value of the layer can be precisely described as:
```lua
output[t][i] = bias[i]
+ sum_j sum_{k=1}^kW weight[i][j][k]
* input[dW*(t-1)+k)][j]
```
Here is a simple example:
```lua
inp=5; -- dimensionality of one sequence element
outp=1; -- number of derived features for one sequence element
kw=1; -- kernel only operates on one sequence element per step
dw=1; -- we step once and go on to the next sequence element
mlp=nn.TemporalConvolution(inp,outp,kw,dw)
x=torch.rand(7,inp) -- a sequence of 7 elements
print(mlp:forward(x))
```
which gives:
```lua
-0.9109
-0.9872
-0.6808
-0.9403
-0.9680
-0.6901
-0.6387
[torch.Tensor of dimension 7x1]
```
This is equivalent to:
```lua
weights=torch.reshape(mlp.weight,inp) -- weights applied to all
bias= mlp.bias[1];
for i=1,x:size(1) do -- for each sequence element
element= x[i]; -- features of ith sequence element
print(element:dot(weights) + bias)
end
```
which gives:
```lua
-0.91094998687717
-0.98721705771773
-0.68075004276185
-0.94030132495887
-0.96798754116609
-0.69008470895581
-0.63871422284166
```
<a name="nn.TemporalMaxPooling"></a>
## TemporalMaxPooling ##
```lua
module = nn.TemporalMaxPooling(kW, [dW])
```
Applies 1D max-pooling operation in `kW` regions by step size
`dW` steps. Input sequence composed of `nInputFrame` frames. The `input` tensor in
`forward(input)` is expected to be a 2D tensor (`nInputFrame x inputFrameSize`)
or a 3D tensor (`nBatchFrame x nInputFrame x inputFrameSize`).
If the input sequence is a 2D tensor of dimension `nInputFrame x inputFrameSize`, the output sequence will be
`nOutputFrame x inputFrameSize` where
```lua
nOutputFrame = (nInputFrame - kW) / dW + 1
```
<a name="nn.TemporalSubSampling"></a>
## TemporalSubSampling ##
```lua
module = nn.TemporalSubSampling(inputFrameSize, kW, [dW])
```
Applies a 1D sub-sampling over an input sequence composed of `nInputFrame` frames. The `input` tensor in
`forward(input)` is expected to be a 2D tensor (`nInputFrame x inputFrameSize`). The output frame size
will be the same as the input one (`inputFrameSize`).
The parameters are the following:
* `inputFrameSize`: The input frame size expected in sequences given into `forward()`.
* `kW`: The kernel width of the sub-sampling
* `dW`: The step of the sub-sampling. Default is `1`.
Note that depending of the size of your kernel, several (of the last)
frames of the sequence might be lost. It is up to the user to add proper padding frames in the input
sequences.
If the input sequence is a 2D tensor `nInputFrame x inputFrameSize`, the output sequence will be
`inputFrameSize x nOutputFrame` where
```lua
nOutputFrame = (nInputFrame - kW) / dW + 1
```
The parameters of the sub-sampling can be found in `self.weight` (Tensor of
size `inputFrameSize`) and `self.bias` (Tensor of
size `inputFrameSize`). The corresponding gradients can be found in
`self.gradWeight` and `self.gradBias`.
The output value of the layer can be precisely described as:
```lua
output[i][t] = bias[i] + weight[i] * sum_{k=1}^kW input[i][dW*(t-1)+k)]
```
<a name="nn.LookupTable"></a>
## LookupTable ##
```lua
module = nn.LookupTable(nIndex, sizes)
```
or
```lua
module = nn.LookupTable(nIndex, size1, [size2], [size3], ...)
```
This layer is a particular case of a convolution, where the width of the convolution would be `1`.
When calling `forward(input)`, it assumes `input` is a 1D or 2D tensor filled with indices.
If the input is a matrix, then each row is assumed to be an input sample of given batch. Indices start
at `1` and can go up to `nIndex`. For each index, it outputs a corresponding `Tensor` of size
specified by `sizes` (a `LongStorage`) or `size1 x size2 x...`.
Given a 1D input, the output tensors are concatenated,
generating a `n x size1 x size2 x ... x sizeN` tensor, where `n`
is the size of a 1D `input` tensor.
Again with a 1D input, when only `size1` is provided, the `forward(input)` is equivalent to
performing the following matrix-matrix multiplication in an efficient manner:
```lua
M P
```
where `M` is a 2D matrix `size1 x nIndex` containing the parameters of the lookup-table and
`P` is a 2D matrix, where each column vector `i` is a zero vector except at index `input[i]` where it is `1`.
1D example:
```lua
-- a lookup table containing 10 tensors of size 3
module = nn.LookupTable(10, 3)
input = torch.Tensor{1,2,1,10}
print(module:forward(input))
```
Outputs something like:
```lua
-1.4415 -0.1001 -0.1708
-0.6945 -0.4350 0.7977
-1.4415 -0.1001 -0.1708
-0.0745 1.9275 1.0915
[torch.DoubleTensor of dimension 4x3]
```
Note that the first row vector is the same as the 3rd one!
Given a 2D input tensor of size `m x n`, the output is a `m x n x size1 x size2 x ... x sizeN`
tensor, where `m` is the number of samples in
the batch and `n` is the number of indices per sample.
2D example:
```lua
-- a lookup table containing 10 tensors of size 3
module = nn.LookupTable(10, 3)
-- a batch of 2 samples of 4 indices each
input = torch.Tensor({{1,2,4,5},{4,3,2,10}})
print(module:forward(input))
```
Outputs something like:
```lua
(1,.,.) =
-0.0570 -1.5354 1.8555
-0.9067 1.3392 0.6275
1.9662 0.4645 -0.8111
0.1103 1.7811 1.5969
(2,.,.) =
1.9662 0.4645 -0.8111
0.0026 -1.4547 -0.5154
-0.9067 1.3392 0.6275
-0.0193 -0.8641 0.7396
[torch.DoubleTensor of dimension 2x4x3]
```
<a name="nn.SpatialModules"></a>
## Spatial Modules ##
Excluding an optional batch dimension, spatial layers expect a 3D Tensor as input. The
first dimension is the number of features (e.g. `frameSize`), the last two dimensions
are spatial (e.g. `height x width`). These are commonly used for processing images.
<a name="nn.SpatialConvolution"></a>
### SpatialConvolution ###
```lua
module = nn.SpatialConvolution(nInputPlane, nOutputPlane, kW, kH, [dW], [dH], [padW], [padH])
```
Applies a 2D convolution over an input image composed of several input planes. The `input` tensor in
`forward(input)` is expected to be a 3D tensor (`nInputPlane x height x width`).
The parameters are the following:
* `nInputPlane`: The number of expected input planes in the image given into `forward()`.
* `nOutputPlane`: The number of output planes the convolution layer will produce.
* `kW`: The kernel width of the convolution
* `kH`: The kernel height of the convolution
* `dW`: The step of the convolution in the width dimension. Default is `1`.
* `dH`: The step of the convolution in the height dimension. Default is `1`.
* `padW`: The additional zeros added per width to the input planes. Default is `0`, a good number is `(kW-1)/2`.
* `padH`: The additional zeros added per height to the input planes. Default is `padW`, a good number is `(kH-1)/2`.
Note that depending of the size of your kernel, several (of the last)
columns or rows of the input image might be lost. It is up to the user to
add proper padding in images.
If the input image is a 3D tensor `nInputPlane x height x width`, the output image size
will be `nOutputPlane x oheight x owidth` where
```lua
owidth = floor((width + 2*padW - kW) / dW + 1)
oheight = floor((height + 2*padH - kH) / dH + 1)
```
The parameters of the convolution can be found in `self.weight` (Tensor of
size `nOutputPlane x nInputPlane x kH x kW`) and `self.bias` (Tensor of
size `nOutputPlane`). The corresponding gradients can be found in
`self.gradWeight` and `self.gradBias`.
The output value of the layer can be precisely described as:
```lua
output[i][j][k] = bias[k]
+ sum_l sum_{s=1}^kW sum_{t=1}^kH weight[s][t][l][k]
* input[dW*(i-1)+s)][dH*(j-1)+t][l]
```
<a name="nn.SpatialConvolutionMap"></a>
### SpatialConvolutionMap ###
```lua
module = nn.SpatialConvolutionMap(connectionMatrix, kW, kH, [dW], [dH])
```
This class is a generalization of
[nn.SpatialConvolution](#nn.SpatialConvolution). It uses a generic
connection table between input and output features. The
[nn.SpatialConvolution](#nn.SpatialConvolution) is equivalent to
using a [full connection table](#nn.tables.full). One can specify
different types of connection tables.
<a name="nn.tables.full"></a>
#### Full Connection Table ####
```lua
table = nn.tables.full(nin,nout)
```
This is a precomputed table that specifies connections between every
input and output node.
<a name="nn.tables.onetoone"></a>
#### One to One Connection Table ####
```lua
table = nn.tables.oneToOne(n)
```
This is a precomputed table that specifies a single connection to each
output node from corresponding input node.
<a name="nn.tables.random"></a>
#### Random Connection Table ####
```lua
table = nn.tables.random(nin,nout, nto)
```
This table is randomly populated such that each output unit has
`nto` incoming connections. The algorithm tries to assign uniform
number of outgoing connections to each input node if possible.
<a name="nn.SpatialFullConvolution"></a>
### SpatialFullConvolution ###
```lua
module = nn.SpatialFullConvolution(nInputPlane, nOutputPlane, kW, kH, [dW], [dH], [padW], [padH], [adjW], [adjH])
```
Applies a 2D full convolution over an input image composed of several input planes. The `input` tensor in
`forward(input)` is expected to be a 3D or 4D tensor.
Other frameworks call this operation "In-network Upsampling", "Fractionally-strided convolution", "Backwards Convolution," "Deconvolution", or "Upconvolution."
The parameters are the following:
* `nInputPlane`: The number of expected input planes in the image given into `forward()`.
* `nOutputPlane`: The number of output planes the convolution layer will produce.
* `kW`: The kernel width of the convolution
* `kH`: The kernel height of the convolution
* `dW`: The step of the convolution in the width dimension. Default is `1`.
* `dH`: The step of the convolution in the height dimension. Default is `1`.
* `padW`: The additional zeros added per width to the input planes. Default is `0`, a good number is `(kW-1)/2`.
* `padH`: The additional zeros added per height to the input planes. Default is `0`, a good number is `(kH-1)/2`.
* `adjW`: Extra width to add to the output image. Default is `0`. Cannot be greater than dW-1.
* `adjH`: Extra height to add to the output image. Default is `0`. Cannot be greater than dH-1.
If the input image is a 3D tensor `nInputPlane x height x width`, the output image size
will be `nOutputPlane x oheight x owidth` where
```lua
owidth = (width - 1) * dW - 2*padW + kW + adjW
oheight = (height - 1) * dH - 2*padH + kH + adjH
```
Further information about the full convolution can be found in the following paper: [Fully Convolutional Networks for Semantic Segmentation](http://www.cs.berkeley.edu/~jonlong/long_shelhamer_fcn.pdf).
<a name="nn.SpatialConvolutionLocal"></a>
### SpatialConvolutionLocal ###
```lua
module = nn.SpatialConvolutionLocal(nInputPlane, nOutputPlane, iW, iH, kW, kH, [dW], [dH], [padW], [padH])
```
Applies a 2D locally-connected layer over an input image composed of several input planes. The `input` tensor in
`forward(input)` is expected to be a 3D or 4D tensor.
A locally-connected layer is similar to a convolution layer but without weight-sharing.
The parameters are the following:
* `nInputPlane`: The number of expected input planes in the image given into `forward()`.
* `nOutputPlane`: The number of output planes the locally-connected layer will produce.
* `iW`: The input width.
* `iH`: The input height.
* `kW`: The kernel width.
* `kH`: The kernel height.
* `dW`: The step in the width dimension. Default is `1`.
* `dH`: The step in the height dimension. Default is `1`.
* `padW`: The additional zeros added per width to the input planes. Default is `0`, a good number is `(kW-1)/2`.
* `padH`: The additional zeros added per height to the input planes. Default is `0`, a good number is `(kH-1)/2`.
If the input image is a 3D tensor `nInputPlane x iH x iW`, the output image size
will be `nOutputPlane x oH x oW` where
```lua
oW = floor((iW + 2*padW - kW) / dW + 1)
oH = floor((iH + 2*padH - kH) / dH + 1)
```
<a name="nn.SpatialLPPooling"></a>
### SpatialLPPooling ###
```lua
module = nn.SpatialLPPooling(nInputPlane, pnorm, kW, kH, [dW], [dH])
```
Computes the `p` norm in a convolutional manner on a set of 2D input planes.
<a name="nn.SpatialMaxPooling"></a>
### SpatialMaxPooling ###
```lua
module = nn.SpatialMaxPooling(kW, kH [, dW, dH, padW, padH])
```
Applies 2D max-pooling operation in `kWxkH` regions by step size
`dWxdH` steps. The number of output features is equal to the number of
input planes.
If the input image is a 3D tensor `nInputPlane x height x width`, the output
image size will be `nOutputPlane x oheight x owidth` where
```lua
owidth = op((width + 2*padW - kW) / dW + 1)
oheight = op((height + 2*padH - kH) / dH + 1)
```
`op` is a rounding operator. By default, it is `floor`. It can be changed
by calling `:ceil()` or `:floor()` methods.
<a name="nn.SpatialFractionalMaxPooling"></a>
### SpatialFractionalMaxPooling ###
```lua
module = nn.SpatialFractionalMaxPooling(kW, kH, outW, outH)
-- the output should be the exact size (outH x outW)
OR
module = nn.SpatialFractionalMaxPooling(kW, kH, ratioW, ratioH)
-- the output should be the size (floor(inH x ratioH) x floor(inW x ratioW))
-- ratios are numbers between (0, 1) exclusive
```
Applies 2D Fractional max-pooling operation as described in the
paper ["Fractional Max Pooling" by Ben Graham](http://arxiv.org/abs/1412.6071) in the "pseudorandom" mode.
The max-pooling operation is applied in `kWxkH` regions by a stochastic step size determined by the target output size.
The number of output features is equal to the number of input planes.
There are two constructors available.
Constructor 1:
```lua
module = nn.SpatialFractionalMaxPooling(kW, kH, outW, outH)
```
Constructor 2:
```lua
module = nn.SpatialFractionalMaxPooling(kW, kH, ratioW, ratioH)
```
If the input image is a 3D tensor `nInputPlane x height x width`, the output
image size will be `nOutputPlane x oheight x owidth`
where
```lua
owidth = floor(width * ratioW)
oheight = floor(height * ratioH)
```
ratios are numbers between (0, 1) exclusive
<a name="nn.SpatialAveragePooling"></a>
### SpatialAveragePooling ###
```lua
module = nn.SpatialAveragePooling(kW, kH [, dW, dH, padW, padH])
```
Applies 2D average-pooling operation in `kWxkH` regions by step size
`dWxdH` steps. The number of output features is equal to the number of
input planes.
If the input image is a 3D tensor `nInputPlane x height x width`, the output
image size will be `nOutputPlane x oheight x owidth` where
```lua
owidth = op((width + 2*padW - kW) / dW + 1)
oheight = op((height + 2*padH - kH) / dH + 1)
```
`op` is a rounding operator. By default, it is `floor`. It can be changed
by calling `:ceil()` or `:floor()` methods.
By default, the output of each pooling region is divided by the number of
elements inside the padded image (which is usually `kW*kH`, except in some
corner cases in which it can be smaller). You can also divide by the number
of elements inside the original non-padded image. To switch between different
division factors, call `:setCountIncludePad()` or `:setCountExcludePad()`. If
`padW=padH=0`, both options give the same results.
<a name="nn.SpatialAdaptiveMaxPooling"></a>
### SpatialAdaptiveMaxPooling ###
```lua
module = nn.SpatialAdaptiveMaxPooling(W, H)
```
Applies 2D max-pooling operation in an image such that the output is of
size `WxH`, for any input size. The number of output features is equal
to the number of input planes.
For an output of dimensions `(owidth,oheight)`, the indexes of the pooling
region `(j,i)` in the input image of dimensions `(iwidth,iheight)` are
given by:
```lua
x_j_start = floor((j /owidth) * iwidth)
x_j_end = ceil(((j+1)/owidth) * iwidth)
y_i_start = floor((i /oheight) * iheight)
y_i_end = ceil(((i+1)/oheight) * iheight)
```
<a name="nn.SpatialMaxUnpooling"></a>
### SpatialMaxUnpooling ###
```lua
module = nn.SpatialMaxUnpooling(poolingModule)
```
Applies 2D "max-unpooling" operation using the indices previously computed
by the SpatialMaxPooling module `poolingModule`.
When `B = poolingModule:forward(A)` is called, the indices of the maximal
values (corresponding to their position within each map) are stored:
`B[{n,k,i,j}] = A[{n,k,indices[{n,k,i}],indices[{n,k,j}]}]`.
If `C` is a tensor of same size as `B`, `module:updateOutput(C)` outputs a
tensor `D` of same size as `A` such that:
`D[{n,k,indices[{n,k,i}],indices[{n,k,j}]}] = C[{n,k,i,j}]`.
Module inspired by:
"Visualizing and understanding convolutional networks" (2014)
by Matthew Zeiler, Rob Fergus
<a name="nn.SpatialSubSampling"></a>
### SpatialSubSampling ###
```lua
module = nn.SpatialSubSampling(nInputPlane, kW, kH, [dW], [dH])
```
Applies a 2D sub-sampling over an input image composed of several input planes. The `input` tensor in
`forward(input)` is expected to be a 3D tensor (`nInputPlane x height x width`). The number of output
planes will be the same as `nInputPlane`.
The parameters are the following:
* `nInputPlane`: The number of expected input planes in the image given into `forward()`.
* `kW`: The kernel width of the sub-sampling
* `kH`: The kernel height of the sub-sampling
* `dW`: The step of the sub-sampling in the width dimension. Default is `1`.
* `dH`: The step of the sub-sampling in the height dimension. Default is `1`.
Note that depending of the size of your kernel, several (of the last)
columns or rows of the input image might be lost. It is up to the user to
add proper padding in images.
If the input image is a 3D tensor `nInputPlane x height x width`, the output image size
will be `nInputPlane x oheight x owidth` where
```lua
owidth = (width - kW) / dW + 1
oheight = (height - kH) / dH + 1 .
```
The parameters of the sub-sampling can be found in `self.weight` (Tensor of
size `nInputPlane`) and `self.bias` (Tensor of size `nInputPlane`). The
corresponding gradients can be found in `self.gradWeight` and
`self.gradBias`.
The output value of the layer can be precisely described as:
```lua
output[i][j][k] = bias[k]
+ weight[k] sum_{s=1}^kW sum_{t=1}^kH input[dW*(i-1)+s)][dH*(j-1)+t][k]
```
<a name="nn.SpatialUpSamplingNearest"></a>
### SpatialUpSamplingNearest ###
```lua
module = nn.SpatialUpSamplingNearest(scale)
```
Applies a 2D up-sampling over an input image composed of several input planes. The `input` tensor in
`forward(input)` is expected to be a 3D or 4D tensor (i.e. for 4D: `nBatchPlane x nInputPlane x height x width`). The number of output planes will be the same. The v dimension is assumed to be the second last dimension (i.e. for 4D it will be the 3rd dim), and the u dimension is assumed to be the last dimension.
The parameters are the following:
* `scale`: The upscale ratio. Must be a positive integer
The up-scaling method is simple nearest neighbor, ie:
```lua
output(u,v) = input(floor((u-1)/scale)+1, floor((v-1)/scale)+1)
```
Where `u` and `v` are index from 1 (as per lua convention). There are no learnable parameters.
<a name="nn.SpatialZeroPadding"></a>
### SpatialZeroPadding ###
```lua
module = nn.SpatialZeroPadding(padLeft, padRight, padTop, padBottom)
```
Each feature map of a given input is padded with specified number of
zeros. If padding values are negative, then input is cropped.
<a name="nn.SpatialSubtractiveNormalization"></a>
### SpatialSubtractiveNormalization ###
```lua
module = nn.SpatialSubtractiveNormalization(ninputplane, kernel)
```
Applies a spatial subtraction operation on a series of 2D inputs using
`kernel` for computing the weighted average in a neighborhood. The
neighborhood is defined for a local spatial region that is the size as
kernel and across all features. For a an input image, since there is
only one feature, the region is only spatial. For an RGB image, the
weighted average is taken over RGB channels and a spatial region.
If the `kernel` is 1D, then it will be used for constructing and seperable
2D kernel. The operations will be much more efficient in this case.
The kernel is generally chosen as a gaussian when it is believed that
the correlation of two pixel locations decrease with increasing
distance. On the feature dimension, a uniform average is used since
the weighting across features is not known.
For this example we use an external package
[image](http://www.github.com/clementfarabet/lua---image/)
```lua
require 'image'
require 'nn'
lena = image.rgb2y(image.lena())
ker = torch.ones(11)
m=nn.SpatialSubtractiveNormalization(1,ker)
processed = m:forward(lena)
w1=image.display(lena)
w2=image.display(processed)
```

<a name="nn.SpatialCrossMapLRN"></a>
### SpatialCrossMapLRN ###
```lua
module = nn.SpatialCrossMapLRN(size [,alpha] [,beta] [,k])
```
Applies Spatial Local Response Normalization between different feature maps.
By default, `alpha = 0.0001`, `beta = 0.75` and `k = 1`
The operation implemented is:
```
x_f
y_f = -------------------------------------------------
(k+(alpha/size)* sum_{l=l1 to l2} (x_l^2))^beta
```
where `x_f` is the input at spatial locations `h,w` (not shown for simplicity) and feature map `f`,
`l1` corresponds to `max(0,f-ceil(size/2))` and `l2` to `min(F, f-ceil(size/2) + size)`. Here, `F`
is the number of feature maps.
More information can be found [here](https://code.google.com/p/cuda-convnet2/wiki/LayerParams#Local_response_normalization_layer_%28across_maps%29).
<a name="nn.SpatialBatchNormalization"></a>
## SpatialBatchNormalization ##
`module` = `nn.SpatialBatchNormalization(N [,eps] [, momentum] [,affine])`
where N = number of input feature maps
eps is a small value added to the standard-deviation to avoid divide-by-zero. Defaults to 1e-5
`affine` is a boolean. When set to false, the learnable affine transform is disabled. Defaults to true
Implements Batch Normalization as described in the paper:
"Batch Normalization: Accelerating Deep Network Training
by Reducing Internal Covariate Shift"
by Sergey Ioffe, Christian Szegedy
The operation implemented is:
```
y = ( x - mean(x) )
-------------------- * gamma + beta
standard-deviation(x)
```
where the mean and standard-deviation are calculated per feature-map over the mini-batches and pixels
and where gamma and beta are learnable parameter vectors of size N (where N = number of feature maps).
The learning of gamma and beta is optional.
In training time, this layer keeps a running estimate of it's computed mean and std.
The running sum is kept with a default momentup of 0.1 (unless over-ridden)
In test time, this running mean/std is used to normalize.
The module only accepts 4D inputs.
```lua
-- with learnable parameters
model = nn.SpatialBatchNormalization(m)
A = torch.randn(b, m, h, w)
C = model:forward(A) -- C will be of size `b x m x h x w`
-- without learnable parameters
model = nn.SpatialBatchNormalization(m, nil, nil, false)
A = torch.randn(b, m, h, w)
C = model:forward(A) -- C will be of size `b x m x h x w`
```
<a name="nn.VolumetricModules"></a>
## Volumetric Modules ##
Excluding an optional batch dimension, volumetric layers expect a 4D Tensor as input. The
first dimension is the number of features (e.g. `frameSize`), the second is sequential (e.g. `time`) and the
last two dimensions are spatial (e.g. `height x width`). These are commonly used for processing videos (sequences of images).
<a name="nn.VolumetricConvolution"></a>
### VolumetricConvolution ###
```lua
module = nn.VolumetricConvolution(nInputPlane, nOutputPlane, kT, kW, kH [, dT, dW, dH, padT, padW, padH])
```
Applies a 3D convolution over an input image composed of several input planes. The `input` tensor in
`forward(input)` is expected to be a 4D tensor (`nInputPlane x time x height x width`).
The parameters are the following:
* `nInputPlane`: The number of expected input planes in the image given into `forward()`.
* `nOutputPlane`: The number of output planes the convolution layer will produce.
* `kT`: The kernel size of the convolution in time
* `kW`: The kernel width of the convolution
* `kH`: The kernel height of the convolution
* `dT`: The step of the convolution in the time dimension. Default is `1`.
* `dW`: The step of the convolution in the width dimension. Default is `1`.
* `dH`: The step of the convolution in the height dimension. Default is `1`.
* `padT`: The additional zeros added per time to the input planes. Default is `0`, a good number is `(kT-1)/2`.
* `padW`: The additional zeros added per width to the input planes. Default is `0`, a good number is `(kW-1)/2`.
* `padH`: The additional zeros added per height to the input planes. Default is `0`, a good number is `(kH-1)/2`.
Note that depending of the size of your kernel, several (of the last)
columns or rows of the input image might be lost. It is up to the user to
add proper padding in images.
If the input image is a 4D tensor `nInputPlane x time x height x width`, the output image size
will be `nOutputPlane x otime x owidth x oheight` where
```lua
otime = floor((time + 2*padT - kT) / dT + 1)
owidth = floor((width + 2*padW - kW) / dW + 1)
oheight = floor((height + 2*padH - kH) / dH + 1)
```
The parameters of the convolution can be found in `self.weight` (Tensor of
size `nOutputPlane x nInputPlane x kT x kH x kW`) and `self.bias` (Tensor of
size `nOutputPlane`). The corresponding gradients can be found in
`self.gradWeight` and `self.gradBias`.
<a name="nn.VolumetricFullConvolution"></a>
### VolumetricFullConvolution ###
```lua
module = nn.VolumetricFullConvolution(nInputPlane, nOutputPlane, kT, kW, kH, [dT], [dW], [dH], [padT], [padW], [padH])
```
Applies a 3D full convolution over an input image composed of several input planes. The `input` tensor in
`forward(input)` is expected to be a 4D or 5D tensor.
The parameters are the following:
* `nInputPlane`: The number of expected input planes in the image given into `forward()`.
* `nOutputPlane`: The number of output planes the convolution layer will produce.
* `kT`: The kernel depth of the convolution
* `kW`: The kernel width of the convolution
* `kH`: The kernel height of the convolution
* `dT`: The step of the convolution in the depth dimension. Default is `1`.
* `dW`: The step of the convolution in the width dimension. Default is `1`.
* `dH`: The step of the convolution in the height dimension. Default is `1`.
* `padT`: The additional zeros added per depth to the input planes. Default is `0`, a good number is `(kT-1)/2`.
* `padW`: The additional zeros added per width to the input planes. Default is `0`, a good number is `(kW-1)/2`.
* `padH`: The additional zeros added per height to the input planes. Default is `0`, a good number is `(kH-1)/2`.
If the input image is a 3D tensor `nInputPlane x depth x height x width`, the output image size
will be `nOutputPlane x odepth x oheight x owidth` where
```lua
odepth = (depth - 1) * dT - 2*padT + kT
owidth = (width - 1) * dW - 2*padW + kW
oheight = (height - 1) * dH - 2*padH + kH
```
<a name="nn.VolumetricMaxPooling"></a>
### VolumetricMaxPooling ###
```lua
module = nn.VolumetricMaxPooling(kT, kW, kH [, dT, dW, dH, padT, padW, padH])
```
Applies 3D max-pooling operation in `kTxkWxkH` regions by step size
`dTxdWxdH` steps. The number of output features is equal to the number of
input planes / dT. The input can optionally be padded with zeros. Padding should be smaller than half of kernel size. That is, `padT < kT/2`, `padW < kW/2` and `padH < kH/2`.
<a name="nn.VolumetricAveragePooling"></a>
### VolumetricAveragePooling ###
```lua
module = nn.VolumetricAveragePooling(kT, kW, kH [, dT, dW, dH])
```
Applies 3D average-pooling operation in `kTxkWxkH` regions by step size
`dTxdWxdH` steps. The number of output features is equal to the number of
input planes / dT.
<a name="nn.VolumetricMaxUnpooling"></a>
### VolumetricMaxUnpooling ###
```lua
module = nn.VolumetricMaxUnpooling(poolingModule)
```
Applies 3D "max-unpooling" operation using the indices previously computed
by the VolumetricMaxPooling module `poolingModule`.
When `B = poolingModule:forward(A)` is called, the indices of the maximal
values (corresponding to their position within each map) are stored:
`B[{n,k,t,i,j}] = A[{n,k,indices[{n,k,t}],indices[{n,k,i}],indices[{n,k,j}]}]`.
If `C` is a tensor of same size as `B`, `module:updateOutput(C)` outputs a
tensor `D` of same size as `A` such that:
`D[{n,k,indices[{n,k,t}],indices[{n,k,i}],indices[{n,k,j}]}] = C[{n,k,t,i,j}]`.
| andreaskoepf/nn | doc/convolution.md | Markdown | bsd-3-clause | 34,886 |
from djangothis.app import read_yaml, read_yaml_file, watchfile
| amitu/djangothis | djangothis/__init__.py | Python | bsd-3-clause | 64 |
<?php
namespace app\models;
use Yii;
use app\components\EnglishBehavior;
/**
* This is the model class for table "dominant".
*
* @property integer $id
* @property string $name
* @property string $name_eng
*
* @property Main[] $mains
*/
class Dominant extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'dominant';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
EnglishBehavior::className(),
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'name_eng'], 'string']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'name_eng' => 'Name Eng',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getMains()
{
return $this->hasMany(Main::className(), ['dominant' => 'id']);
}
}
| martirosyan-kar/transproject-trash | models/Dominant.php | PHP | bsd-3-clause | 1,082 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_LOOKALIKES_LOOKALIKE_URL_SERVICE_H_
#define CHROME_BROWSER_LOOKALIKES_LOOKALIKE_URL_SERVICE_H_
#include <vector>
#include "base/callback_forward.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/field_trial_params.h"
#include "base/sequence_checker.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/lookalikes/core/lookalike_url_util.h"
class Profile;
namespace base {
class Clock;
}
// A service that handles operations on lookalike URLs. It can fetch the list of
// engaged sites in a background thread and cache the results until the next
// update. This is more efficient than fetching the list on each navigation for
// each tab separately.
class LookalikeUrlService : public KeyedService {
public:
explicit LookalikeUrlService(Profile* profile);
LookalikeUrlService(const LookalikeUrlService&) = delete;
LookalikeUrlService& operator=(const LookalikeUrlService&) = delete;
~LookalikeUrlService() override;
using EngagedSitesCallback =
base::OnceCallback<void(const std::vector<DomainInfo>&)>;
static LookalikeUrlService* Get(Profile* profile);
// Returns whether the engaged site list is recently updated. Returns true
// even when an update has already been queued or is in progress.
bool EngagedSitesNeedUpdating() const;
// Triggers an update to the engaged site list if one is not already inflight,
// then schedules |callback| to be called with the new list once available.
void ForceUpdateEngagedSites(EngagedSitesCallback callback);
// Returns the _current_ list of engaged sites, without updating them if
// they're out of date.
const std::vector<DomainInfo> GetLatestEngagedSites() const;
void SetClockForTesting(base::Clock* clock);
base::Clock* clock() const { return clock_; }
static const base::FeatureParam<base::TimeDelta> kManifestFetchDelay;
private:
void OnUpdateEngagedSitesCompleted(std::vector<DomainInfo> new_engaged_sites);
Profile* profile_;
base::Clock* clock_;
base::Time last_engagement_fetch_time_;
std::vector<DomainInfo> engaged_sites_ GUARDED_BY_CONTEXT(sequence_checker_);
// Indicates that an update to the engaged sites list has been queued. Serves
// to prevent enqueuing excessive updates.
bool update_in_progress_ = false;
std::vector<EngagedSitesCallback> pending_update_complete_callbacks_;
SEQUENCE_CHECKER(sequence_checker_);
base::WeakPtrFactory<LookalikeUrlService> weak_factory_{this};
};
#endif // CHROME_BROWSER_LOOKALIKES_LOOKALIKE_URL_SERVICE_H_
| scheib/chromium | chrome/browser/lookalikes/lookalike_url_service.h | C | bsd-3-clause | 2,860 |
<?php
/**
* Description of Model Description
*
* @author Purvesh <ind.purvesh@gmail.com>, <@kdecom>
*/
// module/Admin/src/Admin/Model/StickyNotesTable.php
namespace Admin\Model;
use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;
class ContactTable extends AbstractTableGateway {
protected $table = 'contact';
public function __construct(Adapter $adapter) {
$this->adapter = $adapter;
}
public function fetchAll(Select $select = null) {
if (null === $select)
$select = new Select();
$select->from($this->table);
$resultSet = $this->selectWith($select);
$resultSet->buffer();
return $resultSet;
}
public function getContactOptions() {
$contactOptions = array('' => 'Please Select Any');
$contacts = $this->fetchAll();
foreach ($contacts as $contact) {
$contactOptions [$contact->id] = $contact->first_name . " " . $contact->last_name;
}
return $contactOptions;
}
public function getContact($id) {
$row = $this->select(array('id' => (int) $id))->current();
if (!$row)
return false;
$rowObj = new Entity\Contact();
$rowObj->setId($row->id);
$rowObj->setFirstName($row->first_name);
$rowObj->setLastName($row->last_name);
$rowObj->setAddress($row->address);
$rowObj->setContactTypeId($row->contact_type_id);
return $rowObj;
}
public function save(Entity\Contact $entity) {
$data = array(
'first_name' => $entity->getFirstName(),
'last_name' => $entity->getLastName(),
'address' => $entity->getAddress(),
'contact_type_id' => $entity->getContactTypeId()
);
$id = (int) $entity->getId();
if ($id == 0) {
if (!$this->insert($data))
return false;
return $this->getLastInsertValue();
}
elseif ($this->getContact($id)) {
if (!$this->update($data, array('id' => $id)))
return false;
return $id;
}
else
return false;
}
public function remove($id) {
return $this->delete(array('id' => (int) $id));
}
} | indpurvesh/kd-project-management-system | module/Admin/src/Admin/Model/ContactTable.php | PHP | bsd-3-clause | 2,363 |
#include "sim/init.hh"
extern "C" {
void init_param_BasicPioDevice();
}
EmbeddedSwig embed_swig_param_BasicPioDevice(init_param_BasicPioDevice);
| silkyar/570_Big_Little | build/ARM/python/m5/internal/param_BasicPioDevice.i_init.cc | C++ | bsd-3-clause | 151 |
# coding: utf-8
# Copyright 2015 rpaas authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import unittest
from rpaas import plan, storage
class MongoDBStorageTestCase(unittest.TestCase):
def setUp(self):
self.storage = storage.MongoDBStorage()
self.storage.db[self.storage.quota_collection].remove()
self.storage.db[self.storage.plans_collection].remove()
self.storage.db[self.storage.plans_collection].insert(
{"_id": "small",
"description": "some cool plan",
"config": {"serviceofferingid": "abcdef123456"}}
)
self.storage.db[self.storage.plans_collection].insert(
{"_id": "huge",
"description": "some cool huge plan",
"config": {"serviceofferingid": "abcdef123459"}}
)
def test_set_team_quota(self):
q = self.storage.set_team_quota("myteam", 8)
used, quota = self.storage.find_team_quota("myteam")
self.assertEqual([], used)
self.assertEqual(8, quota)
self.assertEqual(used, q["used"])
self.assertEqual(quota, q["quota"])
def test_list_plans(self):
plans = self.storage.list_plans()
expected = [
{"name": "small", "description": "some cool plan",
"config": {"serviceofferingid": "abcdef123456"}},
{"name": "huge", "description": "some cool huge plan",
"config": {"serviceofferingid": "abcdef123459"}},
]
self.assertEqual(expected, [p.to_dict() for p in plans])
def test_find_plan(self):
plan = self.storage.find_plan("small")
expected = {"name": "small", "description": "some cool plan",
"config": {"serviceofferingid": "abcdef123456"}}
self.assertEqual(expected, plan.to_dict())
with self.assertRaises(storage.PlanNotFoundError):
self.storage.find_plan("something that doesn't exist")
def test_store_plan(self):
p = plan.Plan(name="super_huge", description="very huge thing",
config={"serviceofferingid": "abcdef123"})
self.storage.store_plan(p)
got_plan = self.storage.find_plan(p.name)
self.assertEqual(p.to_dict(), got_plan.to_dict())
def test_store_plan_duplicate(self):
p = plan.Plan(name="small", description="small thing",
config={"serviceofferingid": "abcdef123"})
with self.assertRaises(storage.DuplicateError):
self.storage.store_plan(p)
def test_update_plan(self):
p = plan.Plan(name="super_huge", description="very huge thing",
config={"serviceofferingid": "abcdef123"})
self.storage.store_plan(p)
self.storage.update_plan(p.name, description="wat?",
config={"serviceofferingid": "abcdef123459"})
p = self.storage.find_plan(p.name)
self.assertEqual("super_huge", p.name)
self.assertEqual("wat?", p.description)
self.assertEqual({"serviceofferingid": "abcdef123459"}, p.config)
def test_update_plan_partial(self):
p = plan.Plan(name="super_huge", description="very huge thing",
config={"serviceofferingid": "abcdef123"})
self.storage.store_plan(p)
self.storage.update_plan(p.name, config={"serviceofferingid": "abcdef123459"})
p = self.storage.find_plan(p.name)
self.assertEqual("super_huge", p.name)
self.assertEqual("very huge thing", p.description)
self.assertEqual({"serviceofferingid": "abcdef123459"}, p.config)
def test_update_plan_not_found(self):
with self.assertRaises(storage.PlanNotFoundError):
self.storage.update_plan("my_plan", description="woot")
def test_delete_plan(self):
p = plan.Plan(name="super_huge", description="very huge thing",
config={"serviceofferingid": "abcdef123"})
self.storage.store_plan(p)
self.storage.delete_plan(p.name)
with self.assertRaises(storage.PlanNotFoundError):
self.storage.find_plan(p.name)
def test_delete_plan_not_found(self):
with self.assertRaises(storage.PlanNotFoundError):
self.storage.delete_plan("super_huge")
def test_instance_metadata_storage(self):
self.storage.store_instance_metadata("myinstance", plan="small")
inst_metadata = self.storage.find_instance_metadata("myinstance")
self.assertEqual({"_id": "myinstance",
"plan": "small"}, inst_metadata)
self.storage.store_instance_metadata("myinstance", plan="medium")
inst_metadata = self.storage.find_instance_metadata("myinstance")
self.assertEqual({"_id": "myinstance", "plan": "medium"}, inst_metadata)
self.storage.remove_instance_metadata("myinstance")
inst_metadata = self.storage.find_instance_metadata("myinstance")
self.assertIsNone(inst_metadata)
| vfiebig/rpaas | tests/test_storage.py | Python | bsd-3-clause | 5,053 |
import Data.Either
import Test.Hspec
import qualified Text.Parsec as P
import Lib
import Lexer as L
import Parser as P
program = unlines
[ "dong inflate."
, "[ 3 ] value."
, "[ :x | x name ] value: 9."
]
lexerSpec = do
describe "parseToken" $ do
let parseToken = P.parse L.parseToken "(spec)"
it "parses LBracket" $ do
parseToken "[" `shouldBe` Right LBracket
it "parses RBracket" $ do
parseToken "]" `shouldBe` Right RBracket
it "parses Period" $ do
parseToken "." `shouldBe` Right Period
it "parses Pipe" $ do
parseToken "|" `shouldBe` Right Pipe
it "parses Bind" $ do
parseToken ":=" `shouldBe` Right Bind
it "parses Name" $ do
parseToken "abc" `shouldBe` Right (Name "abc")
it "parses a Name with a number" $ do
parseToken "abc1" `shouldBe` Right (Name "abc1")
it "parses Keyword" $ do
parseToken "abc:" `shouldBe` Right (Keyword "abc")
it "parses Arg" $ do
parseToken ":abc" `shouldBe` Right (Arg "abc")
it "parses Symbol" $ do
parseToken "+" `shouldBe` Right (Symbol "+")
it "parses StringLiteral" $ do
parseToken "'hello'" `shouldBe` Right (StringLiteral "hello")
it "parses CharLiteral" $ do
parseToken "$a" `shouldBe` Right (CharLiteral 'a')
it "parses Number" $ do
parseToken "32" `shouldBe` Right (Number 32)
parserSpec = do
let parse p s = do
lexed <- P.parse L.parseTokens "(spec)" s
P.parse p "(spec)" lexed
describe "parseLiteral" $ do
let parseLiteral = parse P.parseLiteral
it "parses string literal" $ do
parseLiteral "'hi'" `shouldBe` Right (LiteralString "hi")
it "parses number literal" $ do
parseLiteral "23" `shouldBe` Right (LiteralNumber 23)
describe "parseStatement" $ do
let parseStatement = parse P.parseStatement
it "parses unary message" $ do
parseStatement "abc def." `shouldBe`
Right (Statement [(ExpressionSend (OperandIdentifier "abc") [UnaryMessage "def"] [] [])] Nothing)
it "parses binary message" $ do
parseStatement "abc + def." `shouldBe`
Right (Statement [(ExpressionSend (OperandIdentifier "abc")
[]
[BinaryMessage "+" (OperandIdentifier "def")]
[])] Nothing)
it "parses keyword message" $ do
parseStatement "abc def: xyz." `shouldBe`
Right (Statement [(ExpressionSend (OperandIdentifier "abc")
[]
[]
[KeywordMessage "def" (OperandIdentifier "xyz")])] Nothing)
it "parses combined message" $ do
parseStatement "a b - c d: e." `shouldBe`
Right (Statement [(ExpressionSend (OperandIdentifier "a")
[UnaryMessage "b"]
[BinaryMessage "-" (OperandIdentifier "c")]
[KeywordMessage "d" (OperandIdentifier "e")])] Nothing)
it "parses message to nested expression" $ do
parseStatement "(a b) c." `shouldBe`
Right (Statement [(ExpressionSend (OperandNested (ExpressionSend (OperandIdentifier "a") [UnaryMessage "b"] [] []))
[UnaryMessage "c"]
[]
[])] Nothing)
it "parses a naked expression as a statement" $ do
parseStatement "3" `shouldBe` Right (Statement [] (Just $ ExpressionSend (OperandLiteral (LiteralNumber 3)) [] [] []))
it "parses block without args" $ do
parseStatement "[ 3 ]" `shouldBe`
Right (Statement [] (Just $ (ExpressionSend
(OperandBlock
(Block [] [Statement [] (Just $ ExpressionSend (OperandLiteral (LiteralNumber 3)) [] [] [])]))
[] [] []
)
))
it "parses block with args" $ do
parseStatement "[ :x | x ]" `shouldBe`
Right (Statement [] (Just $ (ExpressionSend
(OperandBlock
(Block ["x"] [Statement [] (Just $ ExpressionSend (OperandIdentifier "x") [] [] [])])
) [] [] []
)))
it "parses block with multiple args and statements" $ do
parseStatement "[ :x :y | 2 negate. x + y / 2 ]" `shouldBe`
Right (Statement [] (Just $ ExpressionSend
(OperandBlock
(Block ["x", "y"]
[Statement
[ExpressionSend (OperandLiteral (LiteralNumber 2)) [UnaryMessage "negate"] [] []]
(Just $ ExpressionSend (OperandIdentifier "x")
[]
[BinaryMessage "+" (OperandIdentifier "y"), BinaryMessage "/" (OperandLiteral (LiteralNumber 2))]
[]
)]
)
)
[] [] []))
it "does not parse statement with malformed binop" $ do
parseStatement "a + + b" `shouldSatisfy` isLeft
it "does not parse statement with malformed keyword message" $ do
parseStatement "a b: c: d" `shouldSatisfy` isLeft
main = do
hspec lexerSpec
hspec parserSpec | rjeli/luatalk | test/Spec.hs | Haskell | bsd-3-clause | 5,511 |
"use strict";
var SassExpandedRenderer = require('./sass-expanded-renderer');
/**
* @class SassNestedRenderer
* Nested style is the default Sass style, because it reflects the structure of
* the document in much the same way Sass does. Each rule is indented based on
* how deeply it's nested. Each property has its own line and is indented
* within the rule.
*/
var SassNestedRenderer = module.exports = SassExpandedRenderer.extend({
/**
* Renders the brace at the end of the rule
* @returns string the brace between the rule and its properties
*/
end: function() {
return " }\n";
},
/**
* Returns the indent string for the node
* @param {SassNode} node - the node being rendered
* @returns {string} the indent string for this SassNode
*/
getIndent: function(node) {
return new Array(node.level + 1).join(this.INDENT);
},
/**
* Renders a directive.
* @param {SassNode} node - the node being rendered
* @param {Array} properties - properties of the directive
* @returns {string} the rendered directive
*/
renderDirective: function(node, properties) {
var directive = this.getIndent(node) + node.directive + this.between() + this.renderProperties(properties);
return directive.replace(/(.*\})\n$/, '$1') + this.end();
},
/**
* Renders rule selectors.
* @param {SassNode} node - the node being rendered
* @returns {string} the rendered selectors
*/
renderSelectors: function(node) {
var indent = this.getIndent(node);
return indent.join(",\n" + indent, node.selectors);
}
});
| sstur/haml-js | sass/renderers/sass-nested-renderer.js | JavaScript | bsd-3-clause | 1,628 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>CUTLASS: cutlass::transform::threadblock::RegularTileIterator< Shape_, Element_, layout::TensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >::Detail Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
});
</script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="cutlass-logo-small.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">CUTLASS
</div>
<div id="projectbrief">CUDA Templates for Linear Algebra Subroutines and Solvers</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacecutlass.html">cutlass</a></li><li class="navelem"><a class="el" href="namespacecutlass_1_1transform.html">transform</a></li><li class="navelem"><a class="el" href="namespacecutlass_1_1transform_1_1threadblock.html">threadblock</a></li><li class="navelem"><a class="el" href="classcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_01efd5013a2503d6567e2bf6b40c97360c.html">RegularTileIterator< Shape_, Element_, layout::TensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment ></a></li><li class="navelem"><a class="el" href="structcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_052caec9d5bceeb59b9a13cb3338ce64d.html">Detail</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-static-attribs">Static Public Attributes</a> |
<a href="structcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_0bc37beaa523707a55987f4ffcc372fcd.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">cutlass::transform::threadblock::RegularTileIterator< Shape_, Element_, layout::TensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >::Detail Struct Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>Internal details made public to facilitate introspection.
</p>
<p><code>#include <<a class="el" href="regular__tile__iterator__tensor__op_8h_source.html">regular_tile_iterator_tensor_op.h</a>></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-static-attribs"></a>
Static Public Attributes</h2></td></tr>
<tr class="memitem:ab5ed9dfd3b28a68e629686369e7d2db2"><td class="memItemLeft" align="right" valign="top">static int const </td><td class="memItemRight" valign="bottom"><a class="el" href="structcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_052caec9d5bceeb59b9a13cb3338ce64d.html#ab5ed9dfd3b28a68e629686369e7d2db2">kAccessSizeInBits</a> = 128</td></tr>
<tr class="memdesc:ab5ed9dfd3b28a68e629686369e7d2db2"><td class="mdescLeft"> </td><td class="mdescRight">This iterator is specialized for an access size that is 128 bits in length. <a href="#ab5ed9dfd3b28a68e629686369e7d2db2">More...</a><br /></td></tr>
<tr class="separator:ab5ed9dfd3b28a68e629686369e7d2db2"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Member Data Documentation</h2>
<a class="anchor" id="ab5ed9dfd3b28a68e629686369e7d2db2"></a>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename Shape_ , typename Element_ , int AdvanceRank, typename ThreadMap_ , int Alignment> </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">int const <a class="el" href="classcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator.html">cutlass::transform::threadblock::RegularTileIterator</a>< Shape_, Element_, <a class="el" href="structcutlass_1_1layout_1_1TensorOpMultiplicandCongruous.html">layout::TensorOpMultiplicandCongruous</a>< <a class="el" href="structcutlass_1_1sizeof__bits.html">sizeof_bits</a>< Element_ >::value, int(128/sizeof(Element_))>, AdvanceRank, ThreadMap_, Alignment >::Detail::kAccessSizeInBits = 128</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">static</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<hr/>The documentation for this struct was generated from the following file:<ul>
<li><a class="el" href="regular__tile__iterator__tensor__op_8h_source.html">regular_tile_iterator_tensor_op.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| NVIDIA/cutlass | docs/structcutlass_1_1transform_1_1threadblock_1_1RegularTileIterator_3_01Shape___00_01Element___00_052caec9d5bceeb59b9a13cb3338ce64d.html | HTML | bsd-3-clause | 8,475 |
var Ipc = require('ipc');
// init states
var _states = {
'scene-initializing': false,
'scene-playing': false,
'scene-paused': false,
};
Editor.states = {};
function _defprop ( name, value ) {
Editor.states['_'+name] = value;
Object.defineProperty( Editor.states, name, {
get: function () { return Editor.states['_'+name]; },
set: function ( newValue ) {
if ( Editor.states['_'+name] !== newValue ) {
Editor.states['_'+name] = newValue;
Editor.sendToAll( 'editor:state-changed', name, newValue );
}
},
});
}
for ( var name in _states ) {
_defprop ( name, _states[name] );
}
Ipc.on('editor:state-changed', function ( name, value ) {
Editor.states['_'+name] = value;
});
// apply default main menu
var MainMenuTmplFn = require('./main-menu');
Editor.registerDefaultMainMenu(MainMenuTmplFn);
Editor.MainMenu.reset();
// init modules
Editor.Compiler = require('./compiler');
Editor.Builder = require('./builder');
// load scene utils
require('./scene-utils');
// asset-db ipc
require('./asset-db-ipc');
// ====================
// register events
// ====================
Editor.events.on('focus', function () {
Editor.assetdb.watchOFF();
});
Editor.events.on('blur', function () {
Editor.assetdb.watchON();
});
| bright-sparks/fireball | canvas-studio/core/init.js | JavaScript | bsd-3-clause | 1,334 |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using ServiceStack.Common;
using ServiceStack.Markdown;
using ServiceStack.ServiceHost;
using ServiceStack.WebHost.Endpoints.Formats;
namespace ServiceStack.WebHost.Endpoints.Support.Markdown
{
public class MarkdownPage : IExpirable
{
public const string ModelName = "Model";
public MarkdownPage()
{
this.ExecutionContext = new EvaluatorExecutionContext();
this.Dependents = new List<IExpirable>();
}
public MarkdownPage(MarkdownFormat markdown, string fullPath, string name, string contents)
: this(markdown, fullPath, name, contents, MarkdownPageType.ViewPage)
{
}
public MarkdownPage(MarkdownFormat markdown, string fullPath, string name, string contents, MarkdownPageType pageType)
: this()
{
Markdown = markdown;
FilePath = fullPath;
Name = name;
Contents = contents;
PageType = pageType;
}
public MarkdownFormat Markdown { get; set; }
private int timesRun;
private bool hasCompletedFirstRun;
public MarkdownPageType PageType { get; set; }
public string FilePath { get; set; }
public string Name { get; set; }
public string Contents { get; set; }
public string HtmlContents { get; set; }
public string TemplatePath { get; set; }
public string DirectiveTemplatePath { get; set; }
public EvaluatorExecutionContext ExecutionContext { get; private set; }
public DateTime? LastModified { get; set; }
public List<IExpirable> Dependents { get; private set; }
public DateTime? GetLastModified()
{
if (!hasCompletedFirstRun) return null;
var lastModified = this.LastModified;
foreach (var expirable in this.Dependents)
{
if (!expirable.LastModified.HasValue) continue;
if (!lastModified.HasValue || expirable.LastModified > lastModified)
{
lastModified = expirable.LastModified;
}
}
return lastModified;
}
public string GetTemplatePath()
{
return this.DirectiveTemplatePath ?? this.TemplatePath;
}
private Evaluator evaluator;
public Evaluator Evaluator
{
get
{
if (evaluator == null)
throw new InvalidOperationException("evaluator not ready");
return evaluator;
}
}
private int exprSeq;
public int GetNextId()
{
return exprSeq++;
}
public TemplateBlock[] MarkdownBlocks { get; set; }
public TemplateBlock[] HtmlBlocks { get; set; }
private Exception initException;
readonly object readWriteLock = new object();
private bool isBusy;
public void Reload()
{
var fi = new FileInfo(this.FilePath);
var lastModified = fi.LastWriteTime;
var contents = File.ReadAllText(this.FilePath);
lock (readWriteLock)
{
try
{
isBusy = true;
this.Contents = contents;
foreach (var markdownReplaceToken in Markdown.MarkdownReplaceTokens)
{
this.Contents = this.Contents.Replace(markdownReplaceToken.Key, markdownReplaceToken.Value);
}
this.LastModified = lastModified;
initException = null;
exprSeq = 0;
timesRun = 0;
ExecutionContext = new EvaluatorExecutionContext();
Prepare();
}
catch (Exception ex)
{
initException = ex;
}
isBusy = false;
Monitor.PulseAll(readWriteLock);
}
}
public void Prepare()
{
if (!typeof(MarkdownViewBase).IsAssignableFrom(this.Markdown.MarkdownBaseType))
{
throw new ConfigurationErrorsException(
"Config.MarkdownBaseType must inherit from MarkdownViewBase");
}
if (this.Contents.IsNullOrEmpty()) return;
foreach (var markdownReplaceToken in Markdown.MarkdownReplaceTokens)
{
this.Contents = this.Contents.Replace(markdownReplaceToken.Key, markdownReplaceToken.Value);
}
var markdownStatements = new List<StatementExprBlock>();
var markdownContents = StatementExprBlock.Extract(this.Contents, markdownStatements);
this.MarkdownBlocks = markdownContents.CreateTemplateBlocks(markdownStatements).ToArray();
var htmlStatements = new List<StatementExprBlock>();
var htmlContents = StatementExprBlock.Extract(this.Contents, htmlStatements);
this.HtmlContents = Markdown.Transform(htmlContents);
this.HtmlBlocks = this.HtmlContents.CreateTemplateBlocks(htmlStatements).ToArray();
SetTemplateDirectivePath();
}
private void SetTemplateDirectivePath()
{
var templateDirective = this.HtmlBlocks.FirstOrDefault(
x => x is DirectiveBlock && ((DirectiveBlock)x).TemplatePath != null);
if (templateDirective == null) return;
var fileDir = Path.GetDirectoryName(this.FilePath);
var templatePath = ((DirectiveBlock)templateDirective).TemplatePath;
if (templatePath.StartsWith("~"))
{
this.DirectiveTemplatePath = Path.GetFullPath(templatePath.ReplaceFirst("~", fileDir));
}
else
{
if (templatePath.IsRelativePath())
{
this.DirectiveTemplatePath = Path.GetFullPath(Path.Combine(fileDir, templatePath));
}
}
}
public void Write(TextWriter textWriter, PageContext pageContext)
{
if (textWriter == null)
throw new ArgumentNullException("textWriter");
if (pageContext == null)
pageContext = new PageContext(this, new Dictionary<string, object>(), true);
var blocks = pageContext.RenderHtml ? this.HtmlBlocks : this.MarkdownBlocks;
if (Interlocked.Increment(ref timesRun) == 1)
{
lock (readWriteLock)
{
try
{
isBusy = true;
this.ExecutionContext.BaseType = Markdown.MarkdownBaseType;
this.ExecutionContext.TypeProperties = Markdown.MarkdownGlobalHelpers;
pageContext.MarkdownPage = this;
var initHtmlContext = pageContext.Create(this, true);
var initMarkdownContext = pageContext.Create(this, false);
foreach (var block in this.HtmlBlocks) block.DoFirstRun(initHtmlContext);
foreach (var block in this.MarkdownBlocks) block.DoFirstRun(initMarkdownContext);
this.evaluator = this.ExecutionContext.Build();
foreach (var block in this.HtmlBlocks) block.AfterFirstRun(evaluator);
foreach (var block in this.MarkdownBlocks) block.AfterFirstRun(evaluator);
AddDependentPages(blocks);
initException = null;
hasCompletedFirstRun = true;
}
catch (Exception ex)
{
initException = ex;
throw;
}
finally
{
isBusy = false;
}
}
}
lock (readWriteLock)
{
while (isBusy)
Monitor.Wait(readWriteLock);
}
if (initException != null)
{
timesRun = 0;
throw initException;
}
MarkdownViewBase instance = null;
if (this.evaluator != null)
{
instance = (MarkdownViewBase)this.evaluator.CreateInstance();
object model;
pageContext.ScopeArgs.TryGetValue(ModelName, out model);
instance.Init(Markdown.AppHost, this, pageContext.ScopeArgs, model, pageContext.RenderHtml);
}
foreach (var block in blocks)
{
block.Write(instance, textWriter, pageContext.ScopeArgs);
}
if (instance != null)
{
instance.OnLoad();
}
}
private void AddDependentPages(IEnumerable<TemplateBlock> blocks)
{
foreach (var block in blocks)
{
var exprBlock = block as MethodStatementExprBlock;
if (exprBlock == null || exprBlock.DependentPageName == null) continue;
var page = Markdown.GetViewPage(exprBlock.DependentPageName);
if (page != null)
Dependents.Add(page);
}
MarkdownTemplate template;
if (this.DirectiveTemplatePath != null
&& Markdown.PageTemplates.TryGetValue(this.DirectiveTemplatePath, out template))
{
this.Dependents.Add(template);
}
if (this.TemplatePath != null
&& Markdown.PageTemplates.TryGetValue(this.TemplatePath, out template))
{
this.Dependents.Add(template);
}
}
}
} | mangra/ServiceStack | src/ServiceStack/WebHost.EndPoints/Support/Markdown/MarkdownPage.cs | C# | bsd-3-clause | 8,091 |
<?php
namespace frontend\controllers;
use Yii;
use common\models\PgmbillingHelpers;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
* Site controller
*/
class ReportsController extends Controller
{
public function actionEligibility()
{
return $this->render('eligibility',['PageInfoArr' => PgmbillingHelpers::getPageInfoArr('Reports', 'eligibility')]);
}
public function actionEligibilityResponse()
{
return $this->render('eligibility-response',['PageInfoArr' => PgmbillingHelpers::getPageInfoArr('Reports', 'eligibility-response')]);
}
public function actionIndex()
{
return $this->render('list',['PageInfoArr' => PgmbillingHelpers::getPageInfoArr('Reports', 'list')]);
}
public function actionList()
{
return $this->render('list',['PageInfoArr' => PgmbillingHelpers::getPageInfoArr('Reports', 'list')]);
}
}
| juanmcortez/systemclone_old | frontend/controllers/ReportsController.php | PHP | bsd-3-clause | 1,014 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.sandbox.distributions.extras.ACSkewT_gen.logcdf — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.sandbox.distributions.extras.ACSkewT_gen.logpdf" href="statsmodels.sandbox.distributions.extras.ACSkewT_gen.logpdf.html" />
<link rel="prev" title="statsmodels.sandbox.distributions.extras.ACSkewT_gen.isf" href="statsmodels.sandbox.distributions.extras.ACSkewT_gen.isf.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.sandbox.distributions.extras.ACSkewT_gen.logcdf" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.0</span>
<span class="md-header-nav__topic"> statsmodels.sandbox.distributions.extras.ACSkewT_gen.logcdf </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../distributions.html" class="md-tabs__link">Distributions</a></li>
<li class="md-tabs__item"><a href="statsmodels.sandbox.distributions.extras.ACSkewT_gen.html" class="md-tabs__link">statsmodels.sandbox.distributions.extras.ACSkewT_gen</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.0</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a>
</li>
<li class="md-nav__item">
<a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a>
</li>
<li class="md-nav__item">
<a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a>
</li>
<li class="md-nav__item">
<a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a>
</li>
<li class="md-nav__item">
<a href="../distributions.html" class="md-nav__link">Distributions</a>
</li>
<li class="md-nav__item">
<a href="../graphics.html" class="md-nav__link">Graphics</a>
</li>
<li class="md-nav__item">
<a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a>
</li>
<li class="md-nav__item">
<a href="../tools.html" class="md-nav__link">Tools</a>
</li>
<li class="md-nav__item">
<a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../optimization.html" class="md-nav__link">Optimization</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.sandbox.distributions.extras.ACSkewT_gen.logcdf.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-sandbox-distributions-extras-acskewt-gen-logcdf--page-root">statsmodels.sandbox.distributions.extras.ACSkewT_gen.logcdf<a class="headerlink" href="#generated-statsmodels-sandbox-distributions-extras-acskewt-gen-logcdf--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt id="statsmodels.sandbox.distributions.extras.ACSkewT_gen.logcdf">
<code class="sig-prename descclassname">ACSkewT_gen.</code><code class="sig-name descname">logcdf</code><span class="sig-paren">(</span><em class="sig-param"><span class="n">x</span></em>, <em class="sig-param"><span class="o">*</span><span class="n">args</span></em>, <em class="sig-param"><span class="o">**</span><span class="n">kwds</span></em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.sandbox.distributions.extras.ACSkewT_gen.logcdf" title="Permalink to this definition">¶</a></dt>
<dd><p>Log of the cumulative distribution function at x of the given RV.</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>x</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.19)"><span>array_like</span></a></span></dt><dd><p>quantiles</p>
</dd>
<dt><strong>arg1, arg2, arg3,…</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.19)"><span>array_like</span></a></span></dt><dd><p>The shape parameter(s) for the distribution (see docstring of the
instance object for more information)</p>
</dd>
<dt><strong>loc</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.19)"><span>array_like</span></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>location parameter (default=0)</p>
</dd>
<dt><strong>scale</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.19)"><span>array_like</span></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>scale parameter (default=1)</p>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl>
<dt><strong>logcdf</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/glossary.html#term-array-like" title="(in NumPy v1.19)"><span>array_like</span></a></span></dt><dd><p>Log of the cumulative distribution function evaluated at x</p>
</dd>
</dl>
</dd>
</dl>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.sandbox.distributions.extras.ACSkewT_gen.isf.html" title="statsmodels.sandbox.distributions.extras.ACSkewT_gen.isf"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.sandbox.distributions.extras.ACSkewT_gen.isf </span>
</div>
</a>
<a href="statsmodels.sandbox.distributions.extras.ACSkewT_gen.logpdf.html" title="statsmodels.sandbox.distributions.extras.ACSkewT_gen.logpdf"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.sandbox.distributions.extras.ACSkewT_gen.logpdf </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Aug 27, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | statsmodels/statsmodels.github.io | v0.12.0/generated/statsmodels.sandbox.distributions.extras.ACSkewT_gen.logcdf.html | HTML | bsd-3-clause | 20,753 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/ntp_tiles/most_visited_sites.h"
#include <stddef.h>
#include <map>
#include <memory>
#include <ostream>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/callback_list.h"
#include "base/command_line.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "components/history/core/browser/top_sites.h"
#include "components/history/core/browser/top_sites_observer.h"
#include "components/ntp_tiles/custom_links_manager.h"
#include "components/ntp_tiles/features.h"
#include "components/ntp_tiles/icon_cacher.h"
#include "components/ntp_tiles/popular_sites_impl.h"
#include "components/ntp_tiles/pref_names.h"
#include "components/ntp_tiles/section_type.h"
#include "components/ntp_tiles/switches.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace ntp_tiles {
// Defined for googletest. Must be defined in the same namespace.
void PrintTo(const NTPTile& tile, std::ostream* os) {
*os << "{\"" << tile.title << "\", \"" << tile.url << "\", "
<< static_cast<int>(tile.source) << "}";
}
namespace {
using history::MostVisitedURL;
using history::MostVisitedURLList;
using history::TopSites;
using testing::_;
using testing::AllOf;
using testing::AnyNumber;
using testing::AtLeast;
using testing::ByMove;
using testing::Contains;
using testing::DoAll;
using testing::ElementsAre;
using testing::Eq;
using testing::Ge;
using testing::InSequence;
using testing::Invoke;
using testing::IsEmpty;
using testing::Key;
using testing::Mock;
using testing::Not;
using testing::Pair;
using testing::Return;
using testing::ReturnRef;
using testing::SaveArg;
using testing::SizeIs;
using testing::StrictMock;
const char kHomepageUrl[] = "http://homepa.ge/";
const char16_t kHomepageTitle[] = u"Homepage";
const char kTestExploreUrl[] = "https://example.com/";
const char16_t kTestExploreTitle[] = u"Example";
std::string PrintTile(const std::u16string& title,
const std::string& url,
TileSource source) {
return std::string("has title \"") + base::UTF16ToUTF8(title) +
std::string("\" and url \"") + url + std::string("\" and source ") +
testing::PrintToString(static_cast<int>(source));
}
MATCHER_P3(MatchesTile, title, url, source, PrintTile(title, url, source)) {
return arg.title == title && arg.url == GURL(url) && arg.source == source;
}
std::string PrintTileSource(TileSource source) {
return std::string("has source ") +
testing::PrintToString(static_cast<int>(source));
}
MATCHER_P(TileWithSource, source, PrintTileSource(source)) {
return arg.source == source;
}
MATCHER_P3(LastTileIs,
title,
url,
source,
std::string("last tile ") + PrintTile(title, url, source)) {
const NTPTilesVector& tiles = arg.at(SectionType::PERSONALIZED);
if (tiles.empty())
return false;
const NTPTile& last = tiles.back();
return last.title == title && last.url == GURL(url) && last.source == source;
}
MATCHER_P3(FirstPersonalizedTileIs,
title,
url,
source,
std::string("first tile ") + PrintTile(title, url, source)) {
if (arg.count(SectionType::PERSONALIZED) == 0) {
return false;
}
const NTPTilesVector& tiles = arg.at(SectionType::PERSONALIZED);
return !tiles.empty() && tiles[0].title == title &&
tiles[0].url == GURL(url) && tiles[0].source == source;
}
NTPTile MakeTile(const std::u16string& title,
const std::string& url,
TileSource source) {
NTPTile tile;
tile.title = title;
tile.url = GURL(url);
tile.source = source;
return tile;
}
MostVisitedURL MakeMostVisitedURL(const std::u16string& title,
const std::string& url) {
MostVisitedURL result;
result.title = title;
result.url = GURL(url);
return result;
}
class MockTopSites : public TopSites {
public:
MOCK_METHOD0(ShutdownOnUIThread, void());
MOCK_METHOD1(GetMostVisitedURLs, void(GetMostVisitedURLsCallback callback));
MOCK_METHOD0(SyncWithHistory, void());
MOCK_CONST_METHOD0(HasBlockedUrls, bool());
MOCK_METHOD1(AddBlockedUrl, void(const GURL& url));
MOCK_METHOD1(RemoveBlockedUrl, void(const GURL& url));
MOCK_METHOD1(IsBlocked, bool(const GURL& url));
MOCK_METHOD0(ClearBlockedUrls, void());
MOCK_METHOD0(StartQueryForMostVisited, base::CancelableTaskTracker::TaskId());
MOCK_METHOD1(IsKnownURL, bool(const GURL& url));
MOCK_CONST_METHOD1(GetCanonicalURLString,
const std::string&(const GURL& url));
MOCK_METHOD0(IsFull, bool());
MOCK_CONST_METHOD0(loaded, bool());
MOCK_METHOD0(GetPrepopulatedPages, history::PrepopulatedPageList());
MOCK_METHOD1(OnNavigationCommitted, void(const GURL& url));
// Publicly expose notification to observers, since the implementation cannot
// be overriden.
using TopSites::NotifyTopSitesChanged;
protected:
~MockTopSites() override = default;
};
class MockMostVisitedSitesObserver : public MostVisitedSites::Observer {
public:
MOCK_METHOD1(OnURLsAvailable,
void(const std::map<SectionType, NTPTilesVector>& sections));
MOCK_METHOD1(OnIconMadeAvailable, void(const GURL& site_url));
};
class FakeHomepageClient : public MostVisitedSites::HomepageClient {
public:
FakeHomepageClient()
: homepage_tile_enabled_(false), homepage_url_(kHomepageUrl) {}
~FakeHomepageClient() override {}
bool IsHomepageTileEnabled() const override { return homepage_tile_enabled_; }
GURL GetHomepageUrl() const override { return homepage_url_; }
void QueryHomepageTitle(TitleCallback title_callback) override {
std::move(title_callback).Run(homepage_title_);
}
void SetHomepageTileEnabled(bool homepage_tile_enabled) {
homepage_tile_enabled_ = homepage_tile_enabled;
}
void SetHomepageUrl(GURL homepage_url) { homepage_url_ = homepage_url; }
void SetHomepageTitle(const absl::optional<std::u16string>& homepage_title) {
homepage_title_ = homepage_title;
}
private:
bool homepage_tile_enabled_;
GURL homepage_url_;
absl::optional<std::u16string> homepage_title_;
};
class FakeExploreSitesClient : public MostVisitedSites::ExploreSitesClient {
public:
~FakeExploreSitesClient() override = default;
GURL GetExploreSitesUrl() const override { return GURL(kTestExploreUrl); }
std::u16string GetExploreSitesTitle() const override {
return kTestExploreTitle;
}
};
class MockIconCacher : public IconCacher {
public:
MOCK_METHOD3(StartFetchPopularSites,
void(PopularSites::Site site,
base::OnceClosure icon_available,
base::OnceClosure preliminary_icon_available));
MOCK_METHOD2(StartFetchMostLikely,
void(const GURL& page_url, base::OnceClosure icon_available));
};
class MockCustomLinksManager : public CustomLinksManager {
public:
MOCK_METHOD1(Initialize, bool(const NTPTilesVector& tiles));
MOCK_METHOD0(Uninitialize, void());
MOCK_CONST_METHOD0(IsInitialized, bool());
MOCK_CONST_METHOD0(GetLinks, const std::vector<CustomLinksManager::Link>&());
MOCK_METHOD2(AddLink, bool(const GURL& url, const std::u16string& title));
MOCK_METHOD3(UpdateLink,
bool(const GURL& url,
const GURL& new_url,
const std::u16string& new_title));
MOCK_METHOD2(ReorderLink, bool(const GURL& url, size_t new_pos));
MOCK_METHOD1(DeleteLink, bool(const GURL& url));
MOCK_METHOD0(UndoAction, bool());
MOCK_METHOD1(RegisterCallbackForOnChanged,
base::CallbackListSubscription(base::RepeatingClosure callback));
};
class PopularSitesFactoryForTest {
public:
explicit PopularSitesFactoryForTest(
sync_preferences::TestingPrefServiceSyncable* pref_service)
: prefs_(pref_service) {
test_shared_loader_factory_ =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
&test_url_loader_factory_);
PopularSitesImpl::RegisterProfilePrefs(pref_service->registry());
}
void SeedWithSampleData() {
prefs_->SetString(prefs::kPopularSitesOverrideCountry, "IN");
prefs_->SetString(prefs::kPopularSitesOverrideVersion, "5");
test_url_loader_factory_.ClearResponses();
test_url_loader_factory_.AddResponse(
"https://www.gstatic.com/chrome/ntp/suggested_sites_IN_5.json",
R"([{
"title": "PopularSite1",
"url": "http://popularsite1/",
"favicon_url": "http://popularsite1/favicon.ico"
},
{
"title": "PopularSite2",
"url": "http://popularsite2/",
"favicon_url": "http://popularsite2/favicon.ico"
}
])");
test_url_loader_factory_.AddResponse(
"https://www.gstatic.com/chrome/ntp/suggested_sites_US_5.json",
R"([{
"title": "ESPN",
"url": "http://www.espn.com",
"favicon_url": "http://www.espn.com/favicon.ico"
}, {
"title": "Mobile",
"url": "http://www.mobile.de",
"favicon_url": "http://www.mobile.de/favicon.ico"
}, {
"title": "Google News",
"url": "http://news.google.com",
"favicon_url": "http://news.google.com/favicon.ico"
}
])");
test_url_loader_factory_.AddResponse(
"https://www.gstatic.com/chrome/ntp/suggested_sites_IN_6.json",
R"([{
"section": 1, // PERSONALIZED
"sites": [{
"title": "PopularSite1",
"url": "http://popularsite1/",
"favicon_url": "http://popularsite1/favicon.ico"
},
{
"title": "PopularSite2",
"url": "http://popularsite2/",
"favicon_url": "http://popularsite2/favicon.ico"
},
]
},
{
"section": 4, // NEWS
"sites": [{
"large_icon_url": "https://news.google.com/icon.ico",
"title": "Google News",
"url": "https://news.google.com/"
},
{
"favicon_url": "https://news.google.com/icon.ico",
"title": "Google News Germany",
"url": "https://news.google.de/"
}]
},
{
"section": 2, // SOCIAL
"sites": [{
"large_icon_url": "https://ssl.gstatic.com/icon.png",
"title": "Google+",
"url": "https://plus.google.com/"
}]
},
{
"section": 3, // ENTERTAINMENT
"sites": [
// Intentionally empty site list.
]
}
])");
}
std::unique_ptr<PopularSites> New() {
return std::make_unique<PopularSitesImpl>(prefs_,
/*template_url_service=*/nullptr,
/*variations_service=*/nullptr,
test_shared_loader_factory_);
}
private:
PrefService* prefs_;
network::TestURLLoaderFactory test_url_loader_factory_;
scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_;
};
} // namespace
// Param specifies whether Popular Sites is enabled via variations.
class MostVisitedSitesTest : public ::testing::TestWithParam<bool> {
protected:
using TopSitesCallbackList =
base::OnceCallbackList<TopSites::GetMostVisitedURLsCallback::RunType>;
MostVisitedSitesTest() {
MostVisitedSites::RegisterProfilePrefs(pref_service_.registry());
std::vector<base::Feature> enabled_features;
// Disable FaviconServer in most tests and override in specific tests.
std::vector<base::Feature> disabled_features = {
kNtpMostLikelyFaviconsFromServerFeature};
if (IsPopularSitesFeatureEnabled()) {
enabled_features.push_back(kUsePopularSitesSuggestions);
} else {
disabled_features.push_back(kUsePopularSitesSuggestions);
}
feature_list_.InitWithFeatures(enabled_features, disabled_features);
if (IsPopularSitesFeatureEnabled())
popular_sites_factory_.SeedWithSampleData();
RecreateMostVisitedSites();
}
void RecreateMostVisitedSites() {
// We use StrictMock to make sure the object is not used unless Popular
// Sites is enabled.
auto icon_cacher = std::make_unique<StrictMock<MockIconCacher>>();
icon_cacher_ = icon_cacher.get();
// Custom links needs to be nullptr when MostVisitedSites is created, unless
// the custom links feature is enabled. Custom links is disabled for
// Android, iOS, and third-party NTPs.
std::unique_ptr<StrictMock<MockCustomLinksManager>> mock_custom_links;
if (is_custom_links_enabled_) {
mock_custom_links =
std::make_unique<StrictMock<MockCustomLinksManager>>();
mock_custom_links_ = mock_custom_links.get();
}
if (IsPopularSitesFeatureEnabled()) {
// Populate Popular Sites' internal cache by mimicking a past usage of
// PopularSitesImpl.
auto tmp_popular_sites = popular_sites_factory_.New();
base::RunLoop loop;
bool save_success = false;
tmp_popular_sites->MaybeStartFetch(
/*force_download=*/true,
base::BindOnce(
[](bool* save_success, base::RunLoop* loop, bool success) {
*save_success = success;
loop->Quit();
},
&save_success, &loop));
loop.Run();
EXPECT_TRUE(save_success);
// With PopularSites enabled, blocked urls is exercised.
EXPECT_CALL(*mock_top_sites_, IsBlocked(_)).WillRepeatedly(Return(false));
// Mock icon cacher never replies, and we also don't verify whether the
// code uses it correctly.
EXPECT_CALL(*icon_cacher, StartFetchPopularSites(_, _, _))
.Times(AtLeast(0));
}
EXPECT_CALL(*icon_cacher, StartFetchMostLikely(_, _)).Times(AtLeast(0));
most_visited_sites_ = std::make_unique<MostVisitedSites>(
&pref_service_, mock_top_sites_, popular_sites_factory_.New(),
std::move(mock_custom_links), std::move(icon_cacher),
/*supervisor=*/nullptr);
}
bool IsPopularSitesFeatureEnabled() const { return GetParam(); }
bool VerifyAndClearExpectations() {
base::RunLoop().RunUntilIdle();
const bool success =
Mock::VerifyAndClearExpectations(mock_top_sites_.get()) &&
Mock::VerifyAndClearExpectations(&mock_observer_);
// For convenience, restore the expectations for IsBlocked().
if (IsPopularSitesFeatureEnabled()) {
EXPECT_CALL(*mock_top_sites_, IsBlocked(_)).WillRepeatedly(Return(false));
}
return success;
}
FakeHomepageClient* RegisterNewHomepageClient() {
auto homepage_client = std::make_unique<FakeHomepageClient>();
FakeHomepageClient* raw_client_ptr = homepage_client.get();
most_visited_sites_->SetHomepageClient(std::move(homepage_client));
return raw_client_ptr;
}
FakeExploreSitesClient* RegisterNewExploreSitesClient() {
auto explore_sites_client = std::make_unique<FakeExploreSitesClient>();
FakeExploreSitesClient* raw_client_ptr = explore_sites_client.get();
most_visited_sites_->SetExploreSitesClient(std::move(explore_sites_client));
return raw_client_ptr;
}
void EnableCustomLinks() { is_custom_links_enabled_ = true; }
bool is_custom_links_enabled_ = false;
TopSitesCallbackList top_sites_callbacks_;
base::test::SingleThreadTaskEnvironment task_environment_;
data_decoder::test::InProcessDataDecoder in_process_data_decoder_;
sync_preferences::TestingPrefServiceSyncable pref_service_;
PopularSitesFactoryForTest popular_sites_factory_{&pref_service_};
scoped_refptr<StrictMock<MockTopSites>> mock_top_sites_ =
base::MakeRefCounted<StrictMock<MockTopSites>>();
StrictMock<MockMostVisitedSitesObserver> mock_observer_;
StrictMock<MockMostVisitedSitesObserver> mock_other_observer_;
std::unique_ptr<MostVisitedSites> most_visited_sites_;
base::test::ScopedFeatureList feature_list_;
MockCustomLinksManager* mock_custom_links_;
MockIconCacher* icon_cacher_;
};
TEST_P(MostVisitedSitesTest, ShouldStartNoCallInConstructor) {
// No call to mocks expected by the mere fact of instantiating
// MostVisitedSites.
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldRefreshBackends) {
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
most_visited_sites_->Refresh();
}
TEST_P(MostVisitedSitesTest, ShouldIncludeTileForHomepage) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_, OnURLsAvailable(FirstPersonalizedTileIs(
u"", kHomepageUrl, TileSource::HOMEPAGE)));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldNotIncludeHomepageWithoutClient) {
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Contains(
Pair(SectionType::PERSONALIZED,
Not(Contains(MatchesTile(u"", kHomepageUrl,
TileSource::HOMEPAGE)))))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldIncludeHomeTileWithUrlBeforeQueryingName) {
// Because the query time for the real name might take a while, provide the
// home tile with URL as title immediately and update the tiles as soon as the
// real title was found.
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
homepage_client->SetHomepageTitle(kHomepageTitle);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
{
testing::Sequence seq;
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Contains(
Pair(SectionType::PERSONALIZED,
Not(Contains(MatchesTile(u"", kHomepageUrl,
TileSource::HOMEPAGE)))))));
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Contains(
Pair(SectionType::PERSONALIZED,
Not(Contains(MatchesTile(kHomepageTitle, kHomepageUrl,
TileSource::HOMEPAGE)))))));
}
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldUpdateHomepageTileWhenRefreshHomepageTile) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
// Ensure that home tile is available as usual.
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_, OnURLsAvailable(FirstPersonalizedTileIs(
u"", kHomepageUrl, TileSource::HOMEPAGE)));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
VerifyAndClearExpectations();
// Disable home page and rebuild _without_ Resync. The tile should be gone.
homepage_client->SetHomepageTileEnabled(false);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory()).Times(0);
EXPECT_CALL(mock_observer_, OnURLsAvailable(Not(FirstPersonalizedTileIs(
u"", kHomepageUrl, TileSource::HOMEPAGE))));
most_visited_sites_->RefreshTiles();
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldNotIncludeHomepageIfNoTileRequested) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(
mock_observer_,
OnURLsAvailable(Contains(Pair(SectionType::PERSONALIZED, IsEmpty()))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/0);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldReturnHomepageIfOneTileRequested) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>((
MostVisitedURLList{MakeMostVisitedURL(u"Site 1", "http://site1/")})));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(
mock_observer_,
OnURLsAvailable(Contains(Pair(
SectionType::PERSONALIZED,
ElementsAre(MatchesTile(u"", kHomepageUrl, TileSource::HOMEPAGE))))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldHaveHomepageFirstInListWhenFull) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>((MostVisitedURLList{
MakeMostVisitedURL(u"Site 1", "http://site1/"),
MakeMostVisitedURL(u"Site 2", "http://site2/"),
MakeMostVisitedURL(u"Site 3", "http://site3/"),
MakeMostVisitedURL(u"Site 4", "http://site4/"),
MakeMostVisitedURL(u"Site 5", "http://site5/"),
})));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
std::map<SectionType, NTPTilesVector> sections;
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/4);
base::RunLoop().RunUntilIdle();
ASSERT_THAT(sections, Contains(Key(SectionType::PERSONALIZED)));
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(4ul));
// Assert that the home page is appended as the final tile.
EXPECT_THAT(tiles[0], MatchesTile(u"", kHomepageUrl, TileSource::HOMEPAGE));
}
TEST_P(MostVisitedSitesTest, ShouldHaveHomepageFirstInListWhenNotFull) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>((MostVisitedURLList{
MakeMostVisitedURL(u"Site 1", "http://site1/"),
MakeMostVisitedURL(u"Site 2", "http://site2/"),
MakeMostVisitedURL(u"Site 3", "http://site3/"),
MakeMostVisitedURL(u"Site 4", "http://site4/"),
MakeMostVisitedURL(u"Site 5", "http://site5/"),
})));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
std::map<SectionType, NTPTilesVector> sections;
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/8);
base::RunLoop().RunUntilIdle();
ASSERT_THAT(sections, Contains(Key(SectionType::PERSONALIZED)));
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(6ul));
// Assert that the home page is the first tile.
EXPECT_THAT(tiles[0], MatchesTile(u"", kHomepageUrl, TileSource::HOMEPAGE));
}
TEST_P(MostVisitedSitesTest, ShouldDeduplicateHomepageWithTopSites) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(
(MostVisitedURLList{MakeMostVisitedURL(u"Site 1", "http://site1/"),
MakeMostVisitedURL(u"", kHomepageUrl)})));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(
mock_observer_,
OnURLsAvailable(Contains(Pair(
SectionType::PERSONALIZED,
AllOf(Contains(MatchesTile(u"", kHomepageUrl, TileSource::HOMEPAGE)),
Not(Contains(MatchesTile(u"", kHomepageUrl,
TileSource::TOP_SITES))))))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldNotIncludeHomepageIfThereIsNone) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(false);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Contains(
Pair(SectionType::PERSONALIZED,
Not(Contains(MatchesTile(u"", kHomepageUrl,
TileSource::HOMEPAGE)))))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldNotIncludeHomepageIfEmptyUrl) {
const std::string kEmptyHomepageUrl;
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
homepage_client->SetHomepageUrl(GURL(kEmptyHomepageUrl));
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(kEmptyHomepageUrl)))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Not(FirstPersonalizedTileIs(
u"", kEmptyHomepageUrl, TileSource::HOMEPAGE))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldNotIncludeHomepageIfBlocked) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(
(MostVisitedURLList{MakeMostVisitedURL(u"", kHomepageUrl)})));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AnyNumber())
.WillRepeatedly(Return(false));
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Contains(
Pair(SectionType::PERSONALIZED,
Not(Contains(MatchesTile(u"", kHomepageUrl,
TileSource::HOMEPAGE)))))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldPinHomepageAgainIfBlockedUndone) {
FakeHomepageClient* homepage_client = RegisterNewHomepageClient();
homepage_client->SetHomepageTileEnabled(true);
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillOnce(base::test::RunOnceCallback<0>(
(MostVisitedURLList{MakeMostVisitedURL(u"", kHomepageUrl)})));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AtLeast(1))
.WillRepeatedly(Return(true));
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Contains(
Pair(SectionType::PERSONALIZED,
Not(Contains(MatchesTile(u"", kHomepageUrl,
TileSource::HOMEPAGE)))))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
VerifyAndClearExpectations();
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillOnce(base::test::RunOnceCallback<0>(MostVisitedURLList{}));
EXPECT_CALL(*mock_top_sites_, IsBlocked(Eq(GURL(kHomepageUrl))))
.Times(AtLeast(1))
.WillRepeatedly(Return(false));
EXPECT_CALL(
mock_observer_,
OnURLsAvailable(Contains(Pair(
SectionType::PERSONALIZED,
Contains(MatchesTile(u"", kHomepageUrl, TileSource::HOMEPAGE))))));
most_visited_sites_->OnBlockedSitesChanged();
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldNotIncludeTileForExploreSitesIfNoClient) {
// Does not register an explore sites client.
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{
MakeMostVisitedURL(u"ESPN", "http://espn.com/"),
MakeMostVisitedURL(u"Mobile", "http://m.mobile.de/"),
MakeMostVisitedURL(u"Google", "http://www.google.com/")}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Not(Contains(
Pair(SectionType::PERSONALIZED,
Contains(TileWithSource(TileSource::EXPLORE)))))));
// Note that 5 sites are requested, this means that there should be the 3 from
// top sites and two from popular sites.
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/5);
base::RunLoop().RunUntilIdle();
}
// Tests that the explore sites tile appears when there is a mix of top sites
// and popular sites.
TEST_P(MostVisitedSitesTest, ShouldIncludeTileForExploreSites) {
RegisterNewExploreSitesClient();
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{
MakeMostVisitedURL(u"ESPN", "http://espn.com/"),
MakeMostVisitedURL(u"Mobile", "http://m.mobile.de/"),
MakeMostVisitedURL(u"Google", "http://www.google.com/")}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(mock_observer_,
OnURLsAvailable(LastTileIs(kTestExploreTitle, kTestExploreUrl,
TileSource::EXPLORE)));
// Note that 5 sites are requested, this means that there should be the 3 from
// top sites, one from popular sites, and one explore tile.
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/5);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, RemovesPersonalSiteIfExploreSitesTilePresent) {
RegisterNewExploreSitesClient();
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{
MakeMostVisitedURL(u"ESPN", "http://espn.com/"),
MakeMostVisitedURL(u"Mobile", "http://m.mobile.de/"),
MakeMostVisitedURL(u"Google", "http://www.google.com/")}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Contains(Pair(
SectionType::PERSONALIZED,
ElementsAre(MatchesTile(u"ESPN", "http://espn.com/",
TileSource::TOP_SITES),
MatchesTile(u"Mobile", "http://m.mobile.de/",
TileSource::TOP_SITES),
MatchesTile(kTestExploreTitle, kTestExploreUrl,
TileSource::EXPLORE))))));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesTest, ShouldInformSuggestionSourcesWhenBlocked) {
EXPECT_CALL(*mock_top_sites_, AddBlockedUrl(Eq(GURL(kHomepageUrl)))).Times(1);
most_visited_sites_->AddOrRemoveBlockedUrl(GURL(kHomepageUrl),
/*add_url=*/true);
EXPECT_CALL(*mock_top_sites_, RemoveBlockedUrl(Eq(GURL(kHomepageUrl))))
.Times(1);
most_visited_sites_->AddOrRemoveBlockedUrl(GURL(kHomepageUrl),
/*add_url=*/false);
}
TEST_P(MostVisitedSitesTest,
ShouldDeduplicatePopularSitesWithMostVisitedIffHostAndTitleMatches) {
pref_service_.SetString(prefs::kPopularSitesOverrideCountry, "US");
RecreateMostVisitedSites(); // Refills cache with ESPN and Google News.
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{
MakeMostVisitedURL(u"ESPN", "http://espn.com/"),
MakeMostVisitedURL(u"Mobile", "http://m.mobile.de/"),
MakeMostVisitedURL(u"Google", "http://www.google.com/")}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
std::map<SectionType, NTPTilesVector> sections;
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/6);
base::RunLoop().RunUntilIdle();
ASSERT_THAT(sections, Contains(Key(SectionType::PERSONALIZED)));
EXPECT_THAT(sections.at(SectionType::PERSONALIZED),
Contains(MatchesTile(u"Google", "http://www.google.com/",
TileSource::TOP_SITES)));
if (IsPopularSitesFeatureEnabled()) {
EXPECT_THAT(sections.at(SectionType::PERSONALIZED),
Contains(MatchesTile(u"Google News", "http://news.google.com/",
TileSource::POPULAR)));
}
EXPECT_THAT(sections.at(SectionType::PERSONALIZED),
AllOf(Contains(MatchesTile(u"ESPN", "http://espn.com/",
TileSource::TOP_SITES)),
Contains(MatchesTile(u"Mobile", "http://m.mobile.de/",
TileSource::TOP_SITES)),
Not(Contains(MatchesTile(u"ESPN", "http://www.espn.com/",
TileSource::POPULAR))),
Not(Contains(MatchesTile(u"Mobile", "http://www.mobile.de/",
TileSource::POPULAR)))));
}
TEST_P(MostVisitedSitesTest, ShouldHandleTopSitesCacheHit) {
// If cached, TopSites returns the tiles synchronously, running the callback
// even before the function returns.
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(
MostVisitedURLList{MakeMostVisitedURL(u"Site 1", "http://site1/")}));
InSequence seq;
if (IsPopularSitesFeatureEnabled()) {
EXPECT_CALL(
mock_observer_,
OnURLsAvailable(Contains(Pair(
SectionType::PERSONALIZED,
ElementsAre(
MatchesTile(u"Site 1", "http://site1/", TileSource::TOP_SITES),
MatchesTile(u"PopularSite1", "http://popularsite1/",
TileSource::POPULAR),
MatchesTile(u"PopularSite2", "http://popularsite2/",
TileSource::POPULAR))))));
} else {
EXPECT_CALL(mock_observer_,
OnURLsAvailable(Contains(
Pair(SectionType::PERSONALIZED,
ElementsAre(MatchesTile(u"Site 1", "http://site1/",
TileSource::TOP_SITES))))));
}
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
VerifyAndClearExpectations();
CHECK(top_sites_callbacks_.empty());
// Update by TopSites is propagated.
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillOnce(base::test::RunOnceCallback<0>(
MostVisitedURLList{MakeMostVisitedURL(u"Site 2", "http://site2/")}));
if (IsPopularSitesFeatureEnabled()) {
EXPECT_CALL(*mock_top_sites_, IsBlocked(_)).WillRepeatedly(Return(false));
}
EXPECT_CALL(mock_observer_, OnURLsAvailable(_));
mock_top_sites_->NotifyTopSitesChanged(
history::TopSitesObserver::ChangeReason::MOST_VISITED);
base::RunLoop().RunUntilIdle();
}
// Tests that multiple observers can be added to the MostVisitedSites.
TEST_P(MostVisitedSitesTest, MultipleObservers) {
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(MostVisitedURLList{
MakeMostVisitedURL(u"ESPN", "http://espn.com/"),
MakeMostVisitedURL(u"Mobile", "http://m.mobile.de/"),
MakeMostVisitedURL(u"Google", "http://www.google.com/")}));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
std::map<SectionType, NTPTilesVector> sections;
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/2);
base::RunLoop().RunUntilIdle();
EXPECT_THAT(
sections.at(SectionType::PERSONALIZED),
AllOf(Contains(MatchesTile(u"ESPN", "http://espn.com/",
TileSource::TOP_SITES)),
Contains(MatchesTile(u"Mobile", "http://m.mobile.de/",
TileSource::TOP_SITES)),
Not(Contains(MatchesTile(u"Google", "http://www.google.com/",
TileSource::TOP_SITES)))));
// Verifies that multiple observers can be added.
sections.clear();
std::map<SectionType, NTPTilesVector> sections_other;
EXPECT_CALL(*mock_top_sites_, SyncWithHistory()).Times(1);
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillRepeatedly(SaveArg<0>(§ions));
EXPECT_CALL(mock_other_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions_other));
most_visited_sites_->RefreshTiles();
most_visited_sites_->AddMostVisitedURLsObserver(&mock_other_observer_,
/*max_num_sites=*/2);
base::RunLoop().RunUntilIdle();
// Verifies that two observers will be notified with the same suggestions.
EXPECT_TRUE(sections == sections_other);
ASSERT_THAT(sections, Contains(Key(SectionType::PERSONALIZED)));
EXPECT_THAT(
sections.at(SectionType::PERSONALIZED),
AllOf(Contains(MatchesTile(u"ESPN", "http://espn.com/",
TileSource::TOP_SITES)),
Contains(MatchesTile(u"Mobile", "http://m.mobile.de/",
TileSource::TOP_SITES)),
Not(Contains(MatchesTile(u"Google", "http://www.google.com/",
TileSource::TOP_SITES)))));
}
INSTANTIATE_TEST_SUITE_P(MostVisitedSitesTest,
MostVisitedSitesTest,
::testing::Bool());
TEST(MostVisitedSitesTest, ShouldDeduplicateDomainWithNoWwwDomain) {
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"www.mobile.de"},
"mobile.de"));
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"mobile.de"},
"www.mobile.de"));
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"mobile.co.uk"},
"www.mobile.co.uk"));
}
TEST(MostVisitedSitesTest, ShouldDeduplicateDomainByRemovingMobilePrefixes) {
EXPECT_TRUE(
MostVisitedSites::IsHostOrMobilePageKnown({"bbc.co.uk"}, "m.bbc.co.uk"));
EXPECT_TRUE(
MostVisitedSites::IsHostOrMobilePageKnown({"m.bbc.co.uk"}, "bbc.co.uk"));
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"cnn.com"},
"edition.cnn.com"));
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"edition.cnn.com"},
"cnn.com"));
EXPECT_TRUE(
MostVisitedSites::IsHostOrMobilePageKnown({"cnn.com"}, "mobile.cnn.com"));
EXPECT_TRUE(
MostVisitedSites::IsHostOrMobilePageKnown({"mobile.cnn.com"}, "cnn.com"));
}
TEST(MostVisitedSitesTest, ShouldDeduplicateDomainByReplacingMobilePrefixes) {
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"www.bbc.co.uk"},
"m.bbc.co.uk"));
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"m.mobile.de"},
"www.mobile.de"));
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"www.cnn.com"},
"edition.cnn.com"));
EXPECT_TRUE(MostVisitedSites::IsHostOrMobilePageKnown({"mobile.cnn.com"},
"www.cnn.com"));
}
#if !defined(OS_ANDROID) && !defined(OS_IOS)
class MostVisitedSitesWithCustomLinksTest : public MostVisitedSitesTest {
public:
MostVisitedSitesWithCustomLinksTest() {
EnableCustomLinks();
RecreateMostVisitedSites();
}
void ExpectBuildWithTopSites(
const MostVisitedURLList& expected_list,
std::map<SectionType, NTPTilesVector>* sections) {
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(expected_list));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(sections));
}
void ExpectBuildWithCustomLinks(
const std::vector<CustomLinksManager::Link>& expected_links,
std::map<SectionType, NTPTilesVector>* sections) {
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_custom_links_, GetLinks())
.WillOnce(ReturnRef(expected_links));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(sections));
}
};
TEST_P(MostVisitedSitesWithCustomLinksTest, ChangeVisibility) {
const char kTestUrl[] = "http://site1/";
const char16_t kTestTitle[] = u"Site 1";
std::map<SectionType, NTPTilesVector> sections;
// Build tiles when custom links is not initialized. Tiles should be Top
// Sites.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle, kTestUrl)}, §ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle, kTestUrl, TileSource::TOP_SITES));
EXPECT_TRUE(most_visited_sites_->IsCustomLinksEnabled());
EXPECT_TRUE(most_visited_sites_->IsShortcutsVisible());
// Hide shortcuts. Observer should get notified.
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(1);
most_visited_sites_->SetShortcutsVisible(false);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(most_visited_sites_->IsCustomLinksEnabled());
EXPECT_FALSE(most_visited_sites_->IsShortcutsVisible());
// Attempt to hide the shortcuts again. This should be ignored.
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(0);
most_visited_sites_->SetShortcutsVisible(false);
base::RunLoop().RunUntilIdle();
// Make the shortcuts visible. Observer should get notified.
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(1);
most_visited_sites_->SetShortcutsVisible(true);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(most_visited_sites_->IsCustomLinksEnabled());
EXPECT_TRUE(most_visited_sites_->IsShortcutsVisible());
}
TEST_P(MostVisitedSitesWithCustomLinksTest,
ShouldOnlyBuildCustomLinksWhenInitialized) {
const char kTestUrl[] = "http://site1/";
const char16_t kTestTitle[] = u"Site 1";
std::vector<CustomLinksManager::Link> expected_links(
{CustomLinksManager::Link{GURL(kTestUrl), kTestTitle}});
std::map<SectionType, NTPTilesVector> sections;
// Build tiles when custom links is not initialized. Tiles should be Top
// Sites.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle, kTestUrl)}, §ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle, kTestUrl, TileSource::TOP_SITES));
// Initialize custom links and rebuild tiles. Tiles should be custom links.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(true));
ExpectBuildWithCustomLinks(expected_links, §ions);
most_visited_sites_->InitializeCustomLinks();
most_visited_sites_->RefreshTiles();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(
sections.at(SectionType::PERSONALIZED),
ElementsAre(MatchesTile(kTestTitle, kTestUrl, TileSource::CUSTOM_LINKS)));
// Uninitialize custom links and rebuild tiles. Tiles should be Top Sites.
EXPECT_CALL(*mock_custom_links_, Uninitialize());
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle, kTestUrl)}));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
most_visited_sites_->UninitializeCustomLinks();
base::RunLoop().RunUntilIdle();
tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle, kTestUrl, TileSource::TOP_SITES));
}
TEST_P(MostVisitedSitesWithCustomLinksTest,
ShouldFavorCustomLinksOverTopSites) {
const char kTestUrl[] = "http://site1/";
const char16_t kTestTitle[] = u"Site 1";
std::vector<CustomLinksManager::Link> expected_links(
{CustomLinksManager::Link{GURL(kTestUrl), kTestTitle}});
std::map<SectionType, NTPTilesVector> sections;
// Build tiles when custom links is not initialized. Tiles should be Top
// Sites.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle, kTestUrl)}, §ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle, kTestUrl, TileSource::TOP_SITES));
// Initialize custom links and rebuild tiles. Tiles should be custom links.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(true));
ExpectBuildWithCustomLinks(expected_links, §ions);
most_visited_sites_->InitializeCustomLinks();
most_visited_sites_->RefreshTiles();
base::RunLoop().RunUntilIdle();
ASSERT_THAT(
sections.at(SectionType::PERSONALIZED),
ElementsAre(MatchesTile(kTestTitle, kTestUrl, TileSource::CUSTOM_LINKS)));
// Initiate notification for new Top Sites. This should be ignored.
VerifyAndClearExpectations();
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(0);
top_sites_callbacks_.Notify(
MostVisitedURLList({MakeMostVisitedURL(u"Site 2", "http://site2/")}));
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesWithCustomLinksTest,
DisableCustomLinksWhenNotInitialized) {
const char kTestUrl[] = "http://site1/";
const char16_t kTestTitle16[] = u"Site 1";
std::vector<CustomLinksManager::Link> expected_links(
{CustomLinksManager::Link{GURL(kTestUrl), kTestTitle16}});
std::map<SectionType, NTPTilesVector> sections;
// Build tiles when custom links is not initialized. Tiles should be from
// Top Sites.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle16, kTestUrl)},
§ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle16, kTestUrl, TileSource::TOP_SITES));
// Disable custom links. Tiles should rebuild.
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle16, kTestUrl)}));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(1);
most_visited_sites_->EnableCustomLinks(false);
base::RunLoop().RunUntilIdle();
// Try to disable custom links again. This should not rebuild the tiles.
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_)).Times(0);
EXPECT_CALL(*mock_custom_links_, GetLinks()).Times(0);
most_visited_sites_->EnableCustomLinks(false);
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesWithCustomLinksTest, DisableCustomLinksWhenInitialized) {
const char kTestUrl[] = "http://site1/";
const char16_t kTestTitle16[] = u"Site 1";
std::vector<CustomLinksManager::Link> expected_links(
{CustomLinksManager::Link{GURL(kTestUrl), kTestTitle16}});
std::map<SectionType, NTPTilesVector> sections;
// Build tiles when custom links is initialized and not disabled. Tiles should
// be custom links.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
EXPECT_CALL(*mock_top_sites_, SyncWithHistory());
ExpectBuildWithCustomLinks(expected_links, §ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
ASSERT_THAT(sections.at(SectionType::PERSONALIZED),
ElementsAre(MatchesTile(kTestTitle16, kTestUrl,
TileSource::CUSTOM_LINKS)));
// Disable custom links. Tiles should rebuild and return Top Sites.
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle16, kTestUrl)}));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
most_visited_sites_->EnableCustomLinks(false);
base::RunLoop().RunUntilIdle();
EXPECT_THAT(
sections.at(SectionType::PERSONALIZED),
ElementsAre(MatchesTile(kTestTitle16, kTestUrl, TileSource::TOP_SITES)));
// Re-enable custom links. Tiles should rebuild and return custom links.
ExpectBuildWithCustomLinks(expected_links, §ions);
most_visited_sites_->EnableCustomLinks(true);
base::RunLoop().RunUntilIdle();
ASSERT_THAT(sections.at(SectionType::PERSONALIZED),
ElementsAre(MatchesTile(kTestTitle16, kTestUrl,
TileSource::CUSTOM_LINKS)));
}
TEST_P(MostVisitedSitesWithCustomLinksTest,
ShouldGenerateShortTitleForTopSites) {
std::string kTestUrl1 = "https://www.imdb.com/";
std::u16string kTestTitle1 = u"IMDb - Movies, TV and Celebrities - IMDb";
std::string kTestUrl2 = "https://drive.google.com/";
std::u16string kTestTitle2 =
u"Google Drive - Cloud Storage & File Backup for Photos, Docs & More";
std::string kTestUrl3 = "https://amazon.com/";
std::u16string kTestTitle3 =
u"Amazon.com: Online Shopping for Electronics, Apparel, Computers, "
u"Books, "
u"DVDs & more";
std::map<SectionType, NTPTilesVector> sections;
// Build tiles from Top Sites. The tiles should have short titles.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle1, kTestUrl1),
MakeMostVisitedURL(kTestTitle2, kTestUrl2),
MakeMostVisitedURL(kTestTitle3, kTestUrl3)},
§ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/3);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(3ul));
ASSERT_THAT(
tiles[0],
MatchesTile(/* The short title generated by the heuristic */ u"IMDb",
kTestUrl1, TileSource::TOP_SITES));
ASSERT_THAT(
tiles[1],
MatchesTile(
/* The short title generated by the heuristic */ u"Google Drive",
kTestUrl2, TileSource::TOP_SITES));
ASSERT_THAT(
tiles[2],
MatchesTile(
/* The short title generated by the heuristic */ u"Amazon.com",
kTestUrl3, TileSource::TOP_SITES));
}
TEST_P(MostVisitedSitesWithCustomLinksTest,
ShouldNotCrashIfReceiveAnEmptyTitle) {
std::string kTestUrl1 = "https://site1/";
std::u16string kTestTitle1 = u""; // Empty title
std::string kTestUrl2 = "https://site2/";
std::u16string kTestTitle2 = u" "; // Title only contains spaces
std::map<SectionType, NTPTilesVector> sections;
// Build tiles from Top Sites. The tiles should have short titles.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle1, kTestUrl1),
MakeMostVisitedURL(kTestTitle2, kTestUrl2)},
§ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/2);
base::RunLoop().RunUntilIdle();
// Both cases should not crash and generate an empty title tile.
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(2ul));
ASSERT_THAT(tiles[0], MatchesTile(u"", kTestUrl1, TileSource::TOP_SITES));
ASSERT_THAT(tiles[1], MatchesTile(u"", kTestUrl2, TileSource::TOP_SITES));
}
TEST_P(MostVisitedSitesWithCustomLinksTest,
UninitializeCustomLinksOnUndoAfterFirstAction) {
const char kTestUrl[] = "http://site1/";
const char16_t kTestTitle[] = u"Site 1";
std::vector<CustomLinksManager::Link> expected_links(
{CustomLinksManager::Link{GURL(kTestUrl), kTestTitle}});
std::map<SectionType, NTPTilesVector> sections;
// Build initial tiles with Top Sites.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle, kTestUrl)}, §ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle, kTestUrl, TileSource::TOP_SITES));
// Initialize custom links and complete a custom link action.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, AddLink(_, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_custom_links_, GetLinks())
.WillRepeatedly(ReturnRef(expected_links));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
most_visited_sites_->AddCustomLink(GURL("test.com"), u"test");
base::RunLoop().RunUntilIdle();
ASSERT_THAT(
sections.at(SectionType::PERSONALIZED),
ElementsAre(MatchesTile(kTestTitle, kTestUrl, TileSource::CUSTOM_LINKS)));
// Undo the action. This should uninitialize custom links.
EXPECT_CALL(*mock_custom_links_, UndoAction()).Times(0);
EXPECT_CALL(*mock_custom_links_, Uninitialize());
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle, kTestUrl)}));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
most_visited_sites_->UndoCustomLinkAction();
base::RunLoop().RunUntilIdle();
tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle, kTestUrl, TileSource::TOP_SITES));
}
TEST_P(MostVisitedSitesWithCustomLinksTest,
DontUninitializeCustomLinksOnUndoAfterMultipleActions) {
const char kTestUrl[] = "http://site1/";
const char16_t kTestTitle[] = u"Site 1";
std::vector<CustomLinksManager::Link> expected_links(
{CustomLinksManager::Link{GURL(kTestUrl), kTestTitle}});
std::map<SectionType, NTPTilesVector> sections;
// Build initial tiles with Top Sites.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle, kTestUrl)}, §ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle, kTestUrl, TileSource::TOP_SITES));
// Initialize custom links and complete a custom link action.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, UpdateLink(_, _, _)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_custom_links_, GetLinks())
.WillRepeatedly(ReturnRef(expected_links));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillRepeatedly(SaveArg<0>(§ions));
most_visited_sites_->UpdateCustomLink(GURL("test.com"), GURL("test.com"),
u"test");
base::RunLoop().RunUntilIdle();
ASSERT_THAT(
sections.at(SectionType::PERSONALIZED),
ElementsAre(MatchesTile(kTestTitle, kTestUrl, TileSource::CUSTOM_LINKS)));
// Complete a second custom link action.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(false));
EXPECT_CALL(*mock_custom_links_, DeleteLink(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_custom_links_, GetLinks())
.WillOnce(ReturnRef(expected_links));
most_visited_sites_->DeleteCustomLink(GURL("test.com"));
base::RunLoop().RunUntilIdle();
// Undo the second action. This should not uninitialize custom links.
EXPECT_CALL(*mock_custom_links_, UndoAction()).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, Uninitialize()).Times(0);
EXPECT_CALL(*mock_custom_links_, IsInitialized()).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, GetLinks())
.WillOnce(ReturnRef(expected_links));
most_visited_sites_->UndoCustomLinkAction();
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesWithCustomLinksTest,
UninitializeCustomLinksIfFirstActionFails) {
const char kTestUrl[] = "http://site1/";
const char16_t kTestTitle[] = u"Site 1";
std::vector<CustomLinksManager::Link> expected_links(
{CustomLinksManager::Link{GURL(kTestUrl), kTestTitle}});
std::map<SectionType, NTPTilesVector> sections;
// Build initial tiles with Top Sites.
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle, kTestUrl)}, §ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle, kTestUrl, TileSource::TOP_SITES));
// Fail to add a custom link. This should not initialize custom links but
// notify.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, AddLink(_, _)).WillOnce(Return(false));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(*mock_custom_links_, Uninitialize());
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(1);
most_visited_sites_->AddCustomLink(GURL(kTestUrl), u"test");
base::RunLoop().RunUntilIdle();
// Fail to edit a custom link. This should not initialize custom links but
// notify.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, UpdateLink(_, _, _)).WillOnce(Return(false));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(*mock_custom_links_, Uninitialize());
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(1);
most_visited_sites_->UpdateCustomLink(GURL("test.com"), GURL("test2.com"),
u"test");
base::RunLoop().RunUntilIdle();
// Fail to reorder a custom link. This should not initialize custom links but
// notify.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, ReorderLink(_, _)).WillOnce(Return(false));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(*mock_custom_links_, Uninitialize());
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(1);
most_visited_sites_->ReorderCustomLink(GURL("test.com"), 1);
base::RunLoop().RunUntilIdle();
// Fail to delete a custom link. This should not initialize custom links but
// notify.
EXPECT_CALL(*mock_custom_links_, Initialize(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_custom_links_, DeleteLink(_)).WillOnce(Return(false));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(*mock_custom_links_, Uninitialize());
EXPECT_CALL(mock_observer_, OnURLsAvailable(_)).Times(1);
most_visited_sites_->DeleteCustomLink(GURL("test.com"));
base::RunLoop().RunUntilIdle();
}
TEST_P(MostVisitedSitesWithCustomLinksTest, RebuildTilesOnCustomLinksChanged) {
const char kTestUrl1[] = "http://site1/";
const char kTestUrl2[] = "http://site2/";
const char16_t kTestTitle1[] = u"Site 1";
const char16_t kTestTitle2[] = u"Site 2";
std::vector<CustomLinksManager::Link> expected_links(
{CustomLinksManager::Link{GURL(kTestUrl2), kTestTitle2}});
std::map<SectionType, NTPTilesVector> sections;
// Build initial tiles with Top Sites.
base::RepeatingClosure custom_links_callback;
EXPECT_CALL(*mock_custom_links_, RegisterCallbackForOnChanged(_))
.WillOnce(DoAll(SaveArg<0>(&custom_links_callback),
Return(ByMove(base::CallbackListSubscription()))));
ExpectBuildWithTopSites(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle1, kTestUrl1)},
§ions);
most_visited_sites_->AddMostVisitedURLsObserver(&mock_observer_,
/*max_num_sites=*/1);
base::RunLoop().RunUntilIdle();
NTPTilesVector tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle1, kTestUrl1, TileSource::TOP_SITES));
// Notify that there is a new set of custom links. This should replace the
// current tiles with custom links.
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_custom_links_, GetLinks())
.WillRepeatedly(ReturnRef(expected_links));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
custom_links_callback.Run();
base::RunLoop().RunUntilIdle();
EXPECT_THAT(sections.at(SectionType::PERSONALIZED),
ElementsAre(MatchesTile(kTestTitle2, kTestUrl2,
TileSource::CUSTOM_LINKS)));
// Notify that custom links have been uninitialized. This should rebuild the
// tiles with Top Sites.
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(*mock_top_sites_, GetMostVisitedURLs(_))
.WillRepeatedly(base::test::RunOnceCallback<0>(
MostVisitedURLList{MakeMostVisitedURL(kTestTitle1, kTestUrl1)}));
EXPECT_CALL(*mock_custom_links_, IsInitialized())
.WillRepeatedly(Return(false));
EXPECT_CALL(mock_observer_, OnURLsAvailable(_))
.WillOnce(SaveArg<0>(§ions));
custom_links_callback.Run();
base::RunLoop().RunUntilIdle();
tiles = sections.at(SectionType::PERSONALIZED);
ASSERT_THAT(tiles.size(), Ge(1ul));
ASSERT_THAT(tiles[0],
MatchesTile(kTestTitle1, kTestUrl1, TileSource::TOP_SITES));
}
// These exclude Android and iOS.
INSTANTIATE_TEST_SUITE_P(MostVisitedSitesWithCustomLinksTest,
MostVisitedSitesWithCustomLinksTest,
::testing::Bool());
#endif
// This a test for MostVisitedSites::MergeTiles(...) method, and thus has the
// same scope as the method itself. This tests merging popular sites with
// personal tiles.
// More important things out of the scope of testing presently:
// - Removing blocked tiles.
// - Correct host extraction from the URL.
// - Ensuring personal tiles are not duplicated in popular tiles.
TEST(MostVisitedSitesMergeTest, ShouldMergeTilesWithPersonalOnly) {
std::vector<NTPTile> personal_tiles{
MakeTile(u"Site 1", "https://www.site1.com/", TileSource::TOP_SITES),
MakeTile(u"Site 2", "https://www.site2.com/", TileSource::TOP_SITES),
MakeTile(u"Site 3", "https://www.site3.com/", TileSource::TOP_SITES),
MakeTile(u"Site 4", "https://www.site4.com/", TileSource::TOP_SITES),
};
// Without any popular tiles, the result after merge should be the personal
// tiles.
EXPECT_THAT(MostVisitedSites::MergeTiles(std::move(personal_tiles),
/*popular_tiles=*/NTPTilesVector(),
/*explore_tile=*/absl::nullopt),
ElementsAre(MatchesTile(u"Site 1", "https://www.site1.com/",
TileSource::TOP_SITES),
MatchesTile(u"Site 2", "https://www.site2.com/",
TileSource::TOP_SITES),
MatchesTile(u"Site 3", "https://www.site3.com/",
TileSource::TOP_SITES),
MatchesTile(u"Site 4", "https://www.site4.com/",
TileSource::TOP_SITES)));
}
TEST(MostVisitedSitesMergeTest, ShouldMergeTilesWithPopularOnly) {
std::vector<NTPTile> popular_tiles{
MakeTile(u"Site 1", "https://www.site1.com/", TileSource::POPULAR),
MakeTile(u"Site 2", "https://www.site2.com/", TileSource::POPULAR),
MakeTile(u"Site 3", "https://www.site3.com/", TileSource::POPULAR),
MakeTile(u"Site 4", "https://www.site4.com/", TileSource::POPULAR),
};
// Without any personal tiles, the result after merge should be the popular
// tiles.
EXPECT_THAT(
MostVisitedSites::MergeTiles(/*personal_tiles=*/NTPTilesVector(),
/*popular_tiles=*/std::move(popular_tiles),
/*explore_tile=*/absl::nullopt),
ElementsAre(
MatchesTile(u"Site 1", "https://www.site1.com/", TileSource::POPULAR),
MatchesTile(u"Site 2", "https://www.site2.com/", TileSource::POPULAR),
MatchesTile(u"Site 3", "https://www.site3.com/", TileSource::POPULAR),
MatchesTile(u"Site 4", "https://www.site4.com/",
TileSource::POPULAR)));
}
TEST(MostVisitedSitesMergeTest, ShouldMergeTilesFavoringPersonalOverPopular) {
std::vector<NTPTile> popular_tiles{
MakeTile(u"Site 1", "https://www.site1.com/", TileSource::POPULAR),
MakeTile(u"Site 2", "https://www.site2.com/", TileSource::POPULAR),
};
std::vector<NTPTile> personal_tiles{
MakeTile(u"Site 3", "https://www.site3.com/", TileSource::TOP_SITES),
MakeTile(u"Site 4", "https://www.site4.com/", TileSource::TOP_SITES),
};
absl::optional<NTPTile> explore_tile{
MakeTile(u"Explore", "https://explore.example.com/", TileSource::EXPLORE),
};
EXPECT_THAT(
MostVisitedSites::MergeTiles(std::move(personal_tiles),
/*popular_tiles=*/std::move(popular_tiles),
/*explore_tiles=*/explore_tile),
ElementsAre(
MatchesTile(u"Site 3", "https://www.site3.com/",
TileSource::TOP_SITES),
MatchesTile(u"Site 4", "https://www.site4.com/",
TileSource::TOP_SITES),
MatchesTile(u"Site 1", "https://www.site1.com/", TileSource::POPULAR),
MatchesTile(u"Site 2", "https://www.site2.com/", TileSource::POPULAR),
MatchesTile(u"Explore", "https://explore.example.com/",
TileSource::EXPLORE)));
}
} // namespace ntp_tiles
| scheib/chromium | components/ntp_tiles/most_visited_sites_unittest.cc | C++ | bsd-3-clause | 73,773 |
#region Using
using System;
using System.Web;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using BlogEngine.Core;
#endregion
public partial class archive : BlogEngine.Core.Web.Controls.BlogBasePage
{
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && !IsCallback)
{
CreateMenu();
CreateArchive();
AddTotals();
}
Page.Title = Server.HtmlEncode(Resources.labels.archive);
base.AddMetaTag("description", Resources.labels.archive + " | " + BlogSettings.Instance.Name);
}
/// <summary>
/// Creates the category top menu.
/// </summary>
private void CreateMenu()
{
foreach (Category cat in Category.Categories)
{
AddCategoryToMenu(cat.Title);
}
}
private void AddCategoryToMenu(string title)
{
HtmlAnchor a = new HtmlAnchor();
a.InnerHtml = Server.HtmlEncode(title);
a.HRef = string.Format("{0}archive{1}#cat-{2}", Blog.CurrentInstance.RelativeWebRoot, BlogConfig.FileExtension, Utils.RemoveIllegalCharacters(title));
a.Attributes.Add("rel", "directory");
HtmlGenericControl li = new HtmlGenericControl("li");
li.Controls.Add(a);
ulMenu.Controls.Add(li);
}
/// <summary>
/// Sorts the categories.
/// </summary>
/// <param name="categories">The categories.</param>
private SortedDictionary<string, Guid> SortCategories(Dictionary<Guid, string> categories)
{
SortedDictionary<string, Guid> dic = new SortedDictionary<string, Guid>();
foreach (Category cat in Category.Categories)
{
bool postsExist = cat.Posts.FindAll(delegate(Post post)
{
return post.IsVisible;
}).Count > 0;
if (postsExist)
dic.Add(cat.Title, cat.Id);
}
return dic;
}
private void CreateArchive()
{
foreach (Category cat in Category.Categories)
{
string name = cat.Title;
List<Post> list = cat.Posts.FindAll(delegate(Post p) { return p.IsVisible; });
HtmlGenericControl h2 = CreateRowHeader(cat, name, list.Count);
phArchive.Controls.Add(h2);
HtmlTable table = CreateTable(name);
foreach (Post post in list)
{
CreateTableRow(table, post);
}
phArchive.Controls.Add(table);
}
List<Post> noCatList = Post.Posts.FindAll(delegate(Post p) { return p.Categories.Count == 0 && p.IsVisible; });
if (noCatList.Count > 0)
{
string name = Resources.labels.uncategorized;
HtmlGenericControl h2 = CreateRowHeader(null, name, noCatList.Count);
phArchive.Controls.Add(h2);
HtmlTable table = CreateTable(name);
foreach (Post post in noCatList)
{
CreateTableRow(table, post);
}
phArchive.Controls.Add(table);
AddCategoryToMenu(name);
}
}
private static HtmlGenericControl CreateRowHeader(Category cat, string name, int count)
{
HtmlGenericControl h2 = new HtmlGenericControl("h2");
h2.Attributes["id"] = "cat-" + Utils.RemoveIllegalCharacters(name);
if (cat != null)
{
HtmlAnchor feed = new HtmlAnchor();
feed.HRef = cat.FeedRelativeLink;
HtmlImage img = new HtmlImage();
img.Src = Utils.RelativeWebRoot + "pics/rssButton.png";
img.Alt = "RSS";
feed.Controls.Add(img);
h2.Controls.Add(feed);
}
Control header = new LiteralControl(name + " (" + count + ")");
h2.Controls.Add(header);
return h2;
}
private static void CreateTableRow(HtmlTable table, Post post)
{
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell date = new HtmlTableCell();
date.InnerHtml = post.DateCreated.ToString("yyyy-MM-dd");
date.Attributes.Add("class", "date");
row.Cells.Add(date);
HtmlTableCell title = new HtmlTableCell();
title.InnerHtml = string.Format("<a href=\"{0}\">{1}</a>", post.RelativeLink, post.Title);
title.Attributes.Add("class", "title");
row.Cells.Add(title);
if (BlogSettings.Instance.IsCommentsEnabled)
{
HtmlTableCell comments = new HtmlTableCell();
if(BlogSettings.Instance.ModerationType == BlogSettings.Moderation.Disqus)
comments.InnerHtml = string.Format("<span><a href=\"{0}#disqus_thread\">{1}</a></span>", post.PermaLink, Resources.labels.comments);
else
comments.InnerHtml = post.ApprovedComments.Count.ToString();
comments.Attributes.Add("class", "comments");
row.Cells.Add(comments);
}
if (BlogSettings.Instance.EnableRating)
{
HtmlTableCell rating = new HtmlTableCell();
rating.InnerHtml = post.Raters == 0 ? "None" : Math.Round(post.Rating, 1).ToString();
rating.Attributes.Add("class", "rating");
row.Cells.Add(rating);
}
table.Rows.Add(row);
}
private HtmlTable CreateTable(string name)
{
HtmlTable table = new HtmlTable();
table.Attributes.Add("summary", name);
HtmlTableRow header = new HtmlTableRow();
HtmlTableCell date = new HtmlTableCell("th");
date.InnerHtml = Utils.Translate("date");
header.Cells.Add(date);
HtmlTableCell title = new HtmlTableCell("th");
title.InnerHtml = Utils.Translate("title");
header.Cells.Add(title);
if (BlogSettings.Instance.IsCommentsEnabled)
{
HtmlTableCell comments = new HtmlTableCell("th");
comments.InnerHtml = Utils.Translate("comments");
comments.Attributes.Add("class", "comments");
header.Cells.Add(comments);
}
if (BlogSettings.Instance.EnableRating)
{
HtmlTableCell rating = new HtmlTableCell("th");
rating.InnerHtml = Utils.Translate("rating");
rating.Attributes.Add("class", "rating");
header.Cells.Add(rating);
}
table.Rows.Add(header);
return table;
}
private void AddTotals()
{
int comments = 0;
int raters = 0;
List<Post> posts = Post.Posts.FindAll(delegate(Post p) { return p.IsVisible; });
foreach (Post post in posts)
{
comments += post.ApprovedComments.Count;
raters += post.Raters;
}
ltPosts.Text = posts.Count + " " + Resources.labels.posts.ToLowerInvariant();
if (BlogSettings.Instance.IsCommentsEnabled && BlogSettings.Instance.ModerationType != BlogSettings.Moderation.Disqus)
ltComments.Text = "<span>" + comments + " " + Resources.labels.comments.ToLowerInvariant() + "</span><br />";
if (BlogSettings.Instance.EnableRating)
ltRaters.Text = raters + " " + Resources.labels.raters.ToLowerInvariant();
}
}
| anhcop86/SN-Stock | Thuong_Blog_FinandLife_Original/BlogEngine/BlogEngine.NET/archive.aspx.cs | C# | bsd-3-clause | 6,450 |
<?php
namespace PhpEws\DataType;
use PhpEws\DataType;
/**
* Definition of the AttachmentResponseShapeType type
*/
class AttachmentResponseShapeType extends DataType
{
/**
* IncludeMimeContent property
*
* @var boolean
*/
public $IncludeMimeContent;
/**
* BodyType property
*
* @var BodyTypeResponseType
*/
public $BodyType;
/**
* AdditionalProperties property
*
* @var NonEmptyArrayOfPathsToElementType
*/
public $AdditionalProperties;
}
| adamelso/php-ews | src/PhpEws/DataType/AttachmentResponseShapeType.php | PHP | bsd-3-clause | 529 |
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include "../../core/sql_queries.hpp"
#include "../../core/unit_test_abstract.hpp"
namespace evias {
namespace core {
namespace test {
namespace sqlObjects {
class insertStmt : public unitTest
{
public :
insertStmt () : unitTest() {};
~insertStmt () {};
inline void prepare ()
{
_queryObj = new insertQuery;
setReturnCode((int) RETURN_SUCCESS);
}
inline int execute ()
{
// test creation of insertQuery using map<string,string>.
// if this does not work it means the data storage is
// broken.
map<string,string> data;
data.insert (make_pair ("first_name", "Yannick"));
data.insert (make_pair ("last_name", "Yannick"));
data.insert (make_pair ("address", "Rue de l'église 37"));
data.insert (make_pair ("zipcode", "4720"));
data.insert (make_pair ("city", "Kelmis"));
data.insert (make_pair ("country", "Belgium"));
_queryObj->into ("student")
->values (data);
// make sure we inserted everything
if (_queryObj->getValuesDispatched().size() != 6) {
_returnMsg = "code defines 6 field, value pairs but object returned other entries count.";
return setReturnCode((int) ERROR_DEVELOPMENT);
}
// check if all fields can be retrieved
if (! _queryObj->hasValueForField("first_name") ||
! _queryObj->hasValueForField("last_name") ||
! _queryObj->hasValueForField("address") ||
! _queryObj->hasValueForField("zipcode") ||
! _queryObj->hasValueForField("city") ||
! _queryObj->hasValueForField("country")) {
_returnMsg = "code defines first_name,last_name,address,zipcode,city,country but some are missing at call.";
return setReturnCode((int) ERROR_DEVELOPMENT);
}
return _returnCode;
}
inline int shutdown()
{
if (_queryObj != NULL)
delete _queryObj;
return _returnCode;
}
private :
insertQuery* _queryObj;
};
}; // end namespace sqlObjects
}; // end namespace test
}; // end namespace core
}; // end namespace evias
| evias/evias | evias/tests/sqlObjects/insertStmt.hpp | C++ | bsd-3-clause | 2,662 |
#ifndef TWEBSOCKETFRAME_H
#define TWEBSOCKETFRAME_H
#include <QByteArray>
#include <TGlobal>
class T_CORE_EXPORT TWebSocketFrame {
public:
enum OpCode {
Continuation = 0x0,
TextFrame = 0x1,
BinaryFrame = 0x2,
Reserve3 = 0x3,
Reserve4 = 0x4,
Reserve5 = 0x5,
Reserve6 = 0x6,
Reserve7 = 0x7,
Close = 0x8,
Ping = 0x9,
Pong = 0xA,
ReserveB = 0xB,
ReserveC = 0xC,
ReserveD = 0xD,
ReserveE = 0xE,
ReserveF = 0xF,
};
TWebSocketFrame();
TWebSocketFrame(const TWebSocketFrame &other);
TWebSocketFrame &operator=(const TWebSocketFrame &other);
bool finBit() const { return _firstByte & 0x80; }
bool rsv1Bit() const { return _firstByte & 0x40; }
bool rsv2Bit() const { return _firstByte & 0x20; }
bool rsv3Bit() const { return _firstByte & 0x10; }
bool isFinalFrame() const { return finBit(); }
OpCode opCode() const { return (OpCode)(_firstByte & 0xF); }
bool isControlFrame() const;
quint32 maskKey() const { return _maskKey; }
quint64 payloadLength() const { return _payloadLength; }
const QByteArray &payload() const { return _payload; }
bool isValid() const { return _valid; }
void clear();
QByteArray toByteArray() const;
private:
enum ProcessingState {
Empty = 0,
HeaderParsed,
MoreData,
Completed,
};
void setFinBit(bool fin);
void setOpCode(OpCode opCode);
void setFirstByte(quint8 byte);
void setMaskKey(quint32 maskKey);
void setPayloadLength(quint64 length);
void setPayload(const QByteArray &payload);
QByteArray &payload() { return _payload; }
bool validate();
ProcessingState state() const { return _state; }
void setState(ProcessingState state);
quint8 _firstByte {0x80};
quint32 _maskKey {0};
quint64 _payloadLength {0};
QByteArray _payload; // unmasked data stored
ProcessingState _state {Empty};
bool _valid {false};
friend class TAbstractWebSocket;
friend class TWebSocket;
friend class TEpollWebSocket;
friend class TWebSocketController;
};
#endif // TWEBSOCKETFRAME_H
| AmiArt/treefrog-framework | src/twebsocketframe.h | C | bsd-3-clause | 2,211 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>statsmodels.sandbox.distributions.transformed.LogTransf_gen.sf — statsmodels 0.6.1 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '0.6.1',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="top" title="statsmodels 0.6.1 documentation" href="../index.html" />
<link rel="stylesheet" href="../../_static/facebox.css" type="text/css" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
</head>
<body role="document">
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/statsmodels_hybi_banner.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/group/pystatsmodels?hl=en">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="statsmodels-sandbox-distributions-transformed-logtransf-gen-sf">
<h1>statsmodels.sandbox.distributions.transformed.LogTransf_gen.sf<a class="headerlink" href="#statsmodels-sandbox-distributions-transformed-logtransf-gen-sf" title="Permalink to this headline">¶</a></h1>
<dl class="method">
<dt id="statsmodels.sandbox.distributions.transformed.LogTransf_gen.sf">
<code class="descclassname">LogTransf_gen.</code><code class="descname">sf</code><span class="sig-paren">(</span><em>x</em>, <em>*args</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.sandbox.distributions.transformed.LogTransf_gen.sf" title="Permalink to this definition">¶</a></dt>
<dd><p>Survival function (1-cdf) at x of the given RV.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><p class="first"><strong>x</strong> : array_like</p>
<blockquote>
<div><p>quantiles</p>
</div></blockquote>
<p><strong>arg1, arg2, arg3,...</strong> : array_like</p>
<blockquote>
<div><p>The shape parameter(s) for the distribution (see docstring of the
instance object for more information)</p>
</div></blockquote>
<p><strong>loc</strong> : array_like, optional</p>
<blockquote>
<div><p>location parameter (default=0)</p>
</div></blockquote>
<p><strong>scale</strong> : array_like, optional</p>
<blockquote>
<div><p>scale parameter (default=1)</p>
</div></blockquote>
</td>
</tr>
<tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first"><strong>sf</strong> : array_like</p>
<blockquote class="last">
<div><p>Survival function evaluated at x</p>
</div></blockquote>
</td>
</tr>
</tbody>
</table>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.sandbox.distributions.transformed.LogTransf_gen.sf.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
© Copyright 2009-2013, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1.
</div>
</body>
</html> | statsmodels/statsmodels.github.io | 0.6.1/generated/statsmodels.sandbox.distributions.transformed.LogTransf_gen.sf.html | HTML | bsd-3-clause | 5,869 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.arima.model.ARIMAResults.remove_data — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.arima.model.ARIMAResults.save" href="statsmodels.tsa.arima.model.ARIMAResults.save.html" />
<link rel="prev" title="statsmodels.tsa.arima.model.ARIMAResults.predict" href="statsmodels.tsa.arima.model.ARIMAResults.predict.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.arima.model.ARIMAResults.remove_data" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.14.0.dev0 (+325)</span>
<span class="md-header-nav__topic"> statsmodels.tsa.arima.model.ARIMAResults.remove_data </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../tsa.html" class="md-tabs__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.arima.model.ARIMAResults.html" class="md-tabs__link">statsmodels.tsa.arima.model.ARIMAResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.14.0.dev0 (+325)</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.arima.model.ARIMAResults.remove_data.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<section id="statsmodels-tsa-arima-model-arimaresults-remove-data">
<h1 id="generated-statsmodels-tsa-arima-model-arimaresults-remove-data--page-root">statsmodels.tsa.arima.model.ARIMAResults.remove_data<a class="headerlink" href="#generated-statsmodels-tsa-arima-model-arimaresults-remove-data--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt class="sig sig-object py" id="statsmodels.tsa.arima.model.ARIMAResults.remove_data">
<span class="sig-prename descclassname"><span class="pre">ARIMAResults.</span></span><span class="sig-name descname"><span class="pre">remove_data</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.tsa.arima.model.ARIMAResults.remove_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove data arrays, all nobs arrays from result and model.</p>
<p>This reduces the size of the instance, so it can be pickled with less
memory. Currently tested for use with predict from an unpickled
results and model instance.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Since data and some intermediate results have been removed
calculating new statistics that require them will raise exceptions.
The exception will occur the first time an attribute is accessed
that has been set to None.</p>
</div>
<p>Not fully tested for time series models, tsa, and might delete too much
for prediction or not all that would be possible.</p>
<p>The lists of arrays to delete are maintained as attributes of
the result and model instance, except for cached values. These
lists could be changed before calling remove_data.</p>
<p>The attributes to remove are named in:</p>
<dl class="simple">
<dt>model._data_attr<span class="classifier">arrays attached to both the model instance</span></dt><dd><p>and the results instance with the same attribute name.</p>
</dd>
<dt>result._data_in_cache<span class="classifier">arrays that may exist as values in</span></dt><dd><p>result._cache</p>
</dd>
<dt>result._data_attr_model<span class="classifier">arrays attached to the model</span></dt><dd><p>instance but not to the results instance</p>
</dd>
</dl>
</dd></dl>
</section>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.arima.model.ARIMAResults.predict.html" title="statsmodels.tsa.arima.model.ARIMAResults.predict"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.arima.model.ARIMAResults.predict </span>
</div>
</a>
<a href="statsmodels.tsa.arima.model.ARIMAResults.save.html" title="statsmodels.tsa.arima.model.ARIMAResults.save"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.arima.model.ARIMAResults.save </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Feb 23, 2022.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 4.4.0.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | statsmodels/statsmodels.github.io | devel/generated/statsmodels.tsa.arima.model.ARIMAResults.remove_data.html | HTML | bsd-3-clause | 18,979 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>FireplaceApp Tests</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{content-for 'head'}}
{{content-for 'test-head'}}
<link rel="stylesheet" href="assets/vendor.css">
<link rel="stylesheet" href="assets/fireplace-app.css">
<link rel="stylesheet" href="assets/test-support.css">
{{content-for 'head-footer'}}
{{content-for 'test-head-footer'}}
</head>
<body>
{{content-for 'body'}}
{{content-for 'test-body'}}
<script src="assets/vendor.js"></script>
<script src="assets/test-support.js"></script>
<script src="assets/fireplace-app.js"></script>
<script src="testem.js"></script>
<script src="assets/test-loader.js"></script>
{{content-for 'body-footer'}}
{{content-for 'test-body-footer'}}
</body>
</html>
| knshetty/fireplace-app | tests/index.html | HTML | bsd-3-clause | 983 |
<?php
/**
* @copyright Frederic G. Østby
* @license http://www.makoframework.com/license
*/
namespace mako\i18n\exceptions;
use RuntimeException;
/**
* I18n exception.
*/
class I18nException extends RuntimeException
{
}
| mako-framework/framework | src/mako/i18n/exceptions/I18nException.php | PHP | bsd-3-clause | 233 |
"""
Collection of query wrappers / abstractions to both facilitate data
retrieval and to reduce dependency on DB-specific API.
"""
from contextlib import contextmanager
from datetime import date, datetime, time
from functools import partial
import re
from typing import Iterator, Optional, Union, overload
import warnings
import numpy as np
import pandas._libs.lib as lib
from pandas.core.dtypes.common import is_datetime64tz_dtype, is_dict_like, is_list_like
from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas.core.dtypes.missing import isna
from pandas.core.api import DataFrame, Series
from pandas.core.base import PandasObject
from pandas.core.tools.datetimes import to_datetime
class SQLAlchemyRequired(ImportError):
pass
class DatabaseError(IOError):
pass
# -----------------------------------------------------------------------------
# -- Helper functions
_SQLALCHEMY_INSTALLED = None
def _is_sqlalchemy_connectable(con):
global _SQLALCHEMY_INSTALLED
if _SQLALCHEMY_INSTALLED is None:
try:
import sqlalchemy
_SQLALCHEMY_INSTALLED = True
except ImportError:
_SQLALCHEMY_INSTALLED = False
if _SQLALCHEMY_INSTALLED:
import sqlalchemy # noqa: F811
return isinstance(con, sqlalchemy.engine.Connectable)
else:
return False
def _convert_params(sql, params):
"""Convert SQL and params args to DBAPI2.0 compliant format."""
args = [sql]
if params is not None:
if hasattr(params, "keys"): # test if params is a mapping
args += [params]
else:
args += [list(params)]
return args
def _process_parse_dates_argument(parse_dates):
"""Process parse_dates argument for read_sql functions"""
# handle non-list entries for parse_dates gracefully
if parse_dates is True or parse_dates is None or parse_dates is False:
parse_dates = []
elif not hasattr(parse_dates, "__iter__"):
parse_dates = [parse_dates]
return parse_dates
def _handle_date_column(col, utc=None, format=None):
if isinstance(format, dict):
return to_datetime(col, errors="ignore", **format)
else:
# Allow passing of formatting string for integers
# GH17855
if format is None and (
issubclass(col.dtype.type, np.floating)
or issubclass(col.dtype.type, np.integer)
):
format = "s"
if format in ["D", "d", "h", "m", "s", "ms", "us", "ns"]:
return to_datetime(col, errors="coerce", unit=format, utc=utc)
elif is_datetime64tz_dtype(col.dtype):
# coerce to UTC timezone
# GH11216
return to_datetime(col, utc=True)
else:
return to_datetime(col, errors="coerce", format=format, utc=utc)
def _parse_date_columns(data_frame, parse_dates):
"""
Force non-datetime columns to be read as such.
Supports both string formatted and integer timestamp columns.
"""
parse_dates = _process_parse_dates_argument(parse_dates)
# we want to coerce datetime64_tz dtypes for now to UTC
# we could in theory do a 'nice' conversion from a FixedOffset tz
# GH11216
for col_name, df_col in data_frame.items():
if is_datetime64tz_dtype(df_col.dtype) or col_name in parse_dates:
try:
fmt = parse_dates[col_name]
except TypeError:
fmt = None
data_frame[col_name] = _handle_date_column(df_col, format=fmt)
return data_frame
def _wrap_result(data, columns, index_col=None, coerce_float=True, parse_dates=None):
"""Wrap result set of query in a DataFrame."""
frame = DataFrame.from_records(data, columns=columns, coerce_float=coerce_float)
frame = _parse_date_columns(frame, parse_dates)
if index_col is not None:
frame.set_index(index_col, inplace=True)
return frame
def execute(sql, con, cur=None, params=None):
"""
Execute the given SQL query using the provided connection object.
Parameters
----------
sql : string
SQL query to be executed.
con : SQLAlchemy connectable(engine/connection) or sqlite3 connection
Using SQLAlchemy makes it possible to use any DB supported by the
library.
If a DBAPI2 object, only sqlite3 is supported.
cur : deprecated, cursor is obtained from connection, default: None
params : list or tuple, optional, default: None
List of parameters to pass to execute method.
Returns
-------
Results Iterable
"""
if cur is None:
pandas_sql = pandasSQL_builder(con)
else:
pandas_sql = pandasSQL_builder(cur, is_cursor=True)
args = _convert_params(sql, params)
return pandas_sql.execute(*args)
# -----------------------------------------------------------------------------
# -- Read and write to DataFrames
@overload
def read_sql_table(
table_name,
con,
schema=None,
index_col=None,
coerce_float=True,
parse_dates=None,
columns=None,
chunksize: None = None,
) -> DataFrame:
...
@overload
def read_sql_table(
table_name,
con,
schema=None,
index_col=None,
coerce_float=True,
parse_dates=None,
columns=None,
chunksize: int = 1,
) -> Iterator[DataFrame]:
...
def read_sql_table(
table_name,
con,
schema=None,
index_col=None,
coerce_float=True,
parse_dates=None,
columns=None,
chunksize: Optional[int] = None,
) -> Union[DataFrame, Iterator[DataFrame]]:
"""
Read SQL database table into a DataFrame.
Given a table name and a SQLAlchemy connectable, returns a DataFrame.
This function does not support DBAPI connections.
Parameters
----------
table_name : str
Name of SQL table in database.
con : SQLAlchemy connectable or str
A database URI could be provided as as str.
SQLite DBAPI connection mode not supported.
schema : str, default None
Name of SQL schema in database to query (if database flavor
supports this). Uses default schema if None (default).
index_col : str or list of str, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : bool, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Can result in loss of Precision.
parse_dates : list or dict, default None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default None
List of column names to select from SQL table.
chunksize : int, default None
If specified, returns an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame or Iterator[DataFrame]
A SQL table is returned as two-dimensional data structure with labeled
axes.
See Also
--------
read_sql_query : Read SQL query into a DataFrame.
read_sql : Read SQL query or database table into a DataFrame.
Notes
-----
Any datetime values with time zone information will be converted to UTC.
Examples
--------
>>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
"""
con = _engine_builder(con)
if not _is_sqlalchemy_connectable(con):
raise NotImplementedError(
"read_sql_table only supported for SQLAlchemy connectable."
)
import sqlalchemy
from sqlalchemy.schema import MetaData
meta = MetaData(con, schema=schema)
try:
meta.reflect(only=[table_name], views=True)
except sqlalchemy.exc.InvalidRequestError as err:
raise ValueError(f"Table {table_name} not found") from err
pandas_sql = SQLDatabase(con, meta=meta)
table = pandas_sql.read_table(
table_name,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
columns=columns,
chunksize=chunksize,
)
if table is not None:
return table
else:
raise ValueError(f"Table {table_name} not found", con)
@overload
def read_sql_query(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
chunksize: None = None,
) -> DataFrame:
...
@overload
def read_sql_query(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
chunksize: int = 1,
) -> Iterator[DataFrame]:
...
def read_sql_query(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
chunksize: Optional[int] = None,
) -> Union[DataFrame, Iterator[DataFrame]]:
"""
Read SQL query into a DataFrame.
Returns a DataFrame corresponding to the result set of the query
string. Optionally provide an `index_col` parameter to use one of the
columns as the index, otherwise default integer index will be used.
Parameters
----------
sql : str SQL query or SQLAlchemy Selectable (select or text object)
SQL query to be executed.
con : SQLAlchemy connectable(engine/connection), database str URI,
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
index_col : str or list of str, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : bool, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point. Useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}.
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame or Iterator[DataFrame]
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql : Read SQL query or database table into a DataFrame.
Notes
-----
Any datetime values with time zone information parsed via the `parse_dates`
parameter will be converted to UTC.
"""
pandas_sql = pandasSQL_builder(con)
return pandas_sql.read_query(
sql,
index_col=index_col,
params=params,
coerce_float=coerce_float,
parse_dates=parse_dates,
chunksize=chunksize,
)
@overload
def read_sql(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize: None = None,
) -> DataFrame:
...
@overload
def read_sql(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize: int = 1,
) -> Iterator[DataFrame]:
...
def read_sql(
sql,
con,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
columns=None,
chunksize: Optional[int] = None,
) -> Union[DataFrame, Iterator[DataFrame]]:
"""
Read SQL query or database table into a DataFrame.
This function is a convenience wrapper around ``read_sql_table`` and
``read_sql_query`` (for backward compatibility). It will delegate
to the specific function depending on the provided input. A SQL query
will be routed to ``read_sql_query``, while a database table name will
be routed to ``read_sql_table``. Note that the delegated function might
have more specific notes about their functionality not listed here.
Parameters
----------
sql : str or SQLAlchemy Selectable (select or text object)
SQL query to be executed or a table name.
con : SQLAlchemy connectable (engine/connection) or database str URI
or DBAPI2 connection (fallback mode).
Using SQLAlchemy makes it possible to use any DB supported by that
library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible
for engine disposal and connection closure for the SQLAlchemy connectable. See
`here <https://docs.sqlalchemy.org/en/13/core/connections.html>`_.
index_col : str or list of str, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : bool, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}.
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default: None
List of column names to select from SQL table (only used when reading
a table).
chunksize : int, default None
If specified, return an iterator where `chunksize` is the
number of rows to include in each chunk.
Returns
-------
DataFrame or Iterator[DataFrame]
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql_query : Read SQL query into a DataFrame.
"""
pandas_sql = pandasSQL_builder(con)
if isinstance(pandas_sql, SQLiteDatabase):
return pandas_sql.read_query(
sql,
index_col=index_col,
params=params,
coerce_float=coerce_float,
parse_dates=parse_dates,
chunksize=chunksize,
)
try:
_is_table_name = pandas_sql.has_table(sql)
except Exception:
# using generic exception to catch errors from sql drivers (GH24988)
_is_table_name = False
if _is_table_name:
pandas_sql.meta.reflect(only=[sql])
return pandas_sql.read_table(
sql,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
columns=columns,
chunksize=chunksize,
)
else:
return pandas_sql.read_query(
sql,
index_col=index_col,
params=params,
coerce_float=coerce_float,
parse_dates=parse_dates,
chunksize=chunksize,
)
def to_sql(
frame,
name,
con,
schema=None,
if_exists="fail",
index=True,
index_label=None,
chunksize=None,
dtype=None,
method=None,
) -> None:
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame, Series
name : str
Name of SQL table.
con : SQLAlchemy connectable(engine/connection) or database string URI
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
schema : str, optional
Name of SQL schema in database to write to (if database flavor
supports this). If None, use default schema (default).
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : str or sequence, optional
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
chunksize : int, optional
Specify the number of rows in each batch to be written at a time.
By default, all rows will be written at once.
dtype : dict or scalar, optional
Specifying the datatype for columns. If a dictionary is used, the
keys should be the column names and the values should be the
SQLAlchemy types or strings for the sqlite3 fallback mode. If a
scalar is provided, it will be applied to all columns.
method : {None, 'multi', callable}, optional
Controls the SQL insertion clause used:
- None : Uses standard SQL ``INSERT`` clause (one per row).
- 'multi': Pass multiple values in a single ``INSERT`` clause.
- callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if if_exists not in ("fail", "replace", "append"):
raise ValueError(f"'{if_exists}' is not valid for if_exists")
pandas_sql = pandasSQL_builder(con, schema=schema)
if isinstance(frame, Series):
frame = frame.to_frame()
elif not isinstance(frame, DataFrame):
raise NotImplementedError(
"'frame' argument should be either a Series or a DataFrame"
)
pandas_sql.to_sql(
frame,
name,
if_exists=if_exists,
index=index,
index_label=index_label,
schema=schema,
chunksize=chunksize,
dtype=dtype,
method=method,
)
def has_table(table_name, con, schema=None):
"""
Check if DataBase has named table.
Parameters
----------
table_name: string
Name of SQL table.
con: SQLAlchemy connectable(engine/connection) or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
schema : string, default None
Name of SQL schema in database to write to (if database flavor supports
this). If None, use default schema (default).
Returns
-------
boolean
"""
pandas_sql = pandasSQL_builder(con, schema=schema)
return pandas_sql.has_table(table_name)
table_exists = has_table
def _engine_builder(con):
"""
Returns a SQLAlchemy engine from a URI (if con is a string)
else it just return con without modifying it.
"""
global _SQLALCHEMY_INSTALLED
if isinstance(con, str):
try:
import sqlalchemy
except ImportError:
_SQLALCHEMY_INSTALLED = False
else:
con = sqlalchemy.create_engine(con)
return con
return con
def pandasSQL_builder(con, schema=None, meta=None, is_cursor=False):
"""
Convenience function to return the correct PandasSQL subclass based on the
provided parameters.
"""
# When support for DBAPI connections is removed,
# is_cursor should not be necessary.
con = _engine_builder(con)
if _is_sqlalchemy_connectable(con):
return SQLDatabase(con, schema=schema, meta=meta)
elif isinstance(con, str):
raise ImportError("Using URI string without sqlalchemy installed.")
else:
return SQLiteDatabase(con, is_cursor=is_cursor)
class SQLTable(PandasObject):
"""
For mapping Pandas tables to SQL tables.
Uses fact that table is reflected by SQLAlchemy to
do better type conversions.
Also holds various flags needed to avoid having to
pass them between functions all the time.
"""
# TODO: support for multiIndex
def __init__(
self,
name,
pandas_sql_engine,
frame=None,
index=True,
if_exists="fail",
prefix="pandas",
index_label=None,
schema=None,
keys=None,
dtype=None,
):
self.name = name
self.pd_sql = pandas_sql_engine
self.prefix = prefix
self.frame = frame
self.index = self._index_name(index, index_label)
self.schema = schema
self.if_exists = if_exists
self.keys = keys
self.dtype = dtype
if frame is not None:
# We want to initialize based on a dataframe
self.table = self._create_table_setup()
else:
# no data provided, read-only mode
self.table = self.pd_sql.get_table(self.name, self.schema)
if self.table is None:
raise ValueError(f"Could not init table '{name}'")
def exists(self):
return self.pd_sql.has_table(self.name, self.schema)
def sql_schema(self):
from sqlalchemy.schema import CreateTable
return str(CreateTable(self.table).compile(self.pd_sql.connectable))
def _execute_create(self):
# Inserting table into database, add to MetaData object
self.table = self.table.tometadata(self.pd_sql.meta)
self.table.create()
def create(self):
if self.exists():
if self.if_exists == "fail":
raise ValueError(f"Table '{self.name}' already exists.")
elif self.if_exists == "replace":
self.pd_sql.drop_table(self.name, self.schema)
self._execute_create()
elif self.if_exists == "append":
pass
else:
raise ValueError(f"'{self.if_exists}' is not valid for if_exists")
else:
self._execute_create()
def _execute_insert(self, conn, keys, data_iter):
"""
Execute SQL statement inserting data
Parameters
----------
conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection
keys : list of str
Column names
data_iter : generator of list
Each item contains a list of values to be inserted
"""
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(self.table.insert(), data)
def _execute_insert_multi(self, conn, keys, data_iter):
"""
Alternative to _execute_insert for DBs support multivalue INSERT.
Note: multi-value insert is usually faster for analytics DBs
and tables containing a few columns
but performance degrades quickly with increase of columns.
"""
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(self.table.insert(data))
def insert_data(self):
if self.index is not None:
temp = self.frame.copy()
temp.index.names = self.index
try:
temp.reset_index(inplace=True)
except ValueError as err:
raise ValueError(f"duplicate name in index/columns: {err}") from err
else:
temp = self.frame
column_names = list(map(str, temp.columns))
ncols = len(column_names)
data_list = [None] * ncols
for i, (_, ser) in enumerate(temp.items()):
vals = ser._values
if vals.dtype.kind == "M":
d = vals.to_pydatetime()
elif vals.dtype.kind == "m":
# store as integers, see GH#6921, GH#7076
d = vals.view("i8").astype(object)
else:
d = vals.astype(object)
assert isinstance(d, np.ndarray), type(d)
if ser._can_hold_na:
# Note: this will miss timedeltas since they are converted to int
mask = isna(d)
d[mask] = None
data_list[i] = d
return column_names, data_list
def insert(self, chunksize=None, method=None):
# set insert method
if method is None:
exec_insert = self._execute_insert
elif method == "multi":
exec_insert = self._execute_insert_multi
elif callable(method):
exec_insert = partial(method, self)
else:
raise ValueError(f"Invalid parameter `method`: {method}")
keys, data_list = self.insert_data()
nrows = len(self.frame)
if nrows == 0:
return
if chunksize is None:
chunksize = nrows
elif chunksize == 0:
raise ValueError("chunksize argument should be non-zero")
chunks = int(nrows / chunksize) + 1
with self.pd_sql.run_transaction() as conn:
for i in range(chunks):
start_i = i * chunksize
end_i = min((i + 1) * chunksize, nrows)
if start_i >= end_i:
break
chunk_iter = zip(*[arr[start_i:end_i] for arr in data_list])
exec_insert(conn, keys, chunk_iter)
def _query_iterator(
self, result, chunksize, columns, coerce_float=True, parse_dates=None
):
"""Return generator through chunked result set."""
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
self.frame = DataFrame.from_records(
data, columns=columns, coerce_float=coerce_float
)
self._harmonize_columns(parse_dates=parse_dates)
if self.index is not None:
self.frame.set_index(self.index, inplace=True)
yield self.frame
def read(self, coerce_float=True, parse_dates=None, columns=None, chunksize=None):
if columns is not None and len(columns) > 0:
from sqlalchemy import select
cols = [self.table.c[n] for n in columns]
if self.index is not None:
for idx in self.index[::-1]:
cols.insert(0, self.table.c[idx])
sql_select = select(cols)
else:
sql_select = self.table.select()
result = self.pd_sql.execute(sql_select)
column_names = result.keys()
if chunksize is not None:
return self._query_iterator(
result,
chunksize,
column_names,
coerce_float=coerce_float,
parse_dates=parse_dates,
)
else:
data = result.fetchall()
self.frame = DataFrame.from_records(
data, columns=column_names, coerce_float=coerce_float
)
self._harmonize_columns(parse_dates=parse_dates)
if self.index is not None:
self.frame.set_index(self.index, inplace=True)
return self.frame
def _index_name(self, index, index_label):
# for writing: index=True to include index in sql table
if index is True:
nlevels = self.frame.index.nlevels
# if index_label is specified, set this as index name(s)
if index_label is not None:
if not isinstance(index_label, list):
index_label = [index_label]
if len(index_label) != nlevels:
raise ValueError(
"Length of 'index_label' should match number of "
f"levels, which is {nlevels}"
)
else:
return index_label
# return the used column labels for the index columns
if (
nlevels == 1
and "index" not in self.frame.columns
and self.frame.index.name is None
):
return ["index"]
else:
return [
l if l is not None else f"level_{i}"
for i, l in enumerate(self.frame.index.names)
]
# for reading: index=(list of) string to specify column to set as index
elif isinstance(index, str):
return [index]
elif isinstance(index, list):
return index
else:
return None
def _get_column_names_and_types(self, dtype_mapper):
column_names_and_types = []
if self.index is not None:
for i, idx_label in enumerate(self.index):
idx_type = dtype_mapper(self.frame.index._get_level_values(i))
column_names_and_types.append((str(idx_label), idx_type, True))
column_names_and_types += [
(str(self.frame.columns[i]), dtype_mapper(self.frame.iloc[:, i]), False)
for i in range(len(self.frame.columns))
]
return column_names_and_types
def _create_table_setup(self):
from sqlalchemy import Table, Column, PrimaryKeyConstraint
column_names_and_types = self._get_column_names_and_types(self._sqlalchemy_type)
columns = [
Column(name, typ, index=is_index)
for name, typ, is_index in column_names_and_types
]
if self.keys is not None:
if not is_list_like(self.keys):
keys = [self.keys]
else:
keys = self.keys
pkc = PrimaryKeyConstraint(*keys, name=self.name + "_pk")
columns.append(pkc)
schema = self.schema or self.pd_sql.meta.schema
# At this point, attach to new metadata, only attach to self.meta
# once table is created.
from sqlalchemy.schema import MetaData
meta = MetaData(self.pd_sql, schema=schema)
return Table(self.name, meta, *columns, schema=schema)
def _harmonize_columns(self, parse_dates=None):
"""
Make the DataFrame's column types align with the SQL table
column types.
Need to work around limited NA value support. Floats are always
fine, ints must always be floats if there are Null values.
Booleans are hard because converting bool column with None replaces
all Nones with false. Therefore only convert bool if there are no
NA values.
Datetimes should already be converted to np.datetime64 if supported,
but here we also force conversion if required.
"""
parse_dates = _process_parse_dates_argument(parse_dates)
for sql_col in self.table.columns:
col_name = sql_col.name
try:
df_col = self.frame[col_name]
# Handle date parsing upfront; don't try to convert columns
# twice
if col_name in parse_dates:
try:
fmt = parse_dates[col_name]
except TypeError:
fmt = None
self.frame[col_name] = _handle_date_column(df_col, format=fmt)
continue
# the type the dataframe column should have
col_type = self._get_dtype(sql_col.type)
if (
col_type is datetime
or col_type is date
or col_type is DatetimeTZDtype
):
# Convert tz-aware Datetime SQL columns to UTC
utc = col_type is DatetimeTZDtype
self.frame[col_name] = _handle_date_column(df_col, utc=utc)
elif col_type is float:
# floats support NA, can always convert!
self.frame[col_name] = df_col.astype(col_type, copy=False)
elif len(df_col) == df_col.count():
# No NA values, can convert ints and bools
if col_type is np.dtype("int64") or col_type is bool:
self.frame[col_name] = df_col.astype(col_type, copy=False)
except KeyError:
pass # this column not in results
def _sqlalchemy_type(self, col):
dtype = self.dtype or {}
if col.name in dtype:
return self.dtype[col.name]
# Infer type of column, while ignoring missing values.
# Needed for inserting typed data containing NULLs, GH 8778.
col_type = lib.infer_dtype(col, skipna=True)
from sqlalchemy.types import (
BigInteger,
Integer,
Float,
Text,
Boolean,
DateTime,
Date,
Time,
TIMESTAMP,
)
if col_type == "datetime64" or col_type == "datetime":
# GH 9086: TIMESTAMP is the suggested type if the column contains
# timezone information
try:
if col.dt.tz is not None:
return TIMESTAMP(timezone=True)
except AttributeError:
# The column is actually a DatetimeIndex
# GH 26761 or an Index with date-like data e.g. 9999-01-01
if getattr(col, "tz", None) is not None:
return TIMESTAMP(timezone=True)
return DateTime
if col_type == "timedelta64":
warnings.warn(
"the 'timedelta' type is not supported, and will be "
"written as integer values (ns frequency) to the database.",
UserWarning,
stacklevel=8,
)
return BigInteger
elif col_type == "floating":
if col.dtype == "float32":
return Float(precision=23)
else:
return Float(precision=53)
elif col_type == "integer":
if col.dtype == "int32":
return Integer
else:
return BigInteger
elif col_type == "boolean":
return Boolean
elif col_type == "date":
return Date
elif col_type == "time":
return Time
elif col_type == "complex":
raise ValueError("Complex datatypes not supported")
return Text
def _get_dtype(self, sqltype):
from sqlalchemy.types import Integer, Float, Boolean, DateTime, Date, TIMESTAMP
if isinstance(sqltype, Float):
return float
elif isinstance(sqltype, Integer):
# TODO: Refine integer size.
return np.dtype("int64")
elif isinstance(sqltype, TIMESTAMP):
# we have a timezone capable type
if not sqltype.timezone:
return datetime
return DatetimeTZDtype
elif isinstance(sqltype, DateTime):
# Caution: np.datetime64 is also a subclass of np.number.
return datetime
elif isinstance(sqltype, Date):
return date
elif isinstance(sqltype, Boolean):
return bool
return object
class PandasSQL(PandasObject):
"""
Subclasses Should define read_sql and to_sql.
"""
def read_sql(self, *args, **kwargs):
raise ValueError(
"PandasSQL must be created with an SQLAlchemy "
"connectable or sqlite connection"
)
def to_sql(self, *args, **kwargs):
raise ValueError(
"PandasSQL must be created with an SQLAlchemy "
"connectable or sqlite connection"
)
class SQLDatabase(PandasSQL):
"""
This class enables conversion between DataFrame and SQL databases
using SQLAlchemy to handle DataBase abstraction.
Parameters
----------
engine : SQLAlchemy connectable
Connectable to connect with the database. Using SQLAlchemy makes it
possible to use any DB supported by that library.
schema : string, default None
Name of SQL schema in database to write to (if database flavor
supports this). If None, use default schema (default).
meta : SQLAlchemy MetaData object, default None
If provided, this MetaData object is used instead of a newly
created. This allows to specify database flavor specific
arguments in the MetaData object.
"""
def __init__(self, engine, schema=None, meta=None):
self.connectable = engine
if not meta:
from sqlalchemy.schema import MetaData
meta = MetaData(self.connectable, schema=schema)
self.meta = meta
@contextmanager
def run_transaction(self):
with self.connectable.begin() as tx:
if hasattr(tx, "execute"):
yield tx
else:
yield self.connectable
def execute(self, *args, **kwargs):
"""Simple passthrough to SQLAlchemy connectable"""
return self.connectable.execution_options(no_parameters=True).execute(
*args, **kwargs
)
def read_table(
self,
table_name,
index_col=None,
coerce_float=True,
parse_dates=None,
columns=None,
schema=None,
chunksize=None,
):
"""
Read SQL database table into a DataFrame.
Parameters
----------
table_name : string
Name of SQL table in database.
index_col : string, optional, default: None
Column to set as index.
coerce_float : boolean, default True
Attempts to convert values of non-string, non-numeric objects
(like decimal.Decimal) to floating point. This can result in
loss of precision.
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg}``, where the arg corresponds
to the keyword arguments of :func:`pandas.to_datetime`.
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default: None
List of column names to select from SQL table.
schema : string, default None
Name of SQL schema in database to query (if database flavor
supports this). If specified, this overwrites the default
schema of the SQL database object.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number
of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
pandas.read_sql_table
SQLDatabase.read_query
"""
table = SQLTable(table_name, self, index=index_col, schema=schema)
return table.read(
coerce_float=coerce_float,
parse_dates=parse_dates,
columns=columns,
chunksize=chunksize,
)
@staticmethod
def _query_iterator(
result, chunksize, columns, index_col=None, coerce_float=True, parse_dates=None
):
"""Return generator through chunked result set"""
while True:
data = result.fetchmany(chunksize)
if not data:
break
else:
yield _wrap_result(
data,
columns,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
)
def read_query(
self,
sql,
index_col=None,
coerce_float=True,
parse_dates=None,
params=None,
chunksize=None,
):
"""
Read SQL query into a DataFrame.
Parameters
----------
sql : string
SQL query to be executed.
index_col : string, optional, default: None
Column name to use as index for the returned DataFrame object.
coerce_float : boolean, default True
Attempt to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
List of parameters to pass to execute method. The syntax used
to pass parameters is database driver dependent. Check your
database driver documentation for which of the five syntax styles,
described in PEP 249's paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={'name' : 'value'}
parse_dates : list or dict, default: None
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times, or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict
corresponds to the keyword arguments of
:func:`pandas.to_datetime` Especially useful with databases
without native Datetime support, such as SQLite.
chunksize : int, default None
If specified, return an iterator where `chunksize` is the number
of rows to include in each chunk.
Returns
-------
DataFrame
See Also
--------
read_sql_table : Read SQL database table into a DataFrame.
read_sql
"""
args = _convert_params(sql, params)
result = self.execute(*args)
columns = result.keys()
if chunksize is not None:
return self._query_iterator(
result,
chunksize,
columns,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
)
else:
data = result.fetchall()
frame = _wrap_result(
data,
columns,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
)
return frame
read_sql = read_query
def to_sql(
self,
frame,
name,
if_exists="fail",
index=True,
index_label=None,
schema=None,
chunksize=None,
dtype=None,
method=None,
):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame
name : string
Name of SQL table.
if_exists : {'fail', 'replace', 'append'}, default 'fail'
- fail: If table exists, do nothing.
- replace: If table exists, drop it, recreate it, and insert data.
- append: If table exists, insert data. Create if does not exist.
index : boolean, default True
Write DataFrame index as a column.
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
schema : string, default None
Name of SQL schema in database to write to (if database flavor
supports this). If specified, this overwrites the default
schema of the SQLDatabase object.
chunksize : int, default None
If not None, then rows will be written in batches of this size at a
time. If None, all rows will be written at once.
dtype : single type or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type. If all columns are of the same type, one
single value can be used.
method : {None', 'multi', callable}, default None
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if dtype and not is_dict_like(dtype):
dtype = {col_name: dtype for col_name in frame}
if dtype is not None:
from sqlalchemy.types import to_instance, TypeEngine
for col, my_type in dtype.items():
if not isinstance(to_instance(my_type), TypeEngine):
raise ValueError(f"The type of {col} is not a SQLAlchemy type")
table = SQLTable(
name,
self,
frame=frame,
index=index,
if_exists=if_exists,
index_label=index_label,
schema=schema,
dtype=dtype,
)
table.create()
table.insert(chunksize, method=method)
if not name.isdigit() and not name.islower():
# check for potentially case sensitivity issues (GH7815)
# Only check when name is not a number and name is not lower case
engine = self.connectable.engine
with self.connectable.connect() as conn:
table_names = engine.table_names(
schema=schema or self.meta.schema, connection=conn
)
if name not in table_names:
msg = (
f"The provided table name '{name}' is not found exactly as "
"such in the database after writing the table, possibly "
"due to case sensitivity issues. Consider using lower "
"case table names."
)
warnings.warn(msg, UserWarning)
@property
def tables(self):
return self.meta.tables
def has_table(self, name, schema=None):
return self.connectable.run_callable(
self.connectable.dialect.has_table, name, schema or self.meta.schema
)
def get_table(self, table_name, schema=None):
schema = schema or self.meta.schema
if schema:
tbl = self.meta.tables.get(".".join([schema, table_name]))
else:
tbl = self.meta.tables.get(table_name)
# Avoid casting double-precision floats into decimals
from sqlalchemy import Numeric
for column in tbl.columns:
if isinstance(column.type, Numeric):
column.type.asdecimal = False
return tbl
def drop_table(self, table_name, schema=None):
schema = schema or self.meta.schema
if self.has_table(table_name, schema):
self.meta.reflect(only=[table_name], schema=schema)
self.get_table(table_name, schema).drop()
self.meta.clear()
def _create_sql_schema(self, frame, table_name, keys=None, dtype=None):
table = SQLTable(
table_name, self, frame=frame, index=False, keys=keys, dtype=dtype
)
return str(table.sql_schema())
# ---- SQL without SQLAlchemy ---
# sqlite-specific sql strings and handler class
# dictionary used for readability purposes
_SQL_TYPES = {
"string": "TEXT",
"floating": "REAL",
"integer": "INTEGER",
"datetime": "TIMESTAMP",
"date": "DATE",
"time": "TIME",
"boolean": "INTEGER",
}
def _get_unicode_name(name):
try:
uname = str(name).encode("utf-8", "strict").decode("utf-8")
except UnicodeError as err:
raise ValueError(f"Cannot convert identifier to UTF-8: '{name}'") from err
return uname
def _get_valid_sqlite_name(name):
# See https://stackoverflow.com/questions/6514274/how-do-you-escape-strings\
# -for-sqlite-table-column-names-in-python
# Ensure the string can be encoded as UTF-8.
# Ensure the string does not include any NUL characters.
# Replace all " with "".
# Wrap the entire thing in double quotes.
uname = _get_unicode_name(name)
if not len(uname):
raise ValueError("Empty table or column name specified")
nul_index = uname.find("\x00")
if nul_index >= 0:
raise ValueError("SQLite identifier cannot contain NULs")
return '"' + uname.replace('"', '""') + '"'
_SAFE_NAMES_WARNING = (
"The spaces in these column names will not be changed. "
"In pandas versions < 0.14, spaces were converted to underscores."
)
class SQLiteTable(SQLTable):
"""
Patch the SQLTable for fallback support.
Instead of a table variable just use the Create Table statement.
"""
def __init__(self, *args, **kwargs):
# GH 8341
# register an adapter callable for datetime.time object
import sqlite3
# this will transform time(12,34,56,789) into '12:34:56.000789'
# (this is what sqlalchemy does)
sqlite3.register_adapter(time, lambda _: _.strftime("%H:%M:%S.%f"))
super().__init__(*args, **kwargs)
def sql_schema(self):
return str(";\n".join(self.table))
def _execute_create(self):
with self.pd_sql.run_transaction() as conn:
for stmt in self.table:
conn.execute(stmt)
def insert_statement(self, *, num_rows):
names = list(map(str, self.frame.columns))
wld = "?" # wildcard char
escape = _get_valid_sqlite_name
if self.index is not None:
for idx in self.index[::-1]:
names.insert(0, idx)
bracketed_names = [escape(column) for column in names]
col_names = ",".join(bracketed_names)
row_wildcards = ",".join([wld] * len(names))
wildcards = ",".join(f"({row_wildcards})" for _ in range(num_rows))
insert_statement = (
f"INSERT INTO {escape(self.name)} ({col_names}) VALUES {wildcards}"
)
return insert_statement
def _execute_insert(self, conn, keys, data_iter):
data_list = list(data_iter)
conn.executemany(self.insert_statement(num_rows=1), data_list)
def _execute_insert_multi(self, conn, keys, data_iter):
data_list = list(data_iter)
flattened_data = [x for row in data_list for x in row]
conn.execute(self.insert_statement(num_rows=len(data_list)), flattened_data)
def _create_table_setup(self):
"""
Return a list of SQL statements that creates a table reflecting the
structure of a DataFrame. The first entry will be a CREATE TABLE
statement while the rest will be CREATE INDEX statements.
"""
column_names_and_types = self._get_column_names_and_types(self._sql_type_name)
pat = re.compile(r"\s+")
column_names = [col_name for col_name, _, _ in column_names_and_types]
if any(map(pat.search, column_names)):
warnings.warn(_SAFE_NAMES_WARNING, stacklevel=6)
escape = _get_valid_sqlite_name
create_tbl_stmts = [
escape(cname) + " " + ctype for cname, ctype, _ in column_names_and_types
]
if self.keys is not None and len(self.keys):
if not is_list_like(self.keys):
keys = [self.keys]
else:
keys = self.keys
cnames_br = ", ".join(escape(c) for c in keys)
create_tbl_stmts.append(
f"CONSTRAINT {self.name}_pk PRIMARY KEY ({cnames_br})"
)
create_stmts = [
"CREATE TABLE "
+ escape(self.name)
+ " (\n"
+ ",\n ".join(create_tbl_stmts)
+ "\n)"
]
ix_cols = [cname for cname, _, is_index in column_names_and_types if is_index]
if len(ix_cols):
cnames = "_".join(ix_cols)
cnames_br = ",".join(escape(c) for c in ix_cols)
create_stmts.append(
"CREATE INDEX "
+ escape("ix_" + self.name + "_" + cnames)
+ "ON "
+ escape(self.name)
+ " ("
+ cnames_br
+ ")"
)
return create_stmts
def _sql_type_name(self, col):
dtype = self.dtype or {}
if col.name in dtype:
return dtype[col.name]
# Infer type of column, while ignoring missing values.
# Needed for inserting typed data containing NULLs, GH 8778.
col_type = lib.infer_dtype(col, skipna=True)
if col_type == "timedelta64":
warnings.warn(
"the 'timedelta' type is not supported, and will be "
"written as integer values (ns frequency) to the database.",
UserWarning,
stacklevel=8,
)
col_type = "integer"
elif col_type == "datetime64":
col_type = "datetime"
elif col_type == "empty":
col_type = "string"
elif col_type == "complex":
raise ValueError("Complex datatypes not supported")
if col_type not in _SQL_TYPES:
col_type = "string"
return _SQL_TYPES[col_type]
class SQLiteDatabase(PandasSQL):
"""
Version of SQLDatabase to support SQLite connections (fallback without
SQLAlchemy). This should only be used internally.
Parameters
----------
con : sqlite connection object
"""
def __init__(self, con, is_cursor=False):
self.is_cursor = is_cursor
self.con = con
@contextmanager
def run_transaction(self):
cur = self.con.cursor()
try:
yield cur
self.con.commit()
except Exception:
self.con.rollback()
raise
finally:
cur.close()
def execute(self, *args, **kwargs):
if self.is_cursor:
cur = self.con
else:
cur = self.con.cursor()
try:
cur.execute(*args, **kwargs)
return cur
except Exception as exc:
try:
self.con.rollback()
except Exception as inner_exc: # pragma: no cover
ex = DatabaseError(
f"Execution failed on sql: {args[0]}\n{exc}\nunable to rollback"
)
raise ex from inner_exc
ex = DatabaseError(f"Execution failed on sql '{args[0]}': {exc}")
raise ex from exc
@staticmethod
def _query_iterator(
cursor, chunksize, columns, index_col=None, coerce_float=True, parse_dates=None
):
"""Return generator through chunked result set"""
while True:
data = cursor.fetchmany(chunksize)
if type(data) == tuple:
data = list(data)
if not data:
cursor.close()
break
else:
yield _wrap_result(
data,
columns,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
)
def read_query(
self,
sql,
index_col=None,
coerce_float=True,
params=None,
parse_dates=None,
chunksize=None,
):
args = _convert_params(sql, params)
cursor = self.execute(*args)
columns = [col_desc[0] for col_desc in cursor.description]
if chunksize is not None:
return self._query_iterator(
cursor,
chunksize,
columns,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
)
else:
data = self._fetchall_as_list(cursor)
cursor.close()
frame = _wrap_result(
data,
columns,
index_col=index_col,
coerce_float=coerce_float,
parse_dates=parse_dates,
)
return frame
def _fetchall_as_list(self, cur):
result = cur.fetchall()
if not isinstance(result, list):
result = list(result)
return result
def to_sql(
self,
frame,
name,
if_exists="fail",
index=True,
index_label=None,
schema=None,
chunksize=None,
dtype=None,
method=None,
):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame: DataFrame
name: string
Name of SQL table.
if_exists: {'fail', 'replace', 'append'}, default 'fail'
fail: If table exists, do nothing.
replace: If table exists, drop it, recreate it, and insert data.
append: If table exists, insert data. Create if it does not exist.
index : boolean, default True
Write DataFrame index as a column
index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and
`index` is True, then the index names are used.
A sequence should be given if the DataFrame uses MultiIndex.
schema : string, default None
Ignored parameter included for compatibility with SQLAlchemy
version of ``to_sql``.
chunksize : int, default None
If not None, then rows will be written in batches of this
size at a time. If None, all rows will be written at once.
dtype : single type or dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a string. If all columns are of the same type, one single value
can be used.
method : {None, 'multi', callable}, default None
Controls the SQL insertion clause used:
* None : Uses standard SQL ``INSERT`` clause (one per row).
* 'multi': Pass multiple values in a single ``INSERT`` clause.
* callable with signature ``(pd_table, conn, keys, data_iter)``.
Details and a sample callable implementation can be found in the
section :ref:`insert method <io.sql.method>`.
.. versionadded:: 0.24.0
"""
if dtype and not is_dict_like(dtype):
dtype = {col_name: dtype for col_name in frame}
if dtype is not None:
for col, my_type in dtype.items():
if not isinstance(my_type, str):
raise ValueError(f"{col} ({my_type}) not a string")
table = SQLiteTable(
name,
self,
frame=frame,
index=index,
if_exists=if_exists,
index_label=index_label,
dtype=dtype,
)
table.create()
table.insert(chunksize, method)
def has_table(self, name, schema=None):
# TODO(wesm): unused?
# escape = _get_valid_sqlite_name
# esc_name = escape(name)
wld = "?"
query = f"SELECT name FROM sqlite_master WHERE type='table' AND name={wld};"
return len(self.execute(query, [name]).fetchall()) > 0
def get_table(self, table_name, schema=None):
return None # not supported in fallback mode
def drop_table(self, name, schema=None):
drop_sql = f"DROP TABLE {_get_valid_sqlite_name(name)}"
self.execute(drop_sql)
def _create_sql_schema(self, frame, table_name, keys=None, dtype=None):
table = SQLiteTable(
table_name, self, frame=frame, index=False, keys=keys, dtype=dtype
)
return str(table.sql_schema())
def get_schema(frame, name, keys=None, con=None, dtype=None):
"""
Get the SQL db table schema for the given frame.
Parameters
----------
frame : DataFrame
name : string
name of SQL table
keys : string or sequence, default: None
columns to use a primary key
con: an open SQL database connection object or a SQLAlchemy connectable
Using SQLAlchemy makes it possible to use any DB supported by that
library, default: None
If a DBAPI2 object, only sqlite3 is supported.
dtype : dict of column name to SQL type, default None
Optional specifying the datatype for columns. The SQL type should
be a SQLAlchemy type, or a string for sqlite3 fallback connection.
"""
pandas_sql = pandasSQL_builder(con=con)
return pandas_sql._create_sql_schema(frame, name, keys=keys, dtype=dtype)
| TomAugspurger/pandas | pandas/io/sql.py | Python | bsd-3-clause | 62,333 |
<!DOCTYPE HTML>
<html>
<!--
Copyright (c) 2012 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<head>
<title>ProfilingView tests</title>
<script src="base.js"></script>
<style>
.profiling-view {
border: 1px solid black;
}
</style>
</head>
<body>
<script>
base.require('unittest');
base.require('test_utils');
base.require('profiling_view');
base.require('tracing_controller');
</script>
<script>
'use strict';
var testData = [
{name: 'a', args: {}, pid: 52, ts: 15000, cat: 'foo', tid: 53, ph: 'B'},
{name: 'a', args: {}, pid: 52, ts: 19000, cat: 'foo', tid: 53, ph: 'E'},
{name: 'b', args: {}, pid: 52, ts: 32000, cat: 'foo', tid: 53, ph: 'B'},
{name: 'b', args: {}, pid: 52, ts: 54000, cat: 'foo', tid: 53, ph: 'E'}
];
var systemTraceTestData = [
'systrace.sh-8170 [000] 0.013: sched_switch: ' +
'prev_comm=systrace.sh prev_pid=8170 prev_prio=120 ' +
'prev_state=x ==> next_comm=kworker/1:0 next_pid=7873 ' +
'next_prio=120',
' kworker/1:0-7873 [000] 0.036: sched_switch: ' +
'prev_comm=kworker/1:0 prev_pid=7873 prev_prio=120 ' +
'prev_state=S ==> next_comm=debugd next_pid=4404 next_prio=120',
' debugd-4404 [000] 0.070: sched_switch: prev_comm=debugd ' +
'prev_pid=4404 prev_prio=120 prev_state=S ==> ' +
'next_comm=dbus-daemon next_pid=510 next_prio=120',
'systrace.sh-8182 [000] 0.000: tracing_mark_write: ' +
'trace_event_clock_sync: parent_ts=0.0'
].join('\n');
/* This test just instantiates a ProflingView and adds it to the DOM
* to help with non-unittest UI work.
*/
function testInstantiate() {
var view = new tracing.ProfilingView();
var tracingController;
// This code emulates Chrome's responses to sendFn enough that the real
// tracing controller can be used to interactively test the UI.
var systemTraceRequested = false;
function send(message, opt_args) {
var args = opt_args || [];
if (message == 'beginTracing') {
systemTraceRequested = opt_args[0];
} else if (message == 'beginRequestBufferPercentFull') {
setTimeout(function() {
view.tracingController.onRequestBufferPercentFullComplete(0.5);
}, 1);
} else if (message == 'endTracingAsync') {
setTimeout(function() {
if (systemTraceRequested) {
view.tracingController.onSystemTraceDataCollected(
systemTraceTestData);
}
view.tracingController.onTraceDataCollected(testData);
view.tracingController.onEndTracingComplete();
}, 1);
} else if (message == 'loadTraceFile') {
setTimeout(function() {
view.tracingController.onLoadTraceFileComplete(
JSON.stringify(testData));
}, 150);
} else if (message == 'saveTraceFile') {
setTimeout(function() {
view.tracingController.onSaveTraceFileComplete();
}, 1);
}
}
tracingController = new tracing.TracingController(send);
tracingController.supportsSystemTracing_ = true;
view.tracingController = tracingController;
view.focusElement = view;
this.addHTMLOutput(undefined, view);
}
/*
* Just enough of the TracingController to support the tests below.
*/
function FakeTracingController() {
}
FakeTracingController.prototype = {
__proto__: base.EventTarget.prototype,
get supportsSystemTracing() {
return base.isChromeOS;
},
beginTracing: function(opt_systemTracingEnabled,
opt_continuousTracingEnabled,
opt_traceCategories) {
this.wasBeginTracingCalled = true;
this.wasBeginTracingCalledWithSystemTracingEnabled =
opt_systemTracingEnabled;
this.wasBeginTracingCalledWithContinuousTracingEnabled =
opt_continuousTracingEnabled;
this.beginTracingCategories = opt_traceCategories;
},
collectCategories: function() {
this.wasCollectCategoriesCalled = true;
},
get traceEvents() {
if (!this.wasBeginTracingCalled)
return undefined;
return testData;
},
get systemTraceEvents() {
if (!this.wasBeginTracingCalled)
return [];
if (!this.wasBeginTracingCalledWithSystemTracingEnabled)
return [];
return systemTraceTestData;
}
};
function recordTestCommon() {
var view = new tracing.ProfilingView();
var tracingController = new FakeTracingController();
view.tracingController = tracingController;
view.querySelector('button.record').click();
assertTrue(tracingController.wasCollectCategoriesCalled);
var e = new base.Event('categoriesCollected');
e.categories = ['skia', 'gpu'];
tracingController.dispatchEvent(e);
view.categorySelectionDialog_.querySelector(
'button.record-categories').click();
assertTrue(tracingController.wasBeginTracingCalled);
assertEquals(base.isChromeOS,
tracingController.wasBeginTracingCalledWithSystemTracingEnabled);
var e = new base.Event('traceEnded');
e.events = tracingController.traceEvents;
tracingController.dispatchEvent(e);
assertTrue(!!view.timelineView.model);
}
function testSelectedCategoriesSentToTracing() {
var view = new tracing.ProfilingView();
view.timelineView_.settings.set('cc', 'true', 'record_categories');
view.timelineView_.settings.set('renderer', 'false', 'record_categories');
var tracingController = new FakeTracingController();
view.tracingController = tracingController;
view.querySelector('button.record').click();
assertTrue(tracingController.wasCollectCategoriesCalled);
var e = new base.Event('categoriesCollected');
e.categories = ['skia', 'gpu', 'cc', 'renderer'];
tracingController.dispatchEvent(e);
view.categorySelectionDialog_.querySelector('input#skia').click();
view.categorySelectionDialog_.querySelector(
'button.record-categories').click();
var categories = tracingController.beginTracingCategories;
// Renderer is disabled in settings, skia is clicked off.
assertEquals('-renderer,-skia', categories);
}
function testBadCategories() {
var view = new tracing.ProfilingView();
view.timelineView_.settings.set('foo,bar', 'false', 'record_categories');
var tracingController = new FakeTracingController();
view.tracingController = tracingController;
view.querySelector('button.record').click();
assertTrue(tracingController.wasCollectCategoriesCalled);
var e = new base.Event('categoriesCollected');
e.categories = ['baz,zap', 'gpu'];
tracingController.dispatchEvent(e);
view.categorySelectionDialog_.querySelector(
'button.record-categories').click();
var inputs = view.categorySelectionDialog_.querySelectorAll('input');
var inputs_length = inputs.length;
for (var i = 0; i < inputs_length; ++i) {
// Comes from categories and should be split before getting
// to the category selection dialog.
assertNotEquals('baz,zap', inputs[i].id);
}
var categories = tracingController.beginTracingCategories;
assertEquals('', categories);
}
function testRecordNonCros() {
var old = base.isChromeOS;
base.isChromeOS = false;
try {
recordTestCommon();
} finally {
base.isChromeOS = old;
}
}
function testRecordCros() {
var old = base.isChromeOS;
base.isChromeOS = true;
try {
recordTestCommon();
} finally {
base.isChromeOS = old;
}
}
</script>
</body>
</html>
| CyanogenMod/android_external_chromium-trace | trace-viewer/src/profiling_view_test.html | HTML | bsd-3-clause | 8,129 |
<?php
/**
* Created by PhpStorm.
* User: Kate
* Date: 09.02.15
* Time: 14:13
*/
namespace backend\smile\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\helpers\VarDumper;
class SmileBackendController extends Controller {
public $enableCsrfValidation = false;
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'], // @ - auth users
],
[
'allow' => true,
'actions' => ['login'], // ? - guest users
'roles' => ['?'],
],
],
],
];
}
} | MaN4thes3t/smile-cms | backend/smile/controllers/SmileBackendController.php | PHP | bsd-3-clause | 1,062 |
dart_library.library('collection/priority_queue', null, /* Imports */[
"dart_runtime/dart",
'dart/core',
'dart/collection'
], /* Lazy imports */[
], function(exports, dart, core, collection) {
'use strict';
let dartx = dart.dartx;
let PriorityQueue$ = dart.generic(function(E) {
class PriorityQueue extends core.Object {}
return PriorityQueue;
});
let PriorityQueue = PriorityQueue$();
let _queue = Symbol('_queue');
let _length = Symbol('_length');
let _add = Symbol('_add');
let _locate = Symbol('_locate');
let _removeLast = Symbol('_removeLast');
let _bubbleUp = Symbol('_bubbleUp');
let _bubbleDown = Symbol('_bubbleDown');
let _grow = Symbol('_grow');
let HeapPriorityQueue$ = dart.generic(function(E) {
class HeapPriorityQueue extends core.Object {
HeapPriorityQueue(comparison) {
if (comparison === void 0)
comparison = null;
this[_queue] = core.List$(E).new(HeapPriorityQueue$()._INITIAL_CAPACITY);
this.comparison = comparison != null ? comparison : core.Comparable.compare;
this[_length] = 0;
}
add(element) {
dart.as(element, E);
this[_add](element);
}
addAll(elements) {
dart.as(elements, core.Iterable$(E));
for (let element of elements) {
this[_add](element);
}
}
clear() {
this[_queue] = dart.const(dart.list([], E));
this[_length] = 0;
}
contains(object) {
dart.as(object, E);
return dart.notNull(this[_locate](object)) >= 0;
}
get first() {
if (this[_length] == 0)
dart.throw(new core.StateError("No such element"));
return this[_queue][dartx.get](0);
}
get isEmpty() {
return this[_length] == 0;
}
get isNotEmpty() {
return this[_length] != 0;
}
get length() {
return this[_length];
}
remove(element) {
dart.as(element, E);
let index = this[_locate](element);
if (dart.notNull(index) < 0)
return false;
let last = this[_removeLast]();
if (dart.notNull(index) < dart.notNull(this[_length])) {
let comp = dart.dcall(this.comparison, last, element);
if (dart.notNull(comp) <= 0) {
this[_bubbleUp](last, index);
} else {
this[_bubbleDown](last, index);
}
}
return true;
}
removeAll() {
let result = this[_queue];
let length = this[_length];
this[_queue] = dart.const(dart.list([], E));
this[_length] = 0;
return result[dartx.take](length);
}
removeFirst() {
if (this[_length] == 0)
dart.throw(new core.StateError("No such element"));
let result = this[_queue][dartx.get](0);
let last = this[_removeLast]();
if (dart.notNull(this[_length]) > 0) {
this[_bubbleDown](last, 0);
}
return result;
}
toList() {
let list = core.List$(E).new();
list[dartx.length] = this[_length];
list[dartx.setRange](0, this[_length], this[_queue]);
list[dartx.sort](dart.as(this.comparison, __CastType0));
return list;
}
toSet() {
let set = new (collection.SplayTreeSet$(E))(dart.as(this.comparison, dart.functionType(core.int, [E, E])));
for (let i = 0; dart.notNull(i) < dart.notNull(this[_length]); i = dart.notNull(i) + 1) {
set.add(this[_queue][dartx.get](i));
}
return set;
}
toString() {
return dart.toString(this[_queue][dartx.take](this[_length]));
}
[_add](element) {
dart.as(element, E);
if (this[_length] == this[_queue][dartx.length])
this[_grow]();
this[_bubbleUp](element, (() => {
let x = this[_length];
this[_length] = dart.notNull(x) + 1;
return x;
})());
}
[_locate](object) {
dart.as(object, E);
if (this[_length] == 0)
return -1;
let position = 1;
do {
let index = dart.notNull(position) - 1;
let element = this[_queue][dartx.get](index);
let comp = dart.dcall(this.comparison, element, object);
if (comp == 0)
return index;
if (dart.notNull(comp) < 0) {
let leftChildPosition = dart.notNull(position) * 2;
if (dart.notNull(leftChildPosition) <= dart.notNull(this[_length])) {
position = leftChildPosition;
continue;
}
}
do {
while (dart.notNull(position[dartx.isOdd])) {
position = dart.notNull(position) >> 1;
}
position = dart.notNull(position) + 1;
} while (dart.notNull(position) > dart.notNull(this[_length]));
} while (position != 1);
return -1;
}
[_removeLast]() {
let newLength = dart.notNull(this[_length]) - 1;
let last = this[_queue][dartx.get](newLength);
this[_queue][dartx.set](newLength, null);
this[_length] = newLength;
return last;
}
[_bubbleUp](element, index) {
dart.as(element, E);
while (dart.notNull(index) > 0) {
let parentIndex = ((dart.notNull(index) - 1) / 2)[dartx.truncate]();
let parent = this[_queue][dartx.get](parentIndex);
if (dart.notNull(dart.dcall(this.comparison, element, parent)) > 0)
break;
this[_queue][dartx.set](index, parent);
index = parentIndex;
}
this[_queue][dartx.set](index, element);
}
[_bubbleDown](element, index) {
dart.as(element, E);
let rightChildIndex = dart.notNull(index) * 2 + 2;
while (dart.notNull(rightChildIndex) < dart.notNull(this[_length])) {
let leftChildIndex = dart.notNull(rightChildIndex) - 1;
let leftChild = this[_queue][dartx.get](leftChildIndex);
let rightChild = this[_queue][dartx.get](rightChildIndex);
let comp = dart.dcall(this.comparison, leftChild, rightChild);
let minChildIndex = null;
let minChild = null;
if (dart.notNull(comp) < 0) {
minChild = leftChild;
minChildIndex = leftChildIndex;
} else {
minChild = rightChild;
minChildIndex = rightChildIndex;
}
comp = dart.dcall(this.comparison, element, minChild);
if (dart.notNull(comp) <= 0) {
this[_queue][dartx.set](index, element);
return;
}
this[_queue][dartx.set](index, minChild);
index = minChildIndex;
rightChildIndex = dart.notNull(index) * 2 + 2;
}
let leftChildIndex = dart.notNull(rightChildIndex) - 1;
if (dart.notNull(leftChildIndex) < dart.notNull(this[_length])) {
let child = this[_queue][dartx.get](leftChildIndex);
let comp = dart.dcall(this.comparison, element, child);
if (dart.notNull(comp) > 0) {
this[_queue][dartx.set](index, child);
index = leftChildIndex;
}
}
this[_queue][dartx.set](index, element);
}
[_grow]() {
let newCapacity = dart.notNull(this[_queue][dartx.length]) * 2 + 1;
if (dart.notNull(newCapacity) < dart.notNull(HeapPriorityQueue$()._INITIAL_CAPACITY))
newCapacity = HeapPriorityQueue$()._INITIAL_CAPACITY;
let newQueue = core.List$(E).new(newCapacity);
newQueue[dartx.setRange](0, this[_length], this[_queue]);
this[_queue] = newQueue;
}
}
HeapPriorityQueue[dart.implements] = () => [PriorityQueue$(E)];
dart.setSignature(HeapPriorityQueue, {
constructors: () => ({HeapPriorityQueue: [HeapPriorityQueue$(E), [], [dart.functionType(core.int, [E, E])]]}),
methods: () => ({
add: [dart.void, [E]],
addAll: [dart.void, [core.Iterable$(E)]],
clear: [dart.void, []],
contains: [core.bool, [E]],
remove: [core.bool, [E]],
removeAll: [core.Iterable$(E), []],
removeFirst: [E, []],
toList: [core.List$(E), []],
toSet: [core.Set$(E), []],
[_add]: [dart.void, [E]],
[_locate]: [core.int, [E]],
[_removeLast]: [E, []],
[_bubbleUp]: [dart.void, [E, core.int]],
[_bubbleDown]: [dart.void, [E, core.int]],
[_grow]: [dart.void, []]
})
});
return HeapPriorityQueue;
});
let HeapPriorityQueue = HeapPriorityQueue$();
HeapPriorityQueue._INITIAL_CAPACITY = 7;
let __CastType0$ = dart.generic(function(E) {
let __CastType0 = dart.typedef('__CastType0', () => dart.functionType(core.int, [E, E]));
return __CastType0;
});
let __CastType0 = __CastType0$();
// Exports:
exports.PriorityQueue$ = PriorityQueue$;
exports.PriorityQueue = PriorityQueue;
exports.HeapPriorityQueue$ = HeapPriorityQueue$;
exports.HeapPriorityQueue = HeapPriorityQueue;
});
| ronlobo/dev_compiler | test/codegen/expect/collection/priority_queue.js | JavaScript | bsd-3-clause | 9,079 |
package org.hisp.dhis.system.util;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Lars Helge Overland
*/
public class PageRangeTest
{
@Test
public void testPageSize()
{
PageRange range = new PageRange( 12 ).setPageSize( 5 );
assertTrue( range.nextPage() );
assertEquals( 0, range.getFromIndex() );
assertEquals( 5, range.getToIndex() );
assertTrue( range.nextPage() );
assertEquals( 5, range.getFromIndex() );
assertEquals( 10, range.getToIndex() );
assertTrue( range.nextPage() );
assertEquals( 10, range.getFromIndex() );
assertEquals( 12, range.getToIndex() );
assertFalse( range.nextPage() );
}
@Test
public void testPages()
{
PageRange range = new PageRange( 11 ).setPages( 3 );
assertTrue( range.nextPage() );
assertEquals( 0, range.getFromIndex() );
assertEquals( 4, range.getToIndex() );
assertTrue( range.nextPage() );
assertEquals( 4, range.getFromIndex() );
assertEquals( 8, range.getToIndex() );
assertTrue( range.nextPage() );
assertEquals( 8, range.getFromIndex() );
assertEquals( 11, range.getToIndex() );
assertFalse( range.nextPage() );
}
@Test
public void testGetPages()
{
PageRange range = new PageRange( 12 ).setPageSize( 5 );
List<int[]> pages = range.getPages();
assertEquals( 3, pages.size() );
assertEquals( 0, pages.get( 0 )[0] );
assertEquals( 5, pages.get( 0 )[1] );
assertEquals( 5, pages.get( 1 )[0] );
assertEquals( 10, pages.get( 1 )[1] );
assertEquals( 10, pages.get( 2 )[0] );
assertEquals( 12, pages.get( 2 )[1] );
}
}
| kakada/dhis2 | dhis-support/dhis-support-system/src/test/java/org/hisp/dhis/system/util/PageRangeTest.java | Java | bsd-3-clause | 3,488 |
<?php
/**
* Live.php
* @author Revin Roman http://phptime.ru
*/
namespace resources\User\Auth;
/**
* Class Live
* @package resources\User\Auth
*/
class Live extends AbstractSocial
{
/**
* @return \resources\User\queries\UserLiveQuery
*/
public static function find()
{
return new \resources\User\queries\UserLiveQuery(get_called_class());
}
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user_auth_live}}';
}
} | rmrevin/yii2-application | resources/User/Auth/Live.php | PHP | bsd-3-clause | 510 |
<?php
use app\models\Options;
use app\models\UiListView;
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\widgets\Pjax;
$this->title = 'Payments';
?>
<div class="ui two column stackable grid">
<div class="twelve wide rounded column">
<div class="ui raised segment">
<div class="ui black ribbon label" style="margin-left: -2px;">
<h4>Payments</h4>
</div>
<div class="pull-right"><?= Html::a('<i class="icon plus"></i>',['create'],['class' => 'ui large green icon button']) ?></div>
<p></p>
<?php Pjax::begin(['id' => 'payment-list', 'timeout' => 10000]); ?>
<?= UiListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_list',
]); ?>
<?php Pjax::end(); ?>
</div>
</div>
<div class="four wide column">
<?= $this->render('_search', ['model' => $searchModel]) ?>
</div>
</div>
<?= $this->render('/layouts/_toast')?>
<?php
$pjax = <<< JS
$(document).ready(function(){
// setInterval(function(){
// $.pjax.reload({
// container:'#payment-list',
// success: function(){
// $('ul.pagination > li.active > a').click()
// }
// });
// }, 10000);
});
JS;
$this->registerJs($pjax);
?>
| elevatesolutions/proverbs | _protected/views/payments/index.php | PHP | bsd-3-clause | 1,370 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SYNC_ENGINE_IMPL_DIRECTORY_UPDATE_HANDLER_H_
#define COMPONENTS_SYNC_ENGINE_IMPL_DIRECTORY_UPDATE_HANDLER_H_
#include <map>
#include <memory>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "components/sync/base/model_type.h"
#include "components/sync/base/syncer_error.h"
#include "components/sync/engine_impl/process_updates_util.h"
#include "components/sync/engine_impl/update_handler.h"
namespace sync_pb {
class DataTypeProgressMarker;
}
namespace syncer {
class DataTypeDebugInfoEmitter;
class ModelSafeWorker;
class StatusController;
namespace syncable {
class Directory;
}
// This class represents the syncable::Directory's processes for requesting and
// processing updates from the sync server.
//
// Each instance of this class represents a particular type in the
// syncable::Directory. It can store and retreive that type's progress markers.
// It can also process a set of received SyncEntities and store their data.
class DirectoryUpdateHandler : public UpdateHandler {
public:
DirectoryUpdateHandler(syncable::Directory* dir,
ModelType type,
scoped_refptr<ModelSafeWorker> worker,
DataTypeDebugInfoEmitter* debug_info_emitter);
~DirectoryUpdateHandler() override;
// UpdateHandler implementation.
bool IsInitialSyncEnded() const override;
void GetDownloadProgress(
sync_pb::DataTypeProgressMarker* progress_marker) const override;
void GetDataTypeContext(sync_pb::DataTypeContext* context) const override;
SyncerError ProcessGetUpdatesResponse(
const sync_pb::DataTypeProgressMarker& progress_marker,
const sync_pb::DataTypeContext& mutated_context,
const SyncEntityList& applicable_updates,
StatusController* status) override;
void ApplyUpdates(StatusController* status) override;
void PassiveApplyUpdates(StatusController* status) override;
private:
friend class DirectoryUpdateHandlerApplyUpdateTest;
friend class DirectoryUpdateHandlerProcessUpdateTest;
// Sometimes there is nothing to do, so we can return without doing anything.
bool IsApplyUpdatesRequired();
// Called at the end of ApplyUpdates and PassiveApplyUpdates and performs
// steps common to both (even when IsApplyUpdatesRequired has returned
// false).
void PostApplyUpdates();
// Processes the given SyncEntities and stores their data in the directory.
// Their types must match this update handler's type.
void UpdateSyncEntities(syncable::ModelNeutralWriteTransaction* trans,
const SyncEntityList& applicable_updates,
bool is_initial_sync,
StatusController* status);
// Expires entries according to GC directives.
void ExpireEntriesIfNeeded(
syncable::ModelNeutralWriteTransaction* trans,
const sync_pb::DataTypeProgressMarker& progress_marker);
// Stores the given progress marker in the directory.
// Its type must match this update handler's type.
void UpdateProgressMarker(
const sync_pb::DataTypeProgressMarker& progress_marker);
bool IsValidProgressMarker(
const sync_pb::DataTypeProgressMarker& progress_marker) const;
// Skips all checks and goes straight to applying the updates.
SyncerError ApplyUpdatesImpl(StatusController* status);
// Creates root node for the handled model type.
void CreateTypeRoot(syncable::ModelNeutralWriteTransaction* trans);
syncable::Directory* dir_;
ModelType type_;
scoped_refptr<ModelSafeWorker> worker_;
DataTypeDebugInfoEmitter* debug_info_emitter_;
// The version which directory already ran garbage collection against on.
int64_t cached_gc_directive_version_;
// The day which directory already ran garbage collection against on.
base::Time cached_gc_directive_aged_out_day_;
DISALLOW_COPY_AND_ASSIGN(DirectoryUpdateHandler);
};
} // namespace syncer
#endif // COMPONENTS_SYNC_ENGINE_IMPL_DIRECTORY_UPDATE_HANDLER_H_
| endlessm/chromium-browser | components/sync/engine_impl/directory_update_handler.h | C | bsd-3-clause | 4,172 |
<!DOCTYPE html>
<html class="google mmfb" itemscope itemtype="http://schema.org/WebPage" lang="de">
<head>
<meta charset="utf-8">
<script>
(function(H){H.className=H.className.replace(/\bgoogle\b/,'google-js')})(document.documentElement)
</script>
<meta content="initial-scale=1, minimum-scale=1, width=device-width" name="viewport">
<meta content=
"Google Enterprise Search helps employees and customers find what they need, fast. Get more out of your intranet and extranet."
name="description">
<title>
Solutions - Google Enterprise Search
</title>
<link href=
"https://fonts.googleapis.com/css?family=Roboto:500,400italic,700italic,300,100,700,500italic,400%7CMaterial+Icons+Extended%7COpen+Sans:300,400,600,700%7CProduct+Sans:400&lang=de"
rel="stylesheet">
<link href="/search/css/search.min.css" rel="stylesheet">
<style>
.m-icon,.m-icon-pseudo:after{font-family:'Material Icons Extended';text-rendering:optimizeLegibility;font-feature-settings:"liga" 1;-webkit-font-feature-settings:"liga" 1;-moz-font-feature-settings:"liga" 1;-ms-font-feature-settings:"liga" 1;-o-font-feature-settings:"liga" 1;font-style:normal;text-transform:none;line-height:1;font-size:24px}
</style>
<link href="https://www.google.com/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="https://enterprise.google.com/intl/de/search/solutions/" rel="canonical">
<meta content="NOODP,NOYDIR" name="robots">
<link href="https://plus.google.com/+googlecloud" rel="publisher">
<meta content="Solutions - Google Enterprise Search" property="og:title">
<meta content="website" property="og:type">
<meta content="enterprise.google.com/intl/de/search/solutions/" property="og:url">
<meta content="https://enterprise.google.com/images/logo/google-for-work-social-icon.png"
property="og:image">
<meta content=
"Google Enterprise Search helps employees and customers find what they need, fast. Get more out of your intranet and extranet."
property="og:description">
<meta content="summary" name="twitter:card">
<meta content="https://twitter.com/googlecloud" name="twitter:url">
<meta content="Solutions - Google Enterprise Search" name="twitter:title">
<meta content="https://enterprise.google.com/images/logo/google-for-work-social-icon.png" name=
"twitter:image">
<meta content=
"Google Enterprise Search helps employees and customers find what they need, fast. Get more out of your intranet and extranet."
name="twitter:description">
<meta content="@GoogleCloud" name="twitter:creator">
<meta content="Solutions - Google Enterprise Search" itemprop="name">
<meta content=
"Google Enterprise Search helps employees and customers find what they need, fast. Get more out of your intranet and extranet."
itemprop="description">
<meta content="https://enterprise.google.com/images/logo/google-for-work-social-icon.png"
itemprop="image">
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Product",
"brand": "Google Inc.",
"name": "Solutions - Google Enterprise Search",
"description": "Google Enterprise Search helps employees and customers find what they need, fast. Get more out of your intranet and extranet.",
"url": "https://enterprise.google.com/intl/de/search/solutions/",
"logo": "https://enterprise.google.com/images/logo/google-for-work-social-icon.png",
"sameAs": [
"https://twitter.com/googlecloud",
"https://plus.google.com/+googlecloud",
"https://cloud.googleblog.com/",
"https://www.youtube.com/c/googlecloud"
]
}
</script>
</head>
<body class="page-solutions">
<div class="maia-header" id="maia-header" role="banner">
<div class="maia-aux">
<h1>
<a href="../../search/"><img alt="Google" src=
"//www.google.com/images/branding/googlelogo/1x/googlelogo_color_116x41dp.png" srcset=
"//www.google.com/images/branding/googlelogo/2x/googlelogo_color_116x41dp.png 2x"> Enterprise
Search</a>
</h1><a class="maia-teleport" href="#content">Weiter zum Inhalt</a>
<div class="maia-util">
<div class="search header-search">
<form class="maia-search" id="global-search-form" name="global-search-form">
<input autocomplete="off" id="global-search-term" name="q" placeholder=
"Auf dieser Website suchen" type="text">
<div id="global-search-suggest"></div><button class="maia-button" id=
"global-search-submit" onclick="return false;"><span class=
"maia-search-icon">Suche</span></button>
</form>
</div>
</div>
</div>
</div>
<div class="maia-nav" id="maia-nav-x" role="navigation">
<div class="maia-aux">
<ul>
<li>
<a data-g-action="Global Nav" data-g-event="Search: Solutions" data-g-label="Home"
href="../../search/">Startseite</a>
</li>
<li class="active">
<a class="active" data-g-action="Global Nav" data-g-event="Search: Solutions"
data-g-label="Solutions" href="../../search/solutions/">Lösungen</a>
</li>
<li>
<a data-g-action="Global Nav" data-g-event="Search: Solutions" data-g-label="Products"
href="../../search/products/">Produkte</a>
</li>
<li>
<a data-g-action="Global Nav" data-g-event="Search: Solutions" data-g-label="Customers"
href="../../search/customers/">Kunden</a>
</li>
<li>
<a data-g-action="Global Nav" data-g-event="Search: Solutions" data-g-label="Partners"
href="../../search/partners/">Partner</a>
</li>
<li>
<a data-g-action="Global Nav" data-g-event="Search: Solutions" data-g-label="Support"
href="../../search/support/">Support</a>
</li>
</ul>
</div>
</div><noscript>
<div id="warning-jsdisabled">
<p>
In Ihrem Browser ist JavaScript zurzeit nicht aktiviert. Wir empfehlen Ihnen, entweder eine
neuere Browserversion herunterzuladen oder Ihre Browsereinstellungen so zu ändern, dass der
gesamte Inhalt dieser Seite dargestellt werden kann.
</p>
<p>
<a href="https://www.google.com/support/bin/answer.py?answer=23852">Erfahren Sie, wie Sie
JavaScript in Ihrem Browser aktivieren.</a>
</p>
</div>
<style>
.google #warning-jsdisabled {background-color: #fffbcc; padding: 10px;}
.google #warning-jsdisabled p {margin: 0;}
.google #home-hero h1 {margin: 0;}
</style></noscript>
<div class="max-width centered" id="global-search-results"></div>
<div id="maia-main" role="main">
<div class="maia-teleport" id="content"></div>
<div class="search-bar-container">
<div class="search-bar">
<div class="search-term first" id="search-term"></div>
</div><img alt="" class="search-shadow" src="/search/images/solutions/search-shadow.png">
<div class="scroll-indicator">
<span class="scroll-text">Scrollen</span>
<div class="arrow"></div>
</div>
</div>
<div class="carousel-container">
<div class="carousel" id="carousel">
<div class="carousel-panel landing" data-name="landing" data-navcolor=""
data-search-term="Lösungen">
<div class="hero-text-container">
<h1 class="hero light">
Schnell das Gesuchte finden
</h1>
<p class="hero light">
Google Enterprise Search liefert hochrelevante Ergebnisse für Ihre Kunden und Ihre
Mitarbeiter – und zwar blitzschnell. Wir haben einige Beispiele
zusammengestellt, in denen Kunden und Mitarbeiter unverzüglich fündig wurden.
</p>
</div>
</div>
<div class="carousel-panel intranet" data-name="Intranet" data-navcolor="light"
data-search-term="altersvorsorge">
<div class="hero-text-container">
<h1 class="hero light">
Mehr Nutzen aus dem Intranet ziehen
</h1>
<p class="hero light">
Geben Sie Ihren Mitarbeitern leistungsfähige Tools an die Hand, mit denen sie nach
Personen, Daten und Dokumenten suchen können. Dies funktioniert von der
Personalabteilung bis zur IT und weit darüber hinaus.
</p>
</div>
<div class="panel-dimmer light"></div>
</div>
<div class="carousel-panel extranet" data-name="Extranet" data-navcolor="light"
data-search-term="2012 schalldämpfer">
<div class="hero-text-container">
<h1 class="hero light">
Mehr Nutzen aus dem Extranet ziehen
</h1>
<p class="hero light">
Ihr Unternehmen entwickelt sich weiter und Geschäftsbeziehungen werden verbessert,
da Ihre Partner genau die Informationen finden, die sie benötigen.
</p>
</div>
<div class="panel-dimmer light"></div>
</div>
<div class="carousel-panel websites" data-name="Websites" data-navcolor="dark"
data-search-term="wie kann ich ...">
<div class="hero-text-container">
<h1 class="hero dark">
Optimieren Sie Ihre Website
</h1>
<p class="hero dark">
Sie steigern Ihren Traffic, wenn Sie Ihre öffentliche Website relevanter und
hilfreicher gestalten und die Navigation vereinfachen.
</p>
</div>
<div class="panel-dimmer dark"></div>
</div>
<div class="carousel-panel engineering-design-process" data-name=
"Produktentwickungsprozess" data-navcolor="light" data-search-term=
"silizium-wafer design-spezifikationen">
<div class="hero-text-container">
<h1 class="hero light">
Optimieren Sie Ihren Konstruktionsprozess
</h1>
<p class="hero light">
Techniker, Ingenieure und Wissenschaftler finden alle relevanten
Konstruktionsdokumente, Testergebnisse und Forschungsergebnisse – schnell und
sicher.
</p>
</div>
<div class="panel-dimmer light"></div>
</div>
<div class="carousel-panel customer-support" data-name="Kundensupport" data-navcolor=
"dark" data-search-term="4g beim roaming aktivieren">
<div class="hero-text-container">
<h1 class="hero dark">
Optimieren Sie Ihren Kundendienst
</h1>
<p class="hero dark">
Steigern Sie die Kundenzufriedenheit, indem Sie Kundendienstmitarbeitern einen
direkten Zugriff auf bekannte Probleme und Vorgänge ermöglichen.
</p>
</div>
<div class="panel-dimmer dark"></div>
</div>
<div class="carousel-panel procurement" data-name="Beschaffung" data-navcolor="light"
data-search-term="Auftrag Festplatten Nr. 38472">
<div class="hero-text-container">
<h1 class="hero light">
Organisieren Sie die Beschaffung
</h1>
<p class="hero light">
Rationalisieren Sie den Beschaffungsprozess mit leicht auffindbaren Informationen.
</p>
</div>
<div class="panel-dimmer light"></div>
</div>
</div>
<div class="nav-container">
<div class="carousel-nav"></div>
<div class="solutions-arrow hidden"></div>
</div>
</div>
<div class="solution-copy">
<div class="solutions-detail clearfix hidden" id="solution-intranet">
<h1>
Vorteile
</h1>
<div class="maia-col-4">
<h2>
Kompetenz der Mitarbeiter fördern
</h2>
<p>
Um kluge Entscheidungen zu treffen, benötigen Ihre Mitarbeiter akkurate, relevante
Informationen. Mit der Google Search Appliance finden sie schnell, was sie suchen,
und bleiben produktiv in ihrer Arbeit.
</p>
</div>
<div class="maia-col-4">
<h2>
Produktivität steigern
</h2>
<p>
Wer im Arbeitsalltag auf bestehende Daten zurückgreifen muss, verbringt oft viel Zeit
mit der Suche. Wichtige Informationen sollten Ihren Mitarbeitern unmittelbar zur
Verfügung stehen – ganz gleich, ob es sich um Unternehmensrichtlinien, Projektdaten
oder Präsentationen handelt. Dies ermöglicht rasches Handeln und schafft Raum für
Innovationen.
</p>
</div>
<div class="maia-col-4 clearfix">
<h2>
Alles finden – überall
</h2>
<p>
Die Google Search Appliance liest mehr als 220 Dateitypen, darunter Word, PowerPoint,
Excel und PDF. Sie können auf Informationen aus Datenbanken, Dateisystemen und
gängigen Repositorys wie SharePoint, Livelink, Lotus Notes, Filenet, Documentum usw.
zugreifen.
</p>
</div>
<div class="customer-story">
<h1>
Erfahrungsberichte anderer Kunden
</h1>
<div class="maia-col-4">
<div class="circle outer-circle circle-bg customer-logo">
<a data-g-action="" data-g-event="Search: Solutions" data-g-label=
"Intranet Solution: Societe Generale Case Study" href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_SocGen_2013_de.pdf"
target="_blank">
<div class="circle inner-circle customer-image intranet"></div></a>
</div>
</div>
<div class="customer-story-content">
<p class="casestudy-content">
Die Société Générale Group, einer der Top-Finanzdienstleister der Eurozone,
verfügte über mehr als 70 Intranets, die auf Lotus Notes basierten. Dank der Google
Search Appliance können die 120.000 Mitarbeiter inzwischen schnell und bequem auf
alle relevanten Informationen aus jedem dieser Netzwerke zugreifen. In weniger als
zwei Monaten war das System komplett eingerichtet und der gesamte Datenbestand
vollständig indexiert, sodass mittlerweile über 400.000 Dokumente jederzeit für
alle autorisierten Nutzer verfügbar sind.
</p><br>
<a class="case-study-link link gray" data-g-action="Download" data-g-event=
"Search: Solutions" data-g-label="solution.data_g_label" event="autotrack-data-g"
href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_SocGen_2013_de.pdf"
target="_blank">Hier finden Sie die Fallstudie.</a>
</div><br class="clearfix">
</div>
</div>
<div class="solutions-detail clearfix hidden" id="solution-extranet">
<h1>
Vorteile
</h1>
<div class="maia-col-4">
<h2>
Supportkosten reduzieren
</h2>
<p>
Mit der Google Search Appliance in Ihrem Support-Portal können Ihre Partner relevante
Informationen finden, ohne damit Arbeitskraft zu binden.
</p>
</div>
<div class="maia-col-4">
<h2>
Vorhandenes Wissen optimal nutzen
</h2>
<p>
Erleichtern Sie die Suche in Ihrem Extranet und ermöglichen Sie Ihren Partnern einen
schnellen Zugriff auf entscheidende geschäftliche Informationen – damit Sie Ihre
gemeinsamen Ziele optimal erreichen.
</p>
</div>
<div class="maia-col-4 clearfix">
<h2>
Zugriffsberechtigungen bleiben erhalten
</h2>
<p>
Die Google Search Appliance beachtet alle Ihre Sicherheitsrichtlinien. Nutzer finden
nur solche Inhalte, auf die sie tatsächlich zugreifen dürfen.
</p>
</div>
</div>
<div class="solutions-detail clearfix hidden" id="solution-websites">
<h1>
Vorteile
</h1>
<div class="maia-col-4">
<h2>
Interesse an Ihrer Website steigern
</h2>
<p>
Mit Google Site Search und der Google Search Appliance finden Besucher Ihrer
Unternehmens-Website genau die Informationen, die sie benötigen. Kein Wunder, denn
dahinter steht die Fachkompetenz von Google im Bereich der Suche.
</p>
</div>
<div class="maia-col-4">
<h2>
Suchergebnissen Relevanz verleihen
</h2>
<p>
Die Google Search Appliance liefert Suchergebnisse höchster Relevanz. Mit Funktionen
wie der Kategoriefilterung und der Dokumentvorschau finden sich die Nutzer
problemlos in den Suchergebnissen zurecht.
</p>
</div>
<div class="maia-col-4 clearfix">
<h2>
Kundendienst verbessern
</h2>
<p>
Mit der Google Search Appliance helfen Sie Ihren Kunden, Probleme schnell zu lösen,
denn in diesem Suchportal können Nutzer alle Informationen eigenständig finden.
</p>
</div>
<div class="customer-story">
<h1>
Erfahrungsberichte anderer Kunden
</h1>
<div class="maia-col-4">
<div class="circle outer-circle circle-bg customer-logo">
<a data-g-action="" data-g-event="Search: Solutions" data-g-label=
"Websites Solution: City Of Calgary Case Study" href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_calgary_2013_de.pdf"
target="_blank">
<div class="circle inner-circle customer-image websites"></div></a>
</div>
</div>
<div class="customer-story-content">
<p class="casestudy-content">
Die kanadische Stadt Calgary hat die Google Search Appliance eingesetzt, um
16.000 Seiten auf der offiziellen Website ihrer Kommune zu organisieren.
Dadurch wurde die Online-Kommunikation zwischen der Stadt und ihren Bürgern
optimiert, während gleichzeitig mehr Ressourcen freigesetzt wurden, um diffizile
Anfragen, falls notwendig, auch telefonisch oder persönlich zu besprechen. Vor
Einführung der Google Search Appliance wurde die Suchfunktion lediglich von
4 % der Website-Besucher genutzt. Mittlerweile sind es 65 % – ein enormer
Effizienzgewinn für die Stadt.
</p><br>
<a class="case-study-link link gray" data-g-action="Download" data-g-event=
"Search: Solutions" data-g-label="solution.data_g_label" event="autotrack-data-g"
href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_calgary_2013_de.pdf"
target="_blank">Hier finden Sie die Fallstudie.</a>
</div><br class="clearfix">
</div>
</div>
<div class="solutions-detail clearfix hidden" id="solution-engineering design process">
<h1>
Vorteile
</h1>
<div class="maia-col-4">
<h2>
Innovationen beschleunigen
</h2>
<p>
Ingenieure und Forscher verbringen mit unserer Lösung weniger Zeit mit der Suche nach
existierenden Informationen. Dadurch können sie sich voll und ganz auf die
Entwicklung neuer Ideen konzentrieren, um Ihr Unternehmen weiterzubringen.
</p>
</div>
<div class="maia-col-4">
<h2>
Produktinformationen schnell finden
</h2>
<p>
Die Google Search Appliance crawlt und indexiert Dokumentbibliotheken, Datenbanken,
gemeinsame Dateien und Systeme für das Product Lifecycle Management (PLM).
Entscheidende technische Daten werden sicher bereitgestellt.
</p>
</div>
<div class="maia-col-4 clearfix">
<h2>
Unterlagen und Datenbanken sicher durchsuchen
</h2>
<p>
Die Suche wahrt alle bestehenden Zugriffsberechtigungen. Nur Mitarbeiter mit der
entsprechenden Zugriffsberechtigung können sensible oder vertrauliche Daten einsehen.
</p>
</div>
<div class="customer-story">
<h1>
Erfahrungsberichte anderer Kunden
</h1>
<div class="maia-col-4">
<div class="circle outer-circle circle-bg customer-logo">
<a data-g-action="" data-g-event="Search: Solutions" data-g-label=
"Engineering Design Process Solution: Honeywell Case Study" href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_HoneywellTrans_2013_de.pdf"
target="_blank">
<div class="circle inner-circle customer-image engineering-design-process">
</div></a>
</div>
</div>
<div class="customer-story-content">
<p class="casestudy-content">
Die Techniker von Honeywell Transportation verschwendeten bis zu 20 % ihrer
Arbeitszeit mit der Suche nach Informationen im Produktdaten-Managementsystem des
Unternehmens. Es war äußerst schwierig, Konstruktionszeichnungen, technische Daten
und andere wichtige Dokumente zu finden. Die Google Search Appliance hat diesen
Zeitaufwand um ca. 50 % reduziert. So konnten 5 bis 10 % der täglichen
Arbeitszeit eines Technikers freigesetzt, die Kosten für die Testphasen reduziert
und die Entwicklungsphasen verkürzt werden.
</p><br>
<a class="case-study-link link gray" data-g-action="Download" data-g-event=
"Search: Solutions" data-g-label="solution.data_g_label" event="autotrack-data-g"
href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_HoneywellTrans_2013_de.pdf"
target="_blank">Hier finden Sie die Fallstudie.</a>
</div><br class="clearfix">
</div>
</div>
<div class="solutions-detail clearfix hidden" id="solution-customer support">
<h1>
Vorteile
</h1>
<div class="maia-col-4">
<h2>
Schulungskosten reduzieren
</h2>
<p>
Ihre Kundendienstmitarbeiter arbeiten mit der vertrauten Oberfläche der Google-Suche.
Das bedeutet: Sie sparen Kosten für die Schulung. Mit der Google Search Appliance
können Sie die Schulungskosten pro Kundendienstmitarbeiter um bis zu 25 %
senken.
</p>
</div>
<div class="maia-col-4">
<h2>
Mehr Probleme beim ersten Anruf lösen
</h2>
<p>
Mit der Google Search Appliance finden Ihre Kundendienstmitarbeiter genau die
Informationen, die sie benötigen. So können sie Anrufern zügig die passende Lösung
für ihre Probleme liefern.
</p>
</div>
<div class="maia-col-4 clearfix">
<h2>
Produktivität der Kundendienstmitarbeiter steigern
</h2>
<p>
Kundendienstmitarbeiter, die weniger Zeit für die Suche nach den richtigen
Informationen aufwenden müssen, können sich besser auf den Kunden konzentrieren. Die
Google Search Appliance reduziert die durchschnittliche Gesprächszeit um bis zu
20 Prozent.
</p>
</div>
<div class="customer-story">
<h1>
Erfahrungsberichte anderer Kunden
</h1>
<div class="maia-col-4">
<div class="circle outer-circle circle-bg customer-logo">
<a data-g-action="" data-g-event="Search: Solutions" data-g-label=
"Customer Support Solution: QAD Case Study" href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_QAD_2013_de.pdf"
target="_blank">
<div class="circle inner-circle customer-image customer-support"></div></a>
</div>
</div>
<div class="customer-story-content">
<p class="casestudy-content">
Als Software-Unternehmen war es für QAD unerlässlich, den Kundendienst auf allen
Kontaktebenen zu verbessern. Alle wichtigen Supportdokumente sollten schnell und
problemlos über das Internet, das Intranet und das Extranet für Kunden abrufbar
sein, während vertrauliche Informationen gleichzeitig geschützt bleiben mussten.
Zudem sollte die Umsetzung in mehreren Sprachen erfolgen. Dank der Google Search
Appliance profitieren die Nutzer bei QAD mittlerweile von einem sicheren Zugriff
auf alle relevanten Inhalte.
</p><br>
<a class="case-study-link link gray" data-g-action="Download" data-g-event=
"Search: Solutions" data-g-label="solution.data_g_label" event="autotrack-data-g"
href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_QAD_2013_de.pdf"
target="_blank">Hier finden Sie die Fallstudie.</a>
</div><br class="clearfix">
</div>
</div>
<div class="solutions-detail clearfix hidden" id="solution-procurement">
<h1>
Vorteile
</h1>
<div class="maia-col-4">
<h2>
Entscheidende Informationen schnell finden
</h2>
<p>
Mit der Google Search Appliance steht jede Rechnung, jeder Auftrag, Frachtbrief und
Vertrag sicher auf Ihrem Bildschirm zur Verfügung.
</p>
</div>
<div class="maia-col-4">
<h2>
Beschaffungskosten senken
</h2>
<p>
Durch den mühelosen Zugang zu präzisen Daten können die Mitarbeiter in der
Beschaffung schneller Aufträge bearbeiten, Lieferungen abgleichen und Rechnungen
prüfen. Durch die Optimierung Ihrer Geschäftsprozesse reduzieren Sie die Kosten im
Beschaffungswesen.
</p>
</div>
<div class="maia-col-4 clearfix">
<h2>
Informationen in ERP-Systemen finden
</h2>
<p>
Mit der Google Search Appliance finden Ihre Mitarbeiter Informationen wie
Auftragsnummern oder Lieferantendaten in großen ERP-Systemen genauso leicht, als wenn
sie mit Google.com das Internet durchsuchen.
</p>
</div>
<div class="customer-story">
<h1>
Erfahrungsberichte anderer Kunden
</h1>
<div class="maia-col-4">
<div class="circle outer-circle circle-bg customer-logo">
<a data-g-action="" data-g-event="Search: Solutions" data-g-label=
"Procurement Solution: Honeywell Case Study" href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_HoneywellAero_2013_de.pdf"
target="_blank">
<div class="circle inner-circle customer-image procurement"></div></a>
</div>
</div>
<div class="customer-story-content">
<p class="casestudy-content">
Wöchentlich greifen 14.000 Mitarbeiter von Honeywell Aerospace auf ihr SAP ECC zu.
Besonders für diejenigen Mitarbeiter, die nur wenig Erfahrung mit dem System
hatten, waren häufig 12 bis 14 Klicks erforderlich – verbunden mit einem
Zeitaufwand von ca. 15 Minuten – um eine Rechnung oder einen Auftrag im Intranet zu
finden. Nach der Umstellung auf die Google Search Appliance hat sich die Situation
deutlich verbessert: Inzwischen dauert es weniger als 30 Sekunden, wichtige
Dokumente ausfindig zu machen, was einer Zeitersparnis von 3.500 Stunden pro Woche
entspricht. Gegenwärtig sind 5 Millionen SAP-Objekte bei Honeywell
Transportation indexiert, und die Einarbeitung weiterer 30 Mio. Dokumente für
andere Datenbanken und Repositories ist bereits in Planung.
</p><br>
<a class="case-study-link link gray" data-g-action="Download" data-g-event=
"Search: Solutions" data-g-label="solution.data_g_label" event="autotrack-data-g"
href=
"https://static.googleusercontent.com/media/www.google.com/en/us/work/search/files/gsa_case_study_HoneywellAero_2013_de.pdf"
target="_blank">Hier finden Sie die Fallstudie.</a>
</div><br class="clearfix">
</div>
</div>
</div>
<div class="hidden" data-section-label="Resources" id="feeds">
<div class="maia-col-12">
<h2>
Ressourcen
</h2>
<ul>
<li>
<em>Datenblatt der Google Search Appliance</em>
<div class="content">
Hier finden Sie eine vollständige Liste mit den Funktionen und Vorteilen der Google
Search Appliance 7.2.
</div><a class="download-link-white" data-g-action="Download" data-g-event=
"Search: Products" data-g-label="Search Appliance: Google Search Appliance Datasheet"
href=
"//docs.google.com/a/google.com/viewer?url=https://www.google.com/intl/de/work/search/files/btd_gsa_datasheet-7.2.pdf"
target="_blank">Herunterladen</a>
</li>
<li class="last">
<em>Maximierung der Informationsrendite</em>
<div class="content">
Erfahren Sie, wie Ihnen die Technologie von Google Enterprise Search dabei
helfen kann, Ihre Informationsrendite zu maximieren.
</div><a class="download-link-white" data-g-action="Download" data-g-event=
"Search: Products" data-g-label="Search Appliance: Maximizing Return on Information"
href=
"//docs.google.com/a/google.com/viewer?url=https://www.google.com/intl/de/work/search/files/Internal_Search_ROI.pdf"
target="_blank">Herunterladen</a>
</li>
</ul>
</div>
</div>
</div>
<div id="maia-signature"></div>
<div class="maia-footer" id="maia-footer">
<div id="maia-footer-local">
<div class="maia-aux">
<div class="ent-footer-top"></div>
<div class="ent-footer-links">
<div class="ent-footer-unit">
<h4>
Lösungen
</h4>
<ul>
<li>
<a href="../../search/solutions/index.html">Lösungen entdecken</a>
</li>
</ul>
</div>
<div class="ent-footer-unit">
<h4>
Produkte
</h4>
<ul>
<li>
<a href="../../search/products/gsa.html">Google Search Appliance</a>
</li>
<li>
<a href="../../search/products/gss.html">Google Site Search</a>
</li>
</ul>
</div>
<div class="ent-footer-unit third">
<h4>
Kunden
</h4>
<ul>
<li>
<a href="../../search/customers/">Unsere Kunden</a>
</li>
</ul>
</div>
<div class="ent-footer-unit last">
<h4>
Partner
</h4>
<ul>
<li>
<a href="../../search/partners/">Unsere Partner</a>
</li>
</ul>
</div>
<div class="ent-footer-unit last">
<h4>
Support
</h4>
<ul>
<li>
<a href="../../search/support/">Support kontaktieren</a>
</li>
</ul>
</div>
</div><br class="clear">
</div>
</div>
<div id="maia-footer-global">
<div class="maia-aux">
<div class="maia-locales">
<label><span>Sprache oder Region ändern:</span><select onchange=
"var href=this[this.selectedIndex].value;if(href!=''){window.location.href=href};">
<option value="/intl/id/search/solutions/">
Bahasa Indonesia
</option>
<option value="/intl/cs/search/solutions/">
Čeština
</option>
<option value="/intl/da/search/solutions/">
Dansk
</option>
<option selected value="/intl/de/search/solutions/">
Deutsch
</option>
<option value="/intl/en/search/solutions/">
English
</option>
<option value="/intl/en_au/search/solutions/">
English – Australia
</option>
<option value="/intl/en_gh/search/solutions/">
English – Ghana
</option>
<option value="/intl/en_hk/search/solutions/">
English – Hong Kong
</option>
<option value="/intl/en_in/search/solutions/">
English – India
</option>
<option value="/intl/en_ie/search/solutions/">
English – Ireland
</option>
<option value="/intl/en_ke/search/solutions/">
English – Kenya
</option>
<option value="/intl/en_nz/search/solutions/">
English – New Zealand
</option>
<option value="/intl/en_ng/search/solutions/">
English – Nigeria
</option>
<option value="/intl/en_ph/search/solutions/">
English – Philippines
</option>
<option value="/intl/en_sg/search/solutions/">
English – Singapore
</option>
<option value="/intl/en_za/search/solutions/">
English – South Africa
</option>
<option value="/intl/en_uk/search/solutions/">
English – United Kingdom
</option>
<option value="/intl/es/search/solutions/">
Español
</option>
<option value="/intl/es-419/search/solutions/">
Español (Latinoamérica)
</option>
<option value="/intl/fr/search/solutions/">
Français
</option>
<option value="/intl/it/search/solutions/">
Italiano
</option>
<option value="/intl/hu/search/solutions/">
Magyar
</option>
<option value="/intl/nl/search/solutions/">
Nederlands
</option>
<option value="/intl/no/search/solutions/">
Norsk
</option>
<option value="/intl/pl/search/solutions/">
Polski
</option>
<option value="/intl/pt-BR/search/solutions/">
Português (Brasil)
</option>
<option value="/intl/pt-PT/search/solutions/">
Português (Portugal)
</option>
<option value="/intl/fi/search/solutions/">
Suomi
</option>
<option value="/intl/sv/search/solutions/">
Svenska
</option>
<option value="/intl/vi/search/solutions/">
Tiếng Việt
</option>
<option value="/intl/tr/search/solutions/">
Türkçe
</option>
<option value="/intl/ru/search/solutions/">
Русский
</option>
<option value="/intl/uk/search/solutions/">
Українська
</option>
<option value="/intl/iw/search/solutions/">
עברית
</option>
<option value="/intl/ar/search/solutions/">
العربية
</option>
<option value="/intl/th/search/solutions/">
ไทย
</option>
<option value="/intl/ko/search/solutions/">
한국어
</option>
<option value="/intl/zh-CN/search/solutions/">
中文(简体中文)
</option>
<option value="/intl/zh-TW/search/solutions/">
中文(繁體中文)
</option>
<option value="/intl/ja/search/solutions/">
日本語
</option>
</select></label>
</div>
<ul>
<li>
<a href="//www.google.com/">Google</a>
</li>
<li>
<a href="//www.google.com/intl/de/about/">Über Google</a>
</li>
<li>
<a href="//www.google.com/intl/de/policies/privacy/">Datenschutzerklärung</a>
</li>
<li>
<a href="//www.google.com/intl/de/policies/terms/">Nutzungsbedingungen</a>
</li>
</ul>
</div>
</div>
</div>
<script src="/search/js/enterprise.search.min.js">
</script>
<script>
new enterprise.search.SolutionsPage();
</script>
<script>
var cookiepathValue = function (){
var pna = location.pathname.split('/');
var cp = '/';
if(pna.length > 2) {
cp='/' + pna[1] + '/';
}
return cp;
};
var uaRef = function(){
var dr = document.referrer;
//internal paths
var internalPaths = /\/(enterprise|work|edu|a\/signup)\//;
//referrer path
var refPathMatch = dr.match(/\..+?\/([^\?#]*)/);
var refPath = refPathMatch && refPathMatch.length>1?'/'+refPathMatch[1]: '';
//referrer host
var refHostMatch = dr.match(/\/\/(.+?)\//);
var refHost = refHostMatch && refHostMatch.length>1?refHostMatch[1]: '';
var newRef = '';
if(!(refPath.match(internalPaths) && refHost.match(/\.google(?:goro)?\./))){
newRef = dr.split('?')[0]
}
return newRef;
};
dataLayer = [{
'uaReferrer':uaRef(),
'country': 'de',
'region': 'emea',
'language': 'de',
'host': location.host,
'hostNoSub': location.host.replace(/^(.+\.)google/g, "google"),
'path': location.pathname,
'cookiePath': cookiepathValue(),
'cookiePathCopy': ['/work/apps/business/', 'intl'],
'file': 'index.html',
'fileNoSuffix': 'index'
}];
</script> <noscript><iframe class="inactive" height="0" src=
"//www.googletagmanager.com/ns.html?id=GTM-Q4J6" width="0"></iframe></noscript>
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-Q4J6');
</script>
<div class="cs-dialog-hidden" id="cs-dialog-content">
<form action="https://lp.google-mkto.com/index.php/leadCapture/save" class="form" enctype=
"application/x-www-form-urlencoded" id="mktForm_1441" method="post" name="mktForm_1441">
<input id="00N60000001fchv" name="OSO_Test_Tracking__c" type="hidden" value="">
<input name="lpId" type="hidden" value="18497"> <input name="subId" type="hidden" value=
"95"> <input name="munchkinId" type="hidden" value="248-TPC-286"> <input name="kw" type=
"hidden" value=""> <input name="cr" type="hidden" value=""> <input name="searchstr" type=
"hidden" value=""> <input name="lpurl" type="hidden" value=
"https://lp.google-mkto.com/GLOBALEnterpriseSearchAllContactSalesForm_ContactSalesLP.html?cr={creative}&kw={keyword}">
<input name="formid" type="hidden" value="1441"> <input name="returnURL" type="hidden"
value="https://www.google.com/edu/products/productivity-tools/"> <input name="retURL" type=
"hidden" value="https://www.google.com/edu/products/productivity-tools/"> <input name=
"returnLPId" type="hidden" value="-1"> <input name="Primary_Product_Family__c" type=
"hidden" value="Search"> <input name="Sync_to_Marketo__c" type="hidden" value="True">
<input id="LeadSource" name="LeadSource" type='hidden' value="Website"> <input id=
"Lead_Source_Descr__c" name="Lead_Source_Descr__c" type='hidden' value=
"Website: Contact Sales - Enterprise - Search"> <input id=
"Most_Recent_Lead_Source_Description__c" name="Most_Recent_Lead_Source_Description__c"
type='hidden' value="Website: Contact Sales - Enterprise - Search"> <input id=
"utm_source__c" name="utm_source__c" type="hidden" value=""> <input id="utm_campaign__c"
name="utm_campaign__c" type="hidden" value=""> <input id="utm_medium" name="utm_medium"
type="hidden" value=""> <input id="utm_term" name="utm_term" type="hidden" value="">
<input id="retURL" name="retURL" type="hidden" value=
"https://enterprise.google.com/search/">
<p class="error-msg">
Füllen Sie bitte die markierten Felder aus, um fortzufahren.
</p>
<div class="page-0">
<div class="item-group">
<div class="size-3">
<label for="FirstName" id="FirstName-label">Vorname</label> <input class=
"first-field" name="FirstName">
</div>
<div class="size-3">
<label for="LastName" id="LastName-label">Nachname</label> <input name="LastName">
</div>
<div class="size-3">
<label for="email" id="Email-label">E-Mail</label> <input id="email-address" name=
"Email">
<div id="email-error">
Ungültige E-Mail-Adresse
</div>
</div>
<div class="size-3 optional-field">
<label for="phone" id="Phone-label">Telefonnummer</label> <input class="phone-number"
name="Phone">
</div>
</div>
<div class="item-group">
<div class="size-3">
<label for="company" id="Company-label">Name des Unternehmens</label> <input name=
"Company">
</div>
<div class="size-2">
<label for="Number_of_Employees__c" id="Number_of_Employees__c-label">Anzahl der
Mitarbeiter</label><select name="Number_of_Employees__c">
<option value="">
Auswählen...
</option>
<option value="1">
1
</option>
<option value="2-9">
2–9
</option>
<option value="10-19">
10–19
</option>
<option value="20-49">
20–49
</option>
<option value="50-99">
50–99
</option>
<option value="100-199">
100–199
</option>
<option value="200-349">
200–349
</option>
<option value="350-999">
350–999
</option>
<option value="1000-2999">
1000–2999
</option>
<option value="3000+">
3000+
</option>
</select>
</div>
<div class="size-3">
<label for="Title" id="Title-label">Funktion</label><select name="Title">
<option selected value="">
Auswählen...
</option>
<option value="CEO, Business Owner, President">
Geschäftsführer, Geschäftsinhaber, Präsident
</option>
<option value="CTO">
Technischer Leiter (CTO)
</option>
<option value="CIO / VP of IT">
Vorstand/Direktor Informationstechnologie
</option>
<option value="IT Director">
Leiter der IT-Abteilung
</option>
<option value="IT Manager">
IT-Manager
</option>
<option value="Systems Administrator">
Systemadministrator
</option>
<option value="Consultant">
Berater
</option>
<option value="Office Manager">
Büroleiter
</option>
<option value="End User">
Endnutzer
</option>
<option value="Reseller">
Reseller
</option>
<option value="Other">
Andere
</option>
</select>
</div>
<div class="size-3">
<label for="Domain__c" id="Domain__c-label">Website</label> <input name="Domain__c">
</div>
<div class="size-3">
<label for="Country" id="Country-label">Land</label> <select class="country" name=
"Country">
<option value="AF">
Afghanistan
</option>
<option value="AL">
Albanien
</option>
<option value="AS">
Amerikanisch-Samoa
</option>
<option value="AD">
Andorra
</option>
<option value="AI">
Anguilla
</option>
<option value="AQ">
Antarktis
</option>
<option value="AG">
Antigua und Barbuda
</option>
<option value="AM">
Armenien
</option>
<option value="AR">
Argentinien
</option>
<option value="AW">
Aruba
</option>
<option value="AT">
Österreich
</option>
<option value="AU">
Australien
</option>
<option value="AZ">
Aserbaidschan
</option>
<option value="BS">
Bahamas
</option>
<option value="BH">
Bahrain
</option>
<option value="BD">
Bangladesch
</option>
<option value="BB">
Barbados
</option>
<option value="BY">
Belarus
</option>
<option value="BE">
Belgien
</option>
<option value="BZ">
Belize
</option>
<option value="BJ">
Benin
</option>
<option value="BM">
Bermuda
</option>
<option value="BT">
Bhutan
</option>
<option value="BO">
Bolivien
</option>
<option value="BA">
Bosnien und Herzegowina
</option>
<option value="BW">
Botsuana
</option>
<option value="BV">
Bouvetinsel
</option>
<option value="BR">
Brasilien
</option>
<option value="IO">
Britisches Territorium im Indischen Ozean
</option>
<option value="BN">
Brunei Darussalam
</option>
<option value="BG">
Bulgarien
</option>
<option value="BF">
Burkina Faso
</option>
<option value="BI">
Burundi
</option>
<option value="KH">
Kambodscha
</option>
<option value="CM">
Kamerun
</option>
<option value="CA">
Kanada
</option>
<option value="CV">
Kap Verde
</option>
<option value="KY">
Kaimaninseln
</option>
<option value="CF">
Zentralafrikanische Republik
</option>
<option value="TD">
Tschad
</option>
<option value="CL">
Chile
</option>
<option value="CN">
China
</option>
<option value="CX">
Weihnachtsinsel
</option>
<option value="CC">
Kokosinseln
</option>
<option value="CO">
Kolumbien
</option>
<option value="KM">
Komoren
</option>
<option value="CG">
Kongo-Brazzaville
</option>
<option value="CD">
Kongo-Kinshasa
</option>
<option value="CK">
Cookinseln
</option>
<option value="CR">
Costa Rica
</option>
<option value="CI">
Côte d’Ivoire
</option>
<option value="HR">
Kroatien
</option>
<option value="CY">
Zypern
</option>
<option value="DK">
Dänemark
</option>
<option value="DJ">
Dschibuti
</option>
<option value="DM">
Dominica
</option>
<option value="DO">
Dominikanische Republik
</option>
<option value="TL">
Osttimor
</option>
<option value="EC">
Ecuador
</option>
<option value="EG">
Ägypten
</option>
<option value="SV">
El Salvador
</option>
<option value="GQ">
Äquatorialguinea
</option>
<option value="ER">
Eritrea
</option>
<option value="EE">
Estland
</option>
<option value="ET">
Äthiopien
</option>
<option value="FK">
Falklandinseln
</option>
<option value="FO">
Färöer
</option>
<option value="FJ">
Fidschi
</option>
<option value="FI">
Finnland
</option>
<option value="FR">
Frankreich
</option>
<option value="GF">
Französisch-Guayana
</option>
<option value="PF">
Französisch-Polynesien
</option>
<option value="TF">
Französische Süd- und Antarktisgebiete
</option>
<option value="GA">
Gabun
</option>
<option value="GM">
Gambia
</option>
<option value="GE">
Georgien
</option>
<option selected value="DE">
Deutschland
</option>
<option value="GH">
Ghana
</option>
<option value="GI">
Gibraltar
</option>
<option value="GR">
Griechenland
</option>
<option value="GL">
Grönland
</option>
<option value="GD">
Grenada
</option>
<option value="GP">
Guadeloupe
</option>
<option value="GU">
Guam
</option>
<option value="GT">
Guatemala
</option>
<option value="GN">
Guinea
</option>
<option value="GW">
Guinea-Bissau
</option>
<option value="GY">
Guyana
</option>
<option value="HT">
Haiti
</option>
<option value="HM">
Heard- und McDonald-Inseln
</option>
<option value="HN">
Honduras
</option>
<option value="HK">
Hongkong
</option>
<option value="HU">
Ungarn
</option>
<option value="IN">
Indien
</option>
<option value="ID">
Indonesien
</option>
<option value="IE">
Irland
</option>
<option value="IL">
Israel
</option>
<option value="IQ">
Irak
</option>
<option value="IS">
Island
</option>
<option value="IT">
Italien
</option>
<option value="JM">
Jamaika
</option>
<option value="JP">
Japan
</option>
<option value="JO">
Jordanien
</option>
<option value="KZ">
Kasachstan
</option>
<option value="KE">
Kenia
</option>
<option value="KI">
Kiribati
</option>
<option value="KW">
Kuwait
</option>
<option value="KG">
Kirgisistan
</option>
<option value="LA">
Laos
</option>
<option value="LV">
Lettland
</option>
<option value="LB">
Libanon
</option>
<option value="LS">
Lesotho
</option>
<option value="LR">
Liberia
</option>
<option value="LY">
Libyen
</option>
<option value="LI">
Liechtenstein
</option>
<option value="LT">
Litauen
</option>
<option value="LU">
Luxemburg
</option>
<option value="MO">
Macao
</option>
<option value="MK">
Mazedonien
</option>
<option value="MG">
Madagaskar
</option>
<option value="MW">
Malawi
</option>
<option value="MY">
Malaysia
</option>
<option value="MV">
Malediven
</option>
<option value="ML">
Mali
</option>
<option value="MT">
Malta
</option>
<option value="MH">
Marshallinseln
</option>
<option value="MQ">
Martinique
</option>
<option value="MR">
Mauretanien
</option>
<option value="MU">
Mauritius
</option>
<option value="YT">
Mayotte
</option>
<option value="MX">
Mexiko
</option>
<option value="FM">
Mikronesien
</option>
<option value="MD">
Republik Moldau
</option>
<option value="MC">
Monaco
</option>
<option value="MN">
Mongolei
</option>
<option value="MS">
Montserrat
</option>
<option value="MA">
Marokko
</option>
<option value="MZ">
Mosambik
</option>
<option value="NA">
Namibia
</option>
<option value="NR">
Nauru
</option>
<option value="NP">
Nepal
</option>
<option value="AN">
Niederländische Antillen
</option>
<option value="NL">
Niederlande
</option>
<option value="NC">
Neukaledonien
</option>
<option value="NZ">
Neuseeland
</option>
<option value="NI">
Nicaragua
</option>
<option value="NE">
Niger
</option>
<option value="NG">
Nigeria
</option>
<option value="NU">
Niue
</option>
<option value="NF">
Norfolkinsel
</option>
<option value="MP">
Nördliche Marianen
</option>
<option value="NO">
Norwegen
</option>
<option value="OM">
Oman
</option>
<option value="PK">
Pakistan
</option>
<option value="PW">
Palau
</option>
<option value="PS">
Palästina
</option>
<option value="PA">
Panama
</option>
<option value="PG">
Papua-Neuguinea
</option>
<option value="PY">
Paraguay
</option>
<option value="PE">
Peru
</option>
<option value="PH">
Philippinen
</option>
<option value="PN">
Pitcairninseln
</option>
<option value="PL">
Polen
</option>
<option value="PT">
Portugal
</option>
<option value="PR">
Puerto Rico
</option>
<option value="QA">
Katar
</option>
<option value="RE">
Réunion
</option>
<option value="RO">
Rumänien
</option>
<option value="RU">
Russische Föderation
</option>
<option value="RW">
Ruanda
</option>
<option value="KN">
St. Kitts und Nevis
</option>
<option value="LC">
St. Lucia
</option>
<option value="VC">
St. Vincent und die Grenadinen
</option>
<option value="WS">
Samoa
</option>
<option value="SM">
San Marino
</option>
<option value="ST">
São Tomé und Príncipe
</option>
<option value="SA">
Saudi-Arabien
</option>
<option value="SN">
Senegal
</option>
<option value="SC">
Seychellen
</option>
<option value="SL">
Sierra Leone
</option>
<option value="SG">
Singapur
</option>
<option value="SK">
Slowakei
</option>
<option value="SI">
Slowenien
</option>
<option value="SB">
Salomonen
</option>
<option value="SO">
Somalia
</option>
<option value="ZA">
Südafrika
</option>
<option value="GS">
Südgeorgien und die Südlichen Sandwichinseln
</option>
<option value="KR">
Republik Korea
</option>
<option value="ES">
Spanien
</option>
<option value="LK">
Sri Lanka
</option>
<option value="SH">
St. Helena
</option>
<option value="PM">
St. Pierre und Miquelon
</option>
<option value="SR">
Suriname
</option>
<option value="SJ">
Svalbard und Jan Mayen
</option>
<option value="SZ">
Swasiland
</option>
<option value="SE">
Schweden
</option>
<option value="CH">
Schweiz
</option>
<option value="TW">
Taiwan
</option>
<option value="TJ">
Tadschikistan
</option>
<option value="TZ">
Tansania
</option>
<option value="TH">
Thailand
</option>
<option value="TG">
Togo
</option>
<option value="TK">
Tokelau
</option>
<option value="TO">
Tonga
</option>
<option value="TT">
Trinidad und Tobago
</option>
<option value="TN">
Tunesien
</option>
<option value="TR">
Türkei
</option>
<option value="TM">
Turkmenistan
</option>
<option value="TC">
Turks- und Caicosinseln
</option>
<option value="TV">
Tuvalu
</option>
<option value="UG">
Uganda
</option>
<option value="UA">
Ukraine
</option>
<option value="AE">
Vereinigte Arabische Emirate
</option>
<option value="GB">
Vereinigtes Königreich
</option>
<option value="UM">
Amerikanisch-Ozeanien
</option>
<option value="UY">
Uruguay
</option>
<option value="UZ">
Usbekistan
</option>
<option value="VU">
Vanuatu
</option>
<option value="VA">
Vatikanstadt
</option>
<option value="VE">
Venezuela
</option>
<option value="VN">
Vietnam
</option>
<option value="VG">
Britische Jungferninseln
</option>
<option value="VI">
Amerikanische Jungferninseln
</option>
<option value="WF">
Wallis und Futuna
</option>
<option value="EH">
Westsahara
</option>
<option value="YE">
Jemen
</option>
<option value="ZM">
Sambia
</option>
<option value="ZW">
Simbabwe
</option>
</select>
</div>
<div class="size-3 optional-field">
<label>Anzahl der erforderlichen Suchanfragen</label><select>
<option selected value="">
Auswählen...
</option>
<option value="3 million queries">
drei Millionen Suchanfragen
</option>
<option value="5 million queries">
fünf Millionen Suchanfragen
</option>
<option value="10 million queries">
zehn Millionen Suchanfragen
</option>
<option value="more than 10 million queries">
mehr als zehn Millionen Suchanfragen
</option>
</select>
</div>
</div>
<div class="size-4 optional-field">
<label for="Additional_Information__c" id=
"Additional_Information__c-label"><span>Optional</span> Wie können wir Ihnen
helfen?</label>
<textarea class="optional" name="Additional_Information__c">
</textarea>
</div>
<div class="full">
<p id="comm-label">
Möchten Sie regelmäßig per E-Mail über Neuigkeiten, Produktupdates und Sonderangebote
von Google Cloud oder unseren Partnern informiert werden?
</p>
<div class="inline">
<div class="yes-radio">
<input class="comm-yes" id="comm-yes" name="HasOptedOutOfEmail" type="radio" value=
"FALSE"><label for="comm-yes">Ja</label>
</div>
<div class="no-radio">
<input class="comm-no" id="comm-no" name="HasOptedOutOfEmail" type="radio" value=
"TRUE"><label for="comm-no">Nein</label>
</div>
</div>
</div>
</div><input class="hidden-submit" data-g-action="Submit" data-g-event="Contact sales"
data-g-label="enterprise_google_com/intl/de_ALL/search/solutions/index.html" tabindex="-1"
type="submit" value="Senden">
</form>
</div>
<div class="cs-dialog-hidden" id="cs-dialog-title">
<div class="note">
<p>
Sie benötigen technischen Support? <a data-g-action="Technical support" data-g-event=
"Contact sales" data-g-label=
"enterprise_google_com/intl/de_ALL/search/solutions/index.html" href=
"http://support.google.com/enterprisehelp/go/support?hl=de">Besuchen Sie unsere
Hilfe.</a>
</p>
</div>
<h1 class="blue-section">
Kontaktformular
</h1>
</div>
<div class="cs-dialog-hidden" id="cs-dialog-nav">
<span class="main-actions"><a class=
"kd-button kd-button-submit submit-btn contact-sales-submission" data-g-action="Get in Touch"
data-g-event="Search:" data-g-label="Submit" href="javascript:void(0)">Senden</a> <a class=
"kd-button kd-button-submit continue-btn" data-g-action="Get in Touch" data-g-event="Search:"
data-g-label="Continue" href="javascript:void(0)">Weiter</a> <a class="kd-button cancel-btn"
data-g-action="Get in Touch" data-g-event="Search:" data-g-label="Cancel" href=
"javascript:void(0)">Abbrechen</a></span>
<p class="page-indicator">
<span class="main-actions"><span class="current-page">0</span> von <span class=
"page-count">0</span></span>
</p><span class="secondary-actions"><a class="kd-button back-btn" data-g-action=
"Get in Touch" data-g-event="" data-g-label="Back" href=
"javascript:void(0)">Zurück</a></span>
</div>
<script>
var config=new Object;
var unitedStates=[{value:"",name:"Select..."},{value:"AL",name:"Alabama"},{value:"AK",name:"Alaska"},{value:"AZ",name:"Arizona"},{value:"AR",name:"Arkansas"},{value:"CA",name:"California"},{value:"CO",name:"Colorado"},{value:"CT",name:"Connecticut"},{value:"DE",name:"Delaware"},{value:"DC",name:"District of Columbia"},{value:"FL",name:"Florida"},{value:"GA",name:"Georgia"},{value:"HI",name:"Hawaii"},{value:"ID",name:"Idaho"},{value:"IL",name:"Illinois"},{value:"IN",name:"Indiana"},{value:"IA",name:"Iowa"},
{value:"KS",name:"Kansas"},{value:"KY",name:"Kentucky"},{value:"LA",name:"Louisiana"},{value:"ME",name:"Maine"},{value:"MD",name:"Maryland"},{value:"MA",name:"Massachusetts"},{value:"MI",name:"Michigan"},{value:"MN",name:"Minnesota"},{value:"MS",name:"Mississippi"},{value:"MO",name:"Missouri"},{value:"MT",name:"Montana"},{value:"NE",name:"Nebraska"},{value:"NV",name:"Nevada"},{value:"NH",name:"New Hampshire"},{value:"NJ",name:"New Jersey"},{value:"NM",name:"New Mexico"},{value:"NY",name:"New York"},
{value:"NC",name:"North Carolina"},{value:"ND",name:"North Dakota"},{value:"OH",name:"Ohio"},{value:"OK",name:"Oklahoma"},{value:"OR",name:"Oregon"},{value:"PA",name:"Pennsylvania"},{value:"RI",name:"Rhode Island"},{value:"SC",name:"South Carolina"},{value:"SD",name:"South Dakota"},{value:"TN",name:"Tennessee"},{value:"TX",name:"Texas"},{value:"UT",name:"Utah"},{value:"VT",name:"Vermont"},{value:"VA",name:"Virginia"},{value:"WA",name:"Washington"},{value:"WV",name:"West Virginia"},{value:"WI",name:"Wisconsin"},
{value:"WY",name:"Wyoming"}];var canada=[{value:"",name:"Select..."},{value:"AB",name:"Alberta"},{value:"BC",name:"British Columbia"},{value:"MB",name:"Manitoba"},{value:"NB",name:"New Brunswick"},{value:"NF",name:"Newfoundland"},{value:"NT",name:"Northwest Territories"},{value:"NU",name:"Nunavut"},{value:"NS",name:"Nova Scotia"},{value:"ON",name:"Ontario"},{value:"PE",name:"Prince Edward Island"},{value:"QC",name:"Quebec"},{value:"SK",name:"Saskatchewan"},{value:"YT",name:"Yukon"}];
var australia=[{value:"",name:"Select..."},{value:"ACT",name:"Australian Capital Territory"},{value:"NSW",name:"New South Wales"},{value:"NT",name:"Northern Territory"},{value:"QLD",name:"Queensland"},{value:"SA",name:"South Australia"},{value:"TAS",name:"Tasmania"},{value:"VIC",name:"Victoria"},{value:"WA",name:"Western Australia"}];var newZealand=[{value:"",name:"Select..."},{value:"Northern Territory"},{value:"Auckland"},{value:"Christchurch"},{value:"Wellington"}];
var india=[{value:"",name:"Select..."},{value:"Andra Pradesh"},{value:"Arunachal Pradesh"},{value:"Assam"},{value:"Bihar"},{value:"Chhattisgarh"},{value:"Goa"},{value:"Gujarat"},{value:"Haryana"},{value:"Himachal Pradesh"},{value:"Mizoram"},{value:"Jammu & Kashmir"},{value:"Jharkhand"},{value:"Karnataka"},{value:"Kerala"},{value:"Madhya Pradesh"},{value:"Maharashtra"},{value:"Manipur"},{value:"Meghalaya"},{value:"Nagaland"},{value:"Orissa"},{value:"Punjab"},{value:"Rajasthan"},{value:"Sikkim"},{value:"Tamil Nadu"},
{value:"Tripura"},{value:"Uttar Pradesh"},{value:"Uttaranchal"},{value:"West Bengal"}];
var japan=[{value:"",name:"\u9078\u629e..."},{value:"\u5317\u6d77\u9053"},{value:"\u9752\u68ee\u770c"},{value:"\u5ca9\u624b\u770c"},{value:"\u5bae\u57ce\u770c"},{value:"\u79cb\u7530\u770c"},{value:"\u5c71\u5f62\u770c"},{value:"\u798f\u5cf6\u770c"},{value:"\u8328\u57ce\u770c"},{value:"\u6803\u6728\u770c"},{value:"\u7fa4\u99ac\u770c"},{value:"\u57fc\u7389\u770c"},{value:"\u5343\u8449\u770c"},{value:"\u6771\u4eac\u90fd"},{value:"\u795e\u5948\u5ddd\u770c"},{value:"\u5c71\u68a8\u770c"},{value:"\u65b0\u6f5f\u770c"},
{value:"\u5bcc\u5c71\u770c"},{value:"\u77f3\u5ddd\u770c"},{value:"\u798f\u4e95\u770c"},{value:"\u9577\u91ce\u770c"},{value:"\u5c90\u961c\u770c"},{value:"\u9759\u5ca1\u770c"},{value:"\u611b\u77e5\u770c"},{value:"\u4e09\u91cd\u770c"},{value:"\u6ecb\u8cc0\u770c"},{value:"\u4eac\u90fd\u5e9c"},{value:"\u5927\u962a\u5e9c"},{value:"\u5175\u5eab\u770c"},{value:"\u5948\u826f\u770c"},{value:"\u548c\u6b4c\u5c71\u770c"},{value:"\u9ce5\u53d6\u770c"},{value:"\u5cf6\u6839\u770c"},{value:"\u5ca1\u5c71\u770c"},{value:"\u5e83\u5cf6\u770c"},
{value:"\u5c71\u53e3\u770c"},{value:"\u5fb3\u5cf6\u770c"},{value:"\u9999\u5ddd\u770c"},{value:"\u611b\u5a9b\u770c"},{value:"\u9ad8\u77e5\u770c"},{value:"\u798f\u5ca1\u770c"},{value:"\u4f50\u8cc0\u770c"},{value:"\u9577\u5d0e\u770c"},{value:"\u718a\u672c\u770c"},{value:"\u5927\u5206\u770c"},{value:"\u5bae\u5d0e\u770c"},{value:"\u9e7f\u5150\u5cf6\u770c"},{value:"\u6c96\u7e04\u770c"}];config["pageCount"]=1;config["baseName"]="cs-dialog";config["completionIframePage"]="/intl/de_ALL/search/cs-dialog-thanks.html";
config["locationDetailsMap"]={"US":{stateList:unitedStates,zipCodeInput:true},"CA":{stateList:canada},"AU":{stateList:australia},"NZ":{stateList:newZealand},"IN":{stateList:india},"JP":{stateList:japan}};config["path"]="/search/";config["locale"]="de_ALL";config["countryCode"]="49";new enterprise.ContactForm(config);
enterprise.forms.Tracking.addTracking();
</script>
<script src="//www.google.com/js/maia.js">
</script>
<script>
window.___gcfg = {
lang: ''
};
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<script>
(function() {new enterprise.search.GlobalSiteSearch();})();
</script>
</body>
</html> | todor-dk/HTML-Renderer | Source/Testing/HtmlRenderer.ExperimentalApp/Data/Files/google trad/4E8E92473FAA94B19FF13700F511BD81.html | HTML | bsd-3-clause | 77,916 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/file_manager/fileapi_util.h"
#include <stddef.h>
#include <utility>
#include "base/bind.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "chrome/browser/chromeos/file_manager/app_id.h"
#include "chrome/browser/chromeos/file_manager/filesystem_api_util.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "extensions/browser/extension_util.h"
#include "extensions/common/extension.h"
#include "google_apis/drive/task_util.h"
#include "net/base/escape.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/isolated_context.h"
#include "storage/browser/file_system/open_file_system_mode.h"
#include "storage/common/file_system/file_system_util.h"
#include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h"
#include "ui/shell_dialogs/selected_file_info.h"
#include "url/gurl.h"
#include "url/origin.h"
using content::BrowserThread;
namespace file_manager {
namespace util {
using blink::mojom::FileChooserFileInfo;
using blink::mojom::FileSystemFileInfo;
using blink::mojom::NativeFileInfo;
namespace {
GURL ConvertRelativeFilePathToFileSystemUrl(const base::FilePath& relative_path,
const std::string& extension_id) {
GURL base_url = storage::GetFileSystemRootURI(
extensions::Extension::GetBaseURLFromExtensionId(extension_id),
storage::kFileSystemTypeExternal);
return GURL(base_url.spec() +
net::EscapeUrlEncodedData(relative_path.AsUTF8Unsafe(),
false)); // Space to %20 instead of +.
}
// Creates an ErrorDefinition with an error set to |error|.
EntryDefinition CreateEntryDefinitionWithError(base::File::Error error) {
EntryDefinition result;
result.error = error;
return result;
}
// Helper class for performing conversions from file definitions to entry
// definitions. It is possible to do it without a class, but the code would be
// crazy and super tricky.
//
// This class copies the input |file_definition_list|,
// so there is no need to worry about validity of passed |file_definition_list|
// reference. Also, it automatically deletes itself after converting finished,
// or if shutdown is invoked during ResolveURL(). Must be called on UI thread.
class FileDefinitionListConverter {
public:
FileDefinitionListConverter(Profile* profile,
const std::string& extension_id,
const FileDefinitionList& file_definition_list,
EntryDefinitionListCallback callback);
~FileDefinitionListConverter() = default;
private:
// Converts the element under the iterator to an entry. First, converts
// the virtual path to an URL, and calls OnResolvedURL(). In case of error
// calls OnIteratorConverted with an error entry definition.
void ConvertNextIterator(
std::unique_ptr<FileDefinitionListConverter> self_deleter,
FileDefinitionList::const_iterator iterator);
// Creates an entry definition from the URL as well as the file definition.
// Then, calls OnIteratorConverted with the created entry definition.
void OnResolvedURL(std::unique_ptr<FileDefinitionListConverter> self_deleter,
FileDefinitionList::const_iterator iterator,
base::File::Error error,
const storage::FileSystemInfo& info,
const base::FilePath& file_path,
storage::FileSystemContext::ResolvedEntryType type);
// Called when the iterator is converted. Adds the |entry_definition| to
// |results_| and calls ConvertNextIterator() for the next element.
void OnIteratorConverted(
std::unique_ptr<FileDefinitionListConverter> self_deleter,
FileDefinitionList::const_iterator iterator,
const EntryDefinition& entry_definition);
scoped_refptr<storage::FileSystemContext> file_system_context_;
const std::string extension_id_;
const FileDefinitionList file_definition_list_;
EntryDefinitionListCallback callback_;
std::unique_ptr<EntryDefinitionList> result_;
};
FileDefinitionListConverter::FileDefinitionListConverter(
Profile* profile,
const std::string& extension_id,
const FileDefinitionList& file_definition_list,
EntryDefinitionListCallback callback)
: extension_id_(extension_id),
file_definition_list_(file_definition_list),
callback_(std::move(callback)),
result_(new EntryDefinitionList) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
file_system_context_ =
GetFileSystemContextForExtensionId(profile, extension_id_);
// Deletes the converter, once the scoped pointer gets out of scope. It is
// either, if the conversion is finished, or ResolveURL() is terminated, and
// the callback not called because of shutdown.
std::unique_ptr<FileDefinitionListConverter> self_deleter(this);
ConvertNextIterator(std::move(self_deleter), file_definition_list_.begin());
}
void FileDefinitionListConverter::ConvertNextIterator(
std::unique_ptr<FileDefinitionListConverter> self_deleter,
FileDefinitionList::const_iterator iterator) {
if (iterator == file_definition_list_.end()) {
// The converter object will be destroyed since |self_deleter| gets out of
// scope.
std::move(callback_).Run(std::move(result_));
return;
}
if (!file_system_context_.get()) {
OnIteratorConverted(std::move(self_deleter), iterator,
CreateEntryDefinitionWithError(
base::File::FILE_ERROR_INVALID_OPERATION));
return;
}
storage::FileSystemURL url = file_system_context_->CreateCrackedFileSystemURL(
url::Origin::Create(
extensions::Extension::GetBaseURLFromExtensionId(extension_id_)),
storage::kFileSystemTypeExternal, iterator->virtual_path);
if (!url.is_valid()) {
OnIteratorConverted(
std::move(self_deleter), iterator,
CreateEntryDefinitionWithError(base::File::FILE_ERROR_NOT_FOUND));
return;
}
// The converter object will be deleted if the callback is not called because
// of shutdown during ResolveURL().
file_system_context_->ResolveURL(
url, base::BindOnce(&FileDefinitionListConverter::OnResolvedURL,
base::Unretained(this), std::move(self_deleter),
iterator));
}
void FileDefinitionListConverter::OnResolvedURL(
std::unique_ptr<FileDefinitionListConverter> self_deleter,
FileDefinitionList::const_iterator iterator,
base::File::Error error,
const storage::FileSystemInfo& info,
const base::FilePath& file_path,
storage::FileSystemContext::ResolvedEntryType type) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != base::File::FILE_OK) {
OnIteratorConverted(std::move(self_deleter), iterator,
CreateEntryDefinitionWithError(error));
return;
}
EntryDefinition entry_definition;
entry_definition.file_system_root_url = info.root_url.spec();
entry_definition.file_system_name = info.name;
switch (type) {
case storage::FileSystemContext::RESOLVED_ENTRY_FILE:
entry_definition.is_directory = false;
break;
case storage::FileSystemContext::RESOLVED_ENTRY_DIRECTORY:
entry_definition.is_directory = true;
break;
case storage::FileSystemContext::RESOLVED_ENTRY_NOT_FOUND:
entry_definition.is_directory = iterator->is_directory;
break;
}
entry_definition.error = base::File::FILE_OK;
// Construct a target Entry.fullPath value from the virtual path and the
// root URL. Eg. Downloads/A/b.txt -> A/b.txt.
storage::FileSystemURL fs_url = file_system_context_->CrackURL(info.root_url);
if (!fs_url.is_valid()) {
OnIteratorConverted(
std::move(self_deleter), iterator,
CreateEntryDefinitionWithError(base::File::FILE_ERROR_NOT_FOUND));
return;
}
const base::FilePath root_virtual_path = fs_url.virtual_path();
DCHECK(root_virtual_path == iterator->virtual_path ||
root_virtual_path.IsParent(iterator->virtual_path));
base::FilePath full_path;
root_virtual_path.AppendRelativePath(iterator->virtual_path, &full_path);
entry_definition.full_path = full_path;
OnIteratorConverted(std::move(self_deleter), iterator, entry_definition);
}
void FileDefinitionListConverter::OnIteratorConverted(
std::unique_ptr<FileDefinitionListConverter> self_deleter,
FileDefinitionList::const_iterator iterator,
const EntryDefinition& entry_definition) {
result_->push_back(entry_definition);
ConvertNextIterator(std::move(self_deleter), ++iterator);
}
// Helper function to return the converted definition entry directly, without
// the redundant container.
void OnConvertFileDefinitionDone(
EntryDefinitionCallback callback,
std::unique_ptr<EntryDefinitionList> entry_definition_list) {
DCHECK_EQ(1u, entry_definition_list->size());
std::move(callback).Run(entry_definition_list->at(0));
}
// Checks if the |file_path| points non-native location or not.
bool IsUnderNonNativeLocalPath(const storage::FileSystemContext& context,
const base::FilePath& file_path) {
base::FilePath virtual_path;
if (!context.external_backend()->GetVirtualPath(file_path, &virtual_path))
return false;
const storage::FileSystemURL url = context.CreateCrackedFileSystemURL(
url::Origin(), storage::kFileSystemTypeExternal, virtual_path);
if (!url.is_valid())
return false;
return IsNonNativeFileSystemType(url.type());
}
// Helper class to convert SelectedFileInfoList into ChooserFileInfoList.
class ConvertSelectedFileInfoListToFileChooserFileInfoListImpl {
public:
// The scoped pointer to control lifetime of the instance itself. The pointer
// is passed to callback functions and binds the lifetime of the instance to
// the callback's lifetime.
typedef std::unique_ptr<
ConvertSelectedFileInfoListToFileChooserFileInfoListImpl>
Lifetime;
ConvertSelectedFileInfoListToFileChooserFileInfoListImpl(
storage::FileSystemContext* context,
const GURL& origin,
const SelectedFileInfoList& selected_info_list,
FileChooserFileInfoListCallback callback)
: context_(context),
callback_(std::move(callback)) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
Lifetime lifetime(this);
bool need_fill_metadata = false;
for (size_t i = 0; i < selected_info_list.size(); ++i) {
// Native file.
if (!IsUnderNonNativeLocalPath(*context,
selected_info_list[i].file_path)) {
chooser_info_list_.push_back(
FileChooserFileInfo::NewNativeFile(NativeFileInfo::New(
selected_info_list[i].file_path,
base::UTF8ToUTF16(selected_info_list[i].display_name))));
continue;
}
// Non-native file, but it has a native snapshot file.
if (!selected_info_list[i].local_path.empty()) {
chooser_info_list_.push_back(
FileChooserFileInfo::NewNativeFile(NativeFileInfo::New(
selected_info_list[i].local_path,
base::UTF8ToUTF16(selected_info_list[i].display_name))));
continue;
}
// Non-native file without a snapshot file.
base::FilePath virtual_path;
if (!context->external_backend()->GetVirtualPath(
selected_info_list[i].file_path, &virtual_path)) {
NotifyError(std::move(lifetime));
return;
}
FileSystemURLAndHandle isolated_file_system_url_and_handle =
CreateIsolatedURLFromVirtualPath(*context_, origin, virtual_path);
const GURL url = isolated_file_system_url_and_handle.url.ToGURL();
if (!url.is_valid()) {
NotifyError(std::move(lifetime));
return;
}
// Increase ref count of file system to keep it alive after |file_system|
// goes out of scope. Our destructor will eventually revoke the file
// system.
storage::IsolatedContext::GetInstance()->AddReference(
isolated_file_system_url_and_handle.handle.id());
auto fs_info = FileSystemFileInfo::New();
fs_info->url = url;
chooser_info_list_.push_back(
FileChooserFileInfo::NewFileSystem(std::move(fs_info)));
need_fill_metadata = true;
}
// If the list includes at least one non-native file (wihtout a snapshot
// file), move to IO thread to obtian metadata for the non-native file.
if (need_fill_metadata) {
base::PostTask(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(
&ConvertSelectedFileInfoListToFileChooserFileInfoListImpl::
FillMetadataOnIOThread,
base::Unretained(this), std::move(lifetime),
chooser_info_list_.begin()));
return;
}
NotifyComplete(std::move(lifetime));
}
~ConvertSelectedFileInfoListToFileChooserFileInfoListImpl() {
for (const auto& info : chooser_info_list_) {
if (info && info->is_file_system()) {
storage::IsolatedContext::GetInstance()->RevokeFileSystem(
context_->CrackURL(info->get_file_system()->url)
.mount_filesystem_id());
}
}
}
private:
// Obtains metadata for the non-native file |it|.
void FillMetadataOnIOThread(Lifetime lifetime,
const FileChooserFileInfoList::iterator& it) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (it == chooser_info_list_.end()) {
base::PostTask(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(
&ConvertSelectedFileInfoListToFileChooserFileInfoListImpl::
NotifyComplete,
base::Unretained(this), std::move(lifetime)));
return;
}
if ((*it)->is_native_file()) {
FillMetadataOnIOThread(std::move(lifetime), it + 1);
return;
}
context_->operation_runner()->GetMetadata(
context_->CrackURL((*it)->get_file_system()->url),
storage::FileSystemOperation::GET_METADATA_FIELD_IS_DIRECTORY |
storage::FileSystemOperation::GET_METADATA_FIELD_SIZE |
storage::FileSystemOperation::GET_METADATA_FIELD_LAST_MODIFIED,
base::BindOnce(
&ConvertSelectedFileInfoListToFileChooserFileInfoListImpl::
OnGotMetadataOnIOThread,
base::Unretained(this), std::move(lifetime), it));
}
// Callback invoked after GetMetadata.
void OnGotMetadataOnIOThread(Lifetime lifetime,
const FileChooserFileInfoList::iterator& it,
base::File::Error result,
const base::File::Info& file_info) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (result != base::File::FILE_OK) {
base::PostTask(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(
&ConvertSelectedFileInfoListToFileChooserFileInfoListImpl::
NotifyError,
base::Unretained(this), std::move(lifetime)));
return;
}
(*it)->get_file_system()->length = file_info.size;
(*it)->get_file_system()->modification_time = file_info.last_modified;
DCHECK(!file_info.is_directory);
FillMetadataOnIOThread(std::move(lifetime), it + 1);
}
// Returns a result to the |callback_|.
void NotifyComplete(Lifetime /* lifetime */) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Move the list content so that the file systems are not revoked at the
// destructor.
std::move(callback_).Run(std::move(chooser_info_list_));
}
// Returns an empty list to the |callback_|.
void NotifyError(Lifetime /* lifetime */) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
std::move(callback_).Run(FileChooserFileInfoList());
}
scoped_refptr<storage::FileSystemContext> context_;
FileChooserFileInfoList chooser_info_list_;
FileChooserFileInfoListCallback callback_;
DISALLOW_COPY_AND_ASSIGN(
ConvertSelectedFileInfoListToFileChooserFileInfoListImpl);
};
void CheckIfDirectoryExistsOnIoThread(
scoped_refptr<storage::FileSystemContext> file_system_context,
const storage::FileSystemURL& internal_url,
storage::FileSystemOperationRunner::StatusCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
file_system_context->operation_runner()->DirectoryExists(internal_url,
std::move(callback));
}
void GetMetadataForPathOnIoThread(
scoped_refptr<storage::FileSystemContext> file_system_context,
const storage::FileSystemURL& internal_url,
int fields,
storage::FileSystemOperationRunner::GetMetadataCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
file_system_context->operation_runner()->GetMetadata(internal_url, fields,
std::move(callback));
}
} // namespace
EntryDefinition::EntryDefinition() = default;
EntryDefinition::EntryDefinition(const EntryDefinition& other) = default;
EntryDefinition::~EntryDefinition() = default;
storage::FileSystemContext* GetFileSystemContextForExtensionId(
Profile* profile,
const std::string& extension_id) {
return extensions::util::GetStoragePartitionForExtensionId(extension_id,
profile)
->GetFileSystemContext();
}
storage::FileSystemContext* GetFileSystemContextForRenderFrameHost(
Profile* profile,
content::RenderFrameHost* render_frame_host) {
return render_frame_host->GetStoragePartition()->GetFileSystemContext();
}
bool ConvertAbsoluteFilePathToFileSystemUrl(Profile* profile,
const base::FilePath& absolute_path,
const std::string& extension_id,
GURL* url) {
base::FilePath relative_path;
if (!ConvertAbsoluteFilePathToRelativeFileSystemPath(profile,
extension_id,
absolute_path,
&relative_path)) {
return false;
}
*url = ConvertRelativeFilePathToFileSystemUrl(relative_path, extension_id);
return true;
}
bool ConvertAbsoluteFilePathToRelativeFileSystemPath(
Profile* profile,
const std::string& extension_id,
const base::FilePath& absolute_path,
base::FilePath* virtual_path) {
storage::ExternalFileSystemBackend* backend =
GetFileSystemContextForExtensionId(profile, extension_id)
->external_backend();
if (!backend)
return false;
// Find if this file path is managed by the external backend.
if (!backend->GetVirtualPath(absolute_path, virtual_path))
return false;
return true;
}
void ConvertFileDefinitionListToEntryDefinitionList(
Profile* profile,
const std::string& extension_id,
const FileDefinitionList& file_definition_list,
EntryDefinitionListCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// The converter object destroys itself.
new FileDefinitionListConverter(profile, extension_id, file_definition_list,
std::move(callback));
}
void ConvertFileDefinitionToEntryDefinition(
Profile* profile,
const std::string& extension_id,
const FileDefinition& file_definition,
EntryDefinitionCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
FileDefinitionList file_definition_list;
file_definition_list.push_back(file_definition);
ConvertFileDefinitionListToEntryDefinitionList(
profile, extension_id, file_definition_list,
base::BindOnce(&OnConvertFileDefinitionDone, std::move(callback)));
}
void ConvertSelectedFileInfoListToFileChooserFileInfoList(
storage::FileSystemContext* context,
const GURL& origin,
const SelectedFileInfoList& selected_info_list,
FileChooserFileInfoListCallback callback) {
// The object deletes itself.
new ConvertSelectedFileInfoListToFileChooserFileInfoListImpl(
context, origin, selected_info_list, std::move(callback));
}
std::unique_ptr<base::DictionaryValue> ConvertEntryDefinitionToValue(
const EntryDefinition& entry_definition) {
auto entry = std::make_unique<base::DictionaryValue>();
entry->SetString("fileSystemName", entry_definition.file_system_name);
entry->SetString("fileSystemRoot", entry_definition.file_system_root_url);
entry->SetString(
"fileFullPath",
base::FilePath("/").Append(entry_definition.full_path).AsUTF8Unsafe());
entry->SetBoolean("fileIsDirectory", entry_definition.is_directory);
return entry;
}
std::unique_ptr<base::ListValue> ConvertEntryDefinitionListToListValue(
const EntryDefinitionList& entry_definition_list) {
auto entries = std::make_unique<base::ListValue>();
for (auto it = entry_definition_list.begin();
it != entry_definition_list.end(); ++it) {
entries->Append(ConvertEntryDefinitionToValue(*it));
}
return entries;
}
void CheckIfDirectoryExists(
scoped_refptr<storage::FileSystemContext> file_system_context,
const base::FilePath& directory_path,
storage::FileSystemOperationRunner::StatusCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
storage::ExternalFileSystemBackend* const backend =
file_system_context->external_backend();
DCHECK(backend);
const storage::FileSystemURL internal_url =
backend->CreateInternalURL(file_system_context.get(), directory_path);
base::PostTask(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&CheckIfDirectoryExistsOnIoThread, file_system_context,
internal_url,
google_apis::CreateRelayCallback(std::move(callback))));
}
void GetMetadataForPath(
scoped_refptr<storage::FileSystemContext> file_system_context,
const base::FilePath& entry_path,
int fields,
storage::FileSystemOperationRunner::GetMetadataCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
storage::ExternalFileSystemBackend* const backend =
file_system_context->external_backend();
DCHECK(backend);
const storage::FileSystemURL internal_url =
backend->CreateInternalURL(file_system_context.get(), entry_path);
base::PostTask(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&GetMetadataForPathOnIoThread, file_system_context,
internal_url, fields,
google_apis::CreateRelayCallback(std::move(callback))));
}
FileSystemURLAndHandle CreateIsolatedURLFromVirtualPath(
const storage::FileSystemContext& context,
const GURL& origin,
const base::FilePath& virtual_path) {
const storage::FileSystemURL original_url =
context.CreateCrackedFileSystemURL(url::Origin::Create(origin),
storage::kFileSystemTypeExternal,
virtual_path);
std::string register_name;
storage::IsolatedContext::ScopedFSHandle file_system =
storage::IsolatedContext::GetInstance()->RegisterFileSystemForPath(
original_url.type(), original_url.filesystem_id(),
original_url.path(), ®ister_name);
storage::FileSystemURL isolated_url = context.CreateCrackedFileSystemURL(
url::Origin::Create(origin), storage::kFileSystemTypeIsolated,
base::FilePath(file_system.id()).Append(register_name));
return {isolated_url, file_system};
}
} // namespace util
} // namespace file_manager
| endlessm/chromium-browser | chrome/browser/chromeos/file_manager/fileapi_util.cc | C++ | bsd-3-clause | 24,137 |
<?php
/**
* contentinum - accessibility websites
*
* LICENSE
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category contentinum
* @package Service
* @author Michael Jochum, michael.jochum@jochum-mediaservices.de
* @copyright Copyright (c) 2009-2013 jochum-mediaservices, Katja Jochum (http://www.jochum-mediaservices.de)
* @license http://www.opensource.org/licenses/bsd-license
* @since contentinum version 5.0
* @link https://github.com/Mikel1961/contentinum-components
* @version 1.0.0
*/
namespace Mcwork\Service\Media;
use Contentinum\Service\WebsiteServiceFactory;
use Mcwork\Mapper\Media;
/**
* Content of full media table to use in backend
*
* @author Michael Jochum, michael.jochum@jochum-mediaservices.de
*/
class TagServiceFactory extends WebsiteServiceFactory
{
/**
* Cache key media table
*
* @var string
*/
const CONTENTINUM_DATABASE = 'mcwork_media';
/**
* Name cache factory
*
* @var string
*/
const CONTENTINUM_CACHE = 'Mcwork\Cache\Structures';
/**
* (non-PHPdoc)
*
* @see \Contentinum\Service\WebsiteServiceFactory::queryDbCacheResult()
*/
protected function queryDbCacheResult($config, $sl)
{
$result = array();
$cache = $sl->get(static::CONTENTINUM_CACHE);
$key = $config['cache'];
if (! ($result = $cache->getItem($key))) {
$worker = new Media($sl->get($config['entitymanager']));
$worker->setEntity($config['entity']);
$datas = $worker->fetchMediaTable(array(
'id',
'mediaName',
'mediaSource',
'mediaLink',
'mediaType',
'mediaAlternate',
'mediaMetas',
'mediaSizes',
'resource',
'createdBy',
'updateBy',
'registerDate',
'upDate'
),null,$config['entity']);
foreach ($datas as $row) {
$result[$row['mediaSource']]['mediaSizes'] = $row['mediaSizes'];
$result[$row['mediaSource']]['id'] = $row['id'];
$result[$row['mediaSource']]['mediaLink'] = $row['mediaLink'];
$result[$row['mediaSource']]['mediaName'] = $row['mediaName'];
$result[$row['mediaSource']]['mediaType'] = $row['mediaType'];
$result[$row['mediaSource']]['mediaAlternate'] = $row['mediaAlternate'];
$result[$row['mediaSource']]['mediaMetas'] = $row['mediaMetas'];
$result[$row['mediaSource']]['resource'] = $row['resource'];
$result[$row['mediaSource']]['createdBy'] = $row['createdBy'];
$result[$row['mediaSource']]['updateBy'] = $row['updateBy'];
$result[$row['mediaSource']]['registerDate'] = $row['registerDate'];
$result[$row['mediaSource']]['upDate'] = $row['upDate'];
}
if (isset($config['savecache']) && true === $config['savecache']){
$cache->setItem($key, $result);
}
}
return $result;
}
} | Mikel1961/contentinum.5.1 | module/Mcwork/src/Mcwork/Service/Files/TagServiceFactory.php | PHP | bsd-3-clause | 3,925 |
package ch.codebulb.lambdaomega.abstractions;
import ch.codebulb.lambdaomega.abstractions.functions.DoubleBiFunction;
import ch.codebulb.lambdaomega.abstractions.functions.IntBiFunction;
import ch.codebulb.lambdaomega.abstractions.functions.LongBiFunction;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.BinaryOperator;
import java.util.function.DoubleBinaryOperator;
import java.util.function.IntBinaryOperator;
import java.util.function.LongBinaryOperator;
import java.util.function.ObjDoubleConsumer;
import java.util.function.ObjIntConsumer;
import java.util.function.ObjLongConsumer;
import java.util.function.ToDoubleBiFunction;
import java.util.function.ToIntBiFunction;
import java.util.function.ToLongBiFunction;
/**
* A multi-interface providing a single unified API for all 2-ary {@link FunctionalInterface}s of Java 8 and LambdaOmega.
* Implement / use {@link #call(Object, Object)} / {@link #call()} to call this function.<p/>
*
* Note: {@link BinaryOperator} is not covered by this interface as it is mutually incompatible with {@link BiFunction}.
*
* @param <T> the type of the first argument to the function
* @param <U> the type of the second argument to the function
* @param <R> the type of the result of the function
*/
@FunctionalInterface
public interface BiFunctionalI<T, U, R> extends BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>,
IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator,
IntBiFunction<R>, LongBiFunction<R>, DoubleBiFunction<R>,
ToIntBiFunction<T, U>, ToLongBiFunction<T, U>, ToDoubleBiFunction<T, U>,
ObjIntConsumer<T>, ObjLongConsumer<T>, ObjDoubleConsumer<T> {
/**
* Calls this function with the given arguments.
*/
public R call(T t, U u);
/**
* Calls this function without arguments / with <code>null</code> as argument.
*/
public default R call() {
return call(null, null);
}
@Override
public default R apply(T t, U u) {
return call(t, u);
}
@Override
public default void accept(T t, U u) {
call(t, u);
}
@Override
public default boolean test(T t, U u) {
return (Boolean)call(t, u);
}
@Override
public default int applyAsInt(int left, int right) {
return (Integer)call((T)Integer.valueOf(left), (U)Integer.valueOf(right));
}
@Override
public default long applyAsLong(long left, long right) {
return (Long)call((T)Long.valueOf(left), (U)Long.valueOf(right));
}
@Override
public default double applyAsDouble(double left, double right) {
return (Double)call((T)Double.valueOf(left), (U)Double.valueOf(right));
}
@Override
public default R apply(int t, int u) {
return call((T)Integer.valueOf(t), (U)Integer.valueOf(u));
}
@Override
public default R apply(long t, long u) {
return call((T)Long.valueOf(t), (U)Long.valueOf(u));
}
@Override
public default R apply(double t, double u) {
return call((T)Double.valueOf(t), (U)Double.valueOf(u));
}
@Override
public default int applyAsInt(T t, U u) {
return (Integer)call(t, u);
}
@Override
public default long applyAsLong(T t, U u) {
return (Long)call(t, u);
}
@Override
public default double applyAsDouble(T t, U u) {
return (Double)call(t, u);
}
@Override
public default void accept(T t, int u) {
call(t, (U) Integer.valueOf(u));
}
@Override
public default void accept(T t, long u) {
call(t, (U) Long.valueOf(u));
}
@Override
public default void accept(T t, double u) {
call(t, (U) Double.valueOf(u));
}
}
| codebulb/LambdaOmega | src/main/java/ch/codebulb/lambdaomega/abstractions/BiFunctionalI.java | Java | bsd-3-clause | 3,829 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.init;
/**
* Interface that any {@link AsyncInitializationActivity} can use to interact with this delegate
* during start up. Functions called by
* {@link ChromeBrowserInitializer#handlePreNativeStartup(BrowserParts)} are called in the order
* they are listed.
*/
public interface BrowserParts {
/**
* Called during {@link ChromeBrowserInitializer#handlePreNativeStartup(BrowserParts)}.
* This should consist of java only calls that will not take too much time.
*/
void preInflationStartup();
/**
* Called during {@link ChromeBrowserInitializer#handlePreNativeStartup(BrowserParts)}.
* It should include a call to setContentView and also should start loading libraries using
* {@link NativeInitializationController#startBackgroundTasks()}
*/
void setContentViewAndLoadLibrary();
/**
* Called during {@link ChromeBrowserInitializer#handlePreNativeStartup(BrowserParts)}.
* Early setup after the view hierarchy has been inflated and the background tasks has been
* initialized. No native calls.
*/
void postInflationStartup();
/**
* Called during {@link ChromeBrowserInitializer#handlePostNativeStartup(BrowserParts)}.
* Optionaly preconnect to the URL specified in the launch intent, if any. The
* preconnection is done asynchronously in the native library.
*/
void maybePreconnect();
/**
* Called during {@link ChromeBrowserInitializer#handlePostNativeStartup(BrowserParts)}.
* Initialize the compositor related classes.
*/
void initializeCompositor();
/**
* Called during {@link ChromeBrowserInitializer#handlePostNativeStartup(BrowserParts)}.
* Initialize the tab state restoring tabs or creating new tabs.
*/
void initializeState();
/**
* Called during {@link ChromeBrowserInitializer#handlePostNativeStartup(BrowserParts)}.
* Carry out remaining activity specific tasks for initialization
*/
void finishNativeInitialization();
/**
* Called during {@link ChromeBrowserInitializer#handlePostNativeStartup(BrowserParts)} if
* there was an error during startup.
*/
void onStartupFailure();
/**
* @return Whether the activity this delegate represents has been destoyed.
*/
boolean isActivityDestroyed();
/**
* @return Whether the activity is marked itself to be closed.
*/
boolean isActivityFinishing();
}
| was4444/chromium.src | chrome/android/java/src/org/chromium/chrome/browser/init/BrowserParts.java | Java | bsd-3-clause | 2,656 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.android_webview;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
/**
* Delegate for handling callbacks. All methods are called on the IO thread.
*
* You should create a separate instance for every WebContents that requires the
* provided functionality.
*/
@JNINamespace("android_webview")
public interface AwContentsIoThreadClient {
@CalledByNative
public int getCacheMode();
@CalledByNative
public InterceptedRequestData shouldInterceptRequest(String url);
@CalledByNative
public boolean shouldBlockContentUrls();
@CalledByNative
public boolean shouldBlockFileUrls();
@CalledByNative
public boolean shouldBlockNetworkLoads();
}
| leighpauls/k2cro4 | android_webview/java/src/org/chromium/android_webview/AwContentsIoThreadClient.java | Java | bsd-3-clause | 903 |
# Copyright (C) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from webkitpy.common.checkout.scm.scm_mock import MockSCM
from webkitpy.common.net.buildbot.buildbot_mock import MockBuildBot
from webkitpy.common.net.web_mock import MockWeb
from webkitpy.common.system.systemhost_mock import MockSystemHost
# New-style ports need to move down into webkitpy.common.
from webkitpy.layout_tests.port.factory import PortFactory
from webkitpy.layout_tests.port.test import add_unit_tests_to_mock_filesystem
class MockHost(MockSystemHost):
def __init__(self, log_executive=False, executive_throws_when_run=None, initialize_scm_by_default=True, web=None, scm=None):
MockSystemHost.__init__(self, log_executive, executive_throws_when_run)
add_unit_tests_to_mock_filesystem(self.filesystem)
self.web = web or MockWeb()
self._scm = scm
# FIXME: we should never initialize the SCM by default, since the real
# object doesn't either. This has caused at least one bug (see bug 89498).
if initialize_scm_by_default:
self.initialize_scm()
self.buildbot = MockBuildBot()
# Note: We're using a real PortFactory here. Tests which don't wish to depend
# on the list of known ports should override this with a MockPortFactory.
self.port_factory = PortFactory(self)
def initialize_scm(self, patch_directories=None):
if not self._scm:
self._scm = MockSCM(filesystem=self.filesystem, executive=self.executive)
# Various pieces of code (wrongly) call filesystem.chdir(checkout_root).
# Making the checkout_root exist in the mock filesystem makes that chdir not raise.
self.filesystem.maybe_make_directory(self._scm.checkout_root)
def scm(self):
return self._scm
def scm_for_path(self, path):
# FIXME: consider supporting more than one SCM so that we can do more comprehensive testing.
self.initialize_scm()
return self._scm
def checkout(self):
return self._checkout
| was4444/chromium.src | third_party/WebKit/Tools/Scripts/webkitpy/common/host_mock.py | Python | bsd-3-clause | 3,518 |
/*
* File: app/view/CitiesCombo.js
*
*/
Ext.define('TestApp.view.CitiesCombo', {
extend: 'Ext.form.field.ComboBox',
alias: 'widget.citiescombo',
requires: [
'TestApp.view.CitiesComboViewModel'
],
viewModel: {
type: 'citiescombo'
},
itemId: 'educationcombo1',
fieldLabel: 'Город',
name: 'cities',
displayField: 'name',
valueField: 'id',
bind: {
store: '{CitiesStore}'
}
}); | wursta/zendtest | public/app/view/CitiesCombo.js | JavaScript | bsd-3-clause | 461 |
import numpy as np
from ._layout import Layout
from ._multivector import MultiVector
class ConformalLayout(Layout):
r"""
A layout for a conformal algebra, which adds extra constants and helpers.
Typically these should be constructed via :func:`clifford.conformalize`.
.. versionadded:: 1.2.0
Attributes
----------
ep : MultiVector
The first added basis element, :math:`e_{+}`, usually with :math:`e_{+}^2 = +1`
en : MultiVector
The first added basis element, :math:`e_{-}`, usually with :math:`e_{-}^2 = -1`
eo : MultiVector
The null basis vector at the origin, :math:`e_o = 0.5(e_{-} - e_{+})`
einf : MultiVector
The null vector at infinity, :math:`e_\infty = e_{-} + e_{+}`
E0 : MultiVector
The minkowski subspace bivector, :math:`e_\infty \wedge e_o`
I_base : MultiVector
The pseudoscalar of the base ga, in cga layout
"""
def __init__(self, *args, layout=None, **kwargs):
super().__init__(*args, **kwargs)
self._base_layout = layout
ep, en = self.basis_vectors_lst[-2:]
# setup null basis, and minkowski subspace bivector
eo = .5 ^ (en - ep)
einf = en + ep
E0 = einf ^ eo
I_base = self.pseudoScalar*E0
# helper properties
self.ep = ep
self.en = en
self.eo = eo
self.einf = einf
self.E0 = E0
self.I_base = I_base
@classmethod
def _from_base_layout(cls, layout, added_sig=[1, -1], **kwargs) -> 'ConformalLayout':
""" helper to implement :func:`clifford.conformalize` """
sig_c = list(layout.sig) + added_sig
return cls(
sig_c,
ids=layout._basis_vector_ids.augmented_with(len(added_sig)),
layout=layout, **kwargs)
# some convenience functions
def up(self, x: MultiVector) -> MultiVector:
""" up-project a vector from GA to CGA """
try:
if x.layout == self._base_layout:
# vector is in original space, map it into conformal space
old_val = x.value
new_val = np.zeros(self.gaDims)
new_val[:len(old_val)] = old_val
x = self.MultiVector(value=new_val)
except(AttributeError):
# if x is a scalar it doesnt have layout but following
# will still work
pass
# then up-project into a null vector
return x + (.5 ^ ((x**2)*self.einf)) + self.eo
def homo(self, x: MultiVector) -> MultiVector:
""" homogenize a CGA vector """
return x/(-x | self.einf)[()]
def down(self, x: MultiVector) -> MultiVector:
""" down-project a vector from CGA to GA """
x_down = (self.homo(x) ^ self.E0)*self.E0
# new_val = x_down.value[:self.base_layout.gaDims]
# create vector in self.base_layout (not cga)
# x_down = self.base_layout.MultiVector(value=new_val)
return x_down
| arsenovic/clifford | clifford/_conformal_layout.py | Python | bsd-3-clause | 2,999 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ANIMATION_TEST_SQUARE_INK_DROP_ANIMATION_TEST_API_H_
#define UI_VIEWS_ANIMATION_TEST_SQUARE_INK_DROP_ANIMATION_TEST_API_H_
#include <vector>
#include "base/macros.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/square_ink_drop_animation.h"
#include "ui/views/animation/test/ink_drop_animation_test_api.h"
namespace ui {
class LayerAnimator;
} // namespace ui
namespace views {
namespace test {
// Test API to provide internal access to a SquareInkDropAnimation.
class SquareInkDropAnimationTestApi : public InkDropAnimationTestApi {
public:
// Make the private typedefs accessible.
using InkDropTransforms = SquareInkDropAnimation::InkDropTransforms;
using PaintedShape = SquareInkDropAnimation::PaintedShape;
explicit SquareInkDropAnimationTestApi(
SquareInkDropAnimation* ink_drop_animation);
~SquareInkDropAnimationTestApi() override;
// Wrapper functions to the wrapped InkDropAnimation:
void CalculateCircleTransforms(const gfx::Size& size,
InkDropTransforms* transforms_out) const;
void CalculateRectTransforms(const gfx::Size& size,
float corner_radius,
InkDropTransforms* transforms_out) const;
// InkDropAnimationTestApi:
float GetCurrentOpacity() const override;
protected:
// InkDropAnimationTestApi:
std::vector<ui::LayerAnimator*> GetLayerAnimators() override;
private:
SquareInkDropAnimation* ink_drop_animation() {
return static_cast<const SquareInkDropAnimationTestApi*>(this)
->ink_drop_animation();
}
SquareInkDropAnimation* ink_drop_animation() const {
return static_cast<SquareInkDropAnimation*>(
InkDropAnimationTestApi::ink_drop_animation());
}
DISALLOW_COPY_AND_ASSIGN(SquareInkDropAnimationTestApi);
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_ANIMATION_TEST_SQUARE_INK_DROP_ANIMATION_TEST_API_H_
| was4444/chromium.src | ui/views/animation/test/square_ink_drop_animation_test_api.h | C | bsd-3-clause | 2,121 |
/** @file
EBC VM Test protocol for test purposes.
Copyright (c) 2011 - 2016, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions
of the BSD License which accompanies this distribution. The
full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef _EBC_VM_TEST_PROTOCOL_H_
#define _EBC_VM_TEST_PROTOCOL_H_
//
// Define a protocol for an EBC VM test interface.
//
#define EFI_EBC_VM_TEST_PROTOCOL_GUID \
{ \
0xAAEACCFD, 0xF27B, 0x4C17, { 0xB6, 0x10, 0x75, 0xCA, 0x1F, 0x2D, 0xFB, 0x52 } \
}
//
// Define for forward reference.
//
typedef struct _EFI_EBC_VM_TEST_PROTOCOL EFI_EBC_VM_TEST_PROTOCOL;
//
// VM major/minor version
//
#define VM_MAJOR_VERSION 1
#define VM_MINOR_VERSION 1
//
// Bits in the VM->StopFlags field
//
#define STOPFLAG_APP_DONE 0x0001
#define STOPFLAG_BREAKPOINT 0x0002
#define STOPFLAG_INVALID_BREAK 0x0004
#define STOPFLAG_BREAK_ON_CALLEX 0x0008
//
// Masks for working with the VM flags register
//
#define VMFLAGS_CC 0x0001 // condition flag
#define VMFLAGS_STEP 0x0002 // step instruction mode
#define VMFLAGS_ALL_VALID (VMFLAGS_CC | VMFLAGS_STEP)
//
// Macros for operating on the VM flags register
//
#define VMFLAG_SET(pVM, Flag) (pVM->Flags |= (Flag))
#define VMFLAG_ISSET(pVM, Flag) ((pVM->Flags & (Flag)) ? 1 : 0)
#define VMFLAG_CLEAR(pVM, Flag) (pVM->Flags &= ~(Flag))
//
// Define a macro to get the operand. Then we can change it to be either a
// direct read or have it call a function to read memory.
//
#define GETOPERANDS(pVM) (UINT8) (*(UINT8 *) (pVM->Ip + 1))
#define GETOPCODE(pVM) (UINT8) (*(UINT8 *) pVM->Ip)
//
// Macros for operating on the VM GP registers
//
#define OPERAND1_REGDATA(pVM, Op) pVM->Gpr[OPERAND1_REGNUM (Op)]
#define OPERAND2_REGDATA(pVM, Op) pVM->Gpr[OPERAND2_REGNUM (Op)]
//
// Bits of exception flags field of VM context
//
#define EXCEPTION_FLAG_FATAL 0x80000000 // can't continue
#define EXCEPTION_FLAG_ERROR 0x40000000 // bad, but try to continue
#define EXCEPTION_FLAG_WARNING 0x20000000 // harmless problem
#define EXCEPTION_FLAG_NONE 0x00000000 // for normal return
///
/// instruction pointer for the VM
///
typedef UINT8 *VMIP;
typedef INT64 VM_REGISTER;
typedef UINT32 EXCEPTION_FLAGS;
typedef struct {
VM_REGISTER Gpr[8]; ///< General purpose registers.
///< Flags register:
///< 0 Set to 1 if the result of the last compare was true
///< 1 Set to 1 if stepping
UINT64 Flags; ///< 2..63 Reserved.
VMIP Ip; ///< Instruction pointer.
UINTN LastException;
EXCEPTION_FLAGS ExceptionFlags; ///< to keep track of exceptions
UINT32 StopFlags;
UINT32 CompilerVersion; ///< via break(6)
UINTN HighStackBottom; ///< bottom of the upper stack
UINTN LowStackTop; ///< top of the lower stack
UINT64 StackRetAddr; ///< location of final return address on stack
UINTN *StackMagicPtr; ///< pointer to magic value on stack to detect corruption
EFI_HANDLE ImageHandle; ///< for this EBC driver
EFI_SYSTEM_TABLE *SystemTable; ///< for debugging only
UINTN LastAddrConverted; ///< for debug
UINTN LastAddrConvertedValue; ///< for debug
VOID *FramePtr;
VOID *EntryPoint; ///< entry point of EBC image
UINTN ImageBase;
VOID *StackPool;
VOID *StackTop;
VOID *StackTracker; ///< pointer to an optional, opaque and arch-specific
/// structure, which may be used to track stack ops.
} VM_CONTEXT;
/**
Given a pointer to a new VM context, execute one or more instructions. This
function is only used for test purposes.
@param[in] This A pointer to the EFI_EBC_VM_TEST_PROTOCOL structure.
@param[in] VmPtr A pointer to a VM context.
@param[in, out] InstructionCount A pointer to a UINTN value holding the number of
instructions to execute. If it holds value of 0,
then the instruction to be executed is 1.
@retval EFI_UNSUPPORTED At least one of the opcodes is not supported.
@retval EFI_SUCCESS All of the instructions are executed successfully.
**/
typedef
EFI_STATUS
(EFIAPI *EBC_VM_TEST_EXECUTE) (
IN EFI_EBC_VM_TEST_PROTOCOL *This,
IN VM_CONTEXT *VmPtr,
IN OUT UINTN *InstructionCount
);
/**
Convert AsmText to the instruction. This function is only used for test purposes.
@param[in] This A pointer to the EFI_EBC_VM_TEST_PROTOCOL structure.
@param[in] AsmText A pointer to EBC ASM text code.
@param[out] Buffer Buffer to store the instruction.
@param[out] BufferLen Size of buffer that is required to store data.
@retval EFI_UNSUPPORTED This functionality is unsupported.
@retval EFI_SUCCESS Successfully convert AsmText to the instruction.
**/
typedef
EFI_STATUS
(EFIAPI *EBC_VM_TEST_ASM) (
IN EFI_EBC_VM_TEST_PROTOCOL *This,
IN CHAR16 *AsmText,
IN OUT INT8 *Buffer,
IN OUT UINTN *BufferLen
);
/**
Dump the executed instruction. This function is only used for test purposes.
@param[in] This A pointer to the EFI_EBC_VM_TEST_PROTOCOL structure.
@param[out] AsmText Contain the disasm text.
@param[out] Buffer Buffer to store the instruction.
@param[out] BufferLen Size of buffer that is required to store data.
@retval EFI_UNSUPPORTED This functionality is unsupported.
@retval EFI_SUCCESS Successfully dump the executed instruction.
**/
typedef
EFI_STATUS
(EFIAPI *EBC_VM_TEST_DASM) (
IN EFI_EBC_VM_TEST_PROTOCOL *This,
IN OUT CHAR16 *AsmText,
IN OUT INT8 *Buffer,
IN OUT UINTN *Len
);
//
// Prototype for the actual EBC test protocol interface
//
struct _EFI_EBC_VM_TEST_PROTOCOL {
EBC_VM_TEST_EXECUTE Execute;
EBC_VM_TEST_ASM Assemble;
EBC_VM_TEST_DASM Disassemble;
};
extern EFI_GUID gEfiEbcVmTestProtocolGuid;
#endif
| pbatard/EbcDebugger | Missing/Protocol/EbcVmTest.h | C | bsd-3-clause | 6,904 |
{% load i18n %}
<a href="{% url documents_disquss %}">{% trans 'Обсуждаемые тезисы' %} ({{ disquss }})</a>
<a href="{% url documents_accept %}">{% trans 'Принятые тезисы' %} ({{ accept }})</a>
<a href="{% url documents_reject %}">{% trans 'Отклонённые тезисы' %} ({{ reject }})</a>
<a href="{% url accounts_list %}">{% trans 'Все участники' %} ({{ account_counts }})</a>
<a href="{% url tours_info %}">{% trans 'Сводка по мероприятиям' %}</a>
| m-garanin/conference | templates/experts_menu.html | HTML | bsd-3-clause | 523 |
/*L
* Copyright Oracle Inc
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
*/
package org.exist.storage.analysis;
/**
* This is the default class used by the fulltext indexer for
* tokenizing a string into words. Known token types are defined
* by class Token.
*
*@author Wolfgang Meier
*/
public class SimpleTokenizer implements Tokenizer {
private int pos = 0;
private boolean stem = false;
private CharSequence text;
private int len = 0;
private final TextToken temp = new TextToken();
public SimpleTokenizer() {
}
public SimpleTokenizer(boolean stem) {
this.stem = stem;
}
public void setStemming(boolean stem) {
this.stem = stem;
}
private final char LA(int i) {
final int current = pos + i;
return current > len ? (char) -1 : text.charAt(current - 1);
}
protected TextToken alpha(TextToken token, boolean allowWildcards) {
if (token == null)
token = new TextToken(TextToken.ALPHA, text, pos);
else
token.setType(TextToken.ALPHA);
// consume letters
char ch = LA(1);
int count = 0;
while (ch != (char) -1) {
if (ch == '\\' && isWildcard(LA(2))) {
break;
} else if (ch > '\u2E80' && singleCharToken(ch)) {
// if this is a single char token and first in the sequence,
// consume it
if(count == 0) {
token.consumeNext();
consume();
ch = LA(1);
}
break;
} else if (Character.isLetter(ch) || is_mark(ch) || nonBreakingChar(ch) || (allowWildcards && isWildcard(ch))) {
token.consumeNext();
consume();
ch = LA(1);
count++;
} else {
break;
}
}
if (Character.isDigit(ch)) {
// found non-letter character
// call alphanum()
return alphanum(token, allowWildcards);
}
return token;
}
private final static boolean isWildcard(char ch) {
if (ch == '?' || ch == '*')
return true;
return false;
}
protected TextToken alphanum(TextToken token, boolean allowWildcards) {
if (token == null)
token = new TextToken(TextToken.ALPHANUM, text, pos);
else
token.setType(TextToken.ALPHANUM);
while (LA(1) != (char) - 1) {
if (Character.isLetterOrDigit(LA(1))) {
token.consumeNext();
consume();
} else if (allowWildcards && isWildcard(LA(1))) {
token.consumeNext();
consume();
continue;
} else
break;
}
return token;
}
protected void consume() {
pos++;
}
protected TextToken eof() {
consume();
return TextToken.EOF_TOKEN;
}
public int getLength() {
return len;
}
public String getText() {
return text.toString();
}
protected TextToken nextTerminalToken(boolean wildcards) {
TextToken token = null;
char ch = LA(1);
if (ch == (char) - 1)
return eof();
if (Character.isLetter(ch) || is_mark(ch) || nonBreakingChar(ch)
|| singleCharToken(ch)
|| (wildcards && isWildcard(ch))) {
token = alpha(null, wildcards);
}
if (token == null
&& (Character.isLetterOrDigit(ch)
|| (wildcards && isWildcard(ch))))
token = alphanum(null, wildcards);
if (token == null)
switch (ch) {
case '\\':
if(isWildcard(LA(2))) {
consume();
}
case '*' :
case ',' :
case '-' :
case '_' :
case ':' :
case '.' :
case '@' :
case '/' :
token = p();
break;
default :
token = whitespace();
break;
}
return token;
}
public TextToken nextToken() {
return nextToken(false);
}
public TextToken nextToken(boolean wildcards) {
try {
while (true) {
TextToken token = nextTerminalToken(wildcards);
TextToken next;
int oldPos = pos;
char LA1 = LA(1);
switch (token.getType()) {
case TextToken.EOF :
return null;
case TextToken.ALPHA :
switch (LA1) {
// text with apostrophe like Peter's
case '\'' :
consume();
next = nextTerminalToken(wildcards);
if (next != null
&& next.getType() == TextToken.ALPHA) {
return new TextToken(TextToken.ALPHA, text, token.startOffset(), next.endOffset());
}
pos = oldPos;
break;
// text with some alphanumeric sequence attached
// handles URL's, email addresses, dates or general sequences like
// like Q/22/A4.5 or 12/09/1989
case '_' :
case ':' :
case '.' :
case '/' :
case '@' :
if (LA(2) == (char) - 1
|| Character.isWhitespace(LA(2))) {
consume();
break;
}
TextToken last = null;
while ((next = nextTerminalToken(wildcards))
!= null) {
if (next.getType() == TextToken.EOF
|| next.getType() == TextToken.WS)
break;
if(next.getType() == TextToken.P &&
(LA(2) == (char)-1 || Character.isWhitespace(LA(2))))
break;
last = next;
}
if (last != null)
token =
new TextToken(
TextToken.ALPHANUM,
text, token.startOffset(), last.endOffset());
else
pos = oldPos;
}
return token;
case TextToken.ALPHANUM :
switch (LA1) {
case '/' :
case '*' :
case ',' :
case '-' :
case '_' :
case ':' :
case '.' :
case '@' :
if (LA(2) == (char) - 1
|| Character.isWhitespace(LA(2))) {
consume();
break;
}
TextToken last = null;
while ((next = nextTerminalToken(wildcards)) != null) {
if (next.getType() == TextToken.EOF
|| next.getType() == TextToken.WS)
break;
last = next;
}
if (last != null)
token = new TextToken(TextToken.ALPHANUM, text, token.startOffset(), last.endOffset());
else
token = new TextToken(TextToken.ALPHANUM, text, token.startOffset(), pos);
}
return token;
default :
// fall through to start of while loop
}
}
} catch (Exception e) {
System.out.println("text: " + text);
e.printStackTrace();
return null;
}
}
protected TextToken number() {
TextToken token = new TextToken(TextToken.NUMBER, text, pos);
int oldPos = pos;
while (LA(1) != (char) - 1 && Character.isDigit(LA(1))) {
token.consumeNext();
consume();
}
if (Character.isLetter(LA(1))) {
pos = oldPos;
return null;
}
return token;
}
protected TextToken p() {
temp.set(TextToken.P, text, pos);
temp.consumeNext();
consume();
return temp;
}
public void setText(CharSequence text) {
pos = 0;
len = text.length();
this.text = text;
}
public void setText(CharSequence text, int offset) {
pos = offset;
len = text.length();
this.text = text;
}
protected TextToken whitespace() {
consume();
return TextToken.WS_TOKEN;
}
/**
* The code ranges defined here should be interpreted as 1-char
* tokens.
*/
private static final boolean singleCharToken(char ch) {
return
// CJK Radicals Supplement
(ch >= '\u2E80' && ch <= '\u2EFF') ||
// KangXi Radicals
(ch >= '\u2F00' && ch <= '\u2FDF') ||
// Ideographic Description Characters
(ch >= '\u2FF0' && ch <= '\u2FFF') ||
// Enclosed CJK Letters and Months
(ch >= '\u3200' && ch <= '\u32FF') ||
// CJK Compatibility
(ch >= '\u3300' && ch <= '\u33FF') ||
// CJK Unified Ideographs Extension A
(ch >= '\u3400' && ch <= '\u4DB5') ||
// Yijing Hexagram Symbols
(ch >= '\u4DC0' && ch <= '\u4DFF') ||
// CJK Unified Ideographs
(ch >= '\u4E00' && ch <= '\u9FFF') ||
// CJK Compatibility Ideographs
(ch >= '\uF900' && ch <= '\uFAFF') ||
// CJK Compatibility Forms
(ch >= '\uFE30' && ch <= '\uFE4F');
}
/**
* These codepoints should not be broken into tokens.
*/
private final static boolean nonBreakingChar(char ch) {
return
// Hiragana
(ch >= '\u3040' && ch <= '\u309F') ||
// Katakana
(ch >= '\u30A0' && ch <= '\u30FF') ||
// Bopomofo
(ch >= '\u3100' && ch <= '\u312F') ||
// Hangul Compatibility Jamo
(ch >= '\u3130' && ch <= '\u318F') ||
// Kanbun
(ch >= '\u3190' && ch <= '\u319F') ||
// Bopomofo Extended
(ch >= '\u31A0' && ch <= '\u31BF') ||
// Katakana Phonetic Extensions
(ch >= '\u31F0' && ch <= '\u31FF') ||
// Hangul Syllables
(ch >= '\uAC00' && ch <= '\uD7A3');
}
private final boolean is_mark(char ch) {
return (ch > '\u093d' && ch < '\u094c');
}
public static void main(String args[]) {
String t1 = "\u4ED6\u4E3A\u8FD9\u9879\u5DE5\u7A0B\u6295\u5165\u4E86\u5341\u4E09\u5E74\u65F6\u95F4\u3002";
SimpleTokenizer tokenizer = new SimpleTokenizer();
tokenizer.setText(t1);
TextToken token = tokenizer.nextToken(false);
while(token != null && token.getType() != TextToken.EOF) {
System.out.println(token.getText());
token = tokenizer.nextToken(false);
}
}
}
| NCIP/cadsr-cgmdr-nci-uk | src/org/exist/storage/analysis/SimpleTokenizer.java | Java | bsd-3-clause | 10,777 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <set>
#include <utility>
#include "chrome/browser/tab_contents/render_view_context_menu.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/autocomplete/autocomplete_classifier.h"
#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/prefs/pref_member.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/printing/print_preview_context_menu_observer.h"
#include "chrome/browser/printing/print_preview_tab_controller.h"
#include "chrome/browser/printing/print_view_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_service.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/speech/chrome_speech_recognition_preferences.h"
#include "chrome/browser/spellchecker/spellcheck_host.h"
#include "chrome/browser/spellchecker/spellcheck_host_metrics.h"
#include "chrome/browser/tab_contents/retargeting_details.h"
#include "chrome/browser/tab_contents/spellchecker_submenu_observer.h"
#include "chrome/browser/tab_contents/spelling_menu_observer.h"
#include "chrome/browser/translate/translate_manager.h"
#include "chrome/browser/translate/translate_prefs.h"
#include "chrome/browser/translate/translate_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/search_engines/search_engine_tab_helper.h"
#include "chrome/browser/ui/tab_contents/core_tab_helper.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/browser/view_type_utils.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/net/url_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/print_messages.h"
#include "chrome/common/spellcheck_messages.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/download_manager.h"
#include "content/public/browser/download_save_info.h"
#include "content/public/browser/download_url_parameters.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_restriction.h"
#include "content/public/common/ssl_status.h"
#include "grit/generated_resources.h"
#include "net/base/escape.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebMediaPlayerAction.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginAction.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/text/text_elider.h"
#include "ui/gfx/favicon_size.h"
#include "webkit/glue/webmenuitem.h"
#ifdef FILE_MANAGER_EXTENSION
#include "chrome/browser/chromeos/extensions/file_manager_util.h"
#endif
using WebKit::WebContextMenuData;
using WebKit::WebMediaPlayerAction;
using WebKit::WebPluginAction;
using WebKit::WebString;
using WebKit::WebURL;
using content::BrowserContext;
using content::ChildProcessSecurityPolicy;
using content::DownloadManager;
using content::DownloadUrlParameters;
using content::NavigationController;
using content::NavigationEntry;
using content::OpenURLParams;
using content::RenderViewHost;
using content::SSLStatus;
using content::UserMetricsAction;
using content::WebContents;
using extensions::Extension;
using extensions::MenuItem;
using extensions::MenuManager;
namespace {
// Usually a new tab is expected where this function is used,
// however users should be able to open a tab in background
// or in a new window.
WindowOpenDisposition ForceNewTabDispositionFromEventFlags(
int event_flags) {
WindowOpenDisposition disposition =
chrome::DispositionFromEventFlags(event_flags);
return disposition == CURRENT_TAB ? NEW_FOREGROUND_TAB : disposition;
}
bool IsCustomItemEnabled(const std::vector<WebMenuItem>& items, int id) {
DCHECK(id >= IDC_CONTENT_CONTEXT_CUSTOM_FIRST &&
id <= IDC_CONTENT_CONTEXT_CUSTOM_LAST);
for (size_t i = 0; i < items.size(); ++i) {
int action_id = IDC_CONTENT_CONTEXT_CUSTOM_FIRST + items[i].action;
if (action_id == id)
return items[i].enabled;
if (items[i].type == WebMenuItem::SUBMENU) {
if (IsCustomItemEnabled(items[i].submenu, id))
return true;
}
}
return false;
}
bool IsCustomItemChecked(const std::vector<WebMenuItem>& items, int id) {
DCHECK(id >= IDC_CONTENT_CONTEXT_CUSTOM_FIRST &&
id <= IDC_CONTENT_CONTEXT_CUSTOM_LAST);
for (size_t i = 0; i < items.size(); ++i) {
int action_id = IDC_CONTENT_CONTEXT_CUSTOM_FIRST + items[i].action;
if (action_id == id)
return items[i].checked;
if (items[i].type == WebMenuItem::SUBMENU) {
if (IsCustomItemChecked(items[i].submenu, id))
return true;
}
}
return false;
}
const size_t kMaxCustomMenuDepth = 5;
const size_t kMaxCustomMenuTotalItems = 1000;
void AddCustomItemsToMenu(const std::vector<WebMenuItem>& items,
size_t depth,
size_t* total_items,
ui::SimpleMenuModel::Delegate* delegate,
ui::SimpleMenuModel* menu_model) {
if (depth > kMaxCustomMenuDepth) {
LOG(ERROR) << "Custom menu too deeply nested.";
return;
}
for (size_t i = 0; i < items.size(); ++i) {
if (IDC_CONTENT_CONTEXT_CUSTOM_FIRST + items[i].action >=
IDC_CONTENT_CONTEXT_CUSTOM_LAST) {
LOG(ERROR) << "Custom menu action value too big.";
return;
}
if (*total_items >= kMaxCustomMenuTotalItems) {
LOG(ERROR) << "Custom menu too large (too many items).";
return;
}
(*total_items)++;
switch (items[i].type) {
case WebMenuItem::OPTION:
menu_model->AddItem(
items[i].action + IDC_CONTENT_CONTEXT_CUSTOM_FIRST,
items[i].label);
break;
case WebMenuItem::CHECKABLE_OPTION:
menu_model->AddCheckItem(
items[i].action + IDC_CONTENT_CONTEXT_CUSTOM_FIRST,
items[i].label);
break;
case WebMenuItem::GROUP:
// TODO(viettrungluu): I don't know what this is supposed to do.
NOTREACHED();
break;
case WebMenuItem::SEPARATOR:
menu_model->AddSeparator();
break;
case WebMenuItem::SUBMENU: {
ui::SimpleMenuModel* submenu = new ui::SimpleMenuModel(delegate);
AddCustomItemsToMenu(items[i].submenu, depth + 1, total_items, delegate,
submenu);
menu_model->AddSubMenu(
items[i].action + IDC_CONTENT_CONTEXT_CUSTOM_FIRST,
items[i].label,
submenu);
break;
}
default:
NOTREACHED();
break;
}
}
}
bool ShouldShowTranslateItem(const GURL& page_url) {
if (page_url.SchemeIs("chrome"))
return false;
#ifdef FILE_MANAGER_EXTENSION
if (page_url.SchemeIs("chrome-extension") &&
page_url.DomainIs(kFileBrowserDomain))
return false;
#endif
return true;
}
} // namespace
// static
const size_t RenderViewContextMenu::kMaxExtensionItemTitleLength = 75;
// static
const size_t RenderViewContextMenu::kMaxSelectionTextLength = 50;
// static
bool RenderViewContextMenu::IsDevToolsURL(const GURL& url) {
return url.SchemeIs(chrome::kChromeDevToolsScheme) &&
url.host() == chrome::kChromeUIDevToolsHost;
}
// static
bool RenderViewContextMenu::IsInternalResourcesURL(const GURL& url) {
if (!url.SchemeIs(chrome::kChromeUIScheme))
return false;
return url.host() == chrome::kChromeUISyncResourcesHost;
}
static const int kSpellcheckRadioGroup = 1;
RenderViewContextMenu::RenderViewContextMenu(
WebContents* web_contents,
const content::ContextMenuParams& params)
: params_(params),
source_web_contents_(web_contents),
profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())),
ALLOW_THIS_IN_INITIALIZER_LIST(menu_model_(this)),
external_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(speech_input_submenu_model_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(bidi_submenu_model_(this)),
ALLOW_THIS_IN_INITIALIZER_LIST(protocol_handler_submenu_model_(this)),
protocol_handler_registry_(profile_->GetProtocolHandlerRegistry()) {
}
RenderViewContextMenu::~RenderViewContextMenu() {
}
// Menu construction functions -------------------------------------------------
void RenderViewContextMenu::Init() {
InitMenu();
PlatformInit();
}
void RenderViewContextMenu::Cancel() {
PlatformCancel();
}
static bool ExtensionPatternMatch(const URLPatternSet& patterns,
const GURL& url) {
// No patterns means no restriction, so that implicitly matches.
if (patterns.is_empty())
return true;
return patterns.MatchesURL(url);
}
// static
bool RenderViewContextMenu::ExtensionContextAndPatternMatch(
const content::ContextMenuParams& params,
MenuItem::ContextList contexts,
const URLPatternSet& target_url_patterns) {
bool has_link = !params.link_url.is_empty();
bool has_selection = !params.selection_text.empty();
bool in_frame = !params.frame_url.is_empty();
if (contexts.Contains(MenuItem::ALL) ||
(has_selection && contexts.Contains(MenuItem::SELECTION)) ||
(params.is_editable && contexts.Contains(MenuItem::EDITABLE)) ||
(in_frame && contexts.Contains(MenuItem::FRAME)))
return true;
if (has_link && contexts.Contains(MenuItem::LINK) &&
ExtensionPatternMatch(target_url_patterns, params.link_url))
return true;
switch (params.media_type) {
case WebContextMenuData::MediaTypeImage:
if (contexts.Contains(MenuItem::IMAGE) &&
ExtensionPatternMatch(target_url_patterns, params.src_url))
return true;
break;
case WebContextMenuData::MediaTypeVideo:
if (contexts.Contains(MenuItem::VIDEO) &&
ExtensionPatternMatch(target_url_patterns, params.src_url))
return true;
break;
case WebContextMenuData::MediaTypeAudio:
if (contexts.Contains(MenuItem::AUDIO) &&
ExtensionPatternMatch(target_url_patterns, params.src_url))
return true;
break;
default:
break;
}
// PAGE is the least specific context, so we only examine that if none of the
// other contexts apply (except for FRAME, which is included in PAGE for
// backwards compatibility).
if (!has_link && !has_selection && !params.is_editable &&
params.media_type == WebContextMenuData::MediaTypeNone &&
contexts.Contains(MenuItem::PAGE))
return true;
return false;
}
static const GURL& GetDocumentURL(const content::ContextMenuParams& params) {
return params.frame_url.is_empty() ? params.page_url : params.frame_url;
}
// Given a list of items, returns the ones that match given the contents
// of |params| and the profile.
// static
MenuItem::List RenderViewContextMenu::GetRelevantExtensionItems(
const MenuItem::List& items,
const content::ContextMenuParams& params,
Profile* profile,
bool can_cross_incognito) {
MenuItem::List result;
for (MenuItem::List::const_iterator i = items.begin();
i != items.end(); ++i) {
const MenuItem* item = *i;
if (!ExtensionContextAndPatternMatch(params, item->contexts(),
item->target_url_patterns()))
continue;
const GURL& document_url = GetDocumentURL(params);
if (!ExtensionPatternMatch(item->document_url_patterns(), document_url))
continue;
if (item->id().incognito == profile->IsOffTheRecord() ||
can_cross_incognito)
result.push_back(*i);
}
return result;
}
void RenderViewContextMenu::AppendExtensionItems(
const std::string& extension_id, int* index) {
ExtensionService* service = profile_->GetExtensionService();
MenuManager* manager = service->menu_manager();
const Extension* extension = service->GetExtensionById(extension_id, false);
DCHECK_GE(*index, 0);
int max_index =
IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST - IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST;
if (!extension || *index >= max_index)
return;
// Find matching items.
const MenuItem::List* all_items = manager->MenuItems(extension_id);
if (!all_items || all_items->empty())
return;
bool can_cross_incognito = service->CanCrossIncognito(extension);
MenuItem::List items =
GetRelevantExtensionItems(*all_items, params_, profile_,
can_cross_incognito);
if (items.empty())
return;
// If this is the first extension-provided menu item, and there are other
// items in the menu, add a separator.
if (*index == 0 && menu_model_.GetItemCount())
menu_model_.AddSeparator();
int menu_id = IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST + (*index)++;
// Extensions are only allowed one top-level slot (and it can't be a radio or
// checkbox item because we are going to put the extension icon next to it).
// If they have more than that, we automatically push them into a submenu.
string16 title;
MenuItem::List submenu_items;
if (items.size() > 1 || items[0]->type() != MenuItem::NORMAL) {
title = UTF8ToUTF16(extension->name());
submenu_items = items;
} else {
MenuItem* item = items[0];
extension_item_map_[menu_id] = item->id();
title = item->TitleWithReplacement(PrintableSelectionText(),
kMaxExtensionItemTitleLength);
submenu_items = GetRelevantExtensionItems(item->children(), params_,
profile_, can_cross_incognito);
}
// Now add our item(s) to the menu_model_.
if (submenu_items.empty()) {
menu_model_.AddItem(menu_id, title);
} else {
ui::SimpleMenuModel* submenu = new ui::SimpleMenuModel(this);
extension_menu_models_.push_back(submenu);
menu_model_.AddSubMenu(menu_id, title, submenu);
RecursivelyAppendExtensionItems(submenu_items, can_cross_incognito, submenu,
index);
}
SetExtensionIcon(extension_id);
}
void RenderViewContextMenu::RecursivelyAppendExtensionItems(
const MenuItem::List& items,
bool can_cross_incognito,
ui::SimpleMenuModel* menu_model,
int* index) {
string16 selection_text = PrintableSelectionText();
MenuItem::Type last_type = MenuItem::NORMAL;
int radio_group_id = 1;
for (MenuItem::List::const_iterator i = items.begin();
i != items.end(); ++i) {
MenuItem* item = *i;
// If last item was of type radio but the current one isn't, auto-insert
// a separator. The converse case is handled below.
if (last_type == MenuItem::RADIO &&
item->type() != MenuItem::RADIO) {
menu_model->AddSeparator();
last_type = MenuItem::SEPARATOR;
}
int menu_id = IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST + (*index)++;
if (menu_id >= IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST)
return;
extension_item_map_[menu_id] = item->id();
string16 title = item->TitleWithReplacement(selection_text,
kMaxExtensionItemTitleLength);
if (item->type() == MenuItem::NORMAL) {
MenuItem::List children =
GetRelevantExtensionItems(item->children(), params_,
profile_, can_cross_incognito);
if (children.empty()) {
menu_model->AddItem(menu_id, title);
} else {
ui::SimpleMenuModel* submenu = new ui::SimpleMenuModel(this);
extension_menu_models_.push_back(submenu);
menu_model->AddSubMenu(menu_id, title, submenu);
RecursivelyAppendExtensionItems(children, can_cross_incognito,
submenu, index);
}
} else if (item->type() == MenuItem::CHECKBOX) {
menu_model->AddCheckItem(menu_id, title);
} else if (item->type() == MenuItem::RADIO) {
if (i != items.begin() &&
last_type != MenuItem::RADIO) {
radio_group_id++;
// Auto-append a separator if needed.
if (last_type != MenuItem::SEPARATOR)
menu_model->AddSeparator();
}
menu_model->AddRadioItem(menu_id, title, radio_group_id);
} else if (item->type() == MenuItem::SEPARATOR) {
if (i != items.begin() && last_type != MenuItem::SEPARATOR) {
menu_model->AddSeparator();
}
}
last_type = item->type();
}
}
void RenderViewContextMenu::SetExtensionIcon(const std::string& extension_id) {
ExtensionService* service = profile_->GetExtensionService();
MenuManager* menu_manager = service->menu_manager();
int index = menu_model_.GetItemCount() - 1;
DCHECK_GE(index, 0);
const SkBitmap& icon = menu_manager->GetIconForExtension(extension_id);
DCHECK(icon.width() == gfx::kFaviconSize);
DCHECK(icon.height() == gfx::kFaviconSize);
menu_model_.SetIcon(index, icon);
}
void RenderViewContextMenu::AppendAllExtensionItems() {
extension_item_map_.clear();
ExtensionService* service = profile_->GetExtensionService();
if (!service)
return; // In unit-tests, we may not have an ExtensionService.
MenuManager* menu_manager = service->menu_manager();
// Get a list of extension id's that have context menu items, and sort it by
// the extension's name.
std::set<std::string> ids = menu_manager->ExtensionIds();
std::vector<std::pair<std::string, std::string> > sorted_ids;
for (std::set<std::string>::iterator i = ids.begin(); i != ids.end(); ++i) {
const Extension* extension = service->GetExtensionById(*i, false);
// Platform apps have their context menus created directly in
// AppendPlatformAppItems.
if (extension && !extension->is_platform_app())
sorted_ids.push_back(
std::pair<std::string, std::string>(extension->name(), *i));
}
// TODO(asargent) - See if this works properly for i18n names (bug 32363).
std::sort(sorted_ids.begin(), sorted_ids.end());
if (sorted_ids.empty())
return;
int index = 0;
base::TimeTicks begin = base::TimeTicks::Now();
std::vector<std::pair<std::string, std::string> >::const_iterator i;
for (i = sorted_ids.begin();
i != sorted_ids.end(); ++i) {
AppendExtensionItems(i->second, &index);
}
UMA_HISTOGRAM_TIMES("Extensions.ContextMenus_BuildTime",
base::TimeTicks::Now() - begin);
UMA_HISTOGRAM_COUNTS("Extensions.ContextMenus_ItemCount", index);
}
void RenderViewContextMenu::InitMenu() {
chrome::ViewType view_type = chrome::GetViewType(source_web_contents_);
if (view_type == chrome::VIEW_TYPE_APP_SHELL) {
AppendPlatformAppItems();
return;
} else if (view_type == chrome::VIEW_TYPE_EXTENSION_POPUP) {
AppendPopupExtensionItems();
return;
}
bool has_link = !params_.unfiltered_link_url.is_empty();
bool has_selection = !params_.selection_text.empty();
if (AppendCustomItems()) {
// If there's a selection, don't early return when there are custom items,
// but fall through to adding the normal ones after the custom ones.
if (has_selection) {
menu_model_.AddSeparator();
} else {
// Don't add items for Pepper menu.
if (!params_.custom_context.is_pepper_menu)
AppendDeveloperItems();
return;
}
}
// When no special node or text is selected and selection has no link,
// show page items.
if (params_.media_type == WebContextMenuData::MediaTypeNone &&
!has_link &&
!params_.is_editable &&
!has_selection) {
if (!params_.page_url.is_empty()) {
bool is_devtools = IsDevToolsURL(params_.page_url);
if (!is_devtools && !IsInternalResourcesURL(params_.page_url)) {
AppendPageItems();
// Merge in frame items if we clicked within a frame that needs them.
if (!params_.frame_url.is_empty()) {
is_devtools = IsDevToolsURL(params_.frame_url);
if (!is_devtools && !IsInternalResourcesURL(params_.frame_url)) {
menu_model_.AddSeparator();
AppendFrameItems();
}
}
}
} else {
DCHECK(params_.frame_url.is_empty());
}
}
if (has_link) {
AppendLinkItems();
if (params_.media_type != WebContextMenuData::MediaTypeNone)
menu_model_.AddSeparator();
}
switch (params_.media_type) {
case WebContextMenuData::MediaTypeNone:
break;
case WebContextMenuData::MediaTypeImage:
AppendImageItems();
break;
case WebContextMenuData::MediaTypeVideo:
AppendVideoItems();
break;
case WebContextMenuData::MediaTypeAudio:
AppendAudioItems();
break;
case WebContextMenuData::MediaTypePlugin:
AppendPluginItems();
break;
#ifdef WEBCONTEXT_MEDIATYPEFILE_DEFINED
case WebContextMenuData::MediaTypeFile:
break;
#endif
}
if (params_.is_editable)
AppendEditableItems();
else if (has_selection)
AppendCopyItem();
if (has_selection)
AppendSearchProvider();
if (!IsDevToolsURL(params_.page_url))
AppendAllExtensionItems();
AppendDeveloperItems();
if (!print_preview_menu_observer_.get()) {
TabContents* tab_contents =
TabContents::FromWebContents(source_web_contents_);
print_preview_menu_observer_.reset(
new PrintPreviewContextMenuObserver(tab_contents));
}
observers_.AddObserver(print_preview_menu_observer_.get());
}
const Extension* RenderViewContextMenu::GetExtension() const {
extensions::ExtensionSystem* system =
extensions::ExtensionSystem::Get(profile_);
// There is no process manager in some tests.
if (!system->process_manager())
return NULL;
return system->process_manager()->GetExtensionForRenderViewHost(
source_web_contents_->GetRenderViewHost());
}
void RenderViewContextMenu::AppendPlatformAppItems() {
const Extension* platform_app = GetExtension();
DCHECK(platform_app);
DCHECK(platform_app->is_platform_app());
int index = 0;
AppendExtensionItems(platform_app->id(), &index);
// Add dev tools for unpacked extensions.
if (platform_app->location() == Extension::LOAD) {
menu_model_.AddItemWithStringId(IDC_RELOAD, IDS_CONTENT_CONTEXT_RELOAD);
AppendDeveloperItems();
}
}
void RenderViewContextMenu::AppendPopupExtensionItems() {
bool has_selection = !params_.selection_text.empty();
if (params_.is_editable)
AppendEditableItems();
else if (has_selection)
AppendCopyItem();
if (has_selection)
AppendSearchProvider();
AppendAllExtensionItems();
AppendDeveloperItems();
}
void RenderViewContextMenu::AddMenuItem(int command_id,
const string16& title) {
menu_model_.AddItem(command_id, title);
}
void RenderViewContextMenu::AddCheckItem(int command_id,
const string16& title) {
menu_model_.AddCheckItem(command_id, title);
}
void RenderViewContextMenu::AddSeparator() {
menu_model_.AddSeparator();
}
void RenderViewContextMenu::AddSubMenu(int command_id,
const string16& label,
ui::MenuModel* model) {
menu_model_.AddSubMenu(command_id, label, model);
}
void RenderViewContextMenu::UpdateMenuItem(int command_id,
bool enabled,
bool hidden,
const string16& label) {
// This function needs platform-specific implementation.
NOTIMPLEMENTED();
}
RenderViewHost* RenderViewContextMenu::GetRenderViewHost() const {
return source_web_contents_->GetRenderViewHost();
}
WebContents* RenderViewContextMenu::GetWebContents() const {
return source_web_contents_;
}
Profile* RenderViewContextMenu::GetProfile() const {
return profile_;
}
bool RenderViewContextMenu::AppendCustomItems() {
size_t total_items = 0;
AddCustomItemsToMenu(params_.custom_items, 0, &total_items, this,
&menu_model_);
return total_items > 0;
}
void RenderViewContextMenu::AppendDeveloperItems() {
// Show Inspect Element in DevTools itself only in case of the debug
// devtools build.
bool show_developer_items = !IsDevToolsURL(params_.page_url);
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kDebugDevToolsFrontend))
show_developer_items = true;
#if defined(DEBUG_DEVTOOLS)
show_developer_items = true;
#endif
if (!show_developer_items)
return;
// In the DevTools popup menu, "developer items" is normally the only
// section, so omit the separator there.
if (menu_model_.GetItemCount() > 0)
menu_model_.AddSeparator();
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_INSPECTELEMENT,
IDS_CONTENT_CONTEXT_INSPECTELEMENT);
}
void RenderViewContextMenu::AppendLinkItems() {
if (!params_.link_url.is_empty()) {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB,
IDS_CONTENT_CONTEXT_OPENLINKNEWTAB);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_OPENLINKNEWWINDOW,
IDS_CONTENT_CONTEXT_OPENLINKNEWWINDOW);
if (params_.link_url.is_valid()) {
AppendProtocolHandlerSubMenu();
}
if (!external_) {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_OPENLINKOFFTHERECORD,
IDS_CONTENT_CONTEXT_OPENLINKOFFTHERECORD);
}
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_SAVELINKAS,
IDS_CONTENT_CONTEXT_SAVELINKAS);
}
menu_model_.AddItemWithStringId(
IDC_CONTENT_CONTEXT_COPYLINKLOCATION,
params_.link_url.SchemeIs(chrome::kMailToScheme) ?
IDS_CONTENT_CONTEXT_COPYEMAILADDRESS :
IDS_CONTENT_CONTEXT_COPYLINKLOCATION);
}
void RenderViewContextMenu::AppendImageItems() {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_SAVEIMAGEAS,
IDS_CONTENT_CONTEXT_SAVEIMAGEAS);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_COPYIMAGELOCATION,
IDS_CONTENT_CONTEXT_COPYIMAGELOCATION);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_COPYIMAGE,
IDS_CONTENT_CONTEXT_COPYIMAGE);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_OPENIMAGENEWTAB,
IDS_CONTENT_CONTEXT_OPENIMAGENEWTAB);
}
void RenderViewContextMenu::AppendAudioItems() {
AppendMediaItems();
menu_model_.AddSeparator();
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_SAVEAVAS,
IDS_CONTENT_CONTEXT_SAVEAUDIOAS);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_COPYAVLOCATION,
IDS_CONTENT_CONTEXT_COPYAUDIOLOCATION);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_OPENAVNEWTAB,
IDS_CONTENT_CONTEXT_OPENAUDIONEWTAB);
}
void RenderViewContextMenu::AppendVideoItems() {
AppendMediaItems();
menu_model_.AddSeparator();
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_SAVEAVAS,
IDS_CONTENT_CONTEXT_SAVEVIDEOAS);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_COPYAVLOCATION,
IDS_CONTENT_CONTEXT_COPYVIDEOLOCATION);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_OPENAVNEWTAB,
IDS_CONTENT_CONTEXT_OPENVIDEONEWTAB);
}
void RenderViewContextMenu::AppendMediaItems() {
int media_flags = params_.media_flags;
menu_model_.AddItemWithStringId(
IDC_CONTENT_CONTEXT_PLAYPAUSE,
media_flags & WebContextMenuData::MediaPaused ?
IDS_CONTENT_CONTEXT_PLAY :
IDS_CONTENT_CONTEXT_PAUSE);
menu_model_.AddItemWithStringId(
IDC_CONTENT_CONTEXT_MUTE,
media_flags & WebContextMenuData::MediaMuted ?
IDS_CONTENT_CONTEXT_UNMUTE :
IDS_CONTENT_CONTEXT_MUTE);
menu_model_.AddCheckItemWithStringId(IDC_CONTENT_CONTEXT_LOOP,
IDS_CONTENT_CONTEXT_LOOP);
menu_model_.AddCheckItemWithStringId(IDC_CONTENT_CONTEXT_CONTROLS,
IDS_CONTENT_CONTEXT_CONTROLS);
}
void RenderViewContextMenu::AppendPluginItems() {
if (params_.page_url == params_.src_url) {
// Full page plugin, so show page menu items.
if (params_.link_url.is_empty() && params_.selection_text.empty())
AppendPageItems();
} else {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_SAVEAVAS,
IDS_CONTENT_CONTEXT_SAVEPAGEAS);
menu_model_.AddItemWithStringId(IDC_PRINT, IDS_CONTENT_CONTEXT_PRINT);
}
if (params_.media_flags & WebContextMenuData::MediaCanRotate) {
if (menu_model_.GetItemCount() > 0)
menu_model_.AddSeparator();
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_ROTATECW,
IDS_CONTENT_CONTEXT_ROTATECW);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_ROTATECCW,
IDS_CONTENT_CONTEXT_ROTATECCW);
}
}
void RenderViewContextMenu::AppendPageItems() {
menu_model_.AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK);
menu_model_.AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD);
menu_model_.AddItemWithStringId(IDC_RELOAD, IDS_CONTENT_CONTEXT_RELOAD);
menu_model_.AddSeparator();
menu_model_.AddItemWithStringId(IDC_SAVE_PAGE,
IDS_CONTENT_CONTEXT_SAVEPAGEAS);
menu_model_.AddItemWithStringId(IDC_PRINT, IDS_CONTENT_CONTEXT_PRINT);
if (ShouldShowTranslateItem(params_.page_url)) {
std::string locale = g_browser_process->GetApplicationLocale();
locale = TranslateManager::GetLanguageCode(locale);
string16 language = l10n_util::GetDisplayNameForLocale(locale, locale,
true);
menu_model_.AddItem(
IDC_CONTENT_CONTEXT_TRANSLATE,
l10n_util::GetStringFUTF16(IDS_CONTENT_CONTEXT_TRANSLATE, language));
}
menu_model_.AddItemWithStringId(IDC_VIEW_SOURCE,
IDS_CONTENT_CONTEXT_VIEWPAGESOURCE);
// Only add View Page Info if there's a browser. This is a temporary thing
// while View Page Info crashes Chrome Frame; see http://crbug.com/120901.
// TODO(grt) Remove this once page info is back for Chrome Frame.
if (!external_) {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_VIEWPAGEINFO,
IDS_CONTENT_CONTEXT_VIEWPAGEINFO);
}
}
void RenderViewContextMenu::AppendFrameItems() {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_RELOADFRAME,
IDS_CONTENT_CONTEXT_RELOADFRAME);
// These two menu items have yet to be implemented.
// http://code.google.com/p/chromium/issues/detail?id=11827
// IDS_CONTENT_CONTEXT_SAVEFRAMEAS
// IDS_CONTENT_CONTEXT_PRINTFRAME
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_VIEWFRAMESOURCE,
IDS_CONTENT_CONTEXT_VIEWFRAMESOURCE);
// Only add View Frame Info if there's a browser. This is a temporary thing
// while View Frame Info crashes Chrome Frame; see http://crbug.com/120901.
// TODO(grt) Remove this once frame info is back for Chrome Frame.
if (!external_) {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_VIEWFRAMEINFO,
IDS_CONTENT_CONTEXT_VIEWFRAMEINFO);
}
}
void RenderViewContextMenu::AppendCopyItem() {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_COPY,
IDS_CONTENT_CONTEXT_COPY);
}
void RenderViewContextMenu::AppendSearchProvider() {
DCHECK(profile_);
TrimWhitespace(params_.selection_text, TRIM_ALL, ¶ms_.selection_text);
if (params_.selection_text.empty())
return;
ReplaceChars(params_.selection_text, AutocompleteMatch::kInvalidChars,
ASCIIToUTF16(" "), ¶ms_.selection_text);
AutocompleteMatch match;
AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
params_.selection_text, string16(), false, false, &match, NULL);
selection_navigation_url_ = match.destination_url;
if (!selection_navigation_url_.is_valid())
return;
string16 printable_selection_text = PrintableSelectionText();
// Escape "&" as "&&".
for (size_t i = printable_selection_text.find('&'); i != string16::npos;
i = printable_selection_text.find('&', i + 2))
printable_selection_text.insert(i, 1, '&');
if (match.transition == content::PAGE_TRANSITION_TYPED) {
if ((selection_navigation_url_ != params_.link_url) &&
ChildProcessSecurityPolicy::GetInstance()->IsWebSafeScheme(
selection_navigation_url_.scheme())) {
menu_model_.AddItem(
IDC_CONTENT_CONTEXT_GOTOURL,
l10n_util::GetStringFUTF16(IDS_CONTENT_CONTEXT_GOTOURL,
printable_selection_text));
}
} else {
const TemplateURL* const default_provider =
TemplateURLServiceFactory::GetForProfile(profile_)->
GetDefaultSearchProvider();
if (!default_provider)
return;
menu_model_.AddItem(
IDC_CONTENT_CONTEXT_SEARCHWEBFOR,
l10n_util::GetStringFUTF16(IDS_CONTENT_CONTEXT_SEARCHWEBFOR,
default_provider->short_name(),
printable_selection_text));
}
}
void RenderViewContextMenu::AppendEditableItems() {
AppendSpellingSuggestionsSubMenu();
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_UNDO,
IDS_CONTENT_CONTEXT_UNDO);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_REDO,
IDS_CONTENT_CONTEXT_REDO);
menu_model_.AddSeparator();
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_CUT,
IDS_CONTENT_CONTEXT_CUT);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_COPY,
IDS_CONTENT_CONTEXT_COPY);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_PASTE,
IDS_CONTENT_CONTEXT_PASTE);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_PASTE_AND_MATCH_STYLE,
IDS_CONTENT_CONTEXT_PASTE_AND_MATCH_STYLE);
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_DELETE,
IDS_CONTENT_CONTEXT_DELETE);
menu_model_.AddSeparator();
if (!params_.keyword_url.is_empty()) {
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_ADDSEARCHENGINE,
IDS_CONTENT_CONTEXT_ADDSEARCHENGINE);
menu_model_.AddSeparator();
}
AppendSpellcheckOptionsSubMenu();
AppendSpeechInputOptionsSubMenu();
#if defined(OS_MACOSX)
// OS X provides a contextual menu to set writing direction for BiDi
// languages.
// This functionality is exposed as a keyboard shortcut on Windows & Linux.
AppendBidiSubMenu();
#endif // OS_MACOSX
menu_model_.AddSeparator();
menu_model_.AddItemWithStringId(IDC_CONTENT_CONTEXT_SELECTALL,
IDS_CONTENT_CONTEXT_SELECTALL);
}
void RenderViewContextMenu::AppendSpellingSuggestionsSubMenu() {
if (!spelling_menu_observer_.get())
spelling_menu_observer_.reset(new SpellingMenuObserver(this));
observers_.AddObserver(spelling_menu_observer_.get());
spelling_menu_observer_->InitMenu(params_);
}
void RenderViewContextMenu::AppendSpellcheckOptionsSubMenu() {
if (!spellchecker_submenu_observer_.get()) {
spellchecker_submenu_observer_.reset(new SpellCheckerSubMenuObserver(
this, this, kSpellcheckRadioGroup));
}
spellchecker_submenu_observer_->InitMenu(params_);
observers_.AddObserver(spellchecker_submenu_observer_.get());
}
void RenderViewContextMenu::AppendSpeechInputOptionsSubMenu() {
if (params_.speech_input_enabled) {
speech_input_submenu_model_.AddCheckItem(
IDC_CONTENT_CONTEXT_SPEECH_INPUT_FILTER_PROFANITIES,
l10n_util::GetStringUTF16(
IDS_CONTENT_CONTEXT_SPEECH_INPUT_FILTER_PROFANITIES));
speech_input_submenu_model_.AddItemWithStringId(
IDC_CONTENT_CONTEXT_SPEECH_INPUT_ABOUT,
IDS_CONTENT_CONTEXT_SPEECH_INPUT_ABOUT);
menu_model_.AddSubMenu(
IDC_SPEECH_INPUT_MENU,
l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_SPEECH_INPUT_MENU),
&speech_input_submenu_model_);
}
}
#if defined(OS_MACOSX)
void RenderViewContextMenu::AppendBidiSubMenu() {
bidi_submenu_model_.AddCheckItem(IDC_WRITING_DIRECTION_DEFAULT,
l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_WRITING_DIRECTION_DEFAULT));
bidi_submenu_model_.AddCheckItem(IDC_WRITING_DIRECTION_LTR,
l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_WRITING_DIRECTION_LTR));
bidi_submenu_model_.AddCheckItem(IDC_WRITING_DIRECTION_RTL,
l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_WRITING_DIRECTION_RTL));
menu_model_.AddSubMenu(
IDC_WRITING_DIRECTION_MENU,
l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_WRITING_DIRECTION_MENU),
&bidi_submenu_model_);
}
#endif // OS_MACOSX
void RenderViewContextMenu::AppendProtocolHandlerSubMenu() {
const ProtocolHandlerRegistry::ProtocolHandlerList handlers =
GetHandlersForLinkUrl();
if (handlers.empty())
return;
size_t max = IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_LAST -
IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_FIRST;
for (size_t i = 0; i < handlers.size() && i <= max; i++) {
protocol_handler_submenu_model_.AddItem(
IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_FIRST + i,
handlers[i].title());
}
protocol_handler_submenu_model_.AddSeparator();
protocol_handler_submenu_model_.AddItem(
IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_SETTINGS,
l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_OPENLINKWITH_CONFIGURE));
menu_model_.AddSubMenu(
IDC_CONTENT_CONTEXT_OPENLINKWITH,
l10n_util::GetStringUTF16(IDS_CONTENT_CONTEXT_OPENLINKWITH),
&protocol_handler_submenu_model_);
}
MenuItem* RenderViewContextMenu::GetExtensionMenuItem(int id) const {
MenuManager* manager = profile_->GetExtensionService()->menu_manager();
std::map<int, MenuItem::Id>::const_iterator i =
extension_item_map_.find(id);
if (i != extension_item_map_.end()) {
MenuItem* item = manager->GetItemById(i->second);
if (item)
return item;
}
return NULL;
}
// Menu delegate functions -----------------------------------------------------
bool RenderViewContextMenu::IsCommandIdEnabled(int id) const {
// If this command is is added by one of our observers, we dispatch it to the
// observer.
ObserverListBase<RenderViewContextMenuObserver>::Iterator it(observers_);
RenderViewContextMenuObserver* observer;
while ((observer = it.GetNext()) != NULL) {
if (observer->IsCommandIdSupported(id))
return observer->IsCommandIdEnabled(id);
}
if (id == IDC_PRINT &&
(source_web_contents_->GetContentRestrictions() &
content::CONTENT_RESTRICTION_PRINT)) {
return false;
}
if (id == IDC_SAVE_PAGE &&
(source_web_contents_->GetContentRestrictions() &
content::CONTENT_RESTRICTION_SAVE)) {
return false;
}
// Allow Spell Check language items on sub menu for text area context menu.
if ((id >= IDC_SPELLCHECK_LANGUAGES_FIRST) &&
(id < IDC_SPELLCHECK_LANGUAGES_LAST)) {
return profile_->GetPrefs()->GetBoolean(prefs::kEnableSpellCheck);
}
// Custom items.
if (id >= IDC_CONTENT_CONTEXT_CUSTOM_FIRST &&
id <= IDC_CONTENT_CONTEXT_CUSTOM_LAST) {
return IsCustomItemEnabled(params_.custom_items, id);
}
// Extension items.
if (id >= IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST &&
id <= IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST) {
MenuItem* item = GetExtensionMenuItem(id);
// If this is the parent menu item, it is always enabled.
if (!item)
return true;
return item->enabled();
}
if (id >= IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_FIRST &&
id <= IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_LAST) {
return true;
}
IncognitoModePrefs::Availability incognito_avail =
IncognitoModePrefs::GetAvailability(profile_->GetPrefs());
switch (id) {
case IDC_BACK:
return source_web_contents_->GetController().CanGoBack();
case IDC_FORWARD:
return source_web_contents_->GetController().CanGoForward();
case IDC_RELOAD: {
TabContents* tab_contents =
TabContents::FromWebContents(source_web_contents_);
if (!tab_contents)
return false;
CoreTabHelperDelegate* core_delegate =
tab_contents->core_tab_helper()->delegate();
return !core_delegate || core_delegate->CanReloadContents(tab_contents);
}
case IDC_VIEW_SOURCE:
case IDC_CONTENT_CONTEXT_VIEWFRAMESOURCE:
return source_web_contents_->GetController().CanViewSource();
case IDC_CONTENT_CONTEXT_INSPECTELEMENT:
return IsDevCommandEnabled(id);
case IDC_CONTENT_CONTEXT_VIEWPAGEINFO:
return source_web_contents_->GetController().GetActiveEntry() != NULL;
case IDC_CONTENT_CONTEXT_TRANSLATE: {
TabContents* tab_contents =
TabContents::FromWebContents(source_web_contents_);
if (!tab_contents)
return false;
TranslateTabHelper* helper = tab_contents->translate_tab_helper();
std::string original_lang =
helper->language_state().original_language();
std::string target_lang = g_browser_process->GetApplicationLocale();
target_lang = TranslateManager::GetLanguageCode(target_lang);
// Note that we intentionally enable the menu even if the original and
// target languages are identical. This is to give a way to user to
// translate a page that might contains text fragments in a different
// language.
return !!(params_.edit_flags & WebContextMenuData::CanTranslate) &&
helper->language_state().page_translatable() &&
!original_lang.empty() && // Did we receive the page language yet?
// Only allow translating languages we explitly support and the
// unknown language (in which case the page language is detected on
// the server side).
(original_lang == chrome::kUnknownLanguageCode ||
TranslateManager::IsSupportedLanguage(original_lang)) &&
!helper->language_state().IsPageTranslated() &&
!source_web_contents_->GetInterstitialPage() &&
TranslateManager::IsTranslatableURL(params_.page_url) &&
// There are some application locales which can't be used as a
// target language for translation.
TranslateManager::IsSupportedLanguage(target_lang);
}
case IDC_CONTENT_CONTEXT_OPENLINKNEWTAB:
case IDC_CONTENT_CONTEXT_OPENLINKNEWWINDOW:
return params_.link_url.is_valid();
case IDC_CONTENT_CONTEXT_COPYLINKLOCATION:
return params_.unfiltered_link_url.is_valid();
case IDC_CONTENT_CONTEXT_SAVELINKAS: {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
// Test if file-selection dialogs are forbidden by policy.
if (!local_state->GetBoolean(prefs::kAllowFileSelectionDialogs))
return false;
return params_.link_url.is_valid() &&
ProfileIOData::IsHandledProtocol(params_.link_url.scheme());
}
case IDC_CONTENT_CONTEXT_SAVEIMAGEAS: {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
// Test if file-selection dialogs are forbidden by policy.
if (!local_state->GetBoolean(prefs::kAllowFileSelectionDialogs))
return false;
return params_.src_url.is_valid() &&
ProfileIOData::IsHandledProtocol(params_.src_url.scheme());
}
case IDC_CONTENT_CONTEXT_OPENIMAGENEWTAB:
// The images shown in the most visited thumbnails do not currently open
// in a new tab as they should. Disabling this context menu option for
// now, as a quick hack, before we resolve this issue (Issue = 2608).
// TODO(sidchat): Enable this option once this issue is resolved.
if (params_.src_url.scheme() == chrome::kChromeUIScheme ||
!params_.src_url.is_valid())
return false;
return true;
case IDC_CONTENT_CONTEXT_COPYIMAGE:
return !params_.is_image_blocked;
// Media control commands should all be disabled if the player is in an
// error state.
case IDC_CONTENT_CONTEXT_PLAYPAUSE:
case IDC_CONTENT_CONTEXT_LOOP:
return (params_.media_flags &
WebContextMenuData::MediaInError) == 0;
// Mute and unmute should also be disabled if the player has no audio.
case IDC_CONTENT_CONTEXT_MUTE:
return (params_.media_flags &
WebContextMenuData::MediaHasAudio) != 0 &&
(params_.media_flags &
WebContextMenuData::MediaInError) == 0;
// Media controls can be toggled only for video player. If we toggle
// controls for audio then the player disappears, and there is no way to
// return it back.
case IDC_CONTENT_CONTEXT_CONTROLS:
return (params_.media_flags &
WebContextMenuData::MediaHasVideo) != 0;
case IDC_CONTENT_CONTEXT_ROTATECW:
case IDC_CONTENT_CONTEXT_ROTATECCW:
return
(params_.media_flags & WebContextMenuData::MediaCanRotate) != 0;
case IDC_CONTENT_CONTEXT_COPYAVLOCATION:
case IDC_CONTENT_CONTEXT_COPYIMAGELOCATION:
return params_.src_url.is_valid();
case IDC_CONTENT_CONTEXT_SAVEAVAS: {
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
// Test if file-selection dialogs are forbidden by policy.
if (!local_state->GetBoolean(prefs::kAllowFileSelectionDialogs))
return false;
const GURL& url = params_.src_url;
return (params_.media_flags & WebContextMenuData::MediaCanSave) &&
url.is_valid() && ProfileIOData::IsHandledProtocol(url.scheme()) &&
// Do not save the preview PDF on the print preview page.
!(printing::PrintPreviewTabController::IsPrintPreviewURL(url));
}
case IDC_CONTENT_CONTEXT_OPENAVNEWTAB:
return true;
case IDC_SAVE_PAGE: {
TabContents* tab_contents =
TabContents::FromWebContents(source_web_contents_);
if (!tab_contents)
return false;
CoreTabHelperDelegate* core_delegate =
tab_contents->core_tab_helper()->delegate();
if (core_delegate && !core_delegate->CanSaveContents(tab_contents))
return false;
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
// Test if file-selection dialogs are forbidden by policy.
if (!local_state->GetBoolean(prefs::kAllowFileSelectionDialogs))
return false;
// Instead of using GetURL here, we use url() (which is the "real" url of
// the page) from the NavigationEntry because its reflects their origin
// rather than the display one (returned by GetURL) which may be
// different (like having "view-source:" on the front).
NavigationEntry* active_entry =
source_web_contents_->GetController().GetActiveEntry();
return download_util::IsSavableURL(
(active_entry) ? active_entry->GetURL() : GURL());
}
case IDC_CONTENT_CONTEXT_RELOADFRAME:
return params_.frame_url.is_valid();
case IDC_CONTENT_CONTEXT_UNDO:
return !!(params_.edit_flags & WebContextMenuData::CanUndo);
case IDC_CONTENT_CONTEXT_REDO:
return !!(params_.edit_flags & WebContextMenuData::CanRedo);
case IDC_CONTENT_CONTEXT_CUT:
return !!(params_.edit_flags & WebContextMenuData::CanCut);
case IDC_CONTENT_CONTEXT_COPY:
return !!(params_.edit_flags & WebContextMenuData::CanCopy);
case IDC_CONTENT_CONTEXT_PASTE:
case IDC_CONTENT_CONTEXT_PASTE_AND_MATCH_STYLE:
return !!(params_.edit_flags & WebContextMenuData::CanPaste);
case IDC_CONTENT_CONTEXT_DELETE:
return !!(params_.edit_flags & WebContextMenuData::CanDelete);
case IDC_CONTENT_CONTEXT_SELECTALL:
return !!(params_.edit_flags & WebContextMenuData::CanSelectAll);
case IDC_CONTENT_CONTEXT_OPENLINKOFFTHERECORD:
return !profile_->IsOffTheRecord() && params_.link_url.is_valid() &&
incognito_avail != IncognitoModePrefs::DISABLED;
case IDC_PRINT:
if (g_browser_process->local_state() &&
!g_browser_process->local_state()->GetBoolean(
prefs::kPrintingEnabled)) {
return false;
}
return params_.media_type == WebContextMenuData::MediaTypeNone ||
params_.media_flags & WebContextMenuData::MediaCanPrint;
case IDC_CONTENT_CONTEXT_SEARCHWEBFOR:
case IDC_CONTENT_CONTEXT_GOTOURL:
case IDC_SPELLPANEL_TOGGLE:
case IDC_CONTENT_CONTEXT_LANGUAGE_SETTINGS:
case IDC_CONTENT_CONTEXT_VIEWFRAMEINFO:
return true;
case IDC_CHECK_SPELLING_WHILE_TYPING:
return profile_->GetPrefs()->GetBoolean(prefs::kEnableSpellCheck);
#if defined(OS_MACOSX)
case IDC_WRITING_DIRECTION_DEFAULT: // Provided to match OS defaults.
return params_.writing_direction_default &
WebContextMenuData::CheckableMenuItemEnabled;
case IDC_WRITING_DIRECTION_RTL:
return params_.writing_direction_right_to_left &
WebContextMenuData::CheckableMenuItemEnabled;
case IDC_WRITING_DIRECTION_LTR:
return params_.writing_direction_left_to_right &
WebContextMenuData::CheckableMenuItemEnabled;
case IDC_WRITING_DIRECTION_MENU:
return true;
#elif defined(OS_POSIX)
// TODO(suzhe): this should not be enabled for password fields.
case IDC_INPUT_METHODS_MENU:
return true;
#endif
case IDC_CONTENT_CONTEXT_ADDSEARCHENGINE:
return !params_.keyword_url.is_empty();
case IDC_SPELLCHECK_MENU:
return true;
case IDC_CONTENT_CONTEXT_SPEECH_INPUT_FILTER_PROFANITIES:
case IDC_CONTENT_CONTEXT_SPEECH_INPUT_ABOUT:
case IDC_SPEECH_INPUT_MENU:
return true;
case IDC_CONTENT_CONTEXT_OPENLINKWITH:
return true;
case IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_SETTINGS:
return true;
default:
NOTREACHED();
return false;
}
}
bool RenderViewContextMenu::IsCommandIdChecked(int id) const {
// If this command is is added by one of our observers, we dispatch it to the
// observer.
ObserverListBase<RenderViewContextMenuObserver>::Iterator it(observers_);
RenderViewContextMenuObserver* observer;
while ((observer = it.GetNext()) != NULL) {
if (observer->IsCommandIdSupported(id))
return observer->IsCommandIdChecked(id);
}
// See if the video is set to looping.
if (id == IDC_CONTENT_CONTEXT_LOOP) {
return (params_.media_flags &
WebContextMenuData::MediaLoop) != 0;
}
if (id == IDC_CONTENT_CONTEXT_CONTROLS) {
return (params_.media_flags &
WebContextMenuData::MediaControlRootElement) != 0;
}
// Custom items.
if (id >= IDC_CONTENT_CONTEXT_CUSTOM_FIRST &&
id <= IDC_CONTENT_CONTEXT_CUSTOM_LAST) {
return IsCustomItemChecked(params_.custom_items, id);
}
// Extension items.
if (id >= IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST &&
id <= IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST) {
MenuItem* item = GetExtensionMenuItem(id);
if (item)
return item->checked();
else
return false;
}
#if defined(OS_MACOSX)
if (id == IDC_WRITING_DIRECTION_DEFAULT)
return params_.writing_direction_default &
WebContextMenuData::CheckableMenuItemChecked;
if (id == IDC_WRITING_DIRECTION_RTL)
return params_.writing_direction_right_to_left &
WebContextMenuData::CheckableMenuItemChecked;
if (id == IDC_WRITING_DIRECTION_LTR)
return params_.writing_direction_left_to_right &
WebContextMenuData::CheckableMenuItemChecked;
if (id == IDC_CONTENT_CONTEXT_LOOK_UP_IN_DICTIONARY)
return false;
#endif // OS_MACOSX
#if defined(ENABLE_INPUT_SPEECH)
// Check box for menu item 'Block offensive words'.
if (id == IDC_CONTENT_CONTEXT_SPEECH_INPUT_FILTER_PROFANITIES) {
return ChromeSpeechRecognitionPreferences::GetForProfile(profile_)->
FilterProfanities();
}
#endif
return false;
}
void RenderViewContextMenu::ExecuteCommand(int id) {
ExecuteCommand(id, 0);
}
void RenderViewContextMenu::ExecuteCommand(int id, int event_flags) {
// If this command is is added by one of our observers, we dispatch it to the
// observer.
ObserverListBase<RenderViewContextMenuObserver>::Iterator it(observers_);
RenderViewContextMenuObserver* observer;
while ((observer = it.GetNext()) != NULL) {
if (observer->IsCommandIdSupported(id))
return observer->ExecuteCommand(id);
}
RenderViewHost* rvh = source_web_contents_->GetRenderViewHost();
// Process custom actions range.
if (id >= IDC_CONTENT_CONTEXT_CUSTOM_FIRST &&
id <= IDC_CONTENT_CONTEXT_CUSTOM_LAST) {
unsigned action = id - IDC_CONTENT_CONTEXT_CUSTOM_FIRST;
rvh->ExecuteCustomContextMenuCommand(action, params_.custom_context);
return;
}
// Process extension menu items.
if (id >= IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST &&
id <= IDC_EXTENSIONS_CONTEXT_CUSTOM_LAST) {
MenuManager* manager = profile_->GetExtensionService()->menu_manager();
std::map<int, MenuItem::Id>::const_iterator i =
extension_item_map_.find(id);
if (i != extension_item_map_.end()) {
manager->ExecuteCommand(profile_, source_web_contents_, params_,
i->second);
}
return;
}
if (id >= IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_FIRST &&
id <= IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_LAST) {
ProtocolHandlerRegistry::ProtocolHandlerList handlers =
GetHandlersForLinkUrl();
if (handlers.empty()) {
return;
}
content::RecordAction(
UserMetricsAction("RegisterProtocolHandler.ContextMenu_Open"));
int handlerIndex = id - IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_FIRST;
WindowOpenDisposition disposition =
ForceNewTabDispositionFromEventFlags(event_flags);
OpenURL(
handlers[handlerIndex].TranslateUrl(params_.link_url),
params_.frame_url.is_empty() ? params_.page_url : params_.frame_url,
params_.frame_id,
disposition,
content::PAGE_TRANSITION_LINK);
return;
}
switch (id) {
case IDC_CONTENT_CONTEXT_OPENLINKNEWTAB:
OpenURL(
params_.link_url,
params_.frame_url.is_empty() ? params_.page_url : params_.frame_url,
params_.frame_id,
source_web_contents_->GetDelegate() &&
source_web_contents_->GetDelegate()->IsApplication() ?
NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB,
content::PAGE_TRANSITION_LINK);
break;
case IDC_CONTENT_CONTEXT_OPENLINKNEWWINDOW:
OpenURL(
params_.link_url,
params_.frame_url.is_empty() ? params_.page_url : params_.frame_url,
params_.frame_id,
NEW_WINDOW, content::PAGE_TRANSITION_LINK);
break;
case IDC_CONTENT_CONTEXT_OPENLINKOFFTHERECORD:
OpenURL(params_.link_url,
GURL(),
params_.frame_id,
OFF_THE_RECORD,
content::PAGE_TRANSITION_LINK);
break;
case IDC_CONTENT_CONTEXT_SAVELINKAS: {
download_util::RecordDownloadSource(
download_util::INITIATED_BY_CONTEXT_MENU);
const GURL& referrer =
params_.frame_url.is_empty() ? params_.page_url : params_.frame_url;
const GURL& url = params_.link_url;
content::DownloadSaveInfo save_info;
save_info.prompt_for_save_location = true;
DownloadManager* dlm = BrowserContext::GetDownloadManager(profile_);
scoped_ptr<DownloadUrlParameters> dl_params(
DownloadUrlParameters::FromWebContents(
source_web_contents_, url, save_info));
dl_params->set_referrer(
content::Referrer(referrer, params_.referrer_policy));
dl_params->set_referrer_encoding(params_.frame_charset);
dlm->DownloadUrl(dl_params.Pass());
break;
}
case IDC_CONTENT_CONTEXT_SAVEAVAS:
case IDC_CONTENT_CONTEXT_SAVEIMAGEAS: {
download_util::RecordDownloadSource(
download_util::INITIATED_BY_CONTEXT_MENU);
const GURL& referrer =
params_.frame_url.is_empty() ? params_.page_url : params_.frame_url;
const GURL& url = params_.src_url;
content::DownloadSaveInfo save_info;
save_info.prompt_for_save_location = true;
int64 post_id = -1;
if (url == source_web_contents_->GetURL()) {
const NavigationEntry* entry =
source_web_contents_->GetController().GetActiveEntry();
if (entry)
post_id = entry->GetPostID();
}
DownloadManager* dlm = BrowserContext::GetDownloadManager(profile_);
scoped_ptr<DownloadUrlParameters> dl_params(
DownloadUrlParameters::FromWebContents(
source_web_contents_, url, save_info));
dl_params->set_referrer(
content::Referrer(referrer, params_.referrer_policy));
dl_params->set_post_id(post_id);
dl_params->set_prefer_cache(true);
if (post_id >= 0)
dl_params->set_method("POST");
dlm->DownloadUrl(dl_params.Pass());
break;
}
case IDC_CONTENT_CONTEXT_COPYLINKLOCATION:
WriteURLToClipboard(params_.unfiltered_link_url);
break;
case IDC_CONTENT_CONTEXT_COPYIMAGELOCATION:
case IDC_CONTENT_CONTEXT_COPYAVLOCATION:
WriteURLToClipboard(params_.src_url);
break;
case IDC_CONTENT_CONTEXT_COPYIMAGE:
CopyImageAt(params_.x, params_.y);
break;
case IDC_CONTENT_CONTEXT_OPENIMAGENEWTAB:
case IDC_CONTENT_CONTEXT_OPENAVNEWTAB:
OpenURL(
params_.src_url,
params_.frame_url.is_empty() ? params_.page_url : params_.frame_url,
params_.frame_id,
NEW_BACKGROUND_TAB, content::PAGE_TRANSITION_LINK);
break;
case IDC_CONTENT_CONTEXT_PLAYPAUSE: {
bool play = !!(params_.media_flags & WebContextMenuData::MediaPaused);
if (play) {
content::RecordAction(UserMetricsAction("MediaContextMenu_Play"));
} else {
content::RecordAction(UserMetricsAction("MediaContextMenu_Pause"));
}
MediaPlayerActionAt(gfx::Point(params_.x, params_.y),
WebMediaPlayerAction(
WebMediaPlayerAction::Play, play));
break;
}
case IDC_CONTENT_CONTEXT_MUTE: {
bool mute = !(params_.media_flags & WebContextMenuData::MediaMuted);
if (mute) {
content::RecordAction(UserMetricsAction("MediaContextMenu_Mute"));
} else {
content::RecordAction(UserMetricsAction("MediaContextMenu_Unmute"));
}
MediaPlayerActionAt(gfx::Point(params_.x, params_.y),
WebMediaPlayerAction(
WebMediaPlayerAction::Mute, mute));
break;
}
case IDC_CONTENT_CONTEXT_LOOP:
content::RecordAction(UserMetricsAction("MediaContextMenu_Loop"));
MediaPlayerActionAt(gfx::Point(params_.x, params_.y),
WebMediaPlayerAction(
WebMediaPlayerAction::Loop,
!IsCommandIdChecked(IDC_CONTENT_CONTEXT_LOOP)));
break;
case IDC_CONTENT_CONTEXT_CONTROLS:
content::RecordAction(UserMetricsAction("MediaContextMenu_Controls"));
MediaPlayerActionAt(
gfx::Point(params_.x, params_.y),
WebMediaPlayerAction(
WebMediaPlayerAction::Controls,
!IsCommandIdChecked(IDC_CONTENT_CONTEXT_CONTROLS)));
break;
case IDC_CONTENT_CONTEXT_ROTATECW:
content::RecordAction(
UserMetricsAction("PluginContextMenu_RotateClockwise"));
PluginActionAt(
gfx::Point(params_.x, params_.y),
WebPluginAction(
WebPluginAction::Rotate90Clockwise,
true));
break;
case IDC_CONTENT_CONTEXT_ROTATECCW:
content::RecordAction(
UserMetricsAction("PluginContextMenu_RotateCounterclockwise"));
PluginActionAt(
gfx::Point(params_.x, params_.y),
WebPluginAction(
WebPluginAction::Rotate90Counterclockwise,
true));
break;
case IDC_BACK:
source_web_contents_->GetController().GoBack();
break;
case IDC_FORWARD:
source_web_contents_->GetController().GoForward();
break;
case IDC_SAVE_PAGE:
source_web_contents_->OnSavePage();
break;
case IDC_RELOAD:
// Prevent the modal "Resubmit form post" dialog from appearing in the
// context of an external context menu.
source_web_contents_->GetController().Reload(!external_);
break;
case IDC_PRINT:
if (params_.media_type == WebContextMenuData::MediaTypeNone) {
TabContents* tab_contents =
TabContents::FromWebContents(source_web_contents_);
if (!tab_contents)
break;
if (g_browser_process->local_state()->GetBoolean(
prefs::kPrintPreviewDisabled)) {
tab_contents->print_view_manager()->PrintNow();
} else {
tab_contents->print_view_manager()->PrintPreviewNow();
}
} else {
rvh->Send(new PrintMsg_PrintNodeUnderContextMenu(rvh->GetRoutingID()));
}
break;
case IDC_VIEW_SOURCE:
source_web_contents_->ViewSource();
break;
case IDC_CONTENT_CONTEXT_INSPECTELEMENT:
Inspect(params_.x, params_.y);
break;
case IDC_CONTENT_CONTEXT_VIEWPAGEINFO: {
NavigationController* controller = &source_web_contents_->GetController();
NavigationEntry* nav_entry = controller->GetActiveEntry();
Browser* browser =
browser::FindBrowserWithWebContents(source_web_contents_);
chrome::ShowPageInfo(browser, source_web_contents_, nav_entry->GetURL(),
nav_entry->GetSSL(), true);
break;
}
case IDC_CONTENT_CONTEXT_TRANSLATE: {
// A translation might have been triggered by the time the menu got
// selected, do nothing in that case.
TabContents* tab_contents =
TabContents::FromWebContents(source_web_contents_);
if (!tab_contents)
return;
TranslateTabHelper* helper = tab_contents->translate_tab_helper();
if (helper->language_state().IsPageTranslated() ||
helper->language_state().translation_pending()) {
return;
}
std::string original_lang = helper->language_state().original_language();
std::string target_lang = g_browser_process->GetApplicationLocale();
target_lang = TranslateManager::GetLanguageCode(target_lang);
// Since the user decided to translate for that language and site, clears
// any preferences for not translating them.
TranslatePrefs prefs(profile_->GetPrefs());
prefs.RemoveLanguageFromBlacklist(original_lang);
prefs.RemoveSiteFromBlacklist(params_.page_url.HostNoBrackets());
TranslateManager::GetInstance()->TranslatePage(
source_web_contents_, original_lang, target_lang);
break;
}
case IDC_CONTENT_CONTEXT_RELOADFRAME:
rvh->ReloadFrame();
break;
case IDC_CONTENT_CONTEXT_VIEWFRAMESOURCE:
source_web_contents_->ViewFrameSource(params_.frame_url,
params_.frame_content_state);
break;
case IDC_CONTENT_CONTEXT_VIEWFRAMEINFO: {
Browser* browser = browser::FindBrowserWithWebContents(
source_web_contents_);
chrome::ShowPageInfo(browser, source_web_contents_, params_.frame_url,
params_.security_info, false);
break;
}
case IDC_CONTENT_CONTEXT_UNDO:
rvh->Undo();
break;
case IDC_CONTENT_CONTEXT_REDO:
rvh->Redo();
break;
case IDC_CONTENT_CONTEXT_CUT:
rvh->Cut();
break;
case IDC_CONTENT_CONTEXT_COPY:
rvh->Copy();
break;
case IDC_CONTENT_CONTEXT_PASTE:
rvh->Paste();
break;
case IDC_CONTENT_CONTEXT_PASTE_AND_MATCH_STYLE:
rvh->PasteAndMatchStyle();
break;
case IDC_CONTENT_CONTEXT_DELETE:
rvh->Delete();
break;
case IDC_CONTENT_CONTEXT_SELECTALL:
rvh->SelectAll();
break;
case IDC_CONTENT_CONTEXT_SEARCHWEBFOR:
case IDC_CONTENT_CONTEXT_GOTOURL: {
WindowOpenDisposition disposition =
ForceNewTabDispositionFromEventFlags(event_flags);
OpenURL(selection_navigation_url_,
GURL(),
params_.frame_id,
disposition,
content::PAGE_TRANSITION_LINK);
break;
}
case IDC_CONTENT_CONTEXT_LANGUAGE_SETTINGS: {
WindowOpenDisposition disposition =
ForceNewTabDispositionFromEventFlags(event_flags);
std::string url = std::string(chrome::kChromeUISettingsURL) +
chrome::kLanguageOptionsSubPage;
OpenURL(GURL(url), GURL(), 0, disposition, content::PAGE_TRANSITION_LINK);
break;
}
#if defined(OS_MACOSX)
case IDC_WRITING_DIRECTION_DEFAULT:
// WebKit's current behavior is for this menu item to always be disabled.
NOTREACHED();
break;
case IDC_WRITING_DIRECTION_RTL:
case IDC_WRITING_DIRECTION_LTR: {
WebKit::WebTextDirection dir = WebKit::WebTextDirectionLeftToRight;
if (id == IDC_WRITING_DIRECTION_RTL)
dir = WebKit::WebTextDirectionRightToLeft;
rvh->UpdateTextDirection(dir);
rvh->NotifyTextDirection();
break;
}
#endif // OS_MACOSX
case IDC_CONTENT_CONTEXT_PROTOCOL_HANDLER_SETTINGS: {
content::RecordAction(
UserMetricsAction("RegisterProtocolHandler.ContextMenu_Settings"));
WindowOpenDisposition disposition =
ForceNewTabDispositionFromEventFlags(event_flags);
std::string url = std::string(chrome::kChromeUISettingsURL) +
chrome::kHandlerSettingsSubPage;
OpenURL(GURL(url), GURL(), 0, disposition, content::PAGE_TRANSITION_LINK);
break;
}
case IDC_CONTENT_CONTEXT_ADDSEARCHENGINE: {
// Make sure the model is loaded.
TemplateURLService* model =
TemplateURLServiceFactory::GetForProfile(profile_);
if (!model)
return;
model->Load();
TabContents* tab_contents =
TabContents::FromWebContents(source_web_contents_);
if (tab_contents &&
tab_contents->search_engine_tab_helper() &&
tab_contents->search_engine_tab_helper()->delegate()) {
string16 keyword(TemplateURLService::GenerateKeyword(params_.page_url));
TemplateURLData data;
data.short_name = keyword;
data.SetKeyword(keyword);
data.SetURL(params_.keyword_url.spec());
data.favicon_url =
TemplateURL::GenerateFaviconURL(params_.page_url.GetOrigin());
// Takes ownership of the TemplateURL.
tab_contents->search_engine_tab_helper()->delegate()->
ConfirmAddSearchProvider(new TemplateURL(profile_, data), profile_);
}
break;
}
#if defined(ENABLE_INPUT_SPEECH)
case IDC_CONTENT_CONTEXT_SPEECH_INPUT_FILTER_PROFANITIES: {
ChromeSpeechRecognitionPreferences::GetForProfile(profile_)->
ToggleFilterProfanities();
break;
}
#endif
case IDC_CONTENT_CONTEXT_SPEECH_INPUT_ABOUT: {
GURL url(chrome::kSpeechInputAboutURL);
GURL localized_url = google_util::AppendGoogleLocaleParam(url);
// Open URL with no referrer field (because user clicked on menu item).
OpenURL(localized_url, GURL(), 0, NEW_FOREGROUND_TAB,
content::PAGE_TRANSITION_LINK);
break;
}
default:
NOTREACHED();
break;
}
}
ProtocolHandlerRegistry::ProtocolHandlerList
RenderViewContextMenu::GetHandlersForLinkUrl() {
ProtocolHandlerRegistry::ProtocolHandlerList handlers =
protocol_handler_registry_->GetHandlersFor(params_.link_url.scheme());
std::sort(handlers.begin(), handlers.end());
return handlers;
}
void RenderViewContextMenu::MenuWillShow(ui::SimpleMenuModel* source) {
// Ignore notifications from submenus.
if (source != &menu_model_)
return;
content::RenderWidgetHostView* view =
source_web_contents_->GetRenderWidgetHostView();
if (view)
view->SetShowingContextMenu(true);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_RENDER_VIEW_CONTEXT_MENU_SHOWN,
content::Source<RenderViewContextMenu>(this),
content::NotificationService::NoDetails());
}
void RenderViewContextMenu::MenuClosed(ui::SimpleMenuModel* source) {
// Ignore notifications from submenus.
if (source != &menu_model_)
return;
content::RenderWidgetHostView* view =
source_web_contents_->GetRenderWidgetHostView();
if (view)
view->SetShowingContextMenu(false);
RenderViewHost* rvh = source_web_contents_->GetRenderViewHost();
if (rvh) {
rvh->NotifyContextMenuClosed(params_.custom_context);
}
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_RENDER_VIEW_CONTEXT_MENU_CLOSED,
content::Source<RenderViewContextMenu>(this),
content::NotificationService::NoDetails());
}
bool RenderViewContextMenu::IsDevCommandEnabled(int id) const {
if (id == IDC_CONTENT_CONTEXT_INSPECTELEMENT) {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
if (!profile_->GetPrefs()->GetBoolean(prefs::kWebKitJavascriptEnabled) ||
command_line->HasSwitch(switches::kDisableJavaScript))
return false;
// Don't enable the web inspector if the developer tools are disabled via
// the preference dev-tools-disabled.
if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled))
return false;
}
return true;
}
string16 RenderViewContextMenu::PrintableSelectionText() {
return ui::TruncateString(params_.selection_text,
kMaxSelectionTextLength);
}
// Controller functions --------------------------------------------------------
void RenderViewContextMenu::OpenURL(
const GURL& url, const GURL& referrer, int64 frame_id,
WindowOpenDisposition disposition,
content::PageTransition transition) {
WebContents* new_contents = source_web_contents_->OpenURL(OpenURLParams(
url, content::Referrer(referrer, params_.referrer_policy), disposition,
transition, false));
if (!new_contents)
return;
RetargetingDetails details;
details.source_web_contents = source_web_contents_;
details.source_frame_id = frame_id;
details.target_url = url;
details.target_web_contents = new_contents;
details.not_yet_in_tabstrip = false;
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_RETARGETING,
content::Source<Profile>(Profile::FromBrowserContext(
source_web_contents_->GetBrowserContext())),
content::Details<RetargetingDetails>(&details));
}
void RenderViewContextMenu::CopyImageAt(int x, int y) {
source_web_contents_->GetRenderViewHost()->CopyImageAt(x, y);
}
void RenderViewContextMenu::Inspect(int x, int y) {
content::RecordAction(UserMetricsAction("DevTools_InspectElement"));
DevToolsWindow::InspectElement(
source_web_contents_->GetRenderViewHost(), x, y);
}
void RenderViewContextMenu::WriteURLToClipboard(const GURL& url) {
chrome_common_net::WriteURLToClipboard(
url,
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages),
g_browser_process->clipboard());
}
void RenderViewContextMenu::MediaPlayerActionAt(
const gfx::Point& location,
const WebMediaPlayerAction& action) {
source_web_contents_->GetRenderViewHost()->
ExecuteMediaPlayerActionAtLocation(location, action);
}
void RenderViewContextMenu::PluginActionAt(
const gfx::Point& location,
const WebPluginAction& action) {
source_web_contents_->GetRenderViewHost()->
ExecutePluginActionAtLocation(location, action);
}
| keishi/chromium | chrome/browser/tab_contents/render_view_context_menu.cc | C++ | bsd-3-clause | 73,696 |
<?php
// must be called POST validation
/**
* Adds target="blank" to all outbound links. This transform is
* only attached if Attr.TargetBlank is TRUE. This works regardless
* of whether or not Attr.AllowedFrameTargets
*/
class HTMLPurifier_AttrTransform_TargetBlank extends HTMLPurifier_AttrTransform
{
/**
* @type HTMLPurifier_URIParser
*/
private $parser;
public function __construct()
{
$this->parser = new HTMLPurifier_URIParser();
}
/**
* @param array $attr
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return array
*/
public function transform($attr, $config, $context)
{
if (!isset($attr['href'])) {
return $attr;
}
// XXX Kind of inefficient
$url = $this->parser->parse($attr['href']);
$scheme = $url->getSchemeObj($config, $context);
if ($scheme->browsable && !$url->isBenign($config, $context)) {
$attr['target'] = '_blank';
}
return $attr;
}
}
// vim: et sw=4 sts=4
| meishichao/yii2test | vendor/ezyang/htmlpurifier/library/HTMLPurifier/AttrTransform/TargetBlank.php | PHP | bsd-3-clause | 1,112 |
/* $NetBSD: psychovar.h,v 1.3.4.1 2000/07/18 16:23:20 mrg Exp $ */
/*
* Copyright (c) 1999, 2000 Matthew R. Green
* All rights reserved.
*
* 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 and the following disclaimer.
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _SPARC64_DEV_PSYCHOVAR_H_
#define _SPARC64_DEV_PSYCHOVAR_H_
/* per real PCI bus info */
struct psycho_softc;
struct psycho_pbm {
/* link to mum */
struct psycho_softc *pp_sc;
/*
* note that the sabre really only has one ranges property,
* used for both simba a and simba b (but the ranges for
* real psychos are the same for PCI A and PCI B anyway).
*/
struct psycho_registers *pp_regs;
struct psycho_ranges *pp_range;
struct psycho_interrupt_map *pp_intmap;
struct psycho_interrupt_map_mask pp_intmapmask;
/* counts of above */
int pp_nregs;
int pp_nrange;
int pp_nintmap;
/* chipset tag for this instance */
pci_chipset_tag_t pp_pc;
/* our tags */
bus_space_tag_t pp_memt;
bus_space_tag_t pp_iot;
bus_dma_tag_t pp_dmat;
int pp_bus;
int pp_flags;
/* and pointers into the psycho regs for our bits */
struct pci_ctl *pp_pcictl;
};
/*
* per-PCI bus on mainbus softc structure; one for sabre, or two
* per pair of psycho's.
*/
struct psycho_softc {
struct device sc_dev;
/*
* one sabre has two simba's. psycho's are separately attached,
* with the `other' psycho_pbm allocated at the first's attach.
*/
struct psycho_pbm *sc_sabre;
struct psycho_pbm *__sc_psycho_this;
struct psycho_pbm *__sc_psycho_other;
#define sc_simba_a __sc_psycho_this
#define sc_simba_b __sc_psycho_other
#define sc_psycho_this __sc_psycho_this
#define sc_psycho_other __sc_psycho_other
/*
* PSYCHO register. we record the base physical address of these
* also as it is the base of the entire PSYCHO
*/
struct psychoreg *sc_regs;
paddr_t sc_basepaddr;
/* Interrupt Group Number for this device */
int sc_ign;
/* our tags (from parent) */
bus_space_tag_t sc_bustag;
bus_dma_tag_t sc_dmatag;
/* config space */
bus_space_tag_t sc_configtag;
bus_space_handle_t sc_configaddr;
int sc_clockfreq;
int sc_node; /* prom node */
int sc_mode; /* (whatareya?) */
#define PSYCHO_MODE_SABRE 1 /* i'm a sabre (yob) */
#define PSYCHO_MODE_PSYCHO 2 /* i'm a psycho (w*nker) */
struct iommu_state *sc_is;
};
/* config space is per-psycho. mem/io/dma are per-pci bus */
bus_dma_tag_t psycho_alloc_dma_tag __P((struct psycho_pbm *));
bus_space_tag_t psycho_alloc_bus_tag __P((struct psycho_pbm *, int));
#define psycho_alloc_config_tag(pp) psycho_alloc_bus_tag((pp), PCI_CONFIG_BUS_SPACE)
#define psycho_alloc_mem_tag(pp) psycho_alloc_bus_tag((pp), PCI_MEMORY_BUS_SPACE)
#define psycho_alloc_io_tag(pp) psycho_alloc_bus_tag((pp), PCI_IO_BUS_SPACE)
int psycho_intr_map __P((pcitag_t, int, int, pci_intr_handle_t *));
#endif /* _SPARC64_DEV_PSYCHOVAR_H_ */
| MarginC/kame | netbsd/sys/arch/sparc64/dev/psychovar.h | C | bsd-3-clause | 4,211 |
<?php
use yii\db\Schema;
use yii\db\Migration;
class m150914_084149_create_page_table extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
$this->createTable('page', [
'id' => $this->primaryKey(),
'title' => $this->string(500)->notNull(),
'description' => $this->string(1000),
'content' => $this->text(),
'ru' => $this->smallInteger()->notNull()->defaultValue(0),
'views' => $this->integer()->notNull()->defaultValue(0),
], $tableOptions);
$this->createIndex('idx_page_title', 'page', 'title');
$this->createIndex('idx_page_ru', 'page', 'ru');
}
public function down()
{
$this->dropTable('page');
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
| temirfe/oshkenesh | migrations/m150914_084149_create_page_table.php | PHP | bsd-3-clause | 1,079 |
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/network_interfaces_mac.h"
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <set>
#include <sys/types.h>
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "net/base/escape.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/network_interfaces_posix.h"
#include "url/gurl.h"
#if !defined(OS_IOS)
#include <net/if_media.h>
#include <netinet/in_var.h>
#include <sys/ioctl.h>
#endif // !OS_IOS
namespace net {
namespace {
#if !defined(OS_IOS)
// MacOSX implementation of IPAttributesGetterMac which calls ioctl on socket to
// retrieve IP attributes.
class IPAttributesGetterMacImpl : public internal::IPAttributesGetterMac {
public:
IPAttributesGetterMacImpl();
~IPAttributesGetterMacImpl() override;
bool IsInitialized() const override;
bool GetIPAttributes(const char* ifname,
const sockaddr* sock_addr,
int* native_attributes) override;
private:
int ioctl_socket_;
};
IPAttributesGetterMacImpl::IPAttributesGetterMacImpl()
: ioctl_socket_(socket(AF_INET6, SOCK_DGRAM, 0)) {
DCHECK_GE(ioctl_socket_, 0);
}
bool IPAttributesGetterMacImpl::IsInitialized() const {
return ioctl_socket_ >= 0;
}
IPAttributesGetterMacImpl::~IPAttributesGetterMacImpl() {
if (ioctl_socket_ >= 0) {
close(ioctl_socket_);
}
}
bool IPAttributesGetterMacImpl::GetIPAttributes(const char* ifname,
const sockaddr* sock_addr,
int* native_attributes) {
struct in6_ifreq ifr = {};
strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
memcpy(&ifr.ifr_ifru.ifru_addr, sock_addr, sock_addr->sa_len);
int rv = ioctl(ioctl_socket_, SIOCGIFAFLAG_IN6, &ifr);
if (rv >= 0) {
*native_attributes = ifr.ifr_ifru.ifru_flags;
}
return (rv >= 0);
}
// When returning true, the platform native IPv6 address attributes were
// successfully converted to net IP address attributes. Otherwise, returning
// false and the caller should drop the IP address which can't be used by the
// application layer.
bool TryConvertNativeToNetIPAttributes(int native_attributes,
int* net_attributes) {
// For MacOSX, we disallow addresses with attributes IN6_IFF_ANYCASE,
// IN6_IFF_DUPLICATED, IN6_IFF_TENTATIVE, and IN6_IFF_DETACHED as these are
// still progressing through duplicated address detection (DAD) or are not
// suitable to be used in an one-to-one communication and shouldn't be used
// by the application layer.
if (native_attributes & (IN6_IFF_ANYCAST | IN6_IFF_DUPLICATED |
IN6_IFF_TENTATIVE | IN6_IFF_DETACHED)) {
return false;
}
if (native_attributes & IN6_IFF_TEMPORARY) {
*net_attributes |= IP_ADDRESS_ATTRIBUTE_TEMPORARY;
}
if (native_attributes & IN6_IFF_DEPRECATED) {
*net_attributes |= IP_ADDRESS_ATTRIBUTE_DEPRECATED;
}
return true;
}
NetworkChangeNotifier::ConnectionType GetNetworkInterfaceType(
int addr_family,
const std::string& interface_name) {
NetworkChangeNotifier::ConnectionType type =
NetworkChangeNotifier::CONNECTION_UNKNOWN;
struct ifmediareq ifmr = {};
strncpy(ifmr.ifm_name, interface_name.c_str(), sizeof(ifmr.ifm_name) - 1);
int s = socket(addr_family, SOCK_DGRAM, 0);
if (s == -1) {
return type;
}
if (ioctl(s, SIOCGIFMEDIA, &ifmr) != -1) {
if (ifmr.ifm_current & IFM_IEEE80211) {
type = NetworkChangeNotifier::CONNECTION_WIFI;
} else if (ifmr.ifm_current & IFM_ETHER) {
type = NetworkChangeNotifier::CONNECTION_ETHERNET;
}
}
close(s);
return type;
}
#endif // !OS_IOS
} // namespace
namespace internal {
bool GetNetworkListImpl(NetworkInterfaceList* networks,
int policy,
const ifaddrs* interfaces,
IPAttributesGetterMac* ip_attributes_getter) {
// Enumerate the addresses assigned to network interfaces which are up.
for (const ifaddrs* interface = interfaces; interface != NULL;
interface = interface->ifa_next) {
// Skip loopback interfaces, and ones which are down.
if (!(IFF_RUNNING & interface->ifa_flags))
continue;
if (IFF_LOOPBACK & interface->ifa_flags)
continue;
// Skip interfaces with no address configured.
struct sockaddr* addr = interface->ifa_addr;
if (!addr)
continue;
// Skip unspecified addresses (i.e. made of zeroes) and loopback addresses
// configured on non-loopback interfaces.
if (IsLoopbackOrUnspecifiedAddress(addr))
continue;
const std::string& name = interface->ifa_name;
// Filter out VMware interfaces, typically named vmnet1 and vmnet8.
if (ShouldIgnoreInterface(name, policy)) {
continue;
}
NetworkChangeNotifier::ConnectionType connection_type =
NetworkChangeNotifier::CONNECTION_UNKNOWN;
int ip_attributes = IP_ADDRESS_ATTRIBUTE_NONE;
#if !defined(OS_IOS)
// Retrieve native ip attributes and convert to net version if a getter is
// given.
if (ip_attributes_getter && ip_attributes_getter->IsInitialized()) {
int native_attributes = 0;
if (addr->sa_family == AF_INET6 &&
ip_attributes_getter->GetIPAttributes(
interface->ifa_name, interface->ifa_addr, &native_attributes)) {
if (!TryConvertNativeToNetIPAttributes(native_attributes,
&ip_attributes)) {
continue;
}
}
}
connection_type = GetNetworkInterfaceType(addr->sa_family, name);
#endif // !OS_IOS
IPEndPoint address;
int addr_size = 0;
if (addr->sa_family == AF_INET6) {
addr_size = sizeof(sockaddr_in6);
} else if (addr->sa_family == AF_INET) {
addr_size = sizeof(sockaddr_in);
}
if (address.FromSockAddr(addr, addr_size)) {
uint8_t prefix_length = 0;
if (interface->ifa_netmask) {
// If not otherwise set, assume the same sa_family as ifa_addr.
if (interface->ifa_netmask->sa_family == 0) {
interface->ifa_netmask->sa_family = addr->sa_family;
}
IPEndPoint netmask;
if (netmask.FromSockAddr(interface->ifa_netmask, addr_size)) {
prefix_length = MaskPrefixLength(netmask.address());
}
}
networks->push_back(NetworkInterface(
name, name, if_nametoindex(name.c_str()), connection_type,
address.address(), prefix_length, ip_attributes));
}
}
return true;
}
} // namespace internal
bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
if (networks == NULL)
return false;
// getifaddrs() may require IO operations.
base::ThreadRestrictions::AssertIOAllowed();
ifaddrs* interfaces;
if (getifaddrs(&interfaces) < 0) {
PLOG(ERROR) << "getifaddrs";
return false;
}
scoped_ptr<internal::IPAttributesGetterMac> ip_attributes_getter;
#if !defined(OS_IOS)
ip_attributes_getter.reset(new IPAttributesGetterMacImpl());
#endif
bool result = internal::GetNetworkListImpl(networks, policy, interfaces,
ip_attributes_getter.get());
freeifaddrs(interfaces);
return result;
}
std::string GetWifiSSID() {
NOTIMPLEMENTED();
return "";
}
} // namespace net
| was4444/chromium.src | net/base/network_interfaces_mac.cc | C++ | bsd-3-clause | 7,768 |
<!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_12) on Fri Mar 20 17:29:26 CST 2009 -->
<TITLE>
½Ó¿Ú cn.iaicc.smgk.business.IOptionTemplateInfoService µÄʹÓà (ÉñÃØ¹Ë¿Í¹ÜÀíÆ½Ì¨ API)
</TITLE>
<META NAME="date" CONTENT="2009-03-20">
<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="½Ó¿Ú cn.iaicc.smgk.business.IOptionTemplateInfoService µÄʹÓà (ÉñÃØ¹Ë¿Í¹ÜÀíÆ½Ì¨ API)";
}
}
</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="Ìø¹ýµ¼º½Á´½Ó"></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>¸ÅÊö</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Èí¼þ°ü</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../cn/iaicc/smgk/business/IOptionTemplateInfoService.html" title="cn.iaicc.smgk.business ÖеĽӿÚ"><FONT CLASS="NavBarFont1"><B>Àà</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>ʹÓÃ</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Ê÷</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Òѹýʱ</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Ë÷Òý</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>°ïÖú</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">
ÉÏÒ»¸ö
ÏÂÒ»¸ö</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?cn/iaicc/smgk/business/\class-useIOptionTemplateInfoService.html" target="_top"><B>¿ò¼Ü</B></A>
<A HREF="IOptionTemplateInfoService.html" target="_top"><B>ÎÞ¿ò¼Ü</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>½Ó¿Ú cn.iaicc.smgk.business.IOptionTemplateInfoService<br>µÄʹÓÃ</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
ʹÓà <A HREF="../../../../../cn/iaicc/smgk/business/IOptionTemplateInfoService.html" title="cn.iaicc.smgk.business ÖеĽӿÚ">IOptionTemplateInfoService</A> µÄÈí¼þ°ü</FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#cn.iaicc.smgk.business.service"><B>cn.iaicc.smgk.business.service</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="cn.iaicc.smgk.business.service"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<A HREF="../../../../../cn/iaicc/smgk/business/service/package-summary.html">cn.iaicc.smgk.business.service</A> ÖÐ <A HREF="../../../../../cn/iaicc/smgk/business/IOptionTemplateInfoService.html" title="cn.iaicc.smgk.business ÖеĽӿÚ">IOptionTemplateInfoService</A> µÄʹÓÃ</FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">ʵÏÖ <A HREF="../../../../../cn/iaicc/smgk/business/IOptionTemplateInfoService.html" title="cn.iaicc.smgk.business ÖеĽӿÚ">IOptionTemplateInfoService</A> µÄ <A HREF="../../../../../cn/iaicc/smgk/business/service/package-summary.html">cn.iaicc.smgk.business.service</A> ÖеÄÀà</FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../cn/iaicc/smgk/business/service/OptionTemplateInfoService.html" title="cn.iaicc.smgk.business.service ÖеÄÀà">OptionTemplateInfoService</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Ìø¹ýµ¼º½Á´½Ó"></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>¸ÅÊö</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Èí¼þ°ü</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../cn/iaicc/smgk/business/IOptionTemplateInfoService.html" title="cn.iaicc.smgk.business ÖеĽӿÚ"><FONT CLASS="NavBarFont1"><B>Àà</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>ʹÓÃ</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Ê÷</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Òѹýʱ</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Ë÷Òý</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>°ïÖú</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">
ÉÏÒ»¸ö
ÏÂÒ»¸ö</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?cn/iaicc/smgk/business/\class-useIOptionTemplateInfoService.html" target="_top"><B>¿ò¼Ü</B></A>
<A HREF="IOptionTemplateInfoService.html" target="_top"><B>ÎÞ¿ò¼Ü</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>ËùÓÐÀà</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2008 ±±¾©°¬µÏÖÇÈíÐÅÏ¢¼¼ÊõÓÐÏÞÔðÈι«Ë¾. All Rights Reserved.</i><br/><i><a href="http://www.idea-soft.cn" target="_blank">http://www.idea-soft.cn</a></i> <i><a href="http://www.iaicc.cn" target="_blank">http://www.iaicc.cn</a></i> <i><a href="http://www.xsaas.org" target="_blank">http://www.xsaas.org</a></i>
</BODY>
</HTML>
| wangxin39/xstat | XStatAPI/docs/api/cn/iaicc/smgk/business/class-use/IOptionTemplateInfoService.html | HTML | bsd-3-clause | 8,204 |
<?php
/**
* OWASP Enterprise Security API (ESAPI)
*
* @author Ishida, Mrcio Andr (mishida@conviso.com.br)
* Created on Jan 28, 2010
*/
include("header.php");
?>
<h2 align="center">Tutorial</h2>
<p>This lesson shows how to use user input in a webpage without
introducing scripting vulnerabilities. In the insecure demonstration,
any text that you put in the box
will become a part of the webpage.</p>
<p class="newsItem">
<code>
$name = $_GET['name'];<br />
<p>Hello, <?=$name?></p><br />
</code>
</p>
Notice that the input
will show up in the text of the page right after the word "Hello."
If you enter a script in the field, it will become a part of the page
and will run.</p>
<p>EXAMPLE: <b><script>alert(document.cookie)</script></b></p>
<p>Notice that the input was used twice in the page. Did you see that the
input was also used to repopulate the form field itself.
<p class="newsItem">
<code>
<input name='name' value='<?=$name ?>'>
</code>
</p>
This can be used for
XSS attacks as well. Try the example attack below and then click
in and out of the field with your mouse. Note that you don't need to use any
greater-than or less-than characters for this attack. If you're having trouble, use your
browser's view source function to see just where your attack ended up.</p>
<p>EXAMPLE: <b>' onblur='alert(document.cookie)</b></p>
<p><b>To fix the problem, we can wrap the user input contained in the "name" parameter
with a call to the ESAPI Encoder.encodeForHTML() method.
The encodeForHTML() method uses a "whitelist" HTML entity encoding algorithm to ensure that
they cannot be interpreted as script. The Encoder ensures that there are no double-encoded
characters in the input. This call should be used to wrap any user input
being rendered in HTML element content.</b></p>
<p class="newsItem">
<code>
<?php<br/>
<span style="padding-left: 25px;">require_once dirname(__FILE__).'/src/ESAPI.php';</span><br />
<span style="padding-left: 25px;">$ESAPI = new ESAPI(dirname(__FILE__)."/ESAPI.xml");</span><br />
<span style="padding-left: 25px;">$ESAPI = new ESAPI();</span><br />
<br />
<span style="padding-left: 25px;">$encoder = ESAPI::getEncoder();</span><br />
<span style="padding-left: 25px;">$encoderNomeHtml = $encoder -> encodeForHTML($name);</span><br />
?><br />
<p>Hello, <?=$encoderNomeHtml?></p>
</code>
</p>
<p><b>For the HTML attribute, the updated page uses ESAPI::getEncoder()->encodeForHTMLAttribute($name).
This call does a slightly different encoding that is more effective with attributes.</b></p>
<p class="newsItem">
<code>
<?php<br/>
<span style="padding-left: 25px;">require_once dirname(__FILE__).'/src/ESAPI.php';</span><br />
<span style="padding-left: 25px;">$ESAPI = new ESAPI(dirname(__FILE__)."/ESAPI.xml");</span><br />
<span style="padding-left: 25px;">$ESAPI = new ESAPI();</span><br />
<br />
<span style="padding-left: 25px;">$encoder = ESAPI::getEncoder();</span><br />
<span style="padding-left: 25px;">$encoderNomeHtml = $encoder -> encodeForHTML($name);</span><br />
?><br />
<form action="main.php?function=OutputUserInput&secure" method="POST"><br />
<span style="padding-left: 25px;"><p>Enter your name:</p></span><br />
<span style="padding-left: 25px;"><input name='name' value='<?=$encoderNomeHtml ?>'></span><br />
<span style="padding-left: 25px;"><input type='submit' value='submit'></span><br />
</form>
</code>
</p>
<?php include("footer.php"); ?>
| convisoappsec/swingset-php | OutputUserInputTutorial.php | PHP | bsd-3-clause | 3,613 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebServices.Models.Dtos
{
public class DtoStory
{
public Guid storyId { get; set; }
public String title { get; set; }
public String subtitle { get; set; }
public String body { get; set; }
public DateTime datePublished { get; set; }
public DtoUser author { get; set; }
public double ? lat { get; set; }
public double ? lng { get; set; }
public DtoCategory category { get; set; }
public static DtoStory dtoFromStory (Story story)
{
DtoUser user = DtoUser.UserForUserId(story.authorId);
if (user != null)
{
DtoStory dto = new DtoStory();
dto.storyId = story.Id;
dto.author = DtoUser.UserForUserId(story.authorId);
dto.datePublished = story.DatePublished.ToUniversalTime();
dto.title = story.Title;
dto.subtitle = story.Subtitle;
dto.body = story.Body;
dto.lat = story.Lat;
dto.lng = story.Lng;
dto.category = DtoCategory.dtoFromCategory(story.Category);
return dto;
}
return null;
}
public static DtoStory lightDtoFromStory(Story story)
{
DtoUser user = DtoUser.UserForUserId(story.authorId);
if (user != null)
{
DtoStory dto = new DtoStory();
dto.storyId = story.Id;
dto.author = DtoUser.UserForUserId(story.authorId);
dto.datePublished = story.DatePublished.ToUniversalTime();
dto.title = story.Title;
dto.subtitle = story.Subtitle;
dto.body = null;
dto.lat = story.Lat;
dto.lng = story.Lng;
dto.category = DtoCategory.dtoFromCategory(story.Category);
return dto;
}
return null;
}
public static Story newStoryFromDto(DtoAddStory dtoStory)
{
//Check for user
DtoUser user = DtoUser.UserForUserId(dtoStory.authorId);
if (user != null)
{
Story story = new Story();
story.Id = Guid.NewGuid();
story.authorId = user.Id;
story.DatePublished = DateTime.UtcNow;
story.DateUpdated = DateTime.UtcNow;
story.Body = dtoStory.body;
story.Title = dtoStory.title;
story.Subtitle = dtoStory.subtitle;
story.Lat = dtoStory.lat;
story.Lng = dtoStory.lng;
return story;
}
return null;
}
}
} | UA-CS491-591/WashingtonHerald | Project2/WebServices/Models/Dtos/DtoStory.cs | C# | bsd-3-clause | 2,859 |
<?php
declare(strict_types=1);
namespace GitList\SCM;
class Branch
{
public function __construct(protected Repository $repository, protected string $name, protected Commit $target)
{
}
public function getRepository(): Repository
{
return $this->repository;
}
public function getName(): string
{
return $this->name;
}
public function getTarget(): Commit
{
return $this->target;
}
}
| klaussilveira/gitlist | src/SCM/Branch.php | PHP | bsd-3-clause | 459 |
/*
* Copyright 2013 Couchbase, 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 "hash.h"
#include "pwfile.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
static cb_mutex_t uhash_lock;
static user_db_entry_t **user_ht;
static const unsigned int n_uht_buckets = 12289;
void pwfile_init(void)
{
cb_mutex_initialize(&uhash_lock);
}
void pwfile_term(void)
{
free_user_ht();
cb_mutex_destroy(&uhash_lock);
}
static void kill_whitey(char *s)
{
for (size_t i = strlen(s) - 1; i > 0 && isspace(s[i]); i--) {
s[i] = '\0';
}
}
static int u_hash_key(const char *u)
{
uint32_t h = hash(u, strlen(u), 0) % n_uht_buckets;
cb_assert(h < n_uht_buckets);
return h;
}
static const char *get_isasl_filename(void)
{
return getenv("ISASL_PWFILE");
}
void free_user_ht(void)
{
if (user_ht) {
for (unsigned int i = 0; i < n_uht_buckets; i++) {
while (user_ht[i]) {
user_db_entry_t *e = user_ht[i];
user_db_entry_t *n = e->next;
free(e->username);
free(e->password);
free(e->config);
free(e);
user_ht[i] = n;
}
}
free(user_ht);
user_ht = NULL;
}
}
static void store_pw(user_db_entry_t **ht,
const char *u,
const char *p,
const char *cfg)
{
user_db_entry_t *e;
int h;
cb_assert(ht);
cb_assert(u);
cb_assert(p);
e = calloc(1, sizeof(user_db_entry_t));
cb_assert(e);
e->username = strdup(u);
cb_assert(e->username);
e->password = strdup(p);
cb_assert(e->password);
e->config = cfg ? strdup(cfg) : NULL;
cb_assert(!cfg || e->config);
h = u_hash_key(u);
e->next = ht[h];
ht[h] = e;
}
char *find_pw(const char *u, char **cfg)
{
int h;
user_db_entry_t *e;
cb_assert(u);
cb_assert(user_ht);
cb_mutex_enter(&uhash_lock);
h = u_hash_key(u);
e = user_ht[h];
while (e && strcmp(e->username, u) != 0) {
e = e->next;
}
if (e != NULL) {
*cfg = e->config;
cb_mutex_exit(&uhash_lock);
return e->password;
} else {
cb_mutex_exit(&uhash_lock);
return NULL;
}
}
cbsasl_error_t load_user_db(void)
{
user_db_entry_t **new_ut;
FILE *sfile;
char up[128];
const char *filename = get_isasl_filename();
if (!filename) {
return CBSASL_OK;
}
sfile = fopen(filename, "r");
if (!sfile) {
return CBSASL_FAIL;
}
new_ut = calloc(n_uht_buckets, sizeof(user_db_entry_t *));
if (!new_ut) {
fclose(sfile);
return CBSASL_NOMEM;
}
/* File has lines that are newline terminated. */
/* File may have comment lines that must being with '#'. */
/* Lines should look like... */
/* <NAME><whitespace><PASSWORD><whitespace><CONFIG><optional_whitespace> */
/* */
while (fgets(up, sizeof(up), sfile)) {
if (up[0] != '#') {
char *uname = up, *p = up, *cfg = NULL;
kill_whitey(up);
while (*p && !isspace(p[0])) {
p++;
}
/* If p is pointing at a NUL, there's nothing after the username. */
if (p[0] != '\0') {
p[0] = '\0';
p++;
}
/* p now points to the first character after the (now) */
/* null-terminated username. */
while (*p && isspace(*p)) {
p++;
}
/* p now points to the first non-whitespace character */
/* after the above */
cfg = p;
if (cfg[0] != '\0') {
/* move cfg past the password */
while (*cfg && !isspace(cfg[0])) {
cfg++;
}
if (cfg[0] != '\0') {
cfg[0] = '\0';
cfg++;
/* Skip whitespace */
while (*cfg && isspace(cfg[0])) {
cfg++;
}
}
}
store_pw(new_ut, uname, p, cfg);
}
}
fclose(sfile);
/*
if (settings.verbose) {
settings.extensions.logger->log(EXTENSION_LOG_INFO, NULL,
"Loaded isasl db from %s\n",
filename);
}
*/
/* Replace the current configuration with the new one */
cb_mutex_enter(&uhash_lock);
free_user_ht();
user_ht = new_ut;
cb_mutex_exit(&uhash_lock);
return CBSASL_OK;
}
| cloudrain21/memcached-1 | cbsasl/pwfile.c | C | bsd-3-clause | 5,161 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.