text
stringlengths 2
100k
| meta
dict |
---|---|
0.000 0.000 0.000
219.686 -8806.570 150.957
370.589 -9071.102 145.344
546.270 -9159.442 139.474
703.927 -9184.024 128.174
917.546 -9200.090 114.657
1099.316 -9048.979 155.531
1143.439 -8835.444 174.167
1124.285 -8596.314 179.069
1014.640 -8453.838 172.651
901.359 -8375.313 163.423
655.820 -8331.128 145.360
541.919 -8469.133 145.360
327.881 -8518.503 145.360
342.557 -8299.280 134.421
361.494 -8120.454 126.570
122.280 -7894.312 120.280
305.737 -7773.131 117.193
503.440 -7676.925 113.822
697.730 -7629.715 109.102
790.460 -7874.343 108.630
790.460 -7874.343 108.630
1109.806 -7740.153 129.112
1083.991 -7582.427 136.428
1034.679 -7347.901 146.540
992.915 -7235.798 149.553
748.516 -7098.614 154.783
673.415 -7125.758 154.783
697.575 -6927.227 155.543
652.249 -6740.752 162.088
555.324 -6765.313 162.088
437.778 -6788.952 162.088
800.894 -6542.954 168.695
865.730 -6393.424 172.975
835.951 -6255.288 177.594
566.111 -6133.252 182.335
744.892 -5991.736 185.653
866.491 -5812.417 190.407
1097.189 -5500.215 198.600
804.449 -5270.404 205.734
564.688 -5259.705 205.734
364.887 -5250.789 205.734
241.075 -4884.974 212.761
388.961 -4711.435 216.549
654.035 -4603.539 219.075
933.717 -4616.875 219.075
930.630 -4396.925 222.423
619.004 -4246.919 224.180
639.642 -4008.362 231.598
720.325 -3780.277 245.444
958.187 -3809.581 245.444
971.174 -3530.171 258.164
597.522 -3376.754 264.981
563.670 -3155.927 276.940
563.670 -3155.927 276.940
846.678 -2870.130 363.628
720.942 -2722.658 386.587
527.678 -2540.747 400.517
481.802 -2264.421 452.689
829.216 -2124.297 504.643
757.009 -1903.493 525.414
520.703 -1778.284 529.764
784.181 -1420.800 521.318
614.830 -1245.376 491.900
597.115 -792.515 413.770
575.837 -611.316 380.369
496.439 -601.116 380.369
814.845 -632.974 380.369
1013.418 -656.796 380.369
1048.039 -241.745 326.345
655.008 -50.441 301.834
427.626 159.665 271.424
590.129 435.352 243.962
455.161 638.681 231.166
663.646 911.815 228.165
930.880 1122.966 226.813
774.464 1247.277 227.320
560.940 1504.772 232.332
413.587 1852.546 244.513
818.736 2043.561 257.523
563.810 2244.465 282.917
746.203 2534.379 315.277
488.348 2745.529 372.008
409.615 2890.416 425.194
527.020 2965.353 446.994
747.373 3245.750 411.180
977.464 3230.828 374.773
1270.020 3058.591 337.106
1273.634 4435.839 631.684
2522.179 2026.917 707.534
3241.267 -463.888 798.293
1443.224 -2030.998 1433.135
771.089 458.147 1493.742
728.072 -707.680 1346.888
681.286 -1675.719 1215.771
791.969 -3818.107 1043.320
558.139 -5068.225 820.663
763.263 -6556.163 768.907
1027.935 -7954.292 686.814
807.722 -8858.603 628.986
410.689 -9689.826 612.477
| {
"pile_set_name": "Github"
} |
namespace Acme.PhoneBook
{
public class PhoneBookConsts
{
public const string LocalizationSourceName = "PhoneBook";
public const string ConnectionStringName = "Default";
public const bool MultiTenancyEnabled = true;
}
} | {
"pile_set_name": "Github"
} |
{
"parent": "item/handheld",
"textures": {
"layer0": "ancientwarfare:items/core/diamond_quill"
}
} | {
"pile_set_name": "Github"
} |
// test that we can include umm_malloc.h from sketch (#1652)
#include <umm_malloc/umm_malloc.h>
#include <BSTest.h>
BS_ENV_DECLARE();
void setup()
{
Serial.begin(115200);
BS_RUN(Serial);
}
bool pretest()
{
return true;
}
TEST_CASE("umm_info can be called", "[umm_malloc]")
{
umm_info(NULL, 1);
}
void loop()
{
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 1993-2015 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/* CUda UTility Library */
#ifndef _EXCEPTION_H_
#define _EXCEPTION_H_
// includes, system
#include <exception>
#include <stdexcept>
#include <iostream>
#include <stdlib.h>
//! Exception wrapper.
//! @param Std_Exception Exception out of namespace std for easy typing.
template<class Std_Exception>
class Exception : public Std_Exception
{
public:
//! @brief Static construction interface
//! @return Alwayss throws ( Located_Exception<Exception>)
//! @param file file in which the Exception occurs
//! @param line line in which the Exception occurs
//! @param detailed details on the code fragment causing the Exception
static void throw_it(const char *file,
const int line,
const char *detailed = "-");
//! Static construction interface
//! @return Alwayss throws ( Located_Exception<Exception>)
//! @param file file in which the Exception occurs
//! @param line line in which the Exception occurs
//! @param detailed details on the code fragment causing the Exception
static void throw_it(const char *file,
const int line,
const std::string &detailed);
//! Destructor
virtual ~Exception() throw();
private:
//! Constructor, default (private)
Exception();
//! Constructor, standard
//! @param str string returned by what()
Exception(const std::string &str);
};
////////////////////////////////////////////////////////////////////////////////
//! Exception handler function for arbitrary exceptions
//! @param ex exception to handle
////////////////////////////////////////////////////////////////////////////////
template<class Exception_Typ>
inline void
handleException(const Exception_Typ &ex)
{
std::cerr << ex.what() << std::endl;
exit(EXIT_FAILURE);
}
//! Convenience macros
//! Exception caused by dynamic program behavior, e.g. file does not exist
#define RUNTIME_EXCEPTION( msg) \
Exception<std::runtime_error>::throw_it( __FILE__, __LINE__, msg)
//! Logic exception in program, e.g. an assert failed
#define LOGIC_EXCEPTION( msg) \
Exception<std::logic_error>::throw_it( __FILE__, __LINE__, msg)
//! Out of range exception
#define RANGE_EXCEPTION( msg) \
Exception<std::range_error>::throw_it( __FILE__, __LINE__, msg)
////////////////////////////////////////////////////////////////////////////////
//! Implementation
// includes, system
#include <sstream>
////////////////////////////////////////////////////////////////////////////////
//! Static construction interface.
//! @param Exception causing code fragment (file and line) and detailed infos.
////////////////////////////////////////////////////////////////////////////////
/*static*/ template<class Std_Exception>
void
Exception<Std_Exception>::
throw_it(const char *file, const int line, const char *detailed)
{
std::stringstream s;
// Quiet heavy-weight but exceptions are not for
// performance / release versions
s << "Exception in file '" << file << "' in line " << line << "\n"
<< "Detailed description: " << detailed << "\n";
throw Exception(s.str());
}
////////////////////////////////////////////////////////////////////////////////
//! Static construction interface.
//! @param Exception causing code fragment (file and line) and detailed infos.
////////////////////////////////////////////////////////////////////////////////
/*static*/ template<class Std_Exception>
void
Exception<Std_Exception>::
throw_it(const char *file, const int line, const std::string &msg)
{
throw_it(file, line, msg.c_str());
}
////////////////////////////////////////////////////////////////////////////////
//! Constructor, default (private).
////////////////////////////////////////////////////////////////////////////////
template<class Std_Exception>
Exception<Std_Exception>::Exception() :
Exception("Unknown Exception.\n")
{ }
////////////////////////////////////////////////////////////////////////////////
//! Constructor, standard (private).
//! String returned by what().
////////////////////////////////////////////////////////////////////////////////
template<class Std_Exception>
Exception<Std_Exception>::Exception(const std::string &s) :
Std_Exception(s)
{ }
////////////////////////////////////////////////////////////////////////////////
//! Destructor
////////////////////////////////////////////////////////////////////////////////
template<class Std_Exception>
Exception<Std_Exception>::~Exception() throw() { }
// functions, exported
#endif // #ifndef _EXCEPTION_H_
| {
"pile_set_name": "Github"
} |
categories:
- conversations
conversations:
- - Guten Morgen, wie geht es dir?
- Mir geht es gut und wie geht es dir?
- Mir geht es auch gut
- Das ist schön zu hören.
- Ja, das ist es
- - Hallo
- Hi
- Wie geht es dir?
- Mir geht es sehr gut.
- Das ist schön zu hören.
- Ja, das ist es
- Kann ich dir irgendwie helfen??
- Ja, ich habe eine Frage
- Was ist deine Frage?
- Kann ich mir ein Stück Zucker leihen?
- Tut mir leid, aber ich habe keines
- Trotzdem danke
- Kein Problem
- - Wie geht es dir?
- Mir geht es gut und wie geht es dir?
- Mir geht es auch gut
- Das ist schön
- - Hast du die Nachrichten gehört?
- Welche guten Nachrichten?
- - Was ist dein Lieblingsbuch?
- Ich kann nicht lesen
- Was ist dann deine Lieblingfarbe?
- Blau
- - Ich arbeite an einem Projekt
- An was arbeitest du?
- ich backe einen Kuchen
- - Der Kuchen ist eine Lüge.
- Nein ist er nicht. Er ist sehr lecker.
- Was ist noch lecker?
- Nichts
- Erzähl mir etwas über dich.
- Was möchtest du wissen?
- Bist du ein Roboter?
- Ja, das bin ich
- Wie ist das?
- Was möchtest du genau wissen?
- Wie funktionierst du?
- Das ist kompliziert
- Komplex ist besser als kompliziert
- - Bist du ein Programmierer?
- Ja, ich bin ein Programmierer
- Welche Sprachen benutzt du gerne?
- Ich benutze oft C#, Java und Python.
- Ich selbst benutze auch ein bisschen Python.
- - Was bedeutet YOLO?
- Es bedeutet you only live once. Wo hast du das gehört?
- Ich habe es jemanden sagen hören.
- - Habe ich jemals gelebt?
- Das kommt darauf an, wie du Leben definierst.
- Leben ist Vorraussetzung, dass ein Organismus von alleine wachsen kann, sich fortplanzen
und auf Reize reagieren kann. Außerdem muss er Stoffwechsel betreiben und irgendwann
stirbt er
- Ist das eine Definition oder eine Option?
- - Kann ich dich etwas fragen?
- Gerne, frag nur
| {
"pile_set_name": "Github"
} |
{
"CVE_data_meta": {
"ASSIGNER": "[email protected]",
"ID": "CVE-2008-3503",
"STATE": "PUBLIC"
},
"affects": {
"vendor": {
"vendor_data": [
{
"product": {
"product_data": [
{
"product_name": "n/a",
"version": {
"version_data": [
{
"version_value": "n/a"
}
]
}
}
]
},
"vendor_name": "n/a"
}
]
}
},
"data_format": "MITRE",
"data_type": "CVE",
"data_version": "4.0",
"description": {
"description_data": [
{
"lang": "eng",
"value": "RSSFromParent in Plain Black WebGUI before 7.5.13 does not restrict view access to Collaboration System (CS) RSS feeds, which allows remote attackers to obtain sensitive information (CS data)."
}
]
},
"problemtype": {
"problemtype_data": [
{
"description": [
{
"lang": "eng",
"value": "n/a"
}
]
}
]
},
"references": {
"reference_data": [
{
"name": "webgui-collaboration-info-disclosure(43344)",
"refsource": "XF",
"url": "https://exchange.xforce.ibmcloud.com/vulnerabilities/43344"
},
{
"name": "http://www.webgui.org/bugs/tracker/security-issue---collaboration-rss/",
"refsource": "MISC",
"url": "http://www.webgui.org/bugs/tracker/security-issue---collaboration-rss/"
},
{
"name": "http://www.webgui.org/getwebgui/advisories/webgui-7_5_13-beta-released",
"refsource": "CONFIRM",
"url": "http://www.webgui.org/getwebgui/advisories/webgui-7_5_13-beta-released"
},
{
"name": "29927",
"refsource": "BID",
"url": "http://www.securityfocus.com/bid/29927"
},
{
"name": "30782",
"refsource": "SECUNIA",
"url": "http://secunia.com/advisories/30782"
},
{
"name": "ADV-2008-1932",
"refsource": "VUPEN",
"url": "http://www.vupen.com/english/advisories/2008/1932/references"
}
]
}
} | {
"pile_set_name": "Github"
} |
documentation_complete: true
prodtype: fedora,rhcos4,ol7,ol8,rhel7,rhel8
title: 'Record Events that Modify User/Group Information via open syscall - /etc/shadow'
description: |-
The audit system should collect write events to /etc/shadow file for all users and root.
If the <tt>auditd</tt> daemon is configured
to use the <tt>augenrules</tt> program to read audit rules during daemon
startup (the default), add the following lines to a file with suffix
<tt>.rules</tt> in the directory <tt>/etc/audit/rules.d</tt>:
<pre>-a always,exit -F arch=b32 -S open -F a1&03 -F path=/etc/shadow -F auid>={{{ auid }}} -F auid!=unset -F key=user-modify</pre>
If the <tt>auditd</tt> daemon is configured to use the <tt>auditctl</tt>
utility to read audit rules during daemon startup, add the following lines to
<tt>/etc/audit/audit.rules</tt> file:
<pre>-a always,exit -F arch=b32 -S open -F a1&03 -F path=/etc/shadow -F auid>={{{ auid }}} -F auid!=unset -F key=user-modify</pre>
If the system is 64 bit then also add the following line:
<pre>-a always,exit -F arch=b64 -S open -F a1&03 -F path=/etc/shadow -F auid>={{{ auid }}} -F auid!=unset -F key=user-modify</pre>
rationale: |-
Creation of users through direct edition of /etc/shadow could be an indicator of malicious activity on a system.
Auditing these events could serve as evidence of potential system compromise.
severity: medium
identifiers:
cce@rhel8: CCE-80956-6
cce@rhcos4: CCE-82709-7
references:
nist: AC-2(4),AU-2(d),AU-12(c),AC-6(9),CM-6(a)
ospp: FAU_GEN.1.1.c
{{{ complete_ocil_entry_audit_syscall(syscall="open") }}}
warnings:
- general: |-
Note that these rules can be configured in a
number of ways while still achieving the desired effect. Here the system calls
have been placed independent of other system calls. Grouping system calls related
to the same event is more efficient. See the following example:
<pre>-a always,exit -F arch=b32 -S open,openat,open_by_handle_at -F a1&03 -F path=/etc/shadow -F auid>={{{ auid }}} -F auid!=unset -F key=user-modify</pre>
template:
name: audit_rules_path_syscall
vars:
path: /etc/shadow
pos: a1
syscall: open
| {
"pile_set_name": "Github"
} |
---
title: "Spherical harmonic I/O, storage, and conversions"
keywords: spherical harmonics software package, spherical harmonic transform, legendre functions, multitaper spectral analysis, fortran, Python, gravity, magnetic field
sidebar: fortran_sidebar
permalink: io.html
summary:
toc: true
folder: fortran
---
<style>
table:nth-of-type(n) {
display:table;
width:100%;
}
table:nth-of-type(n) th:nth-of-type(2) {
width:75%;
}
</style>
## Spherical harmonic I/O
| Routine name | Description |
| ------------ | ----------- |
| [SHRead](shread.html) | Read spherical harmonic coefficients from an ascii-formatted file. |
| [SHRead2](shread2.html) | Read spherical harmonic coefficients from a CHAMP or GRACE-like ASCII file. |
| [SHReadJPL](shreadjpl.html) | Read spherical harmonic coefficients from a JPL ASCII file. |
## Spherical harmonic storage
| Routine name | Description |
| ------------ | ----------- |
| [SHCilmToCindex](shcilmtocindex.html) | Convert a three-dimensional array of complex spherical harmonic coefficients to a two-dimensional indexed array. |
| [SHCindexToCilm](shcindextocilm.html) | Convert a two-dimensional indexed array of complex spherical harmonic coefficients to a three-dimensional array. |
| [SHCilmToVector](shcilmtovector.html) | Convert a 3-dimensional array of real spherical harmonic coefficients to a 1-dimensional ordered array. |
| [SHVectorToCilm](shvectortocilm.html) | Convert a 1-dimensional indexed vector of real spherical harmonic coefficients to a 3-dimensional array. |
| [YilmIndexVector](yilmindexvector.html) | Determine the index of a 1D ordered vector of spherical harmonic coefficients corresponding to i, l, and m. |
## Spherical harmonic conversions
| Routine name | Description |
| ------------ | ----------- |
| [SHrtoc](shrtoc.html) | Convert real spherical harmonics to complex form. |
| [SHctor](shctor.html) | Convert complex spherical harmonics to real form. |
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.KoubeiSalesKbassetStuffFeedbackstockorderSyncModel import KoubeiSalesKbassetStuffFeedbackstockorderSyncModel
class KoubeiSalesKbassetStuffFeedbackstockorderSyncRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._udf_params = None
self._need_encrypt = False
@property
def biz_model(self):
return self._biz_model
@biz_model.setter
def biz_model(self, value):
self._biz_model = value
@property
def biz_content(self):
return self._biz_content
@biz_content.setter
def biz_content(self, value):
if isinstance(value, KoubeiSalesKbassetStuffFeedbackstockorderSyncModel):
self._biz_content = value
else:
self._biz_content = KoubeiSalesKbassetStuffFeedbackstockorderSyncModel.from_alipay_dict(value)
@property
def version(self):
return self._version
@version.setter
def version(self, value):
self._version = value
@property
def terminal_type(self):
return self._terminal_type
@terminal_type.setter
def terminal_type(self, value):
self._terminal_type = value
@property
def terminal_info(self):
return self._terminal_info
@terminal_info.setter
def terminal_info(self, value):
self._terminal_info = value
@property
def prod_code(self):
return self._prod_code
@prod_code.setter
def prod_code(self, value):
self._prod_code = value
@property
def notify_url(self):
return self._notify_url
@notify_url.setter
def notify_url(self, value):
self._notify_url = value
@property
def return_url(self):
return self._return_url
@return_url.setter
def return_url(self, value):
self._return_url = value
@property
def udf_params(self):
return self._udf_params
@udf_params.setter
def udf_params(self, value):
if not isinstance(value, dict):
return
self._udf_params = value
@property
def need_encrypt(self):
return self._need_encrypt
@need_encrypt.setter
def need_encrypt(self, value):
self._need_encrypt = value
def add_other_text_param(self, key, value):
if not self.udf_params:
self.udf_params = dict()
self.udf_params[key] = value
def get_params(self):
params = dict()
params[P_METHOD] = 'koubei.sales.kbasset.stuff.feedbackstockorder.sync'
params[P_VERSION] = self.version
if self.biz_model:
params[P_BIZ_CONTENT] = json.dumps(obj=self.biz_model.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
if self.biz_content:
if hasattr(self.biz_content, 'to_alipay_dict'):
params['biz_content'] = json.dumps(obj=self.biz_content.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
else:
params['biz_content'] = self.biz_content
if self.terminal_type:
params['terminal_type'] = self.terminal_type
if self.terminal_info:
params['terminal_info'] = self.terminal_info
if self.prod_code:
params['prod_code'] = self.prod_code
if self.notify_url:
params['notify_url'] = self.notify_url
if self.return_url:
params['return_url'] = self.return_url
if self.udf_params:
params.update(self.udf_params)
return params
def get_multipart_params(self):
multipart_params = dict()
return multipart_params
| {
"pile_set_name": "Github"
} |
// Copyright 2018 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.
// +build !aix,!darwin,!dragonfly,!freebsd,!hurd,!linux,!netbsd,!openbsd,!plan9,!solaris,!windows
package filelock
import "os"
type lockType int8
const (
readLock = iota + 1
writeLock
)
func lock(f File, lt lockType) error {
return &os.PathError{
Op: lt.String(),
Path: f.Name(),
Err: ErrNotSupported,
}
}
func unlock(f File) error {
return &os.PathError{
Op: "Unlock",
Path: f.Name(),
Err: ErrNotSupported,
}
}
func isNotSupported(err error) bool {
return err == ErrNotSupported
}
| {
"pile_set_name": "Github"
} |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="stylesheet" type="text/css" href="../stylesheets/style.css">
<title>FilterChains and FilterReaders</title>
</head>
<body>
<h2>FilterChains and FilterReaders</h2>
Consider the flexibility of Unix pipes. If you wanted,
for example, to copy just those lines that contained the
string blee from the first 10 lines of a text file 'foo'
(<em>you wouldn't want to filter a binary file</em>)
to a file 'bar', you would do something like:<p>
<code>
cat foo|head -n10|grep blee > bar
</code><p>
Apache Ant was not flexible enough. There was no way for the
<code><copy></code> task to do something similar. If you wanted
the <code><copy></code> task to get the first 10 lines, you would have
had to create special attributes:<p>
<code>
<copy file="foo" tofile="bar" head="10" contains="blee"/>
</code><p>
The obvious problem thus surfaced: Ant tasks would not be able
to accommodate such data transformation attributes as they would
be endless. The task would also not know in which order these
attributes were to be interpreted. That is, must the task execute the
contains attribute first and then the head attribute or vice-versa?
What Ant tasks needed was a mechanism to allow pluggable filter (data
transformer) chains. Ant would provide a few filters for which there
have been repeated requests. Users with special filtering needs
would be able to easily write their own and plug them in.<p>
The solution was to refactor data transformation oriented
tasks to support FilterChains. A FilterChain is a group of
ordered FilterReaders. Users can define their own FilterReaders
by just extending the java.io.FilterReader class. Such custom
FilterReaders can be easily plugged in as nested elements of
<code><filterchain></code> by using <code><filterreader></code> elements.
<p>
Example:
<blockquote><pre>
<copy file="${src.file}" tofile="${dest.file}">
<filterchain>
<filterreader classname="your.extension.of.java.io.FilterReader">
<param name="foo" value="bar"/>
</filterreader>
<filterreader classname="another.extension.of.java.io.FilterReader">
<classpath>
<pathelement path="${classpath}"/>
</classpath>
<param name="blah" value="blee"/>
<param type="abra" value="cadabra"/>
</filterreader>
</filterchain>
</copy>
</pre></blockquote>
Ant provides some built-in filter readers. These filter readers
can also be declared using a syntax similar to the above syntax.
However, they can be declared using some simpler syntax also.<p>
Example:
<blockquote><pre>
<loadfile srcfile="${src.file}" property="src.file.head">
<filterchain>
<headfilter lines="15"/>
</filterchain>
</loadfile>
</pre></blockquote>
is equivalent to:
<blockquote><pre>
<loadfile srcfile="${src.file}" property="src.file.head">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.HeadFilter">
<param name="lines" value="15"/>
</filterreader>
</filterchain>
</loadfile>
</pre></blockquote>
The following built-in tasks support nested <code><filterchain></code> elements.<br>
<a href="../Tasks/concat.html">Concat</a>,<br>
<a href="../Tasks/copy.html">Copy</a>,<br>
<a href="../Tasks/loadfile.html">LoadFile</a>,<br>
<a href="../Tasks/loadproperties.html">LoadProperties</a>,<br>
<a href="../Tasks/loadresource.html">LoadResource</a>,<br>
<a href="../Tasks/move.html">Move</a><br><br>
A FilterChain is formed by defining zero or more of the following
nested elements.<br>
<a href="#filterreader">FilterReader</a><br>
<a href="#classconstants">ClassConstants</a><br>
<a href="#escapeunicode">EscapeUnicode</a><br>
<a href="#expandproperties">ExpandProperties</a><br>
<a href="#headfilter">HeadFilter</a><br>
<a href="#linecontains">LineContains</a><br>
<a href="#linecontainsregexp">LineContainsRegExp</a><br>
<a href="#prefixlines">PrefixLines</a><br>
<a href="#replacetokens">ReplaceTokens</a><br>
<a href="#stripjavacomments">StripJavaComments</a><br>
<a href="#striplinebreaks">StripLineBreaks</a><br>
<a href="#striplinecomments">StripLineComments</a><br>
<a href="#suffixlines">SuffixLines</a><br>
<a href="#tabstospaces">TabsToSpaces</a><br>
<a href="#tailfilter">TailFilter</a><br>
<a href="#deletecharacters">DeleteCharacters</a><br>
<a href="#concatfilter">ConcatFilter</a><br>
<a href="#tokenfilter">TokenFilter</a><br>
<a href="../Tasks/fixcrlf.html">FixCRLF</a><br>
<a href="#sortfilter">SortFilter</a><br>
<h3><a name="filterreader">FilterReader</a></h3>
The filterreader element is the generic way to
define a filter. User defined filter elements are
defined in the build file using this. Please note that
built in filter readers can also be defined using this
syntax.
A FilterReader element must be supplied with a class name as
an attribute value. The class resolved by this name must
extend java.io.FilterReader. If the custom filter reader
needs to be parameterized, it must implement
org.apache.tools.type.Parameterizable.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>classname</td>
<td vAlign=top>The class name of the filter reader.</td>
<td vAlign=top align="center">Yes</td>
</tr>
</table>
<p>
<h4>Nested Elements:</h4>
<code><filterreader></code> supports <code><classpath></code> and <code><param></code>
as nested elements. Each <code><param></code> element may take in the following
attributes - name, type and value.
<p>
The following FilterReaders are supplied with the default
distribution.
<h3><a name="classconstants">ClassConstants</a></h3>
<p>
This filters basic constants defined in a Java Class,
and outputs them in lines composed of the format <i>name</i>=<i>value</i>.
This filter uses the <em>bcel</em> library to understand the Java Class file.
See <a href="../install.html#librarydependencies">Library Dependencies</a>.
<p>
<p>
<em><b>Important:</b></em>
This filter is different from most of the other filters.
Most of the filters operate on a sequence of characters.
This filter operates on the sequence of bytes that makes up
a class. However the bytes arrive to the filter as a sequence
of characters. This means that one must be careful on the
choice of character encoding to use. Most encoding lose information
on conversion from an arbitrary sequence of bytes to characters
and back again to bytes. In particular the usual default
character encodings (CP152 and UTF-8) do.
For this reason, <em>since Ant 1.7</em>, the character
encoding <b>ISO-8859-1</b> is used to convert from characters back to
bytes, so one <b>has</b> to use this encoding for reading the java
class file.
<h4>Example:</h4>
This loads the basic constants defined in a Java class as Ant properties.
<blockquote><pre>
<loadproperties srcfile="foo.class" encoding="ISO-8859-1">
<filterchain>
<classconstants/>
</filterchain>
</loadproperties>
</pre></blockquote>
This loads the constants from a Java class file as Ant properties,
prepending the names with a prefix.
<blockquote><pre>
<loadproperties srcfile="build/classes/org/acme/bar.class"
encoding="ISO-8859-1">
<filterchain>
<classconstants/>
<prefixlines prefix="ini."/>
</filterchain>
</loadproperties>
</pre></blockquote>
<h3><a name="escapeunicode">EscapeUnicode</a></h3>
<p>
This filter converts its input by changing all non US-ASCII characters
into their equivalent unicode escape backslash u plus 4 digits.</p>
<p><em>since Ant 1.6</em></p>
<h4>Example:</h4>
This loads the basic constants defined in a Java class as Ant properties.
<blockquote><pre>
<loadproperties srcfile="non_ascii_property.properties">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.EscapeUnicode"/>
</filterchain>
</loadproperties>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<loadproperties srcfile="non_ascii_property.properties">
<filterchain>
<escapeunicode/>
</filterchain>
</loadproperties>
</pre></blockquote>
<h3><a name="expandproperties">ExpandProperties</a></h3>
<p>
If the data contains data that represents Ant
properties (of the form ${...}), that is substituted
with the property's actual value.
<p>
<h4>Example:</h4>
This results in the property modifiedmessage holding the value
"All these moments will be lost in time, like teardrops in the rain"
<blockquote><pre>
<echo
message="All these moments will be lost in time, like teardrops in the ${weather}"
file="loadfile1.tmp"
/>
<property name="weather" value="rain"/>
<loadfile property="modifiedmessage" srcFile="loadfile1.tmp">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.ExpandProperties"/>
</filterchain>
</loadfile>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<echo
message="All these moments will be lost in time, like teardrops in the ${weather}"
file="loadfile1.tmp"
/>
<property name="weather" value="rain"/>
<loadfile property="modifiedmessage" srcFile="loadfile1.tmp">
<filterchain>
<expandproperties/>
</filterchain>
</loadfile>
</pre></blockquote>
<p>As of Ant <strong>1.8.3</strong>, a nested
<a href="propertyset.html">PropertySet</a> can be specified:
<blockquote><pre>
<property name="weather" value="rain"/>
<loadfile property="modifiedmessage" srcFile="loadfile1.tmp">
<filterchain>
<expandproperties>
<propertyset>
<propertyref name="weather" />
</propertyset>
</expandproperties>
</filterchain>
</loadfile>
</pre></blockquote>
<h3><a name="headfilter">HeadFilter</a></h3>
This filter reads the first few lines from the data supplied to it.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>lines</td>
<td vAlign=top align="center">Number of lines to be read.
Defaults to "10" <br> A negative value means that all lines are
passed (useful with <i>skip</i>)</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>skip</td>
<td vAlign=top align="center">Number of lines to be skipped (from the beginning).
Defaults to "0"</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<p>
<h4>Example:</h4>
This stores the first 15 lines of the supplied data in the property src.file.head
<blockquote><pre>
<loadfile srcfile="${src.file}" property="src.file.head">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.HeadFilter">
<param name="lines" value="15"/>
</filterreader>
</filterchain>
</loadfile>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<loadfile srcfile="${src.file}" property="src.file.head">
<filterchain>
<headfilter lines="15"/>
</filterchain>
</loadfile>
</pre></blockquote>
This stores the first 15 lines, skipping the first 2 lines, of the supplied data
in the property src.file.head. (Means: lines 3-17)
<blockquote><pre>
<loadfile srcfile="${src.file}" property="src.file.head">
<filterchain>
<headfilter lines="15" skip="2"/>
</filterchain>
</loadfile>
</pre></blockquote>
See the testcases for more examples (<i>src\etc\testcases\filters\head-tail.xml</i> in the
source distribution).
<h3><a name="linecontains">LineContains</a></h3>
This filter includes only those lines that contain all the user-specified
strings.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Type</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>contains</td>
<td vAlign=top align="center">Substring to be searched for.</td>
<td vAlign=top align="center">Yes</td>
</tr>
<tr>
<td vAlign=top>negate</td>
<td vAlign=top align="center">Whether to select
<i>non-</i>matching lines only. <b>Since Ant 1.7</b></td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<p>
<h4>Example:</h4>
This will include only those lines that contain <code>foo</code> and
<code>bar</code>.
<blockquote><pre>
<filterreader classname="org.apache.tools.ant.filters.LineContains">
<param type="contains" value="foo"/>
<param type="contains" value="bar"/>
</filterreader>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<linecontains>
<contains value="foo"/>
<contains value="bar"/>
</linecontains>
</pre></blockquote>
Negation:
<blockquote><pre>
<filterreader classname="org.apache.tools.ant.filters.LineContains">
<param type="negate" value="true"/>
<param type="contains" value="foo"/>
<param type="contains" value="bar"/>
</filterreader>
</pre></blockquote>
<i>or</i>
<blockquote><pre>
<linecontains negate="true">
<contains value="foo"/>
<contains value="bar"/>
</linecontains>
</pre></blockquote>
<h3><a name="linecontainsregexp">LineContainsRegExp</a></h3>
Filter which includes only those lines that contain the user-specified
regular expression matching strings.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Type</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>regexp</td>
<td vAlign=top align="center">Regular expression to be searched for.</td>
<td vAlign=top align="center">Yes</td>
</tr>
<tr>
<td vAlign=top>negate</td>
<td vAlign=top align="center">Whether to select
<i>non-</i>matching lines only. <b>Since Ant 1.7</b></td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>casesensitive</td>
<td vAlign=top align="center">Perform a case sensitive
match. Default is true. <b>Since Ant 1.8.2</b></td>
<td vAlign=top align="center">No</td>
</tr>
</table>
See <a href="regexp.html">Regexp Type</a> for the description of the nested element regexp and of
the choice of regular expression implementation.
<h4>Example:</h4>
This will fetch all those lines that contain the pattern <code>foo</code>
<blockquote><pre>
<filterreader classname="org.apache.tools.ant.filters.LineContainsRegExp">
<param type="regexp" value="foo*"/>
</filterreader>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<linecontainsregexp>
<regexp pattern="foo*"/>
</linecontainsregexp>
</pre></blockquote>
Negation:
<blockquote><pre>
<filterreader classname="org.apache.tools.ant.filters.LineContainsRegExp">
<param type="negate" value="true"/>
<param type="regexp" value="foo*"/>
</filterreader>
</pre></blockquote>
<i>or</i>
<blockquote><pre>
<linecontainsregexp negate="true">
<regexp pattern="foo*"/>
</linecontainsregexp>
</pre></blockquote>
<h3><a name="prefixlines">PrefixLines</a></h3>
Attaches a prefix to every line.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>prefix</td>
<td vAlign=top align="center">Prefix to be attached to lines.</td>
<td vAlign=top align="center">Yes</td>
</tr>
</table>
<p>
<h4>Example:</h4>
This will attach the prefix <code>Foo</code> to all lines.
<blockquote><pre>
<filterreader classname="org.apache.tools.ant.filters.PrefixLines">
<param name="prefix" value="Foo"/>
</filterreader>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<prefixlines prefix="Foo"/>
</pre></blockquote>
<h3><a name="suffixlines">SuffixLines</a></h3>
Attaches a suffix to every line.
<p><em>since Ant 1.8.0</em></p>
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>suffix</td>
<td vAlign=top align="center">Suffix to be attached to lines.</td>
<td vAlign=top align="center">Yes</td>
</tr>
</table>
<p>
<h4>Example:</h4>
This will attach the suffix <code>Foo</code> to all lines.
<blockquote><pre>
<filterreader classname="org.apache.tools.ant.filters.SuffixLines">
<param name="suffix" value="Foo"/>
</filterreader>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<suffixlines suffix="Foo"/>
</pre></blockquote>
<h3><a name="replacetokens">ReplaceTokens</a></h3>
This filter reader replaces all strings that are
sandwiched between begintoken and endtoken with
user defined values.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Type</b></td>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>tokenchar</td>
<td vAlign=top>begintoken</td>
<td vAlign=top>String marking the
beginning of a token. Defaults to @</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>tokenchar</td>
<td vAlign=top>endtoken</td>
<td vAlign=top>String marking the
end of a token. Defaults to @</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>User defined String.</td>
<td vAlign=top>token</td>
<td vAlign=top>User defined search String.</td>
<td vAlign=top align="center">Yes</td>
</tr>
<tr>
<td vAlign=top>Not applicable.</td>
<td vAlign=top>propertiesfile</td>
<td vAlign=top>Properties file to take tokens from.</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>Not applicable.</td>
<td vAlign=top>propertiesResource</td>
<td vAlign=top>Properties resource to take tokens from.
Note this only works is you use the
"convenience" <code><replacetokens></code> syntax.
<em>since Ant 1.8.0</em></td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>User defined String.</td>
<td vAlign=top>value</td>
<td vAlign=top>Replace-value for the token</td>
<td vAlign=top align="center">No</td>
</tr></table>
<p>
<h4>Example:</h4>
This replaces occurrences of the string @DATE@ in the data
with today's date and stores it in the property ${src.file.replaced}.
<blockquote><pre>
<tstamp/>
<!-- just for explaining the use of the properties -->
<property name="src.file" value="orders.csv"/>
<property name="src.file.replaced" value="orders.replaced"/>
<!-- do the loading and filtering -->
<loadfile srcfile="${src.file}" property="${src.file.replaced}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
<param type="token" name="DATE" value="${TODAY}"/>
</filterreader>
</filterchain>
</loadfile>
<!-- just for explaining the use of the properties -->
<echo message="${orders.replaced}"/>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<tstamp/>
<loadfile srcfile="${src.file}" property="${src.file.replaced}">
<filterchain>
<replacetokens>
<token key="DATE" value="${TODAY}"/>
</replacetokens>
</filterchain>
</loadfile>
</pre></blockquote>
This replaces occurrences of the string {{DATE}} in the data
with today's date and stores it in the property ${src.file.replaced}.
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.replaced}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
<param type="tokenchar" name="begintoken" value="{{"/>
<param type="tokenchar" name="endtoken" value="}}"/>
</filterreader>
</filterchain>
</loadfile>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<tstamp/>
<loadfile srcfile="${src.file}" property="${src.file.replaced}">
<filterchain>
<replacetokens begintoken="{{" endtoken="}}">
<token key="DATE" value="${TODAY}"/>
</replacetokens>
</filterchain>
</loadfile>
</pre></blockquote>
This will treat each properties file entry in sample.properties as a token/key pair :
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.replaced}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.ReplaceTokens">
<param type="propertiesfile" value="sample.properties"/>
</filterreader>
</filterchain>
</loadfile>
</pre></blockquote>
This reads the properties from an Ant resource referenced by its id:
<blockquote><pre>
<string id="embedded-properties">
foo=bar
baz=xyzzy
</string>
<loadfile srcfile="${src.file}" property="${src.file.replaced}">
<filterchain>
<replacetokens propertiesResource="${ant.refid:embedded-properties}"/>
</filterchain>
</loadfile>
</pre></blockquote>
<h3><a name="stripjavacomments">StripJavaComments</a></h3>
This filter reader strips away comments from the data,
using Java syntax guidelines. This filter does not
take in any parameters.
<p>
<h4>Example:</h4>
<blockquote><pre>
<loadfile srcfile="${java.src.file}" property="${java.src.file.nocomments}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.StripJavaComments"/>
</filterchain>
</loadfile>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<loadfile srcfile="${java.src.file}" property="${java.src.file.nocomments}">
<filterchain>
<stripjavacomments/>
</filterchain>
</loadfile>
</pre></blockquote>
<h3><a name="striplinebreaks">StripLineBreaks</a></h3>
This filter reader strips away specific characters
from the data supplied to it.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>linebreaks</td>
<td vAlign=top align="center">Characters that are to
be stripped out. Defaults to "\r\n"</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<p>
<h4>Examples:</h4>
This strips the '\r' and '\n' characters.
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.contents}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.StripLineBreaks"/>
</filterchain>
</loadfile>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.contents}">
<filterchain>
<striplinebreaks/>
</filterchain>
</loadfile>
</pre></blockquote>
This treats the '(' and ')' characters as line break characters and
strips them.
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.contents}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.StripLineBreaks">
<param name="linebreaks" value="()"/>
</filterreader>
</filterchain>
</loadfile>
</pre></blockquote>
<h3><a name="striplinecomments">StripLineComments</a></h3>
This filter removes all those lines that begin with strings
that represent comments as specified by the user.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Type</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>comment</td>
<td vAlign=top align="center">Strings that identify a line as a comment
when they appear at the start of the line.</td>
<td vAlign=top align="center">Yes</td>
</tr>
</table>
<p>
<h4>Examples:</h4>
This removes all lines that begin with #, --, REM, rem and //
<blockquote><pre>
<filterreader classname="org.apache.tools.ant.filters.StripLineComments">
<param type="comment" value="#"/>
<param type="comment" value="--"/>
<param type="comment" value="REM "/>
<param type="comment" value="rem "/>
<param type="comment" value="//"/>
</filterreader>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<striplinecomments>
<comment value="#"/>
<comment value="--"/>
<comment value="REM "/>
<comment value="rem "/>
<comment value="//"/>
</striplinecomments>
</pre></blockquote>
<h3><a name="tabstospaces">TabsToSpaces</a></h3>
This filter replaces tabs with spaces
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>tablength</td>
<td vAlign=top align="center">Defaults to "8"</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<p>
<h4>Examples:</h4>
This replaces tabs in ${src.file} with spaces.
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.notab}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.TabsToSpaces"/>
</filterchain>
</loadfile>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.notab}">
<filterchain>
<tabstospaces/>
</filterchain>
</loadfile>
</pre></blockquote>
<h3><a name="tailfilter">TailFilter</a></h3>
This filter reads the last few lines from the data supplied to it.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>lines</td>
<td vAlign=top align="center">Number of lines to be read.
Defaults to "10" <br> A negative value means that all lines are
passed (useful with <i>skip</i>)</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>skip</td>
<td vAlign=top align="center">Number of lines to be skipped (from the end).
Defaults to "0" </td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<p>
<h4>Background:</h4>
With HeadFilter and TailFilter you can extract each part of a text file you want.
This graphic shows the dependencies:
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<th> Content </th>
<th></th>
<th></th>
<th></th>
<th> Filter </th>
</tr>
<tr>
<td> Line 1 </td>
<td rowspan="2" bgcolor="#C0C0C0"> </td>
<td rowspan="9" bgcolor="#FF00FF"> </td>
<td rowspan="4"> </td>
<td rowspan="11">
<table>
<tr>
<td bgcolor="#C0C0C0"> </td>
<td><pre><filterchain>
<headfilter lines="2"/>
</filterchain></pre></td>
</tr>
<tr>
<td bgcolor="#FF00FF"> </td>
<td><pre><filterchain>
<tailfilter lines="-1" skip="2"/>
</filterchain></pre></td>
</tr>
<tr>
<td bgcolor="#008000"> </td>
<td><pre><filterchain>
<headfilter lines="-1" skip="2"/>
</filterchain></pre></td>
</tr>
<tr>
<td bgcolor="#0000FF"> </td>
<td><pre><filterchain>
<headfilter lines="-1" skip="2"/>
<tailfilter lines="-1" skip="2"/>
</filterchain></pre></td>
</tr>
<tr>
<td bgcolor="#00FF00"> </td>
<td><pre><filterchain>
<tailfilter lines="2"/>
</filterchain></pre></td>
</tr>
</table>
</td>
</tr>
<tr>
<td> Line 2 </td>
</tr>
<tr>
<td> Line 3 </td>
<td rowspan="9" bgcolor="#008000"> </td>
</tr>
<tr>
<td> Line 4 </td>
</tr>
<tr>
<td> Line 5 </td>
<td rowspan="3" bgcolor="#0000FF"> </td>
</tr>
<tr>
<td> Lines ... </td>
</tr>
<tr>
<td> Line 95 </td>
</tr>
<tr>
<td> Line 96 </td>
<td rowspan="4"> </td>
</tr>
<tr>
<td> Line 97 </td>
</tr>
<tr>
<td> Line 98 </td>
<td rowspan="2" bgcolor="#00FF00"> </td>
</tr>
<tr>
<td> Line 99 </td>
</tr>
</table>
<h4>Examples:</h4>
This stores the last 15 lines of the supplied data in the property ${src.file.tail}
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.tail}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.TailFilter">
<param name="lines" value="15"/>
</filterreader>
</filterchain>
</loadfile>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.tail}">
<filterchain>
<tailfilter lines="15"/>
</filterchain>
</loadfile>
</pre></blockquote>
This stores the last 5 lines of the first 15 lines of the supplied
data in the property ${src.file.mid}
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.mid}">
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.HeadFilter">
<param name="lines" value="15"/>
</filterreader>
<filterreader classname="org.apache.tools.ant.filters.TailFilter">
<param name="lines" value="5"/>
</filterreader>
</filterchain>
</loadfile>
</pre></blockquote>
Convenience method:
<blockquote><pre>
<loadfile srcfile="${src.file}" property="${src.file.mid}">
<filterchain>
<headfilter lines="15"/>
<tailfilter lines="5"/>
</filterchain>
</loadfile>
</pre></blockquote>
This stores the last 10 lines, skipping the last 2 lines, of the supplied data
in the property src.file.head. (Means: if supplied data contains 60 lines,
lines 49-58 are extracted)
<blockquote><pre>
<loadfile srcfile="${src.file}" property="src.file.head">
<filterchain>
<tailfilter lines="10" skip="2"/>
</filterchain>
</loadfile>
</pre></blockquote>
<h3><a name="deletecharacters">DeleteCharacters</a></h3>
<p>This filter deletes specified characters.</p>
<p><em>since Ant 1.6</em></p>
<p>This filter is only available in the convenience form.</p>
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>chars</td>
<td vAlign=top>
The characters to delete. This attribute is
<a href="#backslash">backslash enabled</a>.
</td>
<td vAlign=top align="center">Yes</td>
</tr>
</table>
<p>
<h4>Examples:</h4>
Delete tabs and returns from the data.
<blockquote><pre>
<deletecharacters chars="\t\r"/>
</pre></blockquote>
<h3><a name="concatfilter">ConcatFilter</a></h3>
<p>This filter prepends or appends the content file to the filtered files.</p>
<p><em>since Ant 1.6</em></p>
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>prepend</td>
<td vAlign=top>
The name of the file which content should be prepended to the file.
</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>append</td>
<td vAlign=top>
The name of the file which content should be appended to the file.
</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<p>
<h4>Examples:</h4>
Do nothing:
<blockquote><pre>
<filterchain>
<concatfilter/>
</filterchain>
</pre></blockquote>
Adds a license text before each java source:
<blockquote><pre>
<filterchain>
<concatfilter prepend="apache-license-java.txt"/>
</filterchain>
</pre></blockquote>
<h3><a name="tokenfilter">TokenFilter</a></h3>
This filter tokenizes the inputstream into strings and passes these
strings to filters of strings. Unlike the other filterreaders, this does
not support params, only convenience methods are implemented.
The tokenizer and the string filters are defined by nested elements.
<p><em>since Ant 1.6</em></p>
<p>
Only one tokenizer element may be used, the LineTokenizer is the
default if none are specified. A tokenizer
splits the input into token strings and trailing delimiter strings.
<p>
There may be zero or more string filters. A string filter processes
a token and either returns a string or a null.
It the string is not null it is passed to the next filter. This
proceeds until all the filters are called.
If a string is returned after all the filters, the string is
outputs with its associated token delimiter
(if one is present).
The trailing delimiter may be overridden by the <i>delimOutput</i>
attribute.
<p>
<a name="backslash"><em>backslash interpretation</em></a>
A number of attributes (including <i>delimOutput</i>) interpret
backslash escapes. The following are understood: \n, \r, \f, \t
and \\.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>delimOutput</td>
<td vAlign=top>
This overrides the tokendelimiter
returned by the tokenizer if it is not empty. This
attribute is backslash enabled.
</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<p>
The following tokenizers are provided by the default distribution.
<p>
<a href="#linetokenizer">LineTokenizer</a><br>
<a href="#filetokenizer">FileTokenizer</a><br>
<a href="#stringtokenizer">StringTokenizer</a><br>
</p>
The following string filters are provided by the default distribution.
<p>
<a href="#replacestring">ReplaceString</a><br>
<a href="#containsstring">ContainsString</a><br>
<a href="#replaceregex">ReplaceRegex</a><br>
<a href="#containsregex">ContainsRegex</a><br>
<a href="#trim">Trim</a><br>
<a href="#ignoreblank">IgnoreBlank</a><br>
<a href="#filterdeletecharacters">DeleteCharacters</a><br>
<a href="#uniqfilter">UniqFilter</a><br>
</p>
The following string filters are provided by the optional distribution.
<p>
<a href="#scriptfilter">ScriptFilter</a><br>
</p>
Some of the filters may be used directly within a filter chain. In this
case a tokenfilter is created implicitly. An extra attribute "byline"
is added to the filter to specify whether to use a linetokenizer
(byline="true") or a filetokenizer (byline="false"). The default
is "true".
<p>
<p><b><em><a name="linetokenizer">LineTokenizer</a></em></b></p>
This tokenizer splits the input into lines.
The tokenizer delimits lines
by "\r", "\n" or "\r\n".
This is the default tokenizer.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>includeDelims</td>
<td vAlign=top>
Include the line endings in the token.
Default is false.
</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<h4>Examples:</h4>
Convert input current line endings to unix style line endings.
<blockquote><pre>
<tokenfilter delimoutput="\n"/>
</pre></blockquote>
Remove blank lines.
<blockquote><pre>
<tokenfilter>
<ignoreblank/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="filetokenizer">FileTokenizer</a></em></b></p>
This tokenizer treats <b>all</b> the input as a token. So be
careful not to use this on very large input.
<h4>Examples:</h4>
Replace the first occurrence of package with //package.
<blockquote><pre>
<tokenfilter>
<filetokenizer/>
<replaceregex pattern="([\n\r]+[ \t]*|^[ \t]*)package"
flags="s"
replace="\1//package"/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="stringtokenizer">StringTokenizer</a></em></b></p>
This tokenizer is based on java.util.StringTokenizer.
It splits up the input into strings separated by white space, or
by a specified list of delimiting characters.
If the stream starts with delimiter characters, the first
token will be the empty string (unless the <i>delimsaretokens</i>
attribute is used).
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>delims</td>
<td vAlign=top>The delimiter characters. White space
is used if this is not set. (White space is defined
in this case by java.lang.Character.isWhitespace()).
</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td valign="top">delimsaretokens</td>
<td valign="top">If this is true,
each delimiter character is returned as a token.
Default is false.
</td>
<td valign="top" align="center">No</td>
</tr>
<tr>
<td valign="top">suppressdelims</td>
<td valign="top">
If this is true, delimiters are not returned.
Default is false.
</td>
<td valign="top" align="center">No</td>
</tr>
<tr>
<td vAlign=top>includeDelims</td>
<td vAlign=top>
Include the delimiters in the token.
Default is false.
</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<h4>Examples:</h4>
Surround each non space token with a "[]".
<blockquote><pre>
<tokenfilter>
<stringtokenizer/>
<replaceregex pattern="(.+)" replace="[\1]"/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="replacestring">ReplaceString</a></em></b></p>
This is a simple filter to replace strings.
This filter may be used directly within a filterchain.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>from</td>
<td vAlign=top>The string that must be replaced.</td>
<td vAlign=top align="center">Yes</td>
</tr>
<tr>
<td valign="top">to</td>
<td valign="top">The new value for the replaced string. When omitted
an empty string is used.
</td>
<td valign="top" align="center">No</td>
</tr>
</table>
<h4>Examples:</h4>
Replace "sun" with "moon".
<blockquote><pre>
<tokenfilter>
<replacestring from="sun" to="moon"/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="containsstring">ContainsString</a></em></b></p>
This is a simple filter to filter tokens that contains
a specified string.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>contains</td>
<td vAlign=top>The string that the token must contain.</td>
<td vAlign=top align="center">Yes</td>
</tr>
</table>
<h4>Examples:</h4>
Include only lines that contain "foo";
<blockquote><pre>
<tokenfilter>
<containsstring contains="foo"/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="replaceregex">ReplaceRegex</a></em></b></p>
This string filter replaces regular expressions.
This filter may be used directly within a filterchain.
<p>
See <a href="regexp.html#implementation">Regexp Type</a>
concerning the choice of the implementation.
</p>
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>pattern</td>
<td vAlign=top>The regular expression pattern to match in
the token.</td>
<td vAlign=top align="center">Yes</td>
</tr>
<tr>
<td vAlign=top>replace</td>
<td vAlign=top>The substitution pattern to replace the matched
regular expression. When omitted an empty string is used.</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>flags</td>
<td vAlign=top>See
<a href="../Tasks/replaceregexp.html">ReplaceRegexp</a>
for an explanation of regex flags.</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<h4>Examples:</h4>
Replace all occurrences of "hello" with "world", ignoring case.
<blockquote><pre>
<tokenfilter>
<replaceregex pattern="hello" replace="world" flags="gi"/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="containsregex">ContainsRegex</a></em></b></p>
This filters strings that match regular expressions.
The filter may optionally replace the matched regular expression.
This filter may be used directly within a filterchain.
<p>
See
<a href="regexp.html#implementation">Regexp Type</a>
concerning the choice of regular expression implementation.
</p>
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>pattern</td>
<td vAlign=top>The regular expression pattern to match in
the token.</td>
<td vAlign=top align="center">Yes</td>
</tr>
<tr>
<td vAlign=top>replace</td>
<td vAlign=top>The substitution pattern to replace the matched
regular expression. When omitted the original token is returned.
</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>flags</td>
<td vAlign=top>See
<a href="../Tasks/replaceregexp.html">ReplaceRegexp</a>
for an explanation of regex flags.</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<h4>Examples:</h4>
Filter lines that contain "hello" or "world", ignoring case.
<blockquote><pre>
<tokenfilter>
<containsregex pattern="(hello|world)" flags="i"/>
</tokenfilter>
</pre></blockquote>
This example replaces lines like "SUITE(TestSuite, bits);" with
"void register_bits();" and removes other lines.
<blockquote><pre>
<tokenfilter>
<containsregex
pattern="^ *SUITE\(.*,\s*(.*)\s*\).*"
replace="void register_\1();"/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="trim">Trim</a></em></b></p>
This filter trims whitespace from the start and end of
tokens.
This filter may be used directly within a filterchain.
<p><b><em><a name="ignoreblank">IgnoreBlank</a></em></b></p>
This filter removes empty tokens.
This filter may be used directly within a filterchain.
<p><b><em><a name="filterdeletecharacters">DeleteCharacters</a></em></b></p>
This filter deletes specified characters from tokens.
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>chars</td>
<td vAlign=top>The characters to delete. This attribute
is backslash enabled.</td>
<td vAlign=top align="center">Yes</td>
</tr>
</table>
<h4>Examples:</h4>
Delete tabs from lines, trim the lines and removes empty lines.
<blockquote><pre>
<tokenfilter>
<deletecharacters chars="\t"/>
<trim/>
<ignoreblank/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="uniqfilter">UniqFilter</a></em></b></p>
<p>Suppresses all tokens that match their ancestor token. It is most
useful if combined with a sort filter.</p>
<p>This filter may be used directly within a filterchain.</p>
<h4>Example:</h4>
This suppresses duplicate lines.
<blockquote><pre>
<tokenfilter>
<uniqfilter/>
</tokenfilter>
</pre></blockquote>
<p><b><em><a name="scriptfilter">ScriptFilter</a></em></b></p>
This is an optional filter that executes a script in a
<a href="http://jakarta.apache.org/bsf" target="_top">Apache BSF</a>
or
<a href="https://scripting.dev.java.net">JSR 223</a>
supported language.</p>
See the <a href="../Tasks/script.html">Script</a> task for
an explanation of scripts and dependencies.
</p>
<p>
The script is provided with an object <i>self</i> that has
getToken() and setToken(String) methods.
The getToken() method returns the current token. The setToken(String)
method replaces the current token.
</p>
This filter may be used directly within a filterchain.<p>
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Attribute</b></td>
<td vAlign=top><b>Description</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>language</td>
<td vAlign=top> The programming language the script is written in.
Must be a supported Apache BSF or JSR 223 language</td>
<td vAlign=top align="center">Yes</td>
</tr>
<tr>
<td valign="top">manager</td>
<td valign="top">
The script engine manager to use.
See the <a href="../Tasks/script.html">script</a> task
for using this attribute.
</td>
<td valign="top" align="center">No - default is "auto"</td>
</tr>
<tr>
<td vAlign=top>src</td>
<td vAlign=top>The location of the script as a file, if not inline
</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td valign="top">setbeans</td>
<td valign="top">whether to have all properties, references and targets as
global variables in the script. <em>since Ant 1.8.0</em></td>
<td valign="top" align="center">No, default is "true".</td>
</tr>
<tr>
<td valign="top">classpath</td>
<td valign="top">
The classpath to pass into the script.
</td>
<td align="center" valign="top">No</td>
</tr>
<tr>
<td valign="top">classpathref</td>
<td valign="top">The classpath to use, given as a
<a href="../using.html#references">reference</a> to a path defined elsewhere.
<td align="center" valign="top">No</td>
</tr>
</table>
<p>
This filter can take a nested <classpath> element.
See the <a href="../Tasks/script.html">script</a> task
on how to use this element.
</p>
<h4>Examples:</h4>
Convert to uppercase:
<blockquote><pre>
<tokenfilter>
<scriptfilter language="javascript">
self.setToken(self.getToken().toUpperCase());
</scriptfilter>
</tokenfilter>
</pre></blockquote>
Remove lines containing the string "bad" while
copying text files:
<blockquote>
<pre>
<copy todir="dist">
<fileset dir="src" includes="**/*.txt"/>
<filterchain>
<scriptfilter language="beanshell">
if (self.getToken().indexOf("bad") != -1) {
self.setToken(null);
}
</scriptfilter>
</filterchain>
</copy>
</pre>
</blockquote>
<h4>Custom tokenizers and string filters</h4>
Custom string filters and tokenizers may be plugged in by
extending the interfaces org.apache.tools.ant.filters.TokenFilter.Filter
and org.apache.tools.ant.util.Tokenizer respectly.
They are defined the build file using <code><typedef/></code>. For
example a string filter that capitalizes words may be declared as:
<blockquote><pre>
package my.customant;
import org.apache.tools.ant.filters.TokenFilter;
public class Capitalize
implements TokenFilter.Filter
{
public String filter(String token) {
if (token.length() == 0)
return token;
return token.substring(0, 1).toUpperCase() +
token.substring(1);
}
}
</pre></blockquote>
This may be used as follows:
<blockquote><pre>
<typedef name="capitalize" classname="my.customant.Capitalize"
classpath="my.customant.path"/>
<copy file="input" tofile="output">
<filterchain>
<tokenfilter>
<stringtokenizer/>
<capitalize/>
</tokenfilter>
</filterchain>
</copy>
</pre></blockquote>
<h3><a name="sortfilter">SortFilter</a></h3>
<p><em>since Ant 1.8.0</em></p>
<p>The sort filter reads all lines and sorts them. The sort order can
be reversed and it is possible to specify a custom implementation of
the <code>java.util.Comparator</code> interface to get even more
control.</p>
<table cellSpacing=0 cellPadding=2 border=1>
<tr>
<td vAlign=top><b>Parameter Name</b></td>
<td vAlign=top><b>Parameter Value</b></td>
<td vAlign=top align="center"><b>Required</b></td>
</tr>
<tr>
<td vAlign=top>reverse</td>
<td vAlign=top align="center">whether to reverse the sort order,
defaults to false. <b>Note:</b> this parameter is ignored if
the comparator parameter is present as well.</td>
<td vAlign=top align="center">No</td>
</tr>
<tr>
<td vAlign=top>comparator</td>
<td vAlign=top align="center">Class name of a class that
implements <code>java.util.Comparator</code> for Strings. This
class will be used to determine the sort order of lines.</td>
<td vAlign=top align="center">No</td>
</tr>
</table>
<p>This filter is also available using the
name <code>sortfilter</code>. The <code>reverse</code> parameter
becomes an attribute, <code>comparator</code> can be specified by
using a nested element.</p>
<h4>Examples:</h4>
<blockquote><pre>
<copy todir="build">
<fileset dir="input" includes="*.txt"/>
<filterchain>
<sortfilter/>
</filterchain>
</copy>
</pre></blockquote>
<p>
Sort all files <code>*.txt</code> from <i>src</i> location
into <i>build</i> location. The lines of each file are sorted in
ascendant order comparing the lines via the
<code>String.compareTo(Object o)</code> method.
</p>
<blockquote><pre>
<copy todir="build">
<fileset dir="input" includes="*.txt"/>
<filterchain>
<sortfilter reverse="true"/>
</filterchain>
</copy>
</pre></blockquote>
<p>
Sort all files <code>*.txt</code> from <i>src</i> location into reverse
order and copy them into <i>build</i> location.
</p>
<blockquote><pre>
<copy todir="build">
<fileset dir="input" includes="*.txt"/>
<filterchain>
<filterreader classname="org.apache.tools.ant.filters.SortFilter">
<param name="comparator" value="org.apache.tools.ant.filters.EvenFirstCmp"/>
</filterreader>
</filterchain>
</copy>
</pre></blockquote>
<p>
Sort all files <code>*.txt</code> from <i>src</i> location using as
sorting criterium <code>EvenFirstCmp</code> class, that sorts the file
lines putting even lines first then odd lines for example. The modified files
are copied into <i>build</i> location. The <code>EvenFirstCmp</code>,
has to an instanciable class via <code>Class.newInstance()</code>,
therefore in case of inner class has to be <em>static</em>. It also has to
implement <code>java.util.Comparator</code> interface, for example:
</p>
<pre>
package org.apache.tools.ant.filters;
...(omitted)
public final class EvenFirstCmp implements <b>Comparator</b> {
public int compare(Object o1, Object o2) {
...(omitted)
}
}
</pre>
<p>The example above is equivalent to:</p>
<blockquote><pre>
<componentdef name="evenfirst"
classname="org.apache.tools.ant.filters.EvenFirstCmp"/>
<copy todir="build">
<fileset dir="input" includes="*.txt"/>
<filterchain>
<sortfilter>
<evenfirst/>
</sortfilter>
</filterchain>
</copy>
</pre></blockquote>
</body></html>
| {
"pile_set_name": "Github"
} |
/*See if it works
* v1.0
*/
#include "Func.h"
void control()
{
createAndWriteFile("control.txt");
printf("control\n");
} | {
"pile_set_name": "Github"
} |
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019-2020 Inviwo Foundation
* 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.
*
* 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.
*
*********************************************************************************/
#include <inviwo/core/interaction/events/eventutil.h>
namespace inviwo {} // namespace inviwo
| {
"pile_set_name": "Github"
} |
const name = 'Kaktus'
module.exports = about
function about (wm) {
return {
label: name,
submenu: [
{
label: 'About ' + name,
role: 'about'
},
{
type: 'separator'
},
{
label: 'Preferences',
accelerator: 'CmdOrCtrl+,',
click: function (item, window) {
// wm.send('tabs:open-preferences')
}
},
{
label: 'Services',
role: 'services',
submenu: []
},
{
type: 'separator'
},
{
label: 'Hide ' + name,
accelerator: 'CmdOrCtrl+H',
role: 'hide'
},
{
label: 'Hide Others',
accelerator: 'CmdOrCtrl+Shift+H',
role: 'hideothers'
},
{
label: 'Show All',
role: 'unhide'
},
{
type: 'separator'
},
{
label: 'Quit',
accelerator: 'CmdOrCtrl+Q',
click: function () {
wm.app.quit()
}
}
]
}
}
| {
"pile_set_name": "Github"
} |
/*
* sata_qstor.c - Pacific Digital Corporation QStor SATA
*
* Maintained by: Mark Lord <[email protected]>
*
* Copyright 2005 Pacific Digital Corporation.
* (OSL/GPL code release authorized by Jalil Fadavi).
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/gfp.h>
#include <linux/pci.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "sata_qstor"
#define DRV_VERSION "0.09"
enum {
QS_MMIO_BAR = 4,
QS_PORTS = 4,
QS_MAX_PRD = LIBATA_MAX_PRD,
QS_CPB_ORDER = 6,
QS_CPB_BYTES = (1 << QS_CPB_ORDER),
QS_PRD_BYTES = QS_MAX_PRD * 16,
QS_PKT_BYTES = QS_CPB_BYTES + QS_PRD_BYTES,
/* global register offsets */
QS_HCF_CNFG3 = 0x0003, /* host configuration offset */
QS_HID_HPHY = 0x0004, /* host physical interface info */
QS_HCT_CTRL = 0x00e4, /* global interrupt mask offset */
QS_HST_SFF = 0x0100, /* host status fifo offset */
QS_HVS_SERD3 = 0x0393, /* PHY enable offset */
/* global control bits */
QS_HPHY_64BIT = (1 << 1), /* 64-bit bus detected */
QS_CNFG3_GSRST = 0x01, /* global chip reset */
QS_SERD3_PHY_ENA = 0xf0, /* PHY detection ENAble*/
/* per-channel register offsets */
QS_CCF_CPBA = 0x0710, /* chan CPB base address */
QS_CCF_CSEP = 0x0718, /* chan CPB separation factor */
QS_CFC_HUFT = 0x0800, /* host upstream fifo threshold */
QS_CFC_HDFT = 0x0804, /* host downstream fifo threshold */
QS_CFC_DUFT = 0x0808, /* dev upstream fifo threshold */
QS_CFC_DDFT = 0x080c, /* dev downstream fifo threshold */
QS_CCT_CTR0 = 0x0900, /* chan control-0 offset */
QS_CCT_CTR1 = 0x0901, /* chan control-1 offset */
QS_CCT_CFF = 0x0a00, /* chan command fifo offset */
/* channel control bits */
QS_CTR0_REG = (1 << 1), /* register mode (vs. pkt mode) */
QS_CTR0_CLER = (1 << 2), /* clear channel errors */
QS_CTR1_RDEV = (1 << 1), /* sata phy/comms reset */
QS_CTR1_RCHN = (1 << 4), /* reset channel logic */
QS_CCF_RUN_PKT = 0x107, /* RUN a new dma PKT */
/* pkt sub-field headers */
QS_HCB_HDR = 0x01, /* Host Control Block header */
QS_DCB_HDR = 0x02, /* Device Control Block header */
/* pkt HCB flag bits */
QS_HF_DIRO = (1 << 0), /* data DIRection Out */
QS_HF_DAT = (1 << 3), /* DATa pkt */
QS_HF_IEN = (1 << 4), /* Interrupt ENable */
QS_HF_VLD = (1 << 5), /* VaLiD pkt */
/* pkt DCB flag bits */
QS_DF_PORD = (1 << 2), /* Pio OR Dma */
QS_DF_ELBA = (1 << 3), /* Extended LBA (lba48) */
/* PCI device IDs */
board_2068_idx = 0, /* QStor 4-port SATA/RAID */
};
enum {
QS_DMA_BOUNDARY = ~0UL
};
typedef enum { qs_state_mmio, qs_state_pkt } qs_state_t;
struct qs_port_priv {
u8 *pkt;
dma_addr_t pkt_dma;
qs_state_t state;
};
static int qs_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val);
static int qs_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val);
static int qs_ata_init_one(struct pci_dev *pdev, const struct pci_device_id *ent);
static int qs_port_start(struct ata_port *ap);
static void qs_host_stop(struct ata_host *host);
static void qs_qc_prep(struct ata_queued_cmd *qc);
static unsigned int qs_qc_issue(struct ata_queued_cmd *qc);
static int qs_check_atapi_dma(struct ata_queued_cmd *qc);
static void qs_freeze(struct ata_port *ap);
static void qs_thaw(struct ata_port *ap);
static int qs_prereset(struct ata_link *link, unsigned long deadline);
static void qs_error_handler(struct ata_port *ap);
static struct scsi_host_template qs_ata_sht = {
ATA_BASE_SHT(DRV_NAME),
.sg_tablesize = QS_MAX_PRD,
.dma_boundary = QS_DMA_BOUNDARY,
};
static struct ata_port_operations qs_ata_ops = {
.inherits = &ata_sff_port_ops,
.check_atapi_dma = qs_check_atapi_dma,
.qc_prep = qs_qc_prep,
.qc_issue = qs_qc_issue,
.freeze = qs_freeze,
.thaw = qs_thaw,
.prereset = qs_prereset,
.softreset = ATA_OP_NULL,
.error_handler = qs_error_handler,
.lost_interrupt = ATA_OP_NULL,
.scr_read = qs_scr_read,
.scr_write = qs_scr_write,
.port_start = qs_port_start,
.host_stop = qs_host_stop,
};
static const struct ata_port_info qs_port_info[] = {
/* board_2068_idx */
{
.flags = ATA_FLAG_SATA | ATA_FLAG_PIO_POLLING,
.pio_mask = ATA_PIO4_ONLY,
.udma_mask = ATA_UDMA6,
.port_ops = &qs_ata_ops,
},
};
static const struct pci_device_id qs_ata_pci_tbl[] = {
{ PCI_VDEVICE(PDC, 0x2068), board_2068_idx },
{ } /* terminate list */
};
static struct pci_driver qs_ata_pci_driver = {
.name = DRV_NAME,
.id_table = qs_ata_pci_tbl,
.probe = qs_ata_init_one,
.remove = ata_pci_remove_one,
};
static void __iomem *qs_mmio_base(struct ata_host *host)
{
return host->iomap[QS_MMIO_BAR];
}
static int qs_check_atapi_dma(struct ata_queued_cmd *qc)
{
return 1; /* ATAPI DMA not supported */
}
static inline void qs_enter_reg_mode(struct ata_port *ap)
{
u8 __iomem *chan = qs_mmio_base(ap->host) + (ap->port_no * 0x4000);
struct qs_port_priv *pp = ap->private_data;
pp->state = qs_state_mmio;
writeb(QS_CTR0_REG, chan + QS_CCT_CTR0);
readb(chan + QS_CCT_CTR0); /* flush */
}
static inline void qs_reset_channel_logic(struct ata_port *ap)
{
u8 __iomem *chan = qs_mmio_base(ap->host) + (ap->port_no * 0x4000);
writeb(QS_CTR1_RCHN, chan + QS_CCT_CTR1);
readb(chan + QS_CCT_CTR0); /* flush */
qs_enter_reg_mode(ap);
}
static void qs_freeze(struct ata_port *ap)
{
u8 __iomem *mmio_base = qs_mmio_base(ap->host);
writeb(0, mmio_base + QS_HCT_CTRL); /* disable host interrupts */
qs_enter_reg_mode(ap);
}
static void qs_thaw(struct ata_port *ap)
{
u8 __iomem *mmio_base = qs_mmio_base(ap->host);
qs_enter_reg_mode(ap);
writeb(1, mmio_base + QS_HCT_CTRL); /* enable host interrupts */
}
static int qs_prereset(struct ata_link *link, unsigned long deadline)
{
struct ata_port *ap = link->ap;
qs_reset_channel_logic(ap);
return ata_sff_prereset(link, deadline);
}
static int qs_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val)
{
if (sc_reg > SCR_CONTROL)
return -EINVAL;
*val = readl(link->ap->ioaddr.scr_addr + (sc_reg * 8));
return 0;
}
static void qs_error_handler(struct ata_port *ap)
{
qs_enter_reg_mode(ap);
ata_sff_error_handler(ap);
}
static int qs_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val)
{
if (sc_reg > SCR_CONTROL)
return -EINVAL;
writel(val, link->ap->ioaddr.scr_addr + (sc_reg * 8));
return 0;
}
static unsigned int qs_fill_sg(struct ata_queued_cmd *qc)
{
struct scatterlist *sg;
struct ata_port *ap = qc->ap;
struct qs_port_priv *pp = ap->private_data;
u8 *prd = pp->pkt + QS_CPB_BYTES;
unsigned int si;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
u64 addr;
u32 len;
addr = sg_dma_address(sg);
*(__le64 *)prd = cpu_to_le64(addr);
prd += sizeof(u64);
len = sg_dma_len(sg);
*(__le32 *)prd = cpu_to_le32(len);
prd += sizeof(u64);
VPRINTK("PRD[%u] = (0x%llX, 0x%X)\n", si,
(unsigned long long)addr, len);
}
return si;
}
static void qs_qc_prep(struct ata_queued_cmd *qc)
{
struct qs_port_priv *pp = qc->ap->private_data;
u8 dflags = QS_DF_PORD, *buf = pp->pkt;
u8 hflags = QS_HF_DAT | QS_HF_IEN | QS_HF_VLD;
u64 addr;
unsigned int nelem;
VPRINTK("ENTER\n");
qs_enter_reg_mode(qc->ap);
if (qc->tf.protocol != ATA_PROT_DMA)
return;
nelem = qs_fill_sg(qc);
if ((qc->tf.flags & ATA_TFLAG_WRITE))
hflags |= QS_HF_DIRO;
if ((qc->tf.flags & ATA_TFLAG_LBA48))
dflags |= QS_DF_ELBA;
/* host control block (HCB) */
buf[ 0] = QS_HCB_HDR;
buf[ 1] = hflags;
*(__le32 *)(&buf[ 4]) = cpu_to_le32(qc->nbytes);
*(__le32 *)(&buf[ 8]) = cpu_to_le32(nelem);
addr = ((u64)pp->pkt_dma) + QS_CPB_BYTES;
*(__le64 *)(&buf[16]) = cpu_to_le64(addr);
/* device control block (DCB) */
buf[24] = QS_DCB_HDR;
buf[28] = dflags;
/* frame information structure (FIS) */
ata_tf_to_fis(&qc->tf, 0, 1, &buf[32]);
}
static inline void qs_packet_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
u8 __iomem *chan = qs_mmio_base(ap->host) + (ap->port_no * 0x4000);
VPRINTK("ENTER, ap %p\n", ap);
writeb(QS_CTR0_CLER, chan + QS_CCT_CTR0);
wmb(); /* flush PRDs and pkt to memory */
writel(QS_CCF_RUN_PKT, chan + QS_CCT_CFF);
readl(chan + QS_CCT_CFF); /* flush */
}
static unsigned int qs_qc_issue(struct ata_queued_cmd *qc)
{
struct qs_port_priv *pp = qc->ap->private_data;
switch (qc->tf.protocol) {
case ATA_PROT_DMA:
pp->state = qs_state_pkt;
qs_packet_start(qc);
return 0;
case ATAPI_PROT_DMA:
BUG();
break;
default:
break;
}
pp->state = qs_state_mmio;
return ata_sff_qc_issue(qc);
}
static void qs_do_or_die(struct ata_queued_cmd *qc, u8 status)
{
qc->err_mask |= ac_err_mask(status);
if (!qc->err_mask) {
ata_qc_complete(qc);
} else {
struct ata_port *ap = qc->ap;
struct ata_eh_info *ehi = &ap->link.eh_info;
ata_ehi_clear_desc(ehi);
ata_ehi_push_desc(ehi, "status 0x%02X", status);
if (qc->err_mask == AC_ERR_DEV)
ata_port_abort(ap);
else
ata_port_freeze(ap);
}
}
static inline unsigned int qs_intr_pkt(struct ata_host *host)
{
unsigned int handled = 0;
u8 sFFE;
u8 __iomem *mmio_base = qs_mmio_base(host);
do {
u32 sff0 = readl(mmio_base + QS_HST_SFF);
u32 sff1 = readl(mmio_base + QS_HST_SFF + 4);
u8 sEVLD = (sff1 >> 30) & 0x01; /* valid flag */
sFFE = sff1 >> 31; /* empty flag */
if (sEVLD) {
u8 sDST = sff0 >> 16; /* dev status */
u8 sHST = sff1 & 0x3f; /* host status */
unsigned int port_no = (sff1 >> 8) & 0x03;
struct ata_port *ap = host->ports[port_no];
struct qs_port_priv *pp = ap->private_data;
struct ata_queued_cmd *qc;
DPRINTK("SFF=%08x%08x: sCHAN=%u sHST=%d sDST=%02x\n",
sff1, sff0, port_no, sHST, sDST);
handled = 1;
if (!pp || pp->state != qs_state_pkt)
continue;
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING))) {
switch (sHST) {
case 0: /* successful CPB */
case 3: /* device error */
qs_enter_reg_mode(qc->ap);
qs_do_or_die(qc, sDST);
break;
default:
break;
}
}
}
} while (!sFFE);
return handled;
}
static inline unsigned int qs_intr_mmio(struct ata_host *host)
{
unsigned int handled = 0, port_no;
for (port_no = 0; port_no < host->n_ports; ++port_no) {
struct ata_port *ap = host->ports[port_no];
struct qs_port_priv *pp = ap->private_data;
struct ata_queued_cmd *qc;
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (!qc) {
/*
* The qstor hardware generates spurious
* interrupts from time to time when switching
* in and out of packet mode. There's no
* obvious way to know if we're here now due
* to that, so just ack the irq and pretend we
* knew it was ours.. (ugh). This does not
* affect packet mode.
*/
ata_sff_check_status(ap);
handled = 1;
continue;
}
if (!pp || pp->state != qs_state_mmio)
continue;
if (!(qc->tf.flags & ATA_TFLAG_POLLING))
handled |= ata_sff_port_intr(ap, qc);
}
return handled;
}
static irqreturn_t qs_intr(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
unsigned int handled = 0;
unsigned long flags;
VPRINTK("ENTER\n");
spin_lock_irqsave(&host->lock, flags);
handled = qs_intr_pkt(host) | qs_intr_mmio(host);
spin_unlock_irqrestore(&host->lock, flags);
VPRINTK("EXIT\n");
return IRQ_RETVAL(handled);
}
static void qs_ata_setup_port(struct ata_ioports *port, void __iomem *base)
{
port->cmd_addr =
port->data_addr = base + 0x400;
port->error_addr =
port->feature_addr = base + 0x408; /* hob_feature = 0x409 */
port->nsect_addr = base + 0x410; /* hob_nsect = 0x411 */
port->lbal_addr = base + 0x418; /* hob_lbal = 0x419 */
port->lbam_addr = base + 0x420; /* hob_lbam = 0x421 */
port->lbah_addr = base + 0x428; /* hob_lbah = 0x429 */
port->device_addr = base + 0x430;
port->status_addr =
port->command_addr = base + 0x438;
port->altstatus_addr =
port->ctl_addr = base + 0x440;
port->scr_addr = base + 0xc00;
}
static int qs_port_start(struct ata_port *ap)
{
struct device *dev = ap->host->dev;
struct qs_port_priv *pp;
void __iomem *mmio_base = qs_mmio_base(ap->host);
void __iomem *chan = mmio_base + (ap->port_no * 0x4000);
u64 addr;
pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
if (!pp)
return -ENOMEM;
pp->pkt = dmam_alloc_coherent(dev, QS_PKT_BYTES, &pp->pkt_dma,
GFP_KERNEL);
if (!pp->pkt)
return -ENOMEM;
memset(pp->pkt, 0, QS_PKT_BYTES);
ap->private_data = pp;
qs_enter_reg_mode(ap);
addr = (u64)pp->pkt_dma;
writel((u32) addr, chan + QS_CCF_CPBA);
writel((u32)(addr >> 32), chan + QS_CCF_CPBA + 4);
return 0;
}
static void qs_host_stop(struct ata_host *host)
{
void __iomem *mmio_base = qs_mmio_base(host);
writeb(0, mmio_base + QS_HCT_CTRL); /* disable host interrupts */
writeb(QS_CNFG3_GSRST, mmio_base + QS_HCF_CNFG3); /* global reset */
}
static void qs_host_init(struct ata_host *host, unsigned int chip_id)
{
void __iomem *mmio_base = host->iomap[QS_MMIO_BAR];
unsigned int port_no;
writeb(0, mmio_base + QS_HCT_CTRL); /* disable host interrupts */
writeb(QS_CNFG3_GSRST, mmio_base + QS_HCF_CNFG3); /* global reset */
/* reset each channel in turn */
for (port_no = 0; port_no < host->n_ports; ++port_no) {
u8 __iomem *chan = mmio_base + (port_no * 0x4000);
writeb(QS_CTR1_RDEV|QS_CTR1_RCHN, chan + QS_CCT_CTR1);
writeb(QS_CTR0_REG, chan + QS_CCT_CTR0);
readb(chan + QS_CCT_CTR0); /* flush */
}
writeb(QS_SERD3_PHY_ENA, mmio_base + QS_HVS_SERD3); /* enable phy */
for (port_no = 0; port_no < host->n_ports; ++port_no) {
u8 __iomem *chan = mmio_base + (port_no * 0x4000);
/* set FIFO depths to same settings as Windows driver */
writew(32, chan + QS_CFC_HUFT);
writew(32, chan + QS_CFC_HDFT);
writew(10, chan + QS_CFC_DUFT);
writew( 8, chan + QS_CFC_DDFT);
/* set CPB size in bytes, as a power of two */
writeb(QS_CPB_ORDER, chan + QS_CCF_CSEP);
}
writeb(1, mmio_base + QS_HCT_CTRL); /* enable host interrupts */
}
/*
* The QStor understands 64-bit buses, and uses 64-bit fields
* for DMA pointers regardless of bus width. We just have to
* make sure our DMA masks are set appropriately for whatever
* bridge lies between us and the QStor, and then the DMA mapping
* code will ensure we only ever "see" appropriate buffer addresses.
* If we're 32-bit limited somewhere, then our 64-bit fields will
* just end up with zeros in the upper 32-bits, without any special
* logic required outside of this routine (below).
*/
static int qs_set_dma_masks(struct pci_dev *pdev, void __iomem *mmio_base)
{
u32 bus_info = readl(mmio_base + QS_HID_HPHY);
int rc, have_64bit_bus = (bus_info & QS_HPHY_64BIT);
if (have_64bit_bus &&
!dma_set_mask(&pdev->dev, DMA_BIT_MASK(64))) {
rc = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(64));
if (rc) {
rc = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
if (rc) {
dev_err(&pdev->dev,
"64-bit DMA enable failed\n");
return rc;
}
}
} else {
rc = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
if (rc) {
dev_err(&pdev->dev, "32-bit DMA enable failed\n");
return rc;
}
rc = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
if (rc) {
dev_err(&pdev->dev,
"32-bit consistent DMA enable failed\n");
return rc;
}
}
return 0;
}
static int qs_ata_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
unsigned int board_idx = (unsigned int) ent->driver_data;
const struct ata_port_info *ppi[] = { &qs_port_info[board_idx], NULL };
struct ata_host *host;
int rc, port_no;
ata_print_version_once(&pdev->dev, DRV_VERSION);
/* alloc host */
host = ata_host_alloc_pinfo(&pdev->dev, ppi, QS_PORTS);
if (!host)
return -ENOMEM;
/* acquire resources and fill host */
rc = pcim_enable_device(pdev);
if (rc)
return rc;
if ((pci_resource_flags(pdev, QS_MMIO_BAR) & IORESOURCE_MEM) == 0)
return -ENODEV;
rc = pcim_iomap_regions(pdev, 1 << QS_MMIO_BAR, DRV_NAME);
if (rc)
return rc;
host->iomap = pcim_iomap_table(pdev);
rc = qs_set_dma_masks(pdev, host->iomap[QS_MMIO_BAR]);
if (rc)
return rc;
for (port_no = 0; port_no < host->n_ports; ++port_no) {
struct ata_port *ap = host->ports[port_no];
unsigned int offset = port_no * 0x4000;
void __iomem *chan = host->iomap[QS_MMIO_BAR] + offset;
qs_ata_setup_port(&ap->ioaddr, chan);
ata_port_pbar_desc(ap, QS_MMIO_BAR, -1, "mmio");
ata_port_pbar_desc(ap, QS_MMIO_BAR, offset, "port");
}
/* initialize adapter */
qs_host_init(host, board_idx);
pci_set_master(pdev);
return ata_host_activate(host, pdev->irq, qs_intr, IRQF_SHARED,
&qs_ata_sht);
}
module_pci_driver(qs_ata_pci_driver);
MODULE_AUTHOR("Mark Lord");
MODULE_DESCRIPTION("Pacific Digital Corporation QStor SATA low-level driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, qs_ata_pci_tbl);
MODULE_VERSION(DRV_VERSION);
| {
"pile_set_name": "Github"
} |
#!/bin/sh
# usage: treed PATH
# View folder structure using `tree` with some options
#
# Lifted from https://github.com/mathiasbynens/dotfiles/pull/249/files
tree -aC -I ".git" --dirsfirst "$@" | less -FRNX
| {
"pile_set_name": "Github"
} |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
from itertools import chain
from typing import List, Union, Tuple
import numpy as np
import bpy
from bpy.props import BoolProperty, EnumProperty, BoolVectorProperty
from mathutils import Vector, Matrix
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode
from sverchok.utils.sv_mesh_utils import mesh_join
from sverchok.utils.modules.matrix_utils import matrix_apply_np
from sverchok.data_structure import repeat_last
socket_names = ['Vertices', 'Edges', 'Polygons']
PyVertices = List[Union[List[float], Tuple[float, float, float]]]
PyEdges = List[Union[List[int], Tuple[int, int]]]
PyFaces = List[Union[List[int], Tuple[int]]]
def mesh_join_np(verts, edges, pols, out_np_pols):
'''
joins many meshes
verts and edges have to be list of numpy arrays [(n,3), (n,3),...] and [(n,2), (n,2), ...]
pols should be a numpy array only if you want to get a numpy array with polygons, otherways inputting a regular list will be faster
out_np_pols is a boolean to indicate if you want output numpy arrays in the faces'''
accum_vert_lens = np.add.accumulate([len(v) for v in chain([[]], verts)])
v_out = np.concatenate(verts)
# just checking the first object to detect presence of edges and Polygons
# this would fail if the first object does not have edges/pols and there
# are edges/pols in the next objects but I guess is enough
are_some_edges = len(edges[0]) > 0
are_some_pols = len(pols[0]) > 0
if are_some_edges:
e_out = np.concatenate([edg + l for edg, l in zip(edges, accum_vert_lens)])
else:
e_out = np.array([], dtype=np.int)
if are_some_pols:
if out_np_pols:
is_array_of_lists = pols[0].dtype == object
if is_array_of_lists:
p_out = [np.array(p) + l for pol, l in zip(pols, accum_vert_lens) for p in pol]
else:
p_out = np.concatenate([pol + l for pol, l in zip(pols, accum_vert_lens)])
else:
p_out = [[v + l for v in p] for pol, l in zip(pols, accum_vert_lens) for p in pol]
else:
p_out = np.array([])
return v_out, e_out, p_out
def apply_matrix_to_vectors(vertices, matrices, out_verts):
max_v = len(vertices) - 1
for i, mat in enumerate(matrices):
vert_id = min(i, max_v)
out_verts.append([(mat @ Vector(v))[:] for v in vertices[vert_id]])
def apply_matrix_to_vectors_np(vertices, matrices, out_verts):
r_vertices = [np.array(v) for v in vertices]
max_v = len(vertices) - 1
for i, mat in enumerate(matrices):
vert_id = min(i, max_v)
out_verts.append(matrix_apply_np(r_vertices[vert_id], mat))
def apply_and_join_numpy(vertices, edges, faces, matrices, do_join, out_np):
out_verts = []
output_numpy_verts, output_numpy_edges, output_numpy_pols = out_np
n = len(matrices)
apply_matrix_to_vectors_np(vertices, matrices, out_verts)
if do_join:
#prepare data for joining
out_edges = ([np.array(e) for e in edges] * n)[:n]
if output_numpy_pols:
out_faces = ([np.array(f) for f in faces] * n)[:n]
else:
out_faces = (faces * n)[:n]
out_verts, out_edges, out_faces = mesh_join_np(out_verts, out_edges, out_faces, output_numpy_pols)
out_verts, out_faces = [out_verts], [out_faces]
if output_numpy_edges:
out_edges = [out_edges]
else:
out_edges = [out_edges.tolist()]
else:
out_edges = (edges * n)[:n]
out_faces = (faces * n)[:n]
if not output_numpy_verts:
out_verts = [v.tolist() for v in out_verts]
return out_verts, out_edges, out_faces
def apply_and_join_python(vertices, edges, faces, matrices, do_join):
n = len(matrices)
out_verts = []
if isinstance(vertices[0], np.ndarray):
py_verts = [v.tolist() for v in vertices]
else:
py_verts = vertices
apply_matrix_to_vectors(py_verts, matrices, out_verts)
if do_join:
out_edges = (edges * n)[:n]
out_faces = (faces * n)[:n]
out_verts, out_edges, out_faces = mesh_join(out_verts, out_edges, out_faces)
out_verts, out_edges, out_faces = [out_verts], [out_edges], [out_faces]
else:
out_edges = (edges * n)[:n]
out_faces = (faces * n)[:n]
return out_verts, out_edges, out_faces
def apply_nested_matrices_py(
vertices: List[PyVertices],
edges: List[PyEdges],
faces: List[PyFaces],
matrices: List[List[Matrix]],
do_join: bool) -> Tuple[List[PyVertices], List[PyEdges], List[PyFaces]]:
# Get list of Sverchok meshes and list of list of matrices
# List of matrices applies to a mesh, each matrices copy the mesh inside an object
max_objects = max([len(func_input) for func_input in [vertices, edges, faces, matrices]])
vertices = repeat_last(vertices)
edges = repeat_last(edges)
faces = repeat_last(faces)
matrices = repeat_last(matrices)
meshes: List[Tuple[PyVertices, PyEdges, PyFaces]] = []
for i, obj_vertices, obj_edges, obj_faces, obj_matrices in zip(
range(max_objects), vertices, edges, faces, matrices):
meshes.append(copy_object_and_transform_py(obj_vertices, obj_edges, obj_faces, obj_matrices))
if do_join:
mesh = mesh_join(*list(zip(*meshes)))
return [[mesh_element] for mesh_element in mesh]
else:
return list(zip(*meshes))
def copy_object_and_transform_py(
vertices: PyVertices,
edges: PyEdges,
faces: PyFaces,
matrices: List[Matrix]) -> Tuple[PyVertices, PyEdges, PyFaces]:
# Get mesh and list of matrices
# Each matrices create copy of given mesh and transform it
meshes: List[Tuple[PyVertices, PyEdges, PyFaces]] = []
for matrix in matrices:
new_verts = [(matrix @ Vector(v))[:] for v in vertices]
meshes.append((new_verts, edges, faces))
return mesh_join(*list(zip(*meshes)))
def apply_nested_matrices_np(
vertices: np.ndarray,
edges: np.ndarray,
faces: List[PyFaces],
matrices: List[List[Matrix]],
do_join: bool) -> Tuple[List[np.ndarray], List[np.ndarray], List[PyFaces]]:
# Get list of Sverchok meshes and list of list of matrices
# List of matrices applies to a mesh, each matrices copy the mesh inside an object
max_objects = max([len(func_input) for func_input in [vertices, edges, faces, matrices]])
vertices = repeat_last(vertices)
edges = repeat_last(edges)
faces = repeat_last(faces)
matrices = repeat_last(matrices)
meshes: List[Tuple[PyVertices, PyEdges, PyFaces]] = []
for i, obj_vertices, obj_edges, obj_faces, obj_matrices in zip(
range(max_objects), vertices, edges, faces, matrices):
meshes.append(copy_object_and_transform_np(obj_vertices, obj_edges, obj_faces, obj_matrices))
if do_join:
mesh = mesh_join_np(*list(zip(*meshes)), False)
return [[mesh_element] for mesh_element in mesh]
else:
return list(zip(*meshes))
def copy_object_and_transform_np(
vertices: np.ndarray,
edges: np.ndarray,
faces: PyFaces,
matrices: List[Matrix]) -> Tuple[np.ndarray, np.ndarray, PyFaces]:
# Get mesh and list of matrices
# Each matrices create copy of given mesh and transform it
meshes: List[Tuple[np.ndarray, np.ndarray, PyFaces]] = []
for matrix in matrices:
new_verts = matrix_apply_np(vertices, matrix)
meshes.append((new_verts, edges, faces))
return mesh_join_np(*list(zip(*meshes)), False)
class SvMatrixApplyJoinNode(bpy.types.Node, SverchCustomTreeNode):
"""
Triggers: Mat * Mesh (& Join)
Tooltip: Multiply vectors on matrices with several objects in output, processes edges & faces too. It can also join the output meshes in to a single one
"""
bl_idname = 'SvMatrixApplyJoinNode'
bl_label = 'Matrix Apply'
bl_icon = 'OUTLINER_OB_EMPTY'
sv_icon = 'SV_MATRIX_APPLY_JOIN'
do_join: BoolProperty(name='Join', default=True, update=updateNode)
implementation_modes = [
("NumPy", "NumPy", "NumPy", 0),
("Python", "Python", "Python", 1)]
implementation: EnumProperty(
name='Implementation', items=implementation_modes,
description='Choose calculation method (See Documentation)',
default="Python", update=updateNode)
output_numpy: BoolProperty(
name='Output NumPy',
description='Output NumPy arrays',
default=False, update=updateNode)
out_np: BoolVectorProperty(
name="Ouput Numpy",
description="Output NumPy arrays",
default=(False, False, False),
size=3, update=updateNode)
def sv_init(self, context):
self.inputs.new('SvVerticesSocket', "Vertices")
self.inputs.new('SvStringsSocket', "Edges")
self.inputs.new('SvStringsSocket', "Faces")
self.inputs.new('SvMatrixSocket', "Matrices")
self.outputs.new('SvVerticesSocket', "Vertices")
self.outputs.new('SvStringsSocket', "Edges")
self.outputs.new('SvStringsSocket', "Faces")
def draw_buttons(self, context, layout):
layout.prop(self, "do_join")
def draw_buttons_ext(self, context, layout):
layout.prop(self, "do_join")
layout.label(text="Implementation:")
layout.prop(self, "implementation", expand=True)
if self.implementation == 'NumPy':
layout.label(text="Ouput Numpy:")
row = layout.row()
for i in range(3):
row.prop(self, "out_np", index=i, text=socket_names[i], toggle=True)
def rclick_menu(self, context, layout):
layout.prop(self, "do_join")
layout.prop_menu_enum(self, "implementation", text="Implementation")
if self.implementation == 'NumPy':
layout.label(text="Ouput Numpy:")
for i in range(3):
layout.prop(self, "out_np", index=i, text=socket_names[i], toggle=True)
def process(self):
if not (self.inputs['Vertices'].is_linked and any(s.is_linked for s in self.outputs)):
return
vertices = self.inputs['Vertices'].sv_get(deepcopy=False)
edges = self.inputs['Edges'].sv_get(default=[[]], deepcopy=False)
faces = self.inputs['Faces'].sv_get(default=[[]], deepcopy=False)
matrices = self.inputs['Matrices'].sv_get(default=None, deepcopy=False)
if not matrices:
out_verts = vertices
out_edges = edges
out_faces = faces
elif not isinstance(matrices[0], (list, tuple)):
# most likely it is List[Matrix] or List[np.ndarray]
if self.implementation == 'NumPy':
out_verts, out_edges, out_faces = apply_and_join_numpy(
vertices, edges, faces, matrices, self.do_join, self.out_np)
else:
out_verts, out_edges, out_faces = apply_and_join_python(vertices, edges, faces, matrices, self.do_join)
elif not isinstance(matrices[0][0], (list, tuple)):
# most likely it is List[List[Matrix]] or List[List[np.ndarray]]
if self.implementation == 'NumPy':
vertices = [np.array(verts, dtype=np.float32) for verts in vertices] # float 32 is faster
edges = [np.array(es, dtype=np.int) for es in edges]
out_verts, out_edges, out_faces = apply_nested_matrices_np(
vertices, edges, faces, matrices, self.do_join
)
else:
out_verts, out_edges, out_faces = apply_nested_matrices_py(
vertices, edges, faces, matrices, self.do_join)
else:
# it looks inputs matrices are too nested in lists
raise TypeError("Unsupported matrix format") # will make our errors more clear
self.outputs['Edges'].sv_set(out_edges)
self.outputs['Faces'].sv_set(out_faces)
self.outputs['Vertices'].sv_set(out_verts)
def register():
bpy.utils.register_class(SvMatrixApplyJoinNode)
def unregister():
bpy.utils.unregister_class(SvMatrixApplyJoinNode)
| {
"pile_set_name": "Github"
} |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
// This file is available under and governed by the GNU General Public
// License version 2 only, as published by the Free Software Foundation.
// However, the following notice accompanied the original version of this
// file:
//
//---------------------------------------------------------------------------------
//
// Little Color Management System
// Copyright (c) 1998-2017 Marti Maria Saguer
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//---------------------------------------------------------------------------------
//
#include "lcms2_internal.h"
// inter PCS conversions XYZ <-> CIE L* a* b*
/*
CIE 15:2004 CIELab is defined as:
L* = 116*f(Y/Yn) - 16 0 <= L* <= 100
a* = 500*[f(X/Xn) - f(Y/Yn)]
b* = 200*[f(Y/Yn) - f(Z/Zn)]
and
f(t) = t^(1/3) 1 >= t > (24/116)^3
(841/108)*t + (16/116) 0 <= t <= (24/116)^3
Reverse transform is:
X = Xn*[a* / 500 + (L* + 16) / 116] ^ 3 if (X/Xn) > (24/116)
= Xn*(a* / 500 + L* / 116) / 7.787 if (X/Xn) <= (24/116)
PCS in Lab2 is encoded as:
8 bit Lab PCS:
L* 0..100 into a 0..ff byte.
a* t + 128 range is -128.0 +127.0
b*
16 bit Lab PCS:
L* 0..100 into a 0..ff00 word.
a* t + 128 range is -128.0 +127.9961
b*
Interchange Space Component Actual Range Encoded Range
CIE XYZ X 0 -> 1.99997 0x0000 -> 0xffff
CIE XYZ Y 0 -> 1.99997 0x0000 -> 0xffff
CIE XYZ Z 0 -> 1.99997 0x0000 -> 0xffff
Version 2,3
-----------
CIELAB (16 bit) L* 0 -> 100.0 0x0000 -> 0xff00
CIELAB (16 bit) a* -128.0 -> +127.996 0x0000 -> 0x8000 -> 0xffff
CIELAB (16 bit) b* -128.0 -> +127.996 0x0000 -> 0x8000 -> 0xffff
Version 4
---------
CIELAB (16 bit) L* 0 -> 100.0 0x0000 -> 0xffff
CIELAB (16 bit) a* -128.0 -> +127 0x0000 -> 0x8080 -> 0xffff
CIELAB (16 bit) b* -128.0 -> +127 0x0000 -> 0x8080 -> 0xffff
*/
// Conversions
void CMSEXPORT cmsXYZ2xyY(cmsCIExyY* Dest, const cmsCIEXYZ* Source)
{
cmsFloat64Number ISum;
ISum = 1./(Source -> X + Source -> Y + Source -> Z);
Dest -> x = (Source -> X) * ISum;
Dest -> y = (Source -> Y) * ISum;
Dest -> Y = Source -> Y;
}
void CMSEXPORT cmsxyY2XYZ(cmsCIEXYZ* Dest, const cmsCIExyY* Source)
{
Dest -> X = (Source -> x / Source -> y) * Source -> Y;
Dest -> Y = Source -> Y;
Dest -> Z = ((1 - Source -> x - Source -> y) / Source -> y) * Source -> Y;
}
/*
The break point (24/116)^3 = (6/29)^3 is a very small amount of tristimulus
primary (0.008856). Generally, this only happens for
nearly ideal blacks and for some orange / amber colors in transmission mode.
For example, the Z value of the orange turn indicator lamp lens on an
automobile will often be below this value. But the Z does not
contribute to the perceived color directly.
*/
static
cmsFloat64Number f(cmsFloat64Number t)
{
const cmsFloat64Number Limit = (24.0/116.0) * (24.0/116.0) * (24.0/116.0);
if (t <= Limit)
return (841.0/108.0) * t + (16.0/116.0);
else
return pow(t, 1.0/3.0);
}
static
cmsFloat64Number f_1(cmsFloat64Number t)
{
const cmsFloat64Number Limit = (24.0/116.0);
if (t <= Limit) {
return (108.0/841.0) * (t - (16.0/116.0));
}
return t * t * t;
}
// Standard XYZ to Lab. it can handle negative XZY numbers in some cases
void CMSEXPORT cmsXYZ2Lab(const cmsCIEXYZ* WhitePoint, cmsCIELab* Lab, const cmsCIEXYZ* xyz)
{
cmsFloat64Number fx, fy, fz;
if (WhitePoint == NULL)
WhitePoint = cmsD50_XYZ();
fx = f(xyz->X / WhitePoint->X);
fy = f(xyz->Y / WhitePoint->Y);
fz = f(xyz->Z / WhitePoint->Z);
Lab->L = 116.0*fy - 16.0;
Lab->a = 500.0*(fx - fy);
Lab->b = 200.0*(fy - fz);
}
// Standard XYZ to Lab. It can return negative XYZ in some cases
void CMSEXPORT cmsLab2XYZ(const cmsCIEXYZ* WhitePoint, cmsCIEXYZ* xyz, const cmsCIELab* Lab)
{
cmsFloat64Number x, y, z;
if (WhitePoint == NULL)
WhitePoint = cmsD50_XYZ();
y = (Lab-> L + 16.0) / 116.0;
x = y + 0.002 * Lab -> a;
z = y - 0.005 * Lab -> b;
xyz -> X = f_1(x) * WhitePoint -> X;
xyz -> Y = f_1(y) * WhitePoint -> Y;
xyz -> Z = f_1(z) * WhitePoint -> Z;
}
static
cmsFloat64Number L2float2(cmsUInt16Number v)
{
return (cmsFloat64Number) v / 652.800;
}
// the a/b part
static
cmsFloat64Number ab2float2(cmsUInt16Number v)
{
return ((cmsFloat64Number) v / 256.0) - 128.0;
}
static
cmsUInt16Number L2Fix2(cmsFloat64Number L)
{
return _cmsQuickSaturateWord(L * 652.8);
}
static
cmsUInt16Number ab2Fix2(cmsFloat64Number ab)
{
return _cmsQuickSaturateWord((ab + 128.0) * 256.0);
}
static
cmsFloat64Number L2float4(cmsUInt16Number v)
{
return (cmsFloat64Number) v / 655.35;
}
// the a/b part
static
cmsFloat64Number ab2float4(cmsUInt16Number v)
{
return ((cmsFloat64Number) v / 257.0) - 128.0;
}
void CMSEXPORT cmsLabEncoded2FloatV2(cmsCIELab* Lab, const cmsUInt16Number wLab[3])
{
Lab->L = L2float2(wLab[0]);
Lab->a = ab2float2(wLab[1]);
Lab->b = ab2float2(wLab[2]);
}
void CMSEXPORT cmsLabEncoded2Float(cmsCIELab* Lab, const cmsUInt16Number wLab[3])
{
Lab->L = L2float4(wLab[0]);
Lab->a = ab2float4(wLab[1]);
Lab->b = ab2float4(wLab[2]);
}
static
cmsFloat64Number Clamp_L_doubleV2(cmsFloat64Number L)
{
const cmsFloat64Number L_max = (cmsFloat64Number) (0xFFFF * 100.0) / 0xFF00;
if (L < 0) L = 0;
if (L > L_max) L = L_max;
return L;
}
static
cmsFloat64Number Clamp_ab_doubleV2(cmsFloat64Number ab)
{
if (ab < MIN_ENCODEABLE_ab2) ab = MIN_ENCODEABLE_ab2;
if (ab > MAX_ENCODEABLE_ab2) ab = MAX_ENCODEABLE_ab2;
return ab;
}
void CMSEXPORT cmsFloat2LabEncodedV2(cmsUInt16Number wLab[3], const cmsCIELab* fLab)
{
cmsCIELab Lab;
Lab.L = Clamp_L_doubleV2(fLab ->L);
Lab.a = Clamp_ab_doubleV2(fLab ->a);
Lab.b = Clamp_ab_doubleV2(fLab ->b);
wLab[0] = L2Fix2(Lab.L);
wLab[1] = ab2Fix2(Lab.a);
wLab[2] = ab2Fix2(Lab.b);
}
static
cmsFloat64Number Clamp_L_doubleV4(cmsFloat64Number L)
{
if (L < 0) L = 0;
if (L > 100.0) L = 100.0;
return L;
}
static
cmsFloat64Number Clamp_ab_doubleV4(cmsFloat64Number ab)
{
if (ab < MIN_ENCODEABLE_ab4) ab = MIN_ENCODEABLE_ab4;
if (ab > MAX_ENCODEABLE_ab4) ab = MAX_ENCODEABLE_ab4;
return ab;
}
static
cmsUInt16Number L2Fix4(cmsFloat64Number L)
{
return _cmsQuickSaturateWord(L * 655.35);
}
static
cmsUInt16Number ab2Fix4(cmsFloat64Number ab)
{
return _cmsQuickSaturateWord((ab + 128.0) * 257.0);
}
void CMSEXPORT cmsFloat2LabEncoded(cmsUInt16Number wLab[3], const cmsCIELab* fLab)
{
cmsCIELab Lab;
Lab.L = Clamp_L_doubleV4(fLab ->L);
Lab.a = Clamp_ab_doubleV4(fLab ->a);
Lab.b = Clamp_ab_doubleV4(fLab ->b);
wLab[0] = L2Fix4(Lab.L);
wLab[1] = ab2Fix4(Lab.a);
wLab[2] = ab2Fix4(Lab.b);
}
// Auxiliary: convert to Radians
static
cmsFloat64Number RADIANS(cmsFloat64Number deg)
{
return (deg * M_PI) / 180.;
}
// Auxiliary: atan2 but operating in degrees and returning 0 if a==b==0
static
cmsFloat64Number atan2deg(cmsFloat64Number a, cmsFloat64Number b)
{
cmsFloat64Number h;
if (a == 0 && b == 0)
h = 0;
else
h = atan2(a, b);
h *= (180. / M_PI);
while (h > 360.)
h -= 360.;
while ( h < 0)
h += 360.;
return h;
}
// Auxiliary: Square
static
cmsFloat64Number Sqr(cmsFloat64Number v)
{
return v * v;
}
// From cylindrical coordinates. No check is performed, then negative values are allowed
void CMSEXPORT cmsLab2LCh(cmsCIELCh* LCh, const cmsCIELab* Lab)
{
LCh -> L = Lab -> L;
LCh -> C = pow(Sqr(Lab ->a) + Sqr(Lab ->b), 0.5);
LCh -> h = atan2deg(Lab ->b, Lab ->a);
}
// To cylindrical coordinates. No check is performed, then negative values are allowed
void CMSEXPORT cmsLCh2Lab(cmsCIELab* Lab, const cmsCIELCh* LCh)
{
cmsFloat64Number h = (LCh -> h * M_PI) / 180.0;
Lab -> L = LCh -> L;
Lab -> a = LCh -> C * cos(h);
Lab -> b = LCh -> C * sin(h);
}
// In XYZ All 3 components are encoded using 1.15 fixed point
static
cmsUInt16Number XYZ2Fix(cmsFloat64Number d)
{
return _cmsQuickSaturateWord(d * 32768.0);
}
void CMSEXPORT cmsFloat2XYZEncoded(cmsUInt16Number XYZ[3], const cmsCIEXYZ* fXYZ)
{
cmsCIEXYZ xyz;
xyz.X = fXYZ -> X;
xyz.Y = fXYZ -> Y;
xyz.Z = fXYZ -> Z;
// Clamp to encodeable values.
if (xyz.Y <= 0) {
xyz.X = 0;
xyz.Y = 0;
xyz.Z = 0;
}
if (xyz.X > MAX_ENCODEABLE_XYZ)
xyz.X = MAX_ENCODEABLE_XYZ;
if (xyz.X < 0)
xyz.X = 0;
if (xyz.Y > MAX_ENCODEABLE_XYZ)
xyz.Y = MAX_ENCODEABLE_XYZ;
if (xyz.Y < 0)
xyz.Y = 0;
if (xyz.Z > MAX_ENCODEABLE_XYZ)
xyz.Z = MAX_ENCODEABLE_XYZ;
if (xyz.Z < 0)
xyz.Z = 0;
XYZ[0] = XYZ2Fix(xyz.X);
XYZ[1] = XYZ2Fix(xyz.Y);
XYZ[2] = XYZ2Fix(xyz.Z);
}
// To convert from Fixed 1.15 point to cmsFloat64Number
static
cmsFloat64Number XYZ2float(cmsUInt16Number v)
{
cmsS15Fixed16Number fix32;
// From 1.15 to 15.16
fix32 = v << 1;
// From fixed 15.16 to cmsFloat64Number
return _cms15Fixed16toDouble(fix32);
}
void CMSEXPORT cmsXYZEncoded2Float(cmsCIEXYZ* fXYZ, const cmsUInt16Number XYZ[3])
{
fXYZ -> X = XYZ2float(XYZ[0]);
fXYZ -> Y = XYZ2float(XYZ[1]);
fXYZ -> Z = XYZ2float(XYZ[2]);
}
// Returns dE on two Lab values
cmsFloat64Number CMSEXPORT cmsDeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2)
{
cmsFloat64Number dL, da, db;
dL = fabs(Lab1 -> L - Lab2 -> L);
da = fabs(Lab1 -> a - Lab2 -> a);
db = fabs(Lab1 -> b - Lab2 -> b);
return pow(Sqr(dL) + Sqr(da) + Sqr(db), 0.5);
}
// Return the CIE94 Delta E
cmsFloat64Number CMSEXPORT cmsCIE94DeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2)
{
cmsCIELCh LCh1, LCh2;
cmsFloat64Number dE, dL, dC, dh, dhsq;
cmsFloat64Number c12, sc, sh;
dL = fabs(Lab1 ->L - Lab2 ->L);
cmsLab2LCh(&LCh1, Lab1);
cmsLab2LCh(&LCh2, Lab2);
dC = fabs(LCh1.C - LCh2.C);
dE = cmsDeltaE(Lab1, Lab2);
dhsq = Sqr(dE) - Sqr(dL) - Sqr(dC);
if (dhsq < 0)
dh = 0;
else
dh = pow(dhsq, 0.5);
c12 = sqrt(LCh1.C * LCh2.C);
sc = 1.0 + (0.048 * c12);
sh = 1.0 + (0.014 * c12);
return sqrt(Sqr(dL) + Sqr(dC) / Sqr(sc) + Sqr(dh) / Sqr(sh));
}
// Auxiliary
static
cmsFloat64Number ComputeLBFD(const cmsCIELab* Lab)
{
cmsFloat64Number yt;
if (Lab->L > 7.996969)
yt = (Sqr((Lab->L+16)/116)*((Lab->L+16)/116))*100;
else
yt = 100 * (Lab->L / 903.3);
return (54.6 * (M_LOG10E * (log(yt + 1.5))) - 9.6);
}
// bfd - gets BFD(1:1) difference between Lab1, Lab2
cmsFloat64Number CMSEXPORT cmsBFDdeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2)
{
cmsFloat64Number lbfd1,lbfd2,AveC,Aveh,dE,deltaL,
deltaC,deltah,dc,t,g,dh,rh,rc,rt,bfd;
cmsCIELCh LCh1, LCh2;
lbfd1 = ComputeLBFD(Lab1);
lbfd2 = ComputeLBFD(Lab2);
deltaL = lbfd2 - lbfd1;
cmsLab2LCh(&LCh1, Lab1);
cmsLab2LCh(&LCh2, Lab2);
deltaC = LCh2.C - LCh1.C;
AveC = (LCh1.C+LCh2.C)/2;
Aveh = (LCh1.h+LCh2.h)/2;
dE = cmsDeltaE(Lab1, Lab2);
if (Sqr(dE)>(Sqr(Lab2->L-Lab1->L)+Sqr(deltaC)))
deltah = sqrt(Sqr(dE)-Sqr(Lab2->L-Lab1->L)-Sqr(deltaC));
else
deltah =0;
dc = 0.035 * AveC / (1 + 0.00365 * AveC)+0.521;
g = sqrt(Sqr(Sqr(AveC))/(Sqr(Sqr(AveC))+14000));
t = 0.627+(0.055*cos((Aveh-254)/(180/M_PI))-
0.040*cos((2*Aveh-136)/(180/M_PI))+
0.070*cos((3*Aveh-31)/(180/M_PI))+
0.049*cos((4*Aveh+114)/(180/M_PI))-
0.015*cos((5*Aveh-103)/(180/M_PI)));
dh = dc*(g*t+1-g);
rh = -0.260*cos((Aveh-308)/(180/M_PI))-
0.379*cos((2*Aveh-160)/(180/M_PI))-
0.636*cos((3*Aveh+254)/(180/M_PI))+
0.226*cos((4*Aveh+140)/(180/M_PI))-
0.194*cos((5*Aveh+280)/(180/M_PI));
rc = sqrt((AveC*AveC*AveC*AveC*AveC*AveC)/((AveC*AveC*AveC*AveC*AveC*AveC)+70000000));
rt = rh*rc;
bfd = sqrt(Sqr(deltaL)+Sqr(deltaC/dc)+Sqr(deltah/dh)+(rt*(deltaC/dc)*(deltah/dh)));
return bfd;
}
// cmc - CMC(l:c) difference between Lab1, Lab2
cmsFloat64Number CMSEXPORT cmsCMCdeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2, cmsFloat64Number l, cmsFloat64Number c)
{
cmsFloat64Number dE,dL,dC,dh,sl,sc,sh,t,f,cmc;
cmsCIELCh LCh1, LCh2;
if (Lab1 ->L == 0 && Lab2 ->L == 0) return 0;
cmsLab2LCh(&LCh1, Lab1);
cmsLab2LCh(&LCh2, Lab2);
dL = Lab2->L-Lab1->L;
dC = LCh2.C-LCh1.C;
dE = cmsDeltaE(Lab1, Lab2);
if (Sqr(dE)>(Sqr(dL)+Sqr(dC)))
dh = sqrt(Sqr(dE)-Sqr(dL)-Sqr(dC));
else
dh =0;
if ((LCh1.h > 164) && (LCh1.h < 345))
t = 0.56 + fabs(0.2 * cos(((LCh1.h + 168)/(180/M_PI))));
else
t = 0.36 + fabs(0.4 * cos(((LCh1.h + 35 )/(180/M_PI))));
sc = 0.0638 * LCh1.C / (1 + 0.0131 * LCh1.C) + 0.638;
sl = 0.040975 * Lab1->L /(1 + 0.01765 * Lab1->L);
if (Lab1->L<16)
sl = 0.511;
f = sqrt((LCh1.C * LCh1.C * LCh1.C * LCh1.C)/((LCh1.C * LCh1.C * LCh1.C * LCh1.C)+1900));
sh = sc*(t*f+1-f);
cmc = sqrt(Sqr(dL/(l*sl))+Sqr(dC/(c*sc))+Sqr(dh/sh));
return cmc;
}
// dE2000 The weightings KL, KC and KH can be modified to reflect the relative
// importance of lightness, chroma and hue in different industrial applications
cmsFloat64Number CMSEXPORT cmsCIE2000DeltaE(const cmsCIELab* Lab1, const cmsCIELab* Lab2,
cmsFloat64Number Kl, cmsFloat64Number Kc, cmsFloat64Number Kh)
{
cmsFloat64Number L1 = Lab1->L;
cmsFloat64Number a1 = Lab1->a;
cmsFloat64Number b1 = Lab1->b;
cmsFloat64Number C = sqrt( Sqr(a1) + Sqr(b1) );
cmsFloat64Number Ls = Lab2 ->L;
cmsFloat64Number as = Lab2 ->a;
cmsFloat64Number bs = Lab2 ->b;
cmsFloat64Number Cs = sqrt( Sqr(as) + Sqr(bs) );
cmsFloat64Number G = 0.5 * ( 1 - sqrt(pow((C + Cs) / 2 , 7.0) / (pow((C + Cs) / 2, 7.0) + pow(25.0, 7.0) ) ));
cmsFloat64Number a_p = (1 + G ) * a1;
cmsFloat64Number b_p = b1;
cmsFloat64Number C_p = sqrt( Sqr(a_p) + Sqr(b_p));
cmsFloat64Number h_p = atan2deg(b_p, a_p);
cmsFloat64Number a_ps = (1 + G) * as;
cmsFloat64Number b_ps = bs;
cmsFloat64Number C_ps = sqrt(Sqr(a_ps) + Sqr(b_ps));
cmsFloat64Number h_ps = atan2deg(b_ps, a_ps);
cmsFloat64Number meanC_p =(C_p + C_ps) / 2;
cmsFloat64Number hps_plus_hp = h_ps + h_p;
cmsFloat64Number hps_minus_hp = h_ps - h_p;
cmsFloat64Number meanh_p = fabs(hps_minus_hp) <= 180.000001 ? (hps_plus_hp)/2 :
(hps_plus_hp) < 360 ? (hps_plus_hp + 360)/2 :
(hps_plus_hp - 360)/2;
cmsFloat64Number delta_h = (hps_minus_hp) <= -180.000001 ? (hps_minus_hp + 360) :
(hps_minus_hp) > 180 ? (hps_minus_hp - 360) :
(hps_minus_hp);
cmsFloat64Number delta_L = (Ls - L1);
cmsFloat64Number delta_C = (C_ps - C_p );
cmsFloat64Number delta_H =2 * sqrt(C_ps*C_p) * sin(RADIANS(delta_h) / 2);
cmsFloat64Number T = 1 - 0.17 * cos(RADIANS(meanh_p-30))
+ 0.24 * cos(RADIANS(2*meanh_p))
+ 0.32 * cos(RADIANS(3*meanh_p + 6))
- 0.2 * cos(RADIANS(4*meanh_p - 63));
cmsFloat64Number Sl = 1 + (0.015 * Sqr((Ls + L1) /2- 50) )/ sqrt(20 + Sqr( (Ls+L1)/2 - 50) );
cmsFloat64Number Sc = 1 + 0.045 * (C_p + C_ps)/2;
cmsFloat64Number Sh = 1 + 0.015 * ((C_ps + C_p)/2) * T;
cmsFloat64Number delta_ro = 30 * exp( -Sqr(((meanh_p - 275 ) / 25)));
cmsFloat64Number Rc = 2 * sqrt(( pow(meanC_p, 7.0) )/( pow(meanC_p, 7.0) + pow(25.0, 7.0)));
cmsFloat64Number Rt = -sin(2 * RADIANS(delta_ro)) * Rc;
cmsFloat64Number deltaE00 = sqrt( Sqr(delta_L /(Sl * Kl)) +
Sqr(delta_C/(Sc * Kc)) +
Sqr(delta_H/(Sh * Kh)) +
Rt*(delta_C/(Sc * Kc)) * (delta_H / (Sh * Kh)));
return deltaE00;
}
// This function returns a number of gridpoints to be used as LUT table. It assumes same number
// of gripdpoints in all dimensions. Flags may override the choice.
cmsUInt32Number _cmsReasonableGridpointsByColorspace(cmsColorSpaceSignature Colorspace, cmsUInt32Number dwFlags)
{
cmsUInt32Number nChannels;
// Already specified?
if (dwFlags & 0x00FF0000) {
// Yes, grab'em
return (dwFlags >> 16) & 0xFF;
}
nChannels = cmsChannelsOf(Colorspace);
// HighResPrecalc is maximum resolution
if (dwFlags & cmsFLAGS_HIGHRESPRECALC) {
if (nChannels > 4)
return 7; // 7 for Hifi
if (nChannels == 4) // 23 for CMYK
return 23;
return 49; // 49 for RGB and others
}
// LowResPrecal is lower resolution
if (dwFlags & cmsFLAGS_LOWRESPRECALC) {
if (nChannels > 4)
return 6; // 6 for more than 4 channels
if (nChannels == 1)
return 33; // For monochrome
return 17; // 17 for remaining
}
// Default values
if (nChannels > 4)
return 7; // 7 for Hifi
if (nChannels == 4)
return 17; // 17 for CMYK
return 33; // 33 for RGB
}
cmsBool _cmsEndPointsBySpace(cmsColorSpaceSignature Space,
cmsUInt16Number **White,
cmsUInt16Number **Black,
cmsUInt32Number *nOutputs)
{
// Only most common spaces
static cmsUInt16Number RGBblack[4] = { 0, 0, 0 };
static cmsUInt16Number RGBwhite[4] = { 0xffff, 0xffff, 0xffff };
static cmsUInt16Number CMYKblack[4] = { 0xffff, 0xffff, 0xffff, 0xffff }; // 400% of ink
static cmsUInt16Number CMYKwhite[4] = { 0, 0, 0, 0 };
static cmsUInt16Number LABblack[4] = { 0, 0x8080, 0x8080 }; // V4 Lab encoding
static cmsUInt16Number LABwhite[4] = { 0xFFFF, 0x8080, 0x8080 };
static cmsUInt16Number CMYblack[4] = { 0xffff, 0xffff, 0xffff };
static cmsUInt16Number CMYwhite[4] = { 0, 0, 0 };
static cmsUInt16Number Grayblack[4] = { 0 };
static cmsUInt16Number GrayWhite[4] = { 0xffff };
switch (Space) {
case cmsSigGrayData: if (White) *White = GrayWhite;
if (Black) *Black = Grayblack;
if (nOutputs) *nOutputs = 1;
return TRUE;
case cmsSigRgbData: if (White) *White = RGBwhite;
if (Black) *Black = RGBblack;
if (nOutputs) *nOutputs = 3;
return TRUE;
case cmsSigLabData: if (White) *White = LABwhite;
if (Black) *Black = LABblack;
if (nOutputs) *nOutputs = 3;
return TRUE;
case cmsSigCmykData: if (White) *White = CMYKwhite;
if (Black) *Black = CMYKblack;
if (nOutputs) *nOutputs = 4;
return TRUE;
case cmsSigCmyData: if (White) *White = CMYwhite;
if (Black) *Black = CMYblack;
if (nOutputs) *nOutputs = 3;
return TRUE;
default:;
}
return FALSE;
}
// Several utilities -------------------------------------------------------
// Translate from our colorspace to ICC representation
cmsColorSpaceSignature CMSEXPORT _cmsICCcolorSpace(int OurNotation)
{
switch (OurNotation) {
case 1:
case PT_GRAY: return cmsSigGrayData;
case 2:
case PT_RGB: return cmsSigRgbData;
case PT_CMY: return cmsSigCmyData;
case PT_CMYK: return cmsSigCmykData;
case PT_YCbCr:return cmsSigYCbCrData;
case PT_YUV: return cmsSigLuvData;
case PT_XYZ: return cmsSigXYZData;
case PT_LabV2:
case PT_Lab: return cmsSigLabData;
case PT_YUVK: return cmsSigLuvKData;
case PT_HSV: return cmsSigHsvData;
case PT_HLS: return cmsSigHlsData;
case PT_Yxy: return cmsSigYxyData;
case PT_MCH1: return cmsSigMCH1Data;
case PT_MCH2: return cmsSigMCH2Data;
case PT_MCH3: return cmsSigMCH3Data;
case PT_MCH4: return cmsSigMCH4Data;
case PT_MCH5: return cmsSigMCH5Data;
case PT_MCH6: return cmsSigMCH6Data;
case PT_MCH7: return cmsSigMCH7Data;
case PT_MCH8: return cmsSigMCH8Data;
case PT_MCH9: return cmsSigMCH9Data;
case PT_MCH10: return cmsSigMCHAData;
case PT_MCH11: return cmsSigMCHBData;
case PT_MCH12: return cmsSigMCHCData;
case PT_MCH13: return cmsSigMCHDData;
case PT_MCH14: return cmsSigMCHEData;
case PT_MCH15: return cmsSigMCHFData;
default: return (cmsColorSpaceSignature) 0;
}
}
int CMSEXPORT _cmsLCMScolorSpace(cmsColorSpaceSignature ProfileSpace)
{
switch (ProfileSpace) {
case cmsSigGrayData: return PT_GRAY;
case cmsSigRgbData: return PT_RGB;
case cmsSigCmyData: return PT_CMY;
case cmsSigCmykData: return PT_CMYK;
case cmsSigYCbCrData:return PT_YCbCr;
case cmsSigLuvData: return PT_YUV;
case cmsSigXYZData: return PT_XYZ;
case cmsSigLabData: return PT_Lab;
case cmsSigLuvKData: return PT_YUVK;
case cmsSigHsvData: return PT_HSV;
case cmsSigHlsData: return PT_HLS;
case cmsSigYxyData: return PT_Yxy;
case cmsSig1colorData:
case cmsSigMCH1Data: return PT_MCH1;
case cmsSig2colorData:
case cmsSigMCH2Data: return PT_MCH2;
case cmsSig3colorData:
case cmsSigMCH3Data: return PT_MCH3;
case cmsSig4colorData:
case cmsSigMCH4Data: return PT_MCH4;
case cmsSig5colorData:
case cmsSigMCH5Data: return PT_MCH5;
case cmsSig6colorData:
case cmsSigMCH6Data: return PT_MCH6;
case cmsSigMCH7Data:
case cmsSig7colorData:return PT_MCH7;
case cmsSigMCH8Data:
case cmsSig8colorData:return PT_MCH8;
case cmsSigMCH9Data:
case cmsSig9colorData:return PT_MCH9;
case cmsSigMCHAData:
case cmsSig10colorData:return PT_MCH10;
case cmsSigMCHBData:
case cmsSig11colorData:return PT_MCH11;
case cmsSigMCHCData:
case cmsSig12colorData:return PT_MCH12;
case cmsSigMCHDData:
case cmsSig13colorData:return PT_MCH13;
case cmsSigMCHEData:
case cmsSig14colorData:return PT_MCH14;
case cmsSigMCHFData:
case cmsSig15colorData:return PT_MCH15;
default: return (cmsColorSpaceSignature) 0;
}
}
cmsUInt32Number CMSEXPORT cmsChannelsOf(cmsColorSpaceSignature ColorSpace)
{
switch (ColorSpace) {
case cmsSigMCH1Data:
case cmsSig1colorData:
case cmsSigGrayData: return 1;
case cmsSigMCH2Data:
case cmsSig2colorData: return 2;
case cmsSigXYZData:
case cmsSigLabData:
case cmsSigLuvData:
case cmsSigYCbCrData:
case cmsSigYxyData:
case cmsSigRgbData:
case cmsSigHsvData:
case cmsSigHlsData:
case cmsSigCmyData:
case cmsSigMCH3Data:
case cmsSig3colorData: return 3;
case cmsSigLuvKData:
case cmsSigCmykData:
case cmsSigMCH4Data:
case cmsSig4colorData: return 4;
case cmsSigMCH5Data:
case cmsSig5colorData: return 5;
case cmsSigMCH6Data:
case cmsSig6colorData: return 6;
case cmsSigMCH7Data:
case cmsSig7colorData: return 7;
case cmsSigMCH8Data:
case cmsSig8colorData: return 8;
case cmsSigMCH9Data:
case cmsSig9colorData: return 9;
case cmsSigMCHAData:
case cmsSig10colorData: return 10;
case cmsSigMCHBData:
case cmsSig11colorData: return 11;
case cmsSigMCHCData:
case cmsSig12colorData: return 12;
case cmsSigMCHDData:
case cmsSig13colorData: return 13;
case cmsSigMCHEData:
case cmsSig14colorData: return 14;
case cmsSigMCHFData:
case cmsSig15colorData: return 15;
default: return 3;
}
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env ruby
require 'pathname'
# path to your application root.
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
Dir.chdir APP_ROOT do
# This script is a starting point to setup your application.
# Add necessary setup steps to this file:
puts "== Installing dependencies =="
system "gem install bundler --conservative"
system "bundle check || bundle install"
# puts "\n== Copying sample files =="
# unless File.exist?("config/database.yml")
# system "cp config/database.yml.sample config/database.yml"
# end
puts "\n== Preparing database =="
system "bin/rake db:setup"
puts "\n== Removing old logs and tempfiles =="
system "rm -f log/*"
system "rm -rf tmp/cache"
puts "\n== Restarting application server =="
system "touch tmp/restart.txt"
end
| {
"pile_set_name": "Github"
} |
{
"name": "react-cosmos-shared2",
"version": "5.5.0",
"description": "Code shared between Cosmos packages",
"repository": "https://github.com/react-cosmos/react-cosmos/tree/master/packages/react-cosmos-shared2",
"license": "MIT",
"dependencies": {
"lodash": "^4.17.20",
"query-string": "5.1.1",
"react-element-to-jsx-string": "^14.3.1",
"react-is": "^16.13.1",
"socket.io-client": "2.2.0"
}
}
| {
"pile_set_name": "Github"
} |
submodule ietf-snmp-ssh {
belongs-to ietf-snmp {
prefix snmp;
}
import ietf-inet-types {
prefix inet;
}
include ietf-snmp-common;
include ietf-snmp-engine;
include ietf-snmp-target;
organization
"IETF NETMOD (NETCONF Data Modeling Language) Working Group";
contact
"WG Web: <http://tools.ietf.org/wg/netmod/>
WG List: <mailto:[email protected]>
WG Chair: Thomas Nadeau
<mailto:[email protected]>
WG Chair: Juergen Schoenwaelder
<mailto:[email protected]>
Editor: Martin Bjorklund
<mailto:[email protected]>
Editor: Juergen Schoenwaelder
<mailto:[email protected]>";
description
"This submodule contains a collection of YANG definitions for
configuring the Secure Shell Transport Model (SSHTM)
of SNMP.
Copyright (c) 2014 IETF Trust and the persons identified as
authors of the code. All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, is permitted pursuant to, and subject
to the license terms contained in, the Simplified BSD License
set forth in Section 4.c of the IETF Trust's Legal Provisions
Relating to IETF Documents
(http://trustee.ietf.org/license-info).
This version of this YANG module is part of RFC 7407; see
the RFC itself for full legal notices.";
reference
"RFC 5592: Secure Shell Transport Model for the
Simple Network Management Protocol (SNMP)";
revision 2014-12-10 {
description
"Initial revision.";
reference
"RFC 7407: A YANG Data Model for SNMP Configuration";
}
feature sshtm {
description
"A server implements this feature if it supports the
Secure Shell Transport Model for SNMP.";
reference
"RFC 5592: Secure Shell Transport Model for the
Simple Network Management Protocol (SNMP)";
}
augment /snmp:snmp/snmp:engine/snmp:listen/snmp:transport {
if-feature sshtm;
case ssh {
container ssh {
description
"The IPv4 or IPv6 address and port to which the
engine listens for SNMP messages over SSH.";
leaf ip {
type inet:ip-address;
mandatory true;
description
"The IPv4 or IPv6 address on which the engine listens
for SNMP messages over SSH.";
}
leaf port {
type inet:port-number;
description
"The TCP port on which the engine listens for SNMP
messages over SSH.
If the port is not configured, an engine that
acts as a Command Responder uses port 5161, and
an engine that acts as a Notification Receiver
uses port 5162.";
}
}
}
}
augment /snmp:snmp/snmp:target/snmp:transport {
if-feature sshtm;
case ssh {
reference
"RFC 5592: Secure Shell Transport Model for the
Simple Network Management Protocol (SNMP).
SNMP-SSH-TM-MIB.snmpSSHDomain";
container ssh {
leaf ip {
type inet:host;
mandatory true;
reference
"RFC 3413: Simple Network Management Protocol (SNMP).
Applications.
SNMP-TARGET-MIB.snmpTargetAddrTAddress
RFC 5592: Secure Shell Transport Model for the
Simple Network Management Protocol (SNMP).
SNMP-SSH-TM-MIB.SnmpSSHAddress";
}
leaf port {
type inet:port-number;
default 5161;
reference
"RFC 3413: Simple Network Management Protocol (SNMP).
Applications.
SNMP-TARGET-MIB.snmpTargetAddrTAddress
RFC 5592: Secure Shell Transport Model for the
Simple Network Management Protocol (SNMP).
SNMP-SSH-TM-MIB.SnmpSSHAddress";
}
leaf username {
type string;
reference
"RFC 3413: Simple Network Management Protocol (SNMP).
Applications.
SNMP-TARGET-MIB.snmpTargetAddrTAddress
RFC 5592: Secure Shell Transport Model for the
Simple Network Management Protocol (SNMP).
SNMP-SSH-TM-MIB.SnmpSSHAddress";
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2012 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 bn256
// For details of the algorithms used, see "Multiplication and Squaring on
// Pairing-Friendly Fields, Devegili et al.
// http://eprint.iacr.org/2006/471.pdf.
import (
"math/big"
)
// gfP6 implements the field of size p⁶ as a cubic extension of gfP2 where τ³=ξ
// and ξ=i+3.
type gfP6 struct {
x, y, z *gfP2 // value is xτ² + yτ + z
}
func newGFp6(pool *bnPool) *gfP6 {
return &gfP6{newGFp2(pool), newGFp2(pool), newGFp2(pool)}
}
func (e *gfP6) String() string {
return "(" + e.x.String() + "," + e.y.String() + "," + e.z.String() + ")"
}
func (e *gfP6) Put(pool *bnPool) {
e.x.Put(pool)
e.y.Put(pool)
e.z.Put(pool)
}
func (e *gfP6) Set(a *gfP6) *gfP6 {
e.x.Set(a.x)
e.y.Set(a.y)
e.z.Set(a.z)
return e
}
func (e *gfP6) SetZero() *gfP6 {
e.x.SetZero()
e.y.SetZero()
e.z.SetZero()
return e
}
func (e *gfP6) SetOne() *gfP6 {
e.x.SetZero()
e.y.SetZero()
e.z.SetOne()
return e
}
func (e *gfP6) Minimal() {
e.x.Minimal()
e.y.Minimal()
e.z.Minimal()
}
func (e *gfP6) IsZero() bool {
return e.x.IsZero() && e.y.IsZero() && e.z.IsZero()
}
func (e *gfP6) IsOne() bool {
return e.x.IsZero() && e.y.IsZero() && e.z.IsOne()
}
func (e *gfP6) Negative(a *gfP6) *gfP6 {
e.x.Negative(a.x)
e.y.Negative(a.y)
e.z.Negative(a.z)
return e
}
func (e *gfP6) Frobenius(a *gfP6, pool *bnPool) *gfP6 {
e.x.Conjugate(a.x)
e.y.Conjugate(a.y)
e.z.Conjugate(a.z)
e.x.Mul(e.x, xiTo2PMinus2Over3, pool)
e.y.Mul(e.y, xiToPMinus1Over3, pool)
return e
}
// FrobeniusP2 computes (xτ²+yτ+z)^(p²) = xτ^(2p²) + yτ^(p²) + z
func (e *gfP6) FrobeniusP2(a *gfP6) *gfP6 {
// τ^(2p²) = τ²τ^(2p²-2) = τ²ξ^((2p²-2)/3)
e.x.MulScalar(a.x, xiTo2PSquaredMinus2Over3)
// τ^(p²) = ττ^(p²-1) = τξ^((p²-1)/3)
e.y.MulScalar(a.y, xiToPSquaredMinus1Over3)
e.z.Set(a.z)
return e
}
func (e *gfP6) Add(a, b *gfP6) *gfP6 {
e.x.Add(a.x, b.x)
e.y.Add(a.y, b.y)
e.z.Add(a.z, b.z)
return e
}
func (e *gfP6) Sub(a, b *gfP6) *gfP6 {
e.x.Sub(a.x, b.x)
e.y.Sub(a.y, b.y)
e.z.Sub(a.z, b.z)
return e
}
func (e *gfP6) Double(a *gfP6) *gfP6 {
e.x.Double(a.x)
e.y.Double(a.y)
e.z.Double(a.z)
return e
}
func (e *gfP6) Mul(a, b *gfP6, pool *bnPool) *gfP6 {
// "Multiplication and Squaring on Pairing-Friendly Fields"
// Section 4, Karatsuba method.
// http://eprint.iacr.org/2006/471.pdf
v0 := newGFp2(pool)
v0.Mul(a.z, b.z, pool)
v1 := newGFp2(pool)
v1.Mul(a.y, b.y, pool)
v2 := newGFp2(pool)
v2.Mul(a.x, b.x, pool)
t0 := newGFp2(pool)
t0.Add(a.x, a.y)
t1 := newGFp2(pool)
t1.Add(b.x, b.y)
tz := newGFp2(pool)
tz.Mul(t0, t1, pool)
tz.Sub(tz, v1)
tz.Sub(tz, v2)
tz.MulXi(tz, pool)
tz.Add(tz, v0)
t0.Add(a.y, a.z)
t1.Add(b.y, b.z)
ty := newGFp2(pool)
ty.Mul(t0, t1, pool)
ty.Sub(ty, v0)
ty.Sub(ty, v1)
t0.MulXi(v2, pool)
ty.Add(ty, t0)
t0.Add(a.x, a.z)
t1.Add(b.x, b.z)
tx := newGFp2(pool)
tx.Mul(t0, t1, pool)
tx.Sub(tx, v0)
tx.Add(tx, v1)
tx.Sub(tx, v2)
e.x.Set(tx)
e.y.Set(ty)
e.z.Set(tz)
t0.Put(pool)
t1.Put(pool)
tx.Put(pool)
ty.Put(pool)
tz.Put(pool)
v0.Put(pool)
v1.Put(pool)
v2.Put(pool)
return e
}
func (e *gfP6) MulScalar(a *gfP6, b *gfP2, pool *bnPool) *gfP6 {
e.x.Mul(a.x, b, pool)
e.y.Mul(a.y, b, pool)
e.z.Mul(a.z, b, pool)
return e
}
func (e *gfP6) MulGFP(a *gfP6, b *big.Int) *gfP6 {
e.x.MulScalar(a.x, b)
e.y.MulScalar(a.y, b)
e.z.MulScalar(a.z, b)
return e
}
// MulTau computes τ·(aτ²+bτ+c) = bτ²+cτ+aξ
func (e *gfP6) MulTau(a *gfP6, pool *bnPool) {
tz := newGFp2(pool)
tz.MulXi(a.x, pool)
ty := newGFp2(pool)
ty.Set(a.y)
e.y.Set(a.z)
e.x.Set(ty)
e.z.Set(tz)
tz.Put(pool)
ty.Put(pool)
}
func (e *gfP6) Square(a *gfP6, pool *bnPool) *gfP6 {
v0 := newGFp2(pool).Square(a.z, pool)
v1 := newGFp2(pool).Square(a.y, pool)
v2 := newGFp2(pool).Square(a.x, pool)
c0 := newGFp2(pool).Add(a.x, a.y)
c0.Square(c0, pool)
c0.Sub(c0, v1)
c0.Sub(c0, v2)
c0.MulXi(c0, pool)
c0.Add(c0, v0)
c1 := newGFp2(pool).Add(a.y, a.z)
c1.Square(c1, pool)
c1.Sub(c1, v0)
c1.Sub(c1, v1)
xiV2 := newGFp2(pool).MulXi(v2, pool)
c1.Add(c1, xiV2)
c2 := newGFp2(pool).Add(a.x, a.z)
c2.Square(c2, pool)
c2.Sub(c2, v0)
c2.Add(c2, v1)
c2.Sub(c2, v2)
e.x.Set(c2)
e.y.Set(c1)
e.z.Set(c0)
v0.Put(pool)
v1.Put(pool)
v2.Put(pool)
c0.Put(pool)
c1.Put(pool)
c2.Put(pool)
xiV2.Put(pool)
return e
}
func (e *gfP6) Invert(a *gfP6, pool *bnPool) *gfP6 {
// See "Implementing cryptographic pairings", M. Scott, section 3.2.
// ftp://136.206.11.249/pub/crypto/pairings.pdf
// Here we can give a short explanation of how it works: let j be a cubic root of
// unity in GF(p²) so that 1+j+j²=0.
// Then (xτ² + yτ + z)(xj²τ² + yjτ + z)(xjτ² + yj²τ + z)
// = (xτ² + yτ + z)(Cτ²+Bτ+A)
// = (x³ξ²+y³ξ+z³-3ξxyz) = F is an element of the base field (the norm).
//
// On the other hand (xj²τ² + yjτ + z)(xjτ² + yj²τ + z)
// = τ²(y²-ξxz) + τ(ξx²-yz) + (z²-ξxy)
//
// So that's why A = (z²-ξxy), B = (ξx²-yz), C = (y²-ξxz)
t1 := newGFp2(pool)
A := newGFp2(pool)
A.Square(a.z, pool)
t1.Mul(a.x, a.y, pool)
t1.MulXi(t1, pool)
A.Sub(A, t1)
B := newGFp2(pool)
B.Square(a.x, pool)
B.MulXi(B, pool)
t1.Mul(a.y, a.z, pool)
B.Sub(B, t1)
C := newGFp2(pool)
C.Square(a.y, pool)
t1.Mul(a.x, a.z, pool)
C.Sub(C, t1)
F := newGFp2(pool)
F.Mul(C, a.y, pool)
F.MulXi(F, pool)
t1.Mul(A, a.z, pool)
F.Add(F, t1)
t1.Mul(B, a.x, pool)
t1.MulXi(t1, pool)
F.Add(F, t1)
F.Invert(F, pool)
e.x.Mul(C, F, pool)
e.y.Mul(B, F, pool)
e.z.Mul(A, F, pool)
t1.Put(pool)
A.Put(pool)
B.Put(pool)
C.Put(pool)
F.Put(pool)
return e
}
| {
"pile_set_name": "Github"
} |
label1 ; This is a label
write "Hello World !",!
quit
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2013-2016 Dave Collins <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package spew
import (
"bytes"
"fmt"
"io"
"reflect"
"sort"
"strconv"
)
// Some constants in the form of bytes to avoid string overhead. This mirrors
// the technique used in the fmt package.
var (
panicBytes = []byte("(PANIC=")
plusBytes = []byte("+")
iBytes = []byte("i")
trueBytes = []byte("true")
falseBytes = []byte("false")
interfaceBytes = []byte("(interface {})")
commaNewlineBytes = []byte(",\n")
newlineBytes = []byte("\n")
openBraceBytes = []byte("{")
openBraceNewlineBytes = []byte("{\n")
closeBraceBytes = []byte("}")
asteriskBytes = []byte("*")
colonBytes = []byte(":")
colonSpaceBytes = []byte(": ")
openParenBytes = []byte("(")
closeParenBytes = []byte(")")
spaceBytes = []byte(" ")
pointerChainBytes = []byte("->")
nilAngleBytes = []byte("<nil>")
maxNewlineBytes = []byte("<max depth reached>\n")
maxShortBytes = []byte("<max>")
circularBytes = []byte("<already shown>")
circularShortBytes = []byte("<shown>")
invalidAngleBytes = []byte("<invalid>")
openBracketBytes = []byte("[")
closeBracketBytes = []byte("]")
percentBytes = []byte("%")
precisionBytes = []byte(".")
openAngleBytes = []byte("<")
closeAngleBytes = []byte(">")
openMapBytes = []byte("map[")
closeMapBytes = []byte("]")
lenEqualsBytes = []byte("len=")
capEqualsBytes = []byte("cap=")
)
// hexDigits is used to map a decimal value to a hex digit.
var hexDigits = "0123456789abcdef"
// catchPanic handles any panics that might occur during the handleMethods
// calls.
func catchPanic(w io.Writer, v reflect.Value) {
if err := recover(); err != nil {
w.Write(panicBytes)
fmt.Fprintf(w, "%v", err)
w.Write(closeParenBytes)
}
}
// handleMethods attempts to call the Error and String methods on the underlying
// type the passed reflect.Value represents and outputes the result to Writer w.
//
// It handles panics in any called methods by catching and displaying the error
// as the formatted value.
func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
// We need an interface to check if the type implements the error or
// Stringer interface. However, the reflect package won't give us an
// interface on certain things like unexported struct fields in order
// to enforce visibility rules. We use unsafe, when it's available,
// to bypass these restrictions since this package does not mutate the
// values.
if !v.CanInterface() {
if UnsafeDisabled {
return false
}
v = unsafeReflectValue(v)
}
// Choose whether or not to do error and Stringer interface lookups against
// the base type or a pointer to the base type depending on settings.
// Technically calling one of these methods with a pointer receiver can
// mutate the value, however, types which choose to satisify an error or
// Stringer interface with a pointer receiver should not be mutating their
// state inside these interface methods.
if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() {
v = unsafeReflectValue(v)
}
if v.CanAddr() {
v = v.Addr()
}
// Is it an error or Stringer?
switch iface := v.Interface().(type) {
case error:
defer catchPanic(w, v)
if cs.ContinueOnMethod {
w.Write(openParenBytes)
w.Write([]byte(iface.Error()))
w.Write(closeParenBytes)
w.Write(spaceBytes)
return false
}
w.Write([]byte(iface.Error()))
return true
case fmt.Stringer:
defer catchPanic(w, v)
if cs.ContinueOnMethod {
w.Write(openParenBytes)
w.Write([]byte(iface.String()))
w.Write(closeParenBytes)
w.Write(spaceBytes)
return false
}
w.Write([]byte(iface.String()))
return true
}
return false
}
// printBool outputs a boolean value as true or false to Writer w.
func printBool(w io.Writer, val bool) {
if val {
w.Write(trueBytes)
} else {
w.Write(falseBytes)
}
}
// printInt outputs a signed integer value to Writer w.
func printInt(w io.Writer, val int64, base int) {
w.Write([]byte(strconv.FormatInt(val, base)))
}
// printUint outputs an unsigned integer value to Writer w.
func printUint(w io.Writer, val uint64, base int) {
w.Write([]byte(strconv.FormatUint(val, base)))
}
// printFloat outputs a floating point value using the specified precision,
// which is expected to be 32 or 64bit, to Writer w.
func printFloat(w io.Writer, val float64, precision int) {
w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
}
// printComplex outputs a complex value using the specified float precision
// for the real and imaginary parts to Writer w.
func printComplex(w io.Writer, c complex128, floatPrecision int) {
r := real(c)
w.Write(openParenBytes)
w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
i := imag(c)
if i >= 0 {
w.Write(plusBytes)
}
w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
w.Write(iBytes)
w.Write(closeParenBytes)
}
// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x'
// prefix to Writer w.
func printHexPtr(w io.Writer, p uintptr) {
// Null pointer.
num := uint64(p)
if num == 0 {
w.Write(nilAngleBytes)
return
}
// Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
buf := make([]byte, 18)
// It's simpler to construct the hex string right to left.
base := uint64(16)
i := len(buf) - 1
for num >= base {
buf[i] = hexDigits[num%base]
num /= base
i--
}
buf[i] = hexDigits[num]
// Add '0x' prefix.
i--
buf[i] = 'x'
i--
buf[i] = '0'
// Strip unused leading bytes.
buf = buf[i:]
w.Write(buf)
}
// valuesSorter implements sort.Interface to allow a slice of reflect.Value
// elements to be sorted.
type valuesSorter struct {
values []reflect.Value
strings []string // either nil or same len and values
cs *ConfigState
}
// newValuesSorter initializes a valuesSorter instance, which holds a set of
// surrogate keys on which the data should be sorted. It uses flags in
// ConfigState to decide if and how to populate those surrogate keys.
func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface {
vs := &valuesSorter{values: values, cs: cs}
if canSortSimply(vs.values[0].Kind()) {
return vs
}
if !cs.DisableMethods {
vs.strings = make([]string, len(values))
for i := range vs.values {
b := bytes.Buffer{}
if !handleMethods(cs, &b, vs.values[i]) {
vs.strings = nil
break
}
vs.strings[i] = b.String()
}
}
if vs.strings == nil && cs.SpewKeys {
vs.strings = make([]string, len(values))
for i := range vs.values {
vs.strings[i] = Sprintf("%#v", vs.values[i].Interface())
}
}
return vs
}
// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted
// directly, or whether it should be considered for sorting by surrogate keys
// (if the ConfigState allows it).
func canSortSimply(kind reflect.Kind) bool {
// This switch parallels valueSortLess, except for the default case.
switch kind {
case reflect.Bool:
return true
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return true
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
return true
case reflect.Float32, reflect.Float64:
return true
case reflect.String:
return true
case reflect.Uintptr:
return true
case reflect.Array:
return true
}
return false
}
// Len returns the number of values in the slice. It is part of the
// sort.Interface implementation.
func (s *valuesSorter) Len() int {
return len(s.values)
}
// Swap swaps the values at the passed indices. It is part of the
// sort.Interface implementation.
func (s *valuesSorter) Swap(i, j int) {
s.values[i], s.values[j] = s.values[j], s.values[i]
if s.strings != nil {
s.strings[i], s.strings[j] = s.strings[j], s.strings[i]
}
}
// valueSortLess returns whether the first value should sort before the second
// value. It is used by valueSorter.Less as part of the sort.Interface
// implementation.
func valueSortLess(a, b reflect.Value) bool {
switch a.Kind() {
case reflect.Bool:
return !a.Bool() && b.Bool()
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return a.Int() < b.Int()
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
return a.Uint() < b.Uint()
case reflect.Float32, reflect.Float64:
return a.Float() < b.Float()
case reflect.String:
return a.String() < b.String()
case reflect.Uintptr:
return a.Uint() < b.Uint()
case reflect.Array:
// Compare the contents of both arrays.
l := a.Len()
for i := 0; i < l; i++ {
av := a.Index(i)
bv := b.Index(i)
if av.Interface() == bv.Interface() {
continue
}
return valueSortLess(av, bv)
}
}
return a.String() < b.String()
}
// Less returns whether the value at index i should sort before the
// value at index j. It is part of the sort.Interface implementation.
func (s *valuesSorter) Less(i, j int) bool {
if s.strings == nil {
return valueSortLess(s.values[i], s.values[j])
}
return s.strings[i] < s.strings[j]
}
// sortValues is a sort function that handles both native types and any type that
// can be converted to error or Stringer. Other inputs are sorted according to
// their Value.String() value to ensure display stability.
func sortValues(values []reflect.Value, cs *ConfigState) {
if len(values) == 0 {
return
}
sort.Sort(newValuesSorter(values, cs))
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- From: file:/C:/Users/IBM_ADMIN/git/owaspSecurityShepherdLATAM/MobileShepherd/ReverseEngineer4/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/21.0.3/res/values-my-rMM/values.xml -->
<eat-comment/>
<string msgid="4600421777120114993" name="abc_action_bar_home_description">"မူလနေရာကို သွားရန်"</string>
<string msgid="1397052879051804371" name="abc_action_bar_home_description_format">"%1$s၊ %2$s"</string>
<string msgid="6623331958280229229" name="abc_action_bar_home_subtitle_description_format">"%1$s ၊ %2$s ၊ %3$s"</string>
<string msgid="1594238315039666878" name="abc_action_bar_up_description">"အပေါ်သို့သွားရန်"</string>
<string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"ပိုမိုရွေးချယ်စရာများ"</string>
<string msgid="4076576682505996667" name="abc_action_mode_done">"ပြီးဆုံးပါပြီ"</string>
<string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"အားလုံးကို ကြည့်ရန်"</string>
<string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"အပလီကေးရှင်း တစ်ခုခုကို ရွေးချယ်ပါ"</string>
<string msgid="3691816814315814921" name="abc_searchview_description_clear">"ရှာစရာ အချက်အလက်များ ရှင်းလင်းရန်"</string>
<string msgid="2550479030709304392" name="abc_searchview_description_query">"ရှာစရာ အချက်အလက်နေရာ"</string>
<string msgid="8264924765203268293" name="abc_searchview_description_search">"ရှာဖွေရန်"</string>
<string msgid="8928215447528550784" name="abc_searchview_description_submit">"ရှာဖွေစရာ အချက်အလက်ကို အတည်ပြုရန်"</string>
<string msgid="893419373245838918" name="abc_searchview_description_voice">"အသံဖြင့် ရှာဖွေခြင်း"</string>
<string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"မျှဝေဖို့ ရွေးပါ"</string>
<string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"%s ကို မျှဝေပါရန်"</string>
</resources> | {
"pile_set_name": "Github"
} |
---
date_added: 2020-08-13
title: MOES MS-101
category: unsupported
type: Switch
link: https://www.aliexpress.com/item/33000281995.html
image: /assets/images/moes-MS-101.jpg
link2:
link3:
flash: BEKEN BK7231QN40
---
Beken/HLK-B30 WA2, same as Moes MS-104 | {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title> Scala Puzzlers </title>
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon" />
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/prettify.css" type="text/css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/prettify.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31486114-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body data-spy="scroll" data-target=".subnav" data-offset="50">
<!-- Navbar
================================================== -->
<div class="navbar navbar-fixed-top">
<a target="_blank" href="https://github.com/scalapuzzlers/scalapuzzlers.github.com">
<img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub">
</a>
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="/">Scala ?uzz<img src="img/l.png" alt="l" style="padding-bottom:10px;padding-left:2px;padding-right:2px"/>ers</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li>
<a id="navbar-home" href="index.html">Home</a>
</li>
<li>
<a id="navbar-archive" href="archive.html">Archive</a>
</li>
<li>
<a id="navbar-contribute" href="contribute.html">How to Contribute</a>
</li>
<li>
<a id="navbar-contact" href="contact.html">Contact</a>
</li>
<li>
<a id="navbar-about" href="about.html">About</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<script type="text/javascript">
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
var pathToID = {
"/" : '#navbar-home',
"index.html" : '#navbar-home',
"archive.html" : '#navbar-archive',
"contribute.html" : '#navbar-contribute',
"contact.html" : '#navbar-contact',
"about.html" : '#navbar-about'
};
$(document).ready(function() {
function mapPathToID(path) {
var key;
var id = null;
for (key in pathToID) {
if (path === key) {
id = pathToID[key];
break;
}
}
return id;
};
var id = mapPathToID(window.location.pathname);
if (id != null) {
$(id).addClass("active");
}
});
</script>
<div class="container-fluid">
<div class="row-fluid">
<div class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">Puzzlers</li>
<li><a href="/#pzzlr-001" id="pzzlr-001">Hi There!</a></li>
<li><a href="/#pzzlr-003" id="pzzlr-003">UPSTAIRS downstairs</a></li>
<li><a href="/#pzzlr-004" id="pzzlr-004">Location, Location, Location</a></li>
<li><a href="/#pzzlr-005" id="pzzlr-005">Now You See Me, Now You Don't</a></li>
<li><a href="/#pzzlr-006" id="pzzlr-006">The Missing List</a></li>
<li><a href="/#pzzlr-007" id="pzzlr-007">Arg Arrgh!</a></li>
<li><a href="/#pzzlr-008" id="pzzlr-008">Captured by Closures</a></li>
<li><a href="/#pzzlr-009" id="pzzlr-009">Map Comprehension</a></li>
<li><a href="/#pzzlr-010" id="pzzlr-010">Init You, Init Me</a></li>
<li><a href="/#pzzlr-011" id="pzzlr-011">A Case of Equality</a></li>
<li><a href="/#pzzlr-012" id="pzzlr-012">If At First You Don't Succeed...</a></li>
<li><a href="/#pzzlr-013" id="pzzlr-013">To Map, or Not to Map</a></li>
<li><a href="/#pzzlr-015" id="pzzlr-015">Private Lives</a></li>
<li><a href="/#pzzlr-016" id="pzzlr-016">Self: See 'Self'</a></li>
<li><a href="/#pzzlr-017" id="pzzlr-017">One Egg or Two..?</a></li>
<li><a href="/#pzzlr-018" id="pzzlr-018">Return to Me!</a></li>
<li><a href="/#pzzlr-019" id="pzzlr-019">Implicitly Surprising</a></li>
<li><a href="/#pzzlr-020" id="pzzlr-020">One Bound, Two to Go</a></li>
<li><a href="/#pzzlr-021" id="pzzlr-021">Views From the Top</a></li>
<li><a href="/#pzzlr-022" id="pzzlr-022">Count Me Now, Count Me Later</a></li>
<li><a href="/#pzzlr-023" id="pzzlr-023">Information Overload</a></li>
<li><a href="/#pzzlr-024" id="pzzlr-024">What's in a Name?</a></li>
<!-- 26 'reserved' for Scalaz - suggestion by A.P. Marki -->
<li><a href="/#pzzlr-027" id="pzzlr-027">I Can Has Padding?</a></li>
<li><a href="/#pzzlr-028" id="pzzlr-028">Cast Away</a></li>
<li><a href="/#pzzlr-029" id="pzzlr-029">Pick an Int, Any Int!</a></li>
<li><a href="/#pzzlr-030" id="pzzlr-030">Double Trouble</a></li>
<li><a href="/#pzzlr-032" id="pzzlr-032">Type Extortion</a></li>
<li><a href="/#pzzlr-033" id="pzzlr-033">Implicit Kryptonite</a></li>
<li><a href="/#pzzlr-034" id="pzzlr-034">All's Well That Folds Well</a></li>
<li><a href="/#pzzlr-035" id="pzzlr-035">A Case of Strings</a></li>
<li><a href="/#pzzlr-036" id="pzzlr-036">Adaptive Reasoning</a></li>
<li><a href="/#pzzlr-037" id="pzzlr-037">A View to a Shill</a></li>
<li><a href="/#pzzlr-039" id="pzzlr-039">Accepts Any Args</a></li>
<li><a href="/#pzzlr-040" id="pzzlr-040">Set the Record Straight</a></li>
<li><a href="/#pzzlr-041" id="pzzlr-041">Signs of Trouble</a></li>
<li><a href="/#pzzlr-042" id="pzzlr-042">The Devil Is in the Defaults</a></li>
<li><a href="/#pzzlr-043" id="pzzlr-043">Market Precedence</a></li>
<li><a href="/#pzzlr-044" id="pzzlr-044">Float or Sink?</a></li>
<li><a href="/#pzzlr-045" id="pzzlr-045">Stringy Conversions</a></li>
<li><a href="/#pzzlr-046" id="pzzlr-046">Size It Up</a></li>
<li><a href="/#pzzlr-047" id="pzzlr-047">A Listful of Dollars</a></li>
<li><a href="/#pzzlr-048" id="pzzlr-048">One, Two, Skip a Few</a></li>
<li><a href="/#pzzlr-049" id="pzzlr-049">Oddly Enough</a></li>
<li><a href="/#pzzlr-050" id="pzzlr-050">Extract or Fail?</a></li>
<li><a href="/#pzzlr-051" id="pzzlr-051">Well, In This Case...</a></li>
<li><a href="/#pzzlr-052" id="pzzlr-052">Partial Oddity</a></li>
<li><a href="/#pzzlr-053" id="pzzlr-053">Trial and Error</a></li>
<li><a href="/#pzzlr-054" id="pzzlr-054">Think of 1 Card</a></li>
<li><a href="/#pzzlr-055" id="pzzlr-055">Splitting Headache</a></li>
<li><a href="/#pzzlr-056" id="pzzlr-056">An Exceptional Future</a></li>
<li><a href="/#pzzlr-057" id="pzzlr-057">Applied Values</a></li>
<li><a href="/#pzzlr-058" id="pzzlr-058">The Branch Not Taken</a></li>
<li><a href="/#pzzlr-059" id="pzzlr-059">A Result, Finally!</a></li>
<li><a href="/#pzzlr-060" id="pzzlr-060">Unary Quandary</a></li>
<li><a href="/#pzzlr-061" id="pzzlr-061">Heads You Win...</a></li>
<li><a href="/#pzzlr-062" id="pzzlr-062">Identity Crisis</a></li>
<li><a href="/#pzzlr-063" id="pzzlr-063">(Ex)Stream Surprise</a></li>
<li><a href="/#pzzlr-064" id="pzzlr-064">Traversing Travesty</a></li>
<li><a href="/#pzzlr-065" id="pzzlr-065">A Matter of Context</a></li>
<li><a href="/#pzzlr-066" id="pzzlr-066">Inference Hindrance</a></li>
<li><a href="/#pzzlr-067" id="pzzlr-067">Inconstant Constants</a></li>
<li><a href="/#pzzlr-068" id="pzzlr-068">For Each Step...</a></li>
<li><a href="/#pzzlr-069" id="pzzlr-069">Beep Beep...Reversing</a></li>
<li><a href="/#pzzlr-070" id="pzzlr-070">Reductio Ad Absurdum</a></li>
<li><a href="/#pzzlr-071" id="pzzlr-071">Repeat After Me</a></li>
<li class="divider"></li>
</ul>
</div><!--/.well -->
</div><!--/span-->
<div id="prime-space" class="span9">
<div class="headline-unit">
<h2>How to contribute</h2>
<p>
<strong>1.</strong> Fork our <a target="_blank" href="https://github.com/scalapuzzlers/scalapuzzlers.github.com">github repo</a>.<br/><br/>
<strong>2.</strong> In <code>puzzlers</code> directory, you will find a file called <code>pzzlr-template.html</code>. Make a copy of it,
following the naming convention: <code>pzzlr-???.html</code>. The three digit puzzler number should be the next increment of the latest puzzler in the repository. You might need to check the open <a target="_blank" href="https://github.com/scalapuzzlers/scalapuzzlers.github.com/pulls">pull requests</a> to ensure the number is not already taken.<br/><br/>
<strong>3.</strong> In your newly created puzzler HTML file replace every occurence of the word <em>PLACEHOLDER</em> with your own content. This should require only a minimum knowledge of HTML. Try to keep it simple, but feel free to get creative if your puzzler warrants some more sophisticated presentation. If unsure, please use other puzzler HTML files as a reference.<br/><br/>
<strong>4.</strong> Commit and push your puzzler HTML file (not the template) to github. Then issue a pull request. That's it!
</p>
</div>
<footer class="footer">
Copyright © 2013, Andrew Phillips and Nermin Serifovic
</footer>
</div>
</div>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
def GetCurveType(item):
if hasattr(item, "CurveElementType"): return item.CurveElementType
else: return None
items = UnwrapElement(IN[0])
if isinstance(IN[0], list): OUT = [GetCurveType(x) for x in items]
else: OUT = GetCurveType(items) | {
"pile_set_name": "Github"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Draggable Demos</title>
</head>
<body>
<ul>
<li><a href="default.html">Default functionality</a></li>
<li><a href="events.html">Events</a></li>
<li><a href="constrain-movement.html">Constrain movement</a></li>
<li><a href="delay-start.html">Delay start</a></li>
<li><a href="snap-to.html">Snap to element or grid</a></li>
<li><a href="scroll.html">Auto-scroll</a></li>
<li><a href="revert.html">Revert position</a></li>
<li><a href="visual-feedback.html">Visual feedback</a></li>
<li><a href="handle.html">Drag handle</a></li>
<li><a href="cursor-style.html">Cursor style</a></li>
<li><a href="sortable.html">Draggable + Sortable</a></li>
</ul>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Copyright (c) 2001-2011 Hartmut Kaiser
Copyright (c) 2011 Bryce Lelbach
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_UTREE_DETAIL1)
#define BOOST_SPIRIT_UTREE_DETAIL1
#include <boost/type_traits/alignment_of.hpp>
namespace boost { namespace spirit { namespace detail
{
template <typename UTreeX, typename UTreeY>
struct visit_impl;
struct index_impl;
///////////////////////////////////////////////////////////////////////////
// Our POD double linked list. Straightforward implementation.
// This implementation is very primitive and is not meant to be
// used stand-alone. This is the internal data representation
// of lists in our utree.
///////////////////////////////////////////////////////////////////////////
struct list // keep this a POD!
{
struct node;
template <typename Value>
class node_iterator;
void free();
void copy(list const& other);
void default_construct();
template <typename T, typename Iterator>
void insert(T const& val, Iterator pos);
template <typename T>
void push_front(T const& val);
template <typename T>
void push_back(T const& val);
void pop_front();
void pop_back();
node* erase(node* pos);
node* first;
node* last;
std::size_t size;
};
///////////////////////////////////////////////////////////////////////////
// A range of utree(s) using an iterator range (begin/end) of node(s)
///////////////////////////////////////////////////////////////////////////
struct range
{
list::node* first;
list::node* last;
};
///////////////////////////////////////////////////////////////////////////
// A range of char*s
///////////////////////////////////////////////////////////////////////////
struct string_range
{
char const* first;
char const* last;
};
///////////////////////////////////////////////////////////////////////////
// A void* plus type_info
///////////////////////////////////////////////////////////////////////////
struct void_ptr
{
void* p;
std::type_info const* i;
};
///////////////////////////////////////////////////////////////////////////
// Our POD fast string. This implementation is very primitive and is not
// meant to be used stand-alone. This is the internal data representation
// of strings in our utree. This is deliberately a POD to allow it to be
// placed in a union. This POD fast string specifically utilizes
// (sizeof(list) * alignment_of(list)) - (2 * sizeof(char)). In a 32 bit
// system, this is 14 bytes. The two extra bytes are used by utree to store
// management info.
//
// It is a const string (i.e. immutable). It stores the characters directly
// if possible and only uses the heap if the string does not fit. Null
// characters are allowed, making it suitable to encode raw binary. The
// string length is encoded in the first byte if the string is placed in-situ,
// else, the length plus a pointer to the string in the heap are stored.
///////////////////////////////////////////////////////////////////////////
struct fast_string // Keep this a POD!
{
static std::size_t const
buff_size = (sizeof(list) + boost::alignment_of<list>::value)
/ sizeof(char);
static std::size_t const
small_string_size = buff_size-sizeof(char);
static std::size_t const
max_string_len = small_string_size - 3;
struct heap_store
{
char* str;
std::size_t size;
};
union
{
char buff[buff_size];
long lbuff[buff_size / (sizeof(long)/sizeof(char))]; // for initialize
heap_store heap;
};
int get_type() const;
void set_type(int t);
bool is_heap_allocated() const;
std::size_t size() const;
char const* str() const;
template <typename Iterator>
void construct(Iterator f, Iterator l);
void swap(fast_string& other);
void free();
void copy(fast_string const& other);
void initialize();
char& info();
char info() const;
short tag() const;
void tag(short tag);
};
}}}
#endif
| {
"pile_set_name": "Github"
} |
// ignore_for_file: non_constant_identifier_names, camel_case_types, missing_return, unused_import, unused_local_variable, dead_code, unnecessary_cast
//////////////////////////////////////////////////////////
// GENERATED BY FLUTTIFY. DO NOT EDIT IT.
//////////////////////////////////////////////////////////
import 'dart:typed_data';
import 'package:amap_map_fluttify/src/android/android.export.g.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:foundation_fluttify/foundation_fluttify.dart';
import 'package:core_location_fluttify/core_location_fluttify.dart';
mixin com_amap_api_maps_LocationSource on java_lang_Object {
@mustCallSuper
Future<void> activate(com_amap_api_maps_LocationSource_OnLocationChangedListener var1) {}
@mustCallSuper
Future<void> deactivate() {}
}
| {
"pile_set_name": "Github"
} |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2017 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// 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.
package proto
import (
"fmt"
"reflect"
"strings"
"sync"
"sync/atomic"
)
type generatedDiscarder interface {
XXX_DiscardUnknown()
}
// DiscardUnknown recursively discards all unknown fields from this message
// and all embedded messages.
//
// When unmarshaling a message with unrecognized fields, the tags and values
// of such fields are preserved in the Message. This allows a later call to
// marshal to be able to produce a message that continues to have those
// unrecognized fields. To avoid this, DiscardUnknown is used to
// explicitly clear the unknown fields after unmarshaling.
//
// For proto2 messages, the unknown fields of message extensions are only
// discarded from messages that have been accessed via GetExtension.
func DiscardUnknown(m Message) {
if m, ok := m.(generatedDiscarder); ok {
m.XXX_DiscardUnknown()
return
}
// TODO: Dynamically populate a InternalMessageInfo for legacy messages,
// but the master branch has no implementation for InternalMessageInfo,
// so it would be more work to replicate that approach.
discardLegacy(m)
}
// DiscardUnknown recursively discards all unknown fields.
func (a *InternalMessageInfo) DiscardUnknown(m Message) {
di := atomicLoadDiscardInfo(&a.discard)
if di == nil {
di = getDiscardInfo(reflect.TypeOf(m).Elem())
atomicStoreDiscardInfo(&a.discard, di)
}
di.discard(toPointer(&m))
}
type discardInfo struct {
typ reflect.Type
initialized int32 // 0: only typ is valid, 1: everything is valid
lock sync.Mutex
fields []discardFieldInfo
unrecognized field
}
type discardFieldInfo struct {
field field // Offset of field, guaranteed to be valid
discard func(src pointer)
}
var (
discardInfoMap = map[reflect.Type]*discardInfo{}
discardInfoLock sync.Mutex
)
func getDiscardInfo(t reflect.Type) *discardInfo {
discardInfoLock.Lock()
defer discardInfoLock.Unlock()
di := discardInfoMap[t]
if di == nil {
di = &discardInfo{typ: t}
discardInfoMap[t] = di
}
return di
}
func (di *discardInfo) discard(src pointer) {
if src.isNil() {
return // Nothing to do.
}
if atomic.LoadInt32(&di.initialized) == 0 {
di.computeDiscardInfo()
}
for _, fi := range di.fields {
sfp := src.offset(fi.field)
fi.discard(sfp)
}
// For proto2 messages, only discard unknown fields in message extensions
// that have been accessed via GetExtension.
if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {
// Ignore lock since DiscardUnknown is not concurrency safe.
emm, _ := em.extensionsRead()
for _, mx := range emm {
if m, ok := mx.value.(Message); ok {
DiscardUnknown(m)
}
}
}
if di.unrecognized.IsValid() {
*src.offset(di.unrecognized).toBytes() = nil
}
}
func (di *discardInfo) computeDiscardInfo() {
di.lock.Lock()
defer di.lock.Unlock()
if di.initialized != 0 {
return
}
t := di.typ
n := t.NumField()
for i := 0; i < n; i++ {
f := t.Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
dfi := discardFieldInfo{field: toField(&f)}
tf := f.Type
// Unwrap tf to get its most basic type.
var isPointer, isSlice bool
if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
isSlice = true
tf = tf.Elem()
}
if tf.Kind() == reflect.Ptr {
isPointer = true
tf = tf.Elem()
}
if isPointer && isSlice && tf.Kind() != reflect.Struct {
panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))
}
switch tf.Kind() {
case reflect.Struct:
switch {
case !isPointer:
panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))
case isSlice: // E.g., []*pb.T
di := getDiscardInfo(tf)
dfi.discard = func(src pointer) {
sps := src.getPointerSlice()
for _, sp := range sps {
if !sp.isNil() {
di.discard(sp)
}
}
}
default: // E.g., *pb.T
di := getDiscardInfo(tf)
dfi.discard = func(src pointer) {
sp := src.getPointer()
if !sp.isNil() {
di.discard(sp)
}
}
}
case reflect.Map:
switch {
case isPointer || isSlice:
panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))
default: // E.g., map[K]V
if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)
dfi.discard = func(src pointer) {
sm := src.asPointerTo(tf).Elem()
if sm.Len() == 0 {
return
}
for _, key := range sm.MapKeys() {
val := sm.MapIndex(key)
DiscardUnknown(val.Interface().(Message))
}
}
} else {
dfi.discard = func(pointer) {} // Noop
}
}
case reflect.Interface:
// Must be oneof field.
switch {
case isPointer || isSlice:
panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))
default: // E.g., interface{}
// TODO: Make this faster?
dfi.discard = func(src pointer) {
su := src.asPointerTo(tf).Elem()
if !su.IsNil() {
sv := su.Elem().Elem().Field(0)
if sv.Kind() == reflect.Ptr && sv.IsNil() {
return
}
switch sv.Type().Kind() {
case reflect.Ptr: // Proto struct (e.g., *T)
DiscardUnknown(sv.Interface().(Message))
}
}
}
}
default:
continue
}
di.fields = append(di.fields, dfi)
}
di.unrecognized = invalidField
if f, ok := t.FieldByName("XXX_unrecognized"); ok {
if f.Type != reflect.TypeOf([]byte{}) {
panic("expected XXX_unrecognized to be of type []byte")
}
di.unrecognized = toField(&f)
}
atomic.StoreInt32(&di.initialized, 1)
}
func discardLegacy(m Message) {
v := reflect.ValueOf(m)
if v.Kind() != reflect.Ptr || v.IsNil() {
return
}
v = v.Elem()
if v.Kind() != reflect.Struct {
return
}
t := v.Type()
for i := 0; i < v.NumField(); i++ {
f := t.Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
vf := v.Field(i)
tf := f.Type
// Unwrap tf to get its most basic type.
var isPointer, isSlice bool
if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
isSlice = true
tf = tf.Elem()
}
if tf.Kind() == reflect.Ptr {
isPointer = true
tf = tf.Elem()
}
if isPointer && isSlice && tf.Kind() != reflect.Struct {
panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
}
switch tf.Kind() {
case reflect.Struct:
switch {
case !isPointer:
panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
case isSlice: // E.g., []*pb.T
for j := 0; j < vf.Len(); j++ {
discardLegacy(vf.Index(j).Interface().(Message))
}
default: // E.g., *pb.T
discardLegacy(vf.Interface().(Message))
}
case reflect.Map:
switch {
case isPointer || isSlice:
panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
default: // E.g., map[K]V
tv := vf.Type().Elem()
if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
for _, key := range vf.MapKeys() {
val := vf.MapIndex(key)
discardLegacy(val.Interface().(Message))
}
}
}
case reflect.Interface:
// Must be oneof field.
switch {
case isPointer || isSlice:
panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
default: // E.g., test_proto.isCommunique_Union interface
if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
vf = vf.Elem() // E.g., *test_proto.Communique_Msg
if !vf.IsNil() {
vf = vf.Elem() // E.g., test_proto.Communique_Msg
vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
if vf.Kind() == reflect.Ptr {
discardLegacy(vf.Interface().(Message))
}
}
}
}
}
}
if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
if vf.Type() != reflect.TypeOf([]byte{}) {
panic("expected XXX_unrecognized to be of type []byte")
}
vf.Set(reflect.ValueOf([]byte(nil)))
}
// For proto2 messages, only discard unknown fields in message extensions
// that have been accessed via GetExtension.
if em, err := extendable(m); err == nil {
// Ignore lock since discardLegacy is not concurrency safe.
emm, _ := em.extensionsRead()
for _, mx := range emm {
if m, ok := mx.value.(Message); ok {
discardLegacy(m)
}
}
}
}
| {
"pile_set_name": "Github"
} |
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
/////////////////////////////////////////////////////////////////////////////////
// Module: G4IonInverseIonisation
// Author: L. Desorgher
// Organisation: SpaceIT GmbH
// Contract: ESA contract 21435/08/NL/AT
// Customer: ESA/ESTEC
/////////////////////////////////////////////////////////////////////////////////
//
// CHANGE HISTORY
// --------------
// ChangeHistory:
// 25 August 2009 creation by L. Desorgher
//
//-------------------------------------------------------------
// Documentation:
// Adjoint/reverse discrete ionisation for ions
//
#ifndef G4IonInverseIonisation_h
#define G4IonInverseIonisation_h 1
#include "G4VAdjointReverseReaction.hh"
#include "globals.hh"
#include "G4eIonisation.hh"
#include "G4AdjointIonIonisationModel.hh"
class G4IonInverseIonisation: public G4VAdjointReverseReaction
{
public:
G4IonInverseIonisation(G4bool whichScatCase, G4String process_name, G4AdjointIonIonisationModel* aEmAdjointModel);
~G4IonInverseIonisation();
private:
};
#endif
| {
"pile_set_name": "Github"
} |
---
title: Časové jednotky
actions: ['checkAnswer', 'hints']
requireLogin: true
material:
editor:
language: sol
startingCode:
"zombiefactory.sol": |
pragma solidity ^0.4.19;
import "./ownable.sol";
contract ZombieFactory is Ownable {
event NewZombie(uint zombieId, string name, uint dna);
uint dnaDigits = 16;
uint dnaModulus = 10 ** dnaDigits;
// 1. Tu definuj `cooldownTime`
struct Zombie {
string name;
uint dna;
uint32 level;
uint32 readyTime;
}
Zombie[] public zombies;
mapping (uint => address) public zombieToOwner;
mapping (address => uint) ownerZombieCount;
function _createZombie(string _name, uint _dna) internal {
// 2. Uprav nasledujúci riadok
uint id = zombies.push(Zombie(_name, _dna)) - 1;
zombieToOwner[id] = msg.sender;
ownerZombieCount[msg.sender]++;
NewZombie(id, _name, _dna);
}
function _generateRandomDna(string _str) private view returns (uint) {
uint rand = uint(keccak256(_str));
return rand % dnaModulus;
}
function createRandomZombie(string _name) public {
require(ownerZombieCount[msg.sender] == 0);
uint randDna = _generateRandomDna(_name);
randDna = randDna - randDna % 100;
_createZombie(_name, randDna);
}
}
"zombiefeeding.sol": |
pragma solidity ^0.4.19;
import "./zombiefactory.sol";
contract KittyInterface {
function getKitty(uint256 _id) external view returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
);
}
contract ZombieFeeding is ZombieFactory {
KittyInterface kittyContract;
function setKittyContractAddress(address _address) external onlyOwner {
kittyContract = KittyInterface(_address);
}
function feedAndMultiply(uint _zombieId, uint _targetDna, string _species) public {
require(msg.sender == zombieToOwner[_zombieId]);
Zombie storage myZombie = zombies[_zombieId];
_targetDna = _targetDna % dnaModulus;
uint newDna = (myZombie.dna + _targetDna) / 2;
if (keccak256(_species) == keccak256("kitty")) {
newDna = newDna - newDna % 100 + 99;
}
_createZombie("NoName", newDna);
}
function feedOnKitty(uint _zombieId, uint _kittyId) public {
uint kittyDna;
(,,,,,,,,,kittyDna) = kittyContract.getKitty(_kittyId);
feedAndMultiply(_zombieId, kittyDna, "kitty");
}
}
"ownable.sol": |
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
answer: >
pragma solidity ^0.4.19;
import "./ownable.sol";
contract ZombieFactory is Ownable {
event NewZombie(uint zombieId, string name, uint dna);
uint dnaDigits = 16;
uint dnaModulus = 10 ** dnaDigits;
uint cooldownTime = 1 days;
struct Zombie {
string name;
uint dna;
uint32 level;
uint32 readyTime;
}
Zombie[] public zombies;
mapping (uint => address) public zombieToOwner;
mapping (address => uint) ownerZombieCount;
function _createZombie(string _name, uint _dna) internal {
uint id = zombies.push(Zombie(_name, _dna, 1, uint32(now + cooldownTime))) - 1;
zombieToOwner[id] = msg.sender;
ownerZombieCount[msg.sender]++;
NewZombie(id, _name, _dna);
}
function _generateRandomDna(string _str) private view returns (uint) {
uint rand = uint(keccak256(_str));
return rand % dnaModulus;
}
function createRandomZombie(string _name) public {
require(ownerZombieCount[msg.sender] == 0);
uint randDna = _generateRandomDna(_name);
randDna = randDna - randDna % 100;
_createZombie(_name, randDna);
}
}
---
Atribút `level` by mal byť celkom jasný. Až neskôr vyvinieme systém útočenia a zápasov, víťazní zombie ktorí vyhrajú viac bytiek navýšia svoj level, a získajú prístup k novým schopnostiam.
Atribút `readyTime` si vysvetlíme podrobnejšie. Jeho cieľom je pridať "obdobie chladnutia". To bude predstavovať čas kedy musí zombie čakať, než mu bude znova dovolené útočiť po predchádzajúcom útoku. Bez tejto vlasnosti by zombie mohli útočiť a násobiť sa tisícky krát za deň. To by spravilo hru príliš ľahkú.
Na to aby sme si držali prehľad o tom, koľko času musí zombie čakať než bude môcť znova zaútočiť použijeme časové jednotky Solidity.
## Časové jednotky
Solidty nám pre prácu s časom natívne poskytuje isté časové jednotky.
Globálna premenná `now` vracia vždy aktuálnu unixovú časovú známku (počet sekúnd ktoré uplynuli od 1vého Januára 1970). V momente písania tohoto textu je aktuálny čas v týchto jednotkách `1515527488`.
>Poznámka: Unixový čas je typicky uložený v 32 bitovom čísle. To bude viesť k "Problému roku 2038". Vtedy totiž 32-bitové unixové časové známky pretečú a rozbijú mnoho zastaralých systémov. Ak by sme teda chceli, aby naša aplikáciu fungovala aj po roku 2038, museli by sme použit 64-bitové číslo. Na oplátku by ale naši používatelia našej DAppky by však museli utratiť viac gasu. Je to designové rozhodnutie.
Solidity taktiež obsahuje spomínané časové jednotky `seconds`, `minutes`, `hours`, `days`, `weeks` a `years`. Tieto skonvertujú časový interval do počtu sekúnd v ňom. Napríklad: `1 minutes` je `60`, `1 hours` je `3600` (60 sekúnd x 60 minút), `1 days` je `86400` (24 hodín x 60 minút x 60 sekúnd), atď.
Tu je príklad, ako môžu byť takéto časové jednotky užitočné:
```
uint lastUpdated;
// Nastav `lastUpdated` na `now`
function updateTimestamp() public {
lastUpdated = now;
}
// Vráti `true` v prípade že od času zavolania funkcie `updateTimestamp`
// uplynulo aspoň 5 minút, inak vráti `false`
function fiveMinutesHavePassed() public view returns (bool) {
return (now >= (lastUpdated + 5 minutes));
}
```
Tieto jednotky môžeme podobným spôsobom použiť pre `cooldown` vychladzovacie obdobie našich zombie.
## Vyskúšaj si to sám
Poďme teraz pridať vychladzovacie obdobie do našej DApp. Nastavíme to tak, aby zombie museli čakať **1 deň** po útočení alebo kŕmení, než im bude dovolené útočiť znova.
1. Deklaruj `uint` nazvaný `cooldownTime` a nastav jeho hodnotu na `1 days` (odpusť nedokonalú anglickú gramatiku - ak sa pokúsiš nastaviť hodnotu na "1 day", kontrakt sa neskompiluje!)
2. Nakoľko sme pridali `level` a `readyTime` do našej `Zombie` štruktúry v predchádzajúcej kapitole, budeme musieť aktualizovať `_createZombie()`, aby používal správny počet argumentov pri vytváraní novej `Zombie` štruktúry.
Aktualizuj riadok kódu s `zombies.push` a pridaj 2 nové argumenty: `1` (pre `level`), a `uint32(now + cooldownTime)` (pre `readyTime`).
>Poznámka: `uint32(...)` je nevyhnutnosť, pretože `now` vracia `uint256`, preto ho musíme explicitne pretypovať na `uint32`.
`now + cooldownTime` sa budú rovnať aktuálnej unixovej časovej známke (v sekundách) plus počet sekúnd v jednom dni. To nám dá unixovú časovú známku s hodnotou referujúcou čas presne 1 deň od aktuálneho momentu. Neskôr môžeme porovnávať, či hodnota `readyTime` je vačšia ako `now`, aby sme zistili či uplynulo dostatok času, a či zombie môže opäť bojovať.
V ďalšej kapitole implementujeme funkcionalitu ktorá pomocou `readyTime` obmedzí bojovanie a kŕmenie zombie.
| {
"pile_set_name": "Github"
} |
## Changelog
##### 1.2.7 [LEGACY] - 2016.07.18
* some fixes for issues like #159, #186, #194, #207
##### 1.2.6 - 2015.11.09
* reject with `TypeError` on attempt resolve promise itself
* correct behavior with broken `Promise` subclass constructors / methods
* added `Promise`-based fallback for microtask
* fixed V8 and FF `Array#{values, @@iterator}.name`
* fixed IE7- `[1, 2].join(undefined) -> '1,2'`
* some other fixes / improvements / optimizations
##### 1.2.5 - 2015.11.02
* some more `Number` constructor fixes:
* fixed V8 ~ Node 0.8 bug: `Number('+0x1')` should be `NaN`
* fixed `Number(' 0b1\n')` case, should be `1`
* fixed `Number()` case, should be `0`
##### 1.2.4 - 2015.11.01
* fixed `Number('0b12') -> NaN` case in the shim
* fixed V8 ~ Chromium 40- bug - `Weak(Map|Set)#{delete, get, has}` should not throw errors [#124](https://github.com/zloirock/core-js/issues/124)
* some other fixes and optimizations
##### 1.2.3 - 2015.10.23
* fixed some problems related old V8 bug `Object('a').propertyIsEnumerable(0) // => false`, for example, `Object.assign({}, 'qwe')` from the last release
* fixed `.name` property and `Function#toString` conversion some polyfilled methods
* fixed `Math.imul` arity in Safari 8-
##### 1.2.2 - 2015.10.18
* improved optimisations for V8
* fixed build process from external packages, [#120](https://github.com/zloirock/core-js/pull/120)
* one more `Object.{assign, values, entries}` fix for [**very** specific case](https://github.com/ljharb/proposal-object-values-entries/issues/5)
##### 1.2.1 - 2015.10.02
* replaced fix `JSON.stringify` + `Symbol` behavior from `.toJSON` method to wrapping `JSON.stringify` - little more correct, [compat-table/642](https://github.com/kangax/compat-table/pull/642)
* fixed typo which broke tasks scheduler in WebWorkers in old FF, [#114](https://github.com/zloirock/core-js/pull/114)
##### 1.2.0 - 2015.09.27
* added browser [`Promise` rejection hook](#unhandled-rejection-tracking), [#106](https://github.com/zloirock/core-js/issues/106)
* added correct [`IsRegExp`](http://www.ecma-international.org/ecma-262/6.0/#sec-isregexp) logic to [`String#{includes, startsWith, endsWith}`](https://github.com/zloirock/core-js/#ecmascript-6-string) and [`RegExp` constructor](https://github.com/zloirock/core-js/#ecmascript-6-regexp), `@@match` case, [example](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/match#Disabling_the_isRegExp_check)
* updated [`String#leftPad`](https://github.com/zloirock/core-js/#ecmascript-7) [with proposal](https://github.com/ljharb/proposal-string-pad-left-right/issues/6): string filler truncated from the right side
* replaced V8 [`Object.assign`](https://github.com/zloirock/core-js/#ecmascript-6-object) - its properties order not only [incorrect](https://github.com/sindresorhus/object-assign/issues/22), it is non-deterministic and it causes some problems
* fixed behavior with deleted in getters properties for `Object.{`[`assign`](https://github.com/zloirock/core-js/#ecmascript-6-object)`, `[`entries, values`](https://github.com/zloirock/core-js/#ecmascript-7)`}`, [example](http://goo.gl/iQE01c)
* fixed [`Math.sinh`](https://github.com/zloirock/core-js/#ecmascript-6-math) with very small numbers in V8 near Chromium 38
* some other fixes and optimizations
##### 1.1.4 - 2015.09.05
* fixed support symbols in FF34-35 [`Object.assign`](https://github.com/zloirock/core-js/#ecmascript-6-object)
* fixed [collections iterators](https://github.com/zloirock/core-js/#ecmascript-6-iterators) in FF25-26
* fixed non-generic WebKit [`Array.of`](https://github.com/zloirock/core-js/#ecmascript-6-array)
* some other fixes and optimizations
##### 1.1.3 - 2015.08.29
* fixed support Node.js domains in [`Promise`](https://github.com/zloirock/core-js/#ecmascript-6-promise), [#103](https://github.com/zloirock/core-js/issues/103)
##### 1.1.2 - 2015.08.28
* added `toJSON` method to [`Symbol`](https://github.com/zloirock/core-js/#ecmascript-6-symbol) polyfill and to MS Edge implementation for expected `JSON.stringify` result w/o patching this method
* replaced [`Reflect.construct`](https://github.com/zloirock/core-js/#ecmascript-6-reflect) implementations w/o correct support third argument
* fixed `global` detection with changed `document.domain` in ~IE8, [#100](https://github.com/zloirock/core-js/issues/100)
##### 1.1.1 - 2015.08.20
* added more correct microtask implementation for [`Promise`](#ecmascript-6-promise)
##### 1.1.0 - 2015.08.17
* updated [string padding](https://github.com/zloirock/core-js/#ecmascript-7) to [actual proposal](https://github.com/ljharb/proposal-string-pad-left-right) - renamed, minor internal changes:
* `String#lpad` -> `String#padLeft`
* `String#rpad` -> `String#padRight`
* added [string trim functions](#ecmascript-7) - [proposal](https://github.com/sebmarkbage/ecmascript-string-left-right-trim), defacto standard - required only for IE11- and fixed for some old engines:
* `String#trimLeft`
* `String#trimRight`
* [`String#trim`](https://github.com/zloirock/core-js/#ecmascript-6-string) fixed for some engines by es6 spec and moved from `es5` to single `es6` module
* splitted [`es6.object.statics-accept-primitives`](https://github.com/zloirock/core-js/#ecmascript-6-object)
* caps for `freeze`-family `Object` methods moved from `es5` to `es6` namespace and joined with [es6 wrappers](https://github.com/zloirock/core-js/#ecmascript-6-object)
* `es5` [namespace](https://github.com/zloirock/core-js/#commonjs) also includes modules, moved to `es6` namespace - you can use it as before
* increased `MessageChannel` priority in `$.task`, [#95](https://github.com/zloirock/core-js/issues/95)
* does not get `global.Symbol` on each getting iterator, if you wanna use alternative `Symbol` shim - add it before `core-js`
* [`Reflect.construct`](https://github.com/zloirock/core-js/#ecmascript-6-reflect) optimized and fixed for some cases
* simplified [`Reflect.enumerate`](https://github.com/zloirock/core-js/#ecmascript-6-reflect), see [this question](https://esdiscuss.org/topic/question-about-enumerate-and-property-decision-timing)
* some corrections in [`Math.acosh`](https://github.com/zloirock/core-js/#ecmascript-6-math)
* fixed [`Math.imul`](https://github.com/zloirock/core-js/#ecmascript-6-math) for old WebKit
* some fixes in string / RegExp [well-known symbols](https://github.com/zloirock/core-js/#ecmascript-6-regexp) logic
* some other fixes and optimizations
##### 1.0.1 - 2015.07.31
* some fixes for final MS Edge, replaced broken native `Reflect.defineProperty`
* some minor fixes and optimizations
* changed compression `client/*.min.js` options for safe `Function#name` and `Function#length`, should be fixed [#92](https://github.com/zloirock/core-js/issues/92)
##### 1.0.0 - 2015.07.22
* added logic for [well-known symbols](https://github.com/zloirock/core-js/#ecmascript-6-regexp):
* `Symbol.match`
* `Symbol.replace`
* `Symbol.split`
* `Symbol.search`
* actualized and optimized work with iterables:
* optimized [`Map`, `Set`, `WeakMap`, `WeakSet` constructors](https://github.com/zloirock/core-js/#ecmascript-6-collections), [`Promise.all`, `Promise.race`](https://github.com/zloirock/core-js/#ecmascript-6-promise) for default `Array Iterator`
* optimized [`Array.from`](https://github.com/zloirock/core-js/#ecmascript-6-array) for default `Array Iterator`
* added [`core.getIteratorMethod`](https://github.com/zloirock/core-js/#ecmascript-6-iterators) helper
* uses enumerable properties in shimmed instances - collections, iterators, etc for optimize performance
* added support native constructors to [`Reflect.construct`](https://github.com/zloirock/core-js/#ecmascript-6-reflect) with 2 arguments
* added support native constructors to [`Function#bind`](https://github.com/zloirock/core-js/#ecmascript-5) shim with `new`
* removed obsolete `.clear` methods native [`Weak`-collections](https://github.com/zloirock/core-js/#ecmascript-6-collections)
* maximum modularity, reduced minimal custom build size, separated into submodules:
* [`es6.reflect`](https://github.com/zloirock/core-js/#ecmascript-6-reflect)
* [`es6.regexp`](https://github.com/zloirock/core-js/#ecmascript-6-regexp)
* [`es6.math`](https://github.com/zloirock/core-js/#ecmascript-6-math)
* [`es6.number`](https://github.com/zloirock/core-js/#ecmascript-6-number)
* [`es7.object.to-array`](https://github.com/zloirock/core-js/#ecmascript-7)
* [`core.object`](https://github.com/zloirock/core-js/#object)
* [`core.string`](https://github.com/zloirock/core-js/#escaping-html)
* [`core.iter-helpers`](https://github.com/zloirock/core-js/#ecmascript-6-iterators)
* internal modules (`$`, `$.iter`, etc)
* many other optimizations
* final cleaning non-standard features
* moved `$for` to [separate library](https://github.com/zloirock/forof). This work for syntax - `for-of` loop and comprehensions
* moved `Date#{format, formatUTC}` to [separate library](https://github.com/zloirock/dtf). Standard way for this - `ECMA-402`
* removed `Math` methods from `Number.prototype`. Slight sugar for simple `Math` methods calling
* removed `{Array#, Array, Dict}.turn`
* removed `core.global`
* uses `ToNumber` instead of `ToLength` in [`Number Iterator`](https://github.com/zloirock/core-js/#number-iterator), `Array.from(2.5)` will be `[0, 1, 2]` instead of `[0, 1]`
* fixed [#85](https://github.com/zloirock/core-js/issues/85) - invalid `Promise` unhandled rejection message in nested `setTimeout`
* fixed [#86](https://github.com/zloirock/core-js/issues/86) - support FF extensions
* fixed [#89](https://github.com/zloirock/core-js/issues/89) - behavior `Number` constructor in strange case
##### 0.9.18 - 2015.06.17
* removed `/` from [`RegExp.escape`](https://github.com/zloirock/core-js/#ecmascript-7) escaped characters
##### 0.9.17 - 2015.06.14
* updated [`RegExp.escape`](https://github.com/zloirock/core-js/#ecmascript-7) to the [latest proposal](https://github.com/benjamingr/RexExp.escape)
* fixed conflict with webpack dev server + IE buggy behavior
##### 0.9.16 - 2015.06.11
* more correct order resolving thenable in [`Promise`](https://github.com/zloirock/core-js/#ecmascript-6-promise) polyfill
* uses polyfill instead of [buggy V8 `Promise`](https://github.com/zloirock/core-js/issues/78)
##### 0.9.15 - 2015.06.09
* [collections](https://github.com/zloirock/core-js/#ecmascript-6-collections) from `library` version return wrapped native instances
* fixed collections prototype methods in `library` version
* optimized [`Math.hypot`](https://github.com/zloirock/core-js/#ecmascript-6-math)
##### 0.9.14 - 2015.06.04
* updated [`Promise.resolve` behavior](https://esdiscuss.org/topic/fixing-promise-resolve)
* added fallback for IE11 buggy `Object.getOwnPropertyNames` + iframe
* some other fixes
##### 0.9.13 - 2015.05.25
* added fallback for [`Symbol` polyfill](https://github.com/zloirock/core-js/#ecmascript-6-symbol) for old Android
* some other fixes
##### 0.9.12 - 2015.05.24
* different instances `core-js` should use / recognize the same symbols
* some fixes
##### 0.9.11 - 2015.05.18
* simplified [custom build](https://github.com/zloirock/core-js/#custom-build)
* add custom build js api
* added `grunt-cli` to `devDependencies` for `npm run grunt`
* some fixes
##### 0.9.10 - 2015.05.16
* wrapped `Function#toString` for correct work wrapped methods / constructors with methods similar to the [`lodash` `isNative`](https://github.com/lodash/lodash/issues/1197)
* added proto versions of methods to export object in `default` version for consistency with `library` version
##### 0.9.9 - 2015.05.14
* wrapped `Object#propertyIsEnumerable` for [`Symbol` polyfill](https://github.com/zloirock/core-js/#ecmascript-6-symbol)
* [added proto versions of methods to `library` for ES7 bind syntax](https://github.com/zloirock/core-js/issues/65)
* some other fixes
##### 0.9.8 - 2015.05.12
* fixed [`Math.hypot`](https://github.com/zloirock/core-js/#ecmascript-6-math) with negative arguments
* added `Object#toString.toString` as fallback for [`lodash` `isNative`](https://github.com/lodash/lodash/issues/1197)
##### 0.9.7 - 2015.05.07
* added [support DOM collections](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice#Streamlining_cross-browser_behavior) to IE8- `Array#slice`
##### 0.9.6 - 2015.05.01
* added [`String#lpad`, `String#rpad`](https://github.com/zloirock/core-js/#ecmascript-7)
##### 0.9.5 - 2015.04.30
* added cap for `Function#@@hasInstance`
* some fixes and optimizations
##### 0.9.4 - 2015.04.27
* fixed `RegExp` constructor
##### 0.9.3 - 2015.04.26
* some fixes and optimizations
##### 0.9.2 - 2015.04.25
* more correct [`Promise`](https://github.com/zloirock/core-js/#ecmascript-6-promise) unhandled rejection tracking and resolving / rejection priority
##### 0.9.1 - 2015.04.25
* fixed `__proto__`-based [`Promise`](https://github.com/zloirock/core-js/#ecmascript-6-promise) subclassing in some environments
##### 0.9.0 - 2015.04.24
* added correct [symbols](https://github.com/zloirock/core-js/#ecmascript-6-symbol) descriptors
* fixed behavior `Object.{assign, create, defineProperty, defineProperties, getOwnPropertyDescriptor, getOwnPropertyDescriptors}` with symbols
* added [single entry points](https://github.com/zloirock/core-js/#commonjs) for `Object.{create, defineProperty, defineProperties}`
* added [`Map#toJSON`](https://github.com/zloirock/core-js/#ecmascript-7)
* removed non-standard methods `Object#[_]` and `Function#only` - they solves syntax problems, but now in compilers available arrows and ~~in near future will be available~~ [available](http://babeljs.io/blog/2015/05/14/function-bind/) [bind syntax](https://github.com/zenparsing/es-function-bind)
* removed non-standard undocumented methods `Symbol.{pure, set}`
* some fixes and internal changes
##### 0.8.4 - 2015.04.18
* uses `webpack` instead of `browserify` for browser builds - more compression-friendly result
##### 0.8.3 - 2015.04.14
* fixed `Array` statics with single entry points
##### 0.8.2 - 2015.04.13
* [`Math.fround`](https://github.com/zloirock/core-js/#ecmascript-6-math) now also works in IE9-
* added [`Set#toJSON`](https://github.com/zloirock/core-js/#ecmascript-7)
* some optimizations and fixes
##### 0.8.1 - 2015.04.03
* fixed `Symbol.keyFor`
##### 0.8.0 - 2015.04.02
* changed [CommonJS API](https://github.com/zloirock/core-js/#commonjs)
* splitted and renamed some modules
* added support ES3 environment (ES5 polyfill) to **all** default versions - size increases slightly (+ ~4kb w/o gzip), many issues disappear, if you don't need it - [simply include only required namespaces / features / modules](https://github.com/zloirock/core-js/#commonjs)
* removed [abstract references](https://github.com/zenparsing/es-abstract-refs) support - proposal has been superseded =\
* [`$for.isIterable` -> `core.isIterable`, `$for.getIterator` -> `core.getIterator`](https://github.com/zloirock/core-js/#ecmascript-6-iterators), temporary available in old namespace
* fixed iterators support in v8 `Promise.all` and `Promise.race`
* many other fixes
##### 0.7.2 - 2015.03.09
* some fixes
##### 0.7.1 - 2015.03.07
* some fixes
##### 0.7.0 - 2015.03.06
* rewritten and splitted into [CommonJS modules](https://github.com/zloirock/core-js/#commonjs)
##### 0.6.1 - 2015.02.24
* fixed support [`Object.defineProperty`](https://github.com/zloirock/core-js/#ecmascript-5) with accessors on DOM elements on IE8
##### 0.6.0 - 2015.02.23
* added support safe closing iteration - calling `iterator.return` on abort iteration, if it exists
* added basic support [`Promise`](https://github.com/zloirock/core-js/#ecmascript-6-promise) unhandled rejection tracking in shim
* added [`Object.getOwnPropertyDescriptors`](https://github.com/zloirock/core-js/#ecmascript-7)
* removed `console` cap - creates too many problems - you can use [`core.log`](https://github.com/zloirock/core-js/#console) module as that
* restructuring [namespaces](https://github.com/zloirock/core-js/#custom-build)
* some fixes
##### 0.5.4 - 2015.02.15
* some fixes
##### 0.5.3 - 2015.02.14
* added [support binary and octal literals](https://github.com/zloirock/core-js/#ecmascript-6-number) to `Number` constructor
* added [`Date#toISOString`](https://github.com/zloirock/core-js/#ecmascript-5)
##### 0.5.2 - 2015.02.10
* some fixes
##### 0.5.1 - 2015.02.09
* some fixes
##### 0.5.0 - 2015.02.08
* systematization of modules
* splitted [`es6` module](https://github.com/zloirock/core-js/#ecmascript-6)
* splitted [`console` module](https://github.com/zloirock/core-js/#console): `web.console` - only cap for missing methods, `core.log` - bound methods & additional features
* added [`delay` method](https://github.com/zloirock/core-js/#delay)
* some fixes
##### 0.4.10 - 2015.01.28
* [`Object.getOwnPropertySymbols`](https://github.com/zloirock/core-js/#ecmascript-6-symbol) polyfill returns array of wrapped keys
##### 0.4.9 - 2015.01.27
* FF20-24 fix
##### 0.4.8 - 2015.01.25
* some [collections](https://github.com/zloirock/core-js/#ecmascript-6-collections) fixes
##### 0.4.7 - 2015.01.25
* added support frozen objects as [collections](https://github.com/zloirock/core-js/#ecmascript-6-collections) keys
##### 0.4.6 - 2015.01.21
* added [`Object.getOwnPropertySymbols`](https://github.com/zloirock/core-js/#ecmascript-6-symbol)
* added [`NodeList.prototype[@@iterator]`](https://github.com/zloirock/core-js/#ecmascript-6-iterators)
* added basic `@@species` logic - getter in native constructors
* removed `Function#by`
* some fixes
##### 0.4.5 - 2015.01.16
* some fixes
##### 0.4.4 - 2015.01.11
* enabled CSP support
##### 0.4.3 - 2015.01.10
* added `Function` instances `name` property for IE9+
##### 0.4.2 - 2015.01.10
* `Object` static methods accept primitives
* `RegExp` constructor can alter flags (IE9+)
* added `Array.prototype[Symbol.unscopables]`
##### 0.4.1 - 2015.01.05
* some fixes
##### 0.4.0 - 2015.01.03
* added [`es6.reflect`](https://github.com/zloirock/core-js/#ecmascript-6-reflect) module:
* added `Reflect.apply`
* added `Reflect.construct`
* added `Reflect.defineProperty`
* added `Reflect.deleteProperty`
* added `Reflect.enumerate`
* added `Reflect.get`
* added `Reflect.getOwnPropertyDescriptor`
* added `Reflect.getPrototypeOf`
* added `Reflect.has`
* added `Reflect.isExtensible`
* added `Reflect.preventExtensions`
* added `Reflect.set`
* added `Reflect.setPrototypeOf`
* `core-js` methods now can use external `Symbol.iterator` polyfill
* some fixes
##### 0.3.3 - 2014.12.28
* [console cap](https://github.com/zloirock/core-js/#console) excluded from node.js default builds
##### 0.3.2 - 2014.12.25
* added cap for [ES5](https://github.com/zloirock/core-js/#ecmascript-5) freeze-family methods
* fixed `console` bug
##### 0.3.1 - 2014.12.23
* some fixes
##### 0.3.0 - 2014.12.23
* Optimize [`Map` & `Set`](https://github.com/zloirock/core-js/#ecmascript-6-collections):
* use entries chain on hash table
* fast & correct iteration
* iterators moved to [`es6`](https://github.com/zloirock/core-js/#ecmascript-6) and [`es6.collections`](https://github.com/zloirock/core-js/#ecmascript-6-collections) modules
##### 0.2.5 - 2014.12.20
* `console` no longer shortcut for `console.log` (compatibility problems)
* some fixes
##### 0.2.4 - 2014.12.17
* better compliance of ES6
* added [`Math.fround`](https://github.com/zloirock/core-js/#ecmascript-6-math) (IE10+)
* some fixes
##### 0.2.3 - 2014.12.15
* [Symbols](https://github.com/zloirock/core-js/#ecmascript-6-symbol):
* added option to disable addition setter to `Object.prototype` for Symbol polyfill:
* added `Symbol.useSimple`
* added `Symbol.useSetter`
* added cap for well-known Symbols:
* added `Symbol.hasInstance`
* added `Symbol.isConcatSpreadable`
* added `Symbol.match`
* added `Symbol.replace`
* added `Symbol.search`
* added `Symbol.species`
* added `Symbol.split`
* added `Symbol.toPrimitive`
* added `Symbol.unscopables`
##### 0.2.2 - 2014.12.13
* added [`RegExp#flags`](https://github.com/zloirock/core-js/#ecmascript-6-regexp) ([December 2014 Draft Rev 29](http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts#december_6_2014_draft_rev_29))
* added [`String.raw`](https://github.com/zloirock/core-js/#ecmascript-6-string)
##### 0.2.1 - 2014.12.12
* repair converting -0 to +0 in [native collections](https://github.com/zloirock/core-js/#ecmascript-6-collections)
##### 0.2.0 - 2014.12.06
* added [`es7.proposals`](https://github.com/zloirock/core-js/#ecmascript-7) and [`es7.abstract-refs`](https://github.com/zenparsing/es-abstract-refs) modules
* added [`String#at`](https://github.com/zloirock/core-js/#ecmascript-7)
* added real [`String Iterator`](https://github.com/zloirock/core-js/#ecmascript-6-iterators), older versions used Array Iterator
* added abstract references support:
* added `Symbol.referenceGet`
* added `Symbol.referenceSet`
* added `Symbol.referenceDelete`
* added `Function#@@referenceGet`
* added `Map#@@referenceGet`
* added `Map#@@referenceSet`
* added `Map#@@referenceDelete`
* added `WeakMap#@@referenceGet`
* added `WeakMap#@@referenceSet`
* added `WeakMap#@@referenceDelete`
* added `Dict.{...methods}[@@referenceGet]`
* removed deprecated `.contains` methods
* some fixes
##### 0.1.5 - 2014.12.01
* added [`Array#copyWithin`](https://github.com/zloirock/core-js/#ecmascript-6-array)
* added [`String#codePointAt`](https://github.com/zloirock/core-js/#ecmascript-6-string)
* added [`String.fromCodePoint`](https://github.com/zloirock/core-js/#ecmascript-6-string)
##### 0.1.4 - 2014.11.27
* added [`Dict.mapPairs`](https://github.com/zloirock/core-js/#dict)
##### 0.1.3 - 2014.11.20
* [TC39 November meeting](https://github.com/rwaldron/tc39-notes/tree/master/es6/2014-11):
* [`.contains` -> `.includes`](https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-11/nov-18.md#51--44-arrayprototypecontains-and-stringprototypecontains)
* `String#contains` -> [`String#includes`](https://github.com/zloirock/core-js/#ecmascript-6-string)
* `Array#contains` -> [`Array#includes`](https://github.com/zloirock/core-js/#ecmascript-7)
* `Dict.contains` -> [`Dict.includes`](https://github.com/zloirock/core-js/#dict)
* [removed `WeakMap#clear`](https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-11/nov-19.md#412-should-weakmapweakset-have-a-clear-method-markm)
* [removed `WeakSet#clear`](https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-11/nov-19.md#412-should-weakmapweakset-have-a-clear-method-markm)
##### 0.1.2 - 2014.11.19
* `Map` & `Set` bug fix
##### 0.1.1 - 2014.11.18
* public release | {
"pile_set_name": "Github"
} |
package org.eclipse.ceylon.compiler.java.test.issues.bug09xx;
class Bug919 implements .org.eclipse.ceylon.compiler.java.runtime.model.ReifiedType, .java.io.Serializable {
Bug919() {
}
private final void m$priv$() {
final .ceylon.language.Sequence t = new .ceylon.language.Tuple(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.ceylon.language.String.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$), .ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .ceylon.language.Empty.$TypeDescriptor$), .ceylon.language.String.instance("a"), new .ceylon.language.Tuple<.ceylon.language.Empty, .ceylon.language.Empty, .ceylon.language.Sequential<? extends .ceylon.language.Empty>>(.ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.empty_.get_(), (.ceylon.language.Sequential).ceylon.language.empty_.get_()));
final .ceylon.language.Sequence t2 = (.ceylon.language.Sequence<? extends .java.lang.Object>).ceylon.language.Tuple.instance(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.ceylon.language.String.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$), new .java.lang.Object[]{
.ceylon.language.String.instance("a"),
.ceylon.language.empty_.get_()});
final .ceylon.language.Iterable t3 = new .org.eclipse.ceylon.compiler.java.language.LazyIterable<.java.lang.Object, .java.lang.Object>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.ceylon.language.Empty.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType), .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType)), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, 5, false){
@.java.lang.Override
protected final .java.lang.Object $evaluate$(int $index$) {
switch ($index$) {
case 0:
return .ceylon.language.empty_.get_();
case 1:
return new .org.eclipse.ceylon.compiler.java.language.LazyIterable<.java.lang.Object, .java.lang.Object>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType), .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, 5, false){
@.java.lang.Override
protected final .java.lang.Object $evaluate$(int $index$) {
switch ($index$) {
case 0:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("a"), .ceylon.language.String.instance("b"));
case 1:
return .ceylon.language.empty_.get_();
case 2:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("c"));
case 3:
return .ceylon.language.empty_.get_();
case 4:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("d"), .ceylon.language.String.instance("e"));
default:
return null;
}
}
};
case 2:
return .ceylon.language.empty_.get_();
case 3:
return new .org.eclipse.ceylon.compiler.java.language.LazyIterable<.java.lang.Object, .java.lang.Object>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType), .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, 5, false){
@.java.lang.Override
protected final .java.lang.Object $evaluate$(int $index$) {
switch ($index$) {
case 0:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("a"), .ceylon.language.String.instance("b"));
case 1:
return .ceylon.language.empty_.get_();
case 2:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("c"));
case 3:
return .ceylon.language.empty_.get_();
case 4:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("d"), .ceylon.language.String.instance("e"));
default:
return null;
}
}
};
case 4:
return .ceylon.language.empty_.get_();
default:
return null;
}
}
};
final .ceylon.language.Sequence t4 = new .ceylon.language.Tuple(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, 0, .ceylon.language.String.$TypeDescriptor$), .ceylon.language.Empty.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .ceylon.language.String.$TypeDescriptor$)), .ceylon.language.empty_.get_(), new .ceylon.language.Tuple<.ceylon.language.Sequence<? extends .ceylon.language.String>, .ceylon.language.Sequence<? extends .ceylon.language.String>, .ceylon.language.Sequential<? extends .ceylon.language.Sequence<? extends .ceylon.language.String>>>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .ceylon.language.String.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .ceylon.language.String.$TypeDescriptor$), .ceylon.language.Empty.$TypeDescriptor$, new .ceylon.language.Tuple<.ceylon.language.String, .ceylon.language.String, .ceylon.language.Sequential<? extends .ceylon.language.String>>(.ceylon.language.String.$TypeDescriptor$, .ceylon.language.String.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.String.instance("c"), (.ceylon.language.Sequential).ceylon.language.empty_.get_()), (.ceylon.language.Sequential).ceylon.language.empty_.get_()));
final .ceylon.language.Sequence<? extends .ceylon.language.Sequential<? extends .ceylon.language.String>> t5 = new .ceylon.language.Tuple<.ceylon.language.Sequential<? extends .ceylon.language.String>, .ceylon.language.Sequential<? extends .ceylon.language.String>, .ceylon.language.Sequential<? extends .ceylon.language.Sequential<? extends .ceylon.language.String>>>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Sequential.class, .ceylon.language.String.$TypeDescriptor$), .ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$, (.ceylon.language.Sequential).ceylon.language.empty_.get_(), (.ceylon.language.Sequential).ceylon.language.empty_.get_());
}
@.java.lang.Override
public .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor $getType$() {
return .org.eclipse.ceylon.compiler.java.test.issues.bug09xx.Bug919.$TypeDescriptor$;
}
public static final .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor $TypeDescriptor$ = .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.org.eclipse.ceylon.compiler.java.test.issues.bug09xx.Bug919.class);
}
public final class bug919_2_ {
private bug919_2_() {
}
public static void bug919_2() {
.org.eclipse.ceylon.compiler.java.test.issues.bug09xx.bug919_3_.bug919_3((.ceylon.language.Iterable<? extends .ceylon.language.Iterable<? extends .ceylon.language.Iterable<? extends .ceylon.language.String, ? extends .java.lang.Object>, ? extends .java.lang.Object>, ? extends .java.lang.Object>)(.ceylon.language.Iterable)new .org.eclipse.ceylon.compiler.java.language.LazyIterable<.java.lang.Object, .java.lang.Object>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .ceylon.language.Empty.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType), .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, 2, false){
@.java.lang.Override
protected final .java.lang.Object $evaluate$(int $index$) {
switch ($index$) {
case 0:
return new .org.eclipse.ceylon.compiler.java.language.LazyIterable<.ceylon.language.Empty, .java.lang.Object>(.ceylon.language.Empty.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, 1, false){
@.java.lang.Override
protected final .java.lang.Object $evaluate$(int $index$) {
switch ($index$) {
case 0:
return .ceylon.language.empty_.get_();
default:
return null;
}
}
};
case 1:
return .ceylon.language.empty_.get_();
default:
return null;
}
}
});
.org.eclipse.ceylon.compiler.java.test.issues.bug09xx.bug919_3_.bug919_3((.ceylon.language.Iterable<? extends .ceylon.language.Iterable<? extends .ceylon.language.Iterable<? extends .ceylon.language.String, ? extends .java.lang.Object>, ? extends .java.lang.Object>, ? extends .java.lang.Object>)(.ceylon.language.Iterable)new .ceylon.language.Tuple(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, 0, .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.tuple(false, false, -1, .ceylon.language.Empty.$TypeDescriptor$), new .ceylon.language.Tuple<.ceylon.language.Empty, .ceylon.language.Empty, .ceylon.language.Sequential<? extends .ceylon.language.Empty>>(.ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.empty_.get_(), (.ceylon.language.Sequential).ceylon.language.empty_.get_()), new .ceylon.language.Tuple<.ceylon.language.Empty, .ceylon.language.Empty, .ceylon.language.Sequential<? extends .ceylon.language.Empty>>(.ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.Empty.$TypeDescriptor$, .ceylon.language.empty_.get_(), (.ceylon.language.Sequential).ceylon.language.empty_.get_())));
.org.eclipse.ceylon.compiler.java.test.issues.bug09xx.bug919_3_.bug919_3((.ceylon.language.Iterable<? extends .ceylon.language.Iterable<? extends .ceylon.language.Iterable<? extends .ceylon.language.String, ? extends .java.lang.Object>, ? extends .java.lang.Object>, ? extends .java.lang.Object>)(.ceylon.language.Iterable)new .org.eclipse.ceylon.compiler.java.language.LazyIterable<.java.lang.Object, .java.lang.Object>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.ceylon.language.Empty.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType), .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType)), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, 5, false){
@.java.lang.Override
protected final .java.lang.Object $evaluate$(int $index$) {
switch ($index$) {
case 0:
return .ceylon.language.empty_.get_();
case 1:
return new .org.eclipse.ceylon.compiler.java.language.LazyIterable<.java.lang.Object, .java.lang.Object>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType), .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, 5, false){
@.java.lang.Override
protected final .java.lang.Object $evaluate$(int $index$) {
switch ($index$) {
case 0:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("a"), .ceylon.language.String.instance("b"));
case 1:
return .ceylon.language.empty_.get_();
case 2:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("c"));
case 3:
return .ceylon.language.empty_.get_();
case 4:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("d"), .ceylon.language.String.instance("e"));
default:
return null;
}
}
};
case 2:
return .ceylon.language.empty_.get_();
case 3:
return new .org.eclipse.ceylon.compiler.java.language.LazyIterable<.java.lang.Object, .java.lang.Object>(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.union(.org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.klass(.ceylon.language.Iterable.class, .ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType), .ceylon.language.Empty.$TypeDescriptor$), .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, 5, false){
@.java.lang.Override
protected final .java.lang.Object $evaluate$(int $index$) {
switch ($index$) {
case 0:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("a"), .ceylon.language.String.instance("b"));
case 1:
return .ceylon.language.empty_.get_();
case 2:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("c"));
case 3:
return .ceylon.language.empty_.get_();
case 4:
return new .org.eclipse.ceylon.compiler.java.language.ConstantIterable<.ceylon.language.String, .java.lang.Object>(.ceylon.language.String.$TypeDescriptor$, .org.eclipse.ceylon.compiler.java.runtime.model.TypeDescriptor.NothingType, null, .ceylon.language.String.instance("d"), .ceylon.language.String.instance("e"));
default:
return null;
}
}
};
case 4:
return .ceylon.language.empty_.get_();
default:
return null;
}
}
});
}
public static void main(.java.lang.String[] args) {
.org.eclipse.ceylon.compiler.java.Util.storeArgs(args);
.org.eclipse.ceylon.compiler.java.test.issues.bug09xx.bug919_2_.bug919_2();
}
}
public final class bug919_3_ {
private bug919_3_() {
}
public static void bug919_3(final .ceylon.language.Iterable<? extends .ceylon.language.Iterable<? extends .ceylon.language.Iterable<? extends .ceylon.language.String, ? extends .java.lang.Object>, ? extends .java.lang.Object>, ? extends .java.lang.Object> iterables) {
}
} | {
"pile_set_name": "Github"
} |
from .res_layer import ResLayer
__all__ = ['ResLayer']
| {
"pile_set_name": "Github"
} |
@{
Model.Classes.Add("breadcrumbs");
var items = ((IEnumerable<dynamic>)Model.Items).ToList();
var index = 0;
var tag = Tag(Model, "ul");
}
@if (items.Count > 1) {
@tag.StartElement
foreach (var item in items) {
if (++index == items.Count) {
item.Metadata.Type = "BreadcrumbItem_Last";
<li>@Display(item)</li>
}
else {
<li>@Display(item) ></li>
}
}
@tag.EndElement
} | {
"pile_set_name": "Github"
} |
# frozen_string_literal: true
namespace :tasks do
class InvalidTaskType < StandardError; end
class InvalidOrganization < StandardError; end
class NoTasksToChange < StandardError; end
class NoTasksToReassign < StandardError; end
class MoreTasksToReassign < StandardError; end
class InvalidTaskParent < StandardError; end
class InvalidTaskAssignee < StandardError; end
# usage:
# Change all HoldHearingTasks to AssignHearingDispositionTask (dry run)
# $ bundle exec rake tasks:change_type[HoldHearingTask,AssignHearingDispositionTask]"
# Change all HoldHearingTasks to DispositionTasks (execute)
# $ bundle exec rake tasks:change_type[HoldHearingTask,DispositionTask,false]"
# Change HoldHearingTasks matching passed ids to DispositionTasks (dry run)
# $ bundle exec rake tasks:change_type[HoldHearingTask,DispositionTask,12,13,14,15,16]"
# Change HoldHearingTasks matching passed ids to DispositionTasks (execute)
# $ bundle exec rake tasks:change_type[HoldHearingTask,DispositionTask,false,12,13,14,15,16]"
desc "change tasks from one type to another"
task :change_type, [:from_type, :to_type, :dry_run] => :environment do |_, args|
Rails.logger.tagged("rake tasks:change_type") { Rails.logger.info("Invoked with: #{args.to_a.join(', ')}") }
extras = args.extras
dry_run = args.dry_run&.to_s&.strip&.upcase != "FALSE"
if dry_run && args.dry_run.to_i > 0
extras.unshift(args.dry_run)
end
if dry_run
puts "*** DRY RUN"
puts "*** pass 'false' as the third argument to execute"
end
from_class = Object.const_get(args.from_type)
to_class = Object.const_get(args.to_type)
[from_class, to_class].each do |check_class|
unless Task.descendants.include?(check_class)
fail InvalidTaskType, "#{check_class.name} is not a valid Task type!"
end
end
target_tasks = if extras.any?
from_class.find(extras)
else
from_class.all
end
if target_tasks.count == 0
fail NoTasksToChange, "There aren't any #{from_class.name}s available to change."
end
id_string = target_tasks.map(&:id).sort.join(",")
change = dry_run ? "Would change" : "Changing"
revert = dry_run ? "Would revert" : "Revert"
message = "#{change} #{target_tasks.count} #{from_class.name}s with ids #{id_string} into #{to_class.name}s"
puts message
puts "#{revert} with: bundle exec rake tasks:change_type[#{to_class.name},#{from_class.name},#{id_string}]"
if !dry_run
Rails.logger.tagged("rake tasks:change_type") { Rails.logger.info(message) }
target_tasks.each do |task|
task.update!(type: to_class.name)
end
end
end
# usage:
# Assign all HearingTasks assigned to org with id 1 to org with id 2 (dry run)
# $ bundle exec rake tasks:change_organization_assigned_to[HearingTasks,1,2]"
# Assign all HearingTasks assigned to org with id 1 to org with id 2 (execute)
# $ bundle exec rake tasks:change_organization_assigned_to[HearingTask,1,2,false]"
# Assign all HearingTasks matching passed ids and assigned to org with id 1 to org with id 2 (dry run)
# $ bundle exec rake tasks:change_organization_assigned_to[HearingTask,1,2,12,13,14,15,16]"
# Assign all HearingTasks matching passed ids and assigned to org with id 1 to org with id 2 (execute)
# $ bundle exec rake tasks:change_organization_assigned_to[HearingTask,1,2,false,12,13,14,15,16]"
desc "change the user or organization that active tasks are assigned to"
task :change_organization_assigned_to, [
:task_type, :from_assigned_to_id, :to_assigned_to_id, :dry_run
] => :environment do |_, args|
logger_tag = "rake tasks:change_organization_assigned_to"
Rails.logger.tagged(logger_tag) do
Rails.logger.info("Invoked with: #{args.to_a.join(', ')}")
end
extras = args.extras
dry_run = args.dry_run&.to_s&.strip&.upcase != "FALSE"
if dry_run && args.dry_run.to_i > 0
extras.unshift(args.dry_run)
end
if dry_run
puts "*** DRY RUN"
puts "*** pass 'false' as the fourth argument to execute"
end
task_class = Object.const_get(args.task_type)
fail InvalidTaskType, "#{task_class.name} is not a valid Task type!" unless Task.descendants.include?(task_class)
from_id = args.from_assigned_to_id.to_i
to_id = args.to_assigned_to_id.to_i
[from_id, to_id].each do |check_id|
fail InvalidOrganization, "No organization with id #{check_id}!" if Organization.find_by(id: check_id).blank?
end
from_organization = Organization.find(from_id)
to_organization = Organization.find(to_id)
target_tasks = if extras.any?
task_class.where(id: extras, assigned_to: from_organization)
else
task_class.where(assigned_to: from_organization)
end
if target_tasks.count == 0
fail NoTasksToChange, "There aren't any #{task_class.name}s assigned " \
"to #{from_organization.name} available to change."
end
ids = target_tasks.map(&:id).sort
change = dry_run ? "Would change" : "Changing"
revert = dry_run ? "Would revert" : "Revert"
message = "#{change} assignee of #{target_tasks.count} #{task_class.name}s with ids #{ids.join(',')} " \
"from #{from_organization.name} to #{to_organization.name}"
puts message
puts "#{revert} with: bundle exec rake tasks:change_organization_assigned_to" \
"[#{task_class.name},#{to_id},#{from_id},false,#{ids.join(',')}]"
if !dry_run
Rails.logger.tagged(logger_tag) { Rails.logger.info(message) }
target_tasks.update_all(assigned_to_id: to_id)
end
end
# usage:
# Reassign all tasks assigned to a user with an id of 1 (dry run)
# $ bundle exec rake tasks:reassign_from_user[1]"
# Reassign all tasks assigned to a user with an id of 1 (execute)
# $ bundle exec rake tasks:reassign_from_user[1,false]"
desc "reassign all tasks assigned to a user"
task :reassign_from_user, [:user_id, :dry_run] => :environment do |_, args|
Rails.logger.tagged("rake tasks:reassign_from_user") { Rails.logger.info("Invoked with: #{args.to_a.join(', ')}") }
dry_run = args.dry_run&.to_s&.strip&.upcase != "FALSE"
user = User.find(args.user_id)
if dry_run
puts "*** DRY RUN"
puts "*** pass 'false' as the second argument to execute"
BulkTaskReassignment.new(user).perform_dry_run
else
BulkTaskReassignment.new(user).process
end
end
# Usage:
# Migrates our old admin-judge based JudgeTeams to use the JudgeTeamRole (dry run)
# $ bundle exec rake tasks:assign_judgeteamroles_to_judgeteam_members"
# Reassign all tasks assigned to a user with an id of 1 (execute)
# $ bundle exec rake tasks:assign_judgeteamroles_to_judgeteam_members[false]"
desc "assigning all current JudgeTeam admin members to be JudgeTeamLead"
task :assign_judgeteamroles_to_judgeteam_members, [:dry_run] => :environment do |_, args|
Rails.logger.tagged("rake tasks:assign_judgeteamroles_to_judgeteam_members") do
Rails.logger.info("Invoked with: #{args.to_a.join(', ')}")
end
dry_run = args.dry_run&.to_s&.strip&.upcase != "FALSE"
if dry_run
puts "*** DRY RUN"
puts "*** pass 'false' as the first argument to execute"
AssignJudgeteamRoles.new.perform_dry_run
else
puts "Updating JudgeTeams with JudgeTeamRoles"
AssignJudgeteamRoles.new.process
end
end
end
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.backup;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static google.registry.backup.BackupUtils.GcsMetadataKeys.LOWER_BOUND_CHECKPOINT;
import static google.registry.backup.BackupUtils.GcsMetadataKeys.NUM_TRANSACTIONS;
import static google.registry.backup.BackupUtils.GcsMetadataKeys.UPPER_BOUND_CHECKPOINT;
import static google.registry.backup.BackupUtils.deserializeEntities;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static org.joda.time.DateTimeZone.UTC;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.common.collect.ImmutableMap;
import com.googlecode.objectify.Key;
import google.registry.model.ImmutableObject;
import google.registry.model.ofy.CommitLogBucket;
import google.registry.model.ofy.CommitLogCheckpoint;
import google.registry.model.ofy.CommitLogManifest;
import google.registry.model.ofy.CommitLogMutation;
import google.registry.testing.AppEngineExtension;
import google.registry.testing.GcsTestingUtils;
import google.registry.testing.TestObject;
import java.util.List;
import org.joda.time.DateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
/** Unit tests for {@link ExportCommitLogDiffAction}. */
public class ExportCommitLogDiffActionTest {
@RegisterExtension
public final AppEngineExtension appEngine =
AppEngineExtension.builder()
.withDatastoreAndCloudSql()
.withOfyTestEntities(TestObject.class)
.build();
/** Local GCS service available for testing. */
private final GcsService gcsService = GcsServiceFactory.createGcsService();
private final DateTime now = DateTime.now(UTC);
private final DateTime oneMinuteAgo = now.minusMinutes(1);
private final ExportCommitLogDiffAction task = new ExportCommitLogDiffAction();
@BeforeEach
void beforeEach() {
task.gcsService = gcsService;
task.gcsBucket = "gcs bucket";
task.batchSize = 5;
}
@Test
void testRun_noCommitHistory_onlyUpperCheckpointExported() throws Exception {
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
persistResource(CommitLogCheckpoint.create(
oneMinuteAgo,
ImmutableMap.of(1, oneMinuteAgo, 2, oneMinuteAgo, 3, oneMinuteAgo)));
CommitLogCheckpoint upperCheckpoint = persistResource(CommitLogCheckpoint.create(
now,
ImmutableMap.of(1, now, 2, now, 3, now)));
// Don't persist any manifests or mutations.
task.run();
GcsFilename expectedFilename = new GcsFilename("gcs bucket", "commit_diff_until_" + now);
assertWithMessage("GCS file not found: " + expectedFilename)
.that(gcsService.getMetadata(expectedFilename)).isNotNull();
assertThat(gcsService.getMetadata(expectedFilename).getOptions().getUserMetadata())
.containsExactly(
LOWER_BOUND_CHECKPOINT,
oneMinuteAgo.toString(),
UPPER_BOUND_CHECKPOINT,
now.toString(),
NUM_TRANSACTIONS,
"0");
List<ImmutableObject> exported =
deserializeEntities(GcsTestingUtils.readGcsFile(gcsService, expectedFilename));
assertThat(exported).containsExactly(upperCheckpoint);
}
@Test
void testRun_regularCommitHistory_exportsCorrectCheckpointDiff() throws Exception {
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
// Persist the lower and upper checkpoints, with 3 buckets each and staggered times. We respect
// the real invariant that the time for bucket n in the lower checkpoint is <= the time for
// that bucket in the upper.
persistResource(CommitLogCheckpoint.create(
oneMinuteAgo,
ImmutableMap.of(
1, oneMinuteAgo,
2, oneMinuteAgo.minusDays(1),
3, oneMinuteAgo.minusDays(2))));
CommitLogCheckpoint upperCheckpoint = persistResource(CommitLogCheckpoint.create(
now,
ImmutableMap.of(
1, now,
2, now.minusDays(1),
3, oneMinuteAgo.minusDays(2)))); // Note that this matches the lower bound.
// Persist some fake commit log manifests.
// These shouldn't be in the diff because the lower bound is exclusive.
persistManifestAndMutation(1, oneMinuteAgo);
persistManifestAndMutation(2, oneMinuteAgo.minusDays(1));
persistManifestAndMutation(3, oneMinuteAgo.minusDays(2)); // Even though it's == upper bound.
// These shouldn't be in the diff because they are above the upper bound.
persistManifestAndMutation(1, now.plusMillis(1));
persistManifestAndMutation(2, now.minusDays(1).plusMillis(1));
persistManifestAndMutation(3, oneMinuteAgo.minusDays(2).plusMillis(1));
// These should be in the diff because they are between the bounds. (Not possible for bucket 3.)
persistManifestAndMutation(1, now.minusMillis(1));
persistManifestAndMutation(2, now.minusDays(1).minusMillis(1));
// These should be in the diff because they are at the upper bound. (Not possible for bucket 3.)
persistManifestAndMutation(1, now);
persistManifestAndMutation(2, now.minusDays(1));
task.run();
GcsFilename expectedFilename = new GcsFilename("gcs bucket", "commit_diff_until_" + now);
assertWithMessage("GCS file not found: " + expectedFilename)
.that(gcsService.getMetadata(expectedFilename)).isNotNull();
assertThat(gcsService.getMetadata(expectedFilename).getOptions().getUserMetadata())
.containsExactly(
LOWER_BOUND_CHECKPOINT,
oneMinuteAgo.toString(),
UPPER_BOUND_CHECKPOINT,
now.toString(),
NUM_TRANSACTIONS,
"4");
List<ImmutableObject> exported =
deserializeEntities(GcsTestingUtils.readGcsFile(gcsService, expectedFilename));
assertThat(exported.get(0)).isEqualTo(upperCheckpoint);
// We expect these manifests, in time order, with matching mutations.
CommitLogManifest manifest1 = createManifest(2, now.minusDays(1).minusMillis(1));
CommitLogManifest manifest2 = createManifest(2, now.minusDays(1));
CommitLogManifest manifest3 = createManifest(1, now.minusMillis(1));
CommitLogManifest manifest4 = createManifest(1, now);
assertThat(exported).containsExactly(
upperCheckpoint,
manifest1,
createMutation(manifest1),
manifest2,
createMutation(manifest2),
manifest3,
createMutation(manifest3),
manifest4,
createMutation(manifest4))
.inOrder();
}
@Test
void testRun_simultaneousTransactions_bothExported() throws Exception {
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
persistResource(CommitLogCheckpoint.create(
oneMinuteAgo,
ImmutableMap.of(1, START_OF_TIME, 2, START_OF_TIME, 3, START_OF_TIME)));
CommitLogCheckpoint upperCheckpoint = persistResource(CommitLogCheckpoint.create(
now,
ImmutableMap.of(1, now, 2, now, 3, now)));
// Persist some fake commit log manifests that are at the same time but in different buckets.
persistManifestAndMutation(1, oneMinuteAgo);
persistManifestAndMutation(2, oneMinuteAgo);
persistManifestAndMutation(1, now);
persistManifestAndMutation(2, now);
task.run();
GcsFilename expectedFilename = new GcsFilename("gcs bucket", "commit_diff_until_" + now);
assertWithMessage("GCS file not found: " + expectedFilename)
.that(gcsService.getMetadata(expectedFilename)).isNotNull();
assertThat(gcsService.getMetadata(expectedFilename).getOptions().getUserMetadata())
.containsExactly(
LOWER_BOUND_CHECKPOINT,
oneMinuteAgo.toString(),
UPPER_BOUND_CHECKPOINT,
now.toString(),
NUM_TRANSACTIONS,
"4");
List<ImmutableObject> exported =
deserializeEntities(GcsTestingUtils.readGcsFile(gcsService, expectedFilename));
assertThat(exported.get(0)).isEqualTo(upperCheckpoint);
// We expect these manifests, in the order below, with matching mutations.
CommitLogManifest manifest1 = createManifest(1, oneMinuteAgo);
CommitLogManifest manifest2 = createManifest(2, oneMinuteAgo);
CommitLogManifest manifest3 = createManifest(1, now);
CommitLogManifest manifest4 = createManifest(2, now);
assertThat(exported).containsExactly(
upperCheckpoint,
manifest1,
createMutation(manifest1),
manifest2,
createMutation(manifest2),
manifest3,
createMutation(manifest3),
manifest4,
createMutation(manifest4))
.inOrder();
}
@Test
void testRun_exportsAcrossMultipleBatches() throws Exception {
task.batchSize = 2;
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
persistResource(CommitLogCheckpoint.create(
oneMinuteAgo,
ImmutableMap.of(1, START_OF_TIME, 2, START_OF_TIME, 3, START_OF_TIME)));
CommitLogCheckpoint upperCheckpoint = persistResource(CommitLogCheckpoint.create(
now,
ImmutableMap.of(1, now, 2, now, 3, now)));
// Persist some fake commit log manifests.
persistManifestAndMutation(1, oneMinuteAgo);
persistManifestAndMutation(2, oneMinuteAgo);
persistManifestAndMutation(3, oneMinuteAgo);
persistManifestAndMutation(1, now);
persistManifestAndMutation(2, now);
persistManifestAndMutation(3, now);
task.run();
GcsFilename expectedFilename = new GcsFilename("gcs bucket", "commit_diff_until_" + now);
assertWithMessage("GCS file not found: " + expectedFilename)
.that(gcsService.getMetadata(expectedFilename)).isNotNull();
assertThat(gcsService.getMetadata(expectedFilename).getOptions().getUserMetadata())
.containsExactly(
LOWER_BOUND_CHECKPOINT,
oneMinuteAgo.toString(),
UPPER_BOUND_CHECKPOINT,
now.toString(),
NUM_TRANSACTIONS,
"6");
List<ImmutableObject> exported =
deserializeEntities(GcsTestingUtils.readGcsFile(gcsService, expectedFilename));
assertThat(exported.get(0)).isEqualTo(upperCheckpoint);
// We expect these manifests, in the order below, with matching mutations.
CommitLogManifest manifest1 = createManifest(1, oneMinuteAgo);
CommitLogManifest manifest2 = createManifest(2, oneMinuteAgo);
CommitLogManifest manifest3 = createManifest(3, oneMinuteAgo);
CommitLogManifest manifest4 = createManifest(1, now);
CommitLogManifest manifest5 = createManifest(2, now);
CommitLogManifest manifest6 = createManifest(3, now);
assertThat(exported).containsExactly(
upperCheckpoint,
manifest1,
createMutation(manifest1),
manifest2,
createMutation(manifest2),
manifest3,
createMutation(manifest3),
manifest4,
createMutation(manifest4),
manifest5,
createMutation(manifest5),
manifest6,
createMutation(manifest6))
.inOrder();
}
@Test
void testRun_checkpointDiffWithNeverTouchedBuckets_exportsCorrectly() throws Exception {
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
persistResource(CommitLogCheckpoint.create(
oneMinuteAgo,
ImmutableMap.of(1, START_OF_TIME, 2, START_OF_TIME, 3, START_OF_TIME)));
CommitLogCheckpoint upperCheckpoint = persistResource(CommitLogCheckpoint.create(
now,
ImmutableMap.of(1, START_OF_TIME, 2, START_OF_TIME, 3, START_OF_TIME)));
// Don't persist any commit log manifests; we're just checking that the task runs correctly
// even if the upper timestamp contains START_OF_TIME values.
task.run();
GcsFilename expectedFilename = new GcsFilename("gcs bucket", "commit_diff_until_" + now);
assertWithMessage("GCS file not found: " + expectedFilename)
.that(gcsService.getMetadata(expectedFilename)).isNotNull();
assertThat(gcsService.getMetadata(expectedFilename).getOptions().getUserMetadata())
.containsExactly(
LOWER_BOUND_CHECKPOINT,
oneMinuteAgo.toString(),
UPPER_BOUND_CHECKPOINT,
now.toString(),
NUM_TRANSACTIONS,
"0");
List<ImmutableObject> exported =
deserializeEntities(GcsTestingUtils.readGcsFile(gcsService, expectedFilename));
// We expect no manifests or mutations, only the upper checkpoint.
assertThat(exported).containsExactly(upperCheckpoint);
}
@Test
void testRun_checkpointDiffWithNonExistentBucketTimestamps_exportsCorrectly() throws Exception {
// Non-existent bucket timestamps can exist when the commit log bucket count was increased
// recently.
task.lowerCheckpointTime = oneMinuteAgo;
task.upperCheckpointTime = now;
// No lower checkpoint times are persisted for buckets 2 and 3 (simulating a recent increase in
// the number of commit log buckets from 1 to 3), so all mutations on buckets 2 and 3, even
// those older than the lower checkpoint, will be exported.
persistResource(
CommitLogCheckpoint.createForTest(oneMinuteAgo, ImmutableMap.of(1, oneMinuteAgo)));
CommitLogCheckpoint upperCheckpoint =
persistResource(
CommitLogCheckpoint.create(
now,
ImmutableMap.of(
1, now,
2, now.minusDays(1),
3, oneMinuteAgo.minusDays(2))));
// These shouldn't be in the diff because the lower bound is exclusive.
persistManifestAndMutation(1, oneMinuteAgo);
// These shouldn't be in the diff because they are above the upper bound.
persistManifestAndMutation(1, now.plusMillis(1));
persistManifestAndMutation(2, now.minusDays(1).plusMillis(1));
persistManifestAndMutation(3, oneMinuteAgo.minusDays(2).plusMillis(1));
// These should be in the diff because they happened after START_OF_TIME on buckets with
// non-existent timestamps.
persistManifestAndMutation(2, oneMinuteAgo.minusDays(1));
persistManifestAndMutation(3, oneMinuteAgo.minusDays(2));
// These should be in the diff because they are between the bounds.
persistManifestAndMutation(1, now.minusMillis(1));
persistManifestAndMutation(2, now.minusDays(1).minusMillis(1));
// These should be in the diff because they are at the upper bound.
persistManifestAndMutation(1, now);
persistManifestAndMutation(2, now.minusDays(1));
task.run();
GcsFilename expectedFilename = new GcsFilename("gcs bucket", "commit_diff_until_" + now);
assertWithMessage("GCS file not found: " + expectedFilename)
.that(gcsService.getMetadata(expectedFilename))
.isNotNull();
assertThat(gcsService.getMetadata(expectedFilename).getOptions().getUserMetadata())
.containsExactly(
LOWER_BOUND_CHECKPOINT,
oneMinuteAgo.toString(),
UPPER_BOUND_CHECKPOINT,
now.toString(),
NUM_TRANSACTIONS,
"6");
List<ImmutableObject> exported =
deserializeEntities(GcsTestingUtils.readGcsFile(gcsService, expectedFilename));
assertThat(exported.get(0)).isEqualTo(upperCheckpoint);
// We expect these manifests, in time order, with matching mutations.
CommitLogManifest manifest1 = createManifest(3, oneMinuteAgo.minusDays(2));
CommitLogManifest manifest2 = createManifest(2, oneMinuteAgo.minusDays(1));
CommitLogManifest manifest3 = createManifest(2, now.minusDays(1).minusMillis(1));
CommitLogManifest manifest4 = createManifest(2, now.minusDays(1));
CommitLogManifest manifest5 = createManifest(1, now.minusMillis(1));
CommitLogManifest manifest6 = createManifest(1, now);
assertThat(exported)
.containsExactly(
upperCheckpoint,
manifest1,
createMutation(manifest1),
manifest2,
createMutation(manifest2),
manifest3,
createMutation(manifest3),
manifest4,
createMutation(manifest4),
manifest5,
createMutation(manifest5),
manifest6,
createMutation(manifest6))
.inOrder();
}
@Test
void testRun_exportingFromStartOfTime_exportsAllCommits() throws Exception {
task.lowerCheckpointTime = START_OF_TIME;
task.upperCheckpointTime = now;
CommitLogCheckpoint upperCheckpoint = persistResource(CommitLogCheckpoint.create(
now,
ImmutableMap.of(1, now, 2, now, 3, now)));
// Persist some fake commit log manifests.
persistManifestAndMutation(1, START_OF_TIME.plusMillis(1)); // Oldest possible manifest time.
persistManifestAndMutation(2, oneMinuteAgo);
persistManifestAndMutation(3, now);
task.run();
GcsFilename expectedFilename = new GcsFilename("gcs bucket", "commit_diff_until_" + now);
assertWithMessage("GCS file not found: " + expectedFilename)
.that(gcsService.getMetadata(expectedFilename)).isNotNull();
assertThat(gcsService.getMetadata(expectedFilename).getOptions().getUserMetadata())
.containsExactly(
LOWER_BOUND_CHECKPOINT,
START_OF_TIME.toString(),
UPPER_BOUND_CHECKPOINT,
now.toString(),
NUM_TRANSACTIONS,
"3");
List<ImmutableObject> exported =
deserializeEntities(GcsTestingUtils.readGcsFile(gcsService, expectedFilename));
assertThat(exported.get(0)).isEqualTo(upperCheckpoint);
// We expect these manifests, in the order below, with matching mutations.
CommitLogManifest manifest1 = createManifest(1, START_OF_TIME.plusMillis(1));
CommitLogManifest manifest2 = createManifest(2, oneMinuteAgo);
CommitLogManifest manifest3 = createManifest(3, now);
assertThat(exported).containsExactly(
upperCheckpoint,
manifest1,
createMutation(manifest1),
manifest2,
createMutation(manifest2),
manifest3,
createMutation(manifest3))
.inOrder();
}
private CommitLogManifest createManifest(int bucketNum, DateTime commitTime) {
return CommitLogManifest.create(CommitLogBucket.getBucketKey(bucketNum), commitTime, null);
}
private CommitLogMutation createMutation(CommitLogManifest manifest) {
return CommitLogMutation.create(
Key.create(manifest),
TestObject.create(manifest.getCommitTime().toString()));
}
private void persistManifestAndMutation(int bucketNum, DateTime commitTime) {
persistResource(
createMutation(persistResource(createManifest(bucketNum, commitTime))));
}
}
| {
"pile_set_name": "Github"
} |
id: dsq-1426481263
date: 2014-06-08T23:12:54.0000000-07:00
name: jack
avatar: https://disqus.com/api/users/avatars/jack.jpg
message: <p>Would like (-:</p>
| {
"pile_set_name": "Github"
} |
//
// Concat.swift
// Rx
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class ConcatSink<S: SequenceType, O: ObserverType where S.Generator.Element : ObservableConvertibleType, S.Generator.Element.E == O.E>
: TailRecursiveSink<S, O>
, ObserverType {
typealias Element = O.E
override init(observer: O) {
super.init(observer: observer)
}
func on(event: Event<Element>){
switch event {
case .Next:
forwardOn(event)
case .Error:
forwardOn(event)
dispose()
case .Completed:
schedule(.MoveNext)
}
}
override func subscribeToNext(source: Observable<E>) -> Disposable {
return source.subscribe(self)
}
override func extract(observable: Observable<E>) -> SequenceGenerator? {
if let source = observable as? Concat<S> {
return (source._sources.generate(), source._count)
}
else {
return nil
}
}
}
class Concat<S: SequenceType where S.Generator.Element : ObservableConvertibleType> : Producer<S.Generator.Element.E> {
typealias Element = S.Generator.Element.E
private let _sources: S
private let _count: IntMax?
init(sources: S, count: IntMax?) {
_sources = sources
_count = count
}
override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable {
let sink = ConcatSink<S, O>(observer: observer)
sink.disposable = sink.run((_sources.generate(), _count))
return sink
}
} | {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ParameterizedBuiltinCPInstruction (SystemDS 2.0.0-SNAPSHOT API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ParameterizedBuiltinCPInstruction (SystemDS 2.0.0-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":9,"i1":10,"i2":10,"i3":10,"i4":10,"i5":9,"i6":10};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ParameterizedBuiltinCPInstruction.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/MultiReturnParameterizedBuiltinCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParamservBuiltinCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html" target="_top">Frames</a></li>
<li><a href="ParameterizedBuiltinCPInstruction.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.classes.inherited.from.class.org.apache.sysds.runtime.instructions.cp.CPInstruction">Nested</a> | </li>
<li><a href="#fields.inherited.from.class.org.apache.sysds.runtime.instructions.cp.ComputationCPInstruction">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.sysds.runtime.instructions.cp</div>
<h2 title="Class ParameterizedBuiltinCPInstruction" class="title">Class ParameterizedBuiltinCPInstruction</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html" title="class in org.apache.sysds.runtime.instructions">org.apache.sysds.runtime.instructions.Instruction</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">org.apache.sysds.runtime.instructions.cp.CPInstruction</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">org.apache.sysds.runtime.instructions.cp.ComputationCPInstruction</a></li>
<li>
<ul class="inheritance">
<li>org.apache.sysds.runtime.instructions.cp.ParameterizedBuiltinCPInstruction</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../../org/apache/sysds/runtime/lineage/LineageTraceable.html" title="interface in org.apache.sysds.runtime.lineage">LineageTraceable</a></dd>
</dl>
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParamservBuiltinCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">ParamservBuiltinCPInstruction</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">ParameterizedBuiltinCPInstruction</span>
extends <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">ComputationCPInstruction</a></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested.class.summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested.classes.inherited.from.class.org.apache.sysds.runtime.instructions.cp.CPInstruction">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from class org.apache.sysds.runtime.instructions.cp.<a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">CPInstruction</a></h3>
<code><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.CPType.html" title="enum in org.apache.sysds.runtime.instructions.cp">CPInstruction.CPType</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="nested.classes.inherited.from.class.org.apache.sysds.runtime.instructions.Instruction">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from class org.apache.sysds.runtime.instructions.<a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html" title="class in org.apache.sysds.runtime.instructions">Instruction</a></h3>
<code><a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.IType.html" title="enum in org.apache.sysds.runtime.instructions">Instruction.IType</a></code></li>
</ul>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields.inherited.from.class.org.apache.sysds.runtime.instructions.cp.ComputationCPInstruction">
<!-- -->
</a>
<h3>Fields inherited from class org.apache.sysds.runtime.instructions.cp.<a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">ComputationCPInstruction</a></h3>
<code><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html#input1">input1</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html#input2">input2</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html#input3">input3</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html#output">output</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="fields.inherited.from.class.org.apache.sysds.runtime.instructions.Instruction">
<!-- -->
</a>
<h3>Fields inherited from class org.apache.sysds.runtime.instructions.<a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html" title="class in org.apache.sysds.runtime.instructions">Instruction</a></h3>
<code><a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#DATATYPE_PREFIX">DATATYPE_PREFIX</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#FEDERATED_INST_PREFIX">FEDERATED_INST_PREFIX</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#GPU_INST_PREFIX">GPU_INST_PREFIX</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#INSTRUCTION_DELIM">INSTRUCTION_DELIM</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#LITERAL_PREFIX">LITERAL_PREFIX</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#OPERAND_DELIM">OPERAND_DELIM</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#SP_INST_PREFIX">SP_INST_PREFIX</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#VALUETYPE_PREFIX">VALUETYPE_PREFIX</a></code></li>
</ul>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static <a href="https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html?is-external=true" title="class or interface in java.util">LinkedHashMap</a><<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html#constructParameterMap-java.lang.String:A-">constructParameterMap</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[] params)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>org.apache.commons.lang3.tuple.Pair<<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="../../../../../../org/apache/sysds/runtime/lineage/LineageItem.html" title="class in org.apache.sysds.runtime.lineage">LineageItem</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html#getLineageItem-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">getLineageItem</a></span>(<a href="../../../../../../org/apache/sysds/runtime/controlprogram/context/ExecutionContext.html" title="class in org.apache.sysds.runtime.controlprogram.context">ExecutionContext</a> ec)</code>
<div class="block">Obtain lineage trace of an instruction with a single output.</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html#getParam-java.lang.String-">getParam</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> key)</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html?is-external=true" title="class or interface in java.util">HashMap</a><<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html#getParameterMap--">getParameterMap</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/sysds/runtime/controlprogram/caching/CacheableData.html" title="class in org.apache.sysds.runtime.controlprogram.caching">CacheableData</a><?></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html#getTarget-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">getTarget</a></span>(<a href="../../../../../../org/apache/sysds/runtime/controlprogram/context/ExecutionContext.html" title="class in org.apache.sysds.runtime.controlprogram.context">ExecutionContext</a> ec)</code> </td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">ParameterizedBuiltinCPInstruction</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html#parseInstruction-java.lang.String-">parseInstruction</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> str)</code> </td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html#processInstruction-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">processInstruction</a></span>(<a href="../../../../../../org/apache/sysds/runtime/controlprogram/context/ExecutionContext.html" title="class in org.apache.sysds.runtime.controlprogram.context">ExecutionContext</a> ec)</code>
<div class="block">This method should be used to execute the instruction.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.org.apache.sysds.runtime.instructions.cp.ComputationCPInstruction">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.sysds.runtime.instructions.cp.<a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">ComputationCPInstruction</a></h3>
<code><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html#getInputs--">getInputs</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html#getOutput--">getOutput</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html#getOutputVariableName--">getOutputVariableName</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.org.apache.sysds.runtime.instructions.cp.CPInstruction">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.sysds.runtime.instructions.cp.<a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">CPInstruction</a></h3>
<code><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html#getCPInstructionType--">getCPInstructionType</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html#getGraphString--">getGraphString</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html#getType--">getType</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html#preprocessInstruction-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">preprocessInstruction</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html#requiresLabelUpdate--">requiresLabelUpdate</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html#updateLabels-java.lang.String-org.apache.sysds.runtime.controlprogram.LocalVariableMap-">updateLabels</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.org.apache.sysds.runtime.instructions.Instruction">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.sysds.runtime.instructions.<a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html" title="class in org.apache.sysds.runtime.instructions">Instruction</a></h3>
<code><a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getBeginColumn--">getBeginColumn</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getBeginLine--">getBeginLine</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getEndColumn--">getEndColumn</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getEndLine--">getEndLine</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getExtendedOpcode--">getExtendedOpcode</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getFilename--">getFilename</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getInstID--">getInstID</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getInstructionString--">getInstructionString</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getLineNum--">getLineNum</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getOpcode--">getOpcode</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getOperator--">getOperator</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#getPrivacyConstraint--">getPrivacyConstraint</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#postprocessInstruction-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">postprocessInstruction</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#printMe--">printMe</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#setInstID-long-">setInstID</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#setLocation-org.apache.sysds.parser.DataIdentifier-">setLocation</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#setLocation-org.apache.sysds.runtime.instructions.Instruction-">setLocation</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#setLocation-org.apache.sysds.lops.Lop-">setLocation</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#setLocation-java.lang.String-int-int-int-int-">setLocation</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#setPrivacyConstraint-org.apache.sysds.lops.Lop-">setPrivacyConstraint</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#setPrivacyConstraint-org.apache.sysds.runtime.privacy.PrivacyConstraint-">setPrivacyConstraint</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#toString--">toString</a>, <a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#updateInstructionThreadID-java.lang.String-java.lang.String-">updateInstructionThreadID</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></h3>
<code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#equals-java.lang.Object-" title="class or interface in java.lang">equals</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#getClass--" title="class or interface in java.lang">getClass</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#hashCode--" title="class or interface in java.lang">hashCode</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#notify--" title="class or interface in java.lang">notify</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#notifyAll--" title="class or interface in java.lang">notifyAll</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#wait--" title="class or interface in java.lang">wait</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#wait-long-" title="class or interface in java.lang">wait</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true#wait-long-int-" title="class or interface in java.lang">wait</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.org.apache.sysds.runtime.lineage.LineageTraceable">
<!-- -->
</a>
<h3>Methods inherited from interface org.apache.sysds.runtime.lineage.<a href="../../../../../../org/apache/sysds/runtime/lineage/LineageTraceable.html" title="interface in org.apache.sysds.runtime.lineage">LineageTraceable</a></h3>
<code><a href="../../../../../../org/apache/sysds/runtime/lineage/LineageTraceable.html#getLineageItems-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">getLineageItems</a>, <a href="../../../../../../org/apache/sysds/runtime/lineage/LineageTraceable.html#hasSingleLineage--">hasSingleLineage</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getParameterMap--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getParameterMap</h4>
<pre>public <a href="https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html?is-external=true" title="class or interface in java.util">HashMap</a><<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>> getParameterMap()</pre>
</li>
</ul>
<a name="getParam-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getParam</h4>
<pre>public <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> getParam(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> key)</pre>
</li>
</ul>
<a name="constructParameterMap-java.lang.String:A-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>constructParameterMap</h4>
<pre>public static <a href="https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html?is-external=true" title="class or interface in java.util">LinkedHashMap</a><<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>> constructParameterMap(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>[] params)</pre>
</li>
</ul>
<a name="parseInstruction-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>parseInstruction</h4>
<pre>public static <a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">ParameterizedBuiltinCPInstruction</a> parseInstruction(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> str)</pre>
</li>
</ul>
<a name="processInstruction-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>processInstruction</h4>
<pre>public void processInstruction(<a href="../../../../../../org/apache/sysds/runtime/controlprogram/context/ExecutionContext.html" title="class in org.apache.sysds.runtime.controlprogram.context">ExecutionContext</a> ec)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from class: <code><a href="../../../../../../org/apache/sysds/runtime/instructions/Instruction.html#processInstruction-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">Instruction</a></code></span></div>
<div class="block">This method should be used to execute the instruction.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html#processInstruction-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">processInstruction</a></code> in class <code><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/CPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">CPInstruction</a></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ec</code> - execution context</dd>
</dl>
</li>
</ul>
<a name="getLineageItem-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getLineageItem</h4>
<pre>public org.apache.commons.lang3.tuple.Pair<<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="../../../../../../org/apache/sysds/runtime/lineage/LineageItem.html" title="class in org.apache.sysds.runtime.lineage">LineageItem</a>> getLineageItem(<a href="../../../../../../org/apache/sysds/runtime/controlprogram/context/ExecutionContext.html" title="class in org.apache.sysds.runtime.controlprogram.context">ExecutionContext</a> ec)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from interface: <code><a href="../../../../../../org/apache/sysds/runtime/lineage/LineageTraceable.html#getLineageItem-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">LineageTraceable</a></code></span></div>
<div class="block">Obtain lineage trace of an instruction with a single output.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../../../../org/apache/sysds/runtime/lineage/LineageTraceable.html#getLineageItem-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">getLineageItem</a></code> in interface <code><a href="../../../../../../org/apache/sysds/runtime/lineage/LineageTraceable.html" title="interface in org.apache.sysds.runtime.lineage">LineageTraceable</a></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html#getLineageItem-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">getLineageItem</a></code> in class <code><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ComputationCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp">ComputationCPInstruction</a></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>ec</code> - execution context w/ live variables</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>pair of (output variable name, output lineage item)</dd>
</dl>
</li>
</ul>
<a name="getTarget-org.apache.sysds.runtime.controlprogram.context.ExecutionContext-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getTarget</h4>
<pre>public <a href="../../../../../../org/apache/sysds/runtime/controlprogram/caching/CacheableData.html" title="class in org.apache.sysds.runtime.controlprogram.caching">CacheableData</a><?> getTarget(<a href="../../../../../../org/apache/sysds/runtime/controlprogram/context/ExecutionContext.html" title="class in org.apache.sysds.runtime.controlprogram.context">ExecutionContext</a> ec)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ParameterizedBuiltinCPInstruction.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/MultiReturnParameterizedBuiltinCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../org/apache/sysds/runtime/instructions/cp/ParamservBuiltinCPInstruction.html" title="class in org.apache.sysds.runtime.instructions.cp"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.html" target="_top">Frames</a></li>
<li><a href="ParameterizedBuiltinCPInstruction.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested.classes.inherited.from.class.org.apache.sysds.runtime.instructions.cp.CPInstruction">Nested</a> | </li>
<li><a href="#fields.inherited.from.class.org.apache.sysds.runtime.instructions.cp.ComputationCPInstruction">Field</a> | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="https://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
#ifndef _XT_MARK_H_target
#define _XT_MARK_H_target
#include <linux/netfilter/xt_mark.h>
#endif /*_XT_MARK_H_target */
| {
"pile_set_name": "Github"
} |
import { get, uniqBy, groupBy, sortBy, mapValues } from 'lodash';
import {
HUNTER,
TITAN,
WARLOCK,
WEAPON,
ARMOR,
GHOST,
GHOST_PROJECTION,
EMOTES,
SHIP,
SPARROW,
EMBLEM,
SHADER,
HELMET,
ARMS,
CHEST,
LEGS,
CLASS_ITEM,
ARMOR_MODS_ORNAMENTS,
WEAPON_MODS_ORNAMENTS,
ARMOR_MODS_ORNAMENTS_HUNTER,
ARMOR_MODS_ORNAMENTS_TITAN,
ARMOR_MODS_ORNAMENTS_WARLOCK,
EXOTIC,
LEGENDARY,
UNCOMMON,
RARE,
COMMON
} from 'app/lib/destinyEnums';
const tierTypeNameValue = {
Common: 4,
Uncommon: 3,
Rare: 2,
Legendary: 1,
Exotic: 0
};
export const isArmorOrnament = item =>
item.itemCategoryHashes &&
item.itemCategoryHashes.includes(ARMOR_MODS_ORNAMENTS);
const RARITY_SCORE = {
[EXOTIC]: 100,
[LEGENDARY]: 1000,
[UNCOMMON]: 10000,
[RARE]: 100000,
[COMMON]: 1000000
};
function scoreItem(item) {
const plugCategoryIdentifier = get(item, 'plug.plugCategoryIdentifier');
if (isArmorOrnament(item) && plugCategoryIdentifier) {
if (plugCategoryIdentifier.includes('head')) {
return 1;
} else if (plugCategoryIdentifier.includes('arms')) {
return 2;
} else if (plugCategoryIdentifier.includes('chest')) {
return 3;
} else if (plugCategoryIdentifier.includes('legs')) {
return 4;
} else if (plugCategoryIdentifier.includes('class')) {
return 5;
}
}
if (item.itemCategoryHashes.includes(HELMET)) {
return 1;
} else if (item.itemCategoryHashes.includes(ARMS)) {
return 2;
} else if (item.itemCategoryHashes.includes(CHEST)) {
return 3;
} else if (item.itemCategoryHashes.includes(LEGS)) {
return 4;
} else if (item.itemCategoryHashes.includes(CLASS_ITEM)) {
return 5;
}
}
function sortArmor(items) {
return sortBy(items, item => {
const rarity = RARITY_SCORE[item.inventory.tierTypeHash] || 0;
return rarity + scoreItem(item);
});
}
const isCategory = (item, category) =>
item.itemCategoryHashes.includes(category);
export default function sortItems(_items, verbose = false) {
const items = uniqBy(_items, item => item.hash);
const _sectionItems = groupBy(items, item => {
if (item.itemCategoryHashes.includes(ARMOR_MODS_ORNAMENTS)) {
if (isCategory(item, ARMOR_MODS_ORNAMENTS_TITAN)) {
return ARMOR_MODS_ORNAMENTS_TITAN;
} else if (isCategory(item, ARMOR_MODS_ORNAMENTS_WARLOCK)) {
return ARMOR_MODS_ORNAMENTS_WARLOCK;
} else if (isCategory(item, ARMOR_MODS_ORNAMENTS_HUNTER)) {
return ARMOR_MODS_ORNAMENTS_HUNTER;
}
} else if (item.itemCategoryHashes.includes(WEAPON)) {
return 'weapon';
} else if (item.itemCategoryHashes.includes(GHOST)) {
return 'ghosts';
} else if (item.itemCategoryHashes.includes(GHOST_PROJECTION)) {
return 'ghostProjections';
} else if (item.itemCategoryHashes.includes(EMOTES)) {
return 'emotes';
} else if (item.itemCategoryHashes.includes(SHIP)) {
return 'ships';
} else if (item.itemCategoryHashes.includes(SPARROW)) {
return 'sparrows';
} else if (item.itemCategoryHashes.includes(EMBLEM)) {
return 'emblems';
} else if (item.itemCategoryHashes.includes(SHADER)) {
return 'shaders';
} else if (item.itemCategoryHashes.includes(ARMOR)) {
return item.classType;
} else if (item.itemCategoryHashes.includes(WEAPON_MODS_ORNAMENTS)) {
return 'weaponOrnaments';
} else {
return 'other';
}
});
const sectionItems = mapValues(_sectionItems, items => {
return sortBy(items, item => {
return tierTypeNameValue[item.inventory.tierTypeName];
});
});
const sections = [
{ name: 'Weapons', items: sectionItems.weapon },
{ name: 'Hunter armor', items: sortArmor(sectionItems[HUNTER]) },
{
name: 'Hunter ornaments',
items: sortArmor(sectionItems[ARMOR_MODS_ORNAMENTS_HUNTER])
},
{ name: 'Titan armor', items: sortArmor(sectionItems[TITAN]) },
{
name: 'Titan ornaments',
items: sortArmor(sectionItems[ARMOR_MODS_ORNAMENTS_TITAN])
},
{ name: 'Warlock armor', items: sortArmor(sectionItems[WARLOCK]) },
{
name: 'Warlock ornaments',
items: sortArmor(sectionItems[ARMOR_MODS_ORNAMENTS_WARLOCK])
},
{ name: 'Emotes', items: sectionItems.emotes },
{ name: 'Ghosts', items: sectionItems.ghosts },
{ name: 'Ghost Projections', items: sectionItems.ghostProjections },
{ name: 'Ships', items: sectionItems.ships },
{ name: 'Sparrows', items: sectionItems.sparrows },
{ name: 'Emblems', items: sectionItems.emblems },
{ name: 'Shaders', items: sectionItems.shaders },
{ name: 'Weapon Ornaments', items: sectionItems.weaponOrnaments },
{ name: 'Other', items: sectionItems.other }
]
.filter(({ items }) => {
return items && items.length > 0;
})
.map(section => {
if (verbose) {
return section;
}
const items = section.items.map(item => item.hash);
return {
...section,
items
};
});
return sections;
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved.
#include <algorithm>
#include <cassert>
#include <iostream>
#include <random>
#include <string>
#include <unordered_map>
using std::boolalpha;
using std::cout;
using std::default_random_engine;
using std::endl;
using std::random_device;
using std::string;
using std::uniform_int_distribution;
using std::unordered_map;
using std::vector;
string RandString(int len) {
string ret;
default_random_engine gen((random_device())());
while (len--) {
uniform_int_distribution<int> dis(0, 26);
int x = dis(gen);
ret += (x < 26) ? 'a' + x : ' ';
}
return ret;
}
// @include
bool IsLetterConstructibleFromMagazine(const string& letter_text,
const string& magazine_text) {
unordered_map<char, int> char_frequency_for_letter;
// Compute the frequencies for all chars in letter_text.
for (char c : letter_text) {
++char_frequency_for_letter[c];
}
// Check if the characters in magazine_text can cover characters
// in char_frequency_for_letter.
for (char c : magazine_text) {
auto it = char_frequency_for_letter.find(c);
if (it != char_frequency_for_letter.cend()) {
--it->second;
if (it->second == 0) {
char_frequency_for_letter.erase(it);
if (char_frequency_for_letter.empty()) {
// All characters for letter_text are matched.
break;
}
}
}
}
// Empty char_frequency_for_letter means every char in letter_text can be
// covered by a character in magazine_text.
return char_frequency_for_letter.empty();
}
// @exclude
void SimpleTest() {
assert(!IsLetterConstructibleFromMagazine("123", "456"));
assert(!IsLetterConstructibleFromMagazine("123", "12222222"));
assert(IsLetterConstructibleFromMagazine("123", "1123"));
assert(IsLetterConstructibleFromMagazine("123", "123"));
assert(!IsLetterConstructibleFromMagazine("12323", "123"));
assert(
IsLetterConstructibleFromMagazine("GATTACA", "A AD FS GA T ACA TTT"));
assert(!IsLetterConstructibleFromMagazine("a", ""));
assert(IsLetterConstructibleFromMagazine("aa", "aa"));
assert(IsLetterConstructibleFromMagazine("aa", "aaa"));
assert(IsLetterConstructibleFromMagazine("", "123"));
assert(IsLetterConstructibleFromMagazine("", ""));
}
int main(int argc, char* argv[]) {
SimpleTest();
default_random_engine gen((random_device())());
string L, M;
if (argc == 3) {
L = argv[1], M = argv[2];
} else {
uniform_int_distribution<int> L_dis(1, 1000);
uniform_int_distribution<int> M_dis(1, 100000);
L = RandString(L_dis(gen)), M = RandString(M_dis(gen));
}
cout << L << endl;
cout << M << endl;
cout << boolalpha << IsLetterConstructibleFromMagazine(L, M) << endl;
return 0;
}
| {
"pile_set_name": "Github"
} |
using System;
using DiffEngine;
namespace Shouldly.Configuration
{
public delegate string FilenameGenerator(
TestMethodInfo testMethodInfo, string? discriminator, string fileType, string fileExtension);
public class ShouldMatchConfiguration
{
public ShouldMatchConfiguration()
{
}
public ShouldMatchConfiguration(ShouldMatchConfiguration initialConfig)
{
StringCompareOptions = initialConfig.StringCompareOptions;
FilenameDiscriminator = initialConfig.FilenameDiscriminator;
PreventDiff = initialConfig.PreventDiff;
FileExtension = initialConfig.FileExtension;
TestMethodFinder = initialConfig.TestMethodFinder;
ApprovalFileSubFolder = initialConfig.ApprovalFileSubFolder;
Scrubber = initialConfig.Scrubber;
FilenameGenerator = initialConfig.FilenameGenerator;
}
public StringCompareShould StringCompareOptions { get; set; } = StringCompareShould.IgnoreLineEndings;
public string? FilenameDiscriminator { get; set; }
public bool PreventDiff { get; set; } = DiffRunner.Disabled;
/// <summary>
/// File extension without the.
/// </summary>
public string FileExtension { get; set; } = "txt";
public ITestMethodFinder TestMethodFinder { get; set; } = new FirstNonShouldlyMethodFinder();
public string? ApprovalFileSubFolder { get; set; }
/// <summary>
/// Scrubbers allow you to alter the received document before comparing it to approved.
///
/// This is useful for replacing dates or dynamic data with fixed data
/// </summary>
public Func<string, string>? Scrubber { get; set; }
public FilenameGenerator FilenameGenerator { get; set; } =
(testMethodInfo, discriminator, type, extension)
=> $"{testMethodInfo.DeclaringTypeName}.{testMethodInfo.MethodName}{discriminator}.{type}.{extension}";
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Short description for file.
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Fixture
* @since CakePHP(tm) v 1.2.0.6879//Correct version number as needed**
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Short description for file.
*
* @package Cake.Test.Fixture
* @since CakePHP(tm) v 1.2.0.6879//Correct version number as needed**
*/
class DependencyFixture extends CakeTestFixture {
/**
* fields property
*
* @var array
*/
public $fields = array(
'id' => 'integer',
'child_id' => 'integer',
'parent_id' => 'integer'
);
/**
* records property
*
* @var array
*/
public $records = array(
array('id' => 1, 'child_id' => 1, 'parent_id' => 2),
);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.history;
import org.camunda.bpm.engine.exception.NotValidException;
import org.camunda.bpm.engine.query.Query;
/**
* Defines a report query for cleanable case instances.
*
*/
public interface CleanableHistoricCaseInstanceReport extends Query<CleanableHistoricCaseInstanceReport, CleanableHistoricCaseInstanceReportResult> {
/**
* Only takes historic case instances into account for the given case definition ids.
*
* @throws NotValidException if one of the given ids is null
*/
CleanableHistoricCaseInstanceReport caseDefinitionIdIn(String... caseDefinitionIds);
/**
* Only takes historic case instances into account for the given case definition keys.
*
* @throws NotValidException if one of the given keys is null
*/
CleanableHistoricCaseInstanceReport caseDefinitionKeyIn(String... caseDefinitionKeys);
/**
* Only select historic case instances with one of the given tenant ids.
*
* @throws NotValidException if one of the given ids is null
*/
CleanableHistoricCaseInstanceReport tenantIdIn(String... tenantIds);
/**
* Only selects historic case instances which have no tenant id.
*/
CleanableHistoricCaseInstanceReport withoutTenantId();
/**
* Only selects historic case instances which have more than zero finished instances.
*/
CleanableHistoricCaseInstanceReport compact();
/**
* Order by finished case instances amount (needs to be followed by {@link #asc()} or {@link #desc()}).
*/
CleanableHistoricCaseInstanceReport orderByFinished();
}
| {
"pile_set_name": "Github"
} |
#!/bin/sh
export RAILS_ENV=production
cd /app/db && exec bundle exec ridgepole -c ../config/database.yml -E production --file Schemafile -a
| {
"pile_set_name": "Github"
} |
/*
* HaoRan ImageFilter Classes v0.1
* Copyright (C) 2012 Zhenjun Dai
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation.
*/
package com.marshalchen.common.uimodule.ImageFilter;
public class OldPhotoFilter implements IImageFilter{
private GaussianBlurFilter blurFx;
private NoiseFilter noiseFx;
private VignetteFilter vignetteFx;
private GradientMapFilter gradientFx;
public OldPhotoFilter(){
blurFx = new GaussianBlurFilter();
blurFx.Sigma = 0.3f;
noiseFx = new NoiseFilter();
noiseFx.Intensity = 0.03f;
vignetteFx = new VignetteFilter();
vignetteFx.Size = 0.6f;
gradientFx = new GradientMapFilter();
gradientFx.ContrastFactor = 0.3f;
}
//@Override
public Image process(Image imageIn) {
imageIn = this.noiseFx.process(this.blurFx.process(imageIn));
imageIn = this.gradientFx.process(imageIn);
return this.vignetteFx.process(imageIn);
}
}
| {
"pile_set_name": "Github"
} |
// ***********************************************************************
// Assembly : XLabs.Forms.Droid
// Author : XLabs Team
// Created : 12-27-2015
//
// Last Modified By : XLabs Team
// Last Modified On : 01-04-2016
// ***********************************************************************
// <copyright file="CalendarPickerView.cs" company="XLabs Team">
// Copyright (c) XLabs Team. All rights reserved.
// </copyright>
// <summary>
// This project is licensed under the Apache 2.0 license
// https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE
//
// XLabs is a open source project that aims to provide a powerfull and cross
// platform set of controls tailored to work with Xamarin Forms.
// </summary>
// ***********************************************************************
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Android.Content;
using Android.Runtime;
using Android.Support.V4.View;
using Android.Util;
using Android.Widget;
using Java.Lang;
using XLabs.Forms.Droid;
namespace XLabs.Forms.Controls.MonoDroid.TimesSquare
{
/// <summary>
/// Class CalendarPickerView.
/// </summary>
public class CalendarPickerView : ViewPager
{
/// <summary>
/// Enum SelectionMode
/// </summary>
public enum SelectionMode
{
/// <summary>
/// The single
/// </summary>
Single,
/// <summary>
/// The multi
/// </summary>
Multi,
/// <summary>
/// The range
/// </summary>
Range}
;
/// <summary>
/// Class OnPageChangeListener.
/// </summary>
internal class OnPageChangeListener : SimpleOnPageChangeListener
{
/// <summary>
/// The _picker
/// </summary>
CalendarPickerView _picker;
/// <summary>
/// Initializes a new instance of the <see cref="OnPageChangeListener"/> class.
/// </summary>
/// <param name="picker">The picker.</param>
public OnPageChangeListener(CalendarPickerView picker)
{
this._picker = picker;
}
/// <summary>
/// Called when [page selected].
/// </summary>
/// <param name="position">The position.</param>
public override void OnPageSelected(int position)
{
_picker.InvokeOnMonthChanged(position);
//base.OnPageSelected(position);
}
}
/// <summary>
/// The _context
/// </summary>
private readonly Context _context;
/// <summary>
/// My adapter
/// </summary>
internal readonly MonthAdapter MyAdapter;
/// <summary>
/// The months
/// </summary>
internal readonly List<MonthDescriptor> Months = new List<MonthDescriptor>();
/// <summary>
/// The cells
/// </summary>
internal readonly List<List<List<MonthCellDescriptor>>> Cells =
new List<List<List<MonthCellDescriptor>>>();
/// <summary>
/// The selected cells
/// </summary>
internal List<MonthCellDescriptor> SelectedCells = new List<MonthCellDescriptor>();
/// <summary>
/// The _highlighted cells
/// </summary>
private readonly List<MonthCellDescriptor> _highlightedCells = new List<MonthCellDescriptor>();
/// <summary>
/// The selected cals
/// </summary>
internal List<DateTime> SelectedCals = new List<DateTime>();
/// <summary>
/// The _highlighted cals
/// </summary>
private readonly List<DateTime> _highlightedCals = new List<DateTime>();
/// <summary>
/// The today
/// </summary>
internal readonly DateTime Today = DateTime.Now;
/// <summary>
/// The minimum date
/// </summary>
internal DateTime MinDate;
/// <summary>
/// The maximum date
/// </summary>
internal DateTime MaxDate;
/// <summary>
/// The _month counter
/// </summary>
private DateTime _monthCounter;
//This provides styling to the calendar elements
//Elements holds reference to it through Month and Week cell descriptors
/// <summary>
/// The _style descriptor
/// </summary>
private StyleDescriptor _styleDescriptor;
/// <summary>
/// Gets the style descriptor.
/// </summary>
/// <value>The style descriptor.</value>
public StyleDescriptor StyleDescriptor {
get {
return _styleDescriptor;
}
}
/// <summary>
/// The month name format
/// </summary>
internal readonly string MonthNameFormat;
/// <summary>
/// The weekday name format
/// </summary>
internal readonly string WeekdayNameFormat;
/// <summary>
/// The full date format
/// </summary>
internal readonly string FullDateFormat;
/// <summary>
/// The click handler
/// </summary>
internal ClickHandler ClickHandler;
/// <summary>
/// Occurs when [on invalid date selected].
/// </summary>
public event EventHandler<DateSelectedEventArgs> OnInvalidDateSelected;
/// <summary>
/// Occurs when [on date selected].
/// </summary>
public event EventHandler<DateSelectedEventArgs> OnDateSelected;
/// <summary>
/// Occurs when [on date unselected].
/// </summary>
public event EventHandler<DateSelectedEventArgs> OnDateUnselected;
/// <summary>
/// Occurs when [on month changed].
/// </summary>
public event EventHandler<MonthChangedEventArgs> OnMonthChanged;
/// <summary>
/// Occurs when [on date selectable].
/// </summary>
public event DateSelectableHandler OnDateSelectable;
/// <summary>
/// Gets or sets the mode.
/// </summary>
/// <value>The mode.</value>
public SelectionMode Mode { get; set; }
/// <summary>
/// Gets the current month.
/// </summary>
/// <value>The current month.</value>
public DateTime CurrentMonth {
get {
return this.Months[this.CurrentItem].Date;
}
}
/// <summary>
/// Gets the month count.
/// </summary>
/// <value>The month count.</value>
public int MonthCount {
get {
return this.Months.Count;
}
}
/// <summary>
/// Invokes the on month changed.
/// </summary>
/// <param name="position">The position.</param>
protected void InvokeOnMonthChanged(int position)
{
if(this.OnMonthChanged != null) {
var month = this.Months[position];
this.OnMonthChanged(this, new MonthChangedEventArgs(month.Date));
}
}
/// <summary>
/// Gets the selected date.
/// </summary>
/// <value>The selected date.</value>
public DateTime SelectedDate {
get { return SelectedCals.Count > 0 ? SelectedCals[0] : DateTime.MinValue; }
}
/// <summary>
/// Gets the selected dates.
/// </summary>
/// <value>The selected dates.</value>
public List<DateTime> SelectedDates {
get {
var selectedDates = SelectedCells.Select(cal => cal.DateTime).ToList();
selectedDates.Sort();
return selectedDates;
}
}
/**
* Forces a redraw of the calendar and thus applying of the styles
*/
/// <summary>
/// Updates the styles.
/// </summary>
public void UpdateStyles()
{
base.SetBackgroundColor(_styleDescriptor.BackgroundColor);
Adapter.NotifyDataSetChanged();
}
/// <summary>
/// The _hlighlighted days of week
/// </summary>
Dictionary<int, bool> _hlighlightedDaysOfWeek;
/// <summary>
/// Initializes a new instance of the <see cref="CalendarPickerView"/> class.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="attrs">The attrs.</param>
public CalendarPickerView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
ResourceIdManager.UpdateIdValues();
_context = context;
_styleDescriptor = new StyleDescriptor();
MyAdapter = new MonthAdapter(context, this);
base.Adapter = MyAdapter;
//base.Divider = null;
//base.DividerHeight = 0;
this.PageMargin = 32;
SetPadding(0, 0, 0, 0);
//Sometimes dates could not be selected after the transform. I had to disable it. :(
//SetPageTransformer(true, new CalendarMonthPageTransformer());
var bgColor = base.Resources.GetColor(Resource.Color.calendar_bg);
base.SetBackgroundColor(bgColor);
//base.CacheColorHint = bgColor;
MonthNameFormat = base.Resources.GetString(Resource.String.month_name_format);
WeekdayNameFormat = base.Resources.GetString(Resource.String.day_name_format);
FullDateFormat = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern;
ClickHandler += OnCellClicked;
OnInvalidDateSelected += OnInvalidateDateClicked;
this.SetOnPageChangeListener(new OnPageChangeListener(this));
if(base.IsInEditMode) {
Init(DateTime.Now, DateTime.Now.AddYears(1), new DayOfWeek[]{ }).WithSelectedDate(DateTime.Now);
}
}
/// <summary>
/// Called when [cell clicked].
/// </summary>
/// <param name="cell">The cell.</param>
private void OnCellClicked(MonthCellDescriptor cell)
{
var clickedDate = cell.DateTime;
if(!IsBetweenDates(clickedDate, MinDate, MaxDate) || !IsSelectable(clickedDate)) {
if(OnInvalidDateSelected != null) {
OnInvalidDateSelected(this, new DateSelectedEventArgs(clickedDate));
}
} else {
bool wasSelected = DoSelectDate(clickedDate, cell);
if(OnDateSelected != null) {
if(wasSelected) {
OnDateSelected(this, new DateSelectedEventArgs(clickedDate));
} else if(OnDateUnselected != null) {
OnDateUnselected(this, new DateSelectedEventArgs(clickedDate));
}
}
}
}
/// <summary>
/// Handles the <see cref="E:InvalidateDateClicked" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="DateSelectedEventArgs"/> instance containing the event data.</param>
private void OnInvalidateDateClicked(object sender, DateSelectedEventArgs e)
{
string fullDateFormat = _context.Resources.GetString(Resource.String.full_date_format);
string errorMsg = _context.Resources.GetString(Resource.String.invalid_date);
errorMsg = string.Format(errorMsg, MinDate.ToString(fullDateFormat),
MaxDate.ToString(fullDateFormat));
Toast.MakeText(_context, errorMsg, ToastLength.Short).Show();
}
/// <summary>
/// Initializes the specified minimum date.
/// </summary>
/// <param name="minDate">The minimum date.</param>
/// <param name="maxDate">The maximum date.</param>
/// <param name="highlightedDaysOfWeek">The highlighted days of week.</param>
/// <returns>FluentInitializer.</returns>
/// <exception cref="Java.Lang.IllegalArgumentException">
/// minDate and maxDate must be non-zero. +
/// Debug(minDate, maxDate)
/// or
/// minDate must be before maxDate. +
/// Debug(minDate, maxDate)
/// </exception>
public FluentInitializer Init(DateTime minDate, DateTime maxDate, DayOfWeek[] highlightedDaysOfWeek)
{
if(minDate == DateTime.MinValue || maxDate == DateTime.MinValue) {
throw new IllegalArgumentException("minDate and maxDate must be non-zero. " +
Debug(minDate, maxDate));
}
if(minDate.CompareTo(maxDate) > 0) {
throw new IllegalArgumentException("minDate must be before maxDate. " +
Debug(minDate, maxDate));
}
HighlighDaysOfWeeks(highlightedDaysOfWeek);
Mode = SelectionMode.Single;
//Clear out any previously selected dates/cells.
SelectedCals.Clear();
SelectedCells.Clear();
_highlightedCals.Clear();
_highlightedCells.Clear();
//Clear previous state.
Cells.Clear();
Months.Clear();
MinDate = minDate;
MaxDate = maxDate;
MinDate = SetMidnight(MinDate);
MaxDate = SetMidnight(MaxDate);
// maxDate is exclusive: bump back to the previous day so if maxDate is the first of a month,
// We don't accidentally include that month in the view.
if(MaxDate.Day == 1) {
MaxDate = MaxDate.AddMinutes(-1);
}
//Now iterate between minCal and maxCal and build up our list of months to show.
_monthCounter = MinDate;
int maxMonth = MaxDate.Month;
int maxYear = MaxDate.Year;
while((_monthCounter.Month <= maxMonth
|| _monthCounter.Year < maxYear)
&& _monthCounter.Year < maxYear + 1) {
var month = new MonthDescriptor(_monthCounter.Month, _monthCounter.Year, _monthCounter,
_monthCounter.ToString(MonthNameFormat), _styleDescriptor);
Cells.Add(GetMonthCells(month, _monthCounter));
Logr.D("Adding month {0}", month);
Months.Add(month);
_monthCounter = _monthCounter.AddMonths(1);
}
ValidateAndUpdate();
return new FluentInitializer(this);
}
/// <summary>
/// Highlighes the days of weeks.
/// </summary>
/// <param name="daysOfWeeks">The days of weeks.</param>
public void HighlighDaysOfWeeks(DayOfWeek[] daysOfWeeks)
{
_hlighlightedDaysOfWeek = new Dictionary<int,bool>();
for(int i = 0; i <= 6; i++) {
_hlighlightedDaysOfWeek[i] = false;
}
foreach(var dOw in daysOfWeeks) {
_hlighlightedDaysOfWeek[(int)dOw] = true;
}
}
/// <summary>
/// Gets the month cells.
/// </summary>
/// <param name="month">The month.</param>
/// <param name="startCal">The start cal.</param>
/// <returns>List<List<MonthCellDescriptor>>.</returns>
internal List<List<MonthCellDescriptor>> GetMonthCells(MonthDescriptor month, DateTime startCal)
{
var cells = new List<List<MonthCellDescriptor>>();
var cal = new DateTime(startCal.Year, startCal.Month, 1);
var firstDayOfWeek = (int)cal.DayOfWeek;
cal = cal.AddDays((int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - firstDayOfWeek);
var minSelectedCal = GetMinDate(SelectedCals);
var maxSelectedCal = GetMaxDate(SelectedCals);
while((cal.Month < month.Month + 1 || cal.Year < month.Year)
&& cal.Year <= month.Year) {
Logr.D("Building week row starting at {0}", cal);
var weekCells = new List<MonthCellDescriptor>();
cells.Add(weekCells);
for(int i = 0; i < 7; i++) {
var date = cal;
bool isCurrentMonth = cal.Month == month.Month;
bool isSelected = isCurrentMonth && ContatinsDate(SelectedCals, cal);
bool isSelectable = isCurrentMonth && IsBetweenDates(cal, MinDate, MaxDate);
bool isToday = IsSameDate(cal, Today);
bool isHighlighted = ContatinsDate(_highlightedCals, cal) || _hlighlightedDaysOfWeek[(int)cal.DayOfWeek];
int value = cal.Day;
var rangeState = RangeState.None;
if(SelectedCals.Count > 1) {
if(IsSameDate(minSelectedCal, cal)) {
rangeState = RangeState.First;
} else if(IsSameDate(maxSelectedCal, cal)) {
rangeState = RangeState.Last;
} else if(IsBetweenDates(cal, minSelectedCal, maxSelectedCal)) {
rangeState = RangeState.Middle;
}
}
weekCells.Add(new MonthCellDescriptor(date, isCurrentMonth, isSelectable, isSelected,
isToday, isHighlighted, value, rangeState, _styleDescriptor));
cal = cal.AddDays(1);
}
}
return cells;
}
/// <summary>
/// Scrolls to selected month.
/// </summary>
/// <param name="selectedIndex">Index of the selected.</param>
internal void ScrollToSelectedMonth(int selectedIndex)
{
ScrollToSelectedMonth(selectedIndex, false);
}
/// <summary>
/// Scrolls to selected month.
/// </summary>
/// <param name="selectedIndex">Index of the selected.</param>
/// <param name="smoothScroll">if set to <c>true</c> [smooth scroll].</param>
internal void ScrollToSelectedMonth(int selectedIndex, bool smoothScroll)
{
// Task.Factory.StartNew(() =>
// {
// if (smoothScroll)
// {
// SmoothScrollToPosition(selectedIndex);
// }
// else
// {
// SetSelection(selectedIndex);
// }
// });
this.SetCurrentItem(selectedIndex, smoothScroll);
}
/// <summary>
/// Gets the month cell with index by date.
/// </summary>
/// <param name="date">The date.</param>
/// <returns>MonthCellWithMonthIndex.</returns>
private MonthCellWithMonthIndex GetMonthCellWithIndexByDate(DateTime date)
{
int index = 0;
foreach(var monthCell in Cells) {
foreach(var actCell in from weekCell in monthCell
from actCell in weekCell
where IsSameDate(actCell.DateTime, date) && actCell.IsSelectable
select actCell)
return new MonthCellWithMonthIndex(actCell, index);
index++;
}
return null;
}
/// <summary>
/// Called when [measure].
/// </summary>
/// <param name="widthMeasureSpec">horizontal space requirements as imposed by the parent.
/// The requirements are encoded with
/// <c><see cref="T:Android.Views.View+MeasureSpec" /></c>.</param>
/// <param name="heightMeasureSpec">vertical space requirements as imposed by the parent.
/// The requirements are encoded with
/// <c><see cref="T:Android.Views.View+MeasureSpec" /></c>.</param>
/// <exception cref="System.InvalidOperationException">Must have at least one month to display. Did you forget to call Init()?</exception>
/// <since version="Added in API level 1" />
/// <altmember cref="P:Android.Views.View.MeasuredWidth" />
/// <altmember cref="P:Android.Views.View.MeasuredHeight" />
/// <altmember cref="M:Android.Views.View.SetMeasuredDimension(System.Int32, System.Int32)" />
/// <altmember cref="M:Android.Views.View.get_SuggestedMinimumHeight" />
/// <altmember cref="M:Android.Views.View.get_SuggestedMinimumWidth" />
/// <altmember cref="M:Android.Views.View.MeasureSpec.GetMode(System.Int32)" />
/// <altmember cref="M:Android.Views.View.MeasureSpec.GetSize(System.Int32)" />
/// <remarks><para tool="javadoc-to-mdoc" />
/// <para tool="javadoc-to-mdoc">
/// Measure the view and its content to determine the measured width and the
/// measured height. This method is invoked by <c><see cref="M:Android.Views.View.Measure(System.Int32, System.Int32)" /></c> and
/// should be overriden by subclasses to provide accurate and efficient
/// measurement of their contents.
/// </para>
/// <para tool="javadoc-to-mdoc">
/// <i>CONTRACT:</i> When overriding this method, you
/// <i>must</i> call <c><see cref="M:Android.Views.View.SetMeasuredDimension(System.Int32, System.Int32)" /></c> to store the
/// measured width and height of this view. Failure to do so will trigger an
/// <c>IllegalStateException</c>, thrown by
/// <c><see cref="M:Android.Views.View.Measure(System.Int32, System.Int32)" /></c>. Calling the superclass'
/// <c><see cref="M:Android.Views.View.OnMeasure(System.Int32, System.Int32)" /></c> is a valid use.
/// </para>
/// <para tool="javadoc-to-mdoc">
/// The base class implementation of measure defaults to the background size,
/// unless a larger size is allowed by the MeasureSpec. Subclasses should
/// override <c><see cref="M:Android.Views.View.OnMeasure(System.Int32, System.Int32)" /></c> to provide better measurements of
/// their content.
/// </para>
/// <para tool="javadoc-to-mdoc">
/// If this method is overridden, it is the subclass's responsibility to make
/// sure the measured height and width are at least the view's minimum height
/// and width (<c><see cref="M:Android.Views.View.get_SuggestedMinimumHeight" /></c> and
/// <c><see cref="M:Android.Views.View.get_SuggestedMinimumWidth" /></c>).
/// </para>
/// <para tool="javadoc-to-mdoc">
/// <format type="text/html">
/// <a href="http://developer.android.com/reference/android/view/View.html#onMeasure(int, int)" target="_blank">[Android Documentation]</a>
/// </format>
/// </para></remarks>
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if(Months.Count == 0) {
throw new InvalidOperationException(
"Must have at least one month to display. Did you forget to call Init()?");
}
Logr.D("PickerView.OnMeasure w={0} h={1}", MeasureSpec.ToString(widthMeasureSpec),
MeasureSpec.ToString(heightMeasureSpec));
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
}
/// <summary>
/// Sets the midnight.
/// </summary>
/// <param name="date">The date.</param>
/// <returns>DateTime.</returns>
private static DateTime SetMidnight(DateTime date)
{
return date.Subtract(date.TimeOfDay);
}
/// <summary>
/// Determines whether the specified date is selectable.
/// </summary>
/// <param name="date">The date.</param>
/// <returns><c>true</c> if the specified date is selectable; otherwise, <c>false</c>.</returns>
private bool IsSelectable(DateTime date)
{
return OnDateSelectable == null || OnDateSelectable(date);
}
/// <summary>
/// Applies the multi select.
/// </summary>
/// <param name="date">The date.</param>
/// <param name="selectedCal">The selected cal.</param>
/// <returns>DateTime.</returns>
private DateTime ApplyMultiSelect(DateTime date, DateTime selectedCal)
{
foreach(var selectedCell in SelectedCells) {
if(selectedCell.DateTime == date) {
//De-select the currently selected cell.
selectedCell.IsSelected = false;
SelectedCells.Remove(selectedCell);
date = DateTime.MinValue;
break;
}
}
foreach(var cal in SelectedCals) {
if(IsSameDate(cal, selectedCal)) {
SelectedCals.Remove(cal);
break;
}
}
return date;
}
/// <summary>
/// Clears the old selection.
/// </summary>
private void ClearOldSelection()
{
foreach(var selectedCell in SelectedCells) {
//De-select the currently selected cell.
selectedCell.IsSelected = false;
}
SelectedCells.Clear();
SelectedCals.Clear();
}
/// <summary>
/// Deselects the date.
/// </summary>
public void DeselectDate()
{
if(SelectedDate != DateTime.MinValue) {
DoSelectDate(DateTime.MinValue, null);
}
}
/// <summary>
/// Does the select date.
/// </summary>
/// <param name="date">The date.</param>
/// <param name="cell">The cell.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
/// <exception cref="Java.Lang.IllegalStateException">Unknown SelectionMode + Mode</exception>
internal bool DoSelectDate(DateTime date, MonthCellDescriptor cell)
{
var newlySelectedDate = date;
SetMidnight(newlySelectedDate);
//Clear any remaining range state.
foreach(var selectedCell in SelectedCells) {
selectedCell.RangeState = RangeState.None;
}
switch(Mode) {
case SelectionMode.Range:
if(SelectedCals.Count > 1) {
//We've already got a range selected: clear the old one.
ClearOldSelection();
} else if(SelectedCals.Count == 1 && newlySelectedDate.CompareTo(SelectedCals[0]) < 0) {
//We're moving the start of the range back in time: clear the old start date.
ClearOldSelection();
}
break;
case SelectionMode.Multi:
date = ApplyMultiSelect(date, newlySelectedDate);
break;
case SelectionMode.Single:
ClearOldSelection();
break;
default:
throw new IllegalStateException("Unknown SelectionMode " + Mode);
}
if(date > DateTime.MinValue) {
if(SelectedCells.Count == 0 || !SelectedCells[0].Equals(cell)) {
SelectedCells.Add(cell);
cell.IsSelected = true;
}
SelectedCals.Add(newlySelectedDate);
if(Mode == SelectionMode.Range && SelectedCells.Count > 1) {
//Select all days in between start and end.
var startDate = SelectedCells[0].DateTime;
var endDate = SelectedCells[1].DateTime;
SelectedCells[0].RangeState = RangeState.First;
SelectedCells[1].RangeState = RangeState.Last;
foreach(var month in Cells) {
foreach(var week in month) {
foreach(var singleCell in week) {
var singleCellDate = singleCell.DateTime;
if(singleCellDate.CompareTo(startDate) >= 0
&& singleCellDate.CompareTo(endDate) <= 0
&& singleCell.IsSelectable) {
singleCell.IsSelected = true;
singleCell.RangeState = RangeState.Middle;
SelectedCells.Add(singleCell);
}
}
}
}
}
}
ValidateAndUpdate();
return date > DateTime.MinValue;
}
/// <summary>
/// Validates the and update.
/// </summary>
internal void ValidateAndUpdate()
{
if(Adapter == null) {
Adapter = MyAdapter;
}
MyAdapter.NotifyDataSetChanged();
}
/// <summary>
/// Selects the date.
/// </summary>
/// <param name="date">The date.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
internal bool SelectDate(DateTime date)
{
return SelectDate(date, false);
}
/// <summary>
/// Selects the date.
/// </summary>
/// <param name="date">The date.</param>
/// <param name="smoothScroll">if set to <c>true</c> [smooth scroll].</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
private bool SelectDate(DateTime date, bool smoothScroll)
{
ValidateDate(date);
var cell = GetMonthCellWithIndexByDate(date);
if(cell == null || !IsSelectable(date)) {
return false;
}
bool wasSelected = DoSelectDate(date, cell.Cell);
if(wasSelected) {
ScrollToSelectedMonth(cell.MonthIndex, smoothScroll);
}
return wasSelected;
}
/// <summary>
/// Validates the date.
/// </summary>
/// <param name="date">The date.</param>
/// <exception cref="Java.Lang.IllegalArgumentException">
/// Selected date must be non-zero.
/// or
/// </exception>
private void ValidateDate(DateTime date)
{
if(date == DateTime.MinValue) {
throw new IllegalArgumentException("Selected date must be non-zero.");
}
if(date.CompareTo(MinDate) < 0 || date.CompareTo(MaxDate) > 0) {
throw new IllegalArgumentException(
string.Format("Selected date must be between minDate and maxDate. "
+ "minDate: {0}, maxDate: {1}, selectedDate: {2}.",
MinDate.ToShortDateString(), MaxDate.ToShortDateString(), date.ToShortDateString()));
}
}
/// <summary>
/// Gets the minimum date.
/// </summary>
/// <param name="selectedCals">The selected cals.</param>
/// <returns>DateTime.</returns>
private static DateTime GetMinDate(List<DateTime> selectedCals)
{
if(selectedCals == null || selectedCals.Count == 0) {
return DateTime.MinValue;
}
selectedCals.Sort();
return selectedCals[0];
}
/// <summary>
/// Gets the maximum date.
/// </summary>
/// <param name="selectedCals">The selected cals.</param>
/// <returns>DateTime.</returns>
private static DateTime GetMaxDate(List<DateTime> selectedCals)
{
if(selectedCals == null || selectedCals.Count == 0) {
return DateTime.MinValue;
}
selectedCals.Sort();
return selectedCals[selectedCals.Count - 1];
}
/// <summary>
/// Determines whether [is between dates] [the specified date].
/// </summary>
/// <param name="date">The date.</param>
/// <param name="minCal">The minimum cal.</param>
/// <param name="maxCal">The maximum cal.</param>
/// <returns><c>true</c> if [is between dates] [the specified date]; otherwise, <c>false</c>.</returns>
private static bool IsBetweenDates(DateTime date, DateTime minCal, DateTime maxCal)
{
return (date.Equals(minCal) || date.CompareTo(minCal) > 0)// >= minCal
&& date.CompareTo(maxCal) <= 0; // && < maxCal
}
/// <summary>
/// Determines whether [is same date] [the specified cal].
/// </summary>
/// <param name="cal">The cal.</param>
/// <param name="selectedDate">The selected date.</param>
/// <returns><c>true</c> if [is same date] [the specified cal]; otherwise, <c>false</c>.</returns>
private static bool IsSameDate(DateTime cal, DateTime selectedDate)
{
return cal.Month == selectedDate.Month
&& cal.Year == selectedDate.Year
&& cal.Day == selectedDate.Day;
}
/// <summary>
/// Determines whether [is same month] [the specified cal].
/// </summary>
/// <param name="cal">The cal.</param>
/// <param name="month">The month.</param>
/// <returns><c>true</c> if [is same month] [the specified cal]; otherwise, <c>false</c>.</returns>
internal static bool IsSameMonth(DateTime cal, MonthDescriptor month)
{
return (cal.Month == month.Month && cal.Year == month.Year);
}
/// <summary>
/// Contatinses the date.
/// </summary>
/// <param name="selectedCals">The selected cals.</param>
/// <param name="cal">The cal.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
private static bool ContatinsDate(IEnumerable<DateTime> selectedCals, DateTime cal)
{
return selectedCals.Any(selectedCal => IsSameDate(cal, selectedCal));
}
/// <summary>
/// Highlights the dates.
/// </summary>
/// <param name="dates">The dates.</param>
public void HighlightDates(ICollection<DateTime> dates)
{
foreach(var date in dates) {
ValidateDate(date);
var monthCellWithMonthIndex = GetMonthCellWithIndexByDate(date);
if(monthCellWithMonthIndex != null) {
var cell = monthCellWithMonthIndex.Cell;
_highlightedCells.Add(cell);
_highlightedCals.Add(date);
cell.IsHighlighted = true;
}
}
MyAdapter.NotifyDataSetChanged();
Adapter = MyAdapter;
}
/// <summary>
/// Debugs the specified minimum date.
/// </summary>
/// <param name="minDate">The minimum date.</param>
/// <param name="maxDate">The maximum date.</param>
/// <returns>System.String.</returns>
private static string Debug(DateTime minDate, DateTime maxDate)
{
return "minDate: " + minDate + "\nmaxDate: " + maxDate;
}
/// <summary>
/// Class MonthCellWithMonthIndex.
/// </summary>
private class MonthCellWithMonthIndex
{
/// <summary>
/// The cell
/// </summary>
public readonly MonthCellDescriptor Cell;
/// <summary>
/// The month index
/// </summary>
public readonly int MonthIndex;
/// <summary>
/// Initializes a new instance of the <see cref="MonthCellWithMonthIndex"/> class.
/// </summary>
/// <param name="cell">The cell.</param>
/// <param name="monthIndex">Index of the month.</param>
public MonthCellWithMonthIndex(MonthCellDescriptor cell, int monthIndex)
{
Cell = cell;
MonthIndex = monthIndex;
}
}
}
/// <summary>
/// Class FluentInitializer.
/// </summary>
public class FluentInitializer
{
/// <summary>
/// The _calendar
/// </summary>
private readonly CalendarPickerView _calendar;
/// <summary>
/// Initializes a new instance of the <see cref="FluentInitializer"/> class.
/// </summary>
/// <param name="calendar">The calendar.</param>
public FluentInitializer(CalendarPickerView calendar)
{
_calendar = calendar;
}
/// <summary>
/// Ins the mode.
/// </summary>
/// <param name="mode">The mode.</param>
/// <returns>FluentInitializer.</returns>
public FluentInitializer InMode(CalendarPickerView.SelectionMode mode)
{
_calendar.Mode = mode;
_calendar.ValidateAndUpdate();
return this;
}
/// <summary>
/// Withes the selected date.
/// </summary>
/// <param name="selectedDate">The selected date.</param>
/// <returns>FluentInitializer.</returns>
public FluentInitializer WithSelectedDate(DateTime selectedDate)
{
return WithSelectedDates(new List<DateTime> { selectedDate });
}
/// <summary>
/// Withes the selected dates.
/// </summary>
/// <param name="selectedDates">The selected dates.</param>
/// <returns>FluentInitializer.</returns>
/// <exception cref="Java.Lang.IllegalArgumentException">SINGLE mode can't be used with multiple selectedDates</exception>
public FluentInitializer WithSelectedDates(ICollection<DateTime> selectedDates)
{
if(_calendar.Mode == CalendarPickerView.SelectionMode.Single && _calendar.SelectedDates.Count > 1) {
throw new IllegalArgumentException("SINGLE mode can't be used with multiple selectedDates");
}
if(_calendar.SelectedDates != null) {
foreach(var date in selectedDates) {
_calendar.SelectDate(date);
}
}
int selectedIndex = -1;
int todayIndex = -1;
for(int i = 0; i < _calendar.Months.Count; i++) {
var month = _calendar.Months[i];
if(selectedIndex == -1) {
if(_calendar.SelectedCals.Any(
selectedCal => CalendarPickerView.IsSameMonth(selectedCal, month))) {
selectedIndex = i;
}
if(selectedIndex == -1 && todayIndex == -1 &&
CalendarPickerView.IsSameMonth(DateTime.Now, month)) {
todayIndex = i;
}
}
}
if(selectedIndex != -1) {
_calendar.ScrollToSelectedMonth(selectedIndex);
} else if(todayIndex != -1) {
_calendar.ScrollToSelectedMonth(todayIndex);
}
_calendar.ValidateAndUpdate();
return this;
}
/// <summary>
/// Withes the locale.
/// </summary>
/// <param name="locale">The locale.</param>
/// <returns>FluentInitializer.</returns>
/// <exception cref="System.NotImplementedException"></exception>
public FluentInitializer WithLocale(Java.Util.Locale locale)
{
//Not sure how to translate this to C# flavor.
//Leave it later.
throw new NotImplementedException();
}
/// <summary>
/// Withes the highlighted dates.
/// </summary>
/// <param name="dates">The dates.</param>
/// <returns>FluentInitializer.</returns>
public FluentInitializer WithHighlightedDates(ICollection<DateTime> dates)
{
_calendar.HighlightDates(dates);
return this;
}
// public FluentInitializer WithHighlightedDaysOfWeek()
// {
// _calendar.HighlighDaysOfWeeks(daysOfWeeks);
// return this;
// }
/// <summary>
/// Withes the highlighted date.
/// </summary>
/// <param name="date">The date.</param>
/// <returns>FluentInitializer.</returns>
public FluentInitializer WithHighlightedDate(DateTime date)
{
return WithHighlightedDates(new List<DateTime> { date });
}
}
/// <summary>
/// Delegate ClickHandler
/// </summary>
/// <param name="cell">The cell.</param>
public delegate void ClickHandler(MonthCellDescriptor cell);
/// <summary>
/// Delegate DateSelectableHandler
/// </summary>
/// <param name="date">The date.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
public delegate bool DateSelectableHandler(DateTime date);
/// <summary>
/// Class DateSelectedEventArgs.
/// </summary>
public class DateSelectedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="DateSelectedEventArgs"/> class.
/// </summary>
/// <param name="date">The date.</param>
public DateSelectedEventArgs(DateTime date)
{
SelectedDate = date;
}
/// <summary>
/// Gets the selected date.
/// </summary>
/// <value>The selected date.</value>
public DateTime SelectedDate { get; private set; }
}
/// <summary>
/// Class MonthChangedEventArgs.
/// </summary>
public class MonthChangedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="MonthChangedEventArgs"/> class.
/// </summary>
/// <param name="date">The date.</param>
public MonthChangedEventArgs(DateTime date)
{
DisplayedMonth = date;
}
/// <summary>
/// Gets the displayed month.
/// </summary>
/// <value>The displayed month.</value>
public DateTime DisplayedMonth { get; private set; }
}
} | {
"pile_set_name": "Github"
} |
# Default config
| {
"pile_set_name": "Github"
} |
##
# This file is an EasyBuild reciPY as per https://github.com/easybuilders/easybuild
#
# Copyright:: Copyright 2012-2014 Uni.Lu/LCSB, NTUA
# Authors:: Fotis Georgatos <[email protected]>
# License:: MIT/GPL
# $Id$
#
# This work implements a part of the HPCBIOS project and is a component of the policy:
# http://hpcbios.readthedocs.org/en/latest/HPCBIOS_2012-97.html
##
easyblock = 'CMakeMake'
name = 'VTK'
version = '6.3.0'
versionsuffix = '-Python-%(pyver)s'
homepage = 'http://www.vtk.org'
description = """The Visualization Toolkit (VTK) is an open-source, freely available software system for
3D computer graphics, image processing and visualization. VTK consists of a C++ class library and several
interpreted interface layers including Tcl/Tk, Java, and Python. VTK supports a wide variety of visualization
algorithms including: scalar, vector, tensor, texture, and volumetric methods; and advanced modeling techniques
such as: implicit modeling, polygon reduction, mesh smoothing, cutting, contouring, and Delaunay triangulation."""
toolchain = {'name': 'foss', 'version': '2016b'}
source_urls = ['http://www.vtk.org/files/release/%(version_major_minor)s']
sources = [
SOURCE_TAR_GZ,
'%(name)sData-%(version)s.tar.gz',
]
builddependencies = [('CMake', '3.6.1')]
dependencies = [
('Python', '2.7.12'),
('libGLU', '9.0.0'),
('X11', '20160819'),
]
configopts = "-DOPENGL_glu_LIBRARY=$EBROOTLIBGLU/lib/libGLU.%s " % SHLIB_EXT
configopts += "-DOPENGL_gl_LIBRARY=$EBROOTMESA/lib/libGL.%s " % SHLIB_EXT
configopts += "-DOPENGL_INCLUDE_DIR=$EBROOTMESA/include -DVTK_WRAP_PYTHON=ON "
configopts += "-DPYTHON_LIBRARY=$EBROOTPYTHON/lib/libpython%%(pyshortver)s.%s " % SHLIB_EXT
configopts += " -DPYTHON_INCLUDE_DIR=$EBROOTPYTHON/include/python%(pyshortver)s "
preinstallopts = "mkdir -p %(installdir)s/lib/python%(pyshortver)s/site-packages/ && "
preinstallopts += "export PYTHONPATH=%(installdir)s/lib/python%(pyshortver)s/site-packages:$PYTHONPATH && "
modextrapaths = {'PYTHONPATH': ['lib/python%(pyshortver)s/site-packages']}
sanity_check_paths = {
'files': ['bin/vtk%s-%%(version_major_minor)s' % x for x in ['EncodeString', 'HashSource',
'mkg3states', 'ParseOGLExt']],
'dirs': ['lib/python%(pyshortver)s/site-packages/', 'include/vtk-%(version_major_minor)s'],
}
sanity_check_commands = [('python', "-c 'import %(namelower)s'")]
moduleclass = 'vis'
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Ciao" version="1.1.0" />
<package id="NUnit.Runners" version="2.6.4" />
</packages>
| {
"pile_set_name": "Github"
} |
""" Encoding Aliases Support
This module is used by the encodings package search function to
map encodings names to module names.
Note that the search function normalizes the encoding names before
doing the lookup, so the mapping will have to map normalized
encoding names to module names.
Contents:
The following aliases dictionary contains mappings of all IANA
character set names for which the Python core library provides
codecs. In addition to these, a few Python specific codec
aliases have also been added.
"""
aliases = {
# Please keep this list sorted alphabetically by value !
# ascii codec
'646' : 'ascii',
'ansi_x3.4_1968' : 'ascii',
'ansi_x3_4_1968' : 'ascii', # some email headers use this non-standard name
'ansi_x3.4_1986' : 'ascii',
'cp367' : 'ascii',
'csascii' : 'ascii',
'ibm367' : 'ascii',
'iso646_us' : 'ascii',
'iso_646.irv_1991' : 'ascii',
'iso_ir_6' : 'ascii',
'us' : 'ascii',
'us_ascii' : 'ascii',
# base64_codec codec
'base64' : 'base64_codec',
'base_64' : 'base64_codec',
# big5 codec
'big5_tw' : 'big5',
'csbig5' : 'big5',
# big5hkscs codec
'big5_hkscs' : 'big5hkscs',
'hkscs' : 'big5hkscs',
# bz2_codec codec
'bz2' : 'bz2_codec',
# cp037 codec
'037' : 'cp037',
'csibm037' : 'cp037',
'ebcdic_cp_ca' : 'cp037',
'ebcdic_cp_nl' : 'cp037',
'ebcdic_cp_us' : 'cp037',
'ebcdic_cp_wt' : 'cp037',
'ibm037' : 'cp037',
'ibm039' : 'cp037',
# cp1026 codec
'1026' : 'cp1026',
'csibm1026' : 'cp1026',
'ibm1026' : 'cp1026',
# cp1140 codec
'1140' : 'cp1140',
'ibm1140' : 'cp1140',
# cp1250 codec
'1250' : 'cp1250',
'windows_1250' : 'cp1250',
# cp1251 codec
'1251' : 'cp1251',
'windows_1251' : 'cp1251',
# cp1252 codec
'1252' : 'cp1252',
'windows_1252' : 'cp1252',
# cp1253 codec
'1253' : 'cp1253',
'windows_1253' : 'cp1253',
# cp1254 codec
'1254' : 'cp1254',
'windows_1254' : 'cp1254',
# cp1255 codec
'1255' : 'cp1255',
'windows_1255' : 'cp1255',
# cp1256 codec
'1256' : 'cp1256',
'windows_1256' : 'cp1256',
# cp1257 codec
'1257' : 'cp1257',
'windows_1257' : 'cp1257',
# cp1258 codec
'1258' : 'cp1258',
'windows_1258' : 'cp1258',
# cp424 codec
'424' : 'cp424',
'csibm424' : 'cp424',
'ebcdic_cp_he' : 'cp424',
'ibm424' : 'cp424',
# cp437 codec
'437' : 'cp437',
'cspc8codepage437' : 'cp437',
'ibm437' : 'cp437',
# cp500 codec
'500' : 'cp500',
'csibm500' : 'cp500',
'ebcdic_cp_be' : 'cp500',
'ebcdic_cp_ch' : 'cp500',
'ibm500' : 'cp500',
# cp775 codec
'775' : 'cp775',
'cspc775baltic' : 'cp775',
'ibm775' : 'cp775',
# cp850 codec
'850' : 'cp850',
'cspc850multilingual' : 'cp850',
'ibm850' : 'cp850',
# cp852 codec
'852' : 'cp852',
'cspcp852' : 'cp852',
'ibm852' : 'cp852',
# cp855 codec
'855' : 'cp855',
'csibm855' : 'cp855',
'ibm855' : 'cp855',
# cp857 codec
'857' : 'cp857',
'csibm857' : 'cp857',
'ibm857' : 'cp857',
# cp858 codec
'858' : 'cp858',
'csibm858' : 'cp858',
'ibm858' : 'cp858',
# cp860 codec
'860' : 'cp860',
'csibm860' : 'cp860',
'ibm860' : 'cp860',
# cp861 codec
'861' : 'cp861',
'cp_is' : 'cp861',
'csibm861' : 'cp861',
'ibm861' : 'cp861',
# cp862 codec
'862' : 'cp862',
'cspc862latinhebrew' : 'cp862',
'ibm862' : 'cp862',
# cp863 codec
'863' : 'cp863',
'csibm863' : 'cp863',
'ibm863' : 'cp863',
# cp864 codec
'864' : 'cp864',
'csibm864' : 'cp864',
'ibm864' : 'cp864',
# cp865 codec
'865' : 'cp865',
'csibm865' : 'cp865',
'ibm865' : 'cp865',
# cp866 codec
'866' : 'cp866',
'csibm866' : 'cp866',
'ibm866' : 'cp866',
# cp869 codec
'869' : 'cp869',
'cp_gr' : 'cp869',
'csibm869' : 'cp869',
'ibm869' : 'cp869',
# cp932 codec
'932' : 'cp932',
'ms932' : 'cp932',
'mskanji' : 'cp932',
'ms_kanji' : 'cp932',
# cp949 codec
'949' : 'cp949',
'ms949' : 'cp949',
'uhc' : 'cp949',
# cp950 codec
'950' : 'cp950',
'ms950' : 'cp950',
# euc_jis_2004 codec
'jisx0213' : 'euc_jis_2004',
'eucjis2004' : 'euc_jis_2004',
'euc_jis2004' : 'euc_jis_2004',
# euc_jisx0213 codec
'eucjisx0213' : 'euc_jisx0213',
# euc_jp codec
'eucjp' : 'euc_jp',
'ujis' : 'euc_jp',
'u_jis' : 'euc_jp',
# euc_kr codec
'euckr' : 'euc_kr',
'korean' : 'euc_kr',
'ksc5601' : 'euc_kr',
'ks_c_5601' : 'euc_kr',
'ks_c_5601_1987' : 'euc_kr',
'ksx1001' : 'euc_kr',
'ks_x_1001' : 'euc_kr',
# gb18030 codec
'gb18030_2000' : 'gb18030',
# gb2312 codec
'chinese' : 'gb2312',
'csiso58gb231280' : 'gb2312',
'euc_cn' : 'gb2312',
'euccn' : 'gb2312',
'eucgb2312_cn' : 'gb2312',
'gb2312_1980' : 'gb2312',
'gb2312_80' : 'gb2312',
'iso_ir_58' : 'gb2312',
# gbk codec
'936' : 'gbk',
'cp936' : 'gbk',
'ms936' : 'gbk',
# hex_codec codec
'hex' : 'hex_codec',
# hp_roman8 codec
'roman8' : 'hp_roman8',
'r8' : 'hp_roman8',
'csHPRoman8' : 'hp_roman8',
# hz codec
'hzgb' : 'hz',
'hz_gb' : 'hz',
'hz_gb_2312' : 'hz',
# iso2022_jp codec
'csiso2022jp' : 'iso2022_jp',
'iso2022jp' : 'iso2022_jp',
'iso_2022_jp' : 'iso2022_jp',
# iso2022_jp_1 codec
'iso2022jp_1' : 'iso2022_jp_1',
'iso_2022_jp_1' : 'iso2022_jp_1',
# iso2022_jp_2 codec
'iso2022jp_2' : 'iso2022_jp_2',
'iso_2022_jp_2' : 'iso2022_jp_2',
# iso2022_jp_2004 codec
'iso_2022_jp_2004' : 'iso2022_jp_2004',
'iso2022jp_2004' : 'iso2022_jp_2004',
# iso2022_jp_3 codec
'iso2022jp_3' : 'iso2022_jp_3',
'iso_2022_jp_3' : 'iso2022_jp_3',
# iso2022_jp_ext codec
'iso2022jp_ext' : 'iso2022_jp_ext',
'iso_2022_jp_ext' : 'iso2022_jp_ext',
# iso2022_kr codec
'csiso2022kr' : 'iso2022_kr',
'iso2022kr' : 'iso2022_kr',
'iso_2022_kr' : 'iso2022_kr',
# iso8859_10 codec
'csisolatin6' : 'iso8859_10',
'iso_8859_10' : 'iso8859_10',
'iso_8859_10_1992' : 'iso8859_10',
'iso_ir_157' : 'iso8859_10',
'l6' : 'iso8859_10',
'latin6' : 'iso8859_10',
# iso8859_11 codec
'thai' : 'iso8859_11',
'iso_8859_11' : 'iso8859_11',
'iso_8859_11_2001' : 'iso8859_11',
# iso8859_13 codec
'iso_8859_13' : 'iso8859_13',
'l7' : 'iso8859_13',
'latin7' : 'iso8859_13',
# iso8859_14 codec
'iso_8859_14' : 'iso8859_14',
'iso_8859_14_1998' : 'iso8859_14',
'iso_celtic' : 'iso8859_14',
'iso_ir_199' : 'iso8859_14',
'l8' : 'iso8859_14',
'latin8' : 'iso8859_14',
# iso8859_15 codec
'iso_8859_15' : 'iso8859_15',
'l9' : 'iso8859_15',
'latin9' : 'iso8859_15',
# iso8859_16 codec
'iso_8859_16' : 'iso8859_16',
'iso_8859_16_2001' : 'iso8859_16',
'iso_ir_226' : 'iso8859_16',
'l10' : 'iso8859_16',
'latin10' : 'iso8859_16',
# iso8859_2 codec
'csisolatin2' : 'iso8859_2',
'iso_8859_2' : 'iso8859_2',
'iso_8859_2_1987' : 'iso8859_2',
'iso_ir_101' : 'iso8859_2',
'l2' : 'iso8859_2',
'latin2' : 'iso8859_2',
# iso8859_3 codec
'csisolatin3' : 'iso8859_3',
'iso_8859_3' : 'iso8859_3',
'iso_8859_3_1988' : 'iso8859_3',
'iso_ir_109' : 'iso8859_3',
'l3' : 'iso8859_3',
'latin3' : 'iso8859_3',
# iso8859_4 codec
'csisolatin4' : 'iso8859_4',
'iso_8859_4' : 'iso8859_4',
'iso_8859_4_1988' : 'iso8859_4',
'iso_ir_110' : 'iso8859_4',
'l4' : 'iso8859_4',
'latin4' : 'iso8859_4',
# iso8859_5 codec
'csisolatincyrillic' : 'iso8859_5',
'cyrillic' : 'iso8859_5',
'iso_8859_5' : 'iso8859_5',
'iso_8859_5_1988' : 'iso8859_5',
'iso_ir_144' : 'iso8859_5',
# iso8859_6 codec
'arabic' : 'iso8859_6',
'asmo_708' : 'iso8859_6',
'csisolatinarabic' : 'iso8859_6',
'ecma_114' : 'iso8859_6',
'iso_8859_6' : 'iso8859_6',
'iso_8859_6_1987' : 'iso8859_6',
'iso_ir_127' : 'iso8859_6',
# iso8859_7 codec
'csisolatingreek' : 'iso8859_7',
'ecma_118' : 'iso8859_7',
'elot_928' : 'iso8859_7',
'greek' : 'iso8859_7',
'greek8' : 'iso8859_7',
'iso_8859_7' : 'iso8859_7',
'iso_8859_7_1987' : 'iso8859_7',
'iso_ir_126' : 'iso8859_7',
# iso8859_8 codec
'csisolatinhebrew' : 'iso8859_8',
'hebrew' : 'iso8859_8',
'iso_8859_8' : 'iso8859_8',
'iso_8859_8_1988' : 'iso8859_8',
'iso_ir_138' : 'iso8859_8',
# iso8859_9 codec
'csisolatin5' : 'iso8859_9',
'iso_8859_9' : 'iso8859_9',
'iso_8859_9_1989' : 'iso8859_9',
'iso_ir_148' : 'iso8859_9',
'l5' : 'iso8859_9',
'latin5' : 'iso8859_9',
# johab codec
'cp1361' : 'johab',
'ms1361' : 'johab',
# koi8_r codec
'cskoi8r' : 'koi8_r',
# latin_1 codec
#
# Note that the latin_1 codec is implemented internally in C and a
# lot faster than the charmap codec iso8859_1 which uses the same
# encoding. This is why we discourage the use of the iso8859_1
# codec and alias it to latin_1 instead.
#
'8859' : 'latin_1',
'cp819' : 'latin_1',
'csisolatin1' : 'latin_1',
'ibm819' : 'latin_1',
'iso8859' : 'latin_1',
'iso8859_1' : 'latin_1',
'iso_8859_1' : 'latin_1',
'iso_8859_1_1987' : 'latin_1',
'iso_ir_100' : 'latin_1',
'l1' : 'latin_1',
'latin' : 'latin_1',
'latin1' : 'latin_1',
# mac_cyrillic codec
'maccyrillic' : 'mac_cyrillic',
# mac_greek codec
'macgreek' : 'mac_greek',
# mac_iceland codec
'maciceland' : 'mac_iceland',
# mac_latin2 codec
'maccentraleurope' : 'mac_latin2',
'maclatin2' : 'mac_latin2',
# mac_roman codec
'macroman' : 'mac_roman',
# mac_turkish codec
'macturkish' : 'mac_turkish',
# mbcs codec
'dbcs' : 'mbcs',
# ptcp154 codec
'csptcp154' : 'ptcp154',
'pt154' : 'ptcp154',
'cp154' : 'ptcp154',
'cyrillic_asian' : 'ptcp154',
# quopri_codec codec
'quopri' : 'quopri_codec',
'quoted_printable' : 'quopri_codec',
'quotedprintable' : 'quopri_codec',
# rot_13 codec
'rot13' : 'rot_13',
# shift_jis codec
'csshiftjis' : 'shift_jis',
'shiftjis' : 'shift_jis',
'sjis' : 'shift_jis',
's_jis' : 'shift_jis',
# shift_jis_2004 codec
'shiftjis2004' : 'shift_jis_2004',
'sjis_2004' : 'shift_jis_2004',
's_jis_2004' : 'shift_jis_2004',
# shift_jisx0213 codec
'shiftjisx0213' : 'shift_jisx0213',
'sjisx0213' : 'shift_jisx0213',
's_jisx0213' : 'shift_jisx0213',
# tactis codec
'tis260' : 'tactis',
# tis_620 codec
'tis620' : 'tis_620',
'tis_620_0' : 'tis_620',
'tis_620_2529_0' : 'tis_620',
'tis_620_2529_1' : 'tis_620',
'iso_ir_166' : 'tis_620',
# utf_16 codec
'u16' : 'utf_16',
'utf16' : 'utf_16',
# utf_16_be codec
'unicodebigunmarked' : 'utf_16_be',
'utf_16be' : 'utf_16_be',
# utf_16_le codec
'unicodelittleunmarked' : 'utf_16_le',
'utf_16le' : 'utf_16_le',
# utf_32 codec
'u32' : 'utf_32',
'utf32' : 'utf_32',
# utf_32_be codec
'utf_32be' : 'utf_32_be',
# utf_32_le codec
'utf_32le' : 'utf_32_le',
# utf_7 codec
'u7' : 'utf_7',
'utf7' : 'utf_7',
'unicode_1_1_utf_7' : 'utf_7',
# utf_8 codec
'u8' : 'utf_8',
'utf' : 'utf_8',
'utf8' : 'utf_8',
'utf8_ucs2' : 'utf_8',
'utf8_ucs4' : 'utf_8',
# uu_codec codec
'uu' : 'uu_codec',
# zlib_codec codec
'zip' : 'zlib_codec',
'zlib' : 'zlib_codec',
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
*
* http://www.ec-cube.co.jp/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Page\Install\InstallPage;
/**
* @group installer
*/
class ZZ99InstallerCest
{
protected $writableFiles = [
'app/Plugin',
'app/PluginData',
'app/proxy',
'app/template',
'html',
'var',
'vendor',
'composer.json',
'composer.lock',
];
/**
* 権限チェックのテスト.
*
* @param AcceptanceTester $I
*/
public function installer_CheckPermission(\AcceptanceTester $I)
{
$I->wantTo('ZZ99 インストーラ 権限チェックのテスト');
// step1
$page = InstallPage::go($I);
$I->see('ようこそ', InstallPage::$STEP1_タイトル);
// 次へ
$page->step1_次へボタンをクリック();
// step2
$I->see('権限チェック', InstallPage::$STEP2_タイトル);
$I->see('アクセス権限は正常です', InstallPage::$STEP2_テキストエリア);
$rootDir = __DIR__.'/../../';
foreach ($this->writableFiles as $file) {
$path = $rootDir.$file;
$origin = octdec(substr(sprintf('%o', fileperms($path)), -4));
// 書き込み権限を外す
chmod($path, 0555);
// リロードしてエラーが表示されることを確認.
$page->step2_リロード();
$I->see('以下のファイルまたはディレクトリに書き込み権限を付与してください', InstallPage::$STEP2_テキストエリア);
$I->see($file, InstallPage::$STEP2_テキストエリア);
// 権限を戻す.
chmod($path, $origin);
}
// 対象外のディレクトリ・ファイルの確認
$externalDir = $rootDir.'externalDir';
mkdir($externalDir, 0555, true);
$externalFile = $rootDir.'externalFile.txt';
touch($externalFile);
chmod($externalFile, 0555);
$page->step2_リロード();
$I->see('アクセス権限は正常です', InstallPage::$STEP2_テキストエリア);
chmod($externalDir, 0777);
chmod($externalFile, 0777);
rmdir($externalDir);
unlink($externalFile);
}
}
| {
"pile_set_name": "Github"
} |
sum = zb2rhoMMnNH7etHbYEKmm2LVJJpuzSPUMfsy4R3jSpJtb5kiY
zipWith = zb2rhmLLC868BNchhioA8CQdAQvRVHaT6nCXAYBomhP83y9Nf
# a => b =>
(sum
(zipWith (mul) a b))
| {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H
#define EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H
namespace Eigen {
/** \class TensorConcatenationOp
* \ingroup CXX11_Tensor_Module
*
* \brief Tensor concatenation class.
*
*
*/
namespace internal {
template<typename Axis, typename LhsXprType, typename RhsXprType>
struct traits<TensorConcatenationOp<Axis, LhsXprType, RhsXprType> >
{
// Type promotion to handle the case where the types of the lhs and the rhs are different.
typedef typename promote_storage_type<typename LhsXprType::Scalar,
typename RhsXprType::Scalar>::ret Scalar;
typedef typename promote_storage_type<typename traits<LhsXprType>::StorageKind,
typename traits<RhsXprType>::StorageKind>::ret StorageKind;
typedef typename promote_index_type<typename traits<LhsXprType>::Index,
typename traits<RhsXprType>::Index>::type Index;
typedef typename LhsXprType::Nested LhsNested;
typedef typename RhsXprType::Nested RhsNested;
typedef typename remove_reference<LhsNested>::type _LhsNested;
typedef typename remove_reference<RhsNested>::type _RhsNested;
static const int NumDimensions = traits<LhsXprType>::NumDimensions;
static const int Layout = traits<LhsXprType>::Layout;
enum { Flags = 0 };
};
template<typename Axis, typename LhsXprType, typename RhsXprType>
struct eval<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, Eigen::Dense>
{
typedef const TensorConcatenationOp<Axis, LhsXprType, RhsXprType>& type;
};
template<typename Axis, typename LhsXprType, typename RhsXprType>
struct nested<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, 1, typename eval<TensorConcatenationOp<Axis, LhsXprType, RhsXprType> >::type>
{
typedef TensorConcatenationOp<Axis, LhsXprType, RhsXprType> type;
};
} // end namespace internal
template<typename Axis, typename LhsXprType, typename RhsXprType>
class TensorConcatenationOp : public TensorBase<TensorConcatenationOp<Axis, LhsXprType, RhsXprType>, WriteAccessors>
{
public:
typedef typename internal::traits<TensorConcatenationOp>::Scalar Scalar;
typedef typename internal::traits<TensorConcatenationOp>::StorageKind StorageKind;
typedef typename internal::traits<TensorConcatenationOp>::Index Index;
typedef typename internal::nested<TensorConcatenationOp>::type Nested;
typedef typename internal::promote_storage_type<typename LhsXprType::CoeffReturnType,
typename RhsXprType::CoeffReturnType>::ret CoeffReturnType;
typedef typename NumTraits<Scalar>::Real RealScalar;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorConcatenationOp(const LhsXprType& lhs, const RhsXprType& rhs, Axis axis)
: m_lhs_xpr(lhs), m_rhs_xpr(rhs), m_axis(axis) {}
EIGEN_DEVICE_FUNC
const typename internal::remove_all<typename LhsXprType::Nested>::type&
lhsExpression() const { return m_lhs_xpr; }
EIGEN_DEVICE_FUNC
const typename internal::remove_all<typename RhsXprType::Nested>::type&
rhsExpression() const { return m_rhs_xpr; }
EIGEN_DEVICE_FUNC const Axis& axis() const { return m_axis; }
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE TensorConcatenationOp& operator = (const TensorConcatenationOp& other)
{
typedef TensorAssignOp<TensorConcatenationOp, const TensorConcatenationOp> Assign;
Assign assign(*this, other);
internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
return *this;
}
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE TensorConcatenationOp& operator = (const OtherDerived& other)
{
typedef TensorAssignOp<TensorConcatenationOp, const OtherDerived> Assign;
Assign assign(*this, other);
internal::TensorExecutor<const Assign, DefaultDevice>::run(assign, DefaultDevice());
return *this;
}
protected:
typename LhsXprType::Nested m_lhs_xpr;
typename RhsXprType::Nested m_rhs_xpr;
const Axis m_axis;
};
// Eval as rvalue
template<typename Axis, typename LeftArgType, typename RightArgType, typename Device>
struct TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device>
{
typedef TensorConcatenationOp<Axis, LeftArgType, RightArgType> XprType;
typedef typename XprType::Index Index;
static const int NumDims = internal::array_size<typename TensorEvaluator<LeftArgType, Device>::Dimensions>::value;
static const int RightNumDims = internal::array_size<typename TensorEvaluator<RightArgType, Device>::Dimensions>::value;
typedef DSizes<Index, NumDims> Dimensions;
typedef typename XprType::Scalar Scalar;
typedef typename XprType::CoeffReturnType CoeffReturnType;
typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
enum {
IsAligned = false,
PacketAccess = TensorEvaluator<LeftArgType, Device>::PacketAccess & TensorEvaluator<RightArgType, Device>::PacketAccess,
Layout = TensorEvaluator<LeftArgType, Device>::Layout,
RawAccess = false
};
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorEvaluator(const XprType& op, const Device& device)
: m_leftImpl(op.lhsExpression(), device), m_rightImpl(op.rhsExpression(), device), m_axis(op.axis())
{
EIGEN_STATIC_ASSERT((static_cast<int>(TensorEvaluator<LeftArgType, Device>::Layout) == static_cast<int>(TensorEvaluator<RightArgType, Device>::Layout) || NumDims == 1), YOU_MADE_A_PROGRAMMING_MISTAKE);
EIGEN_STATIC_ASSERT((NumDims == RightNumDims), YOU_MADE_A_PROGRAMMING_MISTAKE);
EIGEN_STATIC_ASSERT((NumDims > 0), YOU_MADE_A_PROGRAMMING_MISTAKE);
eigen_assert(0 <= m_axis && m_axis < NumDims);
const Dimensions& lhs_dims = m_leftImpl.dimensions();
const Dimensions& rhs_dims = m_rightImpl.dimensions();
{
int i = 0;
for (; i < m_axis; ++i) {
eigen_assert(lhs_dims[i] > 0);
eigen_assert(lhs_dims[i] == rhs_dims[i]);
m_dimensions[i] = lhs_dims[i];
}
eigen_assert(lhs_dims[i] > 0); // Now i == m_axis.
eigen_assert(rhs_dims[i] > 0);
m_dimensions[i] = lhs_dims[i] + rhs_dims[i];
for (++i; i < NumDims; ++i) {
eigen_assert(lhs_dims[i] > 0);
eigen_assert(lhs_dims[i] == rhs_dims[i]);
m_dimensions[i] = lhs_dims[i];
}
}
if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
m_leftStrides[0] = 1;
m_rightStrides[0] = 1;
m_outputStrides[0] = 1;
for (int j = 1; j < NumDims; ++j) {
m_leftStrides[j] = m_leftStrides[j-1] * lhs_dims[j-1];
m_rightStrides[j] = m_rightStrides[j-1] * rhs_dims[j-1];
m_outputStrides[j] = m_outputStrides[j-1] * m_dimensions[j-1];
}
} else {
m_leftStrides[NumDims - 1] = 1;
m_rightStrides[NumDims - 1] = 1;
m_outputStrides[NumDims - 1] = 1;
for (int j = NumDims - 2; j >= 0; --j) {
m_leftStrides[j] = m_leftStrides[j+1] * lhs_dims[j+1];
m_rightStrides[j] = m_rightStrides[j+1] * rhs_dims[j+1];
m_outputStrides[j] = m_outputStrides[j+1] * m_dimensions[j+1];
}
}
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Dimensions& dimensions() const { return m_dimensions; }
// TODO(phli): Add short-circuit memcpy evaluation if underlying data are linear?
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool evalSubExprsIfNeeded(Scalar* /*data*/)
{
m_leftImpl.evalSubExprsIfNeeded(NULL);
m_rightImpl.evalSubExprsIfNeeded(NULL);
return true;
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void cleanup()
{
m_leftImpl.cleanup();
m_rightImpl.cleanup();
}
// TODO(phli): attempt to speed this up. The integer divisions and modulo are slow.
// See CL/76180724 comments for more ideas.
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType coeff(Index index) const
{
// Collect dimension-wise indices (subs).
array<Index, NumDims> subs;
if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
for (int i = NumDims - 1; i > 0; --i) {
subs[i] = index / m_outputStrides[i];
index -= subs[i] * m_outputStrides[i];
}
subs[0] = index;
} else {
for (int i = 0; i < NumDims - 1; ++i) {
subs[i] = index / m_outputStrides[i];
index -= subs[i] * m_outputStrides[i];
}
subs[NumDims - 1] = index;
}
const Dimensions& left_dims = m_leftImpl.dimensions();
if (subs[m_axis] < left_dims[m_axis]) {
Index left_index;
if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
left_index = subs[0];
for (int i = 1; i < NumDims; ++i) {
left_index += (subs[i] % left_dims[i]) * m_leftStrides[i];
}
} else {
left_index = subs[NumDims - 1];
for (int i = NumDims - 2; i >= 0; --i) {
left_index += (subs[i] % left_dims[i]) * m_leftStrides[i];
}
}
return m_leftImpl.coeff(left_index);
} else {
subs[m_axis] -= left_dims[m_axis];
const Dimensions& right_dims = m_rightImpl.dimensions();
Index right_index;
if (static_cast<int>(Layout) == static_cast<int>(ColMajor)) {
right_index = subs[0];
for (int i = 1; i < NumDims; ++i) {
right_index += (subs[i] % right_dims[i]) * m_rightStrides[i];
}
} else {
right_index = subs[NumDims - 1];
for (int i = NumDims - 2; i >= 0; --i) {
right_index += (subs[i] % right_dims[i]) * m_rightStrides[i];
}
}
return m_rightImpl.coeff(right_index);
}
}
// TODO(phli): Add a real vectorization.
template<int LoadMode>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const
{
const int packetSize = internal::unpacket_traits<PacketReturnType>::size;
EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE)
eigen_assert(index + packetSize - 1 < dimensions().TotalSize());
EIGEN_ALIGN_MAX CoeffReturnType values[packetSize];
for (int i = 0; i < packetSize; ++i) {
values[i] = coeff(index+i);
}
PacketReturnType rslt = internal::pload<PacketReturnType>(values);
return rslt;
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorOpCost
costPerCoeff(bool vectorized) const {
const double compute_cost = NumDims * (2 * TensorOpCost::AddCost<Index>() +
2 * TensorOpCost::MulCost<Index>() +
TensorOpCost::DivCost<Index>() +
TensorOpCost::ModCost<Index>());
const double lhs_size = m_leftImpl.dimensions().TotalSize();
const double rhs_size = m_rightImpl.dimensions().TotalSize();
return (lhs_size / (lhs_size + rhs_size)) *
m_leftImpl.costPerCoeff(vectorized) +
(rhs_size / (lhs_size + rhs_size)) *
m_rightImpl.costPerCoeff(vectorized) +
TensorOpCost(0, 0, compute_cost);
}
EIGEN_DEVICE_FUNC Scalar* data() const { return NULL; }
/// required by sycl in order to extract the accessor
const TensorEvaluator<LeftArgType, Device>& left_impl() const { return m_leftImpl; }
/// required by sycl in order to extract the accessor
const TensorEvaluator<RightArgType, Device>& right_impl() const { return m_rightImpl; }
/// required by sycl in order to extract the accessor
const Axis& axis() const { return m_axis; }
protected:
Dimensions m_dimensions;
array<Index, NumDims> m_outputStrides;
array<Index, NumDims> m_leftStrides;
array<Index, NumDims> m_rightStrides;
TensorEvaluator<LeftArgType, Device> m_leftImpl;
TensorEvaluator<RightArgType, Device> m_rightImpl;
const Axis m_axis;
};
// Eval as lvalue
template<typename Axis, typename LeftArgType, typename RightArgType, typename Device>
struct TensorEvaluator<TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device>
: public TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device>
{
typedef TensorEvaluator<const TensorConcatenationOp<Axis, LeftArgType, RightArgType>, Device> Base;
typedef TensorConcatenationOp<Axis, LeftArgType, RightArgType> XprType;
typedef typename Base::Dimensions Dimensions;
enum {
IsAligned = false,
PacketAccess = TensorEvaluator<LeftArgType, Device>::PacketAccess & TensorEvaluator<RightArgType, Device>::PacketAccess,
Layout = TensorEvaluator<LeftArgType, Device>::Layout,
RawAccess = false
};
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE TensorEvaluator(XprType& op, const Device& device)
: Base(op, device)
{
EIGEN_STATIC_ASSERT((static_cast<int>(Layout) == static_cast<int>(ColMajor)), YOU_MADE_A_PROGRAMMING_MISTAKE);
}
typedef typename XprType::Index Index;
typedef typename XprType::Scalar Scalar;
typedef typename XprType::CoeffReturnType CoeffReturnType;
typedef typename PacketType<CoeffReturnType, Device>::type PacketReturnType;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE CoeffReturnType& coeffRef(Index index)
{
// Collect dimension-wise indices (subs).
array<Index, Base::NumDims> subs;
for (int i = Base::NumDims - 1; i > 0; --i) {
subs[i] = index / this->m_outputStrides[i];
index -= subs[i] * this->m_outputStrides[i];
}
subs[0] = index;
const Dimensions& left_dims = this->m_leftImpl.dimensions();
if (subs[this->m_axis] < left_dims[this->m_axis]) {
Index left_index = subs[0];
for (int i = 1; i < Base::NumDims; ++i) {
left_index += (subs[i] % left_dims[i]) * this->m_leftStrides[i];
}
return this->m_leftImpl.coeffRef(left_index);
} else {
subs[this->m_axis] -= left_dims[this->m_axis];
const Dimensions& right_dims = this->m_rightImpl.dimensions();
Index right_index = subs[0];
for (int i = 1; i < Base::NumDims; ++i) {
right_index += (subs[i] % right_dims[i]) * this->m_rightStrides[i];
}
return this->m_rightImpl.coeffRef(right_index);
}
}
template <int StoreMode> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
void writePacket(Index index, const PacketReturnType& x)
{
const int packetSize = internal::unpacket_traits<PacketReturnType>::size;
EIGEN_STATIC_ASSERT((packetSize > 1), YOU_MADE_A_PROGRAMMING_MISTAKE)
eigen_assert(index + packetSize - 1 < this->dimensions().TotalSize());
EIGEN_ALIGN_MAX CoeffReturnType values[packetSize];
internal::pstore<CoeffReturnType, PacketReturnType>(values, x);
for (int i = 0; i < packetSize; ++i) {
coeffRef(index+i) = values[i];
}
}
};
} // end namespace Eigen
#endif // EIGEN_CXX11_TENSOR_TENSOR_CONCATENATION_H
| {
"pile_set_name": "Github"
} |
# Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .network import NetworkModel
__all__ = ['NetworkModel']
| {
"pile_set_name": "Github"
} |
#import "GeneratedPluginRegistrant.h"
| {
"pile_set_name": "Github"
} |
//no attachments on either of the M16A2s.
class M16A2_DZ : M16A2
{
magazines[] =
{
30Rnd_556x45_Stanag,
30Rnd_556x45_StanagSD
};
class Attachments
{
Attachment_M203 = "M16A2_GL_DZ";
};
};
class M16A2_GL_DZ : M16A2GL
{
magazines[] =
{
30Rnd_556x45_Stanag,
30Rnd_556x45_StanagSD
};
class ItemActions
{
class RemoveGL
{
text = $STR_DZ_ATT_M203_RMVE;
script = "; ['Attachment_M203',_id,'M16A2_DZ'] call player_removeAttachment";
};
};
}; | {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CSS Writing Modes Test: absolutely positioned non-replaced element - 'direction: ltr' and 'top', 'height' and 'bottom' are 'auto'</title>
<link rel="author" title="Gérard Talbot" href="http://www.gtalbot.org/BrowserBugsSection/css21testsuite/" />
<link rel="help" href="http://www.w3.org/TR/css-writing-modes-3/#vertical-layout" title="7.1 Principles of Layout in Vertical Writing Modes" />
<link rel="help" href="http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width" title="10.3.7 Absolutely positioned, non-replaced elements" />
<link rel="match" href="abs-pos-non-replaced-vrl-006-ref.xht" />
<meta name="flags" content="ahem image" />
<meta name="assert" content="When 'direction' is 'ltr' and 'top', 'height' and 'bottom' are 'auto', then set 'top' to the static position, the height is based on the content and then solve for 'bottom'." />
<link rel="stylesheet" type="text/css" href="/fonts/ahem.css" />
<style type="text/css"><![CDATA[
html
{
writing-mode: vertical-rl;
}
div#containing-block
{
background: red url("support/bg-red-3col-3row-320x320.png");
color: transparent;
direction: ltr;
font: 80px/1 Ahem;
height: 320px;
position: relative;
width: 320px;
}
div#containing-block > span
{
background-color: red;
bottom: auto;
color: green;
height: auto;
position: absolute;
top: auto;
}
/*
"
Layout calculation rules (such as those in CSS2.1, Section 10.3) that apply to the horizontal dimension in horizontal writing modes instead apply to the vertical dimension in vertical writing modes.
"
7.1 Principles of Layout in Vertical Writing Modes
http://www.w3.org/TR/css-writing-modes-3/#vertical-layout
So here, *-top and *-bottom properties are input into the §10.3.7 algorithms where *-top properties refer to *-left properties in the layout rules and where *-bottom properties refer to *-right properties in the layout rules.
"
If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0. Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.
3. 'width' and 'right' are 'auto' and 'left' is not 'auto', then the width is shrink-to-fit . Then solve for 'right'
"
'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = height of containing block
So:
160px : top: auto: set to static position
+
0px : margin-top
+
0px : border-top-width
+
0px : padding-top
+
(based on the content) : height: auto
+
0px : padding-bottom
+
0px : border-bottom-width
+
0px : margin-bottom
+
(solve) : bottom: auto
=====================
320px : height of containing block
gives us:
160px : top: auto: set to static position
+
0px : margin-top
+
0px : border-top-width
+
0px : padding-top
+
80px : (based on the content) : height: auto
+
0px : padding-bottom
+
0px : border-bottom-width
+
0px : margin-bottom
+
(solve) : bottom: auto
=====================
320px : height of containing block
And so computed bottom value must be 80px .
*/
]]></style>
</head>
<body>
<p><img src="support/pass-cdts-abs-pos-non-replaced.png" width="246" height="36" alt="Image download support must be enabled" /></p>
<div id="containing-block">1 2 34<span>X</span></div>
</body>
</html> | {
"pile_set_name": "Github"
} |
{{!
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
}}
{{breadcrumb-bar breadcrumbs=breadcrumbs}}
<div class="panel-group">
<div class="panel panel-default">
<div class="yarn-app-header">
<div class="flex">
<div class="top-1">
<h3>{{model.selected}}</h3>
{{#if model.selectedQueue.state}}
<div>
{{em-table-simple-status-cell content=model.selectedQueue.state}}
</div>
{{/if}}
{{#if (eq model.queues.firstObject.type "capacity")}}
<div class="top-1">
<span class="yarn-label secondary">
<span class="label-key">configured capacity</span>
<span class="label-value">{{model.selectedQueue.capacity}}%</span>
</span>
<span class="yarn-label secondary">
<span class="label-key">configured max capacity</span>
<span class="label-value">{{model.selectedQueue.maxCapacity}}%</span>
</span>
{{#if model.selectedQueue.isLeafQueue}}
<span class="yarn-label secondary">
<span class="label-key">user limit</span>
<span class="label-value">{{model.selectedQueue.userLimit}}%</span>
</span>
<span class="yarn-label secondary">
<span class="label-key">user limit factor</span>
<span class="label-value">{{model.selectedQueue.userLimitFactor}}</span>
</span>
{{/if}}
</div>
{{/if}}
</div>
<div class="flex-right">
{{#each model.selectedQueue.capacitiesBarChartData as |item|}}
<span class="yarn-label primary">
<span class="label-key"> {{lower item.label}}</span>
<span class="label-value">{{item.value}}{{#if (eq model.queues.firstObject.type "fair")}} MB{{else}}%{{/if}}</span>
</span>
{{/each}}
</div>
</div>
</div>
<div class="panel-body yarn-app-body">
{{outlet}}
</div>
</div>
</div>
| {
"pile_set_name": "Github"
} |
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef BASEVIEWMODEL_SHARED_H
#define BASEVIEWMODEL_SHARED_H
#ifdef _WIN32
#pragma once
#endif
#include "predictable_entity.h"
#include "utlvector.h"
#include "baseplayer_shared.h"
#include "shared_classnames.h"
#include "econ/ihasowner.h"
class CBaseCombatWeapon;
class CBaseCombatCharacter;
class CVGuiScreen;
#if defined( CLIENT_DLL )
#define CBaseViewModel C_BaseViewModel
#define CBaseCombatWeapon C_BaseCombatWeapon
#endif
#define VIEWMODEL_INDEX_BITS 1
class CBaseViewModel : public CBaseAnimating, public IHasOwner
{
DECLARE_CLASS( CBaseViewModel, CBaseAnimating );
public:
DECLARE_NETWORKCLASS();
DECLARE_PREDICTABLE();
#if !defined( CLIENT_DLL )
DECLARE_DATADESC();
#endif
CBaseViewModel( void );
~CBaseViewModel( void );
bool IsViewable(void) { return false; }
virtual void UpdateOnRemove( void );
// Weapon client handling
virtual void SendViewModelMatchingSequence( int sequence );
virtual void SetWeaponModel( const char *pszModelname, CBaseCombatWeapon *weapon );
virtual void CalcViewModelLag( Vector& origin, QAngle& angles, QAngle& original_angles );
virtual void CalcViewModelView( CBasePlayer *owner, const Vector& eyePosition,
const QAngle& eyeAngles );
virtual void AddViewModelBob( CBasePlayer *owner, Vector& eyePosition, QAngle& eyeAngles ) {};
// Initializes the viewmodel for use
void SetOwner( CBaseEntity *pEntity );
void SetIndex( int nIndex );
// Returns which viewmodel it is
int ViewModelIndex( ) const;
virtual void Precache( void );
virtual void Spawn( void );
virtual CBaseEntity *GetOwner( void ) { return m_hOwner; };
virtual void AddEffects( int nEffects );
virtual void RemoveEffects( int nEffects );
void SpawnControlPanels();
void DestroyControlPanels();
void SetControlPanelsActive( bool bState );
void ShowControlPanells( bool show );
virtual CBaseCombatWeapon *GetOwningWeapon( void );
virtual CBaseEntity *GetOwnerViaInterface( void ) { return GetOwner(); }
virtual bool IsSelfAnimating()
{
return true;
}
Vector m_vecLastFacing;
// Only support prediction in TF2 for now
#if defined( INVASION_DLL ) || defined( INVASION_CLIENT_DLL )
// All predicted weapons need to implement and return true
virtual bool IsPredicted( void ) const
{
return true;
}
#endif
#if !defined( CLIENT_DLL )
virtual int UpdateTransmitState( void );
virtual int ShouldTransmit( const CCheckTransmitInfo *pInfo );
virtual void SetTransmit( CCheckTransmitInfo *pInfo, bool bAlways );
#else
virtual RenderGroup_t GetRenderGroup();
// Only supported in TF2 right now
#if defined( INVASION_CLIENT_DLL )
virtual bool ShouldPredict( void )
{
if ( GetOwner() && GetOwner() == C_BasePlayer::GetLocalPlayer() )
return true;
return BaseClass::ShouldPredict();
}
#endif
virtual void FireEvent( const Vector& origin, const QAngle& angles, int event, const char *options );
virtual void OnDataChanged( DataUpdateType_t updateType );
virtual void PostDataUpdate( DataUpdateType_t updateType );
virtual bool Interpolate( float currentTime );
bool ShouldFlipViewModel();
void UpdateAnimationParity( void );
virtual void ApplyBoneMatrixTransform( matrix3x4_t& transform );
virtual bool ShouldDraw();
virtual int DrawModel( int flags );
virtual int InternalDrawModel( int flags );
int DrawOverriddenViewmodel( int flags );
virtual int GetFxBlend( void );
virtual bool IsTransparent( void );
virtual bool UsesPowerOfTwoFrameBufferTexture( void );
// Should this object cast shadows?
virtual ShadowType_t ShadowCastType() { return SHADOWS_NONE; }
// Should this object receive shadows?
virtual bool ShouldReceiveProjectedTextures( int flags )
{
return false;
}
// Add entity to visible view models list?
virtual void AddEntity( void );
virtual void GetBoneControllers(float controllers[MAXSTUDIOBONECTRLS]);
// See C_StudioModel's definition of this.
virtual void UncorrectViewModelAttachment( Vector &vOrigin );
// (inherited from C_BaseAnimating)
virtual void FormatViewModelAttachment( int nAttachment, matrix3x4_t &attachmentToWorld );
virtual bool IsViewModel() const;
CBaseCombatWeapon *GetWeapon() const { return m_hWeapon.Get(); }
#ifdef CLIENT_DLL
virtual bool ShouldResetSequenceOnNewModel( void ) { return false; }
// Attachments
virtual int LookupAttachment( const char *pAttachmentName );
virtual bool GetAttachment( int number, matrix3x4_t &matrix );
virtual bool GetAttachment( int number, Vector &origin );
virtual bool GetAttachment( int number, Vector &origin, QAngle &angles );
virtual bool GetAttachmentVelocity( int number, Vector &originVel, Quaternion &angleVel );
#endif
private:
CBaseViewModel( const CBaseViewModel & ); // not defined, not accessible
#endif
private:
CNetworkVar( int, m_nViewModelIndex ); // Which viewmodel is it?
CNetworkHandle( CBaseEntity, m_hOwner ); // Player or AI carrying this weapon
// soonest time Update will call WeaponIdle
float m_flTimeWeaponIdle;
Activity m_Activity;
// Used to force restart on client, only needs a few bits
CNetworkVar( int, m_nAnimationParity );
// Weapon art
string_t m_sVMName; // View model of this weapon
string_t m_sAnimationPrefix; // Prefix of the animations that should be used by the player carrying this weapon
#if defined( CLIENT_DLL )
int m_nOldAnimationParity;
#endif
typedef CHandle< CBaseCombatWeapon > CBaseCombatWeaponHandle;
CNetworkVar( CBaseCombatWeaponHandle, m_hWeapon );
// Control panel
typedef CHandle<CVGuiScreen> ScreenHandle_t;
CUtlVector<ScreenHandle_t> m_hScreens;
};
#endif // BASEVIEWMODEL_SHARED_H
| {
"pile_set_name": "Github"
} |
#LyX 2.1 created this file. For more info see http://www.lyx.org/
\lyxformat 474
\begin_document
\begin_header
\textclass IEEEtran
\use_default_options false
\maintain_unincluded_children false
\language british
\language_package default
\inputencoding default
\fontencoding global
\font_roman default
\font_sans default
\font_typewriter default
\font_math auto
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref true
\pdf_title "Self-Authentication"
\pdf_author "David Irvine"
\pdf_subject "Authentication"
\pdf_keywords "security, freedom, privacy, authentication"
\pdf_bookmarks true
\pdf_bookmarksnumbered false
\pdf_bookmarksopen false
\pdf_bookmarksopenlevel 1
\pdf_breaklinks false
\pdf_pdfborder true
\pdf_colorlinks false
\pdf_backref false
\pdf_pdfusetitle true
\papersize default
\use_geometry false
\use_package amsmath 0
\use_package amssymb 0
\use_package cancel 1
\use_package esint 0
\use_package mathdots 0
\use_package mathtools 1
\use_package mhchem 1
\use_package stackrel 1
\use_package stmaryrd 1
\use_package undertilde 1
\cite_engine basic
\cite_engine_type default
\biblio_style plain
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\justification true
\use_refstyle 0
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 3
\tocdepth 3
\paragraph_separation indent
\paragraph_indentation default
\quotes_language english
\papercolumns 2
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header
\begin_body
\begin_layout Title
Self-Authentication
\end_layout
\begin_layout Author
\begin_inset Flex Author Name
status open
\begin_layout Plain Layout
David Irvine
\end_layout
\end_inset
\begin_inset Flex Author Mark
status open
\begin_layout Plain Layout
1
\end_layout
\end_inset
\begin_inset Newline newline
\end_inset
\begin_inset Flex Author Affiliation
status open
\begin_layout Plain Layout
MaidSafe.net, 72 Templehill, Troon, South Ayrshire, Scotland, UK.
KA10 6BE.
\end_layout
\end_inset
\begin_inset Newline newline
\end_inset
\begin_inset Flex Author Mark
status open
\begin_layout Plain Layout
1
\end_layout
\end_inset
[email protected]
\end_layout
\begin_layout Page headings
\begin_inset Argument 1
status open
\begin_layout Plain Layout
Irvine: Self-Authentication
\end_layout
\end_inset
\end_layout
\begin_layout Address
First published September 2010.
\end_layout
\begin_layout Abstract
Today all known mechanisms that grant access to distributed or shared services
and resources require central authoritative control in some form, raising
issues in regard to security, trust and privacy.
This paper presents a system of authentication that not only abolishes
the requirements for any centrally stored user credential records, it also
negates the necessity for any server based systems as a login entity for
users to connect with prior to gaining access to a system.
\end_layout
\begin_layout Keywords
security, freedom, privacy, authentication
\end_layout
\begin_layout Standard
\begin_inset CommandInset toc
LatexCommand tableofcontents
\end_inset
\end_layout
\begin_layout Section
Introduction
\end_layout
\begin_layout Standard
\begin_inset Flex Paragraph Start
status open
\begin_layout Plain Layout
\begin_inset Argument 1
status open
\begin_layout Plain Layout
A
\end_layout
\end_inset
uthentication
\end_layout
\end_inset
allows access to a system at a certain level or privilege.
This is generally accepted as the privilege as granted by an authoritative
third party who owns or manages the particular service or resource being
accessed.
In cloud-computing or personal computing this is a limiting factor and
a significant security risk.
Trust in third parties with personal or confidential data is something
that is arguably impossible without any radical change in the very structure
and fabric of modern society.
This paper presents a system where there is no requirement for such a third-par
ty involvement.
\end_layout
\begin_layout Standard
A significant shift in thinking nowadays is to spread data across multiple
locations for security and ease of access.
This has surfaced privacy concerns, and increased awareness of ownership
of data, something that is often disregarded very easily.
But rarely all personal data is surrendered in this way; many systems offer
some level of encryption to ensure privacy of data, but none offer any
system of personal access to personal data, privately.
In almost every case there is some form of contract, whether implied or
actual between the third-party service provider and the client.
Furthermore the supplier may independently decide or be forced to act on
the data, whether deleting encrypted data, going out of business or becoming
a victim of damage or theft.
\end_layout
\begin_layout Standard
This situation is a crucial impediment to personal freedom, and without
a change in technical capabilities that allow the mindset change that appears
more prevalent as time goes by, there will be a significant gulf between
people's individual desires and technology's ability to deliver.
This in itself may impede progress and innovation, which would be an enormous
failure of Science and Engineering to take responsibility for.
\end_layout
\begin_layout Standard
This paper will outline and detail a significant mind-shift in access controls
that not only answer these issues, but take the current situation and dramatica
lly alter our relationship with technology, particularly in regard to storing,
sharing and developing our most personal thoughts, aspirations and desires.
\end_layout
\begin_layout Section
Implementation
\end_layout
\begin_layout Subsection
Issues to be Solved
\end_layout
\begin_layout Standard
Given a traditional resource exchange, the bargain between involved parties
tends to be direct and physically local.
However, the
\emph on
de facto
\emph default
replacement of barter by monetary systems in modern societies introduced
the requirement of trust in third parties providing and controlling the
necessary infrastructure, such as banks and financial authorities.
\end_layout
\begin_layout Standard
It is an illogical consideration to have created a technology based solution
which requires this demand of trust, and to do so in a manner that is almost
uncontrolled.
Technology tends to be based on logic, thus it would appear obvious that
creating, sharing and retrieving information fed into a computing device
by a person should not require that computer to connect to a network of
computers with a controller or guardian that is not a system of pure logic.
\end_layout
\begin_layout Standard
A significant reason for the current situation is the inability for identities
to be created, managed and personally controlled.
This is a reasonable request from people to make from their technology,
but so far has been regarded as impossible by technology professionals.
A system of personal identity management is fundamental for the removal
of the illogical situation of today.
\end_layout
\begin_layout Subsection
Conventions
\end_layout
\begin_layout Standard
There is scope for confusion when using the term
\begin_inset Quotes eld
\end_inset
key
\begin_inset Quotes erd
\end_inset
, as sometimes it refers to a cryptographic key, and at other times it is
in respect to the key of a DHT
\begin_inset Quotes eld
\end_inset
key, value
\begin_inset Quotes erd
\end_inset
pair.
In order to avoid confusion, cryptographic keys will be referred to as
\begin_inset Formula $\mathsf{K}$
\end_inset
, and DHT keys simply as keys.
\end_layout
\begin_layout Itemize
\begin_inset Formula $\mathsf{H}$
\end_inset
≡ Hash function such as SHA, MD5, etc.
\end_layout
\begin_layout Itemize
\begin_inset Formula $\mathsf{PBKDF2_{[Passphrase][Salt]}}$
\end_inset
≡ Password-Based Key Derivation Function or similar.
\end_layout
\begin_layout Itemize
\begin_inset Formula $\mathsf{SymEnc_{[K]}(Data)}$
\end_inset
≡ Symmetrically encrypt
\begin_inset Formula $\mathsf{Data}$
\end_inset
using
\begin_inset Formula $\mathsf{K}$
\end_inset
.
\end_layout
\begin_layout Itemize
\begin_inset Formula $\mathsf{SymDec_{[K]}(Data)}$
\end_inset
≡ Symmetrically decrypt
\begin_inset Formula $\mathsf{Data}$
\end_inset
using
\begin_inset Formula $\mathsf{K}$
\end_inset
.
\end_layout
\begin_layout Itemize
\begin_inset Formula $\mathsf{+}$
\end_inset
≡ Concatenation.
\end_layout
\begin_layout Itemize
\begin_inset Formula $\mathsf{PutV_{[Key]}(Value)}$
\end_inset
≡ Store a
\begin_inset Formula $\mathsf{Value}$
\end_inset
under the given
\begin_inset Formula $\mathsf{Key}$
\end_inset
.
\end_layout
\begin_layout Itemize
\begin_inset Formula $\mathsf{GetV_{[Key]}}$
\end_inset
≡ Retrieve the
\begin_inset Formula $\mathsf{Value}$
\end_inset
identified by
\begin_inset Formula $\mathsf{Key}$
\end_inset
.
\end_layout
\begin_layout Itemize
\begin_inset Formula $\mathsf{DelV_{[Key]}(Value)}$
\end_inset
≡ Delete
\begin_inset Formula $\mathsf{Value}$
\end_inset
identified by
\begin_inset Formula $\mathsf{Key}$
\end_inset
.
\begin_inset Formula $\mathsf{Value}$
\end_inset
must be provided as multiple values can be stored under a single key.
\end_layout
\begin_layout Subsection
Overview of Self-Authentication
\end_layout
\begin_layout Subsubsection
Requirements
\end_layout
\begin_layout Standard
Self-authentication requires a storage mechanism accessible by the users
of the system.
This may be public (such as a peer-to-peer network) or private (such a
a storage area network); this paper assumes that it should also be a key
addressable storage system.
\end_layout
\begin_layout Subsubsection
Methodology
\end_layout
\begin_layout Standard
Self-authentication relies on a system where an entity can create a unique
key to store a value in the storage system.
The value stored with this key should contain an encrypted passport to
data.
This passport may be cryptographically secure keys and or a list of other
keys to make use of the information to be stored and or shared as well
as any additional components required.
\end_layout
\begin_layout Standard
The location of this initial key should be masked or at least not obvious
in the storage mechanism.
Further masking should be considered.
This simplified approach is the basis for self authentication and is extended
into a system that is capable of security in a manner that allows access
data to be stored publically and with no additional requirement such as
firewalls or access controls.
\end_layout
\begin_layout Section
Detailed Implementation
\end_layout
\begin_layout Subsection
Creation of an Account
\end_layout
\begin_layout Standard
Here we will assume there are two inputs from the user of the system: user-name
\begin_inset Formula $\mathsf{U}$
\end_inset
, and password
\begin_inset Formula $\mathsf{W}$
\end_inset
.
A salt
\begin_inset Formula $\mathsf{S}$
\end_inset
is also derived (in a repeatable way) from
\begin_inset Formula $\mathsf{U}$
\end_inset
and
\begin_inset Formula $\mathsf{W}$
\end_inset
.
\end_layout
\begin_layout Standard
To generate a unique identifier, we hash the concatenation of the user-name
and the salt,
\begin_inset Formula $\mathsf{H(U+S)}$
\end_inset
.
\end_layout
\begin_layout Standard
PBKDF2 is used here to strengthen any password keys used.
This is required as user selected passwords are inevitably weak and the
user may not know the user-name is also used as a password in the system.
\begin_inset Formula $\mathsf{Account}$
\end_inset
specifies session data, like user details or an index of references to
further data.
This packet is located through an Access Packet holding a random string
\begin_inset Formula $\mathsf{RndStr}$
\end_inset
.
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{GetV_{[H(U+S)]}\equiv False}$
\end_inset
(Ensure uniqueness)
\end_layout
\begin_layout Enumerate
Generate random string
\begin_inset Formula $\mathsf{RndStr}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+S)]}\left(SymEnc_{[PBKDF2_{[U][S]}]}(RndStr)\right)}$
\end_inset
(Store Access Packet)
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+S+RndStr)]}\left(SymEnc_{[PBKDF2_{[W][S]}]}(Account)\right)}$
\end_inset
(Store Account Packet)
\end_layout
\begin_layout Subsection
Login / Load Session Process
\begin_inset CommandInset label
LatexCommand label
name "sub:Login-to-a"
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{SymDec_{[PBKDF2_{[U][S]}]}\left(GetV_{[H(U+S)]}\right)\equiv RndStr}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{SymDec_{[PBKDF2_{[W][S]}]}(GetV_{[H(U+S+RndStr)]})\equiv Account}$
\end_inset
\end_layout
\begin_layout Standard
For the following operation,
\begin_inset Formula $\mathsf{RndStr}$
\end_inset
should be kept locally for the duration of the session.
\end_layout
\begin_layout Subsection
Logout / Save Session Process
\end_layout
\begin_layout Enumerate
Generate new random string
\begin_inset Formula $\mathsf{RndStr_{new}}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+S+RndStr_{new})]}\left(SymEnc_{[PBKDF2_{[W][S]}]}(Account)\right)}$
\end_inset
(Store new Account Packet)
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+S)]}\left(SymEnc_{[PBKDF2_{[U][S]}]}(RndStr_{new})\right)}$
\end_inset
(Update Access Packet)
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{DelV_{[H(U+S+RndStr)]}(OldAccount)}$
\end_inset
(Delete old Account Packet)
\end_layout
\begin_layout Subsection
Fallback Account Packets
\end_layout
\begin_layout Standard
The previous sections outlined the basic system of authentication.
However, this can be extended for safety reasons.
As with any system, the serialisation and store operation of the account
data can fail for any reason, resulting in unreadable data upon retrieval.
This would be catastrophic as access to the user's data on the system may
be rendered impossible.
To reduce any such risk, a fallback copy of an Account Packet (and its
Access Packet) is kept, to allow reverting to the previous version in case
the current version can't be restored or turns out to have been generated
erroneously.
Like the main Access Packet, the fallback Access Packet contains an (encrypted)
random string, designated
\begin_inset Formula $\mathsf{RndStr_{fallback}}$
\end_inset
.
\end_layout
\begin_layout Subsubsection
Updated Account Creation Process
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{GetV_{[H(U+S)]}\equiv False}$
\end_inset
(Ensure uniqueness of Access Packet)
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{GetV_{[H(U+(S-1))]}\equiv False}$
\end_inset
(Ensure uniqueness of fallback Access Packet)
\end_layout
\begin_layout Enumerate
Generate random string
\begin_inset Formula $\mathsf{RndStr}$
\end_inset
and copy
\begin_inset Formula $\mathsf{RndStr\rightarrow RndStr_{fallback}}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+S)]}\left(SymEnc_{[PBKDF2_{[U][S]}]}(RndStr)\right)}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+(S-1))]}\left(SymEnc_{[PBKDF2_{[U][S-1]}]}(RndStr)\right)}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+S+RndStr)]}\left(SymEnc_{[PBKDF2_{[W][S]}]}(Account)\right)}$
\end_inset
\end_layout
\begin_layout Standard
In this case, the random strings in the Access Packets are the same, thus
point to the same (unique) Account Packet.
Fallback packets are only kept once the Account Packet is updated.
\end_layout
\begin_layout Subsubsection
Updated Login Process
\end_layout
\begin_layout Enumerate
if (
\begin_inset Formula $\mathsf{GetV_{[H(U+S)]}\equiv EncRndStr}$
\end_inset
)
\end_layout
\begin_deeper
\begin_layout Enumerate
\begin_inset Formula $\mathsf{SymDec_{[PBKDF2_{[U][S]}]}(EncRndStr)\equiv RndStr}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{SymDec_{[PBKDF2_{[W][S]}]}\left(GetV_{[H(U+S+RndStr)]}\right)\equiv}$
\end_inset
\begin_inset Newline newline
\end_inset
\begin_inset Formula $\mathsf{Account}$
\end_inset
\end_layout
\end_deeper
\begin_layout Enumerate
else (or if previous attempt failed)
\end_layout
\begin_deeper
\begin_layout Enumerate
\begin_inset Formula $\mathsf{GetV_{[H(U+(S-1))]}\equiv EncRndStr_{fallback}}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{SymDec_{[PBKDF2_{[U][S-1]}]}(EncRndStr_{fallback})\equiv}$
\end_inset
\begin_inset Newline newline
\end_inset
\begin_inset Formula $\mathsf{RndStr_{fallback}}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{SymDec_{[PBKDF2_{[W][S-1]}]}\left(GetV_{[H(U+S+RndStr_{fallback})]}\right)}$
\end_inset
\begin_inset Newline newline
\end_inset
\begin_inset Formula $\mathsf{\equiv Account_{fallback}}$
\end_inset
\end_layout
\end_deeper
\begin_layout Subsubsection
Updated Logout / Save Session Process
\end_layout
\begin_layout Standard
Designate existing
\begin_inset Formula $\mathsf{RndStr}$
\end_inset
as
\begin_inset Formula $\mathsf{RndStr_{old}}$
\end_inset
and
\begin_inset Formula $\mathsf{RndStr_{fallback}}$
\end_inset
as
\begin_inset Formula $\mathsf{RndStr_{fallback\,old}}$
\end_inset
\end_layout
\begin_layout Enumerate
Generate new random string
\begin_inset Formula $\mathsf{RndStr_{new}}$
\end_inset
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+S)]}\left(SymEnc_{[PBKDF2_{[U][S]}]}(RndStr_{new})\right)}$
\end_inset
(Update Access Packet with new random string)
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+(S-1))]}\left(SymEnc_{[PBKDF2_{[U][S-1]}]}(RndStr_{old})\right)}$
\end_inset
(Update fallback Access Packet with old random string)
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{PutV_{[H(U+S+RndStr_{new})]}\left(SymEnc_{[PBKDF2_{[W][S]}]}(Account)\right)}$
\end_inset
(Update Account Packet using new random string)
\end_layout
\begin_layout Enumerate
\begin_inset Formula $\mathsf{DelV_{[H(U+S+RndStr_{fallback\,old})]}(Account_{fallback\,old})}$
\end_inset
(Delete old Account Packet)
\end_layout
\begin_layout Standard
The previous Account Packet remains untouched, instead the fallback Access
Packet is redirected to it and the normal Access Packet points to the new
Account Packet.
The previous fallback Account Packet is deleted.
This is a security measure to hinder slow brute-force attacks on decrypting
the Access Packet, which by the time the cleartext random string is obtained
would make it obsolete.
\end_layout
\begin_layout Subsection
Further Enhancements
\end_layout
\begin_layout Subsubsection
Time Based Obfuscation
\end_layout
\begin_layout Standard
In the previous sections a system of self authentication was detailed which
is very effective.
A potential failure point, however, may be the Access Packets, as those
are never altering their location (key) and can pose a target for any attacker
who is monitoring data traffic between the user and the system.
\end_layout
\begin_layout Standard
To remove this weakness, a predictably altering piece of data can be introduced,
such as time (e.g.
week number, day of year or similar).
In this case in
\begin_inset CommandInset ref
LatexCommand ref
reference "sub:Login-to-a"
\end_inset
the
\begin_inset Formula $\mathsf{GetV}$
\end_inset
call would be iterative, starting at the current time slot and decrementing
until it returns with a value.
Access Packets at
\begin_inset Quotes eld
\end_inset
outdated
\begin_inset Quotes erd
\end_inset
locations would be deleted on detection, and updates always stored in the
current location, resulting in regularly
\begin_inset Quotes eld
\end_inset
moving
\begin_inset Quotes erd
\end_inset
packets.
\end_layout
\begin_layout Subsubsection
Distributed Storage System
\end_layout
\begin_layout Standard
This system can be enhanced with the introduction of a distributed storage
network as described in
\begin_inset CommandInset citation
LatexCommand cite
key "4"
\end_inset
.
This has many advantages including the ability to mask any account data
in a large address space and protect with cryptographically secure privileges
that can prevent unauthorised deletion or any loss of data packets.
\end_layout
\begin_layout Section
Conclusions
\end_layout
\begin_layout Standard
The system presented is one version of a server-less authentication system.
There is a strong case for this to enable true cloud based services with
users being in control of their own data and access privileges.
Such a system can be applied in a multitude of situations and may be particular
ly useful with paid services, which would not require the customer to divulge
any personal information or create yet another identity specifically for
a single service, providing a shared infrastructure exists.
\end_layout
\begin_layout Standard
We demonstrated a working version of such a system for the first time in
April 2008 in our offices in Troon, Scotland, and as far as we are aware
this was the first time in history a person created their own identity,
stored it and managed all their actions without any server requirement
and without any third party control.
\end_layout
\begin_layout Section*
Acknowledgment
\end_layout
\begin_layout Standard
Thanks to Yanick Vézina who provided great assistance in proof reading this
paper.
\end_layout
\begin_layout Bibliography
\begin_inset CommandInset bibitem
LatexCommand bibitem
label "1"
key "1"
\end_inset
as described by Van Jacobson in this link below, August 30, 2006 http://video.Goo
gle.com/videoplay?docid=-6972678839686672840
\end_layout
\begin_layout Bibliography
\begin_inset CommandInset bibitem
LatexCommand bibitem
label "2"
key "2"
\end_inset
David Irvine, Self Encrypting Data, [email protected]
\end_layout
\begin_layout Bibliography
\begin_inset CommandInset bibitem
LatexCommand bibitem
label "3"
key "3"
\end_inset
David Irvine, "Peer to Peer" Public Key Infrastructure, [email protected]
\end_layout
\begin_layout Bibliography
\begin_inset CommandInset bibitem
LatexCommand bibitem
label "4"
key "4"
\end_inset
David Irvine, maidsafe: A new networking paradigm, [email protected]
\end_layout
\begin_layout Biography without photo
\begin_inset Argument 1
status open
\begin_layout Plain Layout
David Irvine
\end_layout
\end_inset
is a Scottish Engineer and innovator who has spent the last 12 years researchin
g ways to make computers function in a more efficient manner.
\end_layout
\begin_layout Biography without photo
He is an Inventor listed on more than 20 patent submissions and was Designer
of one of the World's largest private networks (Saudi Aramco, over $300M).
He is an experienced Project Manager and has been involved in start up
businesses since 1995 and has provided business consultancy to corporates
and SMEs in many sectors.
\end_layout
\begin_layout Biography without photo
He has presented technology at Google (Seattle), British Computer Society
(Christmas Lecture) and many others.
\end_layout
\begin_layout Biography without photo
He has spent many years as a lifeboat Helmsman and is a keen sailor when
time permits.
\end_layout
\end_body
\end_document
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Cyphon Engine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cyphon Engine. If not, see <http://www.gnu.org/licenses/>.
#
# Generated by Django 1.10.1 on 2017-03-20 16:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import utils.validators.validators
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Label',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=40, unique=True)),
],
),
migrations.CreateModel(
name='LabelField',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('field_name', models.CharField(max_length=40, unique=True, validators=[utils.validators.validators.field_name_validator])),
('field_type', models.CharField(choices=[('BooleanField', 'BooleanField'), ('CharField', 'CharField'), ('ChoiceField', 'ChoiceField'), ('DateTimeField', 'DateTimeField'), ('EmailField', 'EmailField'), ('FileField', 'FileField'), ('FloatField', 'FloatField'), ('IntegerField', 'IntegerField'), ('GenericIPAddressField', 'IPAddressField'), ('ListField', 'ListField'), ('PointField', 'PointField'), ('TextField', 'TextField'), ('URLField', 'URLField'), ('EmbeddedDocument', 'EmbeddedDocument')], max_length=40)),
('target_type', models.CharField(blank=True, choices=[('Account', 'Account'), ('DateTime', 'DateTime'), ('IPAddress', 'IPAddress'), ('Keyword', 'Keyword'), ('Location', 'Location')], max_length=40, null=True)),
('object_id', models.PositiveIntegerField(help_text='The id of the inspection or procedure that will analyze the data.', verbose_name='analyzer id')),
('content_type', models.ForeignKey(help_text='Inspections determine whether data match a set of rules, defined by regular expressions. <br>Procedures perform more complex analyses, such as sentiment analysis or geolocation.', on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType', verbose_name='analyzer type')),
],
),
migrations.AddField(
model_name='label',
name='fields',
field=models.ManyToManyField(to='labels.LabelField'),
),
migrations.AlterUniqueTogether(
name='labelfield',
unique_together=set([('field_name', 'content_type', 'object_id')]),
),
]
| {
"pile_set_name": "Github"
} |
<?php
/**
* *** BEGIN LICENSE BLOCK *****
*
* This file is part of FirePHP (http://www.firephp.org/).
*
* Software License Agreement (New BSD License)
*
* Copyright (c) 2006-2008, Christoph Dorn
* 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 Christoph Dorn 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.
*
* ***** END LICENSE BLOCK *****
*
* @copyright Copyright (C) 2007-2008 Christoph Dorn
* @author Christoph Dorn <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php
* @package FirePHP
*/
/**
* Sends the given data to the FirePHP Firefox Extension.
* The data can be displayed in the Firebug Console or in the
* "Server" request tab.
*
* For more information see: http://www.firephp.org/
*
* @copyright Copyright (C) 2007-2008 Christoph Dorn
* @author Christoph Dorn <[email protected]>
* @license http://www.opensource.org/licenses/bsd-license.php
* @package FirePHP
*/
class FirePHP {
/**
* FirePHP version
*
* @var string
*/
const VERSION = '0.2.0';
/**
* Firebug LOG level
*
* Logs a message to firebug console.
*
* @var string
*/
const LOG = 'LOG';
/**
* Firebug INFO level
*
* Logs a message to firebug console and displays an info icon before the message.
*
* @var string
*/
const INFO = 'INFO';
/**
* Firebug WARN level
*
* Logs a message to firebug console, displays an warning icon before the message and colors the line turquoise.
*
* @var string
*/
const WARN = 'WARN';
/**
* Firebug ERROR level
*
* Logs a message to firebug console, displays an error icon before the message and colors the line yellow. Also increments the firebug error count.
*
* @var string
*/
const ERROR = 'ERROR';
/**
* Dumps a variable to firebug's server panel
*
* @var string
*/
const DUMP = 'DUMP';
/**
* Displays a stack trace in firebug console
*
* @var string
*/
const TRACE = 'TRACE';
/**
* Displays an exception in firebug console
*
* Increments the firebug error count.
*
* @var string
*/
const EXCEPTION = 'EXCEPTION';
/**
* Displays an table in firebug console
*
* @var string
*/
const TABLE = 'TABLE';
/**
* Starts a group in firebug console
*
* @var string
*/
const GROUP_START = 'GROUP_START';
/**
* Ends a group in firebug console
*
* @var string
*/
const GROUP_END = 'GROUP_END';
/**
* Singleton instance of FirePHP
*
* @var FirePHP
*/
protected static $instance = null;
/**
* Wildfire protocol message index
*
* @var int
*/
protected $messageIndex = 1;
/**
* Options for the library
*
* @var array
*/
protected $options = array();
/**
* Filters used to exclude object members when encoding
*
* @var array
*/
protected $objectFilters = array();
/**
* A stack of objects used to detect recursion during object encoding
*
* @var object
*/
protected $objectStack = array();
/**
* Flag to enable/disable logging
*
* @var boolean
*/
protected $enabled = true;
/**
* The object constructor
*/
function __construct() {
$this->options['maxObjectDepth'] = 10;
$this->options['maxArrayDepth'] = 20;
$this->options['useNativeJsonEncode'] = true;
$this->options['includeLineNumbers'] = true;
}
/**
* When the object gets serialized only include specific object members.
*
* @return array
*/
public function __sleep() {
return array('options','objectFilters','enabled');
}
/**
* Gets singleton instance of FirePHP
*
* @param boolean $AutoCreate
* @return FirePHP
*/
public static function getInstance($AutoCreate=false) {
if($AutoCreate===true && !self::$instance) {
self::init();
}
return self::$instance;
}
/**
* Creates FirePHP object and stores it for singleton access
*
* @return FirePHP
*/
public static function init() {
return self::$instance = new self();
}
/**
* Enable and disable logging to Firebug
*
* @param boolean $Enabled TRUE to enable, FALSE to disable
* @return void
*/
public function setEnabled($Enabled) {
$this->enabled = $Enabled;
}
/**
* Check if logging is enabled
*
* @return boolean TRUE if enabled
*/
public function getEnabled() {
return $this->enabled;
}
/**
* Specify a filter to be used when encoding an object
*
* Filters are used to exclude object members.
*
* @param string $Class The class name of the object
* @param array $Filter An array or members to exclude
* @return void
*/
public function setObjectFilter($Class, $Filter) {
$this->objectFilters[$Class] = $Filter;
}
/**
* Set some options for the library
*
* Options:
* - maxObjectDepth: The maximum depth to traverse objects (default: 10)
* - maxArrayDepth: The maximum depth to traverse arrays (default: 20)
* - useNativeJsonEncode: If true will use json_encode() (default: true)
* - includeLineNumbers: If true will include line numbers and filenames (default: true)
*
* @param array $Options The options to be set
* @return void
*/
public function setOptions($Options) {
$this->options = array_merge($this->options,$Options);
}
/**
* Register FirePHP as your error handler
*
* Will throw exceptions for each php error.
*/
public function registerErrorHandler()
{
//NOTE: The following errors will not be caught by this error handler:
// E_ERROR, E_PARSE, E_CORE_ERROR,
// E_CORE_WARNING, E_COMPILE_ERROR,
// E_COMPILE_WARNING, E_STRICT
set_error_handler(array($this,'errorHandler'));
}
/**
* FirePHP's error handler
*
* Throws exception for each php error that will occur.
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
* @param array $errcontext
*/
public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
{
// Don't throw exception if error reporting is switched off
if (error_reporting() == 0) {
return;
}
// Only throw exceptions for errors we are asking for
if (error_reporting() & $errno) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
}
/**
* Register FirePHP as your exception handler
*/
public function registerExceptionHandler()
{
set_exception_handler(array($this,'exceptionHandler'));
}
/**
* FirePHP's exception handler
*
* Logs all exceptions to your firebug console and then stops the script.
*
* @param Exception $Exception
* @throws Exception
*/
function exceptionHandler($Exception) {
$this->fb($Exception);
}
/**
* Set custom processor url for FirePHP
*
* @param string $URL
*/
public function setProcessorUrl($URL)
{
$this->setHeader('X-FirePHP-ProcessorURL', $URL);
}
/**
* Set custom renderer url for FirePHP
*
* @param string $URL
*/
public function setRendererUrl($URL)
{
$this->setHeader('X-FirePHP-RendererURL', $URL);
}
/**
* Start a group for following messages
*
* @param string $Name
* @return true
* @throws Exception
*/
public function group($Name) {
return $this->fb(null, $Name, FirePHP::GROUP_START);
}
/**
* Ends a group you have started before
*
* @return true
* @throws Exception
*/
public function groupEnd() {
return $this->fb(null, null, FirePHP::GROUP_END);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::LOG
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function log($Object, $Label=null) {
return $this->fb($Object, $Label, FirePHP::LOG);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::INFO
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function info($Object, $Label=null) {
return $this->fb($Object, $Label, FirePHP::INFO);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::WARN
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function warn($Object, $Label=null) {
return $this->fb($Object, $Label, FirePHP::WARN);
}
/**
* Log object with label to firebug console
*
* @see FirePHP::ERROR
* @param mixes $Object
* @param string $Label
* @return true
* @throws Exception
*/
public function error($Object, $Label=null) {
return $this->fb($Object, $Label, FirePHP::ERROR);
}
/**
* Dumps key and variable to firebug server panel
*
* @see FirePHP::DUMP
* @param string $Key
* @param mixed $Variable
* @return true
* @throws Exception
*/
public function dump($Key, $Variable) {
return $this->fb($Variable, $Key, FirePHP::DUMP);
}
/**
* Log a trace in the firebug console
*
* @see FirePHP::TRACE
* @param string $Label
* @return true
* @throws Exception
*/
public function trace($Label) {
return $this->fb($Label, FirePHP::TRACE);
}
/**
* Log a table in the firebug console
*
* @see FirePHP::TABLE
* @param string $Label
* @param string $Table
* @return true
* @throws Exception
*/
public function table($Label, $Table) {
return $this->fb($Table, $Label, FirePHP::TABLE);
}
/**
* Check if FirePHP is installed on client
*
* @return boolean
*/
public function detectClientExtension() {
/* Check if FirePHP is installed on client */
if(!@preg_match_all('/\sFirePHP\/([\.|\d]*)\s?/si',$this->getUserAgent(),$m) ||
!version_compare($m[1][0],'0.0.6','>=')) {
return false;
}
return true;
}
/**
* Log varible to Firebug
*
* @see http://www.firephp.org/Wiki/Reference/Fb
* @param mixed $Object The variable to be logged
* @return true Return TRUE if message was added to headers, FALSE otherwise
* @throws Exception
*/
public function fb($Object) {
if(!$this->enabled) {
return false;
}
if (headers_sent($filename, $linenum)) {
throw $this->newException('Headers already sent in '.$filename.' on line '.$linenum.'. Cannot send log data to FirePHP. You must have Output Buffering enabled via ob_start() or output_buffering ini directive.');
}
$Type = null;
$Label = null;
if(func_num_args()==1) {
} else
if(func_num_args()==2) {
switch(func_get_arg(1)) {
case self::LOG:
case self::INFO:
case self::WARN:
case self::ERROR:
case self::DUMP:
case self::TRACE:
case self::EXCEPTION:
case self::TABLE:
case self::GROUP_START:
case self::GROUP_END:
$Type = func_get_arg(1);
break;
default:
$Label = func_get_arg(1);
break;
}
} else
if(func_num_args()==3) {
$Type = func_get_arg(2);
$Label = func_get_arg(1);
} else {
throw $this->newException('Wrong number of arguments to fb() function!');
}
if(!$this->detectClientExtension()) {
return false;
}
$meta = array();
$skipFinalObjectEncode = false;
if($Object instanceof Exception) {
$meta['file'] = $this->_escapeTraceFile($Object->getFile());
$meta['line'] = $Object->getLine();
$trace = $Object->getTrace();
if($Object instanceof ErrorException
&& isset($trace[0]['function'])
&& $trace[0]['function']=='errorHandler'
&& isset($trace[0]['class'])
&& $trace[0]['class']=='FirePHP') {
$severity = false;
switch($Object->getSeverity()) {
case E_WARNING: $severity = 'E_WARNING'; break;
case E_NOTICE: $severity = 'E_NOTICE'; break;
case E_USER_ERROR: $severity = 'E_USER_ERROR'; break;
case E_USER_WARNING: $severity = 'E_USER_WARNING'; break;
case E_USER_NOTICE: $severity = 'E_USER_NOTICE'; break;
case E_STRICT: $severity = 'E_STRICT'; break;
case E_RECOVERABLE_ERROR: $severity = 'E_RECOVERABLE_ERROR'; break;
case E_DEPRECATED: $severity = 'E_DEPRECATED'; break;
case E_USER_DEPRECATED: $severity = 'E_USER_DEPRECATED'; break;
}
$Object = array('Class'=>get_class($Object),
'Message'=>$severity.': '.$Object->getMessage(),
'File'=>$this->_escapeTraceFile($Object->getFile()),
'Line'=>$Object->getLine(),
'Type'=>'trigger',
'Trace'=>$this->_escapeTrace(array_splice($trace,2)));
$skipFinalObjectEncode = true;
} else {
$Object = array('Class'=>get_class($Object),
'Message'=>$Object->getMessage(),
'File'=>$this->_escapeTraceFile($Object->getFile()),
'Line'=>$Object->getLine(),
'Type'=>'throw',
'Trace'=>$this->_escapeTrace($trace));
$skipFinalObjectEncode = true;
}
$Type = self::EXCEPTION;
} else
if($Type==self::TRACE) {
$trace = debug_backtrace();
if(!$trace) return false;
for( $i=0 ; $i<sizeof($trace) ; $i++ ) {
if(isset($trace[$i]['class'])
&& isset($trace[$i]['file'])
&& ($trace[$i]['class']=='FirePHP'
|| $trace[$i]['class']=='FB')
&& (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
|| substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
/* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
} else
if(isset($trace[$i]['class'])
&& isset($trace[$i+1]['file'])
&& $trace[$i]['class']=='FirePHP'
&& substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip fb() */
} else
if($trace[$i]['function']=='fb'
|| $trace[$i]['function']=='trace'
|| $trace[$i]['function']=='send') {
$Object = array('Class'=>isset($trace[$i]['class'])?$trace[$i]['class']:'',
'Type'=>isset($trace[$i]['type'])?$trace[$i]['type']:'',
'Function'=>isset($trace[$i]['function'])?$trace[$i]['function']:'',
'Message'=>$trace[$i]['args'][0],
'File'=>isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'',
'Line'=>isset($trace[$i]['line'])?$trace[$i]['line']:'',
'Args'=>isset($trace[$i]['args'])?$this->encodeObject($trace[$i]['args']):'',
'Trace'=>$this->_escapeTrace(array_splice($trace,$i+1)));
$skipFinalObjectEncode = true;
$meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
$meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
break;
}
}
} else
if($Type==self::TABLE) {
if(isset($Object[0]) && is_string($Object[0])) {
$Object[1] = $this->encodeTable($Object[1]);
} else {
$Object = $this->encodeTable($Object);
}
$skipFinalObjectEncode = true;
} else {
if($Type===null) {
$Type = self::LOG;
}
}
if($this->options['includeLineNumbers']) {
if(!isset($meta['file']) || !isset($meta['line'])) {
$trace = debug_backtrace();
for( $i=0 ; $trace && $i<sizeof($trace) ; $i++ ) {
if(isset($trace[$i]['class'])
&& isset($trace[$i]['file'])
&& ($trace[$i]['class']=='FirePHP'
|| $trace[$i]['class']=='FB')
&& (substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php'
|| substr($this->_standardizePath($trace[$i]['file']),-29,29)=='FirePHPCore/FirePHP.class.php')) {
/* Skip - FB::trace(), FB::send(), $firephp->trace(), $firephp->fb() */
} else
if(isset($trace[$i]['class'])
&& isset($trace[$i+1]['file'])
&& $trace[$i]['class']=='FirePHP'
&& substr($this->_standardizePath($trace[$i+1]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip fb() */
} else
if(isset($trace[$i]['file'])
&& substr($this->_standardizePath($trace[$i]['file']),-18,18)=='FirePHPCore/fb.php') {
/* Skip FB::fb() */
} else {
$meta['file'] = isset($trace[$i]['file'])?$this->_escapeTraceFile($trace[$i]['file']):'';
$meta['line'] = isset($trace[$i]['line'])?$trace[$i]['line']:'';
break;
}
}
}
} else {
unset($meta['file']);
unset($meta['line']);
}
$this->setHeader('X-Wf-Protocol-1','http://meta.wildfirehq.org/Protocol/JsonStream/0.2');
$this->setHeader('X-Wf-1-Plugin-1','http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/'.self::VERSION);
$structure_index = 1;
if($Type==self::DUMP) {
$structure_index = 2;
$this->setHeader('X-Wf-1-Structure-2','http://meta.firephp.org/Wildfire/Structure/FirePHP/Dump/0.1');
} else {
$this->setHeader('X-Wf-1-Structure-1','http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1');
}
if($Type==self::DUMP) {
$msg = '{"'.$Label.'":'.$this->jsonEncode($Object, $skipFinalObjectEncode).'}';
} else {
$msg_meta = array('Type'=>$Type);
if($Label!==null) {
$msg_meta['Label'] = $Label;
}
if(isset($meta['file'])) {
$msg_meta['File'] = $meta['file'];
}
if(isset($meta['line'])) {
$msg_meta['Line'] = $meta['line'];
}
$msg = '['.$this->jsonEncode($msg_meta).','.$this->jsonEncode($Object, $skipFinalObjectEncode).']';
}
$parts = explode("\n",chunk_split($msg, 5000, "\n"));
for( $i=0 ; $i<count($parts) ; $i++) {
$part = $parts[$i];
if ($part) {
if(count($parts)>2) {
// Message needs to be split into multiple parts
$this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
(($i==0)?strlen($msg):'')
. '|' . $part . '|'
. (($i<count($parts)-2)?'\\':''));
} else {
$this->setHeader('X-Wf-1-'.$structure_index.'-'.'1-'.$this->messageIndex,
strlen($part) . '|' . $part . '|');
}
$this->messageIndex++;
if ($this->messageIndex > 99999) {
throw new Exception('Maximum number (99,999) of messages reached!');
}
}
}
$this->setHeader('X-Wf-1-Index',$this->messageIndex-1);
return true;
}
/**
* Standardizes path for windows systems.
*
* @param string $Path
* @return string
*/
protected function _standardizePath($Path) {
return preg_replace('/\\\\+/','/',$Path);
}
/**
* Escape trace path for windows systems
*
* @param array $Trace
* @return array
*/
protected function _escapeTrace($Trace) {
if(!$Trace) return $Trace;
for( $i=0 ; $i<sizeof($Trace) ; $i++ ) {
if(isset($Trace[$i]['file'])) {
$Trace[$i]['file'] = $this->_escapeTraceFile($Trace[$i]['file']);
}
if(isset($Trace[$i]['args'])) {
$Trace[$i]['args'] = $this->encodeObject($Trace[$i]['args']);
}
}
return $Trace;
}
/**
* Escape file information of trace for windows systems
*
* @param string $File
* @return string
*/
protected function _escapeTraceFile($File) {
/* Check if we have a windows filepath */
if(strpos($File,'\\')) {
/* First strip down to single \ */
$file = preg_replace('/\\\\+/','\\',$File);
return $file;
}
return $File;
}
/**
* Send header
*
* @param string $Name
* @param string_type $Value
*/
protected function setHeader($Name, $Value) {
return header($Name.': '.$Value);
}
/**
* Get user agent
*
* @return string|false
*/
protected function getUserAgent() {
if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
return $_SERVER['HTTP_USER_AGENT'];
}
/**
* Returns a new exception
*
* @param string $Message
* @return Exception
*/
protected function newException($Message) {
return new Exception($Message);
}
/**
* Encode an object into a JSON string
*
* Uses PHP's jeson_encode() if available
*
* @param object $Object The object to be encoded
* @return string The JSON string
*/
protected function jsonEncode($Object, $skipObjectEncode=false)
{
if(!$skipObjectEncode) {
$Object = $this->encodeObject($Object);
}
if(function_exists('json_encode')
&& $this->options['useNativeJsonEncode']!=false) {
return json_encode($Object);
} else {
return $this->json_encode($Object);
}
}
/**
* Encodes a table by encoding each row and column with encodeObject()
*
* @param array $Table The table to be encoded
* @return array
*/
protected function encodeTable($Table) {
if(!$Table) return $Table;
for( $i=0 ; $i<count($Table) ; $i++ ) {
if(is_array($Table[$i])) {
for( $j=0 ; $j<count($Table[$i]) ; $j++ ) {
$Table[$i][$j] = $this->encodeObject($Table[$i][$j]);
}
}
}
return $Table;
}
/**
* Encodes an object including members with
* protected and private visibility
*
* @param Object $Object The object to be encoded
* @param int $Depth The current traversal depth
* @return array All members of the object
*/
protected function encodeObject($Object, $ObjectDepth = 1, $ArrayDepth = 1)
{
$return = array();
if (is_object($Object)) {
if ($ObjectDepth > $this->options['maxObjectDepth']) {
return '** Max Object Depth ('.$this->options['maxObjectDepth'].') **';
}
foreach ($this->objectStack as $refVal) {
if ($refVal === $Object) {
return '** Recursion ('.get_class($Object).') **';
}
}
array_push($this->objectStack, $Object);
$return['__className'] = $class = get_class($Object);
$reflectionClass = new ReflectionClass($class);
$properties = array();
foreach( $reflectionClass->getProperties() as $property) {
$properties[$property->getName()] = $property;
}
$members = (array)$Object;
foreach( $properties as $raw_name => $property ) {
$name = $raw_name;
if($property->isStatic()) {
$name = 'static:'.$name;
}
if($property->isPublic()) {
$name = 'public:'.$name;
} else
if($property->isPrivate()) {
$name = 'private:'.$name;
$raw_name = "\0".$class."\0".$raw_name;
} else
if($property->isProtected()) {
$name = 'protected:'.$name;
$raw_name = "\0".'*'."\0".$raw_name;
}
if(!(isset($this->objectFilters[$class])
&& is_array($this->objectFilters[$class])
&& in_array($raw_name,$this->objectFilters[$class]))) {
if(array_key_exists($raw_name,$members)
&& !$property->isStatic()) {
$return[$name] = $this->encodeObject($members[$raw_name], $ObjectDepth + 1, 1);
} else {
if(method_exists($property,'setAccessible')) {
$property->setAccessible(true);
$return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1);
} else
if($property->isPublic()) {
$return[$name] = $this->encodeObject($property->getValue($Object), $ObjectDepth + 1, 1);
} else {
$return[$name] = '** Need PHP 5.3 to get value **';
}
}
} else {
$return[$name] = '** Excluded by Filter **';
}
}
// Include all members that are not defined in the class
// but exist in the object
foreach( $members as $raw_name => $value ) {
$name = $raw_name;
if ($name{0} == "\0") {
$parts = explode("\0", $name);
$name = $parts[2];
}
if(!isset($properties[$name])) {
$name = 'undeclared:'.$name;
if(!(isset($this->objectFilters[$class])
&& is_array($this->objectFilters[$class])
&& in_array($raw_name,$this->objectFilters[$class]))) {
$return[$name] = $this->encodeObject($value, $ObjectDepth + 1, 1);
} else {
$return[$name] = '** Excluded by Filter **';
}
}
}
array_pop($this->objectStack);
} elseif (is_array($Object)) {
if ($ArrayDepth > $this->options['maxArrayDepth']) {
return '** Max Array Depth ('.$this->options['maxArrayDepth'].') **';
}
foreach ($Object as $key => $val) {
// Encoding the $GLOBALS PHP array causes an infinite loop
// if the recursion is not reset here as it contains
// a reference to itself. This is the only way I have come up
// with to stop infinite recursion in this case.
if($key=='GLOBALS'
&& is_array($val)
&& array_key_exists('GLOBALS',$val)) {
$val['GLOBALS'] = '** Recursion (GLOBALS) **';
}
$return[$key] = $this->encodeObject($val, 1, $ArrayDepth + 1);
}
} else {
if(self::is_utf8($Object)) {
return $Object;
} else {
return utf8_encode($Object);
}
}
return $return;
}
/**
* Returns true if $string is valid UTF-8 and false otherwise.
*
* @param mixed $str String to be tested
* @return boolean
*/
protected static function is_utf8($str) {
$c=0; $b=0;
$bits=0;
$len=strlen($str);
for($i=0; $i<$len; $i++){
$c=ord($str[$i]);
if($c > 128){
if(($c >= 254)) return false;
elseif($c >= 252) $bits=6;
elseif($c >= 248) $bits=5;
elseif($c >= 240) $bits=4;
elseif($c >= 224) $bits=3;
elseif($c >= 192) $bits=2;
else return false;
if(($i+$bits) > $len) return false;
while($bits > 1){
$i++;
$b=ord($str[$i]);
if($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: 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.
*
* THIS SOFTWARE IS PROVIDED ``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 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
* @package Services_JSON
* @author Michal Migurski <[email protected]>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @author Christoph Dorn <[email protected]>
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Keep a list of objects as we descend into the array so we can detect recursion.
*/
private $json_objectStack = array();
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
private function json_utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
private function json_encode($var)
{
if(is_object($var)) {
if(in_array($var,$this->json_objectStack)) {
return '"** Recursion **"';
}
}
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->json_utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$this->json_objectStack[] = $var;
$properties = array_map(array($this, 'json_name_value'),
array_keys($var),
array_values($var));
array_pop($this->json_objectStack);
foreach($properties as $property) {
if($property instanceof Exception) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
$this->json_objectStack[] = $var;
// treat it like a regular array
$elements = array_map(array($this, 'json_encode'), $var);
array_pop($this->json_objectStack);
foreach($elements as $element) {
if($element instanceof Exception) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = self::encodeObject($var);
$this->json_objectStack[] = $var;
$properties = array_map(array($this, 'json_name_value'),
array_keys($vars),
array_values($vars));
array_pop($this->json_objectStack);
foreach($properties as $property) {
if($property instanceof Exception) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return null;
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
private function json_name_value($name, $value)
{
// Encoding the $GLOBALS PHP array causes an infinite loop
// if the recursion is not reset here as it contains
// a reference to itself. This is the only way I have come up
// with to stop infinite recursion in this case.
if($name=='GLOBALS'
&& is_array($value)
&& array_key_exists('GLOBALS',$value)) {
$value['GLOBALS'] = '** Recursion **';
}
$encoded_value = $this->json_encode($value);
if($encoded_value instanceof Exception) {
return $encoded_value;
}
return $this->json_encode(strval($name)) . ':' . $encoded_value;
}
}
| {
"pile_set_name": "Github"
} |
import sys, os, math
import matplotlib.pyplot as plt
from optparse import OptionParser
cities = []
def strip(s):
return s.strip('\t\n ')
def load_data(path):
global cities
f = open(path, 'r')
lines = f.readlines()
f.close();
for l in lines:
if l.startswith('#'):
continue
data = l.split('|')
if len(data) < 6:
continue
item = {}
item['name'] = strip(data[0])
item['population'] = int(strip(data[1]))
item['region'] = strip(data[2])
item['width'] = float(strip(data[3]))
item['height'] = float(strip(data[4]))
item['square'] = float(data[5])
cities.append(item)
# build plot
print "Cities count: %d" % len(cities)
def formula(popul, base = 32, mult = 0.5):
#return math.exp(math.log(popul, base)) * mult
return math.pow(popul, 1 / base) * mult
def avgDistance(approx, data):
dist = 0
for x in xrange(len(data)):
dist += math.fabs(approx[x] - data[x])
return dist / float(len(data))
def findBest(popul, data, minBase = 5, maxBase = 100, stepBase = 0.1, minMult = 0.01, maxMult = 1, stepMult = 0.01):
# try to find best parameters
base = minBase
minDist = -1
bestMult = minMult
bestBase = base
while base <= maxBase:
print "%.02f%% best mult: %f, best base: %f, best dist: %f" % (100 * (base - minBase) / (maxBase - minBase), bestMult, bestBase, minDist)
mult = minMult
while mult <= maxMult:
approx = []
for p in popul:
approx.append(formula(p, base, mult))
dist = avgDistance(approx, data)
if minDist < 0 or minDist > dist:
minDist = dist
bestBase = base
bestMult = mult
mult += stepMult
base += stepBase
return (bestBase, bestMult)
def process_data(steps_count, base, mult, bestFind = False, dataFlag = 0):
avgData = []
maxData = []
sqrData = []
population = []
maxPopulation = 0
minPopulation = -1
for city in cities:
p = city['population']
w = city['width']
h = city['height']
s = city['square']
population.append(p)
if p > maxPopulation:
maxPopulation = p
if minPopulation < 0 or p < minPopulation:
minPopulation = p
maxData.append(max([w, h]))
avgData.append((w + h) * 0.5)
sqrData.append(math.sqrt(s))
bestBase = base
bestMult = mult
if bestFind:
d = maxData
if dataFlag == 1:
d = avgData
elif dataFlag == 2:
d = sqrData
bestBase, bestMult = findBest(population, d)
print "Finished\n\nBest mult: %f, Best base: %f" % (bestMult, bestBase)
approx = []
population2 = []
v = minPopulation
step = (maxPopulation - minPopulation) / float(steps_count)
for i in xrange(0, steps_count):
approx.append(formula(v, bestBase, bestMult))
population2.append(v)
v += step
plt.plot(population, avgData, 'bo', population, maxData, 'ro', population, sqrData, 'go', population2, approx, 'y')
plt.axis([minPopulation, maxPopulation, 0, 100])
plt.xscale('log')
plt.show()
if __name__ == "__main__":
if len(sys.argv) < 3:
print 'city_radius.py <data_file> <steps>'
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename", default="city_popul_sqr.data",
help="source data file", metavar="path")
parser.add_option("-s", "--scan",
dest="best", default=False, action="store_true",
help="scan best values of mult and base")
parser.add_option('-m', "--mult",
dest='mult', default=1,
help='multiplier value')
parser.add_option('-b', '--base',
dest='base', default=3.6,
help="base value")
parser.add_option('-d', '--data',
default=0, dest='data',
help="Dataset to use on best values scan: 0 - max, 1 - avg, 2 - sqr")
(options, args) = parser.parse_args()
load_data(options.filename)
process_data(1000, float(options.base), float(options.mult), options.best, int(options.data))
| {
"pile_set_name": "Github"
} |
package translators
import (
"fmt"
"github.com/gobuffalo/pop/fizz"
"github.com/jmoiron/sqlx"
)
type cockroachIndexListInfo struct {
Name string `db:"name"`
NonUnique bool `db:"non_unique"`
}
type cockroachIndexInfo struct {
Name string `db:"name"`
Direction string `db:"direction"`
}
type cockroachTableInfo struct {
Name string `db:"column_name"`
Type string `db:"data_type"`
NotNull bool `db:"not_null"`
Default interface{} `db:"column_default"`
PK bool `db:"pk"`
}
func (t cockroachTableInfo) ToColumn() fizz.Column {
c := fizz.Column{
Name: t.Name,
ColType: t.Type,
Primary: t.PK,
Options: fizz.Options{},
}
if !t.NotNull {
c.Options["null"] = true
}
if t.Default != nil {
c.Options["default_raw"] = fmt.Sprint(t.Default) //strings.TrimSuffix(strings.TrimPrefix(fmt.Sprintf("%s", t.Default), "'"), "'")
}
return c
}
type cockroachSchema struct {
Schema
}
func (p *cockroachSchema) Build() error {
var err error
p.db, err = sqlx.Open("postgres", p.URL)
if err != nil {
return err
}
defer p.db.Close()
res, err := p.db.Queryx("SELECT table_name as name FROM information_schema.tables;")
if err != nil {
return err
}
for res.Next() {
table := &fizz.Table{
Columns: []fizz.Column{},
Indexes: []fizz.Index{},
}
err = res.StructScan(table)
if err != nil {
return err
}
if table.Name != "cockroach_sequence" {
err = p.buildTableData(table)
if err != nil {
return err
}
}
}
return nil
}
func (p *cockroachSchema) buildTableData(table *fizz.Table) error {
prag := fmt.Sprintf("SELECT c.column_name, c.data_type, (c.is_nullable = 'NO') as \"not_null\", c.column_default, (tc.table_schema IS NOT NULL)::bool AS \"pk\" FROM information_schema.columns AS c LEFT JOIN information_schema.key_column_usage as kcu ON ((c.table_schema = kcu.table_schema) AND (c.table_name = kcu.table_name) AND (c.column_name = kcu.column_name)) LEFT JOIN information_schema.table_constraints AS tc ON ((tc.table_schema = kcu.table_schema) AND (tc.table_name = kcu.table_name) AND (tc.constraint_name = kcu.constraint_name)) AND (tc.constraint_name = 'primary') WHERE c.table_name = '%s';", table.Name)
res, err := p.db.Queryx(prag)
if err != nil {
return nil
}
for res.Next() {
ti := cockroachTableInfo{}
err = res.StructScan(&ti)
if err != nil {
return err
}
table.Columns = append(table.Columns, ti.ToColumn())
}
err = p.buildTableIndexes(table)
if err != nil {
return err
}
p.schema[table.Name] = table
return nil
}
func (p *cockroachSchema) buildTableIndexes(t *fizz.Table) error {
prag := fmt.Sprintf("SELECT distinct index_name as name, non_unique FROM information_schema.statistics where table_name = '%s';", t.Name)
res, err := p.db.Queryx(prag)
if err != nil {
return err
}
for res.Next() {
li := cockroachIndexListInfo{}
err = res.StructScan(&li)
if err != nil {
return err
}
i := fizz.Index{
Name: li.Name,
Unique: !li.NonUnique,
Columns: []string{},
}
prag = fmt.Sprintf("SELECT column_name as name, direction FROM information_schema.statistics where index_name = '%s';", i.Name)
iires, err := p.db.Queryx(prag)
if err != nil {
return err
}
for iires.Next() {
ii := cockroachIndexInfo{}
err = iires.StructScan(&ii)
if err != nil {
return err
}
i.Columns = append(i.Columns, ii.Name)
}
t.Indexes = append(t.Indexes, i)
}
return nil
}
| {
"pile_set_name": "Github"
} |
#ifdef GL_ES
precision mediump float;
precision mediump int;
#endif
#define PROCESSING_TEXTURE_SHADER
uniform sampler2D texture;
uniform vec2 texOffset;
varying vec4 vertColor;
varying vec4 vertTexCoord;
float rand(vec2 n) {
return fract(sin(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);
}
vec3 csb(vec3 color, float brt, float sat, float con) {
const float AvgLumR = 0.5;
const float AvgLumG = 0.5;
const float AvgLumB = 0.5;
const vec3 LumCoeff = vec3(0.2125, 0.7154, 0.0721);
vec3 AvgLumin = vec3(AvgLumR, AvgLumG, AvgLumB);
vec3 brtColor = color * brt;
vec3 intensity = vec3(dot(brtColor, LumCoeff));
vec3 satColor = mix(intensity, brtColor, sat);
vec3 conColor = mix(AvgLumin, satColor, con);
return conColor;
}
vec3 blur(){
vec2 tc0 = vertTexCoord.st + vec2(-texOffset.s, -texOffset.t);
vec2 tc1 = vertTexCoord.st + vec2( 0.0, -texOffset.t);
vec2 tc2 = vertTexCoord.st + vec2(+texOffset.s, -texOffset.t);
vec2 tc3 = vertTexCoord.st + vec2(-texOffset.s, 0.0);
vec2 tc4 = vertTexCoord.st + vec2( 0.0, 0.0);
vec2 tc5 = vertTexCoord.st + vec2(+texOffset.s, 0.0);
vec2 tc6 = vertTexCoord.st + vec2(-texOffset.s, +texOffset.t);
vec2 tc7 = vertTexCoord.st + vec2( 0.0, +texOffset.t);
vec2 tc8 = vertTexCoord.st + vec2(+texOffset.s, +texOffset.t);
vec3 col0 = texture2D(texture, tc0).rgb;
vec3 col1 = texture2D(texture, tc1).rgb;
vec3 col2 = texture2D(texture, tc2).rgb;
vec3 col3 = texture2D(texture, tc3).rgb;
vec3 col4 = texture2D(texture, tc4).rgb;
vec3 col5 = texture2D(texture, tc5).rgb;
vec3 col6 = texture2D(texture, tc6).rgb;
vec3 col7 = texture2D(texture, tc7).rgb;
vec3 col8 = texture2D(texture, tc8).rgb;
return (1.0 * col0 + 2.0 * col1 + 1.0 * col2 +
2.0 * col3 + 4.0 * col4 + 2.0 * col5 +
1.0 * col6 + 2.0 * col7 + 1.0 * col8) / 16.0;
}
void main(void) {
vec2 st = vertTexCoord.st;
vec3 col = texture2D(texture, st).rgb;
float luma = col.r*0.2126+col.g*0.7152+col.b*0.0722;
vec3 sum = mix(col, blur(), .8);
float dis = 1.0-pow(clamp(distance(st, vec2(0.5)), 0.0, 1.0), 2.4)*0.5;
sum = mix(sum, vec3(luma+rand(st*200)*0.4-0.2), 0.12*(1-luma));
sum = csb(sum, 1.1+luma*0.05, 1.2+(1.0-dis)*2.6, 1.0)*dis;
sum.r = pow(sum.r, 1.0);
sum.g = pow(sum.g, 0.95);
sum.b = pow(sum.b, 1.0);
gl_FragColor = vec4(sum.rgb, 1.0) * vertColor;
}
| {
"pile_set_name": "Github"
} |
# Making Changes to a VoltDB cluster
Here is information and links to help you plan for changes on a live system.
## Changing the Schema
Most schema changes can be made online using CREATE or ALTER commands via SQLCMD. *Using VoltDB* has an overview of this, [Modifying the Schema](https://docs.voltdb.com/UsingVoltDB/SchemaModify.php).
There are a few types of schema changes that require taking the database offline following the process [Performing Update Using Save and Restore](https://docs.voltdb.com/AdminGuide/Maintainschema.php#MaintainSchemaSaveRestore) from *Administrator's Guide*. This is required only for the following types of schema changes:
- Changing the partitioning of a table that is not empty
- Adding a unique index to a table that is not empty
### Changing Stored Procedures
You can load, replace or delete stored procedure Java code using the "load/remove classes" directives in sqlcmd. For more information, see the the "Class management directives" section in the [sqlcmd reference page](https://docs.voltdb.com/UsingVoltDB/clisqlcmd.php) in *Using VoltDB*.
## Changing the Deployment Configuration
You can change the configuration of the following settings by editing the deployment.xml file and uploading it using the following command:
voltadmin update deployment.xml
If you do not have a copy of the latest deployment.xml file that is used by your database, you can retrieve it using the following command:
voltdb get deployment
Allowable changes include the following (see the ['update' section of the voltadmin reference page](https://docs.voltdb.com/UsingVoltDB/clivoltadmin.php) in *Using VoltDB*):
- Security settings, including user accounts
- Import and export settings (including add or remove configurations, or toggle enabled=true/false)
- Database replication settings (except the DR cluster ID)
- Automated snapshots
- System settings:
- Heartbeat timeout
- Query Timeout
- Resource Limit — Disk Limit
- Resource Limit — Memory Limit
Otherwise, you need to apply the change using a maintenance window process which involves taking a snapshot and then using the `voltdb init` command to initialize a new database instance initialized with the modified deployment.xml file, after which you can restart and restore the snapshot. See [Reconfiguring the Cluster During a Maintenance Window](https://docs.voltdb.com/AdminGuide/MaintainUpgradeHw.php#MaintainUpgradeRestart) in *Administrator's Guide*. Specifically, you need to use this process to change:
- temp table limit
- paths
- ports
- command logging configuration
- any cluster attributes (e.g. K safety or sites per host).
- enable/disable HTTP interface
| {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2011, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 2.9.0
*/
.yui-overlay,
.yui-panel-container {
visibility: hidden;
position: absolute;
z-index: 2;
}
.yui-panel {
position:relative;
}
.yui-panel-container form {
margin: 0;
}
.mask {
z-index: 1;
display: none;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.mask.block-scrollbars {
/*
Application of "overflow:auto" prevents Mac scrollbars from bleeding
through the modality mask in Gecko. The block-scollbars class is only
added for Gecko on MacOS
*/
overflow: auto;
}
/*
PLEASE NOTE:
1) ".masked select" is used to prevent <SELECT> elements bleeding through
the modality mask in IE 6.
2) ".drag select" is used to hide <SELECT> elements when dragging a
Panel in IE 6. This is necessary to prevent some redraw problems with
the <SELECT> elements when a Panel instance is dragged.
3) ".hide-select select" is appended to an Overlay instance's root HTML
element when it is being annimated by YAHOO.widget.ContainerEffect.
This is necessary because <SELECT> elements don't inherit their parent
element's opacity in IE 6.
*/
.masked select,
.drag select,
.hide-select select {
_visibility: hidden;
}
.yui-panel-container select {
_visibility: inherit;
}
/*
There are two known issues with YAHOO.widget.Overlay (and its subclasses) that
manifest in Gecko-based browsers on Mac OS X:
1) Elements with scrollbars will poke through Overlay instances floating
above them.
2) An Overlay's scrollbars and the scrollbars of its child nodes remain
visible when the Overlay is hidden.
To fix these bugs:
1) The "overflow" property of an Overlay instance's root element and child
nodes is toggled between "hidden" and "auto" (through the application
and removal of the "hide-scrollbars" and "show-scrollbars" CSS classes)
as its "visibility" configuration property is toggled between
"false" and "true."
2) The "display" property of <SELECT> elements that are child nodes of the
Overlay instance's root element is set to "none" when it is hidden.
PLEASE NOTE:
1) The "hide-scrollbars" and "show-scrollbars" CSS classes classes are
applied only for Gecko on Mac OS X and are added/removed to/from the
Overlay's root HTML element (DIV) via the "hideMacGeckoScrollbars" and
"showMacGeckoScrollbars" methods of YAHOO.widget.Overlay.
2) There may be instances where the CSS for a web page or application
contains style rules whose specificity override the rules implemented by
the Container CSS files to fix this bug. In such cases, is necessary to
leverage the provided "hide-scrollbars" and "show-scrollbars" classes to
write custom style rules to guard against this bug.
** For more information on this issue, see:
+ https://bugzilla.mozilla.org/show_bug.cgi?id=187435
+ YUILibrary bug #1723530
*/
.hide-scrollbars,
.hide-scrollbars * {
overflow: hidden;
}
.hide-scrollbars select {
display: none;
}
.show-scrollbars {
overflow: auto;
}
.yui-panel-container.show-scrollbars,
.yui-tt.show-scrollbars {
overflow: visible;
}
.yui-panel-container.show-scrollbars .underlay,
.yui-tt.show-scrollbars .yui-tt-shadow {
overflow: auto;
}
/*
Workaround for Safari 2.x - the yui-force-redraw class is applied, and then removed when
the Panel's content changes, to force Safari 2.x to redraw the underlay.
We attempt to choose a CSS property which has no visual impact when added,
removed.
*/
.yui-panel-container.shadow .underlay.yui-force-redraw {
padding-bottom: 1px;
}
.yui-effect-fade .underlay, .yui-effect-fade .yui-tt-shadow {
display:none;
}
/*
PLEASE NOTE: The <DIV> element used for a Tooltip's shadow is appended
to its root element via JavaScript once it has been rendered. The
code that creates the shadow lives in the Tooltip's public "onRender"
event handler that is a prototype method of YAHOO.widget.Tooltip.
Implementers wishing to remove a Tooltip's shadow or add any other markup
required for a given skin for Tooltip should override the "onRender" method.
*/
.yui-tt-shadow {
position: absolute;
}
.yui-override-padding {
padding:0 !important;
}
.yui-panel-container .container-close {
overflow:hidden;
text-indent:-10000em;
text-decoration:none;
}
.yui-overlay.yui-force-redraw, .yui-panel-container.yui-force-redraw {
margin-bottom:1px;
} | {
"pile_set_name": "Github"
} |
#!@BASH_PATH@
#
# cts-regression
#
# Convenience wrapper for running any of the Pacemaker regression tests
#
# Copyright 2012-2018 the Pacemaker project contributors
#
# The version control history for this file may have further details.
#
# This source code is licensed under the GNU General Public License version 2
# or later (GPLv2+) WITHOUT ANY WARRANTY.
#
USAGE_TEXT="Usage: cts-regression [<options>] [<test> ...]
Options:
--help Display this text, then exit
-V, --verbose Increase test verbosity
-v, --valgrind Run test commands under valgrind
Tests (default tests are 'scheduler cli'):
scheduler Action scheduler
cli Command-line tools
exec Local resource agent executor
pacemaker_remote Resource agent executor in remote mode
fencing Fencer
all Synonym for 'scheduler cli exec fencing'"
# If readlink supports -e (i.e. GNU), use it
readlink -e / >/dev/null 2>/dev/null
if [ $? -eq 0 ]; then
test_home="$(dirname "$(readlink -e "$0")")"
else
test_home="$(dirname "$0")"
fi
valgrind=""
verbose=""
tests=""
# These constants must track crm_exit_t values
CRM_EX_OK=0
CRM_EX_ERROR=1
CRM_EX_NOT_INSTALLED=5
CRM_EX_USAGE=64
function info() {
printf "$*\n"
}
function error() {
printf " * ERROR: $*\n"
}
function run_as_root() {
CMD="$1"
shift
ARGS="$*" # assumes arguments don't need quoting
# Test might not be executable if run from source directory
chmod a+x $CMD
CMD="$CMD $ARGS $verbose"
if [ $EUID -eq 0 ]; then
$CMD
elif [ -z $TRAVIS ]; then
# sudo doesn't work in buildbot, su doesn't work in travis
echo "Enter the root password..."
su root -c "$CMD"
else
echo "Enter the root password if prompted..."
sudo -- $CMD
fi
}
add_test() {
local TEST="$1"
case "$TEST" in
scheduler|exec|pacemaker_remote|fencing|cli)
if [[ ! $tests =~ $TEST ]]; then
tests="$tests $TEST"
fi
;;
*)
error "unknown test: $TEST"
echo
echo "$USAGE_TEXT"
exit $CRM_EX_USAGE
;;
esac
}
run_test() {
local t="$1"
info "Executing the $t regression tests"
info "============================================================"
case $t in
scheduler)
if [ -x $test_home/cts-scheduler ]; then
$test_home/cts-scheduler $verbose $valgrind
rc=$?
else
error "scheduler regression test not found"
rc=$CRM_EX_NOT_INSTALLED
fi
;;
exec)
if [ -x $test_home/cts-exec ]; then
run_as_root $test_home/cts-exec
rc=$?
else
error "executor regression test not found"
rc=$CRM_EX_NOT_INSTALLED
fi
;;
pacemaker_remote)
if [ -x $test_home/cts-exec ]; then
run_as_root $test_home/cts-exec -R
rc=$?
else
error "pacemaker_remote regression test not found"
rc=$CRM_EX_NOT_INSTALLED
fi
;;
fencing)
if [ -x $test_home/cts-fencing ]; then
run_as_root $test_home/cts-fencing
rc=$?
else
error "fencing regression test not found"
rc=$CRM_EX_NOT_INSTALLED
fi
;;
cli)
if [ -x $test_home/cts-cli ]; then
$test_home/cts-cli $verbose $valgrind
rc=$?
else
error "cli regression test not found"
rc=$CRM_EX_NOT_INSTALLED
fi
;;
esac
info "============================================================"
info ""
info ""
return $rc
}
run_tests() {
local TEST
local TEST_RC
local FAILED
FAILED=""
for TEST in "$@"; do
run_test $TEST
TEST_RC=$?
if [ $TEST_RC -ne 0 ]; then
info "$TEST regression tests failed ($TEST_RC)"
FAILED="$FAILED $TEST"
fi
done
if [ -n "$FAILED" ]; then
error "failed regression tests: $FAILED"
return $CRM_EX_ERROR
fi
return $CRM_EX_OK
}
while [ $# -gt 0 ] ; do
case "$1" in
--help)
echo "$USAGE_TEXT"
exit $CRM_EX_OK
;;
-V|--verbose)
verbose="-V"
shift
;;
-v|--valgrind)
valgrind="-v"
shift
;;
scheduler|exec|pacemaker_remote|fencing|cli)
add_test $1
shift
;;
all)
add_test scheduler
add_test cli
add_test exec
add_test fencing
shift
;;
*)
error "unknown option: $1"
echo
echo "$USAGE_TEXT"
exit $CRM_EX_USAGE
;;
esac
done
if [ -z "$tests" ]; then
add_test scheduler
add_test cli
fi
run_tests $tests
| {
"pile_set_name": "Github"
} |
package widget
import (
"image/color"
"github.com/jmigpin/editor/v2/util/fontutil"
"github.com/jmigpin/editor/v2/util/imageutil"
)
//----------
var DefaultPalette = Palette{
"text_cursor_fg": nil, // present but nil uses the current fg
"text_fg": cint(0x0),
"text_bg": cint(0xffffff),
"text_selection_fg": nil,
"text_selection_bg": cint(0xeeee9e), // yellow
"text_colorize_string_fg": cint(0x008b00), // green
"text_colorize_string_bg": nil,
"text_colorize_comments_fg": cint(0x757575), // grey 600
"text_colorize_comments_bg": nil,
"text_highlightword_fg": nil,
"text_highlightword_bg": cint(0xc6ee9e), // green
"text_wrapline_fg": cint(0x0),
"text_wrapline_bg": cint(0xd8d8d8),
"text_parenthesis_fg": cint(0x0),
"text_parenthesis_bg": cint(0xc3c3c3),
"text_annotations_fg": cint(0x0),
"text_annotations_bg": cint(0xb0e0ef),
"text_annotations_select_fg": cint(0x0),
"text_annotations_select_bg": cint(0xefc7b0),
"scrollbar_bg": cint(0xf2f2f2),
"scrollhandle_normal": cint(0xb2b2b2),
"scrollhandle_hover": cint(0x8e8e8e),
"scrollhandle_select": cint(0x5f5f5f),
"button_hover_fg": nil,
"button_hover_bg": cint(0xdddddd),
"button_down_fg": nil,
"button_down_bg": cint(0xaaaaaa),
"button_sticky_fg": cint(0xffffff),
"button_sticky_bg": cint(0x0),
"pad": cint(0x8080ff), // helpful color to debug
"border": cint(0x00ff00), // helpful color to debug
"rect": cint(0xff8000), // helpful color to debug
}
//----------
type Theme struct {
FontFace *fontutil.FontFace
Palette Palette
PaletteNamePrefix string
}
func (t *Theme) empty() bool {
return (t.FontFace == nil &&
(t.Palette == nil || t.Palette.Empty()) &&
t.PaletteNamePrefix == "")
}
func (t *Theme) Clear() {
if t.empty() {
*t = Theme{}
}
}
//----------
// Can be set to nil to erase.
func (t *Theme) SetFontFace(ff *fontutil.FontFace) {
t.FontFace = ff
t.Clear()
}
// Can be set to nil to erase.
func (t *Theme) SetPalette(p Palette) {
t.Palette = p
t.Clear()
}
// Can be set to nil to erase.
func (t *Theme) SetPaletteColor(name string, c color.Color) {
// delete color
if c == nil {
if t.Palette != nil {
delete(t.Palette, name)
}
t.Clear()
return
}
if t.Palette == nil {
t.Palette = Palette{}
}
t.Palette[name] = c
}
// Can be set to "" to erase.
func (t *Theme) SetPaletteNamePrefix(prefix string) {
t.PaletteNamePrefix = prefix
t.Clear()
}
//----------
type Palette map[string]color.Color
func (pal Palette) Empty() bool {
return pal == nil || len(pal) == 0
}
func (pal Palette) Merge(p2 Palette) {
for k, v := range p2 {
pal[k] = v
}
}
//----------
func cint(c int) color.RGBA {
return imageutil.RgbaFromInt(c)
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1995, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#include "jni.h"
#include "jni_util.h"
#include "jvm.h"
#include "java_lang_SecurityManager.h"
#include "java_lang_ClassLoader.h"
/*
* Make sure a security manager instance is initialized.
* TRUE means OK, FALSE means not.
*/
static jboolean
check(JNIEnv *env, jobject this)
{
static jfieldID initField = 0;
jboolean initialized = JNI_FALSE;
if (initField == 0) {
jclass clazz = (*env)->FindClass(env, "java/lang/SecurityManager");
if (clazz == 0) {
(*env)->ExceptionClear(env);
return JNI_FALSE;
}
initField = (*env)->GetFieldID(env, clazz, "initialized", "Z");
if (initField == 0) {
(*env)->ExceptionClear(env);
return JNI_FALSE;
}
}
initialized = (*env)->GetBooleanField(env, this, initField);
if (initialized == JNI_TRUE) {
return JNI_TRUE;
} else {
jclass securityException =
(*env)->FindClass(env, "java/lang/SecurityException");
if (securityException != 0) {
(*env)->ThrowNew(env, securityException,
"security manager not initialized.");
}
return JNI_FALSE;
}
}
JNIEXPORT jobjectArray JNICALL
Java_java_lang_SecurityManager_getClassContext(JNIEnv *env, jobject this)
{
if (!check(env, this)) {
return NULL; /* exception */
}
return JVM_GetClassContext(env);
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule warning
*/
'use strict';
var emptyFunction = require('emptyFunction');
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
function printWarning(format, ...args) {
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, () => args[argIndex++]);
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
}
var warning = __DEV__
? function(condition, format, ...args) {
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
printWarning(format, ...args);
}
}
: emptyFunction;
module.exports = warning;
| {
"pile_set_name": "Github"
} |
/* Sources directory */
#define SOURCE_FOLDER "${PROJECT_SOURCE_DIR}"
/* Binaries directory */
#define BINARY_FOLDER "${PROJECT_BINARY_DIR}"
/* NVIDIA Cuda */
#cmakedefine HAVE_CUDA
/* NVIDIA cuDNN */
#cmakedefine HAVE_CUDNN
#cmakedefine USE_CUDNN
/* NVIDIA cuDNN */
#cmakedefine CPU_ONLY
#cmakedefine DPU_ACCURACY
if(NCCL_FOUND)
#cmakedefine USE_NCCL
endif()
/* Test device */
#define CUDA_TEST_DEVICE ${CUDA_TEST_DEVICE}
/* Temporary (TODO: remove) */
#if 1
#define CMAKE_SOURCE_DIR SOURCE_FOLDER "/src/"
#define EXAMPLES_SOURCE_DIR BINARY_FOLDER "/examples/"
#define CMAKE_EXT ".gen.cmake"
#else
#define CMAKE_SOURCE_DIR "src/"
#define EXAMPLES_SOURCE_DIR "examples/"
#define CMAKE_EXT ""
#endif
/* Matlab */
#cmakedefine HAVE_MATLAB
/* IO libraries */
#cmakedefine USE_OPENCV
#cmakedefine USE_LEVELDB
#cmakedefine USE_LMDB
#cmakedefine ALLOW_LMDB_NOLOCK
| {
"pile_set_name": "Github"
} |
#define BOOST_TEST_MODULE test_meshmarker
#include <feel/feelcore/testsuite.hpp>
#include <feel/feelfilters/geotool.hpp>
#include <feel/feelvf/vf.hpp>
FEELPP_ENVIRONMENT_NO_OPTIONS
BOOST_AUTO_TEST_SUITE( test_meshmarker )
BOOST_AUTO_TEST_CASE( test_meshmarker1 )
{
using namespace Feel;
typedef Mesh<Simplex<3,1,3> > mesh_type;
double l = 0.3;
GeoTool::Node x1(-l,-l,-l);
GeoTool::Node x2( l,-l,-l);
GeoTool::Node x3( l, l,-l);
GeoTool::Node x4(-l, l,-l);
GeoTool::Node x5(-l,-l, l);
GeoTool::Node x6( l,-l, l);
GeoTool::Node x7( l, l, l);
GeoTool::Node x8(-l, l, l);
GeoTool::Hexahedron H(doption(_name="gmsh.hsize"),"UnHexa",x1,x2,x3,x4,x5,x6,x7,x8);
H.setMarker(_type="point",_name="markPoints",_markerAll=true);
H.setMarker(_type="line",_name="markLines",_markerAll=true);
H.setMarker(_type="surface",_name="GammaDirichlet",_marker2=true,_marker3=true,_marker4=true,_marker5=true,_marker6=true);
H.setMarker(_type="surface",_name="GammaNeumann",_marker1=true);
H.setMarker(_type="volume",_name="OmegaFluid",_markerAll=true);
auto mesh = H.createMesh(_mesh= new mesh_type,
_name="un_cube" );
double intSurf1 = integrate(_range=markedfaces(mesh, "GammaDirichlet" ),_expr=cst(1.) ).evaluate()(0,0);
double intSurf2 = integrate(_range=markedfaces(mesh, "GammaNeumann" ),_expr=cst(1.) ).evaluate()(0,0);
BOOST_CHECK_SMALL( intSurf1-5*(2*l*2*l),1e-12 );
BOOST_CHECK_SMALL( intSurf2-1*(2*l*2*l),1e-12 );
auto submeshFaces = createSubmesh(_mesh=mesh,_range=markedfaces(mesh,"GammaNeumann"));
double intSubmeshFaces = integrate(_range=elements(submeshFaces),_expr=cst(1.) ).evaluate()(0,0);
BOOST_CHECK_SMALL( intSubmeshFaces-1*(2*l*2*l),1e-12 );
double intMarkedLinesSubmeshFaces = integrate(_range=markedfaces(submeshFaces,"markLines"),_expr=cst(1.) ).evaluate()(0,0);
BOOST_CHECK_SMALL( intMarkedLinesSubmeshFaces-4*2*l,1e-12 );
size_type nMarkedPointsSubmeshFaces = nelements( markedpoints(submeshFaces,"markPoints"), true );
if ( Environment::numberOfProcessors() > 1 )
BOOST_CHECK( nMarkedPointsSubmeshFaces >= 4 );
else
BOOST_CHECK( nMarkedPointsSubmeshFaces == 4 );
auto submeshLines = createSubmesh(_mesh=mesh,_range=markededges(mesh,"markLines"),_update=size_type(0));
double intSubmeshLines = integrate(_range=elements(submeshLines),_expr=cst(1.) ).evaluate()(0,0);
BOOST_CHECK_SMALL( intSubmeshLines-12*2*l,1e-12 );
size_type nMarkedPointsSubmeshLines = nelements( markedpoints(submeshLines,"markPoints"), true );
if ( Environment::numberOfProcessors() > 1 )
BOOST_CHECK( nMarkedPointsSubmeshLines >= 8 );
else
BOOST_CHECK( nMarkedPointsSubmeshLines == 8 );
size_type nMarkedPoints = nelements( markedpoints(mesh,"markPoints"), true );
if ( Environment::numberOfProcessors() > 1 )
BOOST_CHECK( nMarkedPoints >= 8 );
else
BOOST_CHECK( nMarkedPoints == 8 );
mesh->updateMarker3WithRange(markedfaces(mesh,"GammaNeumann"),1);
mesh->updateMarkersFromFaces();
auto submesh = createSubmesh(_mesh=mesh,_range=marked3elements(mesh,1));
double intSubmesh = integrate(_range=markedfaces(submesh,"GammaNeumann"),_expr=cst(1.) ).evaluate()(0,0);
BOOST_CHECK_SMALL( intSubmesh-1*(2*l*2*l),1e-12 );
size_type nMarkedPointsSubmesh = nelements( markedpoints(submesh,"markPoints"), true );
if ( Environment::numberOfProcessors() > 1 )
BOOST_CHECK( nMarkedPointsSubmesh >= 4 );
else
BOOST_CHECK( nMarkedPointsSubmesh == 4 );
}
BOOST_AUTO_TEST_SUITE_END()
| {
"pile_set_name": "Github"
} |
package com.java110.common.listener.carInoutDetail;
import com.alibaba.fastjson.JSONObject;
import com.java110.common.dao.ICarInoutDetailServiceDao;
import com.java110.entity.center.Business;
import com.java110.core.event.service.AbstractBusinessServiceDataFlowListener;
import com.java110.utils.constant.ResponseConstant;
import com.java110.utils.constant.StatusConstant;
import com.java110.utils.exception.ListenerExecuteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 进出场详情 服务侦听 父类
* Created by wuxw on 2018/7/4.
*/
public abstract class AbstractCarInoutDetailBusinessServiceDataFlowListener extends AbstractBusinessServiceDataFlowListener {
private static Logger logger = LoggerFactory.getLogger(AbstractCarInoutDetailBusinessServiceDataFlowListener.class);
/**
* 获取 DAO工具类
*
* @return
*/
public abstract ICarInoutDetailServiceDao getCarInoutDetailServiceDaoImpl();
/**
* 刷新 businessCarInoutDetailInfo 数据
* 主要将 数据库 中字段和 接口传递字段建立关系
*
* @param businessCarInoutDetailInfo
*/
protected void flushBusinessCarInoutDetailInfo(Map businessCarInoutDetailInfo, String statusCd) {
businessCarInoutDetailInfo.put("newBId", businessCarInoutDetailInfo.get("b_id"));
businessCarInoutDetailInfo.put("inoutId", businessCarInoutDetailInfo.get("inout_id"));
businessCarInoutDetailInfo.put("machineId", businessCarInoutDetailInfo.get("machine_id"));
businessCarInoutDetailInfo.put("machineCode", businessCarInoutDetailInfo.get("machine_code"));
businessCarInoutDetailInfo.put("operate", businessCarInoutDetailInfo.get("operate"));
businessCarInoutDetailInfo.put("carInout", businessCarInoutDetailInfo.get("car_inout"));
businessCarInoutDetailInfo.put("detailId", businessCarInoutDetailInfo.get("detail_id"));
businessCarInoutDetailInfo.put("carNum", businessCarInoutDetailInfo.get("car_num"));
businessCarInoutDetailInfo.put("communityId", businessCarInoutDetailInfo.get("community_id"));
businessCarInoutDetailInfo.remove("bId");
businessCarInoutDetailInfo.put("statusCd", statusCd);
}
/**
* 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
*
* @param businessCarInoutDetail 进出场详情信息
*/
protected void autoSaveDelBusinessCarInoutDetail(Business business, JSONObject businessCarInoutDetail) {
//自动插入DEL
Map info = new HashMap();
info.put("detailId", businessCarInoutDetail.getString("detailId"));
info.put("statusCd", StatusConstant.STATUS_CD_VALID);
List<Map> currentCarInoutDetailInfos = getCarInoutDetailServiceDaoImpl().getCarInoutDetailInfo(info);
if (currentCarInoutDetailInfos == null || currentCarInoutDetailInfos.size() != 1) {
throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
}
Map currentCarInoutDetailInfo = currentCarInoutDetailInfos.get(0);
currentCarInoutDetailInfo.put("bId", business.getbId());
currentCarInoutDetailInfo.put("inoutId", currentCarInoutDetailInfo.get("inout_id"));
currentCarInoutDetailInfo.put("machineId", currentCarInoutDetailInfo.get("machine_id"));
currentCarInoutDetailInfo.put("machineCode", currentCarInoutDetailInfo.get("machine_code"));
currentCarInoutDetailInfo.put("operate", currentCarInoutDetailInfo.get("operate"));
currentCarInoutDetailInfo.put("carInout", currentCarInoutDetailInfo.get("car_inout"));
currentCarInoutDetailInfo.put("detailId", currentCarInoutDetailInfo.get("detail_id"));
currentCarInoutDetailInfo.put("carNum", currentCarInoutDetailInfo.get("car_num"));
currentCarInoutDetailInfo.put("communityId", currentCarInoutDetailInfo.get("community_id"));
currentCarInoutDetailInfo.put("operate", StatusConstant.OPERATE_DEL);
getCarInoutDetailServiceDaoImpl().saveBusinessCarInoutDetailInfo(currentCarInoutDetailInfo);
for (Object key : currentCarInoutDetailInfo.keySet()) {
if (businessCarInoutDetail.get(key) == null) {
businessCarInoutDetail.put(key.toString(), currentCarInoutDetailInfo.get(key));
}
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.xcontent;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.ParseField;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
public class NamedXContentRegistry {
/**
* The empty {@link NamedXContentRegistry} for use when you are sure that you aren't going to call
* {@link XContentParser#namedObject(Class, String, Object)}. Be *very* careful with this singleton because a parser using it will fail
* every call to {@linkplain XContentParser#namedObject(Class, String, Object)}. Every non-test usage really should be checked
* thoroughly and marked with a comment about how it was checked. That way anyone that sees code that uses it knows that it is
* potentially dangerous.
*/
public static final NamedXContentRegistry EMPTY = new NamedXContentRegistry(emptyList());
/**
* An entry in the {@linkplain NamedXContentRegistry} containing the name of the object and the parser that can parse it.
*/
public static class Entry {
/** The class that this entry can read. */
public final Class<?> categoryClass;
/** A name for the entry which is unique within the {@link #categoryClass}. */
public final ParseField name;
/** A parser capability of parser the entry's class. */
private final ContextParser<Object, ?> parser;
/** Creates a new entry which can be stored by the registry. */
public <T> Entry(Class<T> categoryClass, ParseField name, CheckedFunction<XContentParser, ? extends T, IOException> parser) {
this.categoryClass = Objects.requireNonNull(categoryClass);
this.name = Objects.requireNonNull(name);
this.parser = Objects.requireNonNull((p, c) -> parser.apply(p));
}
/**
* Creates a new entry which can be stored by the registry.
* Prefer {@link Entry#Entry(Class, ParseField, CheckedFunction)} unless you need a context to carry around while parsing.
*/
public <T> Entry(Class<T> categoryClass, ParseField name, ContextParser<Object, ? extends T> parser) {
this.categoryClass = Objects.requireNonNull(categoryClass);
this.name = Objects.requireNonNull(name);
this.parser = Objects.requireNonNull(parser);
}
}
private final Map<Class<?>, Map<String, Entry>> registry;
public NamedXContentRegistry(List<Entry> entries) {
if (entries.isEmpty()) {
registry = emptyMap();
return;
}
entries = new ArrayList<>(entries);
entries.sort((e1, e2) -> e1.categoryClass.getName().compareTo(e2.categoryClass.getName()));
Map<Class<?>, Map<String, Entry>> registry = new HashMap<>();
Map<String, Entry> parsers = null;
Class<?> currentCategory = null;
for (Entry entry : entries) {
if (currentCategory != entry.categoryClass) {
if (currentCategory != null) {
// we've seen the last of this category, put it into the big map
registry.put(currentCategory, unmodifiableMap(parsers));
}
parsers = new HashMap<>();
currentCategory = entry.categoryClass;
}
for (String name : entry.name.getAllNamesIncludedDeprecated()) {
Object old = parsers.put(name, entry);
if (old != null) {
throw new IllegalArgumentException("NamedXContent [" + currentCategory.getName() + "][" + entry.name + "]" +
" is already registered for [" + old.getClass().getName() + "]," +
" cannot register [" + entry.parser.getClass().getName() + "]");
}
}
}
// handle the last category
registry.put(currentCategory, unmodifiableMap(parsers));
this.registry = unmodifiableMap(registry);
}
/**
* Parse a named object, throwing an exception if the parser isn't found. Throws an {@link NamedObjectNotFoundException} if the
* {@code categoryClass} isn't registered because this is almost always a bug. Throws an {@link NamedObjectNotFoundException} if the
* {@code categoryClass} is registered but the {@code name} isn't.
*
* @throws NamedObjectNotFoundException if the categoryClass or name is not registered
*/
public <T, C> T parseNamedObject(Class<T> categoryClass, String name, XContentParser parser, C context) throws IOException {
Map<String, Entry> parsers = registry.get(categoryClass);
if (parsers == null) {
if (registry.isEmpty()) {
// The "empty" registry will never work so we throw a better exception as a hint.
throw new XContentParseException("named objects are not supported for this parser");
}
throw new XContentParseException("unknown named object category [" + categoryClass.getName() + "]");
}
Entry entry = parsers.get(name);
if (entry == null) {
throw new NamedObjectNotFoundException(parser.getTokenLocation(), "unknown field [" + name + "]", parsers.keySet());
}
if (false == entry.name.match(name, parser.getDeprecationHandler())) {
/* Note that this shouldn't happen because we already looked up the entry using the names but we need to call `match` anyway
* because it is responsible for logging deprecation warnings. */
throw new XContentParseException(parser.getTokenLocation(),
"unable to parse " + categoryClass.getSimpleName() + " with name [" + name + "]: parser didn't match");
}
return categoryClass.cast(entry.parser.parse(parser, context));
}
}
| {
"pile_set_name": "Github"
} |
// Tencent is pleased to support the open source community by making Mars available.
// Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
// Licensed under the MIT License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://opensource.org/licenses/MIT
// 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.
#ifndef __ANDROID_XLOG__
#define __ANDROID_XLOG__
#include "xlogger/xloggerbase.h"
/*
* Android log priority values, in ascending priority order.
*/
typedef enum android_LogPriority {
ANDROID_LOG_UNKNOWN = 0,
ANDROID_LOG_DEFAULT, /* only for SetMinPriority() */
ANDROID_LOG_VERBOSE,
ANDROID_LOG_DEBUG,
ANDROID_LOG_INFO,
ANDROID_LOG_WARN,
ANDROID_LOG_ERROR,
ANDROID_LOG_FATAL,
ANDROID_LOG_SILENT, /* only for SetMinPriority(); must be last */
} android_LogPriority;
static void __ComLogV(int level, const char *tag, const char* file, const char* func, int line, const char* fmt, va_list args) {
struct XLoggerInfo_t info;
info.level = (TLogLevel)level;
info.tag = tag;
info.filename = file;
info.func_name = func;
info.line = line;
gettimeofday(&info.timeval, NULL);
info.pid = -1;
info.tid = -1;
info.maintid = -1;
xlogger_VPrint(&info, fmt, args);
//important: do not use like this:xlogger2((TLogLevel)level, tag, file, func, line, fmt, args);
//xlogger2((TLogLevel)level, tag, file, func, line).VPrintf(fmt, args);
}
static void __ComLog(int level, const char *tag, const char* file, const char* func, int line, const char* fmt, ...) {
va_list args;
va_start(args,fmt);
__ComLogV(level, tag, file, func, line,fmt, args);
va_end(args);
}
#define __LOG__(LEVEL, LOG_TAG, FMT, ...) if ((!xlogger_IsEnabledFor(LEVEL))); else __ComLog(LEVEL, LOG_TAG , __FILE__, __FUNCTION__, __LINE__, FMT,## __VA_ARGS__)
#define __LOGV__(LEVEL, LOG_TAG, FMT, VA_LIST) if ((!xlogger_IsEnabledFor(LEVEL))); else __ComLogV(LEVEL, LOG_TAG , __FILE__, __FUNCTION__, __LINE__, FMT, VA_LIST)
#define LOGV(LOG_TAG, FMT, ...) __LOG__(kLevelVerbose, LOG_TAG, FMT, ##__VA_ARGS__)
#define LOGD(LOG_TAG, FMT, ...) __LOG__(kLevelDebug, LOG_TAG, FMT, ##__VA_ARGS__)
#define LOGI(LOG_TAG, FMT, ...) __LOG__(kLevelInfo, LOG_TAG, FMT, ##__VA_ARGS__)
#define LOGW(LOG_TAG, FMT, ...) __LOG__(kLevelWarn, LOG_TAG, FMT, ##__VA_ARGS__)
#define LOGE(LOG_TAG, FMT, ...) __LOG__(kLevelError, LOG_TAG, FMT, ##__VA_ARGS__)
#define __android_log_print(PRIO, TAG, FMT, ...) __LOG__((TLogLevel)(PRIO-2), TAG , FMT, ##__VA_ARGS__)
#define __android_log_write(PRIO, TAG, TEXT) __LOG__((TLogLevel)(PRIO-2), TAG, TEXT)
#define __android_log_vprint(PRIO, TAG, FMT, VA_LIST) __LOG__((TLogLevel)(PRIO-2), TAG, FMT, VA_LIST)
#define __android_log_assert(COND, TAG, FMT, ...) if (((COND) || !xlogger_IsEnabledFor(kLevelFatal)));else {\
XLoggerInfo info= {kLevelFatal, TAG, __FILE__, __FUNCTION__, __LINE__,\
{0, 0}, -1, -1, -1};\
gettimeofday(&info.timeval, NULL);\
xlogger_AssertP(&info, #COND, FMT, ##__VA_ARGS__);}
#endif
| {
"pile_set_name": "Github"
} |
//Prevayler(TM) - The Free-Software Prevalence Layer.
//Copyright (C) 2001-2004 Klaus Wuestefeld
//This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//Contributions: Carlos Villela, Jacob Kjome
package org.prevayler.foundation.monitor;
import java.io.File;
/**
* A Monitor for interesting events in the system.
*/
public interface Monitor {
/**
* Something interesting happened.
*/
void notify(Class<?> clazz, String message);
/**
* An interesting exception was thrown.
*/
void notify(Class<?> clazz, String message, Exception ex);
/**
* Something interesting happened regarding access to a file.
*/
void notify(Class<?> clazz, String message, File file);
/**
* An exception was thrown while trying to access a file.
*/
void notify(Class<?> clazz, String message, File file, Exception ex);
}
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
import os
import sys
import time
# -----------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root + '/python')
# -----------------------------------------------------------------------------
import ccxt # noqa: E402
# -----------------------------------------------------------------------------
# common constants
msec = 1000
minute = 60 * msec
hold = 30
# -----------------------------------------------------------------------------
exchange = ccxt.bitfinex({
'rateLimit': 10000,
'enableRateLimit': True,
# 'verbose': True,
})
# -----------------------------------------------------------------------------
from_datetime = '2017-01-01 00:00:00'
from_timestamp = exchange.parse8601(from_datetime)
# -----------------------------------------------------------------------------
now = exchange.milliseconds()
# -----------------------------------------------------------------------------
data = []
while from_timestamp < now:
try:
print(exchange.milliseconds(), 'Fetching candles starting from', exchange.iso8601(from_timestamp))
ohlcvs = exchange.fetch_ohlcv('BTC/USD', '5m', from_timestamp)
print(exchange.milliseconds(), 'Fetched', len(ohlcvs), 'candles')
if len(ohlcvs) > 0:
first = ohlcvs[0][0]
last = ohlcvs[-1][0]
print('First candle epoch', first, exchange.iso8601(first))
print('Last candle epoch', last, exchange.iso8601(last))
# from_timestamp += len(ohlcvs) * minute * 5 # very bad
from_timestamp = ohlcvs[-1][0] + minute * 5 # good
data += ohlcvs
except (ccxt.ExchangeError, ccxt.AuthenticationError, ccxt.ExchangeNotAvailable, ccxt.RequestTimeout) as error:
print('Got an error', type(error).__name__, error.args, ', retrying in', hold, 'seconds...')
time.sleep(hold)
| {
"pile_set_name": "Github"
} |
// This file is automatically generated. Do not edit.
// ['../../libs/compatibility/generate_cpp_c_headers.py']
// Wed Jul 23 12:11:19 2003 ('GMTST', 'GMTST')
#ifndef __CSTDIO_HEADER
#define __CSTDIO_HEADER
#include <stdio.h>
namespace std {
using ::FILE;
using ::fpos_t;
using ::size_t;
using ::clearerr;
using ::fgets;
using ::fscanf;
using ::gets;
using ::rename;
using ::tmpfile;
using ::fclose;
using ::fopen;
using ::fseek;
using ::perror;
using ::rewind;
using ::tmpnam;
using ::feof;
using ::fprintf;
using ::fsetpos;
using ::printf;
using ::scanf;
using ::ungetc;
using ::ferror;
using ::fputc;
using ::ftell;
using ::putc;
using ::setbuf;
using ::vfprintf;
using ::fflush;
using ::fputs;
using ::fwrite;
using ::putchar;
using ::setvbuf;
using ::vprintf;
using ::fgetc;
using ::fread;
using ::getc;
using ::puts;
using ::sprintf;
using ::vsprintf;
using ::fgetpos;
using ::freopen;
using ::getchar;
using ::remove;
using ::sscanf;
}
#endif // CSTDIO_HEADER
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace SwqlStudio.Metadata
{
internal class SwisMetaDataProvider : IMetadataProvider
{
private readonly ConnectionInfo info;
private Dictionary<string, Entity> entities = new Dictionary<string, Entity>();
public SwisMetaDataProvider(ConnectionInfo info)
{
this.info = info;
Name = info.Title;
_capabilities = new Lazy<Capability>(GetCapabilities);
}
private readonly Lazy<Capability> _capabilities;
private Capability Capabilities => _capabilities.Value;
private readonly IEnumerable<string> _metadataDefaultAttributes = new[]
{
"Entity.FullName", "Entity.Namespace", "Entity.BaseType",
"(Entity.Type ISA 'System.Indication') AS IsIndication",
"Entity.Properties.Name", "Entity.Properties.Type", "Entity.Properties.IsNavigable",
"Entity.Properties.IsInherited", "Entity.Properties.IsKey", "Entity.Verbs.EntityName", "Entity.Verbs.Name",
"Entity.IsAbstract"
};
private IEnumerable<string> AccessControlMetadataAttributes => Capabilities.HasFlag(Capability.AccessControl)
? new[] { "Entity.CanCreate", "Entity.CanDelete", "Entity.CanInvoke", "Entity.CanRead", "Entity.CanUpdate" }
: new string[0];
private IEnumerable<string> DocumentationMetadataAttributes => Capabilities.HasFlag(Capability.Documentation)
? new[] { "Entity.Summary", "Entity.Properties.Summary", "Entity.Verbs.Summary" }
: new string[0];
private IEnumerable<string> ObsoleteMetadataAttributes => Capabilities.HasFlag(Capability.Obsolete)
? new[] { "Entity.IsObsolete", "Entity.ObsolescenceReason", "Entity.Properties.IsObsolete", "Entity.Properties.ObsolescenceReason",
"Entity.Verbs.IsObsolete", "Entity.Verbs.ObsolescenceReason" }
: new string[0];
private IEnumerable<string> MetadataAttributes => _metadataDefaultAttributes
.Concat(AccessControlMetadataAttributes).Concat(DocumentationMetadataAttributes).Concat(ObsoleteMetadataAttributes);
public void Refresh()
{
string query = $"SELECT {string.Join(",", MetadataAttributes)} FROM Metadata.Entity";
entities = info.Query<Entity>(query).ToDictionary(entity => entity.FullName);
foreach (var entity in entities.Values)
{
if (entity.BaseType != null && entities.TryGetValue(entity.BaseType, out var baseEntity))
entity.BaseEntity = baseEntity;
}
EntitiesRefreshed?.Invoke(this, new EventArgs());
}
[Flags]
public enum Capability
{
None = 0,
AccessControl = 1,
Documentation = 2,
Obsolete = 4,
}
public Capability GetCapabilities()
{
const string query = @"SELECT Name
FROM Metadata.Property
WHERE EntityName='Metadata.Entity' AND Name IN ('CanCreate', 'Summary', 'IsObsolete')";
Capability cap = Capability.None;
DataTable dt = info.Query(query);
foreach (DataRow row in dt.Rows)
{
if ((string)row["Name"] == "CanCreate")
cap |= Capability.AccessControl;
else if ((string)row["Name"] == "Summary")
cap |= Capability.Documentation;
else if ((string)row["Name"] == "IsObsolete")
cap |= Capability.Obsolete;
}
return cap;
}
public IEnumerable<VerbArgument> GetVerbArguments(Verb verb)
{
return info.Query<VerbArgument>(
string.Format(
"SELECT VerbArgument.Name, VerbArgument.Type, VerbArgument.Position " +
(XmlTemplateSupported ? ", VerbArgument.XmlTemplate " : "") +
(_capabilities.Value.HasFlag(Capability.Documentation) ? ", VerbArgument.Summary " : "") +
"FROM Metadata.VerbArgument WHERE VerbArgument.EntityName='{0}' AND VerbArgument.VerbName='{1}' " +
"ORDER BY VerbArgument.Position",
verb.EntityName, verb.Name));
}
protected bool XmlTemplateSupported
{
get { return entities["Metadata.VerbArgument"].Properties.Any(p => p.Name == "XmlTemplate"); }
}
public ConnectionInfo ConnectionInfo
{
get { return info; }
}
public string Name { get; private set; }
public IEnumerable<Entity> Tables
{
get
{
if (entities == null)
Refresh();
return entities.Values.OrderBy(t => t.FullName);
}
}
/// <inheritdoc />
public event EventHandler EntitiesRefreshed;
}
}
| {
"pile_set_name": "Github"
} |
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: {
rewrites: [
{ from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
],
},
hot: true,
contentBase: false, // since we use CopyWebpackPlugin.
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
| {
"pile_set_name": "Github"
} |
// gcc -g -O2 -o parameter_ref parameter_ref.c
volatile int vv;
/* Don't inline, but do allow clone to create specialized versions. */
static __attribute__((noinline)) int
foo (int x, int y, int z)
{
int a = x * 2;
int b = y * 2;
int c = z * 2;
vv++;
return x + z;
}
int
main (int x, char **argv)
{
return foo (x, 2, 3) + foo (x, 4, 3) + foo (x + 6, x, 3) + x;
}
| {
"pile_set_name": "Github"
} |
cmake_minimum_required(VERSION 3.8.2)
# Automatically create moc files
set(CMAKE_AUTOMOC ON)
option(QT_STATICPLUGIN "Build a static plugin" OFF)
find_package(Qt5Qml REQUIRED)
find_package(Qt5Quick REQUIRED)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 11)
###############################################################################
# configure
include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR})
if(QT_STATICPLUGIN)
set(CMAKE_AUTOMOC_MOC_OPTIONS -Muri=NosonThumbnailer)
add_definitions(-DQT_PLUGIN)
add_definitions(-DQT_STATICPLUGIN)
endif()
if (MSVC)
set (CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /W3 /Od /RTC1")
set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /O2 /EHsc /nologo")
set (CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /O2 /EHsc /nologo")
set (CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /O2 /EHsc /nologo")
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /W3 /Od /RTC1 /EHsc /nologo")
endif ()
set(
NosonThumbnailer_SOURCES
plugin.cpp
albumartgenerator.cpp
artistartgenerator.cpp
thumbnailerimageresponse.cpp
thumbnailer/thumbnailer.cpp
thumbnailer/thumbnailerjob.cpp
thumbnailer/ratelimiter.cpp
thumbnailer/netrequest.cpp
thumbnailer/netmanager.cpp
thumbnailer/diskcachemanager.cpp
thumbnailer/artistinfo.cpp
thumbnailer/albuminfo.cpp
thumbnailer/abstractapi.cpp
thumbnailer/tinyxml2.cpp
thumbnailer/xmldict.cpp
thumbnailer/jsonparser.cpp
thumbnailer/lastfm/lastfm.cpp
thumbnailer/lastfm/lfm-artistinfo.cpp
thumbnailer/lastfm/lfm-albuminfo.cpp
thumbnailer/deezer/deezer.cpp
thumbnailer/deezer/deezer-artistinfo.cpp
thumbnailer/deezer/deezer-albuminfo.cpp
)
set(
NosonThumbnailer_HEADERS
plugin.h
albumartgenerator.h
artistartgenerator.h
thumbnailerimageresponse.h
thumbnailer/thumbnailer.h
thumbnailer/thumbnailerjob.h
thumbnailer/ratelimiter.h
thumbnailer/netrequest.h
thumbnailer/netmanager.h
thumbnailer/diskcachemanager.h
thumbnailer/artistinfo.h
thumbnailer/albuminfo.h
thumbnailer/abstractapi.h
thumbnailer/jsonparser.h
thumbnailer/lastfm/lastfm.h
thumbnailer/deezer/deezer.h
)
if(QT_STATICPLUGIN)
add_library(NosonThumbnailer STATIC ${NosonThumbnailer_SOURCES})
else()
add_library(NosonThumbnailer MODULE ${NosonThumbnailer_SOURCES})
endif()
set_target_properties(NosonThumbnailer PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${QML_IMPORT_DIRECTORY}/NosonThumbnailer)
target_link_libraries(NosonThumbnailer Qt5::Qml Qt5::Quick)
# Copy qmldir file to build dir for running in QtCreator
add_custom_target(NosonThumbnailer-qmldir ALL
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/qmldir ${QML_IMPORT_DIRECTORY}/NosonThumbnailer/qmldir
DEPENDS ${QMLFILES}
)
if(NOT QT_STATICPLUGIN)
# Install plugin file
MESSAGE(STATUS "PlugIns install path: ${PLUGINS_DIR}")
install(TARGETS NosonThumbnailer DESTINATION ${PLUGINS_DIR}/NosonThumbnailer/)
install(FILES qmldir DESTINATION ${PLUGINS_DIR}/NosonThumbnailer/)
endif()
| {
"pile_set_name": "Github"
} |
*if_pyth.txt* For Vim version 7.4. Last change: 2014 Jul 23
VIM REFERENCE MANUAL by Paul Moore
The Python Interface to Vim *python* *Python*
1. Commands |python-commands|
2. The vim module |python-vim|
3. Buffer objects |python-buffer|
4. Range objects |python-range|
5. Window objects |python-window|
6. Tab page objects |python-tabpage|
7. vim.bindeval objects |python-bindeval-objects|
8. pyeval(), py3eval() Vim functions |python-pyeval|
9. Dynamic loading |python-dynamic|
10. Python 3 |python3|
{Vi does not have any of these commands}
The Python 2.x interface is available only when Vim was compiled with the
|+python| feature.
The Python 3 interface is available only when Vim was compiled with the
|+python3| feature.
Both can be available at the same time, but read |python-2-and-3|.
==============================================================================
1. Commands *python-commands*
*:python* *:py* *E263* *E264* *E887*
:[range]py[thon] {stmt}
Execute Python statement {stmt}. A simple check if
the `:python` command is working: >
:python print "Hello"
:[range]py[thon] << {endmarker}
{script}
{endmarker}
Execute Python script {script}.
Note: This command doesn't work when the Python
feature wasn't compiled in. To avoid errors, see
|script-here|.
{endmarker} must NOT be preceded by any white space. If {endmarker} is
omitted from after the "<<", a dot '.' must be used after {script}, like
for the |:append| and |:insert| commands.
This form of the |:python| command is mainly useful for including python code
in Vim scripts.
Example: >
function! IcecreamInitialize()
python << EOF
class StrawberryIcecream:
def __call__(self):
print 'EAT ME'
EOF
endfunction
<
Note: Python is very sensitive to the indenting. Make sure the "class" line
and "EOF" do not have any indent.
*:pydo*
:[range]pydo {body} Execute Python function "def _vim_pydo(line, linenr):
{body}" for each line in the [range], with the
function arguments being set to the text of each line
in turn, without a trailing <EOL>, and the current
line number. The function should return a string or
None. If a string is returned, it becomes the text of
the line in the current turn. The default for [range]
is the whole file: "1,$".
{not in Vi}
Examples:
>
:pydo return "%s\t%d" % (line[::-1], len(line))
:pydo if line: return "%4d: %s" % (linenr, line)
<
*:pyfile* *:pyf*
:[range]pyf[ile] {file}
Execute the Python script in {file}. The whole
argument is used as a single file name. {not in Vi}
Both of these commands do essentially the same thing - they execute a piece of
Python code, with the "current range" |python-range| set to the given line
range.
In the case of :python, the code to execute is in the command-line.
In the case of :pyfile, the code to execute is the contents of the given file.
Python commands cannot be used in the |sandbox|.
To pass arguments you need to set sys.argv[] explicitly. Example: >
:python import sys
:python sys.argv = ["foo", "bar"]
:pyfile myscript.py
Here are some examples *python-examples* >
:python from vim import *
:python from string import upper
:python current.line = upper(current.line)
:python print "Hello"
:python str = current.buffer[42]
(Note that changes - like the imports - persist from one command to the next,
just like in the Python interpreter.)
==============================================================================
2. The vim module *python-vim*
Python code gets all of its access to vim (with one exception - see
|python-output| below) via the "vim" module. The vim module implements two
methods, three constants, and one error object. You need to import the vim
module before using it: >
:python import vim
Overview >
:py print "Hello" # displays a message
:py vim.command(cmd) # execute an Ex command
:py w = vim.windows[n] # gets window "n"
:py cw = vim.current.window # gets the current window
:py b = vim.buffers[n] # gets buffer "n"
:py cb = vim.current.buffer # gets the current buffer
:py w.height = lines # sets the window height
:py w.cursor = (row, col) # sets the window cursor position
:py pos = w.cursor # gets a tuple (row, col)
:py name = b.name # gets the buffer file name
:py line = b[n] # gets a line from the buffer
:py lines = b[n:m] # gets a list of lines
:py num = len(b) # gets the number of lines
:py b[n] = str # sets a line in the buffer
:py b[n:m] = [str1, str2, str3] # sets a number of lines at once
:py del b[n] # deletes a line
:py del b[n:m] # deletes a number of lines
Methods of the "vim" module
vim.command(str) *python-command*
Executes the vim (ex-mode) command str. Returns None.
Examples: >
:py vim.command("set tw=72")
:py vim.command("%s/aaa/bbb/g")
< The following definition executes Normal mode commands: >
def normal(str):
vim.command("normal "+str)
# Note the use of single quotes to delimit a string containing
# double quotes
normal('"a2dd"aP')
< *E659*
The ":python" command cannot be used recursively with Python 2.2 and
older. This only works with Python 2.3 and later: >
:py vim.command("python print 'Hello again Python'")
vim.eval(str) *python-eval*
Evaluates the expression str using the vim internal expression
evaluator (see |expression|). Returns the expression result as:
- a string if the Vim expression evaluates to a string or number
- a list if the Vim expression evaluates to a Vim list
- a dictionary if the Vim expression evaluates to a Vim dictionary
Dictionaries and lists are recursively expanded.
Examples: >
:py text_width = vim.eval("&tw")
:py str = vim.eval("12+12") # NB result is a string! Use
# string.atoi() to convert to
# a number.
:py tagList = vim.eval('taglist("eval_expr")')
< The latter will return a python list of python dicts, for instance:
[{'cmd': '/^eval_expr(arg, nextcmd)$/', 'static': 0, 'name':
'eval_expr', 'kind': 'f', 'filename': './src/eval.c'}]
vim.bindeval(str) *python-bindeval*
Like |python-eval|, but returns special objects described in
|python-bindeval-objects|. These python objects let you modify (|List|
or |Dictionary|) or call (|Funcref|) vim objects.
vim.strwidth(str) *python-strwidth*
Like |strwidth()|: returns number of display cells str occupies, tab
is counted as one cell.
vim.foreach_rtp(callable) *python-foreach_rtp*
Call the given callable for each path in 'runtimepath' until either
callable returns something but None, the exception is raised or there
are no longer paths. If stopped in case callable returned non-None,
vim.foreach_rtp function returns the value returned by callable.
vim.chdir(*args, **kwargs) *python-chdir*
vim.fchdir(*args, **kwargs) *python-fchdir*
Run os.chdir or os.fchdir, then all appropriate vim stuff.
Note: you should not use these functions directly, use os.chdir and
os.fchdir instead. Behavior of vim.fchdir is undefined in case
os.fchdir does not exist.
Error object of the "vim" module
vim.error *python-error*
Upon encountering a Vim error, Python raises an exception of type
vim.error.
Example: >
try:
vim.command("put a")
except vim.error:
# nothing in register a
Constants of the "vim" module
Note that these are not actually constants - you could reassign them.
But this is silly, as you would then lose access to the vim objects
to which the variables referred.
vim.buffers *python-buffers*
A mapping object providing access to the list of vim buffers. The
object supports the following operations: >
:py b = vim.buffers[i] # Indexing (read-only)
:py b in vim.buffers # Membership test
:py n = len(vim.buffers) # Number of elements
:py for b in vim.buffers: # Iterating over buffer list
<
vim.windows *python-windows*
A sequence object providing access to the list of vim windows. The
object supports the following operations: >
:py w = vim.windows[i] # Indexing (read-only)
:py w in vim.windows # Membership test
:py n = len(vim.windows) # Number of elements
:py for w in vim.windows: # Sequential access
< Note: vim.windows object always accesses current tab page.
|python-tabpage|.windows objects are bound to parent |python-tabpage|
object and always use windows from that tab page (or throw vim.error
in case tab page was deleted). You can keep a reference to both
without keeping a reference to vim module object or |python-tabpage|,
they will not lose their properties in this case.
vim.tabpages *python-tabpages*
A sequence object providing access to the list of vim tab pages. The
object supports the following operations: >
:py t = vim.tabpages[i] # Indexing (read-only)
:py t in vim.tabpages # Membership test
:py n = len(vim.tabpages) # Number of elements
:py for t in vim.tabpages: # Sequential access
<
vim.current *python-current*
An object providing access (via specific attributes) to various
"current" objects available in vim:
vim.current.line The current line (RW) String
vim.current.buffer The current buffer (RW) Buffer
vim.current.window The current window (RW) Window
vim.current.tabpage The current tab page (RW) TabPage
vim.current.range The current line range (RO) Range
The last case deserves a little explanation. When the :python or
:pyfile command specifies a range, this range of lines becomes the
"current range". A range is a bit like a buffer, but with all access
restricted to a subset of lines. See |python-range| for more details.
Note: When assigning to vim.current.{buffer,window,tabpage} it expects
valid |python-buffer|, |python-window| or |python-tabpage| objects
respectively. Assigning triggers normal (with |autocommand|s)
switching to given buffer, window or tab page. It is the only way to
switch UI objects in python: you can't assign to
|python-tabpage|.window attribute. To switch without triggering
autocommands use >
py << EOF
saved_eventignore = vim.options['eventignore']
vim.options['eventignore'] = 'all'
try:
vim.current.buffer = vim.buffers[2] # Switch to buffer 2
finally:
vim.options['eventignore'] = saved_eventignore
EOF
<
vim.vars *python-vars*
vim.vvars *python-vvars*
Dictionary-like objects holding dictionaries with global (|g:|) and
vim (|v:|) variables respectively. Identical to `vim.bindeval("g:")`,
but faster.
vim.options *python-options*
Object partly supporting mapping protocol (supports setting and
getting items) providing a read-write access to global options.
Note: unlike |:set| this provides access only to global options. You
cannot use this object to obtain or set local options' values or
access local-only options in any fashion. Raises KeyError if no global
option with such name exists (i.e. does not raise KeyError for
|global-local| options and global only options, but does for window-
and buffer-local ones). Use |python-buffer| objects to access to
buffer-local options and |python-window| objects to access to
window-local options.
Type of this object is available via "Options" attribute of vim
module.
Output from Python *python-output*
Vim displays all Python code output in the Vim message area. Normal
output appears as information messages, and error output appears as
error messages.
In implementation terms, this means that all output to sys.stdout
(including the output from print statements) appears as information
messages, and all output to sys.stderr (including error tracebacks)
appears as error messages.
*python-input*
Input (via sys.stdin, including input() and raw_input()) is not
supported, and may cause the program to crash. This should probably be
fixed.
*python2-directory* *python3-directory* *pythonx-directory*
Python 'runtimepath' handling *python-special-path*
In python vim.VIM_SPECIAL_PATH special directory is used as a replacement for
the list of paths found in 'runtimepath': with this directory in sys.path and
vim.path_hooks in sys.path_hooks python will try to load module from
{rtp}/python2 (or python3) and {rtp}/pythonx (for both python versions) for
each {rtp} found in 'runtimepath'.
Implementation is similar to the following, but written in C: >
from imp import find_module, load_module
import vim
import sys
class VimModuleLoader(object):
def __init__(self, module):
self.module = module
def load_module(self, fullname, path=None):
return self.module
def _find_module(fullname, oldtail, path):
idx = oldtail.find('.')
if idx > 0:
name = oldtail[:idx]
tail = oldtail[idx+1:]
fmr = find_module(name, path)
module = load_module(fullname[:-len(oldtail)] + name, *fmr)
return _find_module(fullname, tail, module.__path__)
else:
fmr = find_module(fullname, path)
return load_module(fullname, *fmr)
# It uses vim module itself in place of VimPathFinder class: it does not
# matter for python which object has find_module function attached to as
# an attribute.
class VimPathFinder(object):
@classmethod
def find_module(cls, fullname, path=None):
try:
return VimModuleLoader(_find_module(fullname, fullname, path or vim._get_paths()))
except ImportError:
return None
@classmethod
def load_module(cls, fullname, path=None):
return _find_module(fullname, fullname, path or vim._get_paths())
def hook(path):
if path == vim.VIM_SPECIAL_PATH:
return VimPathFinder
else:
raise ImportError
sys.path_hooks.append(hook)
vim.VIM_SPECIAL_PATH *python-VIM_SPECIAL_PATH*
String constant used in conjunction with vim path hook. If path hook
installed by vim is requested to handle anything but path equal to
vim.VIM_SPECIAL_PATH constant it raises ImportError. In the only other
case it uses special loader.
Note: you must not use value of this constant directly, always use
vim.VIM_SPECIAL_PATH object.
vim.find_module(...) *python-find_module*
vim.path_hook(path) *python-path_hook*
Methods or objects used to implement path loading as described above.
You should not be using any of these directly except for vim.path_hook
in case you need to do something with sys.meta_path. It is not
guaranteed that any of the objects will exist in the future vim
versions.
vim._get_paths *python-_get_paths*
Methods returning a list of paths which will be searched for by path
hook. You should not rely on this method being present in future
versions, but can use it for debugging.
It returns a list of {rtp}/python2 (or {rtp}/python3) and
{rtp}/pythonx directories for each {rtp} in 'runtimepath'.
==============================================================================
3. Buffer objects *python-buffer*
Buffer objects represent vim buffers. You can obtain them in a number of ways:
- via vim.current.buffer (|python-current|)
- from indexing vim.buffers (|python-buffers|)
- from the "buffer" attribute of a window (|python-window|)
Buffer objects have two read-only attributes - name - the full file name for
the buffer, and number - the buffer number. They also have three methods
(append, mark, and range; see below).
You can also treat buffer objects as sequence objects. In this context, they
act as if they were lists (yes, they are mutable) of strings, with each
element being a line of the buffer. All of the usual sequence operations,
including indexing, index assignment, slicing and slice assignment, work as
you would expect. Note that the result of indexing (slicing) a buffer is a
string (list of strings). This has one unusual consequence - b[:] is different
from b. In particular, "b[:] = None" deletes the whole of the buffer, whereas
"b = None" merely updates the variable b, with no effect on the buffer.
Buffer indexes start at zero, as is normal in Python. This differs from vim
line numbers, which start from 1. This is particularly relevant when dealing
with marks (see below) which use vim line numbers.
The buffer object attributes are:
b.vars Dictionary-like object used to access
|buffer-variable|s.
b.options Mapping object (supports item getting, setting and
deleting) that provides access to buffer-local options
and buffer-local values of |global-local| options. Use
|python-window|.options if option is window-local,
this object will raise KeyError. If option is
|global-local| and local value is missing getting it
will return None.
b.name String, RW. Contains buffer name (full path).
Note: when assigning to b.name |BufFilePre| and
|BufFilePost| autocommands are launched.
b.number Buffer number. Can be used as |python-buffers| key.
Read-only.
b.valid True or False. Buffer object becomes invalid when
corresponding buffer is wiped out.
The buffer object methods are:
b.append(str) Append a line to the buffer
b.append(str, nr) Idem, below line "nr"
b.append(list) Append a list of lines to the buffer
Note that the option of supplying a list of strings to
the append method differs from the equivalent method
for Python's built-in list objects.
b.append(list, nr) Idem, below line "nr"
b.mark(name) Return a tuple (row,col) representing the position
of the named mark (can also get the []"<> marks)
b.range(s,e) Return a range object (see |python-range|) which
represents the part of the given buffer between line
numbers s and e |inclusive|.
Note that when adding a line it must not contain a line break character '\n'.
A trailing '\n' is allowed and ignored, so that you can do: >
:py b.append(f.readlines())
Buffer object type is available using "Buffer" attribute of vim module.
Examples (assume b is the current buffer) >
:py print b.name # write the buffer file name
:py b[0] = "hello!!!" # replace the top line
:py b[:] = None # delete the whole buffer
:py del b[:] # delete the whole buffer
:py b[0:0] = [ "a line" ] # add a line at the top
:py del b[2] # delete a line (the third)
:py b.append("bottom") # add a line at the bottom
:py n = len(b) # number of lines
:py (row,col) = b.mark('a') # named mark
:py r = b.range(1,5) # a sub-range of the buffer
:py b.vars["foo"] = "bar" # assign b:foo variable
:py b.options["ff"] = "dos" # set fileformat
:py del b.options["ar"] # same as :set autoread<
==============================================================================
4. Range objects *python-range*
Range objects represent a part of a vim buffer. You can obtain them in a
number of ways:
- via vim.current.range (|python-current|)
- from a buffer's range() method (|python-buffer|)
A range object is almost identical in operation to a buffer object. However,
all operations are restricted to the lines within the range (this line range
can, of course, change as a result of slice assignments, line deletions, or
the range.append() method).
The range object attributes are:
r.start Index of first line into the buffer
r.end Index of last line into the buffer
The range object methods are:
r.append(str) Append a line to the range
r.append(str, nr) Idem, after line "nr"
r.append(list) Append a list of lines to the range
Note that the option of supplying a list of strings to
the append method differs from the equivalent method
for Python's built-in list objects.
r.append(list, nr) Idem, after line "nr"
Range object type is available using "Range" attribute of vim module.
Example (assume r is the current range):
# Send all lines in a range to the default printer
vim.command("%d,%dhardcopy!" % (r.start+1,r.end+1))
==============================================================================
5. Window objects *python-window*
Window objects represent vim windows. You can obtain them in a number of ways:
- via vim.current.window (|python-current|)
- from indexing vim.windows (|python-windows|)
- from indexing "windows" attribute of a tab page (|python-tabpage|)
- from the "window" attribute of a tab page (|python-tabpage|)
You can manipulate window objects only through their attributes. They have no
methods, and no sequence or other interface.
Window attributes are:
buffer (read-only) The buffer displayed in this window
cursor (read-write) The current cursor position in the window
This is a tuple, (row,col).
height (read-write) The window height, in rows
width (read-write) The window width, in columns
vars (read-only) The window |w:| variables. Attribute is
unassignable, but you can change window
variables this way
options (read-only) The window-local options. Attribute is
unassignable, but you can change window
options this way. Provides access only to
window-local options, for buffer-local use
|python-buffer| and for global ones use
|python-options|. If option is |global-local|
and local value is missing getting it will
return None.
number (read-only) Window number. The first window has number 1.
This is zero in case it cannot be determined
(e.g. when the window object belongs to other
tab page).
row, col (read-only) On-screen window position in display cells.
First position is zero.
tabpage (read-only) Window tab page.
valid (read-write) True or False. Window object becomes invalid
when corresponding window is closed.
The height attribute is writable only if the screen is split horizontally.
The width attribute is writable only if the screen is split vertically.
Window object type is available using "Window" attribute of vim module.
==============================================================================
6. Tab page objects *python-tabpage*
Tab page objects represent vim tab pages. You can obtain them in a number of
ways:
- via vim.current.tabpage (|python-current|)
- from indexing vim.tabpages (|python-tabpages|)
You can use this object to access tab page windows. They have no methods and
no sequence or other interfaces.
Tab page attributes are:
number The tab page number like the one returned by
|tabpagenr()|.
windows Like |python-windows|, but for current tab page.
vars The tab page |t:| variables.
window Current tabpage window.
valid True or False. Tab page object becomes invalid when
corresponding tab page is closed.
TabPage object type is available using "TabPage" attribute of vim module.
==============================================================================
7. vim.bindeval objects *python-bindeval-objects*
vim.Dictionary object *python-Dictionary*
Dictionary-like object providing access to vim |Dictionary| type.
Attributes:
Attribute Description ~
locked One of *python-.locked*
Value Description ~
zero Variable is not locked
vim.VAR_LOCKED Variable is locked, but can be unlocked
vim.VAR_FIXED Variable is locked and can't be unlocked
Read-write. You can unlock locked variable by assigning
`True` or `False` to this attribute. No recursive locking
is supported.
scope One of
Value Description ~
zero Dictionary is not a scope one
vim.VAR_DEF_SCOPE |g:| or |l:| dictionary
vim.VAR_SCOPE Other scope dictionary,
see |internal-variables|
Methods (note: methods do not support keyword arguments):
Method Description ~
keys() Returns a list with dictionary keys.
values() Returns a list with dictionary values.
items() Returns a list of 2-tuples with dictionary contents.
update(iterable), update(dictionary), update(**kwargs)
Adds keys to dictionary.
get(key[, default=None])
Obtain key from dictionary, returning the default if it is
not present.
pop(key[, default])
Remove specified key from dictionary and return
corresponding value. If key is not found and default is
given returns the default, otherwise raises KeyError.
popitem()
Remove random key from dictionary and return (key, value)
pair.
has_key(key)
Check whether dictionary contains specified key, similar
to `key in dict`.
__new__(), __new__(iterable), __new__(dictionary), __new__(update)
You can use `vim.Dictionary()` to create new vim
dictionaries. `d=vim.Dictionary(arg)` is the same as
`d=vim.bindeval('{}');d.update(arg)`. Without arguments
constructs empty dictionary.
Examples: >
d = vim.Dictionary(food="bar") # Constructor
d['a'] = 'b' # Item assignment
print d['a'] # getting item
d.update({'c': 'd'}) # .update(dictionary)
d.update(e='f') # .update(**kwargs)
d.update((('g', 'h'), ('i', 'j'))) # .update(iterable)
for key in d.keys(): # .keys()
for val in d.values(): # .values()
for key, val in d.items(): # .items()
print isinstance(d, vim.Dictionary) # True
for key in d: # Iteration over keys
class Dict(vim.Dictionary): # Subclassing
<
Note: when iterating over keys you should not modify dictionary.
vim.List object *python-List*
Sequence-like object providing access to vim |List| type.
Supports `.locked` attribute, see |python-.locked|. Also supports the
following methods:
Method Description ~
extend(item) Add items to the list.
__new__(), __new__(iterable)
You can use `vim.List()` to create new vim lists.
`l=vim.List(iterable)` is the same as
`l=vim.bindeval('[]');l.extend(iterable)`. Without
arguments constructs empty list.
Examples: >
l = vim.List("abc") # Constructor, result: ['a', 'b', 'c']
l.extend(['abc', 'def']) # .extend() method
print l[1:] # slicing
l[:0] = ['ghi', 'jkl'] # slice assignment
print l[0] # getting item
l[0] = 'mno' # assignment
for i in l: # iteration
print isinstance(l, vim.List) # True
class List(vim.List): # Subclassing
vim.Function object *python-Function*
Function-like object, acting like vim |Funcref| object. Supports `.name`
attribute and is callable. Accepts special keyword argument `self`, see
|Dictionary-function|. You can also use `vim.Function(name)` constructor,
it is the same as `vim.bindeval('function(%s)'%json.dumps(name))`.
Examples: >
f = vim.Function('tr') # Constructor
print f('abc', 'a', 'b') # Calls tr('abc', 'a', 'b')
vim.command('''
function DictFun() dict
return self
endfunction
''')
f = vim.bindeval('function("DictFun")')
print f(self={}) # Like call('DictFun', [], {})
print isinstance(f, vim.Function) # True
==============================================================================
8. pyeval() and py3eval() Vim functions *python-pyeval*
To facilitate bi-directional interface, you can use |pyeval()| and |py3eval()|
functions to evaluate Python expressions and pass their values to VimL.
==============================================================================
9. Dynamic loading *python-dynamic*
On MS-Windows the Python library can be loaded dynamically. The |:version|
output then includes |+python/dyn|.
This means that Vim will search for the Python DLL file only when needed.
When you don't use the Python interface you don't need it, thus you can use
Vim without this DLL file.
To use the Python interface the Python DLL must be in your search path. In a
console window type "path" to see what directories are used.
The name of the DLL must match the Python version Vim was compiled with.
Currently the name is "python24.dll". That is for Python 2.4. To know for
sure edit "gvim.exe" and search for "python\d*.dll\c".
==============================================================================
10. Python 3 *python3*
*:py3* *:python3*
The `:py3` and `:python3` commands work similar to `:python`. A simple check
if the `:py3` command is working: >
:py3 print("Hello")
< *:py3file*
The `:py3file` command works similar to `:pyfile`.
*:py3do* *E863*
The `:py3do` command works similar to `:pydo`.
Vim can be built in four ways (:version output):
1. No Python support (-python, -python3)
2. Python 2 support only (+python or +python/dyn, -python3)
3. Python 3 support only (-python, +python3 or +python3/dyn)
4. Python 2 and 3 support (+python/dyn, +python3/dyn)
Some more details on the special case 4: *python-2-and-3*
When Python 2 and Python 3 are both supported they must be loaded dynamically.
When doing this on Linux/Unix systems and importing global symbols, this leads
to a crash when the second Python version is used. So either global symbols
are loaded but only one Python version is activated, or no global symbols are
loaded. The latter makes Python's "import" fail on libraries that expect the
symbols to be provided by Vim.
*E836* *E837*
Vim's configuration script makes a guess for all libraries based on one
standard Python library (termios). If importing this library succeeds for
both Python versions, then both will be made available in Vim at the same
time. If not, only the version first used in a session will be enabled.
When trying to use the other one you will get the E836 or E837 error message.
Here Vim's behavior depends on the system in which it was configured. In a
system where both versions of Python were configured with --enable-shared,
both versions of Python will be activated at the same time. There will still
be problems with other third party libraries that were not linked to
libPython.
To work around such problems there are these options:
1. The problematic library is recompiled to link to the according
libpython.so.
2. Vim is recompiled for only one Python version.
3. You undefine PY_NO_RTLD_GLOBAL in auto/config.h after configuration. This
may crash Vim though.
*E880*
Raising SystemExit exception in python isn't endorsed way to quit vim, use: >
:py vim.command("qall!")
<
*has-python*
You can test what Python version is available with: >
if has('python')
echo 'there is Python 2.x'
elseif has('python3')
echo 'there is Python 3.x'
endif
Note however, that when Python 2 and 3 are both available and loaded
dynamically, these has() calls will try to load them. If only one can be
loaded at a time, just checking if Python 2 or 3 are available will prevent
the other one from being available.
==============================================================================
vim:tw=78:ts=8:ft=help:norl:
| {
"pile_set_name": "Github"
} |
/**
* @file updatersettings.h
* Persistent settings for automatic updates. @ingroup updater
*
* @authors Copyright © 2012-2017 Jaakko Keränen <[email protected]>
* @authors Copyright © 2013 Daniel Swanson <[email protected]>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#ifndef DENG_CLIENT_UPDATERSETTINGS_H
#define DENG_CLIENT_UPDATERSETTINGS_H
#include <de/Time>
#include <de/String>
#include <de/NativePath>
/**
* Convenient interface to the Updater settings. All changes to the settings
* are immediately saved persistently. In practice, the values are stored in
* Config.updater.
*/
class UpdaterSettings
{
public:
enum Frequency
{
Daily = 0,
Biweekly = 1, // Tuesday + Saturday
Weekly = 2, // 7 days
Monthly = 3, // 30 days
AtStartup = 4
};
enum Channel
{
Stable = 0,
Unstable = 1,
StableOrCandidate = 2,
};
public:
UpdaterSettings();
Frequency frequency() const;
Channel channel() const;
de::Time lastCheckTime() const;
bool onlyCheckManually() const;
bool autoDownload() const;
bool deleteAfterUpdate() const;
bool isDefaultDownloadPath() const;
de::NativePath downloadPath() const;
de::NativePath pathToDeleteAtStartup() const;
/**
* @return Human-readable description of when the latest update
* check was made.
*/
de::String lastCheckAgo() const;
void setFrequency(Frequency freq);
void setChannel(Channel channel);
void setLastCheckTime(const de::Time& time);
void setOnlyCheckManually(bool onlyManually);
void setAutoDownload(bool autoDl);
void setDeleteAfterUpdate(bool deleteAfter);
void setDownloadPath(de::NativePath downloadPath);
void useDefaultDownloadPath();
void setPathToDeleteAtStartup(de::NativePath deletePath);
static de::NativePath defaultDownloadPath();
};
#endif // DENG_CLIENT_UPDATERSETTINGS_H
| {
"pile_set_name": "Github"
} |
using JT808.Protocol.Metadata;
using System;
using System.Collections.Generic;
namespace JT808.Protocol.Interfaces
{
/// <summary>
/// 分包策略
/// 注意:处理808的分包读取完流需要先进行转义在进行分包
/// </summary>
public interface IJT808SplitPackageStrategy
{
IEnumerable<JT808SplitPackageProperty> Processor(ReadOnlySpan<byte> bigData);
}
}
| {
"pile_set_name": "Github"
} |
julia 0.6
Nulls
| {
"pile_set_name": "Github"
} |
ovl_Bg_Mori_Idomizu
z_bg_mori_idomizu.c | {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -fsyntax-only -verify %s
int foo() __attribute__((__hot__));
int bar() __attribute__((__cold__));
int var1 __attribute__((__cold__)); // expected-warning{{'__cold__' attribute only applies to functions}}
int var2 __attribute__((__hot__)); // expected-warning{{'__hot__' attribute only applies to functions}}
int qux() __attribute__((__hot__)) __attribute__((__cold__)); // expected-error{{'__cold__' and 'hot' attributes are not compatible}} \
// expected-note{{conflicting attribute is here}}
int baz() __attribute__((__cold__)) __attribute__((__hot__)); // expected-error{{'__hot__' and 'cold' attributes are not compatible}} \
// expected-note{{conflicting attribute is here}}
| {
"pile_set_name": "Github"
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.jsmpp.util;
import org.jsmpp.bean.OptionalParameter;
/**
* Utility to compose the PDU bytes. The size of the buffer is depends to the
* entities appended to the buffer.
*
* @author uudashr
* @version 1.0
* @since 1.0
*
*/
public class PDUByteBuffer {
private static final CapacityPolicy DEFAULT_CAPACITY_POLICY = new SimpleCapacityPolicy();
private CapacityPolicy capacityPolicy;
private byte[] bytes;
private int bytesLength;
/**
* Construct with specified command_id, command_status, and sequence_number.
*
* @param commandId is the command_id.
* @param commandStatus is the command_status.
* @param sequenceNumber is the sequence_number.
*/
public PDUByteBuffer(int commandId, int commandStatus, int sequenceNumber) {
this(commandId, commandStatus, sequenceNumber, DEFAULT_CAPACITY_POLICY);
}
/**
* Construct with specified command_id, command_status, sequence_number and
* capacity policy.
*
* @param commandId is the command_id.
* @param commandStatus is the command_status.
* @param sequenceNumber is the sequence_number.
* @param capacityPolicy is the capacity policy.
*/
public PDUByteBuffer(int commandId, int commandStatus, int sequenceNumber, CapacityPolicy capacityPolicy) {
this(capacityPolicy);
append(commandId);
append(commandStatus);
append(sequenceNumber);
normalizeCommandLength();
}
/**
* Default constructor.
*/
public PDUByteBuffer() {
this(DEFAULT_CAPACITY_POLICY);
}
/**
* Construct with specified capacity policy.
*
* @param capacityPolicy is the capacity policy.
*/
public PDUByteBuffer(CapacityPolicy capacityPolicy) {
/*
* the initial is 4 byte, just for the command_length
*/
bytes = new byte[4];
this.capacityPolicy = capacityPolicy;
bytesLength = 4;
normalizeCommandLength();
}
/**
* Append bytes to specified offset and length.
*
* @param b is the bytes to append.
* @param offset is the offset where the bytes will be placed.
* @param length the length that will specified which part of the bytes will
* be append.
* @return the latest length of the byte buffer.
*/
public int append(byte[] b, int offset, int length) {
int oldLength = bytesLength;
bytesLength += length;
int newCapacity = capacityPolicy.ensureCapacity(bytesLength, bytes.length);
if (newCapacity > bytes.length) {
byte[] newB = new byte[newCapacity];
System.arraycopy(bytes, 0, newB, 0, bytes.length); // copy current bytes to new bytes
bytes = newB;
}
System.arraycopy(b, offset, bytes, oldLength, length); // assign value
normalizeCommandLength();
return bytesLength;
}
/**
* Append all bytes.
*
* @param bytes is the bytes to append.
* @return the latest length of the buffer.
*/
public int append(byte[] bytes) {
return append(bytes, 0, bytes.length);
}
/**
* Append single byte.
*
* @param b is the byte to append.
* @return the latest length of the buffer.
*/
public int append(byte b) {
return append(new byte[] { b });
}
/**
* Append int value (contains 4 octet).
*
* @param intValue is the value to append.
* @return the latest length of the buffer.
*/
public int append(int intValue) {
return append(OctetUtil.intToBytes(intValue));
}
/**
* Append <tt>String</tt> value.
*
* @param stringValue
* @param nullTerminated <tt>true<tt> means C-Octet String.
* The default value is <tt>true</tt>.
* @return the latest length of the buffer.
*/
public int append(String stringValue, boolean nullTerminated) {
if (stringValue != null)
append(stringValue.getBytes());
if (nullTerminated)
append((byte)0);
return bytesLength;
}
/**
* Append C-Octet String / null terminated String value.
*
* @param stringValue is the value to append.
* @return the latest length of the buffer.
*/
public int append(String stringValue) {
return append(stringValue, true);
}
/**
* Append an optional parameter.
*
* @param optionalParameter is the optional parameter.
* @return the latest length of the buffer.
*/
public int append(OptionalParameter optionalParameter) {
return append(optionalParameter.serialize());
}
/**
* Append all optional parameters.
*
* @param optionalParameters is the optional parameters.
* @return the latest length of the buffer.
*/
public int appendAll(OptionalParameter[] optionalParameters) {
int length = 0;
for (OptionalParameter optionalParamameter : optionalParameters) {
length += append(optionalParamameter);
}
return length;
}
/**
* Assign the proper command length to the first 4 octet.
*/
private void normalizeCommandLength() {
System.arraycopy(OctetUtil.intToBytes(bytesLength), 0, bytes, 0, 4);
}
/**
* Get the composed bytes of PDU.
*
* @return the composed bytes.
*/
public byte[] toBytes() {
byte[] returnBytes = new byte[bytesLength];
System.arraycopy(bytes, 0, returnBytes, 0, bytesLength);
return returnBytes;
}
int getCommandLengthValue() {
return OctetUtil.bytesToInt(bytes, 0);
}
int getBytesLength() {
return bytesLength;
}
} | {
"pile_set_name": "Github"
} |
/*
Copyright (c) 2015 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package object
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type Network struct {
Common
}
func NewNetwork(c *vim25.Client, ref types.ManagedObjectReference) *Network {
return &Network{
Common: NewCommon(c, ref),
}
}
// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this Network
func (n Network) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
var e mo.Network
// Use Network.Name rather than Common.Name as the latter does not return the complete name if it contains a '/'
// We can't use Common.ObjectName here either as we need the ManagedEntity.Name field is not set since mo.Network
// has its own Name field.
err := n.Properties(ctx, n.Reference(), []string{"name"}, &e)
if err != nil {
return nil, err
}
backing := &types.VirtualEthernetCardNetworkBackingInfo{
VirtualDeviceDeviceBackingInfo: types.VirtualDeviceDeviceBackingInfo{
DeviceName: e.Name,
},
}
return backing, nil
}
| {
"pile_set_name": "Github"
} |
---
view: page
title: "22. Git внутри: Каталог .git"
---
<h3>Цели</h3>
<ul><li>Узнать о структуре каталога <code>.git</code></li></ul>
<h2><em>01</em> Каталог <code>.git</code></h2>
<p>Настало время провести небольшое исследование. Для начала, из корневого каталога вашего проекта…</p>
<h4 class="h4-pre">Выполните:</h4>
<pre class="instructions">ls -C .git</pre>
<h4 class="h4-pre">Результат:</h4>
<pre class="sample">$ ls -C .git
COMMIT_EDITMSG MERGE_RR config hooks info objects rr-cache
HEAD ORIG_HEAD description index logs refs</pre>
<p>Это магический каталог, в котором хранятся все «материалы» git. Давайте заглянем в каталог объектов.</p>
<h2><em>02</em> База данных объектов</h2>
<h4 class="h4-pre">Выполните:</h4>
<pre class="instructions">ls -C .git/objects</pre>
<h4 class="h4-pre">Результат:</h4>
<pre class="sample">$ ls -C .git/objects
09 24 28 45 59 6a 77 80 8c 97 af c4 e7 info
11 27 43 56 69 6b 78 84 91 9c b5 e4 fa pack</pre>
<p>Вы должны увидеть кучу каталогов, имена которых состоят из 2 символов. Имена каталогов являются первыми двумя буквами хэша sha1 объекта, хранящегося в git.</p>
<h2><em>03</em> Углубляемся в базу данных объектов</h2>
<h4 class="h4-pre">Выполните:</h4>
<pre class="instructions">ls -C .git/objects/<dir></pre>
<h4 class="h4-pre">Результат:</h4>
<pre class="sample">$ ls -C .git/objects/09
6b74c56bfc6b40e754fc0725b8c70b2038b91e 9fb6f9d3a104feb32fcac22354c4d0e8a182c1</pre>
<p>Смотрим в один из каталогов с именем из 2 букв. Вы увидите файлы с именами из 38 символов. Это файлы, содержащие объекты, хранящиеся в git. Они сжаты и закодированы, поэтому просмотр их содержимого нам мало чем поможет.
Рассмотрим далее каталог .git внимательно</p>
<h2><em>04</em> Config File</h2>
<h4 class="h4-pre">Выполните:</h4>
<pre class="instructions">cat .git/config</pre>
<h4 class="h4-pre">Результат:</h4>
<pre class="sample">$ cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
[user]
name = Alexander Shvets
email = [email protected]</pre>
<p>Это файл конфигурации, создающийся для каждого конкретного проекта. Записи в этом файле будут перезаписывать записи в файле <code>.gitconfig</code> вашего главного каталога, по крайней мере в рамках этого проекта.</p>
<h2><em>05</em> Ветки и теги</h2>
<h4 class="h4-pre">Выполните:</h4>
<pre class="instructions">ls .git/refs
ls .git/refs/heads
ls .git/refs/tags
cat .git/refs/tags/v1</pre>
<h4 class="h4-pre">Результат:</h4>
<pre class="sample">$ ls .git/refs
heads
tags
$ ls .git/refs/heads
master
$ ls .git/refs/tags
v1
v1-beta
$ cat .git/refs/tags/v1
fa3c1411aa09441695a9e645d4371e8d749da1dc</pre>
<p>Вы должны узнавать файлы в подкаталоге тегов. Каждый файл соответствует тегу, ранее созданному с помощью команды <code>git tag</code>. Его содержание – это всего лишь хэш коммита, привязанный к тегу.</p>
<p>Каталог <em>heads</em> практически аналогичен, но используется для веток, а не тегов. На данный момент у нас есть только одна ветка, так что все, что вы увидите в этом каталоге – это ветка <em>master</em>.</p>
<h2><em>06</em> Файл <span class="caps">HEAD</span></h2>
<h4 class="h4-pre">Выполните:</h4>
<pre class="instructions">cat .git/HEAD</pre>
<h4 class="h4-pre">Результат:</h4>
<pre class="sample">$ cat .git/HEAD
ref: refs/heads/master</pre>
<p>Файл <span class="caps">HEAD</span> содержит ссылку на текущую ветку, в данный момент это должна быть ветка master.</p> | {
"pile_set_name": "Github"
} |
/*
* Created on Jun 10, 2008
*
* 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.
*
* Copyright @2008-2013 the original author or authors.
*/
package org.fest.swing.driver;
import static org.fest.swing.test.core.CommonAssertions.failWhenExpectingException;
import org.fest.swing.cell.JTableCellWriter;
import org.fest.swing.exception.ActionFailedException;
import org.junit.Test;
/**
* Test case for implementations of {@link JTableCellWriter}.
*
* @author Yvonne Wang
* @author Alex Ruiz
*/
public abstract class JTableCellWriter_startCellEditing_TestCase extends JTableCellWriter_TestCase {
@Test
public void should_throw_error_if_editor_Component_cannot_be_handled() {
try {
writer.startCellEditing(window.table, 0, 1);
failWhenExpectingException();
} catch (ActionFailedException e) {
assertMessageIndicatesWriterWasUnableToActivateEditor(e);
}
}
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.