text stringlengths 2 1.04M | meta dict |
|---|---|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Axis2/C: axis2_async_result.h File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.3 -->
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<form action="search.php" method="get">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td><label> <u>S</u>earch for </label></td>
<td><input type="text" name="query" value="" size="20" accesskey="s"/></td>
</tr>
</table>
</form>
</li>
</ul>
</div>
<div class="nav">
<a class="el" href="dir_f60961de8e5edc3b2658ef023e959e45.html">deploy</a> » <a class="el" href="dir_6b4e91e54b7316b376882a6402adbf44.html">include</a> » <a class="el" href="dir_df3a7695d5a9e696f30b948b566829e7.html">axis2-1.6.0</a></div>
<h1>axis2_async_result.h File Reference</h1><code>#include <<a class="el" href="axis2__defines_8h-source.html">axis2_defines.h</a>></code><br>
<code>#include <<a class="el" href="axutil__env_8h-source.html">axutil_env.h</a>></code><br>
<code>#include <<a class="el" href="axis2__msg__ctx_8h-source.html">axis2_msg_ctx.h</a>></code><br>
<code>#include <<a class="el" href="axiom__soap__envelope_8h-source.html">axiom_soap_envelope.h</a>></code><br>
<p>
<a href="axis2__async__result_8h-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Typedefs</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">typedef struct <br>
axis2_async_result </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__async__result.html#g7f79cfe086dfb98806cc3c0c3b408c3c">axis2_async_result_t</a></td></tr>
<tr><td colspan="2"><br><h2>Functions</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
axiom_soap_envelope_t * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__async__result.html#g78f7a7e270e176c1094ca43d106561b1">axis2_async_result_get_envelope</a> (<a class="el" href="group__axis2__async__result.html#g7f79cfe086dfb98806cc3c0c3b408c3c">axis2_async_result_t</a> *async_result, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
<a class="el" href="group__axis2__msg__ctx.html#g160acae289ac39cb49fa625ffd88e410">axis2_msg_ctx_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__async__result.html#g4b31e913ac079031b24e18c67236ef25">axis2_async_result_get_result</a> (<a class="el" href="group__axis2__async__result.html#g7f79cfe086dfb98806cc3c0c3b408c3c">axis2_async_result_t</a> *async_result, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN void </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__async__result.html#g7dc808667785c5430baef18f3e377d5c">axis2_async_result_free</a> (<a class="el" href="group__axis2__async__result.html#g7f79cfe086dfb98806cc3c0c3b408c3c">axis2_async_result_t</a> *async_result, const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env)</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top">AXIS2_EXTERN <br>
<a class="el" href="group__axis2__async__result.html#g7f79cfe086dfb98806cc3c0c3b408c3c">axis2_async_result_t</a> * </td><td class="memItemRight" valign="bottom"><a class="el" href="group__axis2__async__result.html#g065fafef3286259aa3c8ceb7da9957ee">axis2_async_result_create</a> (const <a class="el" href="structaxutil__env.html">axutil_env_t</a> *env, <a class="el" href="group__axis2__msg__ctx.html#g160acae289ac39cb49fa625ffd88e410">axis2_msg_ctx_t</a> *result)</td></tr>
</table>
<hr><a name="_details"></a><h2>Detailed Description</h2>
<hr size="1"><address style="text-align: right;"><small>Generated on Fri Apr 17 11:49:43 2009 for Axis2/C by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.3 </small></address>
</body>
</html>
| {
"content_hash": "e4077ec946b262008938487b215d8559",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 489,
"avg_line_length": 80.81967213114754,
"alnum_prop": 0.6878296146044625,
"repo_name": "loentar/axis2c-unofficial",
"id": "430e421f38f38ae9bbb3d6699e08ed7452de9caa",
"size": "4930",
"binary": false,
"copies": "1",
"ref": "refs/heads/axis2c-1.6.0",
"path": "xdocs/api/html/axis2__async__result_8h.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "622"
},
{
"name": "C",
"bytes": "5488171"
},
{
"name": "C++",
"bytes": "903476"
},
{
"name": "CSS",
"bytes": "27555"
},
{
"name": "HTML",
"bytes": "11535854"
},
{
"name": "JavaScript",
"bytes": "3212"
},
{
"name": "Makefile",
"bytes": "58149"
},
{
"name": "Objective-C",
"bytes": "3919"
},
{
"name": "PHP",
"bytes": "10231"
},
{
"name": "Perl",
"bytes": "2977"
},
{
"name": "Shell",
"bytes": "12296"
}
],
"symlink_target": ""
} |
<?php
namespace Strimoid\Http\Controllers\Content;
use Strimoid\Http\Controllers\BaseController;
class EmbedController extends BaseController
{
public function getEmbedCode($content): array
{
$embedCode = $content->getEmbed();
return ['status' => 'ok', 'code' => $embedCode];
}
}
| {
"content_hash": "8684e3a152273c1a5b430dd9e66bba29",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 56,
"avg_line_length": 20.8,
"alnum_prop": 0.6794871794871795,
"repo_name": "Strimoid/Strimoid",
"id": "4b39e89a4afd166a611a32be40550bcbbe116957",
"size": "312",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/Http/Controllers/Content/EmbedController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "149706"
},
{
"name": "Dockerfile",
"bytes": "729"
},
{
"name": "HTML",
"bytes": "4577"
},
{
"name": "JavaScript",
"bytes": "57810"
},
{
"name": "Mustache",
"bytes": "1947"
},
{
"name": "PHP",
"bytes": "1018371"
},
{
"name": "SCSS",
"bytes": "8388"
},
{
"name": "Sass",
"bytes": "17483"
},
{
"name": "Shell",
"bytes": "102"
},
{
"name": "Twig",
"bytes": "3397"
}
],
"symlink_target": ""
} |
package io.udash.web.guide.demos.rpc
import io.udash.web.guide.GuideExceptions
import io.udash.web.guide.demos.i18n.Translations
import scala.concurrent.Future
class ExceptionsServer extends ExceptionsRPC {
override def example(): Future[Unit] =
Future.failed(GuideExceptions.ExampleException("Exception from server"))
override def exampleWithTranslatableError(): Future[Unit] =
Future.failed(GuideExceptions.TranslatableExampleException(Translations.exceptions.example))
override def unknownError(): Future[Unit] =
Future.failed(new RuntimeException("RuntimeException from server"))
}
| {
"content_hash": "4e1d648bba35dc8446318aa9201f2949",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 96,
"avg_line_length": 35.8235294117647,
"alnum_prop": 0.8029556650246306,
"repo_name": "UdashFramework/udash-core",
"id": "f7366b0a28a100087f13174c8dba47b8e14edb37",
"size": "609",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "guide/backend/src/main/scala/io/udash/web/guide/demos/rpc/ExceptionsServer.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2450"
},
{
"name": "HTML",
"bytes": "4288"
},
{
"name": "Less",
"bytes": "180"
},
{
"name": "Scala",
"bytes": "2000448"
}
],
"symlink_target": ""
} |
Here I have provided an example of a bingo card you might create to go with watching a lot of crime shows. This example was created using the provided text file and the command:
```
python bingo.py -i example_input.txt -o example.pdf -t CRIME -f "Murder!"
```
| {
"content_hash": "b7e0d951e1a8ff5c8972c78e666dcf4e",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 177,
"avg_line_length": 52.2,
"alnum_prop": 0.7471264367816092,
"repo_name": "krellsarah/bingo-generator",
"id": "5bf7f5c734e9312bfb7df5985746ff38d110d736",
"size": "261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/example.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "16864"
}
],
"symlink_target": ""
} |
<<<<<<< HEAD
[Google App Engine Boilerplate](http://appengine.beecoss.com) [](http://travis-ci.org/coto/gae-boilerplate)
==============================
Sponsored by <a href="http://www.jetbrains.com/pycharm/" alt="Download PyCharm">
<img src="http://www.jetbrains.com/img/logos/pycharm_logo142x29.gif">
</a>
Google App Engine Boilerplate gets your project off the ground quickly using the Google App Engine platform.
Create powerful applications by using the latest technology supported on Google App Engine.
It will introduces new developers to App Engine and advanced developers to follow best practices.
[Try a online demo](http://appengine.beecoss.com)
What's a Boilerplate?
---------------------
A Boilerplate is used to describe sections of code that can be reused over and over in new contexts or applications which provides good default values, reducing the need to specify program details in every project. ([wikipedia](http://en.wikipedia.org/wiki/Boilerplate_code))
What makes this Boilerplate Amazing?
------------------------------------
It is fully featured, actively maintained, and uses the latest and most supported technologies of Google App Engine.
New to Google App Engine? Learn about it by watching [this video](http://www.youtube.com/watch?v=bfgO-LXGpTM) or reading [this website](https://developers.google.com/appengine/).
Get started in just a few easy steps
------------------------------------
1. Download the last version of the [App Engine SDK](http://code.google.com/appengine/downloads.html#Google_App_Engine_SDK_for_Python) for Linux, Mac OS or Windows (Tested with SDK version 1.8.1).
1. Download the code of this Boilerplate ([here](https://github.com/coto/gae-boilerplate/zipball/master))
1. Run locally ([instructions](https://developers.google.com/appengine/docs/python/tools/devserver)).
1. Set your 'application' name in [app.yaml](https://github.com/coto/gae-boilerplate/blob/master/app.yaml)
1. Set custom config parameters in [config/localhost.py](https://github.com/coto/gae-boilerplate/blob/master/config/localhost.py). (secret key, [recaptcha code](http://www.google.com/recaptcha/whyrecaptcha), salt etc.) To get started, copy the default settings from [boilerplate/config.py](https://github.com/coto/gae-boilerplate/blob/master/boilerplate/config.py). . Note that most of the default settings will need to be changed to yield a secure and working application. Make the changes to these settings in the config/*.py (localhost.py for development on your local PC, production.py for production on App Engine's servers, testing.py for unittests configurations) The configurations in /config take precedence over boilerplate/config.py.
1. Set Authentication Options dropdown to Federated Login in the Google App Engine control panel (or if you do not want federated login, set enable_federated_login to false in config.py)
1. Deploy it online ([instructions](https://developers.google.com/appengine/docs/python/gettingstarted/uploading) - recommended setup: python 2.7, high replication datastore)
Please note that boilerplate code is located in the boilerplate module while your custom application code should be located in the web module.
The intention is that separating the boilerplate code from your application code will avoid merge conflicts as you keep up with future boilerplate changes.
Settings, code, and templates in the root [config.py](https://github.com/coto/gae-boilerplate/blob/master/config.py), web module, and templates directory take precedence over the equivalent files in the boilerplate module.
Functions and features:
-----------------------
+ Authentication (Login, Logout, Sign Up)
+ Federated Login - login via your favorite social network (Google, Twitter, etc...) powered by OpenID and OAuth
+ Reset Password
+ Update User Profile
+ Contact Form
+ Client side and server side form validation
+ Automatic detection of user language
+ Support for 8 Languages (English, Spanish, Italian, French, Chinese, Indonesian, German and Russian)
+ Visitors Log
+ Notifications and Confirmation for users when they change their email or password
+ Responsive Design for viewing on PCs, tablets, and mobile phones (synchronized with Twitter-Bootstrap project)
+ Mobile identification
+ Unit testing
+ Error handling
+ Basic user management features available under /admin/users/ for Google Application Administrators
Resources
---------
Boilerplate has a Google group ([gae-boilerplate](https://groups.google.com/forum/?fromgroups#!forum/gae-boilerplate)) for discussions and a Twitter account ([@gaeboilerplate](http://twitter.com/gaeboilerplate/)) for sharing related resources.
Open Source
-----------
If you want to add, fix or improve something, create an [issue](https://github.com/coto/gae-boilerplate/issues) or send a [Pull Request](https://github.com/coto/gae-boilerplate/pull/new/master).
Before committing fixes we recommend running the unitests (in the boilerplate package). This will help guard against changes that accidently break other code. See the testing section below for instructions.
Feel free to commit improvements or new features. Feedback, comments and ideas are welcome.
Testing
-------
**Unit testing**
+ Unit tests can be run via [testrunner](https://github.com/coto/gae-boilerplate/blob/master/testrunner.py) or in Eclipse by right clicking on the web folder and selecting run as... Python unit-test.
+ You may need to add /boilerplate/external to your python path.
+ Please add unittests for your application to [unittests](https://github.com/coto/gae-boilerplate/tree/master/web/tests).
+ To run unittests it may be necessary to install [webtest](http://webtest.pythonpaste.org/en/latest/index.html#installation), [mock](http://www.voidspace.org.uk/python/mock/), and [pyquery](http://packages.python.org/pyquery/) in your local python installation.
sudo pip install webtest
sudo pip install mock
sudo pip install pyquery
+ Your own unittests can be created similarly to those in the boilerplate. Inheriting from boilerplate.lib.test_helpers.HandlerHelpers will provide access to convenient handler testing methods used by the boilerplate.
Technologies used
-----------------
+ Python 2.7.3
+ [NDB 1.0.9](http://developers.google.com/appengine/docs/python/ndb/) (The best datastore API for the Google App Engine Python runtime).
+ [Jinja2 2.6](http://jinja.pocoo.org/docs/) (A fully featured template engine for Python).
+ [WTForms-1.0.2](http://wtforms.simplecodes.com/) (Forms validation framework keeping user interaction secure and flexible with or without javascript).
+ [Babel-0.9.6](http://babel.edgewall.org/) and [gaepytz-2011h](http://code.google.com/p/gae-pytz/) (Industy standard internationalization renders the site in multiple languages).
+ [webapp2 2.5.2](http://webapp-improved.appspot.com/) (A lightweight Python web framework, the most compatible with Google App Engine).
+ webapp2_extras.sessions
+ webapp2_extras.routes
+ webapp2_extras.auth
+ webapp2_extras.i18n
+ Code written following the [Google Python Style Guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html)
+ Unit testing with [unittest](http://docs.python.org/library/unittest.html), [webtest](http://webtest.pythonpaste.org/en/latest/index.html), [pyquery](http://packages.python.org/pyquery/)
+ OpenID library provided by Google App Engine
+ OAuth2 for federated login providers that do not support OpenID
Front-end Technologies
----------------------
+ [HTML5Boilerplate](http://html5boilerplate.com/)
+ [Modernizr 2.6.1](http://modernizr.com)
+ [jQuery 1.8.2](http://jquery.com)
+ [Twitter Bootstrap 2.2.1](http://twitter.github.com/bootstrap/) Template for Desktop Version.
Please help us translate and add new languages!
-----------------------------------------------
In each locale/<locale code>/LC_MESSAGES directory there is a file messages.po. Please help us translate the text in these files.
msgid is the text in English. msgstr is the translation to the language indicated by the locale code. For example:
<tt>msgid "Change your password"</tt>
<tt>msgstr "Cambiar tu contraseña"</tt>
Working with Internationalization (i18n)
----------------------------------------
This boilerplate comes bundled with babel, pytz, and automatic language detection which together provide powerful internationalization capability.
Text to be translated needs to be indicated in code and then translated by users like you after which it is compiled for speed.
Adding or updating text to be translated or adding new languages requires more work as indicated in the steps below:
1. Text to be translated should be enclosed in `_("text to translate")` in *.py files.
+ `{{..._("text to translate")...}}`
+ `{%..._("text to translate")...%}`
1. In html templates translated text is indicated by:
+ `{% trans %}text to translate{% endtrans %}`
**NOTE:** Translations can be added to other types of files too. See [babel.cfg](https://github.com/coto/gae-boilerplate/blob/master/locale/babel.cfg)
and [babel.cfg documentation](http://babel.edgewall.org/wiki/Documentation/0.9/messages.html)
1. Obtain pybabel to perform the steps below. You will need to install and compile [jinja2](http://jinja.pocoo.org/docs/) and [babel](http://babel.edgewall.org/wiki/Download).
Note that you may need to first install [setuptools and easy_install](http://pypi.python.org/pypi/setuptools).
pybabel.exe can be run from the Scripts directory in your python installation.
* `easy_install jinja2 babel`
1. Babel then needs to find all translationed text blocks throughout code and templates.
After installing pybabl run this command to extract messages (assuming ./ is the location of this boilerplate):
<tt>pybabel extract -F ./locale/babel.cfg -o ./locale/messages.pot ./ --sort-output --no-location --omit-header</tt>
1. Update translations of existing languages or add new languages
1. Update translations of existing languages by running this command for each locale:
<tt>pybabel update -l es_ES -d ./locale -i ./locale/messages.pot --previous --ignore-obsolete</tt>
Run this command for each locale by replacing es_ES in the command. Locale names are the directory names in ./locale.
1. Add new languages
Run this command for each new language to add. You will need to replace es_ES in the command with the locale code to add:
<tt>pybabel init -l es_ES -d ./locale -i ./locale/messages.pot</tt>
Add the locale to the locales array in [config.py](https://github.com/coto/gae-boilerplate/blob/master/boilerplate/config.py). Instructions on how to pick a locale code are provided in the comments above the array.
1. Provide translations for each language
In each locale/<locale code>/LC_MESSAGES directory there is a file messages.po. Users translate the strings in these files.
msgid is the text in English. msgstr is the translation to the language indicated by the locale code. For example:
+ `msgid "Change your password"`
+ `msgstr "Cambiar tu contraseña"`
1. Compile translations
Run: <tt>pybabel compile -f -d ./locale</tt>
See [webapp2's tutorial](http://webapp-improved.appspot.com/tutorials/i18n.html) and [pybabel's docs](http://babel.edgewall.org/wiki/Documentation/cmdline.html) for more details.
**Disabling i18n**
i18n can be disabled and language options hidden. Set locales in config.py to None or empty array [] to do this. This may be useful to provide a performance boost or simplify sites that serve a market with only one language.
The locale directory can be safely removed to save space if not needed but the babel and pytz directories cannot be removed without breaking code (imports and trans statements) at this time.
Security
--------
**SSL**
+ SSL is enabled site wide by adding <tt>secure: always</tt> to the section: <tt>- url: /.*</tt> in app.yaml (remove this line to disable)
+ SSL either requires a free google app engine *.appspot.com domain or a [custom domain and certificate](https://developers.google.com/appengine/docs/ssl)
+ Alternatively SSL can be enabled at a controller level via webapp2 schemes. Use the secure_scheme provided in routes.py
+ It is recommended to enable ssl site wide to help prevent [session hijacking](http://en.wikipedia.org/wiki/Session_hijacking)
**Passwords**
+ passwords encrypted with SHA512 and PyCrypto
**CSRF**
+ [Cross-site request forgery](http://en.wikipedia.org/wiki/Cross-site_request_forgery) protection
Acknowledgements
----------------
Google App Engine Boilerplate is a collaborative project created by [coto](https://github.com/coto) which is bringing to you thanks to the help of
these [amazing people](https://github.com/coto/gae-boilerplate/graphs/contributors?type=a)
**Top 10: Primary contributors:**
+ [Tmeryu](https://github.com/tmeryu)
+ [Peta15](https://github.com/peta15)
+ [Sergue1](https://github.com/sergue1)
+ [Sabirmostofa](https://github.com/sabirmostofa)
+ [Pmanacas](https://github.com/pmanacas)
+ [copycat91](https://github.com/copycat91)
+ [Mooose](https://github.com/mooose)
+ [f1shear](https://github.com/f1shear)
+ [presveva](https://github.com/presveva)
+ [Sorced-Jim](https://github.com/sorced-Jim)
=======
AirShare
========
>>>>>>> 324d9b920d13bacc77ae67e6a570305d63c63b8a
| {
"content_hash": "8068c54fa061c520e52095db9439b6b2",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 748,
"avg_line_length": 69.71875,
"alnum_prop": 0.7503361721201255,
"repo_name": "eugenewong/AirShare",
"id": "42f390b77160aaddcff5a48327169158a65b9361",
"size": "13388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10464"
},
{
"name": "JavaScript",
"bytes": "36265"
},
{
"name": "Perl",
"bytes": "71598"
},
{
"name": "Python",
"bytes": "1587268"
},
{
"name": "Shell",
"bytes": "26"
}
],
"symlink_target": ""
} |
// Copyright 2014 The Cockroach Authors.
//
// 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. See the AUTHORS file
// for names of contributors.
//
// Author: Spencer Kimball (spencer.kimball@gmail.com)
package storage
import (
"container/heap"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/proto"
"github.com/cockroachdb/cockroach/util/hlc"
"github.com/cockroachdb/cockroach/util/log"
"github.com/cockroachdb/cockroach/util/stop"
)
// A replicaItem holds a replica and its priority for use with a priority queue.
type replicaItem struct {
value *Replica
priority float64
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A priorityQueue implements heap.Interface and holds replicaItems.
type priorityQueue []*replicaItem
func (pq priorityQueue) Len() int { return len(pq) }
func (pq priorityQueue) Less(i, j int) bool {
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
return pq[i].priority > pq[j].priority
}
func (pq priorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index, pq[j].index = i, j
}
func (pq *priorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*replicaItem)
item.index = n
*pq = append(*pq, item)
}
func (pq *priorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
// update modifies the priority of a replicaItem in the queue.
func (pq *priorityQueue) update(item *replicaItem, priority float64) {
item.priority = priority
heap.Fix(pq, item.index)
}
var (
errQueueDisabled = errors.New("queue disabled")
errReplicaNotAddable = errors.New("replica shouldn't be added to queue")
)
type queueImpl interface {
// needsLeaderLease returns whether this queue requires the leader
// lease to operate on a replica.
needsLeaderLease() bool
// shouldQueue accepts current time and a replica and returns whether
// it should be queued and if so, at what priority.
shouldQueue(proto.Timestamp, *Replica) (shouldQueue bool, priority float64)
// process accepts current time and a replica and executes
// queue-specific work on it.
process(proto.Timestamp, *Replica) error
// timer returns a duration to wait between processing the next item
// from the queue.
timer() time.Duration
}
// baseQueue is the base implementation of the replicaQueue interface.
// Queue implementations should embed a baseQueue and implement queueImpl.
//
// baseQueue is not thread safe and is intended for usage only from
// the scanner's goroutine.
type baseQueue struct {
name string
impl queueImpl
maxSize int // Maximum number of replicas to queue
incoming chan struct{} // Channel signaled when a new replica is added to the queue.
sync.Mutex // Mutex protects priorityQ and replicas
priorityQ priorityQueue // The priority queue
replicas map[proto.RangeID]*replicaItem // Map from RangeID to replicaItem (for updating priority)
// Some tests in this package disable queues.
disabled int32 // updated atomically
}
// newBaseQueue returns a new instance of baseQueue with the
// specified shouldQueue function to determine which replicas to queue
// and maxSize to limit the growth of the queue. Note that
// maxSize doesn't prevent new replicas from being added, it just
// limits the total size. Higher priority replicas can still be
// added; their addition simply removes the lowest priority replica.
func newBaseQueue(name string, impl queueImpl, maxSize int) *baseQueue {
return &baseQueue{
name: name,
impl: impl,
maxSize: maxSize,
incoming: make(chan struct{}, 1),
replicas: map[proto.RangeID]*replicaItem{},
}
}
// Length returns the current size of the queue.
func (bq *baseQueue) Length() int {
bq.Lock()
defer bq.Unlock()
return bq.priorityQ.Len()
}
// SetDisabled turns queue processing off or on as directed.
func (bq *baseQueue) SetDisabled(disabled bool) {
if disabled {
atomic.StoreInt32(&bq.disabled, 1)
} else {
atomic.StoreInt32(&bq.disabled, 0)
}
}
// Start launches a goroutine to process entries in the queue. The
// provided stopper is used to finish processing.
func (bq *baseQueue) Start(clock *hlc.Clock, stopper *stop.Stopper) {
bq.processLoop(clock, stopper)
}
// Add adds the specified replica to the queue, regardless of the return
// value of bq.shouldQueue. The replica is added with specified
// priority. If the queue is too full, the replica may not be added, as
// the replica with the lowest priority will be dropped. Returns an
// error if the replica was not added.
func (bq *baseQueue) Add(repl *Replica, priority float64) error {
bq.Lock()
defer bq.Unlock()
return bq.addInternal(repl, true, priority)
}
// MaybeAdd adds the specified replica if bq.shouldQueue specifies it
// should be queued. Replicas are added to the queue using the priority
// returned by bq.shouldQueue. If the queue is too full, the replica may
// not be added, as the replica with the lowest priority will be
// dropped.
func (bq *baseQueue) MaybeAdd(repl *Replica, now proto.Timestamp) {
bq.Lock()
defer bq.Unlock()
should, priority := bq.impl.shouldQueue(now, repl)
if err := bq.addInternal(repl, should, priority); err != nil && log.V(3) {
log.Infof("couldn't add %s to queue %s: %s", repl, bq.name, err)
}
}
// addInternal adds the replica the queue with specified priority. If the
// replica is already queued, updates the existing priority. Expects the
// queue lock is held by caller. Returns an error if the replica was not
// added.
func (bq *baseQueue) addInternal(repl *Replica, should bool, priority float64) error {
if atomic.LoadInt32(&bq.disabled) == 1 {
return errQueueDisabled
}
rangeID := repl.Desc().RangeID
item, ok := bq.replicas[rangeID]
if !should {
if ok {
bq.remove(item.index)
}
return errReplicaNotAddable
} else if ok {
// Replica has already been added; update priority.
bq.priorityQ.update(item, priority)
return nil
}
if log.V(3) {
log.Infof("adding replica %s to %s queue", repl, bq.name)
}
item = &replicaItem{value: repl, priority: priority}
heap.Push(&bq.priorityQ, item)
bq.replicas[rangeID] = item
// If adding this replica has pushed the queue past its maximum size,
// remove the lowest priority element.
if pqLen := bq.priorityQ.Len(); pqLen > bq.maxSize {
bq.remove(pqLen - 1)
}
// Signal the processLoop that a replica has been added.
select {
case bq.incoming <- struct{}{}:
default:
// No need to signal again.
}
return nil
}
// MaybeRemove removes the specified replica from the queue if enqueued.
func (bq *baseQueue) MaybeRemove(repl *Replica) {
bq.Lock()
defer bq.Unlock()
if item, ok := bq.replicas[repl.Desc().RangeID]; ok {
if log.V(3) {
log.Infof("removing replica %s from %s queue", item.value, bq.name)
}
bq.remove(item.index)
}
}
// processLoop processes the entries in the queue until the provided
// stopper signals exit.
//
// TODO(spencer): current load should factor into replica processing timer.
func (bq *baseQueue) processLoop(clock *hlc.Clock, stopper *stop.Stopper) {
stopper.RunWorker(func() {
// nextTime is initially nil; we don't start any timers until the queue
// becomes non-empty.
var nextTime <-chan time.Time
immediately := make(chan time.Time)
close(immediately)
for {
select {
// Incoming signal sets the next time to process if there were previously
// no replicas in the queue.
case <-bq.incoming:
if nextTime == nil {
// When a replica is added, wake up immediately. This is mainly
// to facilitate testing without unnecessary sleeps.
nextTime = immediately
// In case we're in a test, still block on the impl.
bq.impl.timer()
}
// Process replicas as the timer expires.
case <-nextTime:
stopper.RunTask(func() {
bq.processOne(clock)
})
if bq.Length() == 0 {
nextTime = nil
} else {
nextTime = time.After(bq.impl.timer())
}
// Exit on stopper.
case <-stopper.ShouldStop():
bq.Lock()
bq.replicas = map[proto.RangeID]*replicaItem{}
bq.priorityQ = nil
bq.Unlock()
return
}
}
})
}
func (bq *baseQueue) processOne(clock *hlc.Clock) {
start := time.Now()
bq.Lock()
repl := bq.pop()
bq.Unlock()
if repl != nil {
now := clock.Now()
if log.V(3) {
log.Infof("processing replica %s from %s queue...", repl, bq.name)
}
// If the queue requires a replica to have the range leader lease in
// order to be processed, check whether this replica has leader lease
// and renew or acquire if necessary.
if bq.impl.needsLeaderLease() {
// Create a "fake" get request in order to invoke redirectOnOrAcquireLease.
args := &proto.GetRequest{RequestHeader: proto.RequestHeader{Timestamp: now}}
if err := repl.redirectOnOrAcquireLeaderLease(nil /* Trace */, args.Header().Timestamp); err != nil {
if log.V(3) {
log.Infof("this replica of %s could not acquire leader lease; skipping...", repl)
}
return
}
}
if err := bq.impl.process(now, repl); err != nil {
log.Errorf("failure processing replica %s from %s queue: %s", repl, bq.name, err)
} else if log.V(2) {
log.Infof("processed replica %s from %s queue in %s", repl, bq.name, time.Now().Sub(start))
}
}
}
// pop dequeues the highest priority replica in the queue. Returns the
// replica if not empty; otherwise, returns nil. Expects mutex to be
// locked.
func (bq *baseQueue) pop() *Replica {
if bq.priorityQ.Len() == 0 {
return nil
}
item := heap.Pop(&bq.priorityQ).(*replicaItem)
delete(bq.replicas, item.value.Desc().RangeID)
return item.value
}
// remove removes an element from the priority queue by index. Expects
// mutex to be locked.
func (bq *baseQueue) remove(index int) {
item := heap.Remove(&bq.priorityQ, index).(*replicaItem)
delete(bq.replicas, item.value.Desc().RangeID)
}
| {
"content_hash": "f0b3489db002eb5af885bf69bba234b2",
"timestamp": "",
"source": "github",
"line_count": 335,
"max_line_length": 104,
"avg_line_length": 31.594029850746267,
"alnum_prop": 0.7012471655328798,
"repo_name": "yosiat/cockroach",
"id": "405c4a5f476e95c57294b45d7b610bacb6113523",
"size": "10584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "storage/queue.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "355"
},
{
"name": "C",
"bytes": "6708"
},
{
"name": "C++",
"bytes": "43404"
},
{
"name": "CSS",
"bytes": "9768"
},
{
"name": "Go",
"bytes": "3256357"
},
{
"name": "HTML",
"bytes": "2843"
},
{
"name": "Makefile",
"bytes": "12829"
},
{
"name": "Protocol Buffer",
"bytes": "104443"
},
{
"name": "Shell",
"bytes": "19975"
},
{
"name": "TypeScript",
"bytes": "102079"
},
{
"name": "Yacc",
"bytes": "86820"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ro">
<head>
<!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:26 EEST 2014 -->
<title>Uses of Class net.sf.jasperreports.swing.JRViewerEvent (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class net.sf.jasperreports.swing.JRViewerEvent (JasperReports 5.6.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?net/sf/jasperreports/swing/class-use/JRViewerEvent.html" target="_top">Frames</a></li>
<li><a href="JRViewerEvent.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class net.sf.jasperreports.swing.JRViewerEvent" class="title">Uses of Class<br>net.sf.jasperreports.swing.JRViewerEvent</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">JRViewerEvent</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#net.sf.jasperreports.swing">net.sf.jasperreports.swing</a></td>
<td class="colLast">
<div class="block">Provides support for JasperReports viewer feature.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="net.sf.jasperreports.swing">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">JRViewerEvent</a> in <a href="../../../../../net/sf/jasperreports/swing/package-summary.html">net.sf.jasperreports.swing</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../net/sf/jasperreports/swing/package-summary.html">net.sf.jasperreports.swing</a> with parameters of type <a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">JRViewerEvent</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">JRViewerToolbar.</span><code><strong><a href="../../../../../net/sf/jasperreports/swing/JRViewerToolbar.html#viewerEvent(net.sf.jasperreports.swing.JRViewerEvent)">viewerEvent</a></strong>(<a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">JRViewerEvent</a> event)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">JRViewerPanel.</span><code><strong><a href="../../../../../net/sf/jasperreports/swing/JRViewerPanel.html#viewerEvent(net.sf.jasperreports.swing.JRViewerEvent)">viewerEvent</a></strong>(<a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">JRViewerEvent</a> event)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">JRViewer.</span><code><strong><a href="../../../../../net/sf/jasperreports/swing/JRViewer.html#viewerEvent(net.sf.jasperreports.swing.JRViewerEvent)">viewerEvent</a></strong>(<a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">JRViewerEvent</a> event)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">JRViewerListener.</span><code><strong><a href="../../../../../net/sf/jasperreports/swing/JRViewerListener.html#viewerEvent(net.sf.jasperreports.swing.JRViewerEvent)">viewerEvent</a></strong>(<a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">JRViewerEvent</a> event)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../net/sf/jasperreports/swing/JRViewerEvent.html" title="class in net.sf.jasperreports.swing">Class</a></li>
<li class="navBarCell1Rev">Use</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>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?net/sf/jasperreports/swing/class-use/JRViewerEvent.html" target="_top">Frames</a></li>
<li><a href="JRViewerEvent.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">© 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span>
</small></p>
</body>
</html>
| {
"content_hash": "e8ddb4f3d9481e0486690362d8328dab",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 394,
"avg_line_length": 46.333333333333336,
"alnum_prop": 0.6555445298933267,
"repo_name": "phurtado1112/cnaemvc",
"id": "1b2b78b87c7da7ac810dc24926284b02246989f3",
"size": "8062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/JasperReport__5.6/docs/api/net/sf/jasperreports/swing/class-use/JRViewerEvent.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "HTML",
"bytes": "112926414"
},
{
"name": "Java",
"bytes": "532942"
}
],
"symlink_target": ""
} |
#import "NGMutateDocument.h"
@implementation NGMutateDocument
- (id) init {
if (self = [super init]) {
_documentOperations = [[NSMutableArray alloc] init];
}
return self;
}
+ (NGMutateDocument *) mutateDocument:(NSArray *)documentOperations {
NGMutateDocument *mutateDocumentInstance = [[[NGMutateDocument alloc] init] autorelease];
for (id <NGDocOpComponent> thisOperation in documentOperations) {
[mutateDocumentInstance addOperation:thisOperation];
}
return mutateDocumentInstance;
}
-(void) addOperation:(id <NGDocOpComponent>)operation {
[_documentOperations addObject:operation];
}
- (NSArray *) documentOperations {
return _documentOperations;
}
- (void) dealloc {
[_documentOperations release];
[super dealloc];
}
@end
| {
"content_hash": "cad4f0e36345a94639d2fbcb88e16bda",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 90,
"avg_line_length": 21.457142857142856,
"alnum_prop": 0.748335552596538,
"repo_name": "lqi/ng-project",
"id": "3e6e4eb3950367cfc4f89b40b4e8bde0d8841918",
"size": "1352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/model/document/operation/NGMutateDocument.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "651722"
},
{
"name": "Protocol Buffer",
"bytes": "24488"
},
{
"name": "Shell",
"bytes": "252"
}
],
"symlink_target": ""
} |
This is a sample [PlayN](http://code.google.com/p/playn/) Maven project. Created with Maven archetype.
##Running the sample game##
You need [Maven 3](http://maven.apache.org/) installed:
mvn install
Screenshot:

##Creating Ecplise project files##
mvn eclipse:eclipse -DdownloadJavadocs=true -DdownloadSources=true
| {
"content_hash": "3987c4e1247412d2af3128d49316a639",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 102,
"avg_line_length": 22.4375,
"alnum_prop": 0.7409470752089137,
"repo_name": "janih/playn_project",
"id": "6c53931868de7e7fc19c26015e7469a1b6f87ebf",
"size": "382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "723"
},
{
"name": "Java",
"bytes": "3912"
}
],
"symlink_target": ""
} |
using namespace std;
using namespace Concurrency;
#define MAX_FILE_SIZE 10048576
#define FILE_DRIVE L"C:\\\\temp\\"
#define FILE_PATH L"PriorityTestFile.txt"
volatile bool bEnd = false;
void Write(HANDLE hFile, wchar_t marker);
wstring GetFileName(wchar_t marker)
{
wstring fileName(FILE_DRIVE);
fileName += marker;
fileName += FILE_PATH;
return fileName;
}
HANDLE CreateShareWriteFileHandle(wchar_t marker)
{
wstring fileName = GetFileName(marker);
HANDLE hFile = CreateFile(fileName.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, nullptr);
if (hFile == INVALID_HANDLE_VALUE)
{
wcerr << L"Error opening file: " << hex << GetLastError() << endl;
ExitProcess(-1);
}
return hFile;
}
void ThreadBackgroundModePriority(HANDLE hReadyToWrite, HANDLE hStartWrite)
{
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
HANDLE hFile = CreateShareWriteFileHandle(L'B');
SetEvent(hReadyToWrite);
WaitForSingleObject(hStartWrite, INFINITE);
Write(hFile, L'B');
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
CloseHandle(hFile);
}
void ThreadNormalPriority(HANDLE hReadyToWrite, HANDLE hStartWrite)
{
HANDLE hFile = CreateShareWriteFileHandle(L'N');
SetEvent(hReadyToWrite);
WaitForSingleObject(hStartWrite, INFINITE);
Write(hFile, L'N');
CloseHandle(hFile);
}
void HandleVeryLowPriotiry(HANDLE hReadyToWrite, HANDLE hStartWrite)
{
HANDLE hFile = CreateShareWriteFileHandle(L'L');
__declspec(align(8)) FILE_IO_PRIORITY_HINT_INFO priorityInfo;
priorityInfo.PriorityHint = IoPriorityHintVeryLow;
BOOL result = SetFileInformationByHandle(hFile, FileIoPriorityHintInfo, &priorityInfo, sizeof(FILE_IO_PRIORITY_HINT_INFO));
if (!result)
{
wcerr << L"Error setting priority hint: " << hex << GetLastError() << endl;
ExitProcess(-1);
}
SetEvent(hReadyToWrite);
WaitForSingleObject(hStartWrite, INFINITE);
Write(hFile, L'L');
CloseHandle(hFile);
}
void Write(HANDLE hFile, wchar_t marker)
{
DWORD nWritten;
while (true)
{
BOOL result = WriteFile(hFile, &marker, sizeof(marker), &nWritten, nullptr);
if (!result)
{
wcerr << L"Error writing to the file: " << hex << GetLastError() << endl;
ExitProcess(-1);
}
LARGE_INTEGER fileSize;
GetFileSizeEx(hFile, &fileSize);
if (fileSize.QuadPart >= MAX_FILE_SIZE || bEnd)
return;
}
}
void StartProgress(HANDLE hReadyToWrite[3], HANDLE hStartWrite)
{
WaitForMultipleObjects(3, hReadyToWrite, TRUE, INFINITE);
HANDLE hBFile = CreateShareWriteFileHandle(L'B');
HANDLE hNFile = CreateShareWriteFileHandle(L'N');
HANDLE hLFile = CreateShareWriteFileHandle(L'L');
LARGE_INTEGER fileSize;
//Start the write process
SetEvent(hStartWrite);
long long totalSize = 0;
do
{
GetFileSizeEx(hBFile, &fileSize);
totalSize += fileSize.QuadPart;
GetFileSizeEx(hNFile, &fileSize);
totalSize += fileSize.QuadPart;
GetFileSizeEx(hLFile, &fileSize);
totalSize += fileSize.QuadPart;
wcout << L"File size: " << totalSize << endl;
Sleep(1000);
} while (totalSize < MAX_FILE_SIZE);
bEnd = true;
}
HANDLE CreateManualResetEvent()
{
HANDLE hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
if (hEvent == nullptr)
{
wcerr << L"Error creating Win32 ManualResetEvent: " << hex << GetLastError() << endl;
ExitProcess(-1);
}
return hEvent;
}
int main()
{
DeleteFile(GetFileName(L'L').c_str());
DeleteFile(GetFileName(L'B').c_str());
DeleteFile(GetFileName(L'N').c_str());
HANDLE hStartWrite = CreateManualResetEvent();
HANDLE hBackgroundModeReadyToWrite = CreateManualResetEvent();
HANDLE hNormalPriorityReadyToWrite = CreateManualResetEvent();
HANDLE hVeryLowPriotiryReadyToWrite = CreateManualResetEvent();
HANDLE readyToWrite[] = { hBackgroundModeReadyToWrite, hNormalPriorityReadyToWrite, hVeryLowPriotiryReadyToWrite };
parallel_invoke(
[&]() { StartProgress(readyToWrite, hStartWrite); },
[&]() { ThreadBackgroundModePriority(hBackgroundModeReadyToWrite, hStartWrite); },
[&]() { ThreadNormalPriority(hNormalPriorityReadyToWrite, hStartWrite); },
[&]() { HandleVeryLowPriotiry(hVeryLowPriotiryReadyToWrite, hStartWrite); });
HANDLE hBFile = CreateShareWriteFileHandle(L'B');
HANDLE hNFile = CreateShareWriteFileHandle(L'N');
HANDLE hLFile = CreateShareWriteFileHandle(L'L');
LARGE_INTEGER fileSize;
GetFileSizeEx(hLFile, &fileSize);
wcout << L"Low File Size: " << fileSize.QuadPart << endl;
GetFileSizeEx(hBFile, &fileSize);
wcout << L"Background File Size: " << fileSize.QuadPart << endl;
GetFileSizeEx(hNFile, &fileSize);
wcout << L"Normal File Size: " << fileSize.QuadPart << endl;
CloseHandle(hBFile);
CloseHandle(hNFile);
CloseHandle(hLFile);
return 0;
}
| {
"content_hash": "e4db5fb7b36fe3d363e8387b68edb8e5",
"timestamp": "",
"source": "github",
"line_count": 180,
"max_line_length": 124,
"avg_line_length": 26.483333333333334,
"alnum_prop": 0.73778057478498,
"repo_name": "alonf/Windows-Internals-Course-Materials",
"id": "4106f6a3c934eb63b828c7d1d25ed313e6c7f90e",
"size": "4945",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WindowsInternals/IoPriority/IoPriority.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7332"
},
{
"name": "C++",
"bytes": "20775"
}
],
"symlink_target": ""
} |
package org.apache.beam.sdk.io.gcp.bigquery;
import com.google.api.services.bigquery.model.TableReference;
import com.google.api.services.bigquery.model.TimePartitioning;
import java.io.Serializable;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* Encapsulates a BigQuery table destination.
*/
public class TableDestination implements Serializable {
private static final long serialVersionUID = 1L;
private final String tableSpec;
@Nullable
private final String tableDescription;
@Nullable
private final String jsonTimePartitioning;
public TableDestination(String tableSpec, @Nullable String tableDescription) {
this(tableSpec, tableDescription, (String) null);
}
public TableDestination(TableReference tableReference, @Nullable String tableDescription) {
this(tableReference, tableDescription, (String) null);
}
public TableDestination(TableReference tableReference, @Nullable String tableDescription,
TimePartitioning timePartitioning) {
this(BigQueryHelpers.toTableSpec(tableReference), tableDescription,
timePartitioning != null ? BigQueryHelpers.toJsonString(timePartitioning) : null);
}
public TableDestination(String tableSpec, @Nullable String tableDescription,
TimePartitioning timePartitioning) {
this(tableSpec, tableDescription,
timePartitioning != null ? BigQueryHelpers.toJsonString(timePartitioning) : null);
}
public TableDestination(TableReference tableReference, @Nullable String tableDescription,
@Nullable String jsonTimePartitioning) {
this(BigQueryHelpers.toTableSpec(tableReference), tableDescription, jsonTimePartitioning);
}
public TableDestination(String tableSpec, @Nullable String tableDescription,
@Nullable String jsonTimePartitioning) {
this.tableSpec = tableSpec;
this.tableDescription = tableDescription;
this.jsonTimePartitioning = jsonTimePartitioning;
}
public TableDestination withTableReference(TableReference tableReference) {
return new TableDestination(tableReference, tableDescription, jsonTimePartitioning);
}
public String getTableSpec() {
return tableSpec;
}
public TableReference getTableReference() {
return BigQueryHelpers.parseTableSpec(tableSpec);
}
public String getJsonTimePartitioning() {
return jsonTimePartitioning;
}
public TimePartitioning getTimePartitioning() {
if (jsonTimePartitioning == null) {
return null;
} else {
return BigQueryHelpers.fromJsonString(jsonTimePartitioning, TimePartitioning.class);
}
}
@Nullable
public String getTableDescription() {
return tableDescription;
}
@Override
public String toString() {
String toString = "tableSpec: " + tableSpec;
if (tableDescription != null) {
toString += " tableDescription: " + tableDescription;
}
return toString;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof TableDestination)) {
return false;
}
TableDestination other = (TableDestination) o;
return Objects.equals(this.tableSpec, other.tableSpec)
&& Objects.equals(this.tableDescription, other.tableDescription)
&& Objects.equals(this.jsonTimePartitioning, other.jsonTimePartitioning);
}
@Override
public int hashCode() {
return Objects.hash(tableSpec, tableDescription, jsonTimePartitioning);
}
}
| {
"content_hash": "d40dc2a66deaa14088bd943063e6706b",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 94,
"avg_line_length": 31.34259259259259,
"alnum_prop": 0.7559822747415067,
"repo_name": "tgroh/beam",
"id": "c499a414f774757c4761cf186e3d4c581cac6e8f",
"size": "4174",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sdks/java/io/google-cloud-platform/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/TableDestination.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "5994"
},
{
"name": "Go",
"bytes": "2167258"
},
{
"name": "Groovy",
"bytes": "127719"
},
{
"name": "Java",
"bytes": "17206671"
},
{
"name": "Python",
"bytes": "3584300"
},
{
"name": "Shell",
"bytes": "82600"
}
],
"symlink_target": ""
} |
from twisted.application import service
from .dns import DNSService
from .restapi import webservice
class OrchestrationService(service.MultiService):
""" Handles starting and stopping. """
def __init__(self, conf):
service.MultiService.__init__(self)
self.conf = conf
self.dnsserver = DNSService(conf)
self.dnsserver.setServiceParent(self)
self.webserver = webservice(conf, self.dnsserver)
self.webserver.setServiceParent(self)
| {
"content_hash": "0e962479c48953de5e5fd50712089e6d",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 57,
"avg_line_length": 28.764705882352942,
"alnum_prop": 0.6993865030674846,
"repo_name": "yaybu/callsign",
"id": "3e0d806678bcfe6c8bf8d73fbd2e18ae20a1243a",
"size": "490",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "callsign/orchestra.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "45540"
}
],
"symlink_target": ""
} |
$stdout.sync = true
Lagotto::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# config.assets.prefix = "/dev-assets"
# Compress JavaScripts and CSS
config.assets.js_compressor = :uglifier
# See everything in the log (default is :info)
config.log_level = :debug
# Expands the lines which load the assets
config.assets.debug = true
config.assets.raise_runtime_errors = true
config.active_record.raise_in_transactional_callbacks = true
# for devise
config.action_mailer.default_url_options = { :host => "#{ENV['MAIL_ADDRESS']}:#{ENV['MAIL_PORT']}" }
end
BetterErrors::Middleware.allow_ip! ENV['TRUSTED_IP'] if ENV['TRUSTED_IP']
| {
"content_hash": "61499cba2a95e61c7916b5ce6afa6e01",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 102,
"avg_line_length": 32.90243902439025,
"alnum_prop": 0.7383246849518161,
"repo_name": "articlemetrics/lagotto",
"id": "d5cddc6b15618b1533a7bd9a7441c8e0a50cfdf8",
"size": "1349",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "config/environments/development.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "48156"
},
{
"name": "HTML",
"bytes": "120687"
},
{
"name": "JavaScript",
"bytes": "106205"
},
{
"name": "Ruby",
"bytes": "1270419"
}
],
"symlink_target": ""
} |
package cz.metacentrum.perun.wui.registrar.client.resources;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
/**
* Resources for PerunRegistrar WUI app.
*
* @author Ondřej Velíšek
* @author Pavel Zlámal <zlamal@cesnet.cz>
*/
public interface PerunRegistrarResources extends ClientBundle {
PerunRegistrarResources INSTANCE = GWT.create(PerunRegistrarResources.class);
interface PerunRegistrarCss extends CssResource {
String pageWrapper();
String grid();
String status();
String preview();
String checkbox(); // External
//String footer();
String navbarWrapper();
String logoWrapper();
String navbarFix();
}
@Source("css/PerunRegistrar.gss")
PerunRegistrarCss gss();
}
| {
"content_hash": "5126821c6a42d14d8c4669b38ac10adc",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 78,
"avg_line_length": 19.682926829268293,
"alnum_prop": 0.7509293680297398,
"repo_name": "ondrejvelisek/perun-wui",
"id": "cb64bda70161e69bef1042903d1fd043b592f140",
"size": "811",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "perun-wui-registrar/src/main/java/cz/metacentrum/perun/wui/registrar/client/resources/PerunRegistrarResources.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "546828"
},
{
"name": "Java",
"bytes": "1083005"
}
],
"symlink_target": ""
} |
import expect from 'expect';
import ngReduxProvider from '../../src/components/ngRedux';
import { createStore, combineReducers } from 'redux';
describe('ngRedux provide store functionality', () => {
let ngRedux = {};
let $injector = {};
let $rootScope = {
$evalAsync: () => {},
$on: () => {}
}
beforeEach(() => {
ngRedux = new ngReduxProvider();
$injector = {
get: () => {
return $rootScope;
},
};
});
it('should dispatch both ways', () => {
const providedStore = createStore((state, action) => action.payload || state, 'initial state');
ngRedux.provideStore(providedStore);
const ngredux = ngRedux['$get']($injector);
expect(ngredux.getState()).toEqual('initial state');
providedStore.dispatch({ type: 'TEST', payload: 'new state through provider' });
expect(providedStore.getState()).toEqual('new state through provider');
expect(ngredux.getState()).toEqual('new state through provider');
ngredux.dispatch({
type: 'TEST',
payload: 'new state through ngredux'
});
expect(providedStore.getState()).toEqual('new state through ngredux');
expect(ngredux.getState()).toEqual('new state through ngredux');
});
it('should work with combineReducers', () => {
const initialFooState = 'foo state';
const initialBarState = 'bar state';
const combinedReducers = combineReducers({
fooState: (state = initialFooState, action) => action.payload || state,
barState: (state = initialBarState, action) => action.payload || state,
})
const providedStore = createStore(combinedReducers);
ngRedux.provideStore(providedStore);
const ngredux = ngRedux['$get']($injector);
expect(ngredux.getState()).toEqual({
fooState: 'foo state',
barState: 'bar state'
});
providedStore.dispatch({ type: 'TEST', payload: 'new state through provider' });
expect(providedStore.getState()).toEqual({
fooState: 'new state through provider',
barState: 'new state through provider'
});
expect(ngredux.getState()).toEqual({
fooState: 'new state through provider',
barState: 'new state through provider'
});
ngredux.dispatch({
type: 'TEST',
payload: 'new state through ngredux'
});
expect(providedStore.getState()).toEqual({
fooState: 'new state through ngredux',
barState: 'new state through ngredux'
});
expect(ngredux.getState()).toEqual({
fooState: 'new state through ngredux',
barState: 'new state through ngredux'
});
});
});
| {
"content_hash": "78821d17011e3b857f4451180bc3ba98",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 99,
"avg_line_length": 28.744444444444444,
"alnum_prop": 0.636644762272903,
"repo_name": "angular-redux/ng-redux",
"id": "9710e0896c763f10eb1be235476667ba975655b0",
"size": "2587",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/integration/ngReduxProvidedStore.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "22419"
}
],
"symlink_target": ""
} |
/**
*/
package com.specmate.migration.test.changedtypes.testmodel.artefact.impl;
import com.specmate.migration.test.changedtypes.testmodel.artefact.ArtefactPackage;
import com.specmate.migration.test.changedtypes.testmodel.artefact.Sketch;
import com.specmate.migration.test.changedtypes.testmodel.base.BasePackage;
import com.specmate.migration.test.changedtypes.testmodel.base.IContainer;
import com.specmate.migration.test.changedtypes.testmodel.base.IContentElement;
import com.specmate.migration.test.changedtypes.testmodel.base.IID;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Sketch</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isTested <em>Tested</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getId <em>Id</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getContents <em>Contents</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getByteVar1 <em>Byte Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getByteVar2 <em>Byte Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getByteVar3 <em>Byte Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getByteVar4 <em>Byte Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getByteVar5 <em>Byte Var5</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getShortVar1 <em>Short Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getShortVar2 <em>Short Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getShortVar3 <em>Short Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getShortVar4 <em>Short Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getShortVar5 <em>Short Var5</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getIntVar1 <em>Int Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getIntVar2 <em>Int Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getIntVar3 <em>Int Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getIntVar4 <em>Int Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getIntVar5 <em>Int Var5</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getCharVar1 <em>Char Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getCharVar2 <em>Char Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getCharVar3 <em>Char Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getCharVar4 <em>Char Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getCharVar5 <em>Char Var5</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getLongVar1 <em>Long Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getLongVar2 <em>Long Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getLongVar3 <em>Long Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getLongVar4 <em>Long Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getLongVar5 <em>Long Var5</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getFloatVar1 <em>Float Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getFloatVar2 <em>Float Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getFloatVar3 <em>Float Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getFloatVar4 <em>Float Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getFloatVar5 <em>Float Var5</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getDoubleVar1 <em>Double Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getDoubleVar2 <em>Double Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getDoubleVar3 <em>Double Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getDoubleVar4 <em>Double Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getDoubleVar5 <em>Double Var5</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#getBooleanVar1 <em>Boolean Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isBooleanVar2 <em>Boolean Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isBooleanVar3 <em>Boolean Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isBooleanVar4 <em>Boolean Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isBooleanVar5 <em>Boolean Var5</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isStringVar1 <em>String Var1</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isStringVar2 <em>String Var2</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isStringVar3 <em>String Var3</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isStringVar4 <em>String Var4</em>}</li>
* <li>{@link com.specmate.migration.test.changedtypes.testmodel.artefact.impl.SketchImpl#isStringVar5 <em>String Var5</em>}</li>
* </ul>
*
* @generated
*/
public class SketchImpl extends MinimalEObjectImpl.Container implements Sketch {
/**
* The default value of the '{@link #isTested() <em>Tested</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isTested()
* @generated
* @ordered
*/
protected static final boolean TESTED_EDEFAULT = false;
/**
* The default value of the '{@link #getId() <em>Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getId()
* @generated
* @ordered
*/
protected static final String ID_EDEFAULT = null;
/**
* The default value of the '{@link #getByteVar1() <em>Byte Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getByteVar1()
* @generated
* @ordered
*/
protected static final short BYTE_VAR1_EDEFAULT = 0;
/**
* The default value of the '{@link #getByteVar2() <em>Byte Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getByteVar2()
* @generated
* @ordered
*/
protected static final int BYTE_VAR2_EDEFAULT = 0;
/**
* The default value of the '{@link #getByteVar3() <em>Byte Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getByteVar3()
* @generated
* @ordered
*/
protected static final long BYTE_VAR3_EDEFAULT = 0L;
/**
* The default value of the '{@link #getByteVar4() <em>Byte Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getByteVar4()
* @generated
* @ordered
*/
protected static final float BYTE_VAR4_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getByteVar5() <em>Byte Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getByteVar5()
* @generated
* @ordered
*/
protected static final double BYTE_VAR5_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getShortVar1() <em>Short Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShortVar1()
* @generated
* @ordered
*/
protected static final int SHORT_VAR1_EDEFAULT = 0;
/**
* The default value of the '{@link #getShortVar2() <em>Short Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShortVar2()
* @generated
* @ordered
*/
protected static final long SHORT_VAR2_EDEFAULT = 0L;
/**
* The default value of the '{@link #getShortVar3() <em>Short Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShortVar3()
* @generated
* @ordered
*/
protected static final float SHORT_VAR3_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getShortVar4() <em>Short Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShortVar4()
* @generated
* @ordered
*/
protected static final double SHORT_VAR4_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getShortVar5() <em>Short Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShortVar5()
* @generated
* @ordered
*/
protected static final short SHORT_VAR5_EDEFAULT = 0;
/**
* The default value of the '{@link #getIntVar1() <em>Int Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIntVar1()
* @generated
* @ordered
*/
protected static final long INT_VAR1_EDEFAULT = 0L;
/**
* The default value of the '{@link #getIntVar2() <em>Int Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIntVar2()
* @generated
* @ordered
*/
protected static final float INT_VAR2_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getIntVar3() <em>Int Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIntVar3()
* @generated
* @ordered
*/
protected static final double INT_VAR3_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getIntVar4() <em>Int Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIntVar4()
* @generated
* @ordered
*/
protected static final int INT_VAR4_EDEFAULT = 0;
/**
* The default value of the '{@link #getIntVar5() <em>Int Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getIntVar5()
* @generated
* @ordered
*/
protected static final int INT_VAR5_EDEFAULT = 0;
/**
* The default value of the '{@link #getCharVar1() <em>Char Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCharVar1()
* @generated
* @ordered
*/
protected static final int CHAR_VAR1_EDEFAULT = 0;
/**
* The default value of the '{@link #getCharVar2() <em>Char Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCharVar2()
* @generated
* @ordered
*/
protected static final long CHAR_VAR2_EDEFAULT = 0L;
/**
* The default value of the '{@link #getCharVar3() <em>Char Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCharVar3()
* @generated
* @ordered
*/
protected static final float CHAR_VAR3_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getCharVar4() <em>Char Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCharVar4()
* @generated
* @ordered
*/
protected static final double CHAR_VAR4_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getCharVar5() <em>Char Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCharVar5()
* @generated
* @ordered
*/
protected static final String CHAR_VAR5_EDEFAULT = null;
/**
* The default value of the '{@link #getLongVar1() <em>Long Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLongVar1()
* @generated
* @ordered
*/
protected static final float LONG_VAR1_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getLongVar2() <em>Long Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLongVar2()
* @generated
* @ordered
*/
protected static final double LONG_VAR2_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getLongVar3() <em>Long Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLongVar3()
* @generated
* @ordered
*/
protected static final long LONG_VAR3_EDEFAULT = 0L;
/**
* The default value of the '{@link #getLongVar4() <em>Long Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLongVar4()
* @generated
* @ordered
*/
protected static final long LONG_VAR4_EDEFAULT = 0L;
/**
* The default value of the '{@link #getLongVar5() <em>Long Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLongVar5()
* @generated
* @ordered
*/
protected static final long LONG_VAR5_EDEFAULT = 0L;
/**
* The default value of the '{@link #getFloatVar1() <em>Float Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFloatVar1()
* @generated
* @ordered
*/
protected static final double FLOAT_VAR1_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getFloatVar2() <em>Float Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFloatVar2()
* @generated
* @ordered
*/
protected static final float FLOAT_VAR2_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getFloatVar3() <em>Float Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFloatVar3()
* @generated
* @ordered
*/
protected static final float FLOAT_VAR3_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getFloatVar4() <em>Float Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFloatVar4()
* @generated
* @ordered
*/
protected static final float FLOAT_VAR4_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getFloatVar5() <em>Float Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFloatVar5()
* @generated
* @ordered
*/
protected static final float FLOAT_VAR5_EDEFAULT = 0.0F;
/**
* The default value of the '{@link #getDoubleVar1() <em>Double Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDoubleVar1()
* @generated
* @ordered
*/
protected static final double DOUBLE_VAR1_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getDoubleVar2() <em>Double Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDoubleVar2()
* @generated
* @ordered
*/
protected static final double DOUBLE_VAR2_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getDoubleVar3() <em>Double Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDoubleVar3()
* @generated
* @ordered
*/
protected static final double DOUBLE_VAR3_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getDoubleVar4() <em>Double Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDoubleVar4()
* @generated
* @ordered
*/
protected static final double DOUBLE_VAR4_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getDoubleVar5() <em>Double Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDoubleVar5()
* @generated
* @ordered
*/
protected static final double DOUBLE_VAR5_EDEFAULT = 0.0;
/**
* The default value of the '{@link #getBooleanVar1() <em>Boolean Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBooleanVar1()
* @generated
* @ordered
*/
protected static final String BOOLEAN_VAR1_EDEFAULT = null;
/**
* The default value of the '{@link #isBooleanVar2() <em>Boolean Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isBooleanVar2()
* @generated
* @ordered
*/
protected static final boolean BOOLEAN_VAR2_EDEFAULT = false;
/**
* The default value of the '{@link #isBooleanVar3() <em>Boolean Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isBooleanVar3()
* @generated
* @ordered
*/
protected static final boolean BOOLEAN_VAR3_EDEFAULT = false;
/**
* The default value of the '{@link #isBooleanVar4() <em>Boolean Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isBooleanVar4()
* @generated
* @ordered
*/
protected static final boolean BOOLEAN_VAR4_EDEFAULT = false;
/**
* The default value of the '{@link #isBooleanVar5() <em>Boolean Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isBooleanVar5()
* @generated
* @ordered
*/
protected static final boolean BOOLEAN_VAR5_EDEFAULT = false;
/**
* The default value of the '{@link #isStringVar1() <em>String Var1</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isStringVar1()
* @generated
* @ordered
*/
protected static final boolean STRING_VAR1_EDEFAULT = false;
/**
* The default value of the '{@link #isStringVar2() <em>String Var2</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isStringVar2()
* @generated
* @ordered
*/
protected static final boolean STRING_VAR2_EDEFAULT = false;
/**
* The default value of the '{@link #isStringVar3() <em>String Var3</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isStringVar3()
* @generated
* @ordered
*/
protected static final boolean STRING_VAR3_EDEFAULT = false;
/**
* The default value of the '{@link #isStringVar4() <em>String Var4</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isStringVar4()
* @generated
* @ordered
*/
protected static final boolean STRING_VAR4_EDEFAULT = false;
/**
* The default value of the '{@link #isStringVar5() <em>String Var5</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isStringVar5()
* @generated
* @ordered
*/
protected static final boolean STRING_VAR5_EDEFAULT = false;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SketchImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ArtefactPackage.Literals.SKETCH;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected int eStaticFeatureCount() {
return 0;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isTested() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__TESTED, BasePackage.Literals.ITESTABLE__TESTED, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTested(boolean newTested) {
eDynamicSet(ArtefactPackage.SKETCH__TESTED, BasePackage.Literals.ITESTABLE__TESTED, newTested);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getId() {
return (String)eDynamicGet(ArtefactPackage.SKETCH__ID, BasePackage.Literals.IID__ID, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setId(String newId) {
eDynamicSet(ArtefactPackage.SKETCH__ID, BasePackage.Literals.IID__ID, newId);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
public EList<IContentElement> getContents() {
return (EList<IContentElement>)eDynamicGet(ArtefactPackage.SKETCH__CONTENTS, BasePackage.Literals.ICONTAINER__CONTENTS, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public short getByteVar1() {
return (Short)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR1, ArtefactPackage.Literals.SKETCH__BYTE_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setByteVar1(short newByteVar1) {
eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR1, ArtefactPackage.Literals.SKETCH__BYTE_VAR1, newByteVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getByteVar2() {
return (Integer)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR2, ArtefactPackage.Literals.SKETCH__BYTE_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setByteVar2(int newByteVar2) {
eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR2, ArtefactPackage.Literals.SKETCH__BYTE_VAR2, newByteVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public long getByteVar3() {
return (Long)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR3, ArtefactPackage.Literals.SKETCH__BYTE_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setByteVar3(long newByteVar3) {
eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR3, ArtefactPackage.Literals.SKETCH__BYTE_VAR3, newByteVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getByteVar4() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR4, ArtefactPackage.Literals.SKETCH__BYTE_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setByteVar4(float newByteVar4) {
eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR4, ArtefactPackage.Literals.SKETCH__BYTE_VAR4, newByteVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getByteVar5() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__BYTE_VAR5, ArtefactPackage.Literals.SKETCH__BYTE_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setByteVar5(double newByteVar5) {
eDynamicSet(ArtefactPackage.SKETCH__BYTE_VAR5, ArtefactPackage.Literals.SKETCH__BYTE_VAR5, newByteVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getShortVar1() {
return (Integer)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR1, ArtefactPackage.Literals.SKETCH__SHORT_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setShortVar1(int newShortVar1) {
eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR1, ArtefactPackage.Literals.SKETCH__SHORT_VAR1, newShortVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public long getShortVar2() {
return (Long)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR2, ArtefactPackage.Literals.SKETCH__SHORT_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setShortVar2(long newShortVar2) {
eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR2, ArtefactPackage.Literals.SKETCH__SHORT_VAR2, newShortVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getShortVar3() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR3, ArtefactPackage.Literals.SKETCH__SHORT_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setShortVar3(float newShortVar3) {
eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR3, ArtefactPackage.Literals.SKETCH__SHORT_VAR3, newShortVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getShortVar4() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR4, ArtefactPackage.Literals.SKETCH__SHORT_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setShortVar4(double newShortVar4) {
eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR4, ArtefactPackage.Literals.SKETCH__SHORT_VAR4, newShortVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public short getShortVar5() {
return (Short)eDynamicGet(ArtefactPackage.SKETCH__SHORT_VAR5, ArtefactPackage.Literals.SKETCH__SHORT_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setShortVar5(short newShortVar5) {
eDynamicSet(ArtefactPackage.SKETCH__SHORT_VAR5, ArtefactPackage.Literals.SKETCH__SHORT_VAR5, newShortVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public long getIntVar1() {
return (Long)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR1, ArtefactPackage.Literals.SKETCH__INT_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIntVar1(long newIntVar1) {
eDynamicSet(ArtefactPackage.SKETCH__INT_VAR1, ArtefactPackage.Literals.SKETCH__INT_VAR1, newIntVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getIntVar2() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR2, ArtefactPackage.Literals.SKETCH__INT_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIntVar2(float newIntVar2) {
eDynamicSet(ArtefactPackage.SKETCH__INT_VAR2, ArtefactPackage.Literals.SKETCH__INT_VAR2, newIntVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getIntVar3() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR3, ArtefactPackage.Literals.SKETCH__INT_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIntVar3(double newIntVar3) {
eDynamicSet(ArtefactPackage.SKETCH__INT_VAR3, ArtefactPackage.Literals.SKETCH__INT_VAR3, newIntVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getIntVar4() {
return (Integer)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR4, ArtefactPackage.Literals.SKETCH__INT_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIntVar4(int newIntVar4) {
eDynamicSet(ArtefactPackage.SKETCH__INT_VAR4, ArtefactPackage.Literals.SKETCH__INT_VAR4, newIntVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getIntVar5() {
return (Integer)eDynamicGet(ArtefactPackage.SKETCH__INT_VAR5, ArtefactPackage.Literals.SKETCH__INT_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setIntVar5(int newIntVar5) {
eDynamicSet(ArtefactPackage.SKETCH__INT_VAR5, ArtefactPackage.Literals.SKETCH__INT_VAR5, newIntVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getCharVar1() {
return (Integer)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR1, ArtefactPackage.Literals.SKETCH__CHAR_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCharVar1(int newCharVar1) {
eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR1, ArtefactPackage.Literals.SKETCH__CHAR_VAR1, newCharVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public long getCharVar2() {
return (Long)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR2, ArtefactPackage.Literals.SKETCH__CHAR_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCharVar2(long newCharVar2) {
eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR2, ArtefactPackage.Literals.SKETCH__CHAR_VAR2, newCharVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getCharVar3() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR3, ArtefactPackage.Literals.SKETCH__CHAR_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCharVar3(float newCharVar3) {
eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR3, ArtefactPackage.Literals.SKETCH__CHAR_VAR3, newCharVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getCharVar4() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR4, ArtefactPackage.Literals.SKETCH__CHAR_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCharVar4(double newCharVar4) {
eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR4, ArtefactPackage.Literals.SKETCH__CHAR_VAR4, newCharVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getCharVar5() {
return (String)eDynamicGet(ArtefactPackage.SKETCH__CHAR_VAR5, ArtefactPackage.Literals.SKETCH__CHAR_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCharVar5(String newCharVar5) {
eDynamicSet(ArtefactPackage.SKETCH__CHAR_VAR5, ArtefactPackage.Literals.SKETCH__CHAR_VAR5, newCharVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getLongVar1() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR1, ArtefactPackage.Literals.SKETCH__LONG_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLongVar1(float newLongVar1) {
eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR1, ArtefactPackage.Literals.SKETCH__LONG_VAR1, newLongVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getLongVar2() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR2, ArtefactPackage.Literals.SKETCH__LONG_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLongVar2(double newLongVar2) {
eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR2, ArtefactPackage.Literals.SKETCH__LONG_VAR2, newLongVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public long getLongVar3() {
return (Long)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR3, ArtefactPackage.Literals.SKETCH__LONG_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLongVar3(long newLongVar3) {
eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR3, ArtefactPackage.Literals.SKETCH__LONG_VAR3, newLongVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public long getLongVar4() {
return (Long)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR4, ArtefactPackage.Literals.SKETCH__LONG_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLongVar4(long newLongVar4) {
eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR4, ArtefactPackage.Literals.SKETCH__LONG_VAR4, newLongVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public long getLongVar5() {
return (Long)eDynamicGet(ArtefactPackage.SKETCH__LONG_VAR5, ArtefactPackage.Literals.SKETCH__LONG_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLongVar5(long newLongVar5) {
eDynamicSet(ArtefactPackage.SKETCH__LONG_VAR5, ArtefactPackage.Literals.SKETCH__LONG_VAR5, newLongVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getFloatVar1() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR1, ArtefactPackage.Literals.SKETCH__FLOAT_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFloatVar1(double newFloatVar1) {
eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR1, ArtefactPackage.Literals.SKETCH__FLOAT_VAR1, newFloatVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getFloatVar2() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR2, ArtefactPackage.Literals.SKETCH__FLOAT_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFloatVar2(float newFloatVar2) {
eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR2, ArtefactPackage.Literals.SKETCH__FLOAT_VAR2, newFloatVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getFloatVar3() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR3, ArtefactPackage.Literals.SKETCH__FLOAT_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFloatVar3(float newFloatVar3) {
eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR3, ArtefactPackage.Literals.SKETCH__FLOAT_VAR3, newFloatVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getFloatVar4() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR4, ArtefactPackage.Literals.SKETCH__FLOAT_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFloatVar4(float newFloatVar4) {
eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR4, ArtefactPackage.Literals.SKETCH__FLOAT_VAR4, newFloatVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getFloatVar5() {
return (Float)eDynamicGet(ArtefactPackage.SKETCH__FLOAT_VAR5, ArtefactPackage.Literals.SKETCH__FLOAT_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFloatVar5(float newFloatVar5) {
eDynamicSet(ArtefactPackage.SKETCH__FLOAT_VAR5, ArtefactPackage.Literals.SKETCH__FLOAT_VAR5, newFloatVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getDoubleVar1() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR1, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDoubleVar1(double newDoubleVar1) {
eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR1, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR1, newDoubleVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getDoubleVar2() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR2, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDoubleVar2(double newDoubleVar2) {
eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR2, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR2, newDoubleVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getDoubleVar3() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR3, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDoubleVar3(double newDoubleVar3) {
eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR3, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR3, newDoubleVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getDoubleVar4() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR4, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDoubleVar4(double newDoubleVar4) {
eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR4, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR4, newDoubleVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getDoubleVar5() {
return (Double)eDynamicGet(ArtefactPackage.SKETCH__DOUBLE_VAR5, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDoubleVar5(double newDoubleVar5) {
eDynamicSet(ArtefactPackage.SKETCH__DOUBLE_VAR5, ArtefactPackage.Literals.SKETCH__DOUBLE_VAR5, newDoubleVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getBooleanVar1() {
return (String)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR1, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBooleanVar1(String newBooleanVar1) {
eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR1, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR1, newBooleanVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isBooleanVar2() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR2, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBooleanVar2(boolean newBooleanVar2) {
eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR2, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR2, newBooleanVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isBooleanVar3() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR3, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBooleanVar3(boolean newBooleanVar3) {
eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR3, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR3, newBooleanVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isBooleanVar4() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR4, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBooleanVar4(boolean newBooleanVar4) {
eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR4, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR4, newBooleanVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isBooleanVar5() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__BOOLEAN_VAR5, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBooleanVar5(boolean newBooleanVar5) {
eDynamicSet(ArtefactPackage.SKETCH__BOOLEAN_VAR5, ArtefactPackage.Literals.SKETCH__BOOLEAN_VAR5, newBooleanVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isStringVar1() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR1, ArtefactPackage.Literals.SKETCH__STRING_VAR1, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStringVar1(boolean newStringVar1) {
eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR1, ArtefactPackage.Literals.SKETCH__STRING_VAR1, newStringVar1);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isStringVar2() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR2, ArtefactPackage.Literals.SKETCH__STRING_VAR2, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStringVar2(boolean newStringVar2) {
eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR2, ArtefactPackage.Literals.SKETCH__STRING_VAR2, newStringVar2);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isStringVar3() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR3, ArtefactPackage.Literals.SKETCH__STRING_VAR3, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStringVar3(boolean newStringVar3) {
eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR3, ArtefactPackage.Literals.SKETCH__STRING_VAR3, newStringVar3);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isStringVar4() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR4, ArtefactPackage.Literals.SKETCH__STRING_VAR4, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStringVar4(boolean newStringVar4) {
eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR4, ArtefactPackage.Literals.SKETCH__STRING_VAR4, newStringVar4);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isStringVar5() {
return (Boolean)eDynamicGet(ArtefactPackage.SKETCH__STRING_VAR5, ArtefactPackage.Literals.SKETCH__STRING_VAR5, true, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStringVar5(boolean newStringVar5) {
eDynamicSet(ArtefactPackage.SKETCH__STRING_VAR5, ArtefactPackage.Literals.SKETCH__STRING_VAR5, newStringVar5);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ArtefactPackage.SKETCH__CONTENTS:
return ((InternalEList<?>)getContents()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ArtefactPackage.SKETCH__TESTED:
return isTested();
case ArtefactPackage.SKETCH__ID:
return getId();
case ArtefactPackage.SKETCH__CONTENTS:
return getContents();
case ArtefactPackage.SKETCH__BYTE_VAR1:
return getByteVar1();
case ArtefactPackage.SKETCH__BYTE_VAR2:
return getByteVar2();
case ArtefactPackage.SKETCH__BYTE_VAR3:
return getByteVar3();
case ArtefactPackage.SKETCH__BYTE_VAR4:
return getByteVar4();
case ArtefactPackage.SKETCH__BYTE_VAR5:
return getByteVar5();
case ArtefactPackage.SKETCH__SHORT_VAR1:
return getShortVar1();
case ArtefactPackage.SKETCH__SHORT_VAR2:
return getShortVar2();
case ArtefactPackage.SKETCH__SHORT_VAR3:
return getShortVar3();
case ArtefactPackage.SKETCH__SHORT_VAR4:
return getShortVar4();
case ArtefactPackage.SKETCH__SHORT_VAR5:
return getShortVar5();
case ArtefactPackage.SKETCH__INT_VAR1:
return getIntVar1();
case ArtefactPackage.SKETCH__INT_VAR2:
return getIntVar2();
case ArtefactPackage.SKETCH__INT_VAR3:
return getIntVar3();
case ArtefactPackage.SKETCH__INT_VAR4:
return getIntVar4();
case ArtefactPackage.SKETCH__INT_VAR5:
return getIntVar5();
case ArtefactPackage.SKETCH__CHAR_VAR1:
return getCharVar1();
case ArtefactPackage.SKETCH__CHAR_VAR2:
return getCharVar2();
case ArtefactPackage.SKETCH__CHAR_VAR3:
return getCharVar3();
case ArtefactPackage.SKETCH__CHAR_VAR4:
return getCharVar4();
case ArtefactPackage.SKETCH__CHAR_VAR5:
return getCharVar5();
case ArtefactPackage.SKETCH__LONG_VAR1:
return getLongVar1();
case ArtefactPackage.SKETCH__LONG_VAR2:
return getLongVar2();
case ArtefactPackage.SKETCH__LONG_VAR3:
return getLongVar3();
case ArtefactPackage.SKETCH__LONG_VAR4:
return getLongVar4();
case ArtefactPackage.SKETCH__LONG_VAR5:
return getLongVar5();
case ArtefactPackage.SKETCH__FLOAT_VAR1:
return getFloatVar1();
case ArtefactPackage.SKETCH__FLOAT_VAR2:
return getFloatVar2();
case ArtefactPackage.SKETCH__FLOAT_VAR3:
return getFloatVar3();
case ArtefactPackage.SKETCH__FLOAT_VAR4:
return getFloatVar4();
case ArtefactPackage.SKETCH__FLOAT_VAR5:
return getFloatVar5();
case ArtefactPackage.SKETCH__DOUBLE_VAR1:
return getDoubleVar1();
case ArtefactPackage.SKETCH__DOUBLE_VAR2:
return getDoubleVar2();
case ArtefactPackage.SKETCH__DOUBLE_VAR3:
return getDoubleVar3();
case ArtefactPackage.SKETCH__DOUBLE_VAR4:
return getDoubleVar4();
case ArtefactPackage.SKETCH__DOUBLE_VAR5:
return getDoubleVar5();
case ArtefactPackage.SKETCH__BOOLEAN_VAR1:
return getBooleanVar1();
case ArtefactPackage.SKETCH__BOOLEAN_VAR2:
return isBooleanVar2();
case ArtefactPackage.SKETCH__BOOLEAN_VAR3:
return isBooleanVar3();
case ArtefactPackage.SKETCH__BOOLEAN_VAR4:
return isBooleanVar4();
case ArtefactPackage.SKETCH__BOOLEAN_VAR5:
return isBooleanVar5();
case ArtefactPackage.SKETCH__STRING_VAR1:
return isStringVar1();
case ArtefactPackage.SKETCH__STRING_VAR2:
return isStringVar2();
case ArtefactPackage.SKETCH__STRING_VAR3:
return isStringVar3();
case ArtefactPackage.SKETCH__STRING_VAR4:
return isStringVar4();
case ArtefactPackage.SKETCH__STRING_VAR5:
return isStringVar5();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ArtefactPackage.SKETCH__TESTED:
setTested((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__ID:
setId((String)newValue);
return;
case ArtefactPackage.SKETCH__CONTENTS:
getContents().clear();
getContents().addAll((Collection<? extends IContentElement>)newValue);
return;
case ArtefactPackage.SKETCH__BYTE_VAR1:
setByteVar1((Short)newValue);
return;
case ArtefactPackage.SKETCH__BYTE_VAR2:
setByteVar2((Integer)newValue);
return;
case ArtefactPackage.SKETCH__BYTE_VAR3:
setByteVar3((Long)newValue);
return;
case ArtefactPackage.SKETCH__BYTE_VAR4:
setByteVar4((Float)newValue);
return;
case ArtefactPackage.SKETCH__BYTE_VAR5:
setByteVar5((Double)newValue);
return;
case ArtefactPackage.SKETCH__SHORT_VAR1:
setShortVar1((Integer)newValue);
return;
case ArtefactPackage.SKETCH__SHORT_VAR2:
setShortVar2((Long)newValue);
return;
case ArtefactPackage.SKETCH__SHORT_VAR3:
setShortVar3((Float)newValue);
return;
case ArtefactPackage.SKETCH__SHORT_VAR4:
setShortVar4((Double)newValue);
return;
case ArtefactPackage.SKETCH__SHORT_VAR5:
setShortVar5((Short)newValue);
return;
case ArtefactPackage.SKETCH__INT_VAR1:
setIntVar1((Long)newValue);
return;
case ArtefactPackage.SKETCH__INT_VAR2:
setIntVar2((Float)newValue);
return;
case ArtefactPackage.SKETCH__INT_VAR3:
setIntVar3((Double)newValue);
return;
case ArtefactPackage.SKETCH__INT_VAR4:
setIntVar4((Integer)newValue);
return;
case ArtefactPackage.SKETCH__INT_VAR5:
setIntVar5((Integer)newValue);
return;
case ArtefactPackage.SKETCH__CHAR_VAR1:
setCharVar1((Integer)newValue);
return;
case ArtefactPackage.SKETCH__CHAR_VAR2:
setCharVar2((Long)newValue);
return;
case ArtefactPackage.SKETCH__CHAR_VAR3:
setCharVar3((Float)newValue);
return;
case ArtefactPackage.SKETCH__CHAR_VAR4:
setCharVar4((Double)newValue);
return;
case ArtefactPackage.SKETCH__CHAR_VAR5:
setCharVar5((String)newValue);
return;
case ArtefactPackage.SKETCH__LONG_VAR1:
setLongVar1((Float)newValue);
return;
case ArtefactPackage.SKETCH__LONG_VAR2:
setLongVar2((Double)newValue);
return;
case ArtefactPackage.SKETCH__LONG_VAR3:
setLongVar3((Long)newValue);
return;
case ArtefactPackage.SKETCH__LONG_VAR4:
setLongVar4((Long)newValue);
return;
case ArtefactPackage.SKETCH__LONG_VAR5:
setLongVar5((Long)newValue);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR1:
setFloatVar1((Double)newValue);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR2:
setFloatVar2((Float)newValue);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR3:
setFloatVar3((Float)newValue);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR4:
setFloatVar4((Float)newValue);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR5:
setFloatVar5((Float)newValue);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR1:
setDoubleVar1((Double)newValue);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR2:
setDoubleVar2((Double)newValue);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR3:
setDoubleVar3((Double)newValue);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR4:
setDoubleVar4((Double)newValue);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR5:
setDoubleVar5((Double)newValue);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR1:
setBooleanVar1((String)newValue);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR2:
setBooleanVar2((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR3:
setBooleanVar3((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR4:
setBooleanVar4((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR5:
setBooleanVar5((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__STRING_VAR1:
setStringVar1((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__STRING_VAR2:
setStringVar2((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__STRING_VAR3:
setStringVar3((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__STRING_VAR4:
setStringVar4((Boolean)newValue);
return;
case ArtefactPackage.SKETCH__STRING_VAR5:
setStringVar5((Boolean)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ArtefactPackage.SKETCH__TESTED:
setTested(TESTED_EDEFAULT);
return;
case ArtefactPackage.SKETCH__ID:
setId(ID_EDEFAULT);
return;
case ArtefactPackage.SKETCH__CONTENTS:
getContents().clear();
return;
case ArtefactPackage.SKETCH__BYTE_VAR1:
setByteVar1(BYTE_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BYTE_VAR2:
setByteVar2(BYTE_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BYTE_VAR3:
setByteVar3(BYTE_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BYTE_VAR4:
setByteVar4(BYTE_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BYTE_VAR5:
setByteVar5(BYTE_VAR5_EDEFAULT);
return;
case ArtefactPackage.SKETCH__SHORT_VAR1:
setShortVar1(SHORT_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__SHORT_VAR2:
setShortVar2(SHORT_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__SHORT_VAR3:
setShortVar3(SHORT_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__SHORT_VAR4:
setShortVar4(SHORT_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__SHORT_VAR5:
setShortVar5(SHORT_VAR5_EDEFAULT);
return;
case ArtefactPackage.SKETCH__INT_VAR1:
setIntVar1(INT_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__INT_VAR2:
setIntVar2(INT_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__INT_VAR3:
setIntVar3(INT_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__INT_VAR4:
setIntVar4(INT_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__INT_VAR5:
setIntVar5(INT_VAR5_EDEFAULT);
return;
case ArtefactPackage.SKETCH__CHAR_VAR1:
setCharVar1(CHAR_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__CHAR_VAR2:
setCharVar2(CHAR_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__CHAR_VAR3:
setCharVar3(CHAR_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__CHAR_VAR4:
setCharVar4(CHAR_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__CHAR_VAR5:
setCharVar5(CHAR_VAR5_EDEFAULT);
return;
case ArtefactPackage.SKETCH__LONG_VAR1:
setLongVar1(LONG_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__LONG_VAR2:
setLongVar2(LONG_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__LONG_VAR3:
setLongVar3(LONG_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__LONG_VAR4:
setLongVar4(LONG_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__LONG_VAR5:
setLongVar5(LONG_VAR5_EDEFAULT);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR1:
setFloatVar1(FLOAT_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR2:
setFloatVar2(FLOAT_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR3:
setFloatVar3(FLOAT_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR4:
setFloatVar4(FLOAT_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__FLOAT_VAR5:
setFloatVar5(FLOAT_VAR5_EDEFAULT);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR1:
setDoubleVar1(DOUBLE_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR2:
setDoubleVar2(DOUBLE_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR3:
setDoubleVar3(DOUBLE_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR4:
setDoubleVar4(DOUBLE_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__DOUBLE_VAR5:
setDoubleVar5(DOUBLE_VAR5_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR1:
setBooleanVar1(BOOLEAN_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR2:
setBooleanVar2(BOOLEAN_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR3:
setBooleanVar3(BOOLEAN_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR4:
setBooleanVar4(BOOLEAN_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__BOOLEAN_VAR5:
setBooleanVar5(BOOLEAN_VAR5_EDEFAULT);
return;
case ArtefactPackage.SKETCH__STRING_VAR1:
setStringVar1(STRING_VAR1_EDEFAULT);
return;
case ArtefactPackage.SKETCH__STRING_VAR2:
setStringVar2(STRING_VAR2_EDEFAULT);
return;
case ArtefactPackage.SKETCH__STRING_VAR3:
setStringVar3(STRING_VAR3_EDEFAULT);
return;
case ArtefactPackage.SKETCH__STRING_VAR4:
setStringVar4(STRING_VAR4_EDEFAULT);
return;
case ArtefactPackage.SKETCH__STRING_VAR5:
setStringVar5(STRING_VAR5_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ArtefactPackage.SKETCH__TESTED:
return isTested() != TESTED_EDEFAULT;
case ArtefactPackage.SKETCH__ID:
return ID_EDEFAULT == null ? getId() != null : !ID_EDEFAULT.equals(getId());
case ArtefactPackage.SKETCH__CONTENTS:
return !getContents().isEmpty();
case ArtefactPackage.SKETCH__BYTE_VAR1:
return getByteVar1() != BYTE_VAR1_EDEFAULT;
case ArtefactPackage.SKETCH__BYTE_VAR2:
return getByteVar2() != BYTE_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__BYTE_VAR3:
return getByteVar3() != BYTE_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__BYTE_VAR4:
return getByteVar4() != BYTE_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__BYTE_VAR5:
return getByteVar5() != BYTE_VAR5_EDEFAULT;
case ArtefactPackage.SKETCH__SHORT_VAR1:
return getShortVar1() != SHORT_VAR1_EDEFAULT;
case ArtefactPackage.SKETCH__SHORT_VAR2:
return getShortVar2() != SHORT_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__SHORT_VAR3:
return getShortVar3() != SHORT_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__SHORT_VAR4:
return getShortVar4() != SHORT_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__SHORT_VAR5:
return getShortVar5() != SHORT_VAR5_EDEFAULT;
case ArtefactPackage.SKETCH__INT_VAR1:
return getIntVar1() != INT_VAR1_EDEFAULT;
case ArtefactPackage.SKETCH__INT_VAR2:
return getIntVar2() != INT_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__INT_VAR3:
return getIntVar3() != INT_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__INT_VAR4:
return getIntVar4() != INT_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__INT_VAR5:
return getIntVar5() != INT_VAR5_EDEFAULT;
case ArtefactPackage.SKETCH__CHAR_VAR1:
return getCharVar1() != CHAR_VAR1_EDEFAULT;
case ArtefactPackage.SKETCH__CHAR_VAR2:
return getCharVar2() != CHAR_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__CHAR_VAR3:
return getCharVar3() != CHAR_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__CHAR_VAR4:
return getCharVar4() != CHAR_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__CHAR_VAR5:
return CHAR_VAR5_EDEFAULT == null ? getCharVar5() != null : !CHAR_VAR5_EDEFAULT.equals(getCharVar5());
case ArtefactPackage.SKETCH__LONG_VAR1:
return getLongVar1() != LONG_VAR1_EDEFAULT;
case ArtefactPackage.SKETCH__LONG_VAR2:
return getLongVar2() != LONG_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__LONG_VAR3:
return getLongVar3() != LONG_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__LONG_VAR4:
return getLongVar4() != LONG_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__LONG_VAR5:
return getLongVar5() != LONG_VAR5_EDEFAULT;
case ArtefactPackage.SKETCH__FLOAT_VAR1:
return getFloatVar1() != FLOAT_VAR1_EDEFAULT;
case ArtefactPackage.SKETCH__FLOAT_VAR2:
return getFloatVar2() != FLOAT_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__FLOAT_VAR3:
return getFloatVar3() != FLOAT_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__FLOAT_VAR4:
return getFloatVar4() != FLOAT_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__FLOAT_VAR5:
return getFloatVar5() != FLOAT_VAR5_EDEFAULT;
case ArtefactPackage.SKETCH__DOUBLE_VAR1:
return getDoubleVar1() != DOUBLE_VAR1_EDEFAULT;
case ArtefactPackage.SKETCH__DOUBLE_VAR2:
return getDoubleVar2() != DOUBLE_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__DOUBLE_VAR3:
return getDoubleVar3() != DOUBLE_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__DOUBLE_VAR4:
return getDoubleVar4() != DOUBLE_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__DOUBLE_VAR5:
return getDoubleVar5() != DOUBLE_VAR5_EDEFAULT;
case ArtefactPackage.SKETCH__BOOLEAN_VAR1:
return BOOLEAN_VAR1_EDEFAULT == null ? getBooleanVar1() != null : !BOOLEAN_VAR1_EDEFAULT.equals(getBooleanVar1());
case ArtefactPackage.SKETCH__BOOLEAN_VAR2:
return isBooleanVar2() != BOOLEAN_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__BOOLEAN_VAR3:
return isBooleanVar3() != BOOLEAN_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__BOOLEAN_VAR4:
return isBooleanVar4() != BOOLEAN_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__BOOLEAN_VAR5:
return isBooleanVar5() != BOOLEAN_VAR5_EDEFAULT;
case ArtefactPackage.SKETCH__STRING_VAR1:
return isStringVar1() != STRING_VAR1_EDEFAULT;
case ArtefactPackage.SKETCH__STRING_VAR2:
return isStringVar2() != STRING_VAR2_EDEFAULT;
case ArtefactPackage.SKETCH__STRING_VAR3:
return isStringVar3() != STRING_VAR3_EDEFAULT;
case ArtefactPackage.SKETCH__STRING_VAR4:
return isStringVar4() != STRING_VAR4_EDEFAULT;
case ArtefactPackage.SKETCH__STRING_VAR5:
return isStringVar5() != STRING_VAR5_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == IID.class) {
switch (derivedFeatureID) {
case ArtefactPackage.SKETCH__ID: return BasePackage.IID__ID;
default: return -1;
}
}
if (baseClass == IContentElement.class) {
switch (derivedFeatureID) {
default: return -1;
}
}
if (baseClass == IContainer.class) {
switch (derivedFeatureID) {
case ArtefactPackage.SKETCH__CONTENTS: return BasePackage.ICONTAINER__CONTENTS;
default: return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == IID.class) {
switch (baseFeatureID) {
case BasePackage.IID__ID: return ArtefactPackage.SKETCH__ID;
default: return -1;
}
}
if (baseClass == IContentElement.class) {
switch (baseFeatureID) {
default: return -1;
}
}
if (baseClass == IContainer.class) {
switch (baseFeatureID) {
case BasePackage.ICONTAINER__CONTENTS: return ArtefactPackage.SKETCH__CONTENTS;
default: return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
} //SketchImpl
| {
"content_hash": "5f23f3476a13b3ff1fd5493eb515ccb5",
"timestamp": "",
"source": "github",
"line_count": 2040,
"max_line_length": 134,
"avg_line_length": 30.522549019607844,
"alnum_prop": 0.6739472585359586,
"repo_name": "junkerm/specmate",
"id": "bbf5e7c7993b263f26eccaa2022c4663e4f7df62",
"size": "62266",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "bundles/specmate-migration-test/src/com/specmate/migration/test/changedtypes/testmodel/artefact/impl/SketchImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7101"
},
{
"name": "Dockerfile",
"bytes": "854"
},
{
"name": "GAP",
"bytes": "254786"
},
{
"name": "HTML",
"bytes": "83420"
},
{
"name": "Java",
"bytes": "5874840"
},
{
"name": "Python",
"bytes": "74602"
},
{
"name": "Ruby",
"bytes": "17086"
},
{
"name": "TypeScript",
"bytes": "559148"
},
{
"name": "Xtend",
"bytes": "7445"
}
],
"symlink_target": ""
} |
require 'slim'
require 'spec_helper'
describe Sinatra::Capture do
subject do
Sinatra.new do
enable :inline_templates
helpers Sinatra::Capture
end.new!
end
Tilt.prefer Tilt::ERBTemplate
extend Forwardable
def_delegators :subject, :capture, :capture_later
def render(engine, template)
subject.send(:render, engine, template.to_sym).strip.gsub(/\s+/, ' ')
end
shared_examples_for "a template language" do |engine|
lang = engine
if engine == :erubi || engine == :erubis
lang = :erb
end
if engine == :hamlit
lang = :haml
end
require "#{engine}"
it "captures content" do
expect(render(engine, "simple_#{lang}")).to eq("Say Hello World!")
end
it "allows nested captures" do
expect(render(engine, "nested_#{lang}")).to eq("Say Hello World!")
end
end
describe('haml') { it_behaves_like "a template language", :haml }
describe('hamlit') { it_behaves_like "a template language", :hamlit }
describe('slim') { it_behaves_like "a template language", :slim }
describe('erubi') { it_behaves_like "a template language", :erubi }
describe('erubis') { it_behaves_like "a template language", :erubis }
describe 'erb' do
it_behaves_like "a template language", :erb
it "handles utf-8 encoding" do
expect(render(:erb, "utf_8")).to eq("UTF-8 –")
end
it "handles ISO-8859-1 encoding" do
expect(render(:erb, "iso_8859_1")).to eq("ISO-8859-1 -")
end
end
describe 'without templates' do
it 'captures empty blocks' do
expect(capture {}).to be_nil
end
end
end
__END__
@@ simple_erb
Say
<% a = capture do %>World<% end %>
Hello <%= a %>!
@@ nested_erb
Say
<% a = capture do %>
<% b = capture do %>World<% end %>
<%= b %>!
<% end %>
Hello <%= a.strip %>
@@ simple_slim
| Say
- a = capture do
| World
| Hello #{a.strip}!
@@ nested_slim
| Say
- a = capture do
- b = capture do
| World
| #{b.strip}!
| Hello #{a.strip}
@@ simple_haml
Say
- a = capture do
World
Hello #{a.strip}!
@@ nested_haml
Say
- a = capture do
- b = capture do
World
#{b.strip}!
Hello #{a.strip}
@@ utf_8
<% a = capture do %>–<% end %>
UTF-8 <%= a %>
@@ iso_8859_1
<% a = capture do %>-<% end %>
ISO-8859-1 <%= a.force_encoding("iso-8859-1") %>
| {
"content_hash": "a8f5e27599593c47933778a2ce650ef3",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 73,
"avg_line_length": 20.41592920353982,
"alnum_prop": 0.5999133073255309,
"repo_name": "jkowens/sinatra",
"id": "7fd450a213ae7282ec9ba35cd224c590b1690822",
"size": "2335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sinatra-contrib/spec/capture_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "13"
},
{
"name": "HTML",
"bytes": "1685"
},
{
"name": "Haml",
"bytes": "604"
},
{
"name": "Less",
"bytes": "65"
},
{
"name": "Liquid",
"bytes": "70"
},
{
"name": "Ruby",
"bytes": "654583"
},
{
"name": "SCSS",
"bytes": "35"
},
{
"name": "Sass",
"bytes": "72"
},
{
"name": "Shell",
"bytes": "454"
},
{
"name": "Slim",
"bytes": "498"
},
{
"name": "Stylus",
"bytes": "16"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/Single_IO.iml" filepath="$PROJECT_DIR$/Single_IO.iml" />
<module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
</modules>
</component>
</project>
| {
"content_hash": "25231938ed73901a832bf2cfe0f2949c",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 100,
"avg_line_length": 35.7,
"alnum_prop": 0.6498599439775911,
"repo_name": "whynottry/Signal_IO",
"id": "c8cc677f4c71f78126eb8ea524c94e3a779bfabe",
"size": "357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/modules.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "6748"
}
],
"symlink_target": ""
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/media/capture/content_video_capture_device_core.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback_forward.h"
#include "base/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/metrics/histogram.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "content/public/browser/browser_thread.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/video_capture_types.h"
#include "media/base/video_frame.h"
#include "media/base/video_frame_metadata.h"
#include "media/base/video_util.h"
#include "ui/gfx/geometry/rect.h"
namespace content {
namespace {
void DeleteCaptureMachineOnUIThread(
scoped_ptr<VideoCaptureMachine> capture_machine) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
capture_machine.reset();
}
} // namespace
ThreadSafeCaptureOracle::ThreadSafeCaptureOracle(
scoped_ptr<media::VideoCaptureDevice::Client> client,
const media::VideoCaptureParams& params)
: client_(client.Pass()),
oracle_(base::TimeDelta::FromMicroseconds(
static_cast<int64>(1000000.0 / params.requested_format.frame_rate +
0.5 /* to round to nearest int */))),
params_(params) {}
ThreadSafeCaptureOracle::~ThreadSafeCaptureOracle() {}
bool ThreadSafeCaptureOracle::ObserveEventAndDecideCapture(
VideoCaptureOracle::Event event,
const gfx::Rect& damage_rect,
base::TimeTicks event_time,
scoped_refptr<media::VideoFrame>* storage,
CaptureFrameCallback* callback) {
// Grab the current time before waiting to acquire the |lock_|.
const base::TimeTicks capture_begin_time = base::TimeTicks::Now();
base::AutoLock guard(lock_);
if (!client_)
return false; // Capture is stopped.
const media::VideoFrame::Format video_frame_format =
params_.requested_format.pixel_format == media::PIXEL_FORMAT_TEXTURE ?
media::VideoFrame::NATIVE_TEXTURE : media::VideoFrame::I420;
if (capture_size_.IsEmpty())
capture_size_ = max_frame_size();
const gfx::Size visible_size = capture_size_;
// Always round up the coded size to multiple of 16 pixels.
// See http://crbug.com/402151.
const gfx::Size coded_size((visible_size.width() + 15) & ~15,
(visible_size.height() + 15) & ~15);
scoped_refptr<media::VideoCaptureDevice::Client::Buffer> output_buffer =
client_->ReserveOutputBuffer(video_frame_format, coded_size);
const bool should_capture =
oracle_.ObserveEventAndDecideCapture(event, damage_rect, event_time);
const char* event_name =
(event == VideoCaptureOracle::kTimerPoll ? "poll" :
(event == VideoCaptureOracle::kCompositorUpdate ? "gpu" :
"paint"));
// Consider the various reasons not to initiate a capture.
if (should_capture && !output_buffer.get()) {
TRACE_EVENT_INSTANT1("gpu.capture",
"PipelineLimited",
TRACE_EVENT_SCOPE_THREAD,
"trigger",
event_name);
return false;
} else if (!should_capture && output_buffer.get()) {
if (event == VideoCaptureOracle::kCompositorUpdate) {
// This is a normal and acceptable way to drop a frame. We've hit our
// capture rate limit: for example, the content is animating at 60fps but
// we're capturing at 30fps.
TRACE_EVENT_INSTANT1("gpu.capture", "FpsRateLimited",
TRACE_EVENT_SCOPE_THREAD,
"trigger", event_name);
}
return false;
} else if (!should_capture && !output_buffer.get()) {
// We decided not to capture, but we wouldn't have been able to if we wanted
// to because no output buffer was available.
TRACE_EVENT_INSTANT1("gpu.capture", "NearlyPipelineLimited",
TRACE_EVENT_SCOPE_THREAD,
"trigger", event_name);
return false;
}
int frame_number = oracle_.RecordCapture();
TRACE_EVENT_ASYNC_BEGIN2("gpu.capture", "Capture", output_buffer.get(),
"frame_number", frame_number,
"trigger", event_name);
// NATIVE_TEXTURE frames wrap a texture mailbox, which we don't have at the
// moment. We do not construct those frames.
if (video_frame_format != media::VideoFrame::NATIVE_TEXTURE) {
*storage = media::VideoFrame::WrapExternalPackedMemory(
video_frame_format,
coded_size,
gfx::Rect(visible_size),
visible_size,
static_cast<uint8*>(output_buffer->data()),
output_buffer->size(),
base::SharedMemory::NULLHandle(),
0,
base::TimeDelta(),
base::Closure());
DCHECK(*storage);
}
*callback = base::Bind(&ThreadSafeCaptureOracle::DidCaptureFrame,
this,
frame_number,
output_buffer,
capture_begin_time);
return true;
}
gfx::Size ThreadSafeCaptureOracle::GetCaptureSize() const {
base::AutoLock guard(lock_);
return capture_size_.IsEmpty() ? max_frame_size() : capture_size_;
}
void ThreadSafeCaptureOracle::UpdateCaptureSize(const gfx::Size& source_size) {
base::AutoLock guard(lock_);
// Update |capture_size_| based on |source_size| if either: 1) The resolution
// change policy specifies fixed frame sizes and |capture_size_| has not yet
// been set; or 2) The resolution change policy specifies dynamic frame
// sizes.
if (capture_size_.IsEmpty() || params_.resolution_change_policy ==
media::RESOLUTION_POLICY_DYNAMIC_WITHIN_LIMIT) {
capture_size_ = source_size;
// The capture size should not exceed the maximum frame size.
if (capture_size_.width() > max_frame_size().width() ||
capture_size_.height() > max_frame_size().height()) {
capture_size_ = media::ComputeLetterboxRegion(
gfx::Rect(max_frame_size()), capture_size_).size();
}
// The capture size must be even and not less than the minimum frame size.
capture_size_ = gfx::Size(
std::max(kMinFrameWidth, MakeEven(capture_size_.width())),
std::max(kMinFrameHeight, MakeEven(capture_size_.height())));
}
}
void ThreadSafeCaptureOracle::Stop() {
base::AutoLock guard(lock_);
client_.reset();
}
void ThreadSafeCaptureOracle::ReportError(const std::string& reason) {
base::AutoLock guard(lock_);
if (client_)
client_->OnError(reason);
}
void ThreadSafeCaptureOracle::DidCaptureFrame(
int frame_number,
const scoped_refptr<media::VideoCaptureDevice::Client::Buffer>& buffer,
base::TimeTicks capture_begin_time,
const scoped_refptr<media::VideoFrame>& frame,
base::TimeTicks timestamp,
bool success) {
base::AutoLock guard(lock_);
TRACE_EVENT_ASYNC_END2("gpu.capture", "Capture", buffer.get(),
"success", success,
"timestamp", timestamp.ToInternalValue());
if (!client_)
return; // Capture is stopped.
if (success) {
if (oracle_.CompleteCapture(frame_number, ×tamp)) {
// TODO(miu): Use the locked-in frame rate from AnimatedContentSampler.
frame->metadata()->SetDouble(media::VideoFrameMetadata::FRAME_RATE,
params_.requested_format.frame_rate);
frame->metadata()->SetTimeTicks(
media::VideoFrameMetadata::CAPTURE_BEGIN_TIME, capture_begin_time);
frame->metadata()->SetTimeTicks(
media::VideoFrameMetadata::CAPTURE_END_TIME, base::TimeTicks::Now());
client_->OnIncomingCapturedVideoFrame(buffer, frame, timestamp);
}
}
}
void ContentVideoCaptureDeviceCore::AllocateAndStart(
const media::VideoCaptureParams& params,
scoped_ptr<media::VideoCaptureDevice::Client> client) {
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ != kIdle) {
DVLOG(1) << "Allocate() invoked when not in state Idle.";
return;
}
if (params.requested_format.frame_rate <= 0) {
std::string error_msg("Invalid frame_rate: ");
error_msg += base::DoubleToString(params.requested_format.frame_rate);
DVLOG(1) << error_msg;
client->OnError(error_msg);
return;
}
if (params.requested_format.pixel_format != media::PIXEL_FORMAT_I420 &&
params.requested_format.pixel_format != media::PIXEL_FORMAT_TEXTURE) {
std::string error_msg = base::StringPrintf(
"unsupported format: %d", params.requested_format.pixel_format);
DVLOG(1) << error_msg;
client->OnError(error_msg);
return;
}
if (params.requested_format.frame_size.width() < kMinFrameWidth ||
params.requested_format.frame_size.height() < kMinFrameHeight) {
std::string error_msg =
"invalid frame size: " + params.requested_format.frame_size.ToString();
DVLOG(1) << error_msg;
client->OnError(error_msg);
return;
}
media::VideoCaptureParams new_params = params;
// Frame dimensions must each be an even integer since the client wants (or
// will convert to) YUV420.
new_params.requested_format.frame_size.SetSize(
MakeEven(params.requested_format.frame_size.width()),
MakeEven(params.requested_format.frame_size.height()));
oracle_proxy_ = new ThreadSafeCaptureOracle(client.Pass(), new_params);
// Starts the capture machine asynchronously.
BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::UI,
FROM_HERE,
base::Bind(&VideoCaptureMachine::Start,
base::Unretained(capture_machine_.get()),
oracle_proxy_,
new_params),
base::Bind(&ContentVideoCaptureDeviceCore::CaptureStarted, AsWeakPtr()));
TransitionStateTo(kCapturing);
}
void ContentVideoCaptureDeviceCore::StopAndDeAllocate() {
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ != kCapturing)
return;
oracle_proxy_->Stop();
oracle_proxy_ = NULL;
TransitionStateTo(kIdle);
// Stops the capture machine asynchronously.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, base::Bind(
&VideoCaptureMachine::Stop,
base::Unretained(capture_machine_.get()),
base::Bind(&base::DoNothing)));
}
void ContentVideoCaptureDeviceCore::CaptureStarted(bool success) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!success) {
std::string reason("Failed to start capture machine.");
DVLOG(1) << reason;
Error(reason);
}
}
ContentVideoCaptureDeviceCore::ContentVideoCaptureDeviceCore(
scoped_ptr<VideoCaptureMachine> capture_machine)
: state_(kIdle),
capture_machine_(capture_machine.Pass()) {
DCHECK(capture_machine_.get());
}
ContentVideoCaptureDeviceCore::~ContentVideoCaptureDeviceCore() {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_NE(state_, kCapturing);
// If capture_machine is not NULL, then we need to return to the UI thread to
// safely stop the capture machine.
if (capture_machine_) {
VideoCaptureMachine* capture_machine_ptr = capture_machine_.get();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&VideoCaptureMachine::Stop,
base::Unretained(capture_machine_ptr),
base::Bind(&DeleteCaptureMachineOnUIThread,
base::Passed(&capture_machine_))));
}
DVLOG(1) << "ContentVideoCaptureDeviceCore@" << this << " destroying.";
}
void ContentVideoCaptureDeviceCore::TransitionStateTo(State next_state) {
DCHECK(thread_checker_.CalledOnValidThread());
#ifndef NDEBUG
static const char* kStateNames[] = {
"Idle", "Allocated", "Capturing", "Error"
};
DVLOG(1) << "State change: " << kStateNames[state_]
<< " --> " << kStateNames[next_state];
#endif
state_ = next_state;
}
void ContentVideoCaptureDeviceCore::Error(const std::string& reason) {
DCHECK(thread_checker_.CalledOnValidThread());
if (state_ == kIdle)
return;
if (oracle_proxy_.get())
oracle_proxy_->ReportError(reason);
StopAndDeAllocate();
TransitionStateTo(kError);
}
} // namespace content
| {
"content_hash": "0e030998019cf376341eeae2d6c10e68",
"timestamp": "",
"source": "github",
"line_count": 350,
"max_line_length": 80,
"avg_line_length": 36.011428571428574,
"alnum_prop": 0.6647096159949223,
"repo_name": "fujunwei/chromium-crosswalk",
"id": "5030f6d633005666cc4961f9d52ee99a1d698b20",
"size": "12604",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "content/browser/media/capture/content_video_capture_device_core.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "23829"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "4116349"
},
{
"name": "C++",
"bytes": "233601977"
},
{
"name": "CSS",
"bytes": "931025"
},
{
"name": "Emacs Lisp",
"bytes": "988"
},
{
"name": "HTML",
"bytes": "28881204"
},
{
"name": "Java",
"bytes": "9824090"
},
{
"name": "JavaScript",
"bytes": "19683742"
},
{
"name": "Makefile",
"bytes": "68017"
},
{
"name": "Objective-C",
"bytes": "1478432"
},
{
"name": "Objective-C++",
"bytes": "8653645"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "171186"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "456460"
},
{
"name": "Python",
"bytes": "7963013"
},
{
"name": "Shell",
"bytes": "468673"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
pkgs = find_packages()
setup(
name='strictdict3',
version='0.4.5',
description='Strict Dict',
author='Dmitry Zhiltsov',
author_email='dzhiltsov@me.com',
ext_modules=[],
packages=pkgs,
tests_require=['py==1.4.31', 'pytest==3.0.0'],
cmdclass={'test': PyTest},
scripts=[],
data_files=[],
install_requires=[
'msgpack-python==0.4.8',
],
test_suite="strictdict.tests",
platforms='any',
license='MIT',
url='https://github.com/PushAMP/strictdict3',
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| {
"content_hash": "0c77f12bd08063c9a8290e480a7130e5",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 74,
"avg_line_length": 26.264150943396228,
"alnum_prop": 0.6199712643678161,
"repo_name": "PushAMP/strictdict3",
"id": "e173b2bc547a01838877e3d56c66695118e67280",
"size": "1414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "36264"
}
],
"symlink_target": ""
} |
@interface AGQueue ()
@property (strong, nonatomic) NSMutableArray *queueStorageArray;
@end
@implementation AGQueue
#pragma mark -
- (id)init
{
self = [super init];
if (self) {
_queueStorageArray = [[NSMutableArray alloc] init];
}
return self;
}
#pragma mark -
- (NSUInteger)count
{
return [self.queueStorageArray count];
}
#pragma mark -
- (void)enqueueObject:(id)anObject
{
[self.queueStorageArray addObject:anObject];
}
- (id)dequeueObject
{
if ([self count] == 0) {
return nil;
}
return [self.queueStorageArray objectAtIndex:0];
}
@end | {
"content_hash": "f6587c7b12c15718061e842de34fb42d",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 64,
"avg_line_length": 14.75609756097561,
"alnum_prop": 0.6462809917355372,
"repo_name": "andrewgarn/AGFoundation",
"id": "cbe4a46e6b86d361f8760f5f85f969758fd1dfeb",
"size": "2072",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Foundation/Extensions/AGQueue.m",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Objective-C",
"bytes": "584179"
}
],
"symlink_target": ""
} |
package org.drip.assetbacked.borrower;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2017 Lakshmi Krishnamurthy
* Copyright (C) 2016 Lakshmi Krishnamurthy
*
* This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
* libraries targeting analysts and developers
* https://lakshmidrip.github.io/DRIP/
*
* DRIP is composed of four main libraries:
*
* - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
* - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
* - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
* - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
*
* - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
* Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
* Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
* Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
* Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
*
* - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
* Incorporator, Holdings Constraint, and Transaction Costs.
*
* - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
*
* - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
*
* 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.
*/
/**
* OriginationFICO contains the Borrower's FICO Score at a given Loan's Origination.
*
* @author Lakshmi Krishnamurthy
*/
public class OriginationFICO {
private double _dblFICO = java.lang.Double.NaN;
/**
* OriginationFICO Constructor
*
* @param dblFICO The Borrower's FICO Score at Origination
*
* @throws java.lang.Exception Thrown if the Inputs are Invalid
*/
public OriginationFICO (
final double dblFICO)
throws java.lang.Exception
{
if (!org.drip.quant.common.NumberUtil.IsValid (_dblFICO = dblFICO))
throw new java.lang.Exception ("OriginationFICO Constructor => Invalid Inputs");
}
/**
* Retrieve the Borrower's FICO Score at Origination
*
* @return The Borrower's FICO Score at Origination
*/
public double score()
{
return _dblFICO;
}
}
| {
"content_hash": "d2f2a58c6103b8dfcdf1cf42a58d4cd0",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 104,
"avg_line_length": 36.07058823529412,
"alnum_prop": 0.7341813437703849,
"repo_name": "lakshmiDRIP/DRIP",
"id": "e276d8107d3311040071d032b1ba5e193acb5a2b",
"size": "3066",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/drip/assetbacked/borrower/OriginationFICO.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "19869"
},
{
"name": "HTML",
"bytes": "5974"
},
{
"name": "Java",
"bytes": "20814325"
},
{
"name": "JavaScript",
"bytes": "16520"
}
],
"symlink_target": ""
} |
package eu.verdelhan.ta4j.indicators.simple;
import eu.verdelhan.ta4j.Decimal;
import static eu.verdelhan.ta4j.TATestsUtils.assertDecimalEquals;
import eu.verdelhan.ta4j.TimeSeries;
import eu.verdelhan.ta4j.mocks.MockTimeSeries;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class PriceVariationIndicatorTest {
private PriceVariationIndicator variationIndicator;
private TimeSeries timeSeries;
@Before
public void setUp() {
timeSeries = new MockTimeSeries();
variationIndicator = new PriceVariationIndicator(timeSeries);
}
@Test
public void indicatorShouldRetrieveTickVariation() {
assertDecimalEquals(variationIndicator.getValue(0), 1);
for (int i = 1; i < 10; i++) {
Decimal previousTickClosePrice = timeSeries.getTick(i - 1).getClosePrice();
Decimal currentTickClosePrice = timeSeries.getTick(i).getClosePrice();
assertEquals(variationIndicator.getValue(i), currentTickClosePrice.dividedBy(previousTickClosePrice));
}
}
}
| {
"content_hash": "d07bb5261d4483f707b7020287dbf320",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 114,
"avg_line_length": 32.81818181818182,
"alnum_prop": 0.7331486611265005,
"repo_name": "ElMoe/ta4j",
"id": "4268e1eab3f8fc100df4ae97f16705f94f0cd374",
"size": "2270",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ta4j/src/test/java/eu/verdelhan/ta4j/indicators/simple/PriceVariationIndicatorTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "966393"
}
],
"symlink_target": ""
} |
GOOS=linux GOARCH=arm GOARM=7 go build -o rmc_armv7 main.go
GOOS=linux GOARCH=amd64 go build -o rmc_amd64 main.go
| {
"content_hash": "87bb29b5d78a4454991dbdbee6c86d38",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 59,
"avg_line_length": 57,
"alnum_prop": 0.7719298245614035,
"repo_name": "grafoo/utl",
"id": "70519b232a96dac5ccf3967dcb9131ba94709ab9",
"size": "135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rmc/build.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "501"
},
{
"name": "Go",
"bytes": "1495"
},
{
"name": "Haskell",
"bytes": "1483"
},
{
"name": "Python",
"bytes": "1162"
},
{
"name": "Shell",
"bytes": "7560"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/ec2/model/ResponseMetadata.h>
#include <aws/ec2/model/InternetGateway.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Xml
{
class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{
class AWS_EC2_API DescribeInternetGatewaysResponse
{
public:
DescribeInternetGatewaysResponse();
DescribeInternetGatewaysResponse(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
DescribeInternetGatewaysResponse& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
/**
* <p>Information about one or more internet gateways.</p>
*/
inline const Aws::Vector<InternetGateway>& GetInternetGateways() const{ return m_internetGateways; }
/**
* <p>Information about one or more internet gateways.</p>
*/
inline void SetInternetGateways(const Aws::Vector<InternetGateway>& value) { m_internetGateways = value; }
/**
* <p>Information about one or more internet gateways.</p>
*/
inline void SetInternetGateways(Aws::Vector<InternetGateway>&& value) { m_internetGateways = std::move(value); }
/**
* <p>Information about one or more internet gateways.</p>
*/
inline DescribeInternetGatewaysResponse& WithInternetGateways(const Aws::Vector<InternetGateway>& value) { SetInternetGateways(value); return *this;}
/**
* <p>Information about one or more internet gateways.</p>
*/
inline DescribeInternetGatewaysResponse& WithInternetGateways(Aws::Vector<InternetGateway>&& value) { SetInternetGateways(std::move(value)); return *this;}
/**
* <p>Information about one or more internet gateways.</p>
*/
inline DescribeInternetGatewaysResponse& AddInternetGateways(const InternetGateway& value) { m_internetGateways.push_back(value); return *this; }
/**
* <p>Information about one or more internet gateways.</p>
*/
inline DescribeInternetGatewaysResponse& AddInternetGateways(InternetGateway&& value) { m_internetGateways.push_back(std::move(value)); return *this; }
inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }
inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }
inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }
inline DescribeInternetGatewaysResponse& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}
inline DescribeInternetGatewaysResponse& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}
private:
Aws::Vector<InternetGateway> m_internetGateways;
ResponseMetadata m_responseMetadata;
};
} // namespace Model
} // namespace EC2
} // namespace Aws
| {
"content_hash": "f3ed15ae691b4d995ae0605475a32a88",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 159,
"avg_line_length": 32.52127659574468,
"alnum_prop": 0.7288191036964344,
"repo_name": "JoyIfBam5/aws-sdk-cpp",
"id": "bcb88e714414cda4df5810c83c60f003396c005e",
"size": "3630",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-ec2/include/aws/ec2/model/DescribeInternetGatewaysResponse.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "11868"
},
{
"name": "C++",
"bytes": "167818064"
},
{
"name": "CMake",
"bytes": "591577"
},
{
"name": "HTML",
"bytes": "4471"
},
{
"name": "Java",
"bytes": "271801"
},
{
"name": "Python",
"bytes": "85650"
},
{
"name": "Shell",
"bytes": "5277"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
public class SwapCoolDownUpdate : MonoBehaviour
{
public GUIText GuiText;
public void UpdateText(float time)
{
if (time <= 0f)
{
GuiText.text = "Swap";
}
else
{
GuiText.text = time.ToString("0.0");
}
}
}
| {
"content_hash": "cbca5e19d7693c9fb8a59ce36cf04ab2",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 48,
"avg_line_length": 17.894736842105264,
"alnum_prop": 0.5323529411764706,
"repo_name": "alvin319/Nucleatron",
"id": "59b012b0faf6bf84852d57083ce618cbf9ea5cb2",
"size": "342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/SwapCoolDownUpdate.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "336407"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hbase.util;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import com.google.common.annotations.VisibleForTesting;
/**
* The basic building block for the {@link org.apache.hadoop.hbase.io.hfile.CompoundBloomFilter}
*/
@InterfaceAudience.Private
public class BloomFilterChunk implements BloomFilterBase {
/** Bytes (B) in the array. This actually has to fit into an int. */
protected long byteSize;
/** Number of hash functions */
protected int hashCount;
/** Hash type */
protected final int hashType;
/** Hash Function */
protected final Hash hash;
/** Keys currently in the bloom */
protected int keyCount;
/** Max Keys expected for the bloom */
protected int maxKeys;
/** Bloom bits */
protected ByteBuffer bloom;
/**
* Loads bloom filter meta data from file input.
* @param meta stored bloom meta data
* @throws IllegalArgumentException meta data is invalid
*/
public BloomFilterChunk(DataInput meta)
throws IOException, IllegalArgumentException {
this.byteSize = meta.readInt();
this.hashCount = meta.readInt();
this.hashType = meta.readInt();
this.keyCount = meta.readInt();
this.maxKeys = this.keyCount;
this.hash = Hash.getInstance(this.hashType);
if (hash == null) {
throw new IllegalArgumentException("Invalid hash type: " + hashType);
}
sanityCheck();
}
/**
* Computes the error rate for this Bloom filter, taking into account the
* actual number of hash functions and keys inserted. The return value of
* this function changes as a Bloom filter is being populated. Used for
* reporting the actual error rate of compound Bloom filters when writing
* them out.
*
* @return error rate for this particular Bloom filter
*/
public double actualErrorRate() {
return BloomFilterUtil.actualErrorRate(keyCount, byteSize * 8, hashCount);
}
public BloomFilterChunk(int hashType) {
this.hashType = hashType;
this.hash = Hash.getInstance(hashType);
}
/**
* Determines & initializes bloom filter meta data from user config. Call
* {@link #allocBloom()} to allocate bloom filter data.
*
* @param maxKeys Maximum expected number of keys that will be stored in this
* bloom
* @param errorRate Desired false positive error rate. Lower rate = more
* storage required
* @param hashType Type of hash function to use
* @param foldFactor When finished adding entries, you may be able to 'fold'
* this bloom to save space. Tradeoff potentially excess bytes in
* bloom for ability to fold if keyCount is exponentially greater
* than maxKeys.
* @throws IllegalArgumentException
*/
public BloomFilterChunk(int maxKeys, double errorRate, int hashType,
int foldFactor) throws IllegalArgumentException {
this(hashType);
long bitSize = BloomFilterUtil.computeBitSize(maxKeys, errorRate);
hashCount = BloomFilterUtil.optimalFunctionCount(maxKeys, bitSize);
this.maxKeys = maxKeys;
// increase byteSize so folding is possible
byteSize = BloomFilterUtil.computeFoldableByteSize(bitSize, foldFactor);
sanityCheck();
}
/**
* Creates another similar Bloom filter. Does not copy the actual bits, and
* sets the new filter's key count to zero.
*
* @return a Bloom filter with the same configuration as this
*/
public BloomFilterChunk createAnother() {
BloomFilterChunk bbf = new BloomFilterChunk(hashType);
bbf.byteSize = byteSize;
bbf.hashCount = hashCount;
bbf.maxKeys = maxKeys;
return bbf;
}
public void allocBloom() {
if (this.bloom != null) {
throw new IllegalArgumentException("can only create bloom once.");
}
this.bloom = ByteBuffer.allocate((int)this.byteSize);
assert this.bloom.hasArray();
}
void sanityCheck() throws IllegalArgumentException {
if(0 >= this.byteSize || this.byteSize > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Invalid byteSize: " + this.byteSize);
}
if(this.hashCount <= 0) {
throw new IllegalArgumentException("Hash function count must be > 0");
}
if (this.hash == null) {
throw new IllegalArgumentException("hashType must be known");
}
if (this.keyCount < 0) {
throw new IllegalArgumentException("must have positive keyCount");
}
}
void bloomCheck(ByteBuffer bloom) throws IllegalArgumentException {
if (this.byteSize != bloom.limit()) {
throw new IllegalArgumentException(
"Configured bloom length should match actual length");
}
}
public void add(byte [] buf) {
add(buf, 0, buf.length);
}
public void add(byte [] buf, int offset, int len) {
/*
* For faster hashing, use combinatorial generation
* http://www.eecs.harvard.edu/~kirsch/pubs/bbbf/esa06.pdf
*/
int hash1 = this.hash.hash(buf, offset, len, 0);
int hash2 = this.hash.hash(buf, offset, len, hash1);
for (int i = 0; i < this.hashCount; i++) {
long hashLoc = Math.abs((hash1 + i * hash2) % (this.byteSize * 8));
set(hashLoc);
}
++this.keyCount;
}
@VisibleForTesting
boolean contains(byte [] buf) {
return contains(buf, 0, buf.length, this.bloom);
}
@VisibleForTesting
boolean contains(byte [] buf, int offset, int length) {
return contains(buf, offset, length, bloom);
}
@VisibleForTesting
boolean contains(byte[] buf, ByteBuffer bloom) {
return contains(buf, 0, buf.length, bloom);
}
public boolean contains(byte[] buf, int offset, int length, ByteBuffer theBloom) {
if (theBloom == null) {
theBloom = bloom;
}
if (theBloom.limit() != byteSize) {
throw new IllegalArgumentException("Bloom does not match expected size:"
+ " theBloom.limit()=" + theBloom.limit() + ", byteSize=" + byteSize);
}
return BloomFilterUtil.contains(buf, offset, length, theBloom, 0, (int) byteSize, hash,
hashCount);
}
//---------------------------------------------------------------------------
/** Private helpers */
/**
* Set the bit at the specified index to 1.
*
* @param pos index of bit
*/
void set(long pos) {
int bytePos = (int)(pos / 8);
int bitPos = (int)(pos % 8);
byte curByte = bloom.get(bytePos);
curByte |= BloomFilterUtil.bitvals[bitPos];
bloom.put(bytePos, curByte);
}
/**
* Check if bit at specified index is 1.
*
* @param pos index of bit
* @return true if bit at specified index is 1, false if 0.
*/
static boolean get(int pos, ByteBuffer bloomBuf, int bloomOffset) {
int bytePos = pos >> 3; //pos / 8
int bitPos = pos & 0x7; //pos % 8
// TODO access this via Util API which can do Unsafe access if possible(?)
byte curByte = bloomBuf.get(bloomOffset + bytePos);
curByte &= BloomFilterUtil.bitvals[bitPos];
return (curByte != 0);
}
@Override
public long getKeyCount() {
return keyCount;
}
@Override
public long getMaxKeys() {
return maxKeys;
}
@Override
public long getByteSize() {
return byteSize;
}
public int getHashType() {
return hashType;
}
public void compactBloom() {
// see if the actual size is exponentially smaller than expected.
if (this.keyCount > 0 && this.bloom.hasArray()) {
int pieces = 1;
int newByteSize = (int)this.byteSize;
int newMaxKeys = this.maxKeys;
// while exponentially smaller & folding is lossless
while ((newByteSize & 1) == 0 && newMaxKeys > (this.keyCount<<1)) {
pieces <<= 1;
newByteSize >>= 1;
newMaxKeys >>= 1;
}
// if we should fold these into pieces
if (pieces > 1) {
byte[] array = this.bloom.array();
int start = this.bloom.arrayOffset();
int end = start + newByteSize;
int off = end;
for(int p = 1; p < pieces; ++p) {
for(int pos = start; pos < end; ++pos) {
array[pos] |= array[off++];
}
}
// folding done, only use a subset of this array
this.bloom.rewind();
this.bloom.limit(newByteSize);
this.bloom = this.bloom.slice();
this.byteSize = newByteSize;
this.maxKeys = newMaxKeys;
}
}
}
/**
* Writes just the bloom filter to the output array
* @param out OutputStream to place bloom
* @throws IOException Error writing bloom array
*/
public void writeBloom(final DataOutput out)
throws IOException {
if (!this.bloom.hasArray()) {
throw new IOException("Only writes ByteBuffer with underlying array.");
}
out.write(this.bloom.array(), this.bloom.arrayOffset(), this.bloom.limit());
}
public int getHashCount() {
return hashCount;
}
@Override
public String toString() {
return BloomFilterUtil.toString(this);
}
}
| {
"content_hash": "d3600e9c19d903a7bbce7469c4460e46",
"timestamp": "",
"source": "github",
"line_count": 305,
"max_line_length": 96,
"avg_line_length": 29.550819672131148,
"alnum_prop": 0.6503938755131476,
"repo_name": "SeekerResource/hbase",
"id": "9fff87256ffb4ca3d7ad38ba6fd0678bc9722386",
"size": "9821",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hbase-server/src/main/java/org/apache/hadoop/hbase/util/BloomFilterChunk.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "351"
},
{
"name": "Batchfile",
"bytes": "24335"
},
{
"name": "C",
"bytes": "28534"
},
{
"name": "C++",
"bytes": "770077"
},
{
"name": "CMake",
"bytes": "10933"
},
{
"name": "CSS",
"bytes": "68278"
},
{
"name": "HTML",
"bytes": "70903"
},
{
"name": "Java",
"bytes": "26780919"
},
{
"name": "JavaScript",
"bytes": "2694"
},
{
"name": "Makefile",
"bytes": "1409"
},
{
"name": "PHP",
"bytes": "413443"
},
{
"name": "Perl",
"bytes": "383793"
},
{
"name": "Protocol Buffer",
"bytes": "147894"
},
{
"name": "Python",
"bytes": "539649"
},
{
"name": "Ruby",
"bytes": "512225"
},
{
"name": "Shell",
"bytes": "203386"
},
{
"name": "Thrift",
"bytes": "39996"
},
{
"name": "XSLT",
"bytes": "2892"
}
],
"symlink_target": ""
} |
require 'state_machine'
class User < ActiveRecord::Base
include User::Completeness
include Shared::LocationHandler
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :lockable, :timeoutable and :omniauthable
# :validatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :omniauthable, :confirmable
# begin
# sync_with_mailchimp subscribe_data: ->(user) { { EMAIL: user.email, NAME: user.display_name } },
# list_id: Configuration[:mailchimp_list_id],
# subscribe_when: ->(user) { (user.newsletter_changed? && user.newsletter) || (user.newsletter && user.new_record?) },
# unsubscribe_when: ->(user) { user.newsletter_changed? && !user.newsletter },
# unsubscribe_email: ->(user) { user.email }
# rescue Exception => e
# Rails.logger.info "-----> #{e.inspect}"
# end
delegate :display_name, :display_image, :short_name, :display_image_html,
:medium_name, :display_credits, :display_total_of_contributions, :first_name, :last_name, :gravatar_url,
to: :decorator
mount_uploader :uploaded_image, UserUploader, mount_on: :uploaded_image
validates_length_of :bio, maximum: 140
validates_presence_of :email
validates_uniqueness_of :email, :allow_blank => true, :if => :email_changed?, :message => I18n.t('activerecord.errors.models.user.attributes.email.taken')
validates_format_of :email, :with => Devise.email_regexp, :allow_blank => true, :if => :email_changed?
validates_presence_of :password, :if => :password_required?
validates_confirmation_of :password, :if => :password_confirmation_required?
validates_length_of :password, :within => Devise.password_length, :allow_blank => true
has_many :contributions
has_many :projects
has_many :notifications
has_many :updates
has_many :unsubscribes
has_many :authorizations
has_many :oauth_providers, through: :authorizations
has_many :channels_subscribers
has_one :user_total
has_and_belongs_to_many :subscriptions, join_table: :channels_subscribers, class_name: 'Channel'
has_one :channel
has_one :organization, dependent: :destroy
has_many :channel_members, dependent: :destroy
has_many :channels, through: :channel_members, source: :channel
has_and_belongs_to_many :recommended_projects, join_table: :recommendations, class_name: 'Project'
has_many :endorsements
accepts_nested_attributes_for :authorizations
accepts_nested_attributes_for :channel
accepts_nested_attributes_for :organization
accepts_nested_attributes_for :unsubscribes, allow_destroy: true rescue puts "No association found for name 'unsubscribes'. Has it been defined yet?"
scope :contributions, -> {
where("id IN (
SELECT DISTINCT user_id
FROM contributions
WHERE contributions.state <> ALL(ARRAY['pending'::character varying::text, 'canceled'::character varying::text]))")
}
scope :who_contributed_project, ->(project_id) {
where("id IN (SELECT user_id FROM contributions WHERE contributions.state = 'confirmed' AND project_id = ?)", project_id)
}
scope :subscribed_to_updates, -> {
where("id NOT IN (
SELECT user_id
FROM unsubscribes
WHERE project_id IS NULL)")
}
scope :subscribed_to_project, ->(project_id) {
who_contributed_project(project_id).
where("id NOT IN (SELECT user_id FROM unsubscribes WHERE project_id = ?)", project_id)
}
scope :by_email, ->(email){ where('email ~* ?', email) }
scope :by_payer_email, ->(email) {
where('EXISTS(
SELECT true
FROM contributions
JOIN payment_notifications ON contributions.id = payment_notifications.contribution_id
WHERE contributions.user_id = users.id AND payment_notifications.extra_data ~* ?)', email)
}
scope :by_name, ->(name){ where('users.name ~* ?', name) }
scope :by_id, ->(id){ where(id: id) }
scope :by_key, ->(key){ where('EXISTS(SELECT true FROM contributions WHERE contributions.user_id = users.id AND contributions.key ~* ?)', key) }
scope :has_credits, -> { joins(:user_total).where('user_totals.credits > 0') }
scope :has_not_used_credits_last_month, -> { has_credits.
where("NOT EXISTS (SELECT true FROM contributions b WHERE current_timestamp - b.created_at < '1 month'::interval AND b.credits AND b.state = 'confirmed' AND b.user_id = users.id)")
}
scope :order_by, ->(sort_field){ order(sort_field) }
state_machine :profile_type, initial: :personal do
state :personal, value: 'personal'
state :organization, value: 'organization'
state :channel, value: 'channel'
end
def self.send_credits_notification
has_not_used_credits_last_month.find_each do |user|
Notification.notify_once(
:credits_warning,
user,
{user_id: user.id}
)
end
end
def self.contribution_totals
connection.select_one(
self.all.
joins(:user_total).
select('
count(DISTINCT user_id) as users,
count(*) as contributions,
sum(user_totals.sum) as contributed,
sum(user_totals.credits) as credits').
to_sql
).reduce({}){|memo,el| memo.merge({ el[0].to_sym => BigDecimal.new(el[1] || '0') }) }
end
def decorator
@decorator ||= UserDecorator.new(self)
end
def credits
user_total ? user_total.credits : 0.0
end
def total_contributed_projects
user_total ? user_total.total_contributed_projects : 0
end
def facebook_id
auth = authorizations.joins(:oauth_provider).where("oauth_providers.name = 'facebook'").first
auth.uid if auth
end
def to_param
return "#{self.id}" unless self.display_name
"#{self.id}-#{self.display_name.parameterize}"
end
def total_contributions
contributions.with_state('confirmed').not_anonymous.count
end
def updates_subscription
unsubscribes.updates_unsubscribe(nil)
end
def project_unsubscribes
contributed_projects.map do |p|
unsubscribes.updates_unsubscribe(p.id)
end
end
def projects_led
projects.visible.not_soon
end
def total_led
projects_led.count
end
def contributed_projects
Project.contributed_by(self.id)
end
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
def password_confirmation_required?
!new_record?
end
def confirmation_required?
!confirmed? and not (authorizations.first and authorizations.first.oauth_provider == OauthProvider.where(name: 'facebook').first)
end
end
| {
"content_hash": "a21220a4d6d2c2a148c6dfabcb170951",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 184,
"avg_line_length": 35.25668449197861,
"alnum_prop": 0.6828454421355984,
"repo_name": "raksonibs/raimcrowd",
"id": "1c0a49d17b854466e7c14f8eb2ef63f24d8753e1",
"size": "6609",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/user.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "110095"
},
{
"name": "CoffeeScript",
"bytes": "47590"
},
{
"name": "HTML",
"bytes": "219651"
},
{
"name": "JavaScript",
"bytes": "238203"
},
{
"name": "Ruby",
"bytes": "666017"
},
{
"name": "Shell",
"bytes": "106"
}
],
"symlink_target": ""
} |
import os
from mongrey.migration import radicalspam
from ..base import RESOURCE_DIR
RS_MIGRATION_DIR = os.path.abspath(os.path.join(RESOURCE_DIR, 'rs-3.5.4-postfix-migration'))
def get_resource_path(filename):
return os.path.abspath(os.path.join(RS_MIGRATION_DIR, filename))
class RSMigrationTestCaseMixin:
def _check_resources(self):
resources = [
'local-relays.dbhash',
'local-directory.dbhash',
'local-exceptions-directory.dbhash',
'local-mynetworks-lan.dbhash',
'local-mynetworks-wan.dbhash',
'local-blacklist-clients.dbhash',
'local-blacklist-senders.dbhash',
'local-blacklist-recipients.dbhash',
]
for r in resources:
filepath = get_resource_path(r)
if not os.path.exists(filepath):
self.fail("resource not found in tests : %s" % filepath)
def _test_import_domains(self, models):
filepath = get_resource_path('local-relays.dbhash')
result = radicalspam.import_domains(filepath=filepath, model_klass=models.Domain)
self.assertDictEqual(result, dict(success=1, error=0, error_messages=[]))
def _test_import_mailboxs(self, models):
filepath = get_resource_path('local-directory.dbhash')
result = radicalspam.import_mailboxs(filepath=filepath, model_klass=models.Mailbox)
self.assertEquals(result['success'], 2)
self.assertEquals(result['error'], 1)
self.assertEquals(len(result['error_messages']), 1)
filepath = get_resource_path('local-exceptions-directory.dbhash')
result = radicalspam.import_mailboxs_exceptions(filepath=filepath, model_klass=models.Mailbox)
self.assertDictEqual(result, dict(success=1, error=0, error_messages=[]))
def _test_import_mynetworks(self, models):
filepath = get_resource_path('local-mynetworks-lan.dbhash')
result = radicalspam.import_mynetworks_lan(filepath=filepath, model_klass=models.Mynetwork)
self.assertDictEqual(result, dict(success=2, error=0, error_messages=[]))
filepath = get_resource_path('local-mynetworks-wan.dbhash')
result = radicalspam.import_mynetworks_wan(filepath=filepath, model_klass=models.Mynetwork)
self.assertEquals(result['success'], 1)
self.assertEquals(result['error'], 1)
self.assertEquals(len(result['error_messages']), 1)
def _test_import_blacklist_clients(self, models):
filepath = get_resource_path('local-blacklist-clients.dbhash')
result = radicalspam.import_blacklist_clients(filepath=filepath, model_klass=models.BlackList)
self.assertDictEqual(result, dict(success=1, error=0, error_messages=[]))
def _test_import_blacklist_senders(self, models):
filepath = get_resource_path('local-blacklist-senders.dbhash')
result = radicalspam.import_blacklist_senders(filepath=filepath, model_klass=models.BlackList)
self.assertDictEqual(result, dict(success=2, error=0, error_messages=[]))
def _test_import_blacklist_recipients(self, models):
filepath = get_resource_path('local-blacklist-recipients.dbhash')
result = radicalspam.import_blacklist_recipients(filepath=filepath, model_klass=models.BlackList)
self.assertDictEqual(result, dict(success=1, error=0, error_messages=[]))
| {
"content_hash": "483b4a7796bc54f6b403ae8b7239899d",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 105,
"avg_line_length": 47.125,
"alnum_prop": 0.6837606837606838,
"repo_name": "radical-software/mongrey",
"id": "7be41c46f2fcd9a2644dcac0f6749a25d5592f1f",
"size": "3418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mongrey/tests/migration/test_migration_rs.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "755370"
},
{
"name": "HTML",
"bytes": "676261"
},
{
"name": "Python",
"bytes": "353769"
},
{
"name": "Shell",
"bytes": "3450"
}
],
"symlink_target": ""
} |
package org.diirt.datasource;
import java.util.ArrayList;
import java.util.List;
/**
* A function that takes many inputs and creates a list with them.
*
* @author carcassi
*/
class ListOfFunction implements ReadFunction<List> {
List<ReadFunction> functions;
public ListOfFunction(List<ReadFunction> functions) {
this.functions = functions;
}
@Override
@SuppressWarnings("unchecked")
public List readValue() {
List list = new ArrayList();
for (ReadFunction function : functions) {
list.add(function.readValue());
}
return list;
}
}
| {
"content_hash": "d54980c8b94db3e7252779b14ea85436",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 66,
"avg_line_length": 20.733333333333334,
"alnum_prop": 0.6527331189710611,
"repo_name": "berryma4/diirt",
"id": "382ab8051c745d74bbf2ba57f2cea02277cd2c61",
"size": "763",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "pvmanager/datasource/src/main/java/org/diirt/datasource/ListOfFunction.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "314"
},
{
"name": "CSS",
"bytes": "75261"
},
{
"name": "GAP",
"bytes": "5847"
},
{
"name": "HTML",
"bytes": "423157"
},
{
"name": "Java",
"bytes": "4747777"
},
{
"name": "JavaScript",
"bytes": "1745584"
},
{
"name": "Shell",
"bytes": "3095"
}
],
"symlink_target": ""
} |
namespace LV
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Text = "Form1";
}
#endregion
}
}
| {
"content_hash": "29fd42fbd4c3086576a91ca5eee45264",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 107,
"avg_line_length": 28.846153846153847,
"alnum_prop": 0.5528888888888889,
"repo_name": "timbodv/lv",
"id": "0d538b76b61e2831091187a80209699857141dc5",
"size": "1127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Form1.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "6020"
},
{
"name": "PowerShell",
"bytes": "249"
}
],
"symlink_target": ""
} |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.FolderBinding", Namespace="urn:iControl")]
public partial class ManagementFolder : iControlInterface {
public ManagementFolder() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void create(
string [] folders
) {
this.Invoke("create", new object [] {
folders});
}
public System.IAsyncResult Begincreate(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
folders}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_folders
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void delete_all_folders(
) {
this.Invoke("delete_all_folders", new object [0]);
}
public System.IAsyncResult Begindelete_all_folders(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_folders", new object[0], callback, asyncState);
}
public void Enddelete_all_folders(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_folder
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void delete_folder(
string [] folders
) {
this.Invoke("delete_folder", new object [] {
folders});
}
public System.IAsyncResult Begindelete_folder(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_folder", new object[] {
folders}, callback, asyncState);
}
public void Enddelete_folder(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] folders
) {
object [] results = this.Invoke("get_description", new object [] {
folders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
folders}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_device_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_device_group(
string [] folders
) {
object [] results = this.Invoke("get_device_group", new object [] {
folders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_device_group(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_device_group", new object[] {
folders}, callback, asyncState);
}
public string [] Endget_device_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_no_reference_check_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_no_reference_check_state(
string [] folders
) {
object [] results = this.Invoke("get_no_reference_check_state", new object [] {
folders});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_no_reference_check_state(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_no_reference_check_state", new object[] {
folders}, callback, asyncState);
}
public CommonEnabledState [] Endget_no_reference_check_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_traffic_group(
string [] folders
) {
object [] results = this.Invoke("get_traffic_group", new object [] {
folders});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_traffic_group(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_traffic_group", new object[] {
folders}, callback, asyncState);
}
public string [] Endget_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_device_group_inherited
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_device_group_inherited(
string [] folders
) {
object [] results = this.Invoke("is_device_group_inherited", new object [] {
folders});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_device_group_inherited(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_device_group_inherited", new object[] {
folders}, callback, asyncState);
}
public bool [] Endis_device_group_inherited(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// is_traffic_group_inherited
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_traffic_group_inherited(
string [] folders
) {
object [] results = this.Invoke("is_traffic_group_inherited", new object [] {
folders});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_traffic_group_inherited(string [] folders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_traffic_group_inherited", new object[] {
folders}, callback, asyncState);
}
public bool [] Endis_traffic_group_inherited(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void set_description(
string [] folders,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
folders,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] folders,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
folders,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_device_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void set_device_group(
string [] folders,
string [] groups
) {
this.Invoke("set_device_group", new object [] {
folders,
groups});
}
public System.IAsyncResult Beginset_device_group(string [] folders,string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_device_group", new object[] {
folders,
groups}, callback, asyncState);
}
public void Endset_device_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_no_reference_check_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void set_no_reference_check_state(
string [] folders,
CommonEnabledState [] states
) {
this.Invoke("set_no_reference_check_state", new object [] {
folders,
states});
}
public System.IAsyncResult Beginset_no_reference_check_state(string [] folders,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_no_reference_check_state", new object[] {
folders,
states}, callback, asyncState);
}
public void Endset_no_reference_check_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_traffic_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Folder",
RequestNamespace="urn:iControl:Management/Folder", ResponseNamespace="urn:iControl:Management/Folder")]
public void set_traffic_group(
string [] folders,
string [] groups
) {
this.Invoke("set_traffic_group", new object [] {
folders,
groups});
}
public System.IAsyncResult Beginset_traffic_group(string [] folders,string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_traffic_group", new object[] {
folders,
groups}, callback, asyncState);
}
public void Endset_traffic_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| {
"content_hash": "b0cccb2e41b55958065cfae116cbe31c",
"timestamp": "",
"source": "github",
"line_count": 355,
"max_line_length": 161,
"avg_line_length": 42.96619718309859,
"alnum_prop": 0.6129286042090081,
"repo_name": "F5Networks/f5-icontrol-library-dotnet",
"id": "ad53d35d30e9bb62c1a58329c465af1e768718bd",
"size": "15253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iControl/Interfaces/Management/ManagementFolder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "16922"
},
{
"name": "C#",
"bytes": "10827739"
}
],
"symlink_target": ""
} |
/**
* \file ConstDataBuffer.h
* \author Jason Fernandez
* \date 4/19/2018
*
* https://github.com/jfern2011/io_tools
*/
#ifndef __CONST_DATA_BUFFER_H__
#define __CONST_DATA_BUFFER_H__
#include <cstddef>
namespace net
{
/**
* A convenience class for handling a fixed-size buffer by
* wrapping a pointer, size pair into a single class.
* Note that this class does not manage the buffer at all,
* e.g. no dynamic memory operations are performed
*/
class ConstDataBuffer
{
public:
ConstDataBuffer();
ConstDataBuffer(const char* buf,size_t size);
~ConstDataBuffer();
explicit operator bool() const;
void clear();
const char* get() const;
const char& operator[]( size_t index ) const;
void reset(const char* buf, size_t size);
size_t size() const;
private:
/**
* The internal data buffer
*/
const char* _buf;
/**
* The buffer size (bytes)
*/
size_t _size;
};
}
#endif
| {
"content_hash": "fc9cf81f9e6cfaf308927e9d65086b14",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 59,
"avg_line_length": 16.033898305084747,
"alnum_prop": 0.645877378435518,
"repo_name": "jfern2011/chess",
"id": "4ef65fddde0d23f60642eb6501363ea896b281b4",
"size": "946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "io_tools/udp/ConstDataBuffer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1808227"
},
{
"name": "CMake",
"bytes": "2894"
},
{
"name": "CSS",
"bytes": "18889"
},
{
"name": "HTML",
"bytes": "95563"
},
{
"name": "JavaScript",
"bytes": "28785"
},
{
"name": "Makefile",
"bytes": "4891"
},
{
"name": "Starlark",
"bytes": "3488"
}
],
"symlink_target": ""
} |
import { connect } from 'react-redux';
import CheckAuth from 'components/CheckAuth';
import { loginUser, registerUser } from 'actions/login';
import { updateMessage } from 'actions/snackbarMessage';
function mapStateToProps(store) {
return {
user: store.user || '',
snackbarMessage: store.snackbarMessage || '',
};
}
function mapDispatchToProps(dispatch) {
return {
login: (username, message) => dispatch(loginUser(username, message)),
register: username => dispatch(registerUser(username)),
snackbarMessageEdit: message => dispatch(updateMessage(message)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CheckAuth);
| {
"content_hash": "223fcea9251cfd6fdc170dd458c6ce9d",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 73,
"avg_line_length": 31.714285714285715,
"alnum_prop": 0.7312312312312312,
"repo_name": "CaptainGlac1er/StudentHomeworkProject",
"id": "158846390b33fe01290d26185fa096b23bcbcb85",
"size": "666",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/js/containers/CheckAuth.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "100"
},
{
"name": "HTML",
"bytes": "622"
},
{
"name": "JavaScript",
"bytes": "39045"
}
],
"symlink_target": ""
} |
package com.ifly.transporter.utils;
public class RedisUtil {
/**redis模块划分*/
//验证码模块
public static String Redis_Captcha ="captcha";
/**获取key值*/
public static String getCaptchaKey(String key){
return Redis_Captcha+":"+key;
}
}
| {
"content_hash": "67aea166497ab888b60cce8acfed7449",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 48,
"avg_line_length": 20.75,
"alnum_prop": 0.6746987951807228,
"repo_name": "zhangyiran0314/transporter",
"id": "b1ae901b265aa498c03402b8fc1188f2dfcd579a",
"size": "273",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/ifly/transporter/utils/RedisUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "20249"
},
{
"name": "HTML",
"bytes": "21531"
},
{
"name": "Java",
"bytes": "175583"
},
{
"name": "JavaScript",
"bytes": "56697"
}
],
"symlink_target": ""
} |
<?php
namespace Kunstmaan\AdminBundle\Helper\FormWidgets\Tabs;
use Doctrine\ORM\EntityManager;
use Kunstmaan\UtilitiesBundle\Helper\Slugifier;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\Request;
/**
* A tab pane is a container which holds tabs
*/
class TabPane
{
/**
* @var string
*/
protected $identifier;
/**
* @var TabInterface[]
*/
protected $tabs = [];
/**
* @var string
*/
protected $activeTab;
/**
* @var FormFactoryInterface
*/
protected $formFactory;
/**
* @var Form
*/
protected $form;
/**
* @var FormView
*/
protected $formView;
/** @var Slugifier */
private $slugifier;
/**
* @param string $identifier The identifier
* @param Request $request The request
* @param FormFactoryInterface $formFactory The form factory
*/
public function __construct($identifier, Request $request, FormFactoryInterface $formFactory)
{
$this->identifier = $identifier;
$this->formFactory = $formFactory;
$this->slugifier = new Slugifier();
if ($request->request->get('currenttab')) {
$this->activeTab = $request->request->get('currenttab');
} elseif ($request->get('currenttab')) {
$this->activeTab = $request->get('currenttab');
}
}
/**
* @return FormInterface
*/
public function buildForm()
{
$builder = $this->formFactory->createBuilder(FormType::class, null);
foreach ($this->tabs as $tab) {
$tab->buildForm($builder);
}
$this->form = $builder->getForm();
return $this->form;
}
public function bindRequest(Request $request)
{
$this->form->handleRequest($request);
foreach ($this->tabs as $tab) {
$tab->bindRequest($request);
}
}
/**
* @param EntityManager $em The entity manager
*/
public function persist(EntityManager $em)
{
foreach ($this->tabs as $tab) {
$tab->persist($em);
}
}
private function generateIdentifier(TabInterface $tab): string
{
return $this->slugifier->slugify($tab->getTitle());
}
/**
* @param TabInterface $tab The tab
* @param int|null $position The position
*
* @return TabPane
*/
public function addTab(TabInterface $tab, $position = null)
{
$identifier = $tab->getIdentifier();
if (!$identifier || empty($identifier)) {
$tab->setIdentifier($this->generateIdentifier($tab));
}
if (!\is_null($position) && is_numeric($position) && $position < \count($this->tabs)) {
array_splice($this->tabs, $position, 0, [$tab]);
} else {
$this->tabs[] = $tab;
}
return $this;
}
/**
* @return TabPane
*/
public function removeTab(TabInterface $tab)
{
if (\in_array($tab, $this->tabs)) {
unset($this->tabs[array_search($tab, $this->tabs)]);
$this->reindexTabs();
}
return $this;
}
/**
* @param string $title
*
* @return TabPane
*/
public function removeTabByTitle($title)
{
foreach ($this->tabs as $key => $tab) {
if ($tab->getTitle() === $title) {
unset($this->tabs[$key]);
$this->reindexTabs();
return $this;
}
}
return $this;
}
/**
* @param int $position
*
* @return TabPane
*/
public function removeTabByPosition($position)
{
if (is_numeric($position) && $position < \count($this->tabs)) {
array_splice($this->tabs, $position, 1);
}
return $this;
}
/**
* @return TabInterface[]
*/
public function getTabs()
{
return $this->tabs;
}
/**
* @param string $title
*
* @return TabInterface|null
*/
public function getTabByTitle($title)
{
foreach ($this->tabs as $key => $tab) {
if ($tab->getTitle() === $title) {
return $this->tabs[$key];
}
}
return null;
}
/**
* @param int $position
*
* @return TabInterface|null
*/
public function getTabByPosition($position)
{
if (is_numeric($position) && $position < \count($this->tabs)) {
return $this->tabs[$position];
}
return null;
}
/**
* @return string
*/
public function getActiveTab()
{
return !empty($this->activeTab) ? $this->activeTab : $this->tabs[0]->getIdentifier();
}
/**
* @return Form
*/
public function getForm()
{
return $this->form;
}
/**
* @return FormView
*/
public function getFormView()
{
if (\is_null($this->formView)) {
$this->formView = $this->form->createView();
}
return $this->formView;
}
/**
* @return bool
*/
public function isValid()
{
return $this->form->isValid();
}
/**
* Reset the indexes of the tabs
*/
private function reindexTabs()
{
$this->tabs = array_values($this->tabs);
}
/**
* @return array
*/
public function getExtraParams(Request $request)
{
$extraParams = [];
foreach ($this->getTabs() as $tab) {
$extraParams = array_merge($extraParams, $tab->getExtraParams($request));
}
return $extraParams;
}
}
| {
"content_hash": "4fd5258f7a1e76a45de3c0966ce9bbb6",
"timestamp": "",
"source": "github",
"line_count": 272,
"max_line_length": 97,
"avg_line_length": 21.658088235294116,
"alnum_prop": 0.5252079443218469,
"repo_name": "insiders/KunstmaanBundlesCMS",
"id": "442ed344790a5fb6576e439c99fe2b8404182a7c",
"size": "5891",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Kunstmaan/AdminBundle/Helper/FormWidgets/Tabs/TabPane.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "25520"
},
{
"name": "Gherkin",
"bytes": "22178"
},
{
"name": "HTML",
"bytes": "17762"
},
{
"name": "Hack",
"bytes": "1158"
},
{
"name": "Handlebars",
"bytes": "11544"
},
{
"name": "JavaScript",
"bytes": "747840"
},
{
"name": "PHP",
"bytes": "3771771"
},
{
"name": "SCSS",
"bytes": "278232"
},
{
"name": "Shell",
"bytes": "806"
},
{
"name": "Twig",
"bytes": "484600"
}
],
"symlink_target": ""
} |
import './StageInfo.css';
import { Component } from 'react';
import * as React from 'react';
import cardsNeeded from '../store/cardsNeeded';
class StageInfo extends Component<any, any> {
constructor(props: any, context: any) {
super(props, context);
this.state = {
showContinue: false
};
}
numSelected(cards: any) {
return cards.filter((c: any) => c.mark === this.props.stage).length;
}
numNeeded(cards: any) {
return Math.floor(cards.length / 2);
}
componentWillReceiveProps(nextProps: any) {
// The first time we pass the threshhold, show the continue button.
if (this.state.showContinue) {
if (this.props.stage !== nextProps.stage) {
this.setState({
showContinue: false
});
}
} else {
const numSelected = this.numSelected(nextProps.cards);
const needed = cardsNeeded(nextProps.stage);
if (numSelected >= needed) {
this.setState({
showContinue: true
});
}
}
}
onAdvance = (e: any) => {
e.stopPropagation();
if (this.props.onAdvanceStage) {
this.props.onAdvanceStage(this.props.stage);
}
}
render() {
const numSelected = this.numSelected(this.props.cards);
const needed = cardsNeeded(this.props.stage);
const canAdvance = numSelected === needed;
const tooMany = numSelected > needed;
return (
<div className={'StageInfo ' + this.props.className}>
<h2 className="StageInfo--stage">Round {this.props.stage}</h2>
{ this.state.showContinue ? (
<div
className={'btn StageInfo--btn-continue' + (canAdvance ? '' : ' disabled')}
onClick={canAdvance ? this.onAdvance : undefined}
>
Continue
</div>
) : (
<h1 className="StageInfo--instructions">Select <b>{needed}</b> cards to continue</h1>
)}
<h2 className="StageInfo--progress">
<span
className={'number-selected' + (tooMany ? ' over' : '')}
key={numSelected}
>{numSelected}
</span> / {needed}
</h2>
</div>
);
}
}
namespace StageInfo {
export const defaultProps = {
className: ''
};
}
export default StageInfo;
| {
"content_hash": "1ffa66b7ac07a8e8b43ddef80a05f944",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 95,
"avg_line_length": 26.313953488372093,
"alnum_prop": 0.5815289438798056,
"repo_name": "flubstep/engvalues",
"id": "a24029ed1eeaf7e9fb2d4a8f950552c0472ffed9",
"size": "2263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/StageInfo.tsx",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4671"
},
{
"name": "HTML",
"bytes": "1162"
},
{
"name": "JavaScript",
"bytes": "50058"
},
{
"name": "TypeScript",
"bytes": "20192"
}
],
"symlink_target": ""
} |
from django.core.management.base import NoArgsCommand, BaseCommand
from ffclub.newsletter.utils import generate_newsletter
class Command(BaseCommand):
help = 'Generate Newsletter Static Page'
option_list = NoArgsCommand.option_list
def handle(self, *args, **options):
issue = args[0]
generate_newsletter(issue) | {
"content_hash": "40ac030af300b1ea155fb5a3f0dc0813",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 66,
"avg_line_length": 28.5,
"alnum_prop": 0.7368421052631579,
"repo_name": "elin-moco/ffclub",
"id": "583ab7da288ca43a807c43f33c8b7fbe3a841b1b",
"size": "366",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ffclub/newsletter/management/commands/gen_newsletter.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "326161"
},
{
"name": "HTML",
"bytes": "260715"
},
{
"name": "JavaScript",
"bytes": "359022"
},
{
"name": "Puppet",
"bytes": "6677"
},
{
"name": "Python",
"bytes": "559341"
},
{
"name": "Shell",
"bytes": "2294"
},
{
"name": "Smarty",
"bytes": "215"
}
],
"symlink_target": ""
} |
@implementation Wifts
@end
| {
"content_hash": "854671ac99d8741aaabceeabac09dd53",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 21,
"avg_line_length": 9.333333333333334,
"alnum_prop": 0.7857142857142857,
"repo_name": "tengyifei/wifts",
"id": "5c07e2ab4e44bb68109c3808ddbea9e30667eccb",
"size": "119",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Xcode/Wifts/Wifts.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "945"
},
{
"name": "Swift",
"bytes": "3499"
}
],
"symlink_target": ""
} |
package com.sop4j.dbutils;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Basic implementation of the <code>RowProcessor</code> interface.
*
* <p>
* This class is thread-safe.
* </p>
*
* @see RowProcessor
*/
public class BasicRowProcessor implements RowProcessor {
/**
* The default BeanProcessor instance to use if not supplied in the
* constructor.
*/
private static final BeanProcessor defaultConvert = new BeanProcessor();
/**
* Use this to process beans.
*/
private final BeanProcessor convert;
/**
* BasicRowProcessor constructor. Bean processing defaults to a
* BeanProcessor instance.
*/
public BasicRowProcessor() {
this(defaultConvert);
}
/**
* BasicRowProcessor constructor.
*
* @param convert The BeanProcessor to use when converting columns to bean properties.
* @since 1.1
*/
public BasicRowProcessor(BeanProcessor convert) {
super();
this.convert = convert;
}
/**
* Convert a <code>ResultSet</code> row into an <code>Object[]</code>.
* This implementation copies column values into the array in the same
* order they're returned from the <code>ResultSet</code>. Array elements
* will be set to <code>null</code> if the column was SQL NULL.
*
* @see com.sop4j.dbutils.RowProcessor#toArray(java.sql.ResultSet)
* @param rs ResultSet that supplies the array data
* @throws SQLException if a database access error occurs
* @return the newly created array
*/
@Override
public Object[] toArray(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Object[] result = new Object[cols];
for (int i = 0; i < cols; i++) {
result[i] = rs.getObject(i + 1);
}
return result;
}
/**
* Convert a <code>ResultSet</code> row into a JavaBean. This
* implementation delegates to a BeanProcessor instance.
*
* @see com.sop4j.dbutils.RowProcessor#toBean(java.sql.ResultSet, java.lang.Class)
* @see com.sop4j.dbutils.BeanProcessor#toBean(java.sql.ResultSet, java.lang.Class)
* @param <T> The type of bean to create
* @param rs ResultSet that supplies the bean data
* @param type Class from which to create the bean instance
* @throws SQLException if a database access error occurs
* @return the newly created bean
*/
@Override
public <T> T toBean(ResultSet rs, Class<T> type) throws SQLException {
return this.convert.toBean(rs, type);
}
/**
* Convert a <code>ResultSet</code> into a <code>List</code> of JavaBeans.
* This implementation delegates to a BeanProcessor instance.
*
* @see com.sop4j.dbutils.RowProcessor#toBeanList(java.sql.ResultSet, java.lang.Class)
* @see com.sop4j.dbutils.BeanProcessor#toBeanList(java.sql.ResultSet, java.lang.Class)
* @param <T> The type of bean to create
* @param rs ResultSet that supplies the bean data
* @param type Class from which to create the bean instance
* @throws SQLException if a database access error occurs
* @return A <code>List</code> of beans with the given type in the order
* they were returned by the <code>ResultSet</code>.
*/
@Override
public <T> List<T> toBeanList(ResultSet rs, Class<T> type) throws SQLException {
return this.convert.toBeanList(rs, type);
}
/**
* Convert a <code>ResultSet</code> row into a <code>Map</code>. This
* implementation returns a <code>Map</code> with case insensitive column
* names as keys. Calls to <code>map.get("COL")</code> and
* <code>map.get("col")</code> return the same value.
*
* @see com.sop4j.dbutils.RowProcessor#toMap(java.sql.ResultSet)
* @param rs ResultSet that supplies the map data
* @throws SQLException if a database access error occurs
* @return the newly created Map
*/
@Override
public Map<String, Object> toMap(ResultSet rs) throws SQLException {
Map<String, Object> result = new CaseInsensitiveHashMap();
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
for (int i = 1; i <= cols; i++) {
String columnName = rsmd.getColumnLabel(i);
if (null == columnName || 0 == columnName.length()) {
columnName = rsmd.getColumnName(i);
}
result.put(columnName, rs.getObject(i));
}
return result;
}
/**
* A Map that converts all keys to lowercase Strings for case insensitive
* lookups. This is needed for the toMap() implementation because
* databases don't consistently handle the casing of column names.
*
* <p>The keys are stored as they are given [BUG #DBUTILS-34], so we maintain
* an internal mapping from lowercase keys to the real keys in order to
* achieve the case insensitive lookup.
*
* <p>Note: This implementation does not allow <tt>null</tt>
* for key, whereas {@link HashMap} does, because of the code:
* <pre>
* key.toString().toLowerCase()
* </pre>
*/
private static class CaseInsensitiveHashMap extends HashMap<String, Object> {
/**
* The internal mapping from lowercase keys to the real keys.
*
* <p>
* Any query operation using the key
* ({@link #get(Object)}, {@link #containsKey(Object)})
* is done in three steps:
* <ul>
* <li>convert the parameter key to lower case</li>
* <li>get the actual key that corresponds to the lower case key</li>
* <li>query the map with the actual key</li>
* </ul>
* </p>
*/
private final Map<String, String> lowerCaseMap = new HashMap<String, String>();
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = -2848100435296897392L;
@Override
public boolean containsKey(Object key) {
Object realKey = lowerCaseMap.get(key.toString().toLowerCase(Locale.ENGLISH));
return super.containsKey(realKey);
// Possible optimisation here:
// Since the lowerCaseMap contains a mapping for all the keys,
// we could just do this:
// return lowerCaseMap.containsKey(key.toString().toLowerCase());
}
@Override
public Object get(Object key) {
Object realKey = lowerCaseMap.get(key.toString().toLowerCase(Locale.ENGLISH));
return super.get(realKey);
}
@Override
public Object put(String key, Object value) {
/*
* In order to keep the map and lowerCaseMap synchronized,
* we have to remove the old mapping before putting the
* new one. Indeed, oldKey and key are not necessaliry equals.
* (That's why we call super.remove(oldKey) and not just
* super.put(key, value))
*/
Object oldKey = lowerCaseMap.put(key.toLowerCase(Locale.ENGLISH), key);
Object oldValue = super.remove(oldKey);
super.put(key, value);
return oldValue;
}
@Override
public void putAll(Map<? extends String, ?> m) {
for (Map.Entry<? extends String, ?> entry : m.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
this.put(key, value);
}
}
@Override
public Object remove(Object key) {
Object realKey = lowerCaseMap.remove(key.toString().toLowerCase(Locale.ENGLISH));
return super.remove(realKey);
}
}
}
| {
"content_hash": "08ae45efa16255cabaf4125836225714",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 93,
"avg_line_length": 35.7212389380531,
"alnum_prop": 0.6195961848135761,
"repo_name": "wspeirs/sop4j-dbutils",
"id": "b9a0db9c66db9f2725eea92a31562010fc766ef4",
"size": "8665",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/sop4j/dbutils/BasicRowProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "384023"
}
],
"symlink_target": ""
} |
/**
* Module dependencies
*/
var _ = require('@sailshq/lodash');
var async = require('async');
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// FUTURE
// Pull _most of this_ into a separate module, since it's not specific
// to Sails, and has come up in a few different places.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Mix-in an `after` function to an EventEmitter.
*
* If `events` have already fired, trigger fn immediately (with no args)
* Otherwise bind a normal one-time event using `EventEmitter.prototype.once()`.
* Useful for checking whether or not something has finished loading, etc.
*
* This is a lot like jQuery's `$(document).ready()`.
*
* @param {EventEmitter} emitter The Sails application instance
*/
module.exports = function mixinAfter(emitter) {
/**
* { emitter.warmEvents }
*
* Events which have occurred at least once
* (Required to support `emitter.after()`)
*/
emitter.warmEvents = {};
var _originalEmit = emitter.emit;
/**
* emitter.emit()
*
* Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each.
*
* Override `EventEmitter.prototype.emit` to keep track of all the events that have occurred once.
* (Required to support `emitter.after()`)
*
* @param {String} eventName [name of the event]
* @return {Boolean} Returns true if the event had listeners, false otherwise.
* @see https://nodejs.org/api/events.html#events_emitter_emit_eventname_args
*/
emitter.emit = function(eventName) {
var args = Array.prototype.slice.call(arguments, 0);
emitter.warmEvents[eventName] = true;
return _originalEmit.apply(emitter, args);
};
/**
* `emitter.after()`
*
* Fires your handler **IF THE SPECIFIED EVENT HAS ALREADY BEEN TRIGGERED** or **WHEN IT IS TRIGGERED**.
*
* @param {String|Array} events [name of the event(s)]
* @param {Function} fn [event handler function]
*/
emitter.after = function(events, fn) {
// Support a single event or an array of events
if (!_.isArray(events)) {
events = [events];
}
// Convert named event dependencies into an array
// of async-compatible functions.
var dependencies = _.reduce(events, function (dependencies, event) {
// Push on the handler function.
dependencies.push(function handlerFn(cb) {
// If the event has already fired, then just execute our callback.
if (emitter.warmEvents[event]) {
return cb();
}
// But otherwise, bind a one-time-use handler that listens for the
// first time this event is fired, and then executes our callback
// once it does.
else {
emitter.once(event, function (){
return cb();
});
}
});//</declared and pushed on handler function>
return dependencies;
}, []);//</_.reduce() :: iterate over each event in order to build `dependencies` (an array of handler functions)>
// When all events have fired, call `fn`
// (all arguments passed to `emit()` calls are discarded)
async.parallel(dependencies, function(err) {
if (err) {
console.error('Consistency violation: Received `err`, but this should be impossible! Here is the error: '+err.stack);
console.error('^^^If you are seeing this message, then please report this error at http://sailsjs.com/bugs. (Continuing anyway...)');
}//>-
return fn();
});
};
};
| {
"content_hash": "574936523512233963f99717f7135a68",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 163,
"avg_line_length": 31.301724137931036,
"alnum_prop": 0.6188377857339575,
"repo_name": "balderdashy/sails",
"id": "2f5bd6367a7e698505f312bcd590c1b3ae1f6e5c",
"size": "3631",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/app/private/after.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "EJS",
"bytes": "172"
},
{
"name": "JavaScript",
"bytes": "1350891"
}
],
"symlink_target": ""
} |
require 'spec_helper'
extended = ActiveRecord::Base.extend(Neutral::Model::ActiveRecordExtension)
class Item < extended
neutral
end
class Client < extended
neutral_voter
end
describe Item, type: :model do
it { should be_a(Neutral::Model::ActiveRecordExtension::Voteable) }
before do
@migration = ActiveRecord::Migration.new
@migration.verbose = false
@migration.create_table(:items)
end
after do
@migration.drop_table(:items)
end
describe "#neutral" do
it { should have_many(:votes) }
it { should have_many(:voters) }
it { should have_one(:voting) }
end
end
describe Client, type: :model do
it { should be_a(Neutral::Model::ActiveRecordExtension::Voter) }
before do
@migration = ActiveRecord::Migration.new
@migration.verbose = false
@migration.create_table(:clients)
end
after do
@migration.drop_table(:clients)
end
describe "#neutral_voter" do
it { should have_many(:votes_given) }
end
end
| {
"content_hash": "b128172fdc6777d0b64609e143be9494",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 75,
"avg_line_length": 20.06122448979592,
"alnum_prop": 0.6927772126144456,
"repo_name": "petertoth/neutral",
"id": "03abed4265768c4423903902165c8bdf6f5dd260",
"size": "983",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/models/active_record_extension_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2145"
},
{
"name": "HTML",
"bytes": "9363"
},
{
"name": "JavaScript",
"bytes": "639"
},
{
"name": "Ruby",
"bytes": "64445"
}
],
"symlink_target": ""
} |
// export the Config constructor
module.exports = Config;
/**
* Description...
*
* @constructor
*
* @param {Object} settings
*/
function Config(settings) {
if (settings !== void 0 && typeof settings !== "object") {
throw TypeError("Usage: Config(settings: Object)");
}
/**
* @type {Object}
*/
this._settings = settings || {};
}
/**
* Adds/replaces the given settings field
*
* @param {String} settingsField
* @param {any} value
*
* @return {undefined}
*/
Config.prototype.put = function(settingsField, value) {
if (typeof settingsField !== "string" || value === void 0) {
throw TypeError("Usage: Config::put(settingsField: string, value: Any)");
}
var setting = this._settings;
var fields = settingsField.split(".");
for (var i = 0, l = fields.length, field = fields[i]; i < l; field = fields[++i]) {
// primer the setting (override any previous value)
if (!this._isObject(setting)) {
setting = {};
}
// if the key doesn't exist or is not of type Object create (override with)
// an empty object so we can "continue down" the hierarchy
if (!(field in setting) || !this._isObject(setting[field])) {
setting[field] = {};
}
// assign the value on the last iteration while we still
// have a reference to the settings field
if ((l - i) === 1) {
setting[field] = value;
} else {
// traverse the hierarchy to get the next field reference
setting = setting[field];
}
}
};
/**
* Returns true if the given settings field exists
*
* @param {String} settingsField
*
* @return {Boolean}
*/
Config.prototype.has = function(settingsField) {
if (typeof settingsField !== "string") {
throw TypeError("Usage: Config::has(settingsField: string)");
}
var setting = this._settings;
var fields = settingsField.split(".");
for (var i = 0, l = fields.length, field = fields[i]; i < l; field = fields[++i]) {
if (this._isObject(setting) && field in setting) {
// traverse the hierarchy to get the next field reference
setting = setting[field];
} else {
return false;
}
}
return true;
};
/**
* Returns the given settings field if set or the default value
*
* @param {String} settingsField
* @param {any} defaultValue
*
* @return {any}
*/
Config.prototype.get = function(settingsField, defaultValue) {
// if no settings field was given return all settings
if (settingsField === void 0) {
return this._settings;
}
if (typeof settingsField !== "string") {
throw TypeError("Usage: Config::get(settingsField: string, defaultValue: Any)");
}
var setting = this._settings;
var fields = settingsField.split(".");
for (var i = 0, l = fields.length, field = fields[i]; i < l; field = fields[++i]) {
if (this._isObject(setting) && field in setting) {
// traverse the hierarchy to get the next field reference
setting = setting[field];
} else {
return defaultValue;
}
}
return setting;
};
/**
* Merges in the given settings into the internal settings object
*
* @param {Object} settings
* @param {Boolean} mergeArrays
*
* @return {undefined}
*/
Config.prototype.merge = function(settings, mergeArrays) {
if (typeof settings !== "object") {
throw TypeError("Usage: Config::merge(settings: Object)");
}
this._settings = this._mergeSettings(this._settings, settings, mergeArrays);
};
/**
* Recursively merges the two given settings objects giving priority to the second
*
* @param {Object} settings1
* @param {Object} settings2
* @param {Boolean} mergeArrays
*
* @return {Object}
*/
Config.prototype._mergeSettings = function(settings1, settings2, mergeArrays) {
// clone the given object to leave it intact
// NOTE as the merge is recursive a shallow copy is sufficient
var merged = this._clone(settings1);
var keys = Object.getOwnPropertyNames(settings2);
var key;
for (var i = 0, l = keys.length; i < l; i++) {
key = keys[i];
if (key in merged) {
if (this._isObject(merged[key]) && this._isObject(settings2[key])) {
merged[key] = this._mergeSettings(merged[key], settings2[key], mergeArrays);
} else if (mergeArrays && Array.isArray(merged[key]) && Array.isArray(settings2[keys])) {
merged[key] = merged[key].concat(settings2[key]).reduce(function(prev, curr) {
// only push unique values
if (prev.indexOf(curr) < 0) {
prev.push(curr);
}
return prev;
}, []);
} else {
merged[key] = settings2[key];
}
} else {
merged[key] = settings2[key];
}
}
return merged;
};
/**
* Returns a shallow copy of the given object
*
* @param {Object} object
*
* @return {Object}
*/
Config.prototype._clone = function(object) {
var clone = Object.create(Object.getPrototypeOf(object));
var keys = Object.getOwnPropertyNames(object);
for (var i = 0, l = keys.length; i < l; i++) {
key = keys[i];
Object.defineProperty(clone, key, Object.getOwnPropertyDescriptor(object, key));
}
return clone;
};
/**
* Returns true if the given parameter is an object
*
* @param {any} potentialObject
*
* @return {Boolean}
*/
Config.prototype._isObject = function(potentialObject) {
return Object.prototype.toString.call(potentialObject) === "[object Object]";
};
| {
"content_hash": "3cf1049b4923b937cf9cb9734981a84d",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 101,
"avg_line_length": 27.864734299516908,
"alnum_prop": 0.5880721220527045,
"repo_name": "martin-pettersson/configjs",
"id": "1c7bc4ff394b0d216b1006b30de080c9ee09a4e8",
"size": "5768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "10258"
}
],
"symlink_target": ""
} |
define(["d3", "./LinearScale", "underscore"],
function(d3, LinearScale, _) {
"use strict";
var DateScale = LinearScale.LinearScale.extend({
render: function() {
this.scale = d3.time.scale();
if(this.model.domain.length > 0)
this.scale.domain(this.model.domain);
this.offset = 0;
this.create_event_listeners();
},
});
return {
DateScale: DateScale,
};
});
| {
"content_hash": "c16d81192cb3065793128be8b1c21a90",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 53,
"avg_line_length": 23.7,
"alnum_prop": 0.5189873417721519,
"repo_name": "rmenegaux/bqplot",
"id": "ca940849526a9b94a11034e0aa1e0a682dbe3bfd",
"size": "1076",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/src/DateScale.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5500"
},
{
"name": "JavaScript",
"bytes": "641299"
},
{
"name": "Python",
"bytes": "166038"
}
],
"symlink_target": ""
} |
function [alldiag]=diags_display(dirMat,setDiags,dirTex,nameTex);
% [alldiag]=DIAGS_DISPLAY(dirMat,setDiags,dirTex,nameTex)
% displays a set of diagnostics (setDiags) from the results
% stored (in [dirMat 'diags_set_' setDiags]).
%
% Further outputs the results to tex ([dirTex nameTex '.tex'])
% if dirTex and nameTex are specified. This functionality
% is normally operated via diags_driver_tex.m. If dirMat is
% specified as {dirMat,dirMatRef} then anomalies will be plotted.
%
% setDiags is the choice of diagnostics set such as
% 'A') trasnports
% 'B') air-sea fluxes
% 'C') state variables
% 'D') global and hemispheric budgets
% 'MLD') mixed layer depths
%
% In some cases more specific options can be specified, e.g. to
% display only subsurface budgets one may set setDiags={{'D',11}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%determine input/output params:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%directory names:
if iscell(dirMat); dirMatRef=dirMat{2}; dirMat=dirMat{1}; end;
dirMat=[dirMat '/'];
if isempty(who('dirMatRef')); dirMatRef='';
elseif ~isempty(dirMatRef); dirMatRef=[dirMatRef '/'];
end;
if isempty(who('dirTex')); dirTex=''; else; dirTex=[dirTex '/']; end;
if isempty(who('nameTex')); nameTex='myPlots'; end;
%determine if and where to create tex and figures files
if ~ischar(dirTex); error('mis-specified dirTex'); end;
if isempty(dirTex);
addToTex=1; fileTex='';
else;
addToTex=1; fileTex=[dirTex nameTex '.tex'];
end;
%determined where to display anomalies between runs
doAnomalies=~isempty(dirMatRef);
%more params
setDiagsParams=[];
if iscell(setDiags);
setDiagsParams={setDiags{2:end}};
setDiags=setDiags{1};
end;
%%%%%%%%%%%%%%%%%%%%%%
%load grid and params:
%%%%%%%%%%%%%%%%%%%%%%
gcmfaces_global; global myparms;
test1=~isempty(dir([dirMat 'basic_diags_ecco_mygrid.mat']));
test2=~isempty(dir([dirMat 'diags_grid_parms.mat']));
if ~test1&~test2;
error('missing diags_grid_parms.mat')
elseif test2;
nameGrid='diags_grid_parms.mat';
suffDiag='diags_set_';
budgetList='diags_select_budget_list.mat';
else;
nameGrid='basic_diags_ecco_mygrid.mat';
suffDiag='basic_diags_ecco_';
budgetList='basic_diags_ecco_budget_list.mat';
end;
%reload myparms from dirMat (and mygrid if included the mat file)
eval(['load ' dirMat nameGrid ';']);
%reload mygrid if needed
if isfield(myparms,'dirGrid'); diags_grid(myparms.dirGrid,0); end;
%zonal mean and sections needed for transport computations
if ~isfield(mygrid,'mygrid.LATS_MASKS');
gcmfaces_lines_zonal;
end;
if ~isfield(mygrid,'LINES_MASKS');
[lonPairs,latPairs,names]=gcmfaces_lines_pairs;
gcmfaces_lines_transp(lonPairs,latPairs,names);
end;
%backward compatibility:
if ~isfield(mygrid,'memoryLimit'); mygrid.memoryLimit=0; end;
if ~isfield(mygrid,'ioSize'); mygrid.ioSize=0; end;
%in case mygrid.memoryLimit=1, load the stuff that was not saved to diags_grid_parms.mat
if mygrid.memoryLimit==1;
list0={'hFacS','hFacW'};
for iFld=1:length(list0);
eval(['mygrid.' list0{iFld} '=rdmds2gcmfaces([mygrid.dirGrid ''' list0{iFld} '*'']);']);
end;
%
mygrid.hFacCsurf=mygrid.hFacC;
for ff=1:mygrid.hFacC.nFaces; mygrid.hFacCsurf{ff}=mygrid.hFacC{ff}(:,:,1); end;
%
mskC=mygrid.hFacC; mskC(mskC==0)=NaN; mskC(mskC>0)=1; mygrid.mskC=mskC;
mskW=mygrid.hFacW; mskW(mskW==0)=NaN; mskW(mskW>0)=1; mygrid.mskW=mskW;
mskS=mygrid.hFacS; mskS(mskS==0)=NaN; mskS(mskS>0)=1; mygrid.mskS=mskS;
%
gcmfaces_lines_zonal;
mygrid.LATS=[mygrid.LATS_MASKS.lat]';
[lonPairs,latPairs,names]=gcmfaces_lines_pairs;
gcmfaces_lines_transp(lonPairs,latPairs,names);
end;
%%%%%%%%%%%%%%
%define diags:
%%%%%%%%%%%%%%
%test for results organization
if isdir([dirMat 'diags_set_' setDiags]);
dirMat=[dirMat 'diags_set_' setDiags '/'];
end;
if isdir([dirMatRef 'diags_set_' setDiags]);
dirMatRef=[dirMatRef 'diags_set_' setDiags '/'];
end;
if strcmp(nameGrid,'diags_grid_parms.mat');
%load listDiags and get fileMat (if applies)
userStep=1;
if ~isempty(which(['diags_set_' setDiags]));
eval(['diags_set_' setDiags]);
else;
diags_set_user;
end;
%reformat listDiags to cell array:
jj=strfind(listDiags,' '); jj=[0 jj length(listDiags)+1];
for ii=1:length(jj)-1;
tmp1=listDiags(jj(ii)+1:jj(ii+1)-1);
if ii==1; listDiags2={tmp1}; else; listDiags2{ii}=tmp1; end;
end;
listDiags=listDiags2; clear listDiags2;
end;
%set fileMat to default name if needed
if isempty(who('fileMat')); fileMat=[suffDiag setDiags]; end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%are there results to display?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
test1=isempty(dir([dirMat '/' fileMat '_*.mat']));
tmp1=[dirMat '/' fileMat '_*.mat']; tmp2=strfind(tmp1,'_'); tmp1(tmp2)=' ';
if test1&addToTex;
eval(['load ' dirTex nameTex '.mat;']);
write2tex(fileTex,3,{'[ ',mySection,' ]'},1);
write2tex(fileTex,3,{'abort : did not find any'},1);
write2tex(fileTex,3,{tmp1},1);
write2tex(fileTex,3,{'results files to display'},1);
return;
elseif test1;
fprintf(['\n abort : did not find any \n ' tmp1 '\n results files to display\n\n']);
return;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%
%load pre-computed diags:
%%%%%%%%%%%%%%%%%%%%%%%%%
tic;
diagsWereLoaded=0;
%specific load sequence (if any, diagsWereLoaded will be set to 1)
if strcmp(nameGrid,'diags_grid_parms.mat');
userStep=0;
if ~isempty(which(['diags_set_' setDiags]));
eval(['diags_set_' setDiags]);
else;
diags_set_user;
end;
end;
%generic load (if no specific one, or )
if ~diagsWereLoaded;
alldiag=diags_read_from_mat(dirMat,[fileMat '_*.mat']);
end;
toc;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%load ref and compute anomalies:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if doAnomalies;
% scaleAnom=10;
scaleAnom=1;
%store:
dirMatBak=dirMat; dirMat=dirMatRef; alldiagBak=alldiag;
%load reference solution:
diagsWereLoaded=0;
%specific load sequence (if any, diagsWereLoaded will be set to 1)
if strcmp(nameGrid,'diags_grid_parms.mat');
userStep=0;
if ~isempty(which(['diags_set_' setDiags]));
eval(['diags_set_' setDiags]);
else;
diags_set_user;
end;
end;
%generic load (if no specific one, or )
if ~diagsWereLoaded;
alldiag=diags_read_from_mat(dirMat,[fileMat '_*.mat']);
end;
%restore:
dirMat=dirMatBak; alldiagRef=alldiag; alldiag=alldiagBak;
%compute anomalies:
for ii=1:length(alldiag.listDiags);
tmp0=alldiag.listDiags{ii};
if ~strcmp(tmp0,'listTimes')&~strcmp(tmp0,'listSteps')
if isfield(alldiagRef,tmp0);%compute difference
tmp1=getfield(alldiag,tmp0)-getfield(alldiagRef,tmp0);
alldiag=setfield(alldiag,tmp0,tmp1);
else;%cannot compute diff -> set to NaN
tmp1=NaN*getfield(alldiag,tmp0);
alldiag=setfield(alldiag,tmp0,tmp1);
end;
end;
end;
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%determine time parameters for plots
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%number of months for runmean
if myparms.diagsAreMonthly&myparms.diagsNbRec>12;
myNmean=6; %half window
myNmeanTxt=[' -- ' num2str(myNmean*2) ' months low pass filtered'];
else;
myNmean=0; myNmeanTxt='';
end;
%first and last year of time average
myYmean=myparms.yearInAve;
if myYmean(1)==myYmean(2); myYmeanTxt=[num2str(myYmean(1)) ' '];
else; myYmeanTxt=[num2str(myYmean(1)) '-' num2str(myYmean(2)) ' '];
end;
%to compute time mean/std on the fly
if length(alldiag.listTimes)>diff(myparms.recInAve)+1;
tt=[myparms.recInAve(1):min(myparms.recInAve(2),length(alldiag.listTimes))];
TT=alldiag.listTimes(tt);
else;
tt=[1:length(alldiag.listTimes)];
TT=alldiag.listTimes;
end;
nt=length(TT);
%if only one record, swicth off time series and variance plots
multiTimes=1*(myparms.recInAve(2)>myparms.recInAve(1));
%if llc90 we can plot overturn etc per basin
multiBasins=(sum([90 1170]~=mygrid.ioSize)==0);
%%%%%%%%%%%%%%%
%display diags:
%%%%%%%%%%%%%%%
userStep=-1;
if ~isempty(which(['diags_set_' setDiags]));
eval(['diags_set_' setDiags]);
else;
diags_set_user;
end;
| {
"content_hash": "fefcebccc84a0ab43bfdb08a9bcce77f",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 98,
"avg_line_length": 29.74642857142857,
"alnum_prop": 0.6345299555769,
"repo_name": "gaelforget/gcmfaces",
"id": "7b3bc7199f07e73bffda50d9854bdb60f9bc28b7",
"size": "8329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gcmfaces_diags/diags_display.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "MATLAB",
"bytes": "792142"
},
{
"name": "Objective-C",
"bytes": "4790"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Propel\Generator\Config;
use Propel\Runtime\Propel;
/**
* Runtime configuration converter
* From array to PHP string
*/
class ArrayToPhpConverter
{
/**
* Create a PHP configuration from an array
*
* @param array $c The array configuration
*
* @return string
*/
public static function convert(array $c): string
{
$runtimeVersion = Propel::VERSION;
$conf = '';
$conf .= "\$configuration = \\Propel\\Runtime\\Configuration::getCurrentConfigurationOrCreate();
\$configuration->checkVersion('{$runtimeVersion}');";
// set datasources
if (isset($c['connections'])) {
foreach ($c['connections'] as $name => $params) {
if (!is_array($params)) {
continue;
}
// set adapters
if (isset($params['adapter'])) {
$conf .= "
\$configuration->setAdapterClass('{$name}', '{$params['adapter']}');";
}
// set connection settings
if (isset($params['slaves'])) {
$conf .= "
\$manager = new \\Propel\\Runtime\\Connection\\ConnectionManagerMasterSlave(\$configuration->getAdapter('{$name}'));
\$manager->setReadConfiguration(" . var_export($params['slaves'], true). ");";
} elseif (isset($params['dsn'])) {
$conf .= "
\$manager = new \\Propel\\Runtime\\Connection\\ConnectionManagerSingle(\$configuration->getAdapter('{$name}'));";
} else {
continue;
}
if (isset($params['dsn'])) {
$masterConfigurationSetter = isset($params['slaves']) ? 'setWriteConfiguration' : 'setConfiguration';
$connection = $params;
unset($connection['adapter']);
unset($connection['slaves']);
$conf .= "
\$manager->{$masterConfigurationSetter}(". var_export($connection, true) . ");";
}
$conf .= "
\$manager->setName('{$name}');
\$configuration->setConnectionManager('{$name}', \$manager);";
}
// set default datasource
if (isset($c['defaultConnection'])) {
$defaultDatasource = $c['defaultConnection'];
} elseif (isset($c['connections']) && is_array($c['connections'])) {
// fallback to the first datasource
$datasourceNames = array_keys($c['connections']);
$defaultDatasource = $datasourceNames[0];
}
$conf .= "
\$configuration->setDefaultDatasource('{$defaultDatasource}');";
}
// set profiler
if (isset($c['profiler'])) {
$profilerConf = $c['profiler'];
if (isset($profilerConf['classname'])) {
$conf .= "
\$configuration->setProfilerClass('{$profilerConf['classname']}');";
unset($profilerConf['classname']);
}
if ($profilerConf) {
$conf .= "
\$configuration->setProfilerConfiguration(" . var_export($profilerConf, true) . ");";
}
unset($c['profiler']);
}
// set logger
if (isset($c['log']) && count($c['log']) > 0) {
foreach ($c['log'] as $key => $logger) {
$conf .= "
\$configuration->setLoggerConfiguration('{$key}', " . var_export($logger, true) . ");";
}
unset($c['log']);
}
// register all known entity classes
if (isset($c['databaseToEntities'])) {
foreach ($c['databaseToEntities'] as $database => $entityClasses) {
$entities = var_export($entityClasses, true);
$conf .= "
\$configuration->registerEntity('$database', $entities);";
}
}
$conf .= '
return $configuration;';
return preg_replace('/[ \t]*$/m', '', $conf);
}
}
| {
"content_hash": "0d26104fd0c5fb271979a68c846fa754",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 121,
"avg_line_length": 32.65040650406504,
"alnum_prop": 0.5062250996015937,
"repo_name": "propelorm/Propel3",
"id": "7669014e185b357d9a9ac2ea577539b579fe1727",
"size": "4221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Generator/Config/ArrayToPhpConverter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2909"
},
{
"name": "Gherkin",
"bytes": "6832"
},
{
"name": "HTML",
"bytes": "20281"
},
{
"name": "Makefile",
"bytes": "146"
},
{
"name": "PHP",
"bytes": "4434090"
},
{
"name": "Shell",
"bytes": "3993"
},
{
"name": "XSLT",
"bytes": "74121"
}
],
"symlink_target": ""
} |
package com.reisen.danmulib.sprite;
import com.reisen.danmulib.interfaces.Bullet;
/**
* 点弹
*
* @author Reisen at 2017-08-29
*/
public class PointBullet extends com.reisen.danmulib.sprite.Bullets implements Bullet {
public PointBullet() {
super(0,0,0,0);
}
public PointBullet(float x, float y, float size, long time) {
super(x, y, size,time);
}
public PointBullet(float x, float y, float vectorX, float vectorY, float size, long time) {
super(x,y,vectorX,vectorY,size,time);
}
public PointBullet reset(float x, float y, float size, long time) {
super.reset(x,y,size,time);
parent = null;
return this;
}
public PointBullet reset(float x, float y, float size, long time, Shooter shooter) {
super.reset(x,y,size,time);
parent = shooter;
return this;
}
public PointBullet reset(float x, float y, float vectorX, float vectorY, float size, long time) {
super.reset(x,y,vectorX,vectorY,size,time);
parent = null;
return this;
}
public PointBullet reset(float x, float y, float vectorX, float vectorY, float size, long time, Shooter shooter) {
super.reset(x,y,vectorX,vectorY,size,time);
parent = shooter;
return this;
}
/**
* 检查父机体是否存在, 判断是否消弹
*
* @param remove 父机体不存在时是否消弹 <br/><br/> true : 消弹<br/> false : 不消弹
* @return 是否消弹
*/
public boolean checkParent(boolean remove) {
if (parent == null) {
return remove;
}
return !parent.isAlive && remove;
}
}
| {
"content_hash": "4cb93ae259f612ae8a498bc72583b236",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 118,
"avg_line_length": 26.048387096774192,
"alnum_prop": 0.6074303405572755,
"repo_name": "ReisenZ/AndroidDanmu",
"id": "195f187117ec9bd8c909291271ca560f06cc9814",
"size": "1689",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "danmuLib/src/main/java/com/reisen/danmulib/sprite/PointBullet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "115280"
}
],
"symlink_target": ""
} |
<button type="button" id="attach">attachEvent</button><button type="button" id="addE">addEventListener</button><button
type="button" id="byclick">onClick</button>
<br>
INFO :
<div id="info"></div> | {
"content_hash": "061df69143633a92b922eee3b8c394e9",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 118,
"avg_line_length": 40,
"alnum_prop": 0.705,
"repo_name": "dota8/dota8.github.io",
"id": "c2bba41b97e8de2724494978ddc56783f82f8d6b",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/SD9011/getEventObject.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16260"
},
{
"name": "HTML",
"bytes": "6713234"
},
{
"name": "JavaScript",
"bytes": "18717"
},
{
"name": "PHP",
"bytes": "5618"
},
{
"name": "Pascal",
"bytes": "1375"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.google.bigquery.sql;
import com.google.api.services.bigquery.Bigquery;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.support.DefaultEndpoint;
/**
* Access Google Cloud BigQuery service using SQL queries.
*
* BigQuery Endpoint Definition Represents a table within a BigQuery dataset Contains configuration details for a single
* table and the utility methods (such as check, create) to ease operations URI Parameters: * Logger ID - To ensure that
* logging is unified under Route Logger, the logger ID can be passed on via an endpoint URI parameter * Partitioned -
* to indicate that the table needs to be partitioned - every UTC day to be written into a timestamped separate table
* side effect: Australian operational day is always split between two UTC days, and, therefore, tables
*
* Another consideration is that exceptions are not handled within the class. They are expected to bubble up and be
* handled by Camel.
*/
@UriEndpoint(firstVersion = "2.23.0", scheme = "google-bigquery-sql", title = "Google BigQuery Standard SQL",
syntax = "google-bigquery-sql:projectId:query", label = "cloud,messaging", producerOnly = true)
public class GoogleBigQuerySQLEndpoint extends DefaultEndpoint {
@UriParam
protected final GoogleBigQuerySQLConfiguration configuration;
protected GoogleBigQuerySQLEndpoint(String endpointUri, GoogleBigQuerySQLComponent component,
GoogleBigQuerySQLConfiguration configuration) {
super(endpointUri, component);
this.configuration = configuration;
}
@Override
public Producer createProducer() throws Exception {
Bigquery bigquery = getConfiguration().getConnectionFactory().getDefaultClient();
GoogleBigQuerySQLProducer producer = new GoogleBigQuerySQLProducer(bigquery, this, configuration);
return producer;
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Cannot consume from the BigQuery endpoint: " + getEndpointUri());
}
public GoogleBigQuerySQLConfiguration getConfiguration() {
return configuration;
}
@Override
public GoogleBigQuerySQLComponent getComponent() {
return (GoogleBigQuerySQLComponent) super.getComponent();
}
}
| {
"content_hash": "bcc5208db940201d40058f05dcdc9713",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 120,
"avg_line_length": 43.60344827586207,
"alnum_prop": 0.7516805061289047,
"repo_name": "mcollovati/camel",
"id": "ab40d5e1eb8702ddf30ffb7c002de8a79c97cfc0",
"size": "3331",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "components/camel-google-bigquery/src/main/java/org/apache/camel/component/google/bigquery/sql/GoogleBigQuerySQLEndpoint.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6521"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "14479"
},
{
"name": "HTML",
"bytes": "915679"
},
{
"name": "Java",
"bytes": "84048197"
},
{
"name": "JavaScript",
"bytes": "100326"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Shell",
"bytes": "17240"
},
{
"name": "TSQL",
"bytes": "28835"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "275257"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="java" version="1.7"/>
<installed facet="jst.web" version="2.5"/>
<installed facet="wst.jsdt.web" version="1.0"/>
<installed facet="com.sap.ide.ui5.app.facet" version="latest"/>
</faceted-project>
| {
"content_hash": "0b53b3718f5564886f21726769a17a17",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 65,
"avg_line_length": 38.875,
"alnum_prop": 0.6688102893890675,
"repo_name": "todorovski-vasil/sapui5-exploration",
"id": "5eeb4b7702f201b103dce573398ed8fed11794bf",
"size": "311",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": ".settings/org.eclipse.wst.common.project.facet.core.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1861"
},
{
"name": "JavaScript",
"bytes": "6757"
}
],
"symlink_target": ""
} |
var router = require('koa-router');
module.exports = function(app){
//user module
var user_router = new router();
user_router.prefix('/api/user');
require('./user')(user_router);
app.use(user_router.routes());
//activity module
var activity_router = new router();
activity_router.prefix('/api/activity');
require('./activity')(activity_router);
app.use(activity_router.routes());
//participant module
var participant_router = new router();
participant_router.prefix('/api/participant');
require('./participant')(participant_router);
app.use(participant_router.routes());
//file
var file_router = new router();
file_router.prefix('/api/file');
require('./file')(file_router);
app.use(file_router.routes());
//qn voice img api
var qn_router = new router();
qn_router.prefix('/api/qn');
require('./qn')(qn_router);
app.use(qn_router.routes());
} | {
"content_hash": "db9fca5e3503af7182ba6a67fb801679",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 50,
"avg_line_length": 28.696969696969695,
"alnum_prop": 0.6346356916578669,
"repo_name": "trillers/mt",
"id": "54004e88e4e09cc3fb574a746a81082333c9d484",
"size": "947",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/controllers/api/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39876"
},
{
"name": "HTML",
"bytes": "118121"
},
{
"name": "JavaScript",
"bytes": "205618"
}
],
"symlink_target": ""
} |
package com.netflix.priam.notification;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.MessageAttributeValue;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.netflix.priam.aws.IAMCredential;
import com.netflix.priam.config.IConfiguration;
import com.netflix.priam.identity.config.InstanceInfo;
import com.netflix.priam.merics.BackupMetrics;
import com.netflix.priam.utils.BoundedExponentialRetryCallable;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* A single, persisted, connection to Amazon SNS.
*/
@Singleton
public class AWSSnsNotificationService implements INotificationService {
private static final Logger logger = LoggerFactory.getLogger(AWSSnsNotificationService.class);
private final IConfiguration configuration;
private final AmazonSNS snsClient;
private final BackupMetrics backupMetrics;
@Inject
public AWSSnsNotificationService(
IConfiguration config,
IAMCredential iamCredential,
BackupMetrics backupMetrics,
InstanceInfo instanceInfo) {
this.configuration = config;
this.backupMetrics = backupMetrics;
String ec2_region = instanceInfo.getRegion();
snsClient =
AmazonSNSClient.builder()
.withCredentials(iamCredential.getAwsCredentialProvider())
.withRegion(ec2_region)
.build();
}
@Override
public void notify(
final String msg, final Map<String, MessageAttributeValue> messageAttributes) {
// e.g. arn:aws:sns:eu-west-1:1234:eu-west-1-cass-sample-backup
final String topic_arn = this.configuration.getBackupNotificationTopicArn();
if (!configuration.enableBackupNotification() || StringUtils.isEmpty(topic_arn)) {
return;
}
PublishResult publishResult;
try {
publishResult =
new BoundedExponentialRetryCallable<PublishResult>() {
@Override
public PublishResult retriableCall() throws Exception {
PublishRequest publishRequest =
new PublishRequest(topic_arn, msg)
.withMessageAttributes(messageAttributes);
return snsClient.publish(publishRequest);
}
}.call();
} catch (Exception e) {
logger.error(
String.format(
"Exhausted retries. Publishing notification metric for failure and moving on. Failed msg to publish: %s",
msg),
e);
backupMetrics.incrementSnsNotificationFailure();
return;
}
// If here, message was published. As a extra validation, ensure we have a msg id
String publishedMsgId = publishResult.getMessageId();
if (publishedMsgId == null || publishedMsgId.isEmpty()) {
backupMetrics.incrementSnsNotificationFailure();
return;
}
backupMetrics.incrementSnsNotificationSuccess();
if (logger.isTraceEnabled()) {
logger.trace("Published msg: {} aws sns messageId - {}", msg, publishedMsgId);
}
}
}
| {
"content_hash": "8f89ccdfc1456878e22bb2c04d73fa58",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 135,
"avg_line_length": 39.51086956521739,
"alnum_prop": 0.6382393397524071,
"repo_name": "Netflix/Priam",
"id": "61bcd91f3729c63eba438d9a237f892a60faf7dd",
"size": "4230",
"binary": false,
"copies": "1",
"ref": "refs/heads/3.x",
"path": "priam/src/main/java/com/netflix/priam/notification/AWSSnsNotificationService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "18378"
},
{
"name": "Java",
"bytes": "1350631"
}
],
"symlink_target": ""
} |
//===--- DeclContext.cpp - DeclContext implementation ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/AST/DeclContext.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Expr.h"
#include "swift/AST/FileUnit.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParseRequests.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Types.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SaveAndRestore.h"
#include "clang/AST/ASTContext.h"
using namespace swift;
#define DEBUG_TYPE "Name lookup"
STATISTIC(NumLazyIterableDeclContexts,
"# of serialized iterable declaration contexts");
STATISTIC(NumUnloadedLazyIterableDeclContexts,
"# of serialized iterable declaration contexts never loaded");
ASTContext &DeclContext::getASTContext() const {
return getParentModule()->getASTContext();
}
GenericTypeDecl *DeclContext::getSelfTypeDecl() const {
auto decl = const_cast<Decl*>(getAsDecl());
if (!decl) return nullptr;
auto ext = dyn_cast<ExtensionDecl>(decl);
if (!ext) return dyn_cast<GenericTypeDecl>(decl);
return ext->getExtendedNominal();
}
/// If this DeclContext is a NominalType declaration or an
/// extension thereof, return the NominalTypeDecl.
NominalTypeDecl *DeclContext::getSelfNominalTypeDecl() const {
return dyn_cast_or_null<NominalTypeDecl>(getSelfTypeDecl());
}
ClassDecl *DeclContext::getSelfClassDecl() const {
return dyn_cast_or_null<ClassDecl>(getSelfTypeDecl());
}
EnumDecl *DeclContext::getSelfEnumDecl() const {
return dyn_cast_or_null<EnumDecl>(getSelfTypeDecl());
}
StructDecl *DeclContext::getSelfStructDecl() const {
return dyn_cast_or_null<StructDecl>(getSelfTypeDecl());
}
ProtocolDecl *DeclContext::getSelfProtocolDecl() const {
return dyn_cast_or_null<ProtocolDecl>(getSelfTypeDecl());
}
ProtocolDecl *DeclContext::getExtendedProtocolDecl() const {
if (auto decl = const_cast<Decl*>(getAsDecl()))
if (auto ED = dyn_cast<ExtensionDecl>(decl))
return dyn_cast_or_null<ProtocolDecl>(ED->getExtendedNominal());
return nullptr;
}
VarDecl *DeclContext::getNonLocalVarDecl() const {
if (auto *init = dyn_cast<PatternBindingInitializer>(this)) {
if (auto binding = init->getBinding()) {
if (auto *var = binding->getAnchoringVarDecl(init->getBindingIndex())) {
return var;
}
}
}
return nullptr;
}
GenericTypeParamType *DeclContext::getProtocolSelfType() const {
assert(getSelfProtocolDecl() && "not a protocol");
GenericParamList *genericParams;
if (auto proto = dyn_cast<ProtocolDecl>(this)) {
genericParams = proto->getGenericParams();
} else {
genericParams = cast<ExtensionDecl>(this)->getGenericParams();
}
if (genericParams == nullptr)
return nullptr;
return genericParams->getParams().front()
->getDeclaredInterfaceType()
->castTo<GenericTypeParamType>();
}
Type DeclContext::getDeclaredTypeInContext() const {
if (auto declaredType = getDeclaredInterfaceType())
return mapTypeIntoContext(declaredType);
return Type();
}
Type DeclContext::getDeclaredInterfaceType() const {
if (auto *ED = dyn_cast<ExtensionDecl>(this)) {
auto *NTD = ED->getExtendedNominal();
if (NTD == nullptr)
return ErrorType::get(ED->getASTContext());
return NTD->getDeclaredInterfaceType();
}
if (auto *NTD = dyn_cast<NominalTypeDecl>(this))
return NTD->getDeclaredInterfaceType();
return Type();
}
void DeclContext::forEachGenericContext(
llvm::function_ref<void (GenericParamList *)> fn) const {
auto dc = this;
do {
if (auto decl = dc->getAsDecl()) {
// Extensions do not capture outer generic parameters.
if (auto *ext = dyn_cast<ExtensionDecl>(decl)) {
for (auto *gpList = ext->getGenericParams();
gpList != nullptr;
gpList = gpList->getOuterParameters()) {
fn(gpList);
}
return;
}
if (auto genericCtx = decl->getAsGenericContext())
if (auto *gpList = genericCtx->getGenericParams())
fn(gpList);
}
} while ((dc = dc->getParentForLookup()));
}
unsigned DeclContext::getGenericContextDepth() const {
unsigned depth = -1;
forEachGenericContext([&](GenericParamList *) { ++depth; });
return depth;
}
GenericSignature DeclContext::getGenericSignatureOfContext() const {
auto dc = this;
do {
if (auto decl = dc->getAsDecl())
if (auto GC = decl->getAsGenericContext())
return GC->getGenericSignature();
} while ((dc = dc->getParent()));
return nullptr;
}
GenericEnvironment *DeclContext::getGenericEnvironmentOfContext() const {
auto dc = this;
do {
if (auto decl = dc->getAsDecl())
if (auto GC = decl->getAsGenericContext())
return GC->getGenericEnvironment();
} while ((dc = dc->getParent()));
return nullptr;
}
Type DeclContext::mapTypeIntoContext(Type type) const {
return GenericEnvironment::mapTypeIntoContext(
getGenericEnvironmentOfContext(), type);
}
DeclContext *DeclContext::getLocalContext() {
if (isLocalContext())
return this;
if (isModuleContext())
return nullptr;
return getParent()->getLocalContext();
}
AbstractFunctionDecl *DeclContext::getInnermostMethodContext() {
auto dc = this;
do {
if (auto decl = dc->getAsDecl()) {
auto func = dyn_cast<AbstractFunctionDecl>(decl);
// If we found a non-func decl, we're done.
if (func == nullptr)
return nullptr;
if (func->getDeclContext()->isTypeContext())
return func;
}
} while ((dc = dc->getParent()));
return nullptr;
}
bool DeclContext::isTypeContext() const {
if (auto decl = getAsDecl())
return isa<NominalTypeDecl>(decl) || isa<ExtensionDecl>(decl);
return false;
}
DeclContext *DeclContext::getInnermostTypeContext() {
auto dc = this;
do {
if (dc->isTypeContext())
return dc;
} while ((dc = dc->getParent()));
return nullptr;
}
Decl *DeclContext::getInnermostDeclarationDeclContext() {
auto DC = this;
do {
if (auto decl = DC->getAsDecl())
return isa<ModuleDecl>(decl) ? nullptr : decl;
} while ((DC = DC->getParent()));
return nullptr;
}
DeclContext *DeclContext::getInnermostSkippedFunctionContext() {
auto dc = this;
do {
if (auto afd = dyn_cast<AbstractFunctionDecl>(dc))
if (afd->isBodySkipped())
return afd;
} while ((dc = dc->getParent()));
return nullptr;
}
DeclContext *DeclContext::getParentForLookup() const {
if (isa<ProtocolDecl>(this) || isa<ExtensionDecl>(this)) {
// If we are inside a protocol or an extension, skip directly
// to the module scope context, without looking at any (invalid)
// outer types.
return getModuleScopeContext();
}
if (isa<NominalTypeDecl>(this)) {
// If we are inside a nominal type that is inside a protocol,
// skip the protocol.
if (isa<ProtocolDecl>(getParent()))
return getModuleScopeContext();
}
return getParent();
}
ModuleDecl *DeclContext::getParentModule() const {
const DeclContext *DC = this;
while (!DC->isModuleContext())
DC = DC->getParent();
return const_cast<ModuleDecl *>(cast<ModuleDecl>(DC));
}
SourceFile *DeclContext::getParentSourceFile() const {
const DeclContext *DC = this;
while (!DC->isModuleScopeContext())
DC = DC->getParent();
return const_cast<SourceFile *>(dyn_cast<SourceFile>(DC));
}
DeclContext *DeclContext::getModuleScopeContext() const {
auto DC = const_cast<DeclContext*>(this);
while (true) {
if (DC->ParentAndKind.getInt() == ASTHierarchy::FileUnit)
return DC;
if (auto NextDC = DC->getParent()) {
DC = NextDC;
} else {
assert(isa<ModuleDecl>(DC->getAsDecl()));
return DC;
}
}
}
void DeclContext::getSeparatelyImportedOverlays(
ModuleDecl *declaring, SmallVectorImpl<ModuleDecl *> &overlays) const {
if (auto SF = getParentSourceFile())
SF->getSeparatelyImportedOverlays(declaring, overlays);
}
/// Determine whether the given context is generic at any level.
bool DeclContext::isGenericContext() const {
auto dc = this;
do {
if (auto decl = dc->getAsDecl()) {
if (auto GC = decl->getAsGenericContext()) {
if (GC->getGenericParams())
return true;
}
}
} while ((dc = dc->getParentForLookup()));
return false;
}
ResilienceExpansion DeclContext::getResilienceExpansion() const {
auto fragileKind = getFragileFunctionKind();
switch (fragileKind.kind) {
case FragileFunctionKind::Transparent:
case FragileFunctionKind::Inlinable:
case FragileFunctionKind::AlwaysEmitIntoClient:
case FragileFunctionKind::DefaultArgument:
case FragileFunctionKind::PropertyInitializer:
case FragileFunctionKind::BackDeploy:
return ResilienceExpansion::Minimal;
case FragileFunctionKind::None:
return ResilienceExpansion::Maximal;
}
llvm_unreachable("Bad fragile function kind");
}
FragileFunctionKind DeclContext::getFragileFunctionKind() const {
auto &context = getASTContext();
return evaluateOrDefault(context.evaluator,
FragileFunctionKindRequest { const_cast<DeclContext *>(this) },
{FragileFunctionKind::None, false});
}
FragileFunctionKind
swift::FragileFunctionKindRequest::evaluate(Evaluator &evaluator,
DeclContext *context) const {
for (const auto *dc = context->getLocalContext(); dc && dc->isLocalContext();
dc = dc->getParent()) {
// Default argument initializer contexts have their resilience expansion
// set when they're type checked.
if (isa<DefaultArgumentInitializer>(dc)) {
dc = dc->getParent();
auto *VD = cast<ValueDecl>(dc->getAsDecl());
assert(VD->hasParameterList());
if (VD->getDeclContext()->isLocalContext()) {
auto kind = VD->getDeclContext()->getFragileFunctionKind();
if (kind.kind != FragileFunctionKind::None)
return {FragileFunctionKind::DefaultArgument,
kind.allowUsableFromInline};
}
auto effectiveAccess =
VD->getFormalAccessScope(/*useDC=*/nullptr,
/*treatUsableFromInlineAsPublic=*/true);
auto formalAccess =
VD->getFormalAccessScope(/*useDC=*/nullptr,
/*treatUsableFromInlineAsPublic=*/false);
if (effectiveAccess.isPublic()) {
return {FragileFunctionKind::DefaultArgument,
!formalAccess.isPublic()};
}
return {FragileFunctionKind::None,
/*allowUsableFromInline=*/false};
}
// Stored property initializer contexts use minimal resilience expansion
// if the type is formally fixed layout.
if (auto *init = dyn_cast <PatternBindingInitializer>(dc)) {
auto bindingIndex = init->getBindingIndex();
if (auto *varDecl = init->getBinding()->getAnchoringVarDecl(bindingIndex)) {
if (varDecl->isInitExposedToClients()) {
return {FragileFunctionKind::PropertyInitializer,
/*allowUsableFromInline=*/true};
}
}
return {FragileFunctionKind::None,
/*allowUsableFromInline=*/false};
}
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(dc)) {
// If the function is a nested function, we will serialize its body if
// we serialize the parent's body.
if (AFD->getDeclContext()->isLocalContext())
continue;
auto funcAccess =
AFD->getFormalAccessScope(/*useDC=*/nullptr,
/*treatUsableFromInlineAsPublic=*/true);
// If the function is not externally visible, we will not be serializing
// its body.
if (!funcAccess.isPublic()) {
return {FragileFunctionKind::None,
/*allowUsableFromInline=*/false};
}
// If the function is public, @_transparent implies @inlinable.
if (AFD->isTransparent()) {
return {FragileFunctionKind::Transparent,
/*allowUsableFromInline=*/true};
}
if (AFD->getAttrs().hasAttribute<InlinableAttr>()) {
return {FragileFunctionKind::Inlinable,
/*allowUsableFromInline=*/true};
}
if (AFD->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>()) {
return {FragileFunctionKind::AlwaysEmitIntoClient,
/*allowUsableFromInline=*/true};
}
if (AFD->getAttrs().hasAttribute<BackDeployAttr>()) {
return {FragileFunctionKind::BackDeploy,
/*allowUsableFromInline=*/true};
}
// Property and subscript accessors inherit @_alwaysEmitIntoClient,
// @_backDeploy, and @inlinable from their storage declarations.
if (auto accessor = dyn_cast<AccessorDecl>(AFD)) {
auto *storage = accessor->getStorage();
if (storage->getAttrs().getAttribute<InlinableAttr>()) {
return {FragileFunctionKind::Inlinable,
/*allowUsableFromInline=*/true};
}
if (storage->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>()) {
return {FragileFunctionKind::AlwaysEmitIntoClient,
/*allowUsableFromInline=*/true};
}
if (storage->getAttrs().hasAttribute<BackDeployAttr>()) {
return {FragileFunctionKind::BackDeploy,
/*allowUsableFromInline=*/true};
}
}
}
}
return {FragileFunctionKind::None,
/*allowUsableFromInline=*/false};
}
/// Determine whether the innermost context is generic.
bool DeclContext::isInnermostContextGeneric() const {
if (auto Decl = getAsDecl())
if (auto GC = Decl->getAsGenericContext())
return GC->isGeneric();
return false;
}
unsigned DeclContext::getSyntacticDepth() const {
// Module scope == depth 0.
if (isModuleScopeContext())
return 0;
return 1 + getParent()->getSyntacticDepth();
}
unsigned DeclContext::getSemanticDepth() const {
// For extensions, count the depth of the nominal type being extended.
if (isa<ExtensionDecl>(this)) {
if (auto nominal = getSelfNominalTypeDecl())
return nominal->getSemanticDepth();
return 1;
}
// Module scope == depth 0.
if (isModuleScopeContext())
return 0;
return 1 + getParent()->getSemanticDepth();
}
bool DeclContext::mayContainMembersAccessedByDynamicLookup() const {
// Members of non-generic classes and class extensions can be found by
/// dynamic lookup.
if (auto *CD = getSelfClassDecl())
return !CD->isGenericContext();
// Members of @objc protocols (but not protocol extensions) can be
// found by dynamic lookup.
if (auto *PD = dyn_cast<ProtocolDecl>(this))
return PD->getAttrs().hasAttribute<ObjCAttr>();
return false;
}
bool DeclContext::canBeParentOfExtension() const {
return isa<SourceFile>(this);
}
bool DeclContext::walkContext(ASTWalker &Walker) {
switch (getContextKind()) {
case DeclContextKind::Module:
return cast<ModuleDecl>(this)->walk(Walker);
case DeclContextKind::FileUnit:
return cast<FileUnit>(this)->walk(Walker);
case DeclContextKind::AbstractClosureExpr:
return cast<AbstractClosureExpr>(this)->walk(Walker);
case DeclContextKind::GenericTypeDecl:
return cast<GenericTypeDecl>(this)->walk(Walker);
case DeclContextKind::ExtensionDecl:
return cast<ExtensionDecl>(this)->walk(Walker);
case DeclContextKind::TopLevelCodeDecl:
return cast<TopLevelCodeDecl>(this)->walk(Walker);
case DeclContextKind::AbstractFunctionDecl:
return cast<AbstractFunctionDecl>(this)->walk(Walker);
case DeclContextKind::SubscriptDecl:
return cast<SubscriptDecl>(this)->walk(Walker);
case DeclContextKind::EnumElementDecl:
return cast<EnumElementDecl>(this)->walk(Walker);
case DeclContextKind::SerializedLocal:
llvm_unreachable("walk is unimplemented for deserialized contexts");
case DeclContextKind::Initializer:
// Is there any point in trying to walk the expression?
return false;
}
llvm_unreachable("bad DeclContextKind");
}
void DeclContext::dumpContext() const {
printContext(llvm::errs());
}
void AccessScope::dump() const {
llvm::errs() << getAccessLevelSpelling(accessLevelForDiagnostics()) << ": ";
if (isPublic()) {
llvm::errs() << "(null)\n";
return;
}
if (auto *file = dyn_cast<SourceFile>(getDeclContext())) {
llvm::errs() << "file '" << file->getFilename() << "'\n";
return;
}
if (auto *decl = getDeclContext()->getAsDecl()) {
llvm::errs() << Decl::getKindName(decl->getKind()) << " ";
if (auto *ext = dyn_cast<ExtensionDecl>(decl)) {
auto *extended = ext->getExtendedNominal();
if (extended)
llvm::errs() << extended->getName();
else
llvm::errs() << "(null)";
} else if (auto *named = dyn_cast<ValueDecl>(decl)) {
llvm::errs() << named->getName();
} else {
llvm::errs() << (const void *)decl;
}
SourceLoc loc = decl->getLoc();
if (loc.isValid()) {
llvm::errs() << " at ";
loc.print(llvm::errs(), decl->getASTContext().SourceMgr);
}
llvm::errs() << "\n";
return;
}
// If all else fails, dump the DeclContext tree.
getDeclContext()->printContext(llvm::errs());
}
template <typename DCType>
static unsigned getLineNumber(DCType *DC) {
SourceLoc loc = DC->getLoc();
if (loc.isInvalid())
return 0;
const ASTContext &ctx = static_cast<const DeclContext *>(DC)->getASTContext();
return ctx.SourceMgr.getPresumedLineAndColumnForLoc(loc).first;
}
unsigned DeclContext::printContext(raw_ostream &OS, const unsigned indent,
const bool onlyAPartialLine) const {
unsigned Depth = 0;
if (!onlyAPartialLine)
if (auto *P = getParent())
Depth = P->printContext(OS, indent);
const char *Kind;
switch (getContextKind()) {
case DeclContextKind::Module: Kind = "Module"; break;
case DeclContextKind::FileUnit: Kind = "FileUnit"; break;
case DeclContextKind::SerializedLocal: Kind = "Serialized Local"; break;
case DeclContextKind::AbstractClosureExpr:
Kind = "AbstractClosureExpr";
break;
case DeclContextKind::GenericTypeDecl:
switch (cast<GenericTypeDecl>(this)->getKind()) {
#define DECL(ID, PARENT) \
case DeclKind::ID: Kind = #ID "Decl"; break;
#include "swift/AST/DeclNodes.def"
}
break;
case DeclContextKind::ExtensionDecl: Kind = "ExtensionDecl"; break;
case DeclContextKind::TopLevelCodeDecl: Kind = "TopLevelCodeDecl"; break;
case DeclContextKind::Initializer: Kind = "Initializer"; break;
case DeclContextKind::AbstractFunctionDecl:
Kind = "AbstractFunctionDecl";
break;
case DeclContextKind::SubscriptDecl: Kind = "SubscriptDecl"; break;
case DeclContextKind::EnumElementDecl: Kind = "EnumElementDecl"; break;
}
OS.indent(Depth*2 + indent) << (void*)this << " " << Kind;
switch (getContextKind()) {
case DeclContextKind::Module:
OS << " name=" << cast<ModuleDecl>(this)->getName();
break;
case DeclContextKind::FileUnit:
switch (cast<FileUnit>(this)->getKind()) {
case FileUnitKind::Builtin:
OS << " Builtin";
break;
case FileUnitKind::Source:
OS << " file=\"" << cast<SourceFile>(this)->getFilename() << "\"";
break;
case FileUnitKind::Synthesized:
OS << " synthesized file";
break;
case FileUnitKind::SerializedAST:
case FileUnitKind::ClangModule:
case FileUnitKind::DWARFModule:
OS << " file=\"" << cast<LoadedFile>(this)->getFilename() << "\"";
break;
}
break;
case DeclContextKind::AbstractClosureExpr:
OS << " line=" << getLineNumber(cast<AbstractClosureExpr>(this));
OS << " : " << cast<AbstractClosureExpr>(this)->getType();
break;
case DeclContextKind::GenericTypeDecl:
OS << " name=" << cast<GenericTypeDecl>(this)->getName();
break;
case DeclContextKind::ExtensionDecl:
OS << " line=" << getLineNumber(cast<ExtensionDecl>(this));
OS << " base=" << cast<ExtensionDecl>(this)->getExtendedType();
break;
case DeclContextKind::TopLevelCodeDecl:
OS << " line=" << getLineNumber(cast<TopLevelCodeDecl>(this));
break;
case DeclContextKind::AbstractFunctionDecl: {
auto *AFD = cast<AbstractFunctionDecl>(this);
OS << " name=" << AFD->getName();
if (AFD->hasInterfaceType())
OS << " : " << AFD->getInterfaceType();
else
OS << " : (no type set)";
break;
}
case DeclContextKind::SubscriptDecl: {
auto *SD = cast<SubscriptDecl>(this);
OS << " name=" << SD->getBaseName();
if (SD->hasInterfaceType())
OS << " : " << SD->getInterfaceType();
else
OS << " : (no type set)";
break;
}
case DeclContextKind::EnumElementDecl: {
auto *EED = cast<EnumElementDecl>(this);
OS << " name=" << EED->getBaseName();
if (EED->hasInterfaceType())
OS << " : " << EED->getInterfaceType();
else
OS << " : (no type set)";
break;
}
case DeclContextKind::Initializer:
switch (cast<Initializer>(this)->getInitializerKind()) {
case InitializerKind::PatternBinding: {
auto init = cast<PatternBindingInitializer>(this);
OS << " PatternBinding 0x" << (void*) init->getBinding()
<< " #" << init->getBindingIndex();
break;
}
case InitializerKind::DefaultArgument: {
auto init = cast<DefaultArgumentInitializer>(this);
OS << " DefaultArgument index=" << init->getIndex();
break;
}
case InitializerKind::PropertyWrapper: {
auto init = cast<PropertyWrapperInitializer>(this);
OS << "PropertyWrapper 0x" << (void*)init->getWrappedVar() << ", kind=";
switch (init->getKind()) {
case PropertyWrapperInitializer::Kind::WrappedValue:
OS << "wrappedValue";
break;
case PropertyWrapperInitializer::Kind::ProjectedValue:
OS << "projectedValue";
break;
}
break;
}
}
break;
case DeclContextKind::SerializedLocal: {
auto local = cast<SerializedLocalDeclContext>(this);
switch (local->getLocalDeclContextKind()) {
case LocalDeclContextKind::AbstractClosure: {
auto serializedClosure = cast<SerializedAbstractClosureExpr>(local);
OS << " closure : " << serializedClosure->getType();
break;
}
case LocalDeclContextKind::DefaultArgumentInitializer: {
auto init = cast<SerializedDefaultArgumentInitializer>(local);
OS << "DefaultArgument index=" << init->getIndex();
break;
}
case LocalDeclContextKind::PatternBindingInitializer: {
auto init = cast<SerializedPatternBindingInitializer>(local);
OS << " PatternBinding 0x" << (void*) init->getBinding()
<< " #" << init->getBindingIndex();
break;
}
case LocalDeclContextKind::TopLevelCodeDecl:
OS << " TopLevelCode";
break;
}
}
}
if (auto decl = getAsDecl())
if (decl->getClangNode().getLocation().isValid()) {
auto &clangSM = getASTContext().getClangModuleLoader()
->getClangASTContext().getSourceManager();
OS << " clang_loc=";
decl->getClangNode().getLocation().print(OS, clangSM);
}
if (!onlyAPartialLine)
OS << "\n";
return Depth + 1;
}
const Decl *
IterableDeclContext::getDecl() const {
switch (getIterableContextKind()) {
case IterableDeclContextKind::NominalTypeDecl:
return cast<NominalTypeDecl>(this);
break;
case IterableDeclContextKind::ExtensionDecl:
return cast<ExtensionDecl>(this);
break;
}
llvm_unreachable("Unhandled IterableDeclContextKind in switch.");
}
GenericContext *IterableDeclContext::getAsGenericContext() {
switch (getIterableContextKind()) {
case IterableDeclContextKind::NominalTypeDecl:
return cast<NominalTypeDecl>(this);
case IterableDeclContextKind::ExtensionDecl:
return cast<ExtensionDecl>(this);
}
llvm_unreachable("Unhandled IterableDeclContextKind in switch.");
}
ASTContext &IterableDeclContext::getASTContext() const {
return getDecl()->getASTContext();
}
DeclRange IterableDeclContext::getCurrentMembersWithoutLoading() const {
return DeclRange(FirstDeclAndLazyMembers.getPointer(), nullptr);
}
DeclRange IterableDeclContext::getMembers() const {
loadAllMembers();
return getCurrentMembersWithoutLoading();
}
ArrayRef<Decl *> IterableDeclContext::getParsedMembers() const {
ASTContext &ctx = getASTContext();
auto mutableThis = const_cast<IterableDeclContext *>(this);
return evaluateOrDefault(
ctx.evaluator, ParseMembersRequest{mutableThis},
FingerprintAndMembers())
.members;
}
ArrayRef<Decl *> IterableDeclContext::getABIMembers() const {
ASTContext &ctx = getASTContext();
return evaluateOrDefault(
ctx.evaluator,
ABIMembersRequest{const_cast<IterableDeclContext *>(this)},
ArrayRef<Decl *>());
}
ArrayRef<Decl *> IterableDeclContext::getAllMembers() const {
ASTContext &ctx = getASTContext();
return evaluateOrDefault(
ctx.evaluator,
AllMembersRequest{const_cast<IterableDeclContext *>(this)},
ArrayRef<Decl *>());
}
void IterableDeclContext::addMemberPreservingSourceOrder(Decl *member) {
auto &SM = getASTContext().SourceMgr;
SourceLoc start = member->getStartLoc();
Decl *hint = nullptr;
for (auto *existingMember : getMembers()) {
if (existingMember->isImplicit())
continue;
// An EnumCaseDecl contains one or more EnumElementDecls,
// but the EnumElementDecls are also added as members of
// the parent enum. We ignore the EnumCaseDecl since its
// source range overlaps with that of the EnumElementDecls.
if (isa<EnumCaseDecl>(existingMember))
continue;
// The elements of the active clause of an IfConfigDecl
// are added to the parent type. We ignore the IfConfigDecl
// since its source range overlaps with the source ranges
// of the active elements.
if (isa<IfConfigDecl>(existingMember))
continue;
if (!SM.isBeforeInBuffer(existingMember->getEndLoc(), start))
break;
hint = existingMember;
}
addMember(member, hint, /*insertAtHead=*/hint == nullptr);
}
/// Add a member to this context.
void IterableDeclContext::addMember(Decl *member, Decl *hint, bool insertAtHead) {
// Add the member to the list of declarations without notification.
addMemberSilently(member, hint, insertAtHead);
// Notify our parent declaration that we have added the member, which can
// be used to update the lookup tables.
switch (getIterableContextKind()) {
case IterableDeclContextKind::NominalTypeDecl: {
auto nominal = cast<NominalTypeDecl>(this);
nominal->addedMember(member);
assert(member->getDeclContext() == nominal &&
"Added member to the wrong context");
break;
}
case IterableDeclContextKind::ExtensionDecl: {
auto ext = cast<ExtensionDecl>(this);
ext->addedMember(member);
assert(member->getDeclContext() == ext &&
"Added member to the wrong context");
break;
}
}
}
void IterableDeclContext::addMemberSilently(Decl *member, Decl *hint,
bool insertAtHead) const {
assert(!isa<AccessorDecl>(member) && "Accessors should not be added here");
assert(!member->NextDecl && "Already added to a container");
#ifndef NDEBUG
// Assert that new declarations are always added in source order.
auto checkSourceRange = [&](Decl *prev, Decl *next) {
// SKip these checks for imported and deserialized decls.
if (!member->getDeclContext()->getParentSourceFile())
return;
auto shouldSkip = [](Decl *d) {
// PatternBindingDecl source ranges overlap with VarDecls,
// EnumCaseDecl source ranges overlap with EnumElementDecls,
// and IfConfigDecl source ranges overlap with the elements
// of the active clause. Skip them all here to avoid
// spurious assertions.
if (isa<PatternBindingDecl>(d) ||
isa<EnumCaseDecl>(d) ||
isa<IfConfigDecl>(d))
return true;
// Ignore source location information of implicit declarations.
if (d->isImplicit())
return true;
// Imported decls won't have complete location info.
if (d->hasClangNode())
return true;
return false;
};
if (shouldSkip(prev) || shouldSkip(next))
return;
SourceLoc prevEnd = prev->getEndLoc();
SourceLoc nextStart = next->getStartLoc();
assert(prevEnd.isValid() &&
"Only implicit decls can have invalid source location");
assert(nextStart.isValid() &&
"Only implicit decls can have invalid source location");
if (getASTContext().SourceMgr.isBeforeInBuffer(prevEnd, nextStart))
return;
llvm::errs() << "Source ranges out of order in addMember():\n";
prev->dump(llvm::errs());
next->dump(llvm::errs());
abort();
};
#endif
// Empty list.
if (!FirstDeclAndLazyMembers.getPointer()) {
assert(hint == nullptr);
FirstDeclAndLazyMembers.setPointer(member);
LastDeclAndKind.setPointer(member);
// Insertion at the head.
} else if (insertAtHead) {
assert(hint == nullptr);
member->NextDecl = FirstDeclAndLazyMembers.getPointer();
FirstDeclAndLazyMembers.setPointer(member);
// Insertion at the tail.
} else if (hint == nullptr) {
auto *last = LastDeclAndKind.getPointer();
#ifndef NDEBUG
checkSourceRange(last, member);
#endif
last->NextDecl = member;
LastDeclAndKind.setPointer(member);
// Insertion after 'hint' (which may be the tail).
} else {
#ifndef NDEBUG
checkSourceRange(hint, member);
#endif
member->NextDecl = hint->NextDecl;
hint->NextDecl = member;
// Handle case where the 'hint' is the tail.
if (LastDeclAndKind.getPointer() == hint)
LastDeclAndKind.setPointer(member);
}
}
void IterableDeclContext::setMemberLoader(LazyMemberLoader *loader,
uint64_t contextData) {
assert(!hasLazyMembers() && "already have lazy members");
ASTContext &ctx = getASTContext();
auto contextInfo = ctx.getOrCreateLazyIterableContextData(this, loader);
FirstDeclAndLazyMembers.setInt(true);
contextInfo->memberData = contextData;
++NumLazyIterableDeclContexts;
++NumUnloadedLazyIterableDeclContexts;
// FIXME: (transitional) increment the redundant "always-on" counter.
if (auto s = ctx.Stats) {
++s->getFrontendCounters().NumLazyIterableDeclContexts;
++s->getFrontendCounters().NumUnloadedLazyIterableDeclContexts;
}
}
bool IterableDeclContext::hasUnparsedMembers() const {
if (AddedParsedMembers)
return false;
if (!getAsGenericContext()->getParentSourceFile()) {
// There will never be any parsed members to add, so set the flag to say
// we are done so we can short-circuit next time.
const_cast<IterableDeclContext *>(this)->AddedParsedMembers = 1;
return false;
}
return true;
}
void IterableDeclContext::setHasLazyMembers(bool hasLazyMembers) const {
FirstDeclAndLazyMembers.setInt(hasLazyMembers);
}
void IterableDeclContext::loadAllMembers() const {
ASTContext &ctx = getASTContext();
// For contexts within a source file, get the list of parsed members.
if (getAsGenericContext()->getParentSourceFile()) {
// Retrieve the parsed members. Even if we've already added the parsed
// members to this context, this call is important for recording the
// dependency edge.
auto mutableThis = const_cast<IterableDeclContext *>(this);
auto members = getParsedMembers();
// If we haven't already done so, add these members to this context.
if (!AddedParsedMembers) {
mutableThis->AddedParsedMembers = 1;
for (auto member : members) {
mutableThis->addMember(member);
}
}
}
if (!hasLazyMembers())
return;
// Don't try to load all members re-entrant-ly.
setHasLazyMembers(false);
const Decl *container = getDecl();
auto contextInfo = ctx.getOrCreateLazyIterableContextData(this,
/*lazyLoader=*/nullptr);
contextInfo->loader->loadAllMembers(const_cast<Decl *>(container),
contextInfo->memberData);
--NumUnloadedLazyIterableDeclContexts;
// FIXME: (transitional) decrement the redundant "always-on" counter.
if (auto s = ctx.Stats)
--s->getFrontendCounters().NumUnloadedLazyIterableDeclContexts;
}
bool IterableDeclContext::wasDeserialized() const {
const DeclContext *DC = getAsGenericContext();
if (auto F = dyn_cast<FileUnit>(DC->getModuleScopeContext())) {
return F->getKind() == FileUnitKind::SerializedAST;
}
return false;
}
bool IterableDeclContext::classof(const Decl *D) {
switch (D->getKind()) {
default: return false;
#define DECL(ID, PARENT) // See previous line
#define ITERABLE_DECL(ID, PARENT) \
case DeclKind::ID: return true;
#include "swift/AST/DeclNodes.def"
}
}
IterableDeclContext *
IterableDeclContext::castDeclToIterableDeclContext(const Decl *D) {
switch (D->getKind()) {
default: llvm_unreachable("Decl is not a IterableDeclContext.");
#define DECL(ID, PARENT) // See previous line
#define ITERABLE_DECL(ID, PARENT) \
case DeclKind::ID: \
return const_cast<IterableDeclContext *>( \
static_cast<const IterableDeclContext*>(cast<ID##Decl>(D)));
#include "swift/AST/DeclNodes.def"
}
}
Optional<Fingerprint> IterableDeclContext::getBodyFingerprint() const {
auto fileUnit = dyn_cast<FileUnit>(getAsGenericContext()->getModuleScopeContext());
if (!fileUnit)
return None;
if (isa<SourceFile>(fileUnit)) {
auto mutableThis = const_cast<IterableDeclContext *>(this);
return evaluateOrDefault(getASTContext().evaluator,
ParseMembersRequest{mutableThis},
FingerprintAndMembers())
.fingerprint;
}
if (getDecl()->isImplicit())
return None;
return fileUnit->loadFingerprint(this);
}
/// Return the DeclContext to compare when checking private access in
/// Swift 4 mode. The context returned is the type declaration if the context
/// and the type declaration are in the same file, otherwise it is the types
/// last extension in the source file. If the context does not refer to a
/// declaration or extension, the supplied context is returned.
static const DeclContext *
getPrivateDeclContext(const DeclContext *DC, const SourceFile *useSF) {
auto NTD = DC->getSelfNominalTypeDecl();
if (!NTD)
return DC;
// use the type declaration as the private scope if it is in the same
// file as useSF. This occurs for both extensions and declarations.
if (NTD->getParentSourceFile() == useSF)
return NTD;
// Otherwise use the last extension declaration in the same file.
const DeclContext *lastExtension = nullptr;
for (ExtensionDecl *ED : NTD->getExtensions())
if (ED->getParentSourceFile() == useSF)
lastExtension = ED;
// If there's no last extension, return the supplied context.
return lastExtension ? lastExtension : DC;
}
AccessScope::AccessScope(const DeclContext *DC, bool isPrivate)
: Value(DC, isPrivate) {
if (isPrivate) {
DC = getPrivateDeclContext(DC, DC->getParentSourceFile());
Value.setPointer(DC);
}
if (!DC || isa<ModuleDecl>(DC))
assert(!isPrivate && "public or internal scope can't be private");
}
bool AccessScope::isFileScope() const {
auto DC = getDeclContext();
return DC && isa<FileUnit>(DC);
}
bool AccessScope::isInternal() const {
auto DC = getDeclContext();
return DC && isa<ModuleDecl>(DC);
}
AccessLevel AccessScope::accessLevelForDiagnostics() const {
if (isPublic())
return AccessLevel::Public;
if (isa<ModuleDecl>(getDeclContext()))
return AccessLevel::Internal;
if (getDeclContext()->isModuleScopeContext()) {
return isPrivate() ? AccessLevel::Private : AccessLevel::FilePrivate;
}
return AccessLevel::Private;
}
bool AccessScope::allowsPrivateAccess(const DeclContext *useDC, const DeclContext *sourceDC) {
// Check the lexical scope.
if (useDC->isChildContextOf(sourceDC))
return true;
// Do not allow access if the sourceDC is in a different file
auto useSF = useDC->getParentSourceFile();
if (useSF != sourceDC->getParentSourceFile())
return false;
// Do not allow access if the sourceDC does not represent a type.
auto sourceNTD = sourceDC->getSelfNominalTypeDecl();
if (!sourceNTD)
return false;
// Compare the private scopes and iterate over the parent types.
sourceDC = getPrivateDeclContext(sourceDC, useSF);
while (!useDC->isModuleContext()) {
useDC = getPrivateDeclContext(useDC, useSF);
if (useDC == sourceDC)
return true;
// Get the parent type. If the context represents a type, look at the types
// declaring context instead of the contexts parent. This will crawl up
// the type hierarchy in nested extensions correctly.
if (auto NTD = useDC->getSelfNominalTypeDecl())
useDC = NTD->getDeclContext();
else
useDC = useDC->getParent();
}
return false;
}
DeclContext *Decl::getDeclContextForModule() const {
if (auto module = dyn_cast<ModuleDecl>(this))
return const_cast<ModuleDecl *>(module);
return nullptr;
}
DeclContextKind DeclContext::getContextKind() const {
switch (ParentAndKind.getInt()) {
case ASTHierarchy::Expr:
return DeclContextKind::AbstractClosureExpr;
case ASTHierarchy::Initializer:
return DeclContextKind::Initializer;
case ASTHierarchy::SerializedLocal:
return DeclContextKind::SerializedLocal;
case ASTHierarchy::FileUnit:
return DeclContextKind::FileUnit;
case ASTHierarchy::Decl: {
auto decl = reinterpret_cast<const Decl*>(this + 1);
if (isa<AbstractFunctionDecl>(decl))
return DeclContextKind::AbstractFunctionDecl;
if (isa<GenericTypeDecl>(decl))
return DeclContextKind::GenericTypeDecl;
switch (decl->getKind()) {
case DeclKind::Module:
return DeclContextKind::Module;
case DeclKind::TopLevelCode:
return DeclContextKind::TopLevelCodeDecl;
case DeclKind::Subscript:
return DeclContextKind::SubscriptDecl;
case DeclKind::EnumElement:
return DeclContextKind::EnumElementDecl;
case DeclKind::Extension:
return DeclContextKind::ExtensionDecl;
default:
llvm_unreachable("Unhandled Decl kind");
}
}
}
llvm_unreachable("Unhandled DeclContext ASTHierarchy");
}
bool DeclContext::hasValueSemantics() const {
if (getExtendedProtocolDecl())
return !isClassConstrainedProtocolExtension();
return !getDeclaredInterfaceType()->hasReferenceSemantics();
}
bool DeclContext::isClassConstrainedProtocolExtension() const {
if (getExtendedProtocolDecl()) {
auto ED = cast<ExtensionDecl>(this);
if (auto sig = ED->getGenericSignature()) {
return sig->requiresClass(ED->getSelfInterfaceType());
}
}
return false;
}
bool DeclContext::isAsyncContext() const {
switch (getContextKind()) {
case DeclContextKind::Initializer:
case DeclContextKind::EnumElementDecl:
case DeclContextKind::ExtensionDecl:
case DeclContextKind::SerializedLocal:
case DeclContextKind::Module:
case DeclContextKind::GenericTypeDecl:
return false;
case DeclContextKind::FileUnit:
if (const SourceFile *sf = dyn_cast<SourceFile>(this))
return sf->isAsyncTopLevelSourceFile();
return false;
case DeclContextKind::TopLevelCodeDecl:
return getParent()->isAsyncContext();
case DeclContextKind::AbstractClosureExpr:
return cast<AbstractClosureExpr>(this)->isBodyAsync();
case DeclContextKind::AbstractFunctionDecl: {
const AbstractFunctionDecl *function = cast<AbstractFunctionDecl>(this);
return function->hasAsync();
}
case DeclContextKind::SubscriptDecl: {
AccessorDecl *getter =
cast<SubscriptDecl>(this)->getAccessor(AccessorKind::Get);
return getter != nullptr && getter->hasAsync();
}
}
llvm_unreachable("Unhandled DeclContextKind switch");
}
SourceLoc swift::extractNearestSourceLoc(const DeclContext *dc) {
switch (dc->getContextKind()) {
case DeclContextKind::Module:
return SourceLoc();
case DeclContextKind::AbstractFunctionDecl:
case DeclContextKind::EnumElementDecl:
case DeclContextKind::ExtensionDecl:
case DeclContextKind::GenericTypeDecl:
case DeclContextKind::SubscriptDecl:
case DeclContextKind::TopLevelCodeDecl:
return extractNearestSourceLoc(dc->getAsDecl());
case DeclContextKind::AbstractClosureExpr: {
SourceLoc loc = cast<AbstractClosureExpr>(dc)->getLoc();
if (loc.isValid())
return loc;
return extractNearestSourceLoc(dc->getParent());
}
case DeclContextKind::FileUnit:
return SourceLoc();
case DeclContextKind::Initializer:
case DeclContextKind::SerializedLocal:
return extractNearestSourceLoc(dc->getParent());
}
llvm_unreachable("Unhandled DeclContextKindIn switch");
}
#define DECL(Id, Parent) \
static_assert(!std::is_base_of<DeclContext, Id##Decl>::value, \
"Non-context Decl node has context?");
#define CONTEXT_DECL(Id, Parent) \
static_assert(alignof(DeclContext) == alignof(Id##Decl), "Alignment error"); \
static_assert(std::is_base_of<DeclContext, Id##Decl>::value, \
"CONTEXT_DECL nodes must inherit from DeclContext");
#define CONTEXT_VALUE_DECL(Id, Parent) \
static_assert(alignof(DeclContext) == alignof(Id##Decl), "Alignment error"); \
static_assert(std::is_base_of<DeclContext, Id##Decl>::value, \
"CONTEXT_VALUE_DECL nodes must inherit from DeclContext");
#include "swift/AST/DeclNodes.def"
#define EXPR(Id, Parent) \
static_assert(!std::is_base_of<DeclContext, Id##Expr>::value, \
"Non-context Expr node has context?");
#define CONTEXT_EXPR(Id, Parent) \
static_assert(alignof(DeclContext) == alignof(Id##Expr), "Alignment error"); \
static_assert(std::is_base_of<DeclContext, Id##Expr>::value, \
"CONTEXT_EXPR nodes must inherit from DeclContext");
#include "swift/AST/ExprNodes.def"
#ifndef NDEBUG
// XXX -- static_cast is not static enough for use with static_assert().
// DO verify this by temporarily breaking a Decl or Expr.
// DO NOT assume that the compiler will emit this code blindly.
SWIFT_CONSTRUCTOR
static void verify_DeclContext_is_start_of_node() {
auto decl = reinterpret_cast<Decl*>(0x1000 + sizeof(DeclContext));
#define DECL(Id, Parent)
#define CONTEXT_DECL(Id, Parent) \
assert(reinterpret_cast<DeclContext*>(0x1000) == \
static_cast<Id##Decl*>(decl));
#define CONTEXT_VALUE_DECL(Id, Parent) \
assert(reinterpret_cast<DeclContext*>(0x1000) == \
static_cast<Id##Decl*>(decl));
#include "swift/AST/DeclNodes.def"
auto expr = reinterpret_cast<Expr*>(0x1000 + sizeof(DeclContext));
#define EXPR(Id, Parent)
#define CONTEXT_EXPR(Id, Parent) \
assert(reinterpret_cast<DeclContext*>(0x1000) == \
static_cast<Id##Expr*>(expr));
#include "swift/AST/ExprNodes.def"
}
#endif
void swift::simple_display(llvm::raw_ostream &out,
const IterableDeclContext *idc) {
simple_display(out, idc->getDecl());
}
SourceLoc swift::extractNearestSourceLoc(const IterableDeclContext *idc) {
return extractNearestSourceLoc(idc->getDecl());
}
static bool isSpecializeExtensionContext(const DeclContext *dc) {
if (dc->isModuleScopeContext())
return false;
if (auto *extCtx = dyn_cast<ExtensionDecl>(dc)) {
// and has specialized attr ...
return extCtx->getAttrs().hasAttribute<SpecializeExtensionAttr>();
}
auto *parentDecl = dc->getParent();
return isSpecializeExtensionContext(parentDecl);
}
bool DeclContext::isInSpecializeExtensionContext() const {
return isSpecializeExtensionContext(this);
}
bool DeclContext::isAlwaysAvailableConformanceContext() const {
auto *ext = dyn_cast<ExtensionDecl>(this);
if (ext == nullptr)
return true;
if (AvailableAttr::isUnavailable(ext))
return false;
auto &ctx = getASTContext();
AvailabilityContext conformanceAvailability{
AvailabilityInference::availableRange(ext, ctx)};
auto deploymentTarget =
AvailabilityContext::forDeploymentTarget(ctx);
return deploymentTarget.isContainedIn(conformanceAvailability);
}
| {
"content_hash": "ab17997b7fb4a5850126cd1ba49124cb",
"timestamp": "",
"source": "github",
"line_count": 1388,
"max_line_length": 94,
"avg_line_length": 32.36671469740634,
"alnum_prop": 0.6815581524763494,
"repo_name": "ahoppen/swift",
"id": "92bef88e4d371c5e22c9f861e84ea407ada17284",
"size": "44925",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "lib/AST/DeclContext.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "45571"
},
{
"name": "C",
"bytes": "5428926"
},
{
"name": "C++",
"bytes": "46840716"
},
{
"name": "CMake",
"bytes": "694118"
},
{
"name": "D",
"bytes": "1107"
},
{
"name": "DTrace",
"bytes": "2593"
},
{
"name": "Emacs Lisp",
"bytes": "57594"
},
{
"name": "LLVM",
"bytes": "74481"
},
{
"name": "Makefile",
"bytes": "2361"
},
{
"name": "Objective-C",
"bytes": "466082"
},
{
"name": "Objective-C++",
"bytes": "159688"
},
{
"name": "Python",
"bytes": "1968205"
},
{
"name": "Roff",
"bytes": "3683"
},
{
"name": "Ruby",
"bytes": "2132"
},
{
"name": "Shell",
"bytes": "214936"
},
{
"name": "Swift",
"bytes": "38740617"
},
{
"name": "Vim Script",
"bytes": "20025"
},
{
"name": "sed",
"bytes": "1050"
}
],
"symlink_target": ""
} |
Many users would like to deploy TensorFlow lite interpreter and use it from
Python without requiring the rest of TensorFlow.
## Steps
To build a binary wheel run this script:
```sh
sudo apt install swig libjpeg-dev zlib1g-dev python3-dev python3-numpy
sh tensorflow/lite/tools/make/download_dependencies.sh
sh tensorflow/lite/tools/pip_package/build_pip_package.sh
```
That will print out some output and a .whl file. You can then install that
```sh
pip install --upgrade <wheel>
```
You can also build a wheel inside docker container using make tool. For example
the following command will cross-compile tflite-runtime package for python2.7
and python3.7 (from Debian Buster) on Raspberry Pi:
```sh
make BASE_IMAGE=debian:buster PYTHON=python TENSORFLOW_TARGET=rpi docker-build
make BASE_IMAGE=debian:buster PYTHON=python3 TENSORFLOW_TARGET=rpi docker-build
```
Another option is to cross-compile for python3.5 (from Debian Stretch) on ARM64
board:
```sh
make BASE_IMAGE=debian:stretch PYTHON=python3 TENSORFLOW_TARGET=aarch64 docker-build
```
To build for python3.6 (from Ubuntu 18.04) on x86_64 (native to the docker
image) run:
```sh
make BASE_IMAGE=ubuntu:18.04 PYTHON=python3 TENSORFLOW_TARGET=native docker-build
```
In addition to the wheel there is a way to build Debian package by adding
BUILD_DEB=y to the make command (only for python3):
```sh
make BASE_IMAGE=debian:buster PYTHON=python3 TENSORFLOW_TARGET=rpi BUILD_DEB=y docker-build
```
Note, unlike tensorflow this will be installed to a tflite_runtime namespace.
You can then use the Tensorflow Lite interpreter as.
```python
from tflite_runtime.interpreter import Interpreter
interpreter = Interpreter(model_path="foo.tflite")
```
This currently works to build on Linux machines including Raspberry Pi. In
the future, cross compilation to smaller SOCs like Raspberry Pi from
bigger host will be supported.
## Caveats
* You cannot use TensorFlow Select ops, only TensorFlow Lite builtins.
* Currently custom ops and delegates cannot be registered.
| {
"content_hash": "eb5f5311ebed0e9c31e0adfb6f15c5bf",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 91,
"avg_line_length": 30.818181818181817,
"alnum_prop": 0.7851524090462143,
"repo_name": "gunan/tensorflow",
"id": "dac8ce02ca10366a678e06cff9cf7c079d34d600",
"size": "2077",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/lite/tools/pip_package/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "5003"
},
{
"name": "Batchfile",
"bytes": "45924"
},
{
"name": "C",
"bytes": "774953"
},
{
"name": "C#",
"bytes": "8562"
},
{
"name": "C++",
"bytes": "77908225"
},
{
"name": "CMake",
"bytes": "6500"
},
{
"name": "Dockerfile",
"bytes": "104215"
},
{
"name": "Go",
"bytes": "1841471"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "962443"
},
{
"name": "Jupyter Notebook",
"bytes": "556650"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "1479029"
},
{
"name": "Makefile",
"bytes": "58603"
},
{
"name": "Objective-C",
"bytes": "104667"
},
{
"name": "Objective-C++",
"bytes": "297830"
},
{
"name": "PHP",
"bytes": "23994"
},
{
"name": "Pascal",
"bytes": "3739"
},
{
"name": "Pawn",
"bytes": "17039"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "39476740"
},
{
"name": "RobotFramework",
"bytes": "891"
},
{
"name": "Roff",
"bytes": "2472"
},
{
"name": "Ruby",
"bytes": "7459"
},
{
"name": "Shell",
"bytes": "650007"
},
{
"name": "Smarty",
"bytes": "34649"
},
{
"name": "Swift",
"bytes": "62814"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
package org.jboss.netty.handler.stream;
import static org.jboss.netty.buffer.ChannelBuffers.*;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* A {@link ChunkedInput} that fetches data from a {@link ReadableByteChannel}
* chunk by chunk. Please note that the {@link ReadableByteChannel} must
* operate in blocking mode. Non-blocking mode channels are not supported.
*
* @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
* @author Frederic Bregier
* @version $Rev$, $Date$
*/
public class ChunkedNioStream implements ChunkedInput {
private final ReadableByteChannel in;
private final int chunkSize;
private volatile long offset;
/**
* Associated ByteBuffer
*/
private final ByteBuffer byteBuffer;
/**
* Creates a new instance that fetches data from the specified channel.
*/
public ChunkedNioStream(ReadableByteChannel in) {
this(in, ChunkedStream.DEFAULT_CHUNK_SIZE);
}
/**
* Creates a new instance that fetches data from the specified channel.
*
* @param chunkSize the number of bytes to fetch on each
* {@link #nextChunk()} call
*/
public ChunkedNioStream(ReadableByteChannel in, int chunkSize) {
if (in == null) {
throw new NullPointerException("in");
}
if (chunkSize <= 0) {
throw new IllegalArgumentException("chunkSize: " + chunkSize +
" (expected: a positive integer)");
}
this.in = in;
offset = 0;
this.chunkSize = chunkSize;
byteBuffer = ByteBuffer.allocate(chunkSize);
}
/**
* Returns the number of transferred bytes.
*/
public long getTransferredBytes() {
return offset;
}
@Override
public boolean isEndOfInput() throws Exception {
if (byteBuffer.position() > 0) {
// A previous read was not over, so there is a next chunk in the buffer at least
return false;
}
if (in.isOpen()) {
// Try to read a new part, and keep this part (no rewind)
int b = in.read(byteBuffer);
if (b < 0) {
return true;
} else {
offset += b;
return false;
}
}
return true;
}
@Override
public void close() throws Exception {
in.close();
}
@Override
public Object nextChunk() throws Exception {
if (isEndOfInput()) {
return null;
}
// buffer cannot be not be empty from there
int readBytes = byteBuffer.position();
for (;;) {
int localReadBytes = in.read(byteBuffer);
if (localReadBytes < 0) {
break;
}
readBytes += localReadBytes;
offset += localReadBytes;
if (readBytes == chunkSize) {
break;
}
}
byteBuffer.flip();
// copy since buffer is keeped for next usage
ChannelBuffer buffer = copiedBuffer(byteBuffer);
byteBuffer.clear();
return buffer;
}
}
| {
"content_hash": "780e3a4215dfb183db8b398f29d3750c",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 92,
"avg_line_length": 28.43103448275862,
"alnum_prop": 0.5800485142510613,
"repo_name": "aperepel/netty",
"id": "c07a90cb4a4d8c99f89b9d9af62063557931e3b7",
"size": "3921",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/jboss/netty/handler/stream/ChunkedNioStream.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3693862"
}
],
"symlink_target": ""
} |
class Chef
class Resource
class File
class Verification
#
# Extends File verification to provide Json verification
#
# Example:
# file 'foo.json' do
# content '{"foo": "bar"}'
# verify :json
# end
#
#
class Json < Chef::Resource::File::Verification
provides :json
def verify(path, opts = {})
Chef::JSONCompat.parse(IO.read(path))
true
rescue Chef::Exceptions::JSON::ParseError => e
Chef::Log.error("Json syntax verify failed with : #{e.message}")
false
end
end
end
end
end
end
| {
"content_hash": "a5397f2cabd44e1e4a0285cf52e74185",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 76,
"avg_line_length": 21.65625,
"alnum_prop": 0.49783549783549785,
"repo_name": "MsysTechnologiesllc/chef",
"id": "cb814a68390334975f77b97a0c4af4731516cb67",
"size": "1399",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "lib/chef/resource/file/verification/json.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1453"
},
{
"name": "HTML",
"bytes": "74961"
},
{
"name": "Makefile",
"bytes": "2652"
},
{
"name": "PowerShell",
"bytes": "19271"
},
{
"name": "Python",
"bytes": "13362"
},
{
"name": "Raku",
"bytes": "128"
},
{
"name": "Ruby",
"bytes": "10932869"
},
{
"name": "Shell",
"bytes": "38211"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Medical mycology. Fungous diseases of men and other mammals 229 (1935)
#### Original name
Monilia pseudoalbicans Neveu-Lem.
### Remarks
null | {
"content_hash": "147fcc53a5482b57f87768d4212cece3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 70,
"avg_line_length": 15.692307692307692,
"alnum_prop": 0.7450980392156863,
"repo_name": "mdoering/backbone",
"id": "9a370e89b56ca3f772e65e195ee420daebe116ab",
"size": "276",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Mycoderma/Mycoderma pseudoalbicans/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import demistomock as demisto
from CommonServerPython import *
from copy import copy
from functools import lru_cache
from urllib.parse import urlencode
from urllib3 import disable_warnings
from requests.exceptions import HTTPError
from requests import Response
from typing import Callable, Iterable, Optional, List, Union, Iterator, Dict
STR_OR_STR_LIST = Union[str, List[str]]
MAX_PAGE_SIZE = 100
USER_CONTEXT_PATH = "Zendesk.User"
USERS_HEADERS = ['id', 'name', 'email', 'role', 'active', 'external_id', 'created_at', 'updated_at']
ORGANIZATIONS_HEADERS = ['id', 'name', 'domain_names', 'tags', 'external_id', 'created_at', 'updated_at']
TICKETS_HEADERS = ['id', 'subject', 'description', 'priority', 'status', 'assignee_id', 'created_at', 'updated_at', 'external_id']
COMMENTS_HEADERS = ['id', 'body', 'created_at', 'public', 'attachments']
ATTACHMENTS_HEADERS = ['id', 'file_name', 'content_url', 'size', 'content_type']
ARTICLES_HEADERS = ['body']
ROLES = ['end-user', 'admin', 'agent']
ROLE_TYPES = {
'custom_agent': 0,
'light_agent': 1,
'chat_agent': 2,
'chat_agent_contributor': 3,
'admin': 4,
'billing_admin': 5,
}
TICKET_FILTERS = ['assigned', 'requested', 'ccd', 'followed', 'recent']
CURSOR_SORTS = {
'id_asc': 'id',
'status_asc': 'status',
'updated_at_asc': 'updated_at',
'id_desc': '-id',
'status_desc': '-status',
'updated_at_desc': '-updated_at'
}
TICKET_TYPE = ['problem', 'incident', 'question', 'task']
TICKET_STATUS = ['open', 'pending', 'hold', 'solved', 'closed']
TICKET_PRIORITY = ['urgent', 'high', 'normal', 'low']
PRIORITY_MAP = {
'urgent': IncidentSeverity.CRITICAL,
'high': IncidentSeverity.HIGH,
'normal': IncidentSeverity.MEDIUM,
'low': IncidentSeverity.LOW
}
params = demisto.params() # pylint: disable=W9016
MIRROR_USER_AGENT = 'XSOAR mirror'
MIRROR_DIRECTION = {
'Incoming': 'In',
'Outgoing': 'Out',
'Incoming And Outgoing': 'Both'
}.get(params.get('mirror_direction'))
FIELDS_TO_REMOVE_FROM_MIROR_IN = ['url', 'id', 'created_at']
DEFAULT_UPLOAD_FILES_COMMENT = 'Uploaded from XSOAR.'
MIRROR_TAGS = params.get('mirror_tags') or []
CLOSE_INCIDENT = argToBoolean(params.get('close_incident', False))
INTEGRATION_INSTANCE = demisto.integrationInstance()
CACHE = None
class CacheManager:
def __init__(self, zendesk_client):
self._data = None
self._zendesk_client: ZendeskClient = zendesk_client
@staticmethod
def zendesk_clear_cache(**kwargs):
demisto.setIntegrationContext({})
return 'Cache clear done.'
def save(self):
if self._data:
demisto.setIntegrationContext(self._data)
def replace_ids_change(self, data: Dict, organization_fields: List[str] = [], user_fields: List[str] = []):
for fields, get_func in [(organization_fields, self.organization), (user_fields, self.user)]:
for field in fields:
obj_id = data.get(field)
if obj_id:
field = field.replace('_id', '')
if isinstance(obj_id, List):
data[field] = list(map(get_func, obj_id))
else:
data[field] = get_func(obj_id)
return data
@property
def data(self):
if self._data is None:
self._data = demisto.getIntegrationContext()
return self._data
@lru_cache
def user(self, user_id: int) -> str:
return self._generic_get_by_id('users', user_id, self._zendesk_client._get_user_by_id, 'email')
@lru_cache
def organization(self, organization_id: int) -> str:
return self._generic_get_by_id('organizations', organization_id, self._zendesk_client._get_organization_by_id, 'name')
@lru_cache
def organization_name(self, organization_name: str) -> Union[int, Dict]:
organizations = self._zendesk_client._get_organizations_by_name(organization_name)
ids = ','.join(map(lambda x: str(x['id']), organizations))
assert len(organizations) == 1, \
f"found {len(organizations)} organizations with name {organization_name} and ids {ids}"
return organizations[0]['id']
def _generic_get_by_id(self, data_type: str, obj_id: int, data_get: Callable, val_field: str):
self.data[data_type] = self.data.get(data_type, {})
try:
return self.data[data_type][obj_id]
except KeyError:
pass
try:
user_email = data_get(obj_id)[val_field] or obj_id
self.data[data_type][obj_id] = user_email
return user_email
except: # noqa # lgtm[py/]
return obj_id
def datetime_to_iso(date: datetime) -> str:
return date.strftime('%Y-%m-%dT%H:%M:%SZ')
def prepare_kwargs(kwargs: Dict[str, Any], ignore_args: STR_OR_STR_LIST = [],
str_args: STR_OR_STR_LIST = [],
list_args: STR_OR_STR_LIST = [],
bool_args: STR_OR_STR_LIST = [],
int_args: STR_OR_STR_LIST = [],
json_args: STR_OR_STR_LIST = []) -> Dict[str, Any]:
return_kwargs = dict()
for arg in ignore_args if isinstance(ignore_args, List) else [ignore_args]:
if arg in kwargs:
return_kwargs[arg] = kwargs[arg]
for arg in str_args if isinstance(str_args, List) else [str_args]:
if arg in kwargs:
return_kwargs[arg] = str(kwargs[arg])
for arg in list_args if isinstance(list_args, List) else [list_args]:
if arg in kwargs:
return_kwargs[arg] = argToList(kwargs[arg])
for arg in bool_args if isinstance(bool_args, List) else [bool_args]:
if arg in kwargs:
return_kwargs[arg] = argToBoolean(kwargs[arg])
for arg in int_args if isinstance(int_args, List) else [int_args]:
if arg in kwargs:
return_kwargs[arg] = int(kwargs[arg])
for arg in json_args if isinstance(json_args, List) else [json_args]:
if arg in kwargs:
return_kwargs[arg] = kwargs[arg] if isinstance(kwargs[arg], Dict) else json.loads(kwargs[arg])
return return_kwargs
def error_entry(error_msg: str) -> Dict[str, Any]:
return {
'Type': EntryType.ERROR,
'ContentsFormat': EntryFormat.TEXT,
'Contents': error_msg,
}
def close_entry(reason: str) -> Dict[str, Any]:
return {
'Type': EntryType.NOTE,
'Contents': {
'dbotIncidentClose': True,
'closeReason': reason
},
'ContentsFormat': EntryFormat.JSON
}
class Validators:
@staticmethod
def _validate(val: Any, arg_name: str, allowed: Iterable[Any]):
copy_value = argToList(val)
for value in copy_value:
assert value in allowed, f"'{val}' is not a valid {arg_name}.\nallowed {arg_name}s are '{','.join(allowed)}'"
@staticmethod
def validate_role(role: STR_OR_STR_LIST):
Validators._validate(role, 'role', ROLES)
@staticmethod
def validate_role_type(role_type: str):
Validators._validate(role_type, 'role type', ROLE_TYPES.keys())
@staticmethod
def validate_ticket_filter(ticket_filter: str):
Validators._validate(ticket_filter, 'filter', TICKET_FILTERS)
@staticmethod
def validate_ticket_sort(ticket_sort: str):
Validators._validate(ticket_sort, 'sort', CURSOR_SORTS.keys())
@staticmethod
def validate_ticket_type(ticket_type: str):
Validators._validate(ticket_type, 'type', TICKET_TYPE)
@staticmethod
def validate_ticket_status(ticket_status: str):
Validators._validate(ticket_status, 'status', TICKET_STATUS)
@staticmethod
def validate_ticket_priority(ticket_priority: str):
Validators._validate(ticket_priority, 'priority', TICKET_PRIORITY)
class TicketEvents:
def __init__(self, zendesk_client, after_cursor: str = None, tickets_list: List = []):
self._client = zendesk_client
self._demisto_params = demisto.params() # pylint: disable=W9016
self._tickets_list = tickets_list
self._after_cursor = after_cursor
self._last_fetch: Dict = {}
def _get_all(self, **kwargs):
return self._client._http_request('GET', url_suffix='incremental/tickets/cursor', params=kwargs)
def next_run(self):
next_run = {
'after_cursor': self._last_fetch.get('after_cursor', self._after_cursor),
}
if self._tickets_list:
next_run['tickets'] = self._tickets_list
return next_run
@abstractmethod
def query_params(self):
if after_cursor := self._last_fetch.get('after_cursor', self._after_cursor):
return {'cursor': after_cursor}
return {}
def tickets(self, limit: int = 1000, params: Optional[Dict] = {}):
yielded = 0
if self._tickets_list:
for _ in range(min(limit, len(self._tickets_list))):
yield self._tickets_list.pop(0)
yielded += 1
if yielded >= limit:
return
res = self._get_all(**(self.query_params() | params))
self._tickets_list = res.get('tickets', [])
while True:
self._after_cursor = res.get('after_cursor') or self._after_cursor
for _ in range(min(limit - yielded, len(self._tickets_list))):
yield self._tickets_list.pop(0)
yielded += 1
if res['end_of_stream']:
return
res = self._get_all(**(self.query_params() | params))
class UpdatedTickets(TicketEvents):
def __init__(self, zendesk_client, last_update: int, last_run_data: Dict = {}):
self._last_update = last_update
super(UpdatedTickets, self).__init__(zendesk_client, last_run_data.get('after_cursor'))
def query_params(self):
params = super(UpdatedTickets, self).query_params()
if not params:
params['start_time'] = self._last_update
return params
def tickets(self):
def filter_created_ticket(ticket: Dict):
return ticket['created_at'] != ticket['updated_at']
for ticket in filter(filter_created_ticket, super(UpdatedTickets, self).tickets()):
yield ticket
class CreatedTickets(TicketEvents):
def __init__(self, zendesk_client, last_run):
after_cursor = last_run.get('after_cursor')
self._latest_ticket_id = last_run.get('latest_ticket_id', 0)
self._highest_ticket_id_in_current_run = 0
super(CreatedTickets, self).__init__(zendesk_client, after_cursor, last_run.get('tickets', []))
def next_run(self):
next_run = super(CreatedTickets, self).next_run()
next_run['latest_ticket_id'] = max(self._latest_ticket_id, self._highest_ticket_id_in_current_run)
return next_run
def query_params(self):
params = super(CreatedTickets, self).query_params()
if not params:
params['start_time'] = int(dateparser.parse(
self._demisto_params.get('first_fetch', '3d')
).timestamp())
params['exclude_deleted'] = True
return params
def tickets(self):
limit = int(self._demisto_params.get('max_fetch', 50))
ticket_types = self._demisto_params.get('ticket_types', [])
ticket_types = None if 'all' in ticket_types else ticket_types
def filter_updated_ticket(ticket: Dict):
return ticket['id'] > self._latest_ticket_id and (not ticket_types or ticket.get('type') in ticket_types)
for ticket in filter(filter_updated_ticket, super(CreatedTickets, self).tickets(limit=limit)):
self._highest_ticket_id_in_current_run = max(ticket['id'], self._highest_ticket_id_in_current_run)
yield ticket
class ZendeskClient(BaseClient):
def __init__(self, base_url: str, username: Optional[str] = None, password: Optional[str] = None,
proxy: bool = False, verify: bool = True):
base_url = urljoin(base_url, '/api/v2/')
auth = headers = None
if username and password:
# auth = (f'{username}/token', password)
auth = (username, password)
elif password:
headers = {'Authorization': f'Bearer {password}'}
super(ZendeskClient, self).__init__(base_url, auth=auth, proxy=proxy, verify=verify, headers=headers)
@staticmethod
def error_handler(res: Response) -> None:
res.raise_for_status()
def _http_request(self, method: str, url_suffix: str = '', full_url: Optional[str] = None, # type: ignore[override]
json_data: Optional[Dict] = None, params: Dict = None, data: Dict = None, content: bytes = None,
resp_type: str = 'json', return_empty_response: bool = False, **kwargs):
if params:
final_params_list = []
for k, v in params.items():
if isinstance(v, List):
for singel_v in v:
final_params_list.append(f'{k}[]={singel_v}')
else:
final_params_list.append(f'{k}={v}')
params_str = f'?{"&".join(final_params_list)}'
if url_suffix:
url_suffix = f'{url_suffix}{params_str}'
if full_url:
full_url = f'{full_url}{params_str}'
return super(ZendeskClient, self)._http_request(method, url_suffix=url_suffix, full_url=full_url, json_data=json_data,
data=data or content, return_empty_response=return_empty_response,
resp_type=resp_type, error_handler=self.error_handler, **kwargs)
def __cursor_pagination(self, url_suffix: str, data_field_name: str, params: Optional[Dict] = None,
limit: int = 50) -> Iterator[Dict]:
# API docs here https://developer.zendesk.com/api-reference/ticketing/introduction/#using-cursor-pagination
page_size = min(limit, MAX_PAGE_SIZE)
next_link_section = 'next'
count_data = 1
paged_params = copy(params) if params is not None else {}
paged_params['page[size]'] = page_size
res = self._http_request('GET', url_suffix=url_suffix, params=paged_params)
while True:
for i in res[data_field_name]:
yield i
count_data += 1
if count_data > limit:
return
if not dict_safe_get(res, ['meta', 'has_more']):
break
res = self._http_request('GET', full_url=res['links'][next_link_section])
def __get_spesific_page(self, url_suffix: str, data_field_name: str, page_size: int,
page_number: int, params: Optional[Dict] = None) -> Iterator[Dict]:
# API docs here https://developer.zendesk.com/api-reference/ticketing/introduction/#using-offset-pagination
page_size = min(page_size, MAX_PAGE_SIZE)
paged_params = copy(params) if params is not None else {}
paged_params['per_page'] = page_size
paged_params['page'] = page_number
for res in self._http_request('GET', url_suffix=url_suffix, params=paged_params)[data_field_name]:
yield res
def _paged_request(self, url_suffix: str, data_field_name: str, params: Optional[Dict] = None,
limit: int = 50, page_size: Optional[int] = None, page_number: Optional[int] = None) -> Iterator[Dict]:
# validate parameters
if page_size is not None and page_number is not None:
return self.__get_spesific_page(url_suffix=url_suffix, data_field_name=data_field_name,
params=params, page_size=int(page_size), page_number=int(page_number))
elif page_size is not None or page_number is not None:
raise AssertionError("you need to specify both 'page_size' and 'page_number'.")
else:
return self.__cursor_pagination(url_suffix=url_suffix, data_field_name=data_field_name,
params=params, limit=int(limit))
# ---- user releated functions ---- #
@staticmethod
def __command_results_zendesk_users(users: List[Dict]):
role_types_reverse = {int_k: str_k for str_k, int_k in ROLE_TYPES.items()}
def _iter_context(user: Dict):
user = CACHE.replace_ids_change(user, ['organization_id']) # type: ignore
role_type = role_types_reverse.get(user.get('role_type')) # type: ignore
if role_type:
user['role_type'] = role_type
return user
raw_results = copy(users)
context = list(map(_iter_context, users))
readable_outputs = tableToMarkdown(name='Zendek users:', t=context, headers=USERS_HEADERS,
headerTransform=camelize_string)
return CommandResults(outputs_prefix=USER_CONTEXT_PATH, outputs=context,
readable_output=readable_outputs, raw_response=raw_results)
def _get_user_by_id(self, user_id: str):
return self._http_request('GET', f'users/{user_id}')['user']
def zendesk_user_list(self, user_id: Optional[STR_OR_STR_LIST] = None,
user_name: Optional[str] = None, role: Optional[Union[List[str], str]] = None,
**kwargs):
users_field_name = 'users'
results = []
error_msgs = []
if user_id is not None:
users_list = []
for single_user in argToList(user_id):
try:
users_list.append(self._get_user_by_id(single_user))
except Exception as e:
demisto.error(f'could not retrieve user: {single_user}\n{traceback.format_exc()}')
error_msgs.append(f'could not retrieve user: {single_user}\n{e}')
elif user_name is not None:
users_list = self._http_request('GET', 'users/autocomplete', params={'name': user_name})[users_field_name]
else:
params = prepare_kwargs(kwargs=kwargs, str_args='external_id')
if role:
role_list = argToList(role)
Validators.validate_role(role_list)
params['role'] = role_list[0] if len(role_list) == 1 else role_list
users_list = list(self._paged_request('users', 'users', params=params, **kwargs))
if users_list:
results.append(self.__command_results_zendesk_users(users_list))
if error_msgs:
results.append(error_entry('\n'.join(error_msgs)))
return results if results else 'No outputs.'
@staticmethod
def _handle_role_argument(role: Optional[str] = None, role_type: Optional[str] = None) -> Dict[str, Any]:
role_params: Dict[str, Union[str, int]] = {}
if role:
Validators.validate_role(role)
role_params['role'] = role
if role_type is not None:
assert role == 'agent', "You cannot use the 'role_type' argument if the selected role is not 'agent'"
Validators.validate_role_type(role_type)
role_params['role_type'] = ROLE_TYPES[role_type]
return role_params
def zendesk_user_create(self, name: str, email: str, role: Optional[str] = None, role_type: Optional[str] = None,
check_if_user_exists: bool = False, **kwargs):
url_suffix = 'users/create' if argToBoolean(check_if_user_exists) else 'users/create_or_update'
user_body = {
'name': name,
'email': email
}
if 'organization_name' in kwargs:
assert 'organization_id' not in kwargs, "you can specify 'organization_id' or 'organization_name' not both."
kwargs['organization_id'] = CACHE.organization_name(kwargs.pop('organization_name')) # type: ignore
user_body.update(prepare_kwargs(
kwargs=kwargs,
str_args=['phone', 'notes', 'details', 'external_id', 'locale', 'alias'],
list_args='tags',
int_args=['organization_id', 'default_group_id', 'custom_role_id'],
bool_args='verified',
json_args=['identities', 'user_fields']
))
user_body.update(self._handle_role_argument(role=role, role_type=role_type))
return self.__command_results_zendesk_users([
self._http_request('POST', url_suffix=url_suffix, json_data={'user': user_body})['user']
])
def zendesk_user_update(self, user_id: str, role: Optional[str] = None, role_type: Optional[str] = None, **kwargs):
if 'organization_name' in kwargs:
assert 'organization_id' not in kwargs, "you can specify 'organization_id' or 'organization_name' not both."
kwargs['organization_id'] = CACHE.organization_name(kwargs.pop('organization_name')) # type: ignore
user_body = prepare_kwargs(
kwargs=kwargs,
str_args=['name', 'email', 'phone', 'notes', 'details', 'external_id', 'locale', 'alias'],
list_args='tags',
int_args=['organization_id', 'default_group_id', 'custom_role_id'],
bool_args=['verified', 'suspended'],
json_args=['identities', 'user_fields']
)
user_body.update(self._handle_role_argument(role=role or 'agent', role_type=role_type))
return self.__command_results_zendesk_users([
self._http_request('PUT', url_suffix=f'users/{user_id}', json_data={'user': user_body})['user']
])
def zendesk_user_delete(self, user_id: str): # pragma: no cover
self._http_request('DELETE', url_suffix=f'users/{user_id}')
return f'User deleted. (id: {user_id})'
# ---- organization releated functions ---- #
@staticmethod
def __command_results_zendesk_organizations(organizations: List[Dict]): # pragma: no cover
readable_outputs = tableToMarkdown(name='Zendek organizations:', t=organizations, headers=ORGANIZATIONS_HEADERS,
headerTransform=camelize_string)
return CommandResults(outputs_prefix="Zendesk.Organization",
outputs=organizations, readable_output=readable_outputs)
def _get_organization_by_id(self, organization_id: str) -> Dict[str, Any]:
return self._http_request('GET', f'organizations/{organization_id}')['organization']
def _get_organizations_by_name(self, organization_name: str) -> List[Dict[str, Any]]:
return self._http_request('GET', 'organizations/autocomplete', params={'name': organization_name})['organizations']
def zendesk_organization_list(self, organization_id: Optional[str] = None, **kwargs):
if organization_id:
organizations = [self._get_organization_by_id(organization_id)]
else:
organizations = list(self._paged_request(url_suffix='organizations', data_field_name='organizations', **kwargs))
return self.__command_results_zendesk_organizations(organizations)
# ---- ticket releated functions ---- #
@staticmethod
def __ticket_context(ticket: Dict[str, Any]):
return CACHE.replace_ids_change(ticket, organization_fields=['organization_id'], # type: ignore
user_fields=['assignee_id', 'collaborator_ids',
'email_cc_ids', 'follower_ids', 'requester_id', 'submitter_id'])
@staticmethod
def __command_results_zendesk_tickets(tickets: List[Dict]):
raw = tickets
context = list(map(ZendeskClient.__ticket_context, tickets))
readable_outputs = tableToMarkdown(name='Zendek tickets:', t=context, headers=TICKETS_HEADERS,
headerTransform=camelize_string)
return CommandResults(outputs_prefix="Zendesk.Ticket",
outputs=tickets, readable_output=readable_outputs, raw_response=raw)
def _get_ticket_by_id(self, ticket_id: str, **kwargs):
return self._http_request('GET', f'tickets/{ticket_id}', **kwargs)['ticket']
@staticmethod
def __get_sort_params(sort: str, cursor_paging: bool = False):
Validators.validate_ticket_sort(sort)
if not cursor_paging:
# using the offest paged request
sort_list = sort.split('_')
sort, order = '_'.join(sort_list[:-1]), sort_list[-1]
return {
'sort_by': sort,
'sort_order': order
}
# using the cursor paged request
return {'sort': CURSOR_SORTS[sort]}
@staticmethod
def __get_tickets_url_suffix(filter: str, user_id: Optional[Union[str, int]] = None) -> str:
match filter:
case None:
return 'tickets'
case 'recent': # lgtm[py/unreachable-statement]
return 'tickets/recent'
case _: # lgtm[py/unreachable-statement]
assert user_id, f"user_id is required when using '{filter}' as filter."
Validators.validate_ticket_filter(filter)
return f'/users/{user_id}/tickets/{filter}'
def zendesk_ticket_list(self, ticket_id: Optional[STR_OR_STR_LIST] = None, query: Optional[str] = None,
user_id: Optional[str] = None, sort: Optional[str] = None,
page_number: Optional[int] = None, **kwargs):
filter_ = kwargs.pop('filter', None)
error_msgs = []
command_results = []
if query is not None:
assert ticket_id is None, "please provide either 'query' or 'ticket_id' not both."
ticket_filter = 'type:ticket'
query = query if query.startswith(ticket_filter) else f'{ticket_filter} {query}'
ticket_id = list(map(
lambda x: x['id'],
filter(
lambda x: x['result_type'] == 'ticket',
self.__zebdesk_search_results(query=query, page_number=page_number, **kwargs)
)
))
if ticket_id is not None:
tickets = []
for single_ticket in argToList(ticket_id):
try:
tickets.append(self._get_ticket_by_id(single_ticket))
except Exception as e:
demisto.error(f'could not retrieve ticket: {single_ticket}\n{traceback.format_exc()}')
error_msgs.append(f'could not retrieve ticket: {single_ticket}\n{e}')
else:
can_use_cursor_paging = page_number is None
sort_params = self.__get_sort_params(sort, can_use_cursor_paging) if sort else None
url_suffix = self.__get_tickets_url_suffix(filter_, user_id)
tickets = list(self._paged_request(url_suffix=url_suffix, data_field_name='tickets',
params=sort_params, page_number=page_number, **kwargs))
if tickets:
command_results.append(self.__command_results_zendesk_tickets(tickets))
if error_msgs:
command_results.append(error_entry('\n'.join(error_msgs)))
return command_results if command_results else 'No outputs.'
class Ticket:
def __init__(self, type: Optional[str] = None, collaborators: Optional[str] = None,
comment: Optional[str] = None, public: Optional[Union[str, bool]] = None,
email_ccs: Optional[str] = None, priority: Optional[str] = None,
followers: Optional[Union[List[str], str]] = None, status: Optional[str] = None,
**kwargs):
self._data: Dict[str, Any] = dict()
if type:
Validators.validate_ticket_type(type)
self._data['type'] = type
if type != 'incident':
assert 'problem_id' not in kwargs, "you can't use 'problem_id' if the ticket type is not 'incident'"
if priority:
Validators.validate_ticket_priority(priority)
self._data['priority'] = priority
if comment:
self._data['comment'] = {'body': comment}
if public:
self._data['comment']['public'] = argToBoolean(public)
if status:
Validators.validate_ticket_status(status)
self._data['status'] = status
if collaborators:
self._data['collaborators'] = list(map(self.try_int, argToList(collaborators)))
if followers:
self._data['followers'] = list(map(self.follower_and_email_cc_parse, argToList(followers)))
if email_ccs:
self._data['email_ccs'] = list(map(self.follower_and_email_cc_parse, argToList(followers)))
self._data.update(prepare_kwargs(
kwargs=kwargs,
str_args=['subject', 'requester', 'assignee_email',
'recipient', 'priority', 'external_id', 'due_at', 'comment'],
list_args='tags',
int_args=['forum_topic_id', 'group_id', 'organization_id', 'via_followup_source_id', 'brand_id', 'problem_id'],
json_args='custom_fields'
))
def __iter__(self):
for key, val in self._data.items():
yield key, val
@staticmethod
def try_int(value: str) -> Union[int, str]:
try:
return int(value)
except (ValueError, TypeError):
return value
@staticmethod
def follower_and_email_cc_parse(user_and_action: str):
follower_or_email_cc = {}
splited_user_and_action = user_and_action.split(':')
try:
follower_or_email_cc['user_id'] = str(int(splited_user_and_action[0]))
except ValueError:
follower_or_email_cc['user_email'] = splited_user_and_action[0]
if len(splited_user_and_action) == 2: # action included
follower_or_email_cc['action'] = splited_user_and_action[1]
return follower_or_email_cc
def zendesk_ticket_create(self, **kwargs): # pragma: no cover
for argument in ['subject', 'type', 'requester', 'description']:
assert argument in kwargs, f"'{argument}' is a required argument."
kwargs['comment'] = kwargs.pop('description')
return self.__command_results_zendesk_tickets([
self._http_request('POST', url_suffix='tickets', json_data={'ticket': dict(self.Ticket(**kwargs))})['ticket']
])
def zendesk_ticket_update(self, ticket_id: str, results: Optional[bool] = True, # pragma: no cover
is_mirror: bool = False, **kwargs):
headers = {'user-agent': MIRROR_USER_AGENT} if is_mirror else {}
res = self._http_request('PUT', url_suffix=f'tickets/{ticket_id}',
json_data={'ticket': dict(self.Ticket(**kwargs))}, headers=headers)
if results:
return self.__command_results_zendesk_tickets([
res['ticket']
])
def zendesk_ticket_delete(self, ticket_id: str): # pragma: no cover
self._http_request('DELETE', url_suffix=f'tickets/{ticket_id}', return_empty_response=True)
return f'ticket: {ticket_id} deleted.'
@staticmethod
def _map_comment_attachments(comment: Dict):
if not comment.get('attachments'):
return comment
copy_comment = copy(comment)
copy_comment['attachments'] = []
for attachment in comment['attachments']:
copy_comment['attachments'].append({
'file name': attachment['file_name'],
'content url': attachment['content_url'],
'id': attachment['id'],
})
return copy_comment
@staticmethod
def __command_results_zendesk_ticket_comments(comments: List[Dict]):
readable_pre_proces = list(map(ZendeskClient._map_comment_attachments, comments))
readable_outputs = tableToMarkdown(name='Zendek comments:', t=readable_pre_proces, headers=COMMENTS_HEADERS,
headerTransform=camelize_string, is_auto_json_transform=True)
return CommandResults(outputs_prefix="Zendesk.Ticket.Comment",
outputs=comments, readable_output=readable_outputs)
def _get_comments(self, ticket_id: str, **kwargs):
for comment in self._paged_request(url_suffix=f'tickets/{ticket_id}/comments', data_field_name='comments', **kwargs):
for attachment in comment.get('attachments', []):
attachment.pop('thumbnails', None)
yield CACHE.replace_ids_change(comment, user_fields=['author_id']) # type: ignore
def zendesk_ticket_comment_list(self, ticket_id: str, **kwargs):
return self.__command_results_zendesk_ticket_comments(list(self._get_comments(ticket_id, **kwargs)))
# ---- attachment releated functions ---- #
def zendesk_ticket_attachment_add(self, file_id: STR_OR_STR_LIST, ticket_id: int, comment: str,
file_name: Optional[STR_OR_STR_LIST] = None, is_mirror: bool = False):
headers = {'Content-Type': 'application/binary'}
if is_mirror:
headers['user-agent'] = MIRROR_USER_AGENT
file_id = argToList(file_id)
file_name_list = argToList(file_name) if file_name else [None] * len(file_id)
file_tokens = []
uploaded_files = []
for single_file_id, single_file_name in zip(file_id, file_name_list):
single_file = demisto.getFilePath(single_file_id)
display_name = single_file_name or single_file['name']
with open(single_file['path'], 'rb') as file_to_upload:
file_tokens.append(
self._http_request(
'POST', url_suffix='uploads',
params={'filename': display_name},
headers=headers,
content=file_to_upload.read(),
)['upload']['token'])
uploaded_files.append(display_name)
self._http_request('PUT', url_suffix=f'tickets/{ticket_id}',
json_data={'ticket': {'comment': {'uploads': file_tokens, 'body': comment}}})
return f'file: {", ".join(uploaded_files)} attached to ticket: {ticket_id}'
def zendesk_attachment_get(self, attachment_id: int):
attachments = [
self._http_request(
'GET',
url_suffix=f'attachments/{single_attachent_id}'
)['attachment'] for single_attachent_id in argToList(attachment_id)
]
def filter_thumbnails(attachment: Dict):
attachment.pop('thumbnails')
return attachment
attachments = list(map(filter_thumbnails, attachments))
readable_output = tableToMarkdown(name='Zendesk attachments', t=attachments,
headers=ATTACHMENTS_HEADERS, headerTransform=camelize_string)
results = [CommandResults(outputs_prefix='Zendesk.Attachment',
outputs=attachments, readable_output=readable_output)]
for attachment_link, attachment_name in map(lambda x: (x['content_url'], x['file_name']), attachments):
res = self._http_request('GET', full_url=attachment_link, resp_type='response')
res.raise_for_status()
results.append(fileResult(filename=attachment_name, data=res.content, file_type=EntryType.ENTRY_INFO_FILE))
return results
# ---- search releated functions ---- #
def __zebdesk_search_results(self, query: str, limit: int = 50, page_number: Optional[int] = None, page_size: int = 50):
params = {'query': urlencode({'A': query})[2:]}
results = []
if page_number:
results = list(self.__get_spesific_page(url_suffix='search.json', params=params,
data_field_name='results', page_number=int(page_number), page_size=int(page_size)))
else:
count = self._http_request('GET', url_suffix='search/count.json', params=params)['count']
limit = min(int(limit), count)
size = min(limit, MAX_PAGE_SIZE)
current_page = 1
while len(results) < limit:
results.extend(self.__get_spesific_page(url_suffix='search.json', params=params,
data_field_name='results', page_number=current_page, page_size=size))
current_page += 1
results = results[:limit]
return results
def zendesk_search(self, query: str, limit: int = 50, page_number: Optional[int] = None, page_size: int = 50):
return CommandResults(outputs_prefix="Zendesk.Search",
outputs=self.__zebdesk_search_results(
query=query, limit=limit, page_number=page_number, page_size=page_size
))
# ---- articles releated functions ---- #
def zendesk_article_list(self, locale: Optional[str] = '', article_id: Optional[int] = None, **kwargs):
if locale:
locale = f'{locale}/'
if article_id:
articles = [
self._http_request('GET', url_suffix=f'help_center/{locale}articles/{article_id}')['article']
]
else:
articles = list(self._paged_request(
url_suffix=f'help_center/{locale}articles', data_field_name='articles', **kwargs))
readable_output = ["</h1>Zendesk articles</h1>"]
for title, body in map(lambda x: (x['title'], x['body']), articles):
readable_output.append(f'<h1>{title}</h1>\n{body}')
return CommandResults(outputs_prefix='Zendesk.Article', outputs=articles,
readable_output='\n\n\n'.join(readable_output))
# ---- demisto releated functions ---- #
def test_module(self): # pragma: no cover
for data_type in ['tickets', 'users', 'organizations']:
self._paged_request(url_suffix=data_type, data_field_name=data_type, limit=1)
UpdatedTickets(self, 0).tickets().__next__()
return 'ok'
@staticmethod
def _ticket_to_incident(ticket: Dict):
ticket |= {
'severity': PRIORITY_MAP.get(ticket['priority']),
'mirror_instance': INTEGRATION_INSTANCE,
'mirror_id': str(ticket['id']),
'mirror_direction': MIRROR_DIRECTION,
'mirror_last_sync': datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'),
'mirror_tags': MIRROR_TAGS,
}
return {
'rawJSON': json.dumps(ticket),
'name': ticket['subject'],
'occurred': ticket['created_at'],
}
def fetch_incidents(self, lastRun: Optional[str] = None):
created_tickets = CreatedTickets(self, json.loads(lastRun or '{}') or demisto.getLastRun())
tickets = list(map(
self._ticket_to_incident,
map(
self.__ticket_context,
created_tickets.tickets()
)
))
demisto.incidents(tickets)
demisto.setLastRun(created_tickets.next_run())
def get_modified_remote_data(self, lastUpdate: Optional[str] = None):
try:
timestamp = int(dateparser.parse(lastUpdate).timestamp()) # type: ignore
except (TypeError, AttributeError):
timestamp = 0
last_run = get_last_mirror_run() or {}
updated_tickets = UpdatedTickets(self, timestamp, last_run)
tickets_ids = list(map(lambda x: str(x['id']), updated_tickets.tickets()))
if tickets_ids:
return_results(GetModifiedRemoteDataResponse(tickets_ids))
try:
set_last_mirror_run(updated_tickets.next_run())
except json.decoder.JSONDecodeError as e:
demisto.debug(f'{e}')
@staticmethod
def _create_entry_from_comment(comment: Dict):
comment_body = comment.get('body')
attachments = comment.get('attachments')
if attachments:
attachments_table = tableToMarkdown("attachments", attachments, [
"file_name", "id"], headerTransform=camelize_string)
comment_body = f'{comment_body}\n{attachments_table}'
return {
'Type': EntryType.NOTE,
'Contents': comment_body,
'ContentsFormat': EntryFormat.MARKDOWN,
'Note': True
}
def get_remote_data(self, **kwargs):
try:
parsed_args = GetRemoteDataArgs(kwargs)
last_update = datetime_to_iso(dateparser.parse(parsed_args.last_update, settings={'TIMEZONE': 'UTC'}))
try:
ticket_data = self._get_ticket_by_id(parsed_args.remote_incident_id)
except HTTPError as e:
if e.response.status_code == 404 and CLOSE_INCIDENT:
return GetRemoteDataResponse(
close_entry(f'ticket {parsed_args.remote_incident_id} deleted.'),
[close_entry(f'ticket {parsed_args.remote_incident_id} deleted.')]
)
raise e from None
context = self.__ticket_context(ticket_data)
context['severity'] = PRIORITY_MAP.get(ticket_data['priority'])
context['incomming_mirror_error'] = ''
for field_to_delete in FIELDS_TO_REMOVE_FROM_MIROR_IN:
if field_to_delete in context:
del context[field_to_delete]
def filter_comments(comment: Dict):
return comment['created_at'] > last_update \
and dict_safe_get(comment, ['metadata', 'system', 'client']) != MIRROR_USER_AGENT
ticket_entries = list(map(
self._create_entry_from_comment,
filter(filter_comments, self._get_comments(parsed_args.remote_incident_id, limit=200))
))
if ticket_data.get('status') == 'closed' and CLOSE_INCIDENT:
ticket_entries.append(close_entry(f'ticket {parsed_args.remote_incident_id} closed.'))
return GetRemoteDataResponse(context, ticket_entries)
except Exception as e:
return GetRemoteDataResponse({
'incomming_mirror_error': f'mirroring failed with error: {e}\n{traceback.format_exc()}'
}, [])
def update_remote_system(self, **kwargs):
# TODO: finish outgoing mapper
args = UpdateRemoteSystemArgs(kwargs)
files = []
args.delta = {key: val for key, val in args.delta.items() if val}
if 'severity' in args.delta:
severity = args.delta.pop('severity')
severity = IncidentSeverity.LOW if severity < IncidentSeverity.LOW else severity
for priority, severity_val in PRIORITY_MAP.items():
if severity == severity_val:
args.delta['priority'] = priority
break
if args.incident_changed and CLOSE_INCIDENT:
if args.inc_status == IncidentStatus.DONE or (args.data.get('state') == 'closed'):
args.delta['status'] = 'closed'
def upload_files_and_reset_files_list(files: List):
while files:
comment = files[0].get('contents', DEFAULT_UPLOAD_FILES_COMMENT)
files_to_upload = []
while files and files[0].get('contents', DEFAULT_UPLOAD_FILES_COMMENT) == comment:
files_to_upload.append(files.pop(0)['id'])
self.zendesk_ticket_attachment_add(
file_id=files_to_upload, ticket_id=args.remote_incident_id, comment=comment, is_mirror=True)
try:
for entry in args.entries or []:
# Mirroring files as entries
if entry['type'] in [EntryType.ENTRY_INFO_FILE, EntryType.FILE, EntryType.IMAGE]:
files.append(entry)
else:
upload_files_and_reset_files_list(files)
# Mirroring comment and work notes as entries
self.zendesk_ticket_update(ticket_id=args.remote_incident_id,
comment=entry['contents'], results=False, is_mirror=True)
upload_files_and_reset_files_list(files)
if args.delta:
self.zendesk_ticket_update(ticket_id=args.remote_incident_id, results=False, **args.delta)
except HTTPError as e:
if e.response.status_code != 404 and CLOSE_INCIDENT:
raise e from None
demisto.debug(f'ticket {args.remote_incident_id} deleted.')
return args.remote_incident_id
def get_mapping_fields(self, **kwargs): # pragma: no cover
zendesk_ticket_scheme = SchemeTypeMapping('Zendesk Ticket')
zendesk_ticket_scheme.add_field(
name='type', description='The type of this ticket. Allowed values are "problem", "incident", "question", or "task".')
zendesk_ticket_scheme.add_field(name='subject', description='The value of the subject field for this ticket.')
zendesk_ticket_scheme.add_field(name='description', description='The ticket description.')
zendesk_ticket_scheme.add_field(
name='priority',
description='The urgency with which the ticket should be addressed. '
'Allowed values are "urgent", "high", "normal", or "low".'
)
zendesk_ticket_scheme.add_field(
name='status',
description='The state of the ticket. Allowed values are "new", "open", "pending", "hold", "solved", or "closed".'
)
zendesk_ticket_scheme.add_field(name='recipient', description='The original recipient e-mail address of the ticket.')
zendesk_ticket_scheme.add_field(name='requester', description='The user who requested this ticket.')
zendesk_ticket_scheme.add_field(name='assigne', description='The agent currently assigned to the ticket.')
zendesk_ticket_scheme.add_field(name='organization', description='The organization of the requester.')
zendesk_ticket_scheme.add_field(name='collaborators', description="The users currently CC'ed on the ticket.")
zendesk_ticket_scheme.add_field(name='followers', description='The agents currently following the ticket.')
zendesk_ticket_scheme.add_field(
name='email_ccs', description="The agents or end users currently CC'ed on the ticket.")
zendesk_ticket_scheme.add_field(name='tags', description='The array of tags applied to this ticket.')
zendesk_ticket_scheme.add_field(
name='custom_fields', description='Custom fields for the ticket (this is a json formatted argument see: https://developer.zendesk.com/documentation/ticketing/managing-tickets/creating-and-updating-tickets#setting-custom-field-values).') # noqa: E501
return GetMappingFieldsResponse([zendesk_ticket_scheme])
def main(): # pragma: no cover
params = demisto.params()
verify = not params.get('insecure', False)
if not verify:
disable_warnings()
client = ZendeskClient(
base_url=params['base_url'],
username=params['credentials'].get('identifier'),
password=params['credentials']['password'],
proxy=params.get('proxy', False),
verify=verify
)
global CACHE
CACHE = CacheManager(client)
try:
command = demisto.command()
args = demisto.args()
commands: Dict[str, Callable] = {
# demisto commands
'test-module': client.test_module,
'fetch-incidents': client.fetch_incidents,
'get-modified-remote-data': client.get_modified_remote_data,
'get-remote-data': client.get_remote_data,
'update-remote-system': client.update_remote_system,
'get-mapping-fields': client.get_mapping_fields,
'zendesk-clear-cache': CacheManager.zendesk_clear_cache,
# user commands
'zendesk-user-list': client.zendesk_user_list,
'zendesk-user-create': client.zendesk_user_create,
'zendesk-user-update': client.zendesk_user_update,
'zendesk-user-delete': client.zendesk_user_delete,
# organization commands
'zendesk-organization-list': client.zendesk_organization_list,
# ticket commands
'zendesk-ticket-list': client.zendesk_ticket_list,
'zendesk-ticket-create': client.zendesk_ticket_create,
'zendesk-ticket-update': client.zendesk_ticket_update,
'zendesk-ticket-delete': client.zendesk_ticket_delete,
'zendesk-ticket-comment-list': client.zendesk_ticket_comment_list,
# attachment commands
'zendesk-ticket-attachment-add': client.zendesk_ticket_attachment_add,
'zendesk-attachment-get': client.zendesk_attachment_get,
# search command
'zendesk-search': client.zendesk_search,
# articles command
'zendesk-article-list': client.zendesk_article_list,
}
demisto.debug(f'command {command} called')
if command in commands:
if command_res := commands[command](**args):
return_results(command_res)
else:
raise NotImplementedError(command)
except Exception as e:
return_error(f'An error occurred: {e}', error=e)
finally:
CACHE.save()
if __name__ in ("__main__", "__builtin__", "builtins"): # pragma: no cover
main()
| {
"content_hash": "774920f01ff64e2f1d36f17f09b43be5",
"timestamp": "",
"source": "github",
"line_count": 1110,
"max_line_length": 262,
"avg_line_length": 45.074774774774774,
"alnum_prop": 0.5867527431894949,
"repo_name": "VirusTotal/content",
"id": "6d64e38dab908c95dfb552a1df9ba6c19f9bc33e",
"size": "50033",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Packs/Zendesk/Integrations/Zendeskv2/Zendeskv2.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "2146"
},
{
"name": "HTML",
"bytes": "205901"
},
{
"name": "JavaScript",
"bytes": "1584075"
},
{
"name": "PowerShell",
"bytes": "442288"
},
{
"name": "Python",
"bytes": "47594464"
},
{
"name": "Rich Text Format",
"bytes": "480911"
},
{
"name": "Shell",
"bytes": "108066"
},
{
"name": "YARA",
"bytes": "1185"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "45d7bbf49b14fa37706b1f578fe6bee0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "1bdf4c0fff2418381989db41c5d4014aeb4a9b20",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Aizoaceae/Mentocalyx/Mentocalyx velutina/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from setuptools import setup, find_packages
setup(
name='fast_mc',
description='A collection of Monte Carlo Samplers',
author='Sreekumar Thaithara Balan',
author_email='tbs1980@gmail.com',
version='0.0.1',
packages=find_packages(exclude=['doc', 'tests*']),
install_requires=[
'numpy'
],
tests_require=[
'pytest'
]
)
| {
"content_hash": "57e32da3f11565eb7d884eefe102eae7",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 55,
"avg_line_length": 23.3125,
"alnum_prop": 0.6219839142091153,
"repo_name": "tbs1980/fast-mc",
"id": "90212e3828b6606c3c5626eb4c7b126579bda91e",
"size": "373",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "setup.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "19950"
}
],
"symlink_target": ""
} |
package pl.jakubchmura.snmp.mib.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static pl.jakubchmura.snmp.mib.psi.SmiTypes.*;
import pl.jakubchmura.snmp.mib.psi.*;
public class SmiSnmpObjectTypeMacroTypeImpl extends SmiDefinedMacroTypeImpl implements SmiSnmpObjectTypeMacroType {
public SmiSnmpObjectTypeMacroTypeImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull SmiVisitor visitor) {
visitor.visitSnmpObjectTypeMacroType(this);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof SmiVisitor) accept((SmiVisitor)visitor);
else super.accept(visitor);
}
@Override
@Nullable
public SmiSnmpDefValPart getSnmpDefValPart() {
return PsiTreeUtil.getChildOfType(this, SmiSnmpDefValPart.class);
}
@Override
@Nullable
public SmiSnmpDescrPart getSnmpDescrPart() {
return PsiTreeUtil.getChildOfType(this, SmiSnmpDescrPart.class);
}
@Override
@Nullable
public SmiSnmpIndexPart getSnmpIndexPart() {
return PsiTreeUtil.getChildOfType(this, SmiSnmpIndexPart.class);
}
@Override
@NotNull
public SmiSnmpSyntaxPart getSnmpSyntaxPart() {
return notNullChild(PsiTreeUtil.getChildOfType(this, SmiSnmpSyntaxPart.class));
}
}
| {
"content_hash": "271d86053f36b3188bac520d09e60941",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 115,
"avg_line_length": 27.745098039215687,
"alnum_prop": 0.7795053003533569,
"repo_name": "jchmura/MibPlugin",
"id": "0b772d1845c4db5886435e713f71253e596c3d46",
"size": "1477",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gen/pl/jakubchmura/snmp/mib/psi/impl/SmiSnmpObjectTypeMacroTypeImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "140234"
},
{
"name": "Lex",
"bytes": "6335"
}
],
"symlink_target": ""
} |
using namespace arangodb;
using namespace arangodb::replication2;
using namespace arangodb::replication2::agency;
using namespace arangodb::replication2::replicated_log;
using namespace arangodb::basics;
using namespace arangodb::tests;
TEST(LogCommonTest, log_id) {
auto id = LogId{42};
VPackBuilder builder;
serialize(builder, id);
auto fromVPack = deserialize<LogId>(builder.slice());
EXPECT_EQ(id, fromVPack);
}
TEST(LogCommonTest, log_index) {
auto index = LogIndex{1};
VPackBuilder builder;
serialize(builder, index);
auto fromVPack = deserialize<LogIndex>(builder.slice());
EXPECT_EQ(index, fromVPack);
}
TEST(LogCommonTest, term_index_pair) {
auto spearHead = TermIndexPair{LogTerm{2}, LogIndex{1}};
VPackBuilder builder;
spearHead.toVelocyPack(builder);
auto slice = builder.slice();
auto fromVPack = TermIndexPair::fromVelocyPack(slice);
EXPECT_EQ(spearHead, fromVPack);
auto jsonBuffer = R"({
"term": 2,
"index": 1
})"_vpack;
auto jsonSlice = velocypack::Slice(jsonBuffer->data());
EXPECT_TRUE(VelocyPackHelper::equal(jsonSlice, slice, true))
<< "expected " << jsonSlice.toJson() << " found " << slice.toJson();
}
TEST(LogCommonTest, commit_fail_reason) {
VPackBuilder builder;
auto reason = CommitFailReason::withNothingToCommit();
reason.toVelocyPack(builder);
auto slice = builder.slice();
auto fromVPack = CommitFailReason::fromVelocyPack(slice);
EXPECT_EQ(reason, fromVPack);
auto jsonBuffer = R"({
"reason": "NothingToCommit"
})"_vpack;
auto jsonSlice = velocypack::Slice(jsonBuffer->data());
EXPECT_TRUE(VelocyPackHelper::equal(jsonSlice, slice, true))
<< "expected " << jsonSlice.toJson() << " found " << slice.toJson();
builder.clear();
reason = CommitFailReason::withQuorumSizeNotReached(
{{"PRMR-1234",
{.isFailed = false,
.isAllowedInQuorum = false,
.lastAcknowledged = TermIndexPair(LogTerm(1), LogIndex(2))}}},
TermIndexPair(LogTerm(3), LogIndex(4)));
reason.toVelocyPack(builder);
slice = builder.slice();
fromVPack = CommitFailReason::fromVelocyPack(slice);
EXPECT_EQ(reason, fromVPack)
<< "original: " << to_string(reason) << "\n"
<< "intermediate velocypack: " << slice.toJson() << "\n"
<< "result: " << to_string(fromVPack);
builder.clear();
reason = CommitFailReason::withForcedParticipantNotInQuorum("PRMR-1234");
reason.toVelocyPack(builder);
slice = builder.slice();
fromVPack = CommitFailReason::fromVelocyPack(slice);
EXPECT_EQ(reason, fromVPack);
jsonBuffer = R"({"xyz": "NothingToCommit", "reason": "xyz"})"_vpack;
jsonSlice = velocypack::Slice(jsonBuffer->data());
EXPECT_ANY_THROW({ CommitFailReason::fromVelocyPack(jsonSlice); });
}
TEST(LogCommonTest, participant_flags) {
{
auto participantFlags = ParticipantFlags{
.forced = true, .allowedInQuorum = false, .allowedAsLeader = true};
VPackBuilder builder;
participantFlags.toVelocyPack(builder);
auto slice = builder.slice();
auto fromVPack = ParticipantFlags::fromVelocyPack(slice);
EXPECT_EQ(participantFlags, fromVPack);
}
{
auto participantFlags = ParticipantFlags{
.forced = true, .allowedInQuorum = false, .allowedAsLeader = true};
VPackBuilder builder;
serialize(builder, participantFlags);
auto slice = builder.slice();
auto fromVPack = deserialize<ParticipantFlags>(slice);
EXPECT_EQ(participantFlags, fromVPack);
auto jsonBuffer = R"({
"allowedInQuorum": false,
"forced": true,
"allowedAsLeader": true
})"_vpack;
auto jsonSlice = velocypack::Slice(jsonBuffer->data());
EXPECT_TRUE(VelocyPackHelper::equal(jsonSlice, slice, true))
<< "expected " << jsonSlice.toJson() << " found " << slice.toJson();
}
{
auto const expectedFlags = ParticipantFlags{
.forced = true, .allowedInQuorum = true, .allowedAsLeader = true};
// if allowedInQuorum or allowedAsLeader are not given,
// then they are as a default set to true
auto jsonBuffer = R"({
"forced": true
})"_vpack;
auto jsonSlice = velocypack::Slice(jsonBuffer->data());
auto flags = deserialize<ParticipantFlags>(jsonSlice);
EXPECT_EQ(expectedFlags, flags);
}
}
TEST(LogCommonTest, participants_config) {
auto participantsConfig = ParticipantsConfig{
.generation = 15, .participants = {{"A", ParticipantFlags{}}}};
VPackBuilder builder;
velocypack::serialize(builder, participantsConfig);
auto slice = builder.slice();
auto fromVPack = velocypack::deserialize<ParticipantsConfig>(slice);
EXPECT_EQ(participantsConfig, fromVPack);
}
TEST(LogCommonTest, participants_config_inspector) {
auto participantsConfig = ParticipantsConfig{
.generation = 15, .participants = {{"A", ParticipantFlags{}}}};
VPackBuilder builder;
serialize(builder, participantsConfig);
auto slice = builder.slice();
auto fromVPack = deserialize<ParticipantsConfig>(slice);
EXPECT_EQ(participantsConfig, fromVPack);
auto jsonBuffer = R"({
"generation": 15,
"config": {
"effectiveWriteConcern":1,
"waitForSync":false
},
"participants": {
"A": {
"forced": false,
"allowedInQuorum": true,
"allowedAsLeader": true
}
}
})"_vpack;
auto jsonSlice = velocypack::Slice(jsonBuffer->data());
EXPECT_TRUE(VelocyPackHelper::equal(jsonSlice, slice, true))
<< "expected " << jsonSlice.toJson() << " found " << slice.toJson();
}
| {
"content_hash": "94e043a3495d7a137d8be20b95046e8f",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 76,
"avg_line_length": 31.151685393258425,
"alnum_prop": 0.6804328223624887,
"repo_name": "wiltonlazary/arangodb",
"id": "6e656ccbeb30308b2f7df33d7867b59036c2104b",
"size": "6723",
"binary": false,
"copies": "2",
"ref": "refs/heads/devel",
"path": "tests/Replication2/Serialization/LogCommonTest.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "61827"
},
{
"name": "C",
"bytes": "309788"
},
{
"name": "C++",
"bytes": "34723629"
},
{
"name": "CMake",
"bytes": "383904"
},
{
"name": "CSS",
"bytes": "210549"
},
{
"name": "EJS",
"bytes": "231166"
},
{
"name": "HTML",
"bytes": "23114"
},
{
"name": "JavaScript",
"bytes": "33741286"
},
{
"name": "LLVM",
"bytes": "14975"
},
{
"name": "NASL",
"bytes": "269512"
},
{
"name": "NSIS",
"bytes": "47138"
},
{
"name": "Pascal",
"bytes": "75391"
},
{
"name": "Perl",
"bytes": "9811"
},
{
"name": "PowerShell",
"bytes": "7869"
},
{
"name": "Python",
"bytes": "184352"
},
{
"name": "SCSS",
"bytes": "255542"
},
{
"name": "Shell",
"bytes": "134504"
},
{
"name": "TypeScript",
"bytes": "179074"
},
{
"name": "Yacc",
"bytes": "79620"
}
],
"symlink_target": ""
} |
namespace soothsayer.Scripts
{
public static class ScriptFolders
{
public static readonly string Init = "init";
public static readonly string Up = "up";
public static readonly string Down = "down";
public static readonly string Term = "term";
}
}
| {
"content_hash": "d26f30df4a65a6b613ca4e881f80eef7",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 52,
"avg_line_length": 29.2,
"alnum_prop": 0.6438356164383562,
"repo_name": "paybyphone/soothsayer",
"id": "1f424a6ae209a7892ecf307eb0f2bdc07fb84c18",
"size": "294",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "soothsayer/Scripts/ScriptFolders.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "335530"
}
],
"symlink_target": ""
} |
<?php
namespace Icecave\Exie\Input;
use Icecave\Isolator\IsolatorTrait;
class StreamInput implements InputInterface
{
use IsolatorTrait;
/**
* @param stream $stream
* @param integer $readSize
*/
public function __construct($stream, $readSize = 8192)
{
$this->stream = $stream;
$this->readSize = $readSize;
}
/**
* @return string
*/
public function read()
{
return $this->isolator()->fread($this->stream, $this->readSize);
}
/**
* @return boolean
*/
public function exhausted()
{
return $this->isolator()->feof($this->stream);
}
private $stream;
private $readSize;
}
| {
"content_hash": "f906d646fc3b7f8acb192020b1dd8436",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 72,
"avg_line_length": 18.42105263157895,
"alnum_prop": 0.5714285714285714,
"repo_name": "IcecaveStudios/exie",
"id": "4580798cba8f0dc18ecacadfb940181bd28352c6",
"size": "700",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/Input/StreamInput.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "45052"
},
{
"name": "Shell",
"bytes": "452"
}
],
"symlink_target": ""
} |
#include <linux/pm.h>
#include <linux/suspend.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/spinlock.h>
#include <asm/cacheflush.h>
#include <asm/delay.h>
#include <asm/io.h>
#include <mach/common.h>
#include <mach/da8xx.h>
#include <mach/sram.h>
#include <mach/pm.h>
#include "clock.h"
#define DEEPSLEEP_SLEEPCOUNT_MASK 0xFFFF
static void (*davinci_sram_suspend) (struct davinci_pm_config *);
static struct davinci_pm_config *pdata;
static void davinci_sram_push(void *dest, void *src, unsigned int size)
{
memcpy(dest, src, size);
flush_icache_range((unsigned long)dest, (unsigned long)(dest + size));
}
static void davinci_pm_suspend(void)
{
unsigned val;
if (pdata->cpupll_reg_base != pdata->ddrpll_reg_base) {
/* Switch CPU PLL to bypass mode */
val = __raw_readl(pdata->cpupll_reg_base + PLLCTL);
val &= ~(PLLCTL_PLLENSRC | PLLCTL_PLLEN);
__raw_writel(val, pdata->cpupll_reg_base + PLLCTL);
udelay(PLL_BYPASS_TIME);
/* Powerdown CPU PLL */
val = __raw_readl(pdata->cpupll_reg_base + PLLCTL);
val |= PLLCTL_PLLPWRDN;
__raw_writel(val, pdata->cpupll_reg_base + PLLCTL);
}
/* Configure sleep count in deep sleep register */
val = __raw_readl(pdata->deepsleep_reg);
val &= ~DEEPSLEEP_SLEEPCOUNT_MASK,
val |= pdata->sleepcount;
__raw_writel(val, pdata->deepsleep_reg);
/* System goes to sleep in this call */
davinci_sram_suspend(pdata);
if (pdata->cpupll_reg_base != pdata->ddrpll_reg_base) {
/* put CPU PLL in reset */
val = __raw_readl(pdata->cpupll_reg_base + PLLCTL);
val &= ~PLLCTL_PLLRST;
__raw_writel(val, pdata->cpupll_reg_base + PLLCTL);
/* put CPU PLL in power down */
val = __raw_readl(pdata->cpupll_reg_base + PLLCTL);
val &= ~PLLCTL_PLLPWRDN;
__raw_writel(val, pdata->cpupll_reg_base + PLLCTL);
/* wait for CPU PLL reset */
udelay(PLL_RESET_TIME);
/* bring CPU PLL out of reset */
val = __raw_readl(pdata->cpupll_reg_base + PLLCTL);
val |= PLLCTL_PLLRST;
__raw_writel(val, pdata->cpupll_reg_base + PLLCTL);
/* Wait for CPU PLL to lock */
udelay(PLL_LOCK_TIME);
/* Remove CPU PLL from bypass mode */
val = __raw_readl(pdata->cpupll_reg_base + PLLCTL);
val &= ~PLLCTL_PLLENSRC;
val |= PLLCTL_PLLEN;
__raw_writel(val, pdata->cpupll_reg_base + PLLCTL);
}
}
static int davinci_pm_enter(suspend_state_t state)
{
int ret = 0;
switch (state) {
case PM_SUSPEND_STANDBY:
case PM_SUSPEND_MEM:
davinci_pm_suspend();
break;
default:
ret = -EINVAL;
}
return ret;
}
static const struct platform_suspend_ops davinci_pm_ops = {
.enter = davinci_pm_enter,
.valid = suspend_valid_only_mem,
};
static int __init davinci_pm_probe(struct platform_device *pdev)
{
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_err(&pdev->dev, "cannot get platform data\n");
return -ENOENT;
}
davinci_sram_suspend = sram_alloc(davinci_cpu_suspend_sz, NULL);
if (!davinci_sram_suspend) {
dev_err(&pdev->dev, "cannot allocate SRAM memory\n");
return -ENOMEM;
}
davinci_sram_push(davinci_sram_suspend, davinci_cpu_suspend,
davinci_cpu_suspend_sz);
suspend_set_ops(&davinci_pm_ops);
return 0;
}
static int __exit davinci_pm_remove(struct platform_device *pdev)
{
sram_free(davinci_sram_suspend, davinci_cpu_suspend_sz);
return 0;
}
static struct platform_driver davinci_pm_driver = {
.driver = {
.name = "pm-davinci",
},
.remove = __exit_p(davinci_pm_remove),
};
int __init davinci_pm_init(void)
{
return platform_driver_probe(&davinci_pm_driver, davinci_pm_probe);
}
| {
"content_hash": "8f9d8ec3041813d586e2920442718305",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 71,
"avg_line_length": 23.713333333333335,
"alnum_prop": 0.6755692999718864,
"repo_name": "publicloudapp/csrutil",
"id": "07e23ba61f3ac3df52782455e850068128267bec",
"size": "3858",
"binary": false,
"copies": "976",
"ref": "refs/heads/master",
"path": "linux-4.3/arch/arm/mach-davinci/pm.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3984"
},
{
"name": "Awk",
"bytes": "29136"
},
{
"name": "C",
"bytes": "532969471"
},
{
"name": "C++",
"bytes": "3352303"
},
{
"name": "Clojure",
"bytes": "1489"
},
{
"name": "Cucumber",
"bytes": "4701"
},
{
"name": "Groff",
"bytes": "46775"
},
{
"name": "Lex",
"bytes": "55199"
},
{
"name": "Makefile",
"bytes": "1576284"
},
{
"name": "Objective-C",
"bytes": "521540"
},
{
"name": "Perl",
"bytes": "715196"
},
{
"name": "Perl6",
"bytes": "3783"
},
{
"name": "Python",
"bytes": "273092"
},
{
"name": "Shell",
"bytes": "343618"
},
{
"name": "SourcePawn",
"bytes": "4687"
},
{
"name": "UnrealScript",
"bytes": "12797"
},
{
"name": "XS",
"bytes": "1239"
},
{
"name": "Yacc",
"bytes": "114559"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\CatalogInventory\Model\ResourceModel\Stock;
use Magento\Framework\Data\AbstractCriteria;
/**
* Class StockCriteria
*/
class StockCriteria extends AbstractCriteria implements \Magento\CatalogInventory\Api\StockCriteriaInterface
{
/**
* @param string $mapper
*/
public function __construct($mapper = '')
{
$this->mapperInterfaceName =
$mapper ?: 'Magento\CatalogInventory\Model\ResourceModel\Stock\StockCriteriaMapper';
$this->data['initial_condition'] = true;
}
/**
* @inheritdoc
*/
public function setScopeFilter($scope)
{
$this->data['website_filter'] = $scope;
return true;
}
/**
* Add Criteria object
*
* @param \Magento\CatalogInventory\Api\StockCriteriaInterface $criteria
* @return bool
*/
public function addCriteria(\Magento\CatalogInventory\Api\StockCriteriaInterface $criteria)
{
$this->data[self::PART_CRITERIA_LIST]['list'][] = $criteria;
return true;
}
}
| {
"content_hash": "d2fe4e5c60908e44b95efaf3d088d55c",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 108,
"avg_line_length": 25.047619047619047,
"alnum_prop": 0.6463878326996197,
"repo_name": "j-froehlich/magento2_wk",
"id": "3630fb592ceb4b4fb2a9a1a600ad63e002a32068",
"size": "1160",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/magento/module-catalog-inventory/Model/ResourceModel/Stock/StockCriteria.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "13636"
},
{
"name": "CSS",
"bytes": "2076720"
},
{
"name": "HTML",
"bytes": "6151072"
},
{
"name": "JavaScript",
"bytes": "2488727"
},
{
"name": "PHP",
"bytes": "12466046"
},
{
"name": "Shell",
"bytes": "6088"
},
{
"name": "XSLT",
"bytes": "19979"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "07b57b40e49287f2037292c279cd2f27",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "066a1ec6a938553078cb7cc2a72d42192b36133e",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Anoda/Anoda urophylla/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"""
Created on 20 May, 2011
This module shows how you can use vensim models directly
instead of coding the model in Python. The underlying case
is the same as used in fluExample
.. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
epruyt <e.pruyt (at) tudelft (dot) nl>
"""
import numpy as np
from ema_workbench import (
TimeSeriesOutcome,
ScalarOutcome,
ema_logging,
Policy,
MultiprocessingEvaluator,
save_results,
)
from ema_workbench.connectors.vensim import VensimModel
from ema_workbench.em_framework.parameters import parameters_from_csv
def time_of_max(infected_fraction, time):
index = np.where(infected_fraction == np.max(infected_fraction))
timing = time[index][0]
return timing
if __name__ == "__main__":
ema_logging.log_to_stderr(ema_logging.INFO)
model = VensimModel("fluCase", wd="./models/flu", model_file="FLUvensimV1basecase.vpm")
# outcomes
model.outcomes = [
TimeSeriesOutcome("deceased population region 1"),
TimeSeriesOutcome("infected fraction R1"),
ScalarOutcome(
"max infection fraction", variable_name="infected fraction R1", function=np.max
),
ScalarOutcome(
"time of max", variable_name=["infected fraction R1", "TIME"], function=time_of_max
),
]
# create uncertainties based on csv
model.uncertainties = parameters_from_csv("./models/flu/flu_uncertainties.csv")
# add policies
policies = [
Policy("no policy", model_file="FLUvensimV1basecase.vpm"),
Policy("static policy", model_file="FLUvensimV1static.vpm"),
Policy("adaptive policy", model_file="FLUvensimV1dynamic.vpm"),
]
with MultiprocessingEvaluator(model, n_processes=4) as evaluator:
results = evaluator.perform_experiments(1000, policies=policies)
save_results(results, "./data/1000 flu cases with policies.tar.gz")
| {
"content_hash": "8b822d1dccffcb1a6b577ed76a88873c",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 95,
"avg_line_length": 31.62295081967213,
"alnum_prop": 0.6811819595645412,
"repo_name": "quaquel/EMAworkbench",
"id": "735d818927b0196cf82799ce5653252bc7795a8e",
"size": "1929",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ema_workbench/examples/flu_vensim_example_advanced.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "12462"
},
{
"name": "Jupyter Notebook",
"bytes": "2113522"
},
{
"name": "NetLogo",
"bytes": "46834"
},
{
"name": "Python",
"bytes": "844796"
}
],
"symlink_target": ""
} |
require 'chef/recipe'
require 'chef/resource'
require 'chef/provider'
class Chef
module Consul
require_relative 'consul/node'
require_relative 'consul/version'
end
end
| {
"content_hash": "be606e13d4b04e42f1e1e43881e77162",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 37,
"avg_line_length": 18.1,
"alnum_prop": 0.7458563535911602,
"repo_name": "samdunne/chef-consul",
"id": "db57eca3fdc7c90bc668490713571280b7a35959",
"size": "780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/chef/consul.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "5552"
}
],
"symlink_target": ""
} |
//THis module is the entry point of our application and below code helps
//helps bootstrap the Angular application
/*require("core-js/shim"); // polyfills the browser with any missing modern features
import 'zone.js/dist/zone'; // required by angular
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {AppModule} from "./app/view_system/index";
platformBrowserDynamic().bootstrapModule(AppModule);*/
console.log("Yay!!!"); | {
"content_hash": "6c4e0e745eac07ce0b31f82053a3ca64",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 84,
"avg_line_length": 35.38461538461539,
"alnum_prop": 0.7630434782608696,
"repo_name": "coolchem/myTodoAngularApp1",
"id": "54f73623ef5122f0d3c1a8c2e94aa086434dcb94",
"size": "460",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/client/main.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "66"
},
{
"name": "HTML",
"bytes": "789"
},
{
"name": "JavaScript",
"bytes": "21948"
},
{
"name": "TypeScript",
"bytes": "40029"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a09a1e31e18251f547c043e961669e23",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e6844baf2d72801e62edb55edace29c783303663",
"size": "190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Aquifoliales/Aquifoliaceae/Ilex/Ilex atrata/Ilex atrata glabra/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
(function ($) {
//number aliases
$.extend($.inputmask.defaults.aliases, {
'decimal': {
mask: "~",
placeholder: "",
repeat: "*",
greedy: false,
numericInput: false,
isNumeric: true,
digits: "*", //number of fractionalDigits
groupSeparator: "",//",", // | "."
radixPoint: ".",
groupSize: 3,
autoGroup: false,
allowPlus: true,
allowMinus: true,
//todo
integerDigits: "*", //number of integerDigits
defaultValue: "",
prefix: "",
suffix: "",
//todo
getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) { //custom getMaskLength to take the groupSeparator into account
var calculatedLength = buffer.length;
if (!greedy) {
if (repeat == "*") {
calculatedLength = currentBuffer.length + 1;
} else if (repeat > 1) {
calculatedLength += (buffer.length * (repeat - 1));
}
}
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint);
var currentBufferStr = currentBuffer.join(""), strippedBufferStr = currentBufferStr.replace(new RegExp(escapedGroupSeparator, "g"), "").replace(new RegExp(escapedRadixPoint), ""),
groupOffset = currentBufferStr.length - strippedBufferStr.length;
return calculatedLength + groupOffset;
},
postFormat: function (buffer, pos, reformatOnly, opts) {
if (opts.groupSeparator == "") return pos;
var cbuf = buffer.slice(),
radixPos = $.inArray(opts.radixPoint, buffer);
if (!reformatOnly) {
cbuf.splice(pos, 0, "?"); //set position indicator
}
var bufVal = cbuf.join("");
if (opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) {
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), "");
var radixSplit = bufVal.split(opts.radixPoint);
bufVal = radixSplit[0];
var reg = new RegExp("([-\+]?[\\d\?]+)([\\d\?]{" + opts.groupSize + "})");
while (reg.test(bufVal)) {
bufVal = bufVal.replace(reg, "$1" + opts.groupSeparator + "$2");
bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator);
}
if (radixSplit.length > 1)
bufVal += opts.radixPoint + radixSplit[1];
}
buffer.length = bufVal.length; //align the length
for (var i = 0, l = bufVal.length; i < l; i++) {
buffer[i] = bufVal.charAt(i);
}
var newPos = $.inArray("?", buffer);
if (!reformatOnly) buffer.splice(newPos, 1);
return reformatOnly ? pos : newPos;
},
regex: {
number: function (opts) {
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint);
var digitExpression = isNaN(opts.digits) ? opts.digits : "{0," + opts.digits + "}";
var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : "";
return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)(" + escapedRadixPoint + "\\d" + digitExpression + ")?$");
}
},
onKeyDown: function (e, buffer, opts) {
var $input = $(this), input = this;
if (e.keyCode == opts.keyCode.TAB) {
var radixPosition = $.inArray(opts.radixPoint, buffer);
if (radixPosition != -1) {
var masksets = $input.data("_inputmask")["masksets"];
var activeMasksetIndex = $input.data("_inputmask")["activeMasksetIndex"];
for (var i = 1; i <= opts.digits && i < opts.getMaskLength(masksets[activeMasksetIndex]["_buffer"], masksets[activeMasksetIndex]["greedy"], masksets[activeMasksetIndex]["repeat"], buffer, opts) ; i++) {
if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == "") buffer[radixPosition + i] = "0";
}
input._valueSet(buffer.join(""));
}
} else if (e.keyCode == opts.keyCode.DELETE || e.keyCode == opts.keyCode.BACKSPACE) {
opts.postFormat(buffer, 0, true, opts);
input._valueSet(buffer.join(""));
return true;
}
},
definitions: {
'~': { //real number
validator: function (chrs, buffer, pos, strict, opts) {
if (chrs == "") return false;
if (!strict && pos <= 1 && buffer[0] === "0" && new RegExp("[\\d-]").test(chrs) && buffer.join("").length == 1) { //handle first char
buffer[0] = "";
return { "pos": 0 };
}
var cbuf = strict ? buffer.slice(0, pos) : buffer.slice();
cbuf.splice(pos, 0, chrs);
var bufferStr = cbuf.join("");
//strip groupseparator
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
bufferStr = bufferStr.replace(new RegExp(escapedGroupSeparator, "g"), "");
var isValid = opts.regex.number(opts).test(bufferStr);
if (!isValid) {
//let's help the regex a bit
bufferStr += "0";
isValid = opts.regex.number(opts).test(bufferStr);
if (!isValid) {
//make a valid group
var lastGroupSeparator = bufferStr.lastIndexOf(opts.groupSeparator);
for (var i = bufferStr.length - lastGroupSeparator; i <= 3; i++) {
bufferStr += "0";
}
isValid = opts.regex.number(opts).test(bufferStr);
if (!isValid && !strict) {
if (chrs == opts.radixPoint) {
isValid = opts.regex.number(opts).test("0" + bufferStr + "0");
if (isValid) {
buffer[pos] = "0";
pos++;
return { "pos": pos };
}
}
}
}
}
if (isValid != false && !strict && chrs != opts.radixPoint) {
var newPos = opts.postFormat(buffer, pos, false, opts);
return { "pos": newPos };
}
return isValid;
},
cardinality: 1,
prevalidator: null
}
},
insertMode: true,
autoUnmask: false
},
'integer': {
regex: {
number: function (opts) {
var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator);
var signedExpression = opts.allowPlus || opts.allowMinus ? "[" + (opts.allowPlus ? "\+" : "") + (opts.allowMinus ? "-" : "") + "]?" : "";
return new RegExp("^" + signedExpression + "(\\d+|\\d{1," + opts.groupSize + "}((" + escapedGroupSeparator + "\\d{" + opts.groupSize + "})?)+)$");
}
},
alias: "decimal"
}
});
})(jQuery);
| {
"content_hash": "fc2f6d9892ed45d002d83e0deb632fe3",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 226,
"avg_line_length": 52.349112426035504,
"alnum_prop": 0.4413925624505482,
"repo_name": "rachwal/BreezeWWW",
"id": "997a83f3a31c2752c8f4703f76455a11de685026",
"size": "9118",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Breeze/AdminLTE/plugins/input-mask/js/jquery.inputmask.numeric.extensions.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "96"
},
{
"name": "C#",
"bytes": "172642"
},
{
"name": "CSS",
"bytes": "581471"
},
{
"name": "HTML",
"bytes": "1703508"
},
{
"name": "JavaScript",
"bytes": "3712446"
},
{
"name": "PHP",
"bytes": "1684"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.stats.outliers_influence.GLMInfluence" href="statsmodels.stats.outliers_influence.GLMInfluence.html" />
<link rel="prev" title="statsmodels.stats.outliers_influence.OLSInfluence.resid_var" href="statsmodels.stats.outliers_influence.OLSInfluence.resid_var.html" />
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.11.1</span>
<span class="md-header-nav__topic"> statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.stats.outliers_influence.OLSInfluence.html" class="md-tabs__link">statsmodels.stats.outliers_influence.OLSInfluence</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.11.1</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a>
</li>
<li class="md-nav__item">
<a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a>
</li>
<li class="md-nav__item">
<a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a>
</li>
<li class="md-nav__item">
<a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a>
</li>
<li class="md-nav__item">
<a href="../distributions.html" class="md-nav__link">Distributions</a>
</li>
<li class="md-nav__item">
<a href="../graphics.html" class="md-nav__link">Graphics</a>
</li>
<li class="md-nav__item">
<a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a>
</li>
<li class="md-nav__item">
<a href="../tools.html" class="md-nav__link">Tools</a>
</li>
<li class="md-nav__item">
<a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../optimization.html" class="md-nav__link">Optimization</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-stats-outliers-influence-olsinfluence-sigma2-not-obsi--page-root">statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi<a class="headerlink" href="#generated-statsmodels-stats-outliers-influence-olsinfluence-sigma2-not-obsi--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="attribute">
<dt id="statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi">
<code class="sig-prename descclassname">OLSInfluence.</code><code class="sig-name descname">sigma2_not_obsi</code><a class="headerlink" href="#statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi" title="Permalink to this definition">¶</a></dt>
<dd><p>error variance for all LOOO regressions</p>
<p>This is ‘mse_resid’ from each auxiliary regression.</p>
<p>uses results from leave-one-observation-out loop</p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.stats.outliers_influence.OLSInfluence.resid_var.html" title="Material"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.stats.outliers_influence.OLSInfluence.resid_var </span>
</div>
</a>
<a href="statsmodels.stats.outliers_influence.GLMInfluence.html" title="Admonition"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.stats.outliers_influence.GLMInfluence </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Feb 21, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 2.4.2.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "038bf1670287dc2ac46ea557a7d554c8",
"timestamp": "",
"source": "github",
"line_count": 447,
"max_line_length": 999,
"avg_line_length": 41.266219239373605,
"alnum_prop": 0.6043586685460263,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "db91a25450591349f4e6989c5a96c92729f47130",
"size": "18454",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.11.1/generated/statsmodels.stats.outliers_influence.OLSInfluence.sigma2_not_obsi.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import React from "react";
import css from "../../../css/portal-dashboard/count-container.less";
interface IProps {
numItems: number;
containerLabel: string;
containerLabelType?: string;
}
export class CountContainer extends React.PureComponent<IProps> {
render() {
const { numItems, containerLabel, containerLabelType } = this.props;
return (
<div className={css.countContainer} data-cy={`num-${containerLabelType || containerLabel}-container`}>
<div className={`${css.numItems} ${containerLabelType && css.long}`}
data-cy={`num-${containerLabelType || containerLabel}`}>
<span className={css.containerLabel}>{containerLabel}: </span>
<span data-cy="item-number">{numItems}</span>
{containerLabelType && <span>{` ${containerLabelType}`}</span>}
</div>
</div>
);
}
}
| {
"content_hash": "6eca99f1d3db92cc1401f3115e96b2c7",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 108,
"avg_line_length": 34.44,
"alnum_prop": 0.6527293844367015,
"repo_name": "concord-consortium/portal-report",
"id": "6ce0caa7ed49c2661f9f3f3bac25eafd2085dc8a",
"size": "861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/components/portal-dashboard/count-container.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12402"
},
{
"name": "HTML",
"bytes": "2207"
},
{
"name": "JavaScript",
"bytes": "461208"
},
{
"name": "Less",
"bytes": "107912"
},
{
"name": "Shell",
"bytes": "3185"
},
{
"name": "TypeScript",
"bytes": "307248"
}
],
"symlink_target": ""
} |
module Author
VERSION = "1.2.0.alpha"
end
| {
"content_hash": "945f2b16fafc5b6795486e1f711a92f4",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 25,
"avg_line_length": 14.666666666666666,
"alnum_prop": 0.6818181818181818,
"repo_name": "tschmidt/author",
"id": "c3432ce6b0dd503b1a4aa9515642196194174074",
"size": "44",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/author/version.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13512"
},
{
"name": "Ruby",
"bytes": "34314"
}
],
"symlink_target": ""
} |
//
// ZNBWebViewController.h
// ZNBCos
//
// Created by mac on 2017/7/10.
// Copyright © 2017年 CoderZNBmm. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ZNBWebViewController : UIViewController
/** URL */
@property (nonatomic, copy) NSString *url;
/** source */
@property (nonatomic, copy) NSString *source;
@end
| {
"content_hash": "6d03edaba61fe00dce84855aeb8dec4c",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 54,
"avg_line_length": 20.6875,
"alnum_prop": 0.6948640483383686,
"repo_name": "ZNBmm/WeChat",
"id": "421c1345d4eddba90dc39c053da126fe4e75a46f",
"size": "334",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ZNBCos/Class/WEB/ZNBWebViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "345554"
},
{
"name": "Ruby",
"bytes": "447"
}
],
"symlink_target": ""
} |
package swarm.shared.structs;
import java.util.ArrayList;
import swarm.shared.app.BaseAppContext;
import swarm.shared.app.S_CommonApp;
import swarm.shared.account.E_SignUpValidationError;
import swarm.shared.account.I_SignUpCredentialValidator;
import swarm.shared.account.S_Account;
import swarm.shared.json.A_JsonEncodable;
import swarm.shared.json.A_JsonFactory;
import swarm.shared.json.E_JsonKey;
import swarm.shared.json.I_JsonComparable;
import swarm.shared.json.I_JsonObject;
import swarm.shared.json.JsonHelper;
import swarm.shared.utils.U_Regex;
public class CellAddress extends A_JsonEncodable implements I_JsonComparable
{
public static enum E_Part
{
USERNAME,
CELL
}
private String m_rawAddress = null;
private String m_caseSensitiveRawAddress = null;
private final ArrayList<String> m_parts = new ArrayList<String>();
private E_CellAddressParseError m_parseError = null;
public CellAddress()
{
init(null);
}
public CellAddress(String rawAddress)
{
init(rawAddress);
}
public CellAddress(A_JsonFactory jsonFactory, I_JsonObject json)
{
init(null);
this.readJson(json, jsonFactory);
}
public CellAddress(CellAddress source)
{
this(source.getRawLeadSlash());
}
public boolean isValid()
{
return this.getParseError() == E_CellAddressParseError.NO_ERROR;
}
public int getPartCount()
{
return m_parts.size();
}
public CellAddress getParentAddress(String homeAddress)
{
if( this.getPartCount() == 1 )
{
CellAddress address = new CellAddress(homeAddress);
if( address.isValid() )
{
if( !this.isEqualTo(address) )
{
return address;
}
}
}
else if( this.getPartCount() > 1 )
{
String parentAddress = "";
for(int i = 0; i < this.getPartCount()-1; i++ )
{
parentAddress += this.getPart(i) + "/";
}
CellAddress address = new CellAddress(parentAddress);
if( !address.isValid() )
{
throw new Error();
}
return address;
}
return null;
}
protected void init(String rawAddress)
{
m_caseSensitiveRawAddress = null;
m_rawAddress = null;
m_parseError = null;
m_parts.clear();
parse(rawAddress);
}
public E_CellAddressParseError getParseError()
{
return m_parseError;
}
public String getRawLeadSlash()
{
return "/" + m_rawAddress;
}
public String getRaw()
{
return m_rawAddress;
}
public String getCasedRaw()
{
return m_caseSensitiveRawAddress;
}
public String getCasedRawLeadSlash()
{
return "/" + m_caseSensitiveRawAddress;
}
public String getPart(int part)
{
return m_parts.get(part);
}
private void parse(String rawAddress)
{
m_caseSensitiveRawAddress = null;
m_rawAddress = null;
if( rawAddress == null || rawAddress.length() == 0 )
{
m_parseError = E_CellAddressParseError.EMPTY;
return;
}
//--- DRK > For some reason, the split function below won't recognize multiple trailing slashes, only leading slashes.
//--- So we just account for that strange case simply here.
if( rawAddress.contains("//") )
{
m_parseError = E_CellAddressParseError.TOO_MANY_PARTS;
return;
}
//--- DRK > Strip off leading and trailing slashes.
String rawAddressFiltered = rawAddress.startsWith("/") ? rawAddress.replaceFirst("/", "") : rawAddress;
rawAddressFiltered = rawAddressFiltered.endsWith("/") ? rawAddressFiltered.substring(0, rawAddressFiltered.length()-1) : rawAddressFiltered;
if( rawAddressFiltered == null || rawAddressFiltered.length() == 0 )
{
m_parseError = E_CellAddressParseError.EMPTY;
return;
}
String[] parts = rawAddressFiltered.split("/");
if( parts.length == 0 )
{
m_parseError = E_CellAddressParseError.EMPTY;
return;
}
else if( parts.length > S_CommonApp.MAX_CELL_ADDRESS_PARTS )
{
m_parseError = E_CellAddressParseError.TOO_MANY_PARTS;
return;
}
for( int i = 0; i < parts.length; i++ )
{
String part = parts[i];
if( !U_Regex.calcIsMatch(part, S_Account.USERNAME_REGEX) )
{
m_parseError = E_CellAddressParseError.BAD_FORMAT;
return;
}
String partToLowerCase = part.toLowerCase();
if( m_rawAddress == null )
{
m_rawAddress = partToLowerCase;
m_caseSensitiveRawAddress = part;
}
else
{
m_rawAddress += "/" + partToLowerCase;
m_caseSensitiveRawAddress += "/" + part;
}
m_parts.add(partToLowerCase);
}
m_parseError = E_CellAddressParseError.NO_ERROR;
}
public boolean isEqualTo(CellAddress address)
{
return this.m_rawAddress.equals(address.m_rawAddress);
}
@Override
public void writeJson(I_JsonObject json_out, A_JsonFactory factory)
{
factory.getHelper().putString(json_out, E_JsonKey.rawCellAddress, getCasedRaw());
}
@Override
public void readJson(I_JsonObject json, A_JsonFactory factory)
{
this.init(factory.getHelper().getString(json, E_JsonKey.rawCellAddress));
}
@Override
public boolean isEqualTo(A_JsonFactory factory, I_JsonObject json)
{
String rawAddress = factory.getHelper().getString(json, E_JsonKey.rawCellAddress);
if( rawAddress != null )
{
if( rawAddress.equals(m_rawAddress) )
{
return true;
}
}
return false;
}
@Override
public String toString()
{
return m_rawAddress;
}
} | {
"content_hash": "34c1f843fa38a8ba907b089673a040a0",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 142,
"avg_line_length": 20.7109375,
"alnum_prop": 0.6838928706148624,
"repo_name": "dougkoellmer/swarm",
"id": "2860e69557d770b57133dee3f2e36eb9b3f65ac4",
"size": "5302",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/swarm/shared/structs/CellAddress.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "72"
},
{
"name": "CSS",
"bytes": "25294"
},
{
"name": "Java",
"bytes": "1386664"
},
{
"name": "JavaScript",
"bytes": "401014"
},
{
"name": "Perl",
"bytes": "5572"
},
{
"name": "Shell",
"bytes": "6620"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('content', '0002_source_youtube_id'),
]
operations = [
migrations.AlterField(
model_name='video',
name='id',
field=models.CharField(max_length=70, primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='video',
name='image',
field=models.URLField(),
),
migrations.AlterField(
model_name='video',
name='thmubnail',
field=models.URLField(),
),
]
| {
"content_hash": "59e26adf0b075032fe938a5df3930ee7",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 85,
"avg_line_length": 24.464285714285715,
"alnum_prop": 0.5445255474452555,
"repo_name": "zee93/yt_lab",
"id": "d3d2988edf1a365eaf7d281276f3cb0143a47c53",
"size": "758",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yt_lab/content/migrations/0003_auto_20170319_2207.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Nginx",
"bytes": "998"
},
{
"name": "Python",
"bytes": "46221"
},
{
"name": "Shell",
"bytes": "3848"
}
],
"symlink_target": ""
} |
#ifndef LIBAOUT_H
#define LIBAOUT_H
/* We try to encapsulate the differences in the various a.out file
variants in a few routines, and otherwise share large masses of code.
This means we only have to fix bugs in one place, most of the time. */
#include "bfdlink.h"
/* Macros for accessing components in an aout header. */
#define H_PUT_64 bfd_h_put_64
#define H_PUT_32 bfd_h_put_32
#define H_PUT_16 bfd_h_put_16
#define H_PUT_8 bfd_h_put_8
#define H_PUT_S64 bfd_h_put_signed_64
#define H_PUT_S32 bfd_h_put_signed_32
#define H_PUT_S16 bfd_h_put_signed_16
#define H_PUT_S8 bfd_h_put_signed_8
#define H_GET_64 bfd_h_get_64
#define H_GET_32 bfd_h_get_32
#define H_GET_16 bfd_h_get_16
#define H_GET_8 bfd_h_get_8
#define H_GET_S64 bfd_h_get_signed_64
#define H_GET_S32 bfd_h_get_signed_32
#define H_GET_S16 bfd_h_get_signed_16
#define H_GET_S8 bfd_h_get_signed_8
/* Parameterize the a.out code based on whether it is being built
for a 32-bit architecture or a 64-bit architecture. */
/* Do not "beautify" the CONCAT* macro args. Traditional C will not
remove whitespace added here, and thus will fail to concatenate
the tokens. */
#if ARCH_SIZE==64
#define GET_WORD H_GET_64
#define GET_SWORD H_GET_S64
#define GET_MAGIC H_GET_32
#define PUT_WORD H_PUT_64
#define PUT_MAGIC H_PUT_32
#ifndef NAME
#define NAME(x,y) CONCAT3 (x,_64_,y)
#endif
#define JNAME(x) CONCAT2 (x,_64)
#define BYTES_IN_WORD 8
#else
#if ARCH_SIZE==16
#define GET_WORD H_GET_16
#define GET_SWORD H_GET_S16
#define GET_MAGIC H_GET_16
#define PUT_WORD H_PUT_16
#define PUT_MAGIC H_PUT_16
#ifndef NAME
#define NAME(x,y) CONCAT3 (x,_16_,y)
#endif
#define JNAME(x) CONCAT2 (x,_16)
#define BYTES_IN_WORD 2
#else /* ARCH_SIZE == 32 */
#define GET_WORD H_GET_32
#define GET_SWORD H_GET_S32
#define GET_MAGIC H_GET_32
#define PUT_WORD H_PUT_32
#define PUT_MAGIC H_PUT_32
#ifndef NAME
#define NAME(x,y) CONCAT3 (x,_32_,y)
#endif
#define JNAME(x) CONCAT2 (x,_32)
#define BYTES_IN_WORD 4
#endif /* ARCH_SIZE==32 */
#endif /* ARCH_SIZE==64 */
/* Declare at file level, since used in parameter lists, which have
weird scope. */
struct external_exec;
struct external_nlist;
struct reloc_ext_external;
struct reloc_std_external;
/* a.out backend linker hash table entries. */
struct aout_link_hash_entry
{
struct bfd_link_hash_entry root;
/* Whether this symbol has been written out. */
bfd_boolean written;
/* Symbol index in output file. */
int indx;
};
/* a.out backend linker hash table. */
struct aout_link_hash_table
{
struct bfd_link_hash_table root;
};
/* Look up an entry in an a.out link hash table. */
#define aout_link_hash_lookup(table, string, create, copy, follow) \
((struct aout_link_hash_entry *) \
bfd_link_hash_lookup (&(table)->root, (string), (create), (copy), (follow)))
/* Traverse an a.out link hash table. */
#define aout_link_hash_traverse(table, func, info) \
(bfd_link_hash_traverse \
(&(table)->root, \
(bfd_boolean (*) (struct bfd_link_hash_entry *, void *)) (func), \
(info)))
/* Get the a.out link hash table from the info structure. This is
just a cast. */
#define aout_hash_table(p) ((struct aout_link_hash_table *) ((p)->hash))
/* Back-end information for various a.out targets. */
struct aout_backend_data
{
/* Are ZMAGIC files mapped contiguously? If so, the text section may
need more padding, if the segment size (granularity for memory access
control) is larger than the page size. */
unsigned char zmagic_mapped_contiguous;
/* If this flag is set, ZMAGIC/NMAGIC file headers get mapped in with the
text section, which starts immediately after the file header.
If not, the text section starts on the next page. */
unsigned char text_includes_header;
/* If this flag is set, then if the entry address is not in the
first SEGMENT_SIZE bytes of the text section, it is taken to be
the address of the start of the text section. This can be useful
for kernels. */
unsigned char entry_is_text_address;
/* The value to pass to N_SET_FLAGS. */
unsigned char exec_hdr_flags;
/* If the text section VMA isn't specified, and we need an absolute
address, use this as the default. If we're producing a relocatable
file, zero is always used. */
/* ?? Perhaps a callback would be a better choice? Will this do anything
reasonable for a format that handles multiple CPUs with different
load addresses for each? */
bfd_vma default_text_vma;
/* Callback for setting the page and segment sizes, if they can't be
trivially determined from the architecture. */
bfd_boolean (*set_sizes) (bfd *);
/* zmagic files only. For go32, the length of the exec header contributes
to the size of the text section in the file for alignment purposes but
does *not* get counted in the length of the text section. */
unsigned char exec_header_not_counted;
/* Callback from the add symbols phase of the linker code to handle
a dynamic object. */
bfd_boolean (*add_dynamic_symbols)
(bfd *, struct bfd_link_info *, struct external_nlist **,
bfd_size_type *, char **);
/* Callback from the add symbols phase of the linker code to handle
adding a single symbol to the global linker hash table. */
bfd_boolean (*add_one_symbol)
(struct bfd_link_info *, bfd *, const char *, flagword,
asection *, bfd_vma, const char *, bfd_boolean, bfd_boolean,
struct bfd_link_hash_entry **);
/* Called to handle linking a dynamic object. */
bfd_boolean (*link_dynamic_object)
(struct bfd_link_info *, bfd *);
/* Called for each global symbol being written out by the linker.
This should write out the dynamic symbol information. */
bfd_boolean (*write_dynamic_symbol)
(bfd *, struct bfd_link_info *, struct aout_link_hash_entry *);
/* If this callback is not NULL, the linker calls it for each reloc.
RELOC is a pointer to the unswapped reloc. If *SKIP is set to
TRUE, the reloc will be skipped. *RELOCATION may be changed to
change the effects of the relocation. */
bfd_boolean (*check_dynamic_reloc)
(struct bfd_link_info *info, bfd *input_bfd,
asection *input_section, struct aout_link_hash_entry *h,
void * reloc, bfd_byte *contents, bfd_boolean *skip,
bfd_vma *relocation);
/* Called at the end of a link to finish up any dynamic linking
information. */
bfd_boolean (*finish_dynamic_link) (bfd *, struct bfd_link_info *);
};
#define aout_backend_info(abfd) \
((const struct aout_backend_data *)((abfd)->xvec->backend_data))
/* This is the layout in memory of a "struct exec" while we process it.
All 'lengths' are given as a number of bytes.
All 'alignments' are for relinkable files only; an alignment of
'n' indicates the corresponding segment must begin at an
address that is a multiple of (2**n). */
struct internal_exec
{
long a_info; /* Magic number and flags, packed. */
bfd_vma a_text; /* Length of text, in bytes. */
bfd_vma a_data; /* Length of data, in bytes. */
bfd_vma a_bss; /* Length of uninitialized data area in mem. */
bfd_vma a_syms; /* Length of symbol table data in file. */
bfd_vma a_entry; /* Start address. */
bfd_vma a_trsize; /* Length of text's relocation info, in bytes. */
bfd_vma a_drsize; /* Length of data's relocation info, in bytes. */
/* Added for i960 */
bfd_vma a_tload; /* Text runtime load address. */
bfd_vma a_dload; /* Data runtime load address. */
unsigned char a_talign; /* Alignment of text segment. */
unsigned char a_dalign; /* Alignment of data segment. */
unsigned char a_balign; /* Alignment of bss segment. */
char a_relaxable; /* Enough info for linker relax. */
};
/* Magic number is written
< MSB >
3130292827262524232221201918171615141312111009080706050403020100
< FLAGS >< MACHINE TYPE >< MAGIC NUMBER > */
/* Magic number for NetBSD is
<MSB >
3130292827262524232221201918171615141312111009080706050403020100
< FLAGS >< MACHINE TYPE >< MAGIC NUMBER > */
enum machine_type
{
M_UNKNOWN = 0,
M_68010 = 1,
M_68020 = 2,
M_SPARC = 3,
/* Skip a bunch so we don't run into any of SUN's numbers. */
/* Make these up for the ns32k. */
M_NS32032 = (64), /* NS32032 running ? */
M_NS32532 = (64 + 5), /* NS32532 running mach. */
M_386 = 100,
M_29K = 101, /* AMD 29000. */
M_386_DYNIX = 102, /* Sequent running dynix. */
M_ARM = 103, /* Advanced Risc Machines ARM. */
M_SPARCLET = 131, /* SPARClet = M_SPARC + 128. */
M_386_NETBSD = 134, /* NetBSD/i386 binary. */
M_68K_NETBSD = 135, /* NetBSD/m68k binary. */
M_68K4K_NETBSD = 136, /* NetBSD/m68k4k binary. */
M_532_NETBSD = 137, /* NetBSD/ns32k binary. */
M_SPARC_NETBSD = 138, /* NetBSD/sparc binary. */
M_PMAX_NETBSD = 139, /* NetBSD/pmax (MIPS little-endian) binary. */
M_VAX_NETBSD = 140, /* NetBSD/vax binary. */
M_ALPHA_NETBSD = 141, /* NetBSD/alpha binary. */
M_ARM6_NETBSD = 143, /* NetBSD/arm32 binary. */
M_SPARCLET_1 = 147, /* 0x93, reserved. */
M_POWERPC_NETBSD = 149, /* NetBSD/powerpc (big-endian) binary. */
M_VAX4K_NETBSD = 150, /* NetBSD/vax 4K pages binary. */
M_MIPS1 = 151, /* MIPS R2000/R3000 binary. */
M_MIPS2 = 152, /* MIPS R4000/R6000 binary. */
M_88K_OPENBSD = 153, /* OpenBSD/m88k binary. */
M_HPPA_OPENBSD = 154, /* OpenBSD/hppa binary. */
M_SPARC64_NETBSD = 156, /* NetBSD/sparc64 binary. */
M_X86_64_NETBSD = 157, /* NetBSD/amd64 binary. */
M_SPARCLET_2 = 163, /* 0xa3, reserved. */
M_SPARCLET_3 = 179, /* 0xb3, reserved. */
M_SPARCLET_4 = 195, /* 0xc3, reserved. */
M_HP200 = 200, /* HP 200 (68010) BSD binary. */
M_HP300 = (300 % 256), /* HP 300 (68020+68881) BSD binary. */
M_HPUX = (0x20c % 256), /* HP 200/300 HPUX binary. */
M_SPARCLET_5 = 211, /* 0xd3, reserved. */
M_SPARCLET_6 = 227, /* 0xe3, reserved. */
/*M_SPARCLET_7 = 243 / * 0xf3, reserved. */
M_SPARCLITE_LE = 243,
M_CRIS = 255 /* Axis CRIS binary. */
};
#define N_DYNAMIC(execp) ((execp)->a_info & 0x80000000)
#ifndef N_MAGIC
# define N_MAGIC(execp) ((execp)->a_info & 0xffff)
#endif
#ifndef N_MACHTYPE
# define N_MACHTYPE(execp) ((enum machine_type)(((execp)->a_info >> 16) & 0xff))
#endif
#ifndef N_FLAGS
# define N_FLAGS(execp) (((execp)->a_info >> 24) & 0xff)
#endif
#ifndef N_SET_INFO
# define N_SET_INFO(execp, magic, type, flags) \
((execp)->a_info = ((magic) & 0xffff) \
| (((int)(type) & 0xff) << 16) \
| (((flags) & 0xff) << 24))
#endif
#ifndef N_SET_DYNAMIC
# define N_SET_DYNAMIC(execp, dynamic) \
((execp)->a_info = (dynamic) ? (long) ((execp)->a_info | 0x80000000) : \
((execp)->a_info & 0x7fffffff))
#endif
#ifndef N_SET_MAGIC
# define N_SET_MAGIC(execp, magic) \
((execp)->a_info = (((execp)->a_info & 0xffff0000) | ((magic) & 0xffff)))
#endif
#ifndef N_SET_MACHTYPE
# define N_SET_MACHTYPE(execp, machtype) \
((execp)->a_info = \
((execp)->a_info & 0xff00ffff) | ((((int) (machtype)) &0xff) << 16))
#endif
#ifndef N_SET_FLAGS
# define N_SET_FLAGS(execp, flags) \
((execp)->a_info = \
((execp)->a_info & 0x00ffffff) | (((flags) & 0xff) << 24))
#endif
typedef struct aout_symbol
{
asymbol symbol;
short desc;
char other;
unsigned char type;
} aout_symbol_type;
/* The `tdata' struct for all a.out-like object file formats.
Various things depend on this struct being around any time an a.out
file is being handled. An example is dbxread.c in GDB. */
enum aout_subformat {
default_format = 0,
/* Used on HP 9000/300 running HP/UX. */
gnu_encap_format,
/* Used on Linux, 386BSD, etc. See include/aout/aout64.h. */
q_magic_format
};
enum aout_magic {
undecided_magic = 0,
z_magic,
o_magic,
n_magic
};
struct aoutdata
{
struct internal_exec *hdr; /* Exec file header. */
aout_symbol_type *symbols; /* Symtab for input bfd. */
/* For ease, we do this. */
asection *textsec;
asection *datasec;
asection *bsssec;
/* We remember these offsets so that after check_file_format, we have
no dependencies on the particular format of the exec_hdr. */
file_ptr sym_filepos;
file_ptr str_filepos;
/* Size of a relocation entry in external form. */
unsigned reloc_entry_size;
/* Size of a symbol table entry in external form. */
unsigned symbol_entry_size;
/* Page size - needed for alignment of demand paged files. */
unsigned long page_size;
/* Segment size - needed for alignment of demand paged files. */
unsigned long segment_size;
/* Zmagic disk block size - need to align the start of the text
section in ZMAGIC binaries. Normally the same as page_size. */
unsigned long zmagic_disk_block_size;
unsigned exec_bytes_size;
unsigned vma_adjusted : 1;
/* Used when a bfd supports several highly similar formats. */
enum aout_subformat subformat;
enum aout_magic magic;
/* A buffer for find_nearest_line. */
char *line_buf;
/* The external symbol information. */
struct external_nlist *external_syms;
bfd_size_type external_sym_count;
bfd_window sym_window;
char *external_strings;
bfd_size_type external_string_size;
bfd_window string_window;
struct aout_link_hash_entry **sym_hashes;
/* A pointer for shared library information. */
void * dynamic_info;
/* A mapping from local symbols to offsets into the global offset
table, used when linking on SunOS. This is indexed by the symbol
index. */
bfd_vma *local_got_offsets;
};
struct aout_data_struct
{
struct aoutdata a;
struct internal_exec e;
};
#define adata(bfd) ((bfd)->tdata.aout_data->a)
#define exec_hdr(bfd) (adata (bfd).hdr)
#define obj_aout_symbols(bfd) (adata (bfd).symbols)
#define obj_textsec(bfd) (adata (bfd).textsec)
#define obj_datasec(bfd) (adata (bfd).datasec)
#define obj_bsssec(bfd) (adata (bfd).bsssec)
#define obj_sym_filepos(bfd) (adata (bfd).sym_filepos)
#define obj_str_filepos(bfd) (adata (bfd).str_filepos)
#define obj_reloc_entry_size(bfd) (adata (bfd).reloc_entry_size)
#define obj_symbol_entry_size(bfd) (adata (bfd).symbol_entry_size)
#define obj_aout_subformat(bfd) (adata (bfd).subformat)
#define obj_aout_external_syms(bfd) (adata (bfd).external_syms)
#define obj_aout_external_sym_count(bfd) (adata (bfd).external_sym_count)
#define obj_aout_sym_window(bfd) (adata (bfd).sym_window)
#define obj_aout_external_strings(bfd) (adata (bfd).external_strings)
#define obj_aout_external_string_size(bfd) (adata (bfd).external_string_size)
#define obj_aout_string_window(bfd) (adata (bfd).string_window)
#define obj_aout_sym_hashes(bfd) (adata (bfd).sym_hashes)
#define obj_aout_dynamic_info(bfd) (adata (bfd).dynamic_info)
/* We take the address of the first element of an asymbol to ensure that the
macro is only ever applied to an asymbol. */
#define aout_symbol(asymbol) ((aout_symbol_type *)(&(asymbol)->the_bfd))
/* Information we keep for each a.out section. This is currently only
used by the a.out backend linker. */
struct aout_section_data_struct
{
/* The unswapped relocation entries for this section. */
void * relocs;
};
#define aout_section_data(s) \
((struct aout_section_data_struct *) (s)->used_by_bfd)
#define set_aout_section_data(s,v) \
((s)->used_by_bfd = (void *)&(v)->relocs)
/* Prototype declarations for functions defined in aoutx.h. */
extern bfd_boolean NAME (aout, squirt_out_relocs)
(bfd *, asection *);
extern bfd_boolean NAME (aout, make_sections)
(bfd *);
extern const bfd_target * NAME (aout, some_aout_object_p)
(bfd *, struct internal_exec *, const bfd_target *(*) (bfd *));
extern bfd_boolean NAME (aout, mkobject)
(bfd *);
extern enum machine_type NAME (aout, machine_type)
(enum bfd_architecture, unsigned long, bfd_boolean *);
extern bfd_boolean NAME (aout, set_arch_mach)
(bfd *, enum bfd_architecture, unsigned long);
extern bfd_boolean NAME (aout, new_section_hook)
(bfd *, asection *);
extern bfd_boolean NAME (aout, set_section_contents)
(bfd *, sec_ptr, const void *, file_ptr, bfd_size_type);
extern asymbol * NAME (aout, make_empty_symbol)
(bfd *);
extern bfd_boolean NAME (aout, translate_symbol_table)
(bfd *, aout_symbol_type *, struct external_nlist *, bfd_size_type,
char *, bfd_size_type, bfd_boolean);
extern bfd_boolean NAME (aout, slurp_symbol_table)
(bfd *);
extern bfd_boolean NAME (aout, write_syms)
(bfd *);
extern void NAME (aout, reclaim_symbol_table)
(bfd *);
extern long NAME (aout, get_symtab_upper_bound)
(bfd *);
extern long NAME (aout, canonicalize_symtab)
(bfd *, asymbol **);
extern void NAME (aout, swap_ext_reloc_in)
(bfd *, struct reloc_ext_external *, arelent *, asymbol **,
bfd_size_type);
extern void NAME (aout, swap_std_reloc_in)
(bfd *, struct reloc_std_external *, arelent *, asymbol **,
bfd_size_type);
extern reloc_howto_type * NAME (aout, reloc_type_lookup)
(bfd *, bfd_reloc_code_real_type);
extern reloc_howto_type * NAME (aout, reloc_name_lookup)
(bfd *, const char *);
extern bfd_boolean NAME (aout, slurp_reloc_table)
(bfd *, sec_ptr, asymbol **);
extern long NAME (aout, canonicalize_reloc)
(bfd *, sec_ptr, arelent **, asymbol **);
extern long NAME (aout, get_reloc_upper_bound)
(bfd *, sec_ptr);
extern void NAME (aout, reclaim_reloc)
(bfd *, sec_ptr);
extern alent * NAME (aout, get_lineno)
(bfd *, asymbol *);
extern void NAME (aout, print_symbol)
(bfd *, void *, asymbol *, bfd_print_symbol_type);
extern void NAME (aout, get_symbol_info)
(bfd *, asymbol *, symbol_info *);
extern bfd_boolean NAME (aout, find_nearest_line)
(bfd *, asymbol **, asection *, bfd_vma,
const char **, const char **, unsigned int *, unsigned int *);
extern long NAME (aout, read_minisymbols)
(bfd *, bfd_boolean, void * *, unsigned int *);
extern asymbol * NAME (aout, minisymbol_to_symbol)
(bfd *, bfd_boolean, const void *, asymbol *);
extern int NAME (aout, sizeof_headers)
(bfd *, struct bfd_link_info *);
extern bfd_boolean NAME (aout, adjust_sizes_and_vmas)
(bfd *);
extern void NAME (aout, swap_exec_header_in)
(bfd *, struct external_exec *, struct internal_exec *);
extern void NAME (aout, swap_exec_header_out)
(bfd *, struct internal_exec *, struct external_exec *);
extern struct bfd_hash_entry * NAME (aout, link_hash_newfunc)
(struct bfd_hash_entry *, struct bfd_hash_table *, const char *);
extern bfd_boolean NAME (aout, link_hash_table_init)
(struct aout_link_hash_table *, bfd *,
struct bfd_hash_entry *(*) (struct bfd_hash_entry *,
struct bfd_hash_table *,
const char *),
unsigned int);
extern struct bfd_link_hash_table * NAME (aout, link_hash_table_create)
(bfd *);
extern bfd_boolean NAME (aout, link_add_symbols)
(bfd *, struct bfd_link_info *);
extern bfd_boolean NAME (aout, final_link)
(bfd *, struct bfd_link_info *,
void (*) (bfd *, file_ptr *, file_ptr *, file_ptr *));
extern bfd_boolean NAME (aout, bfd_free_cached_info)
(bfd *);
#define aout_32_find_inliner_info _bfd_nosymbols_find_inliner_info
#if 0 /* Are these needed? */
#define aout_16_find_inliner_info _bfd_nosymbols_find_inliner_info
#define aout_64_find_inliner_info _bfd_nosymbols_find_inliner_info
#endif
/* A.out uses the generic versions of these routines... */
#define aout_16_get_section_contents _bfd_generic_get_section_contents
#define aout_32_get_section_contents _bfd_generic_get_section_contents
#define aout_64_get_section_contents _bfd_generic_get_section_contents
#ifndef NO_WRITE_HEADER_KLUDGE
#define NO_WRITE_HEADER_KLUDGE 0
#endif
#ifndef aout_32_bfd_is_local_label_name
#define aout_32_bfd_is_local_label_name bfd_generic_is_local_label_name
#endif
#ifndef aout_32_bfd_is_target_special_symbol
#define aout_32_bfd_is_target_special_symbol _bfd_bool_bfd_asymbol_false
#endif
#ifndef WRITE_HEADERS
#define WRITE_HEADERS(abfd, execp) \
{ \
if (adata(abfd).magic == undecided_magic) \
NAME (aout, adjust_sizes_and_vmas) (abfd); \
\
execp->a_syms = bfd_get_symcount (abfd) * EXTERNAL_NLIST_SIZE; \
execp->a_entry = bfd_get_start_address (abfd); \
\
execp->a_trsize = ((obj_textsec (abfd)->reloc_count) * \
obj_reloc_entry_size (abfd)); \
execp->a_drsize = ((obj_datasec (abfd)->reloc_count) * \
obj_reloc_entry_size (abfd)); \
NAME (aout, swap_exec_header_out) (abfd, execp, & exec_bytes); \
\
if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0 \
|| bfd_bwrite (& exec_bytes, (bfd_size_type) EXEC_BYTES_SIZE, \
abfd) != EXEC_BYTES_SIZE) \
return FALSE; \
/* Now write out reloc info, followed by syms and strings. */ \
\
if (bfd_get_outsymbols (abfd) != NULL \
&& bfd_get_symcount (abfd) != 0) \
{ \
if (bfd_seek (abfd, (file_ptr) (N_SYMOFF (execp)), SEEK_SET) != 0)\
return FALSE; \
\
if (! NAME (aout, write_syms) (abfd)) \
return FALSE; \
} \
\
if (bfd_seek (abfd, (file_ptr) (N_TRELOFF (execp)), SEEK_SET) != 0) \
return FALSE; \
if (!NAME (aout, squirt_out_relocs) (abfd, obj_textsec (abfd))) \
return FALSE; \
\
if (bfd_seek (abfd, (file_ptr) (N_DRELOFF (execp)), SEEK_SET) != 0) \
return FALSE; \
if (!NAME (aout, squirt_out_relocs) (abfd, obj_datasec (abfd))) \
return FALSE; \
}
#endif
/* Test if a read-only section can be merged with .text. This is
possible if:
1. Section has file contents and is read-only.
2. The VMA of the section is after the end of .text and before
the start of .data.
3. The image is demand-pageable (otherwise, a_text in the header
will not reflect the gap between .text and .data). */
#define aout_section_merge_with_text_p(abfd, sec) \
(((sec)->flags & (SEC_HAS_CONTENTS | SEC_READONLY)) == \
(SEC_HAS_CONTENTS | SEC_READONLY) \
&& obj_textsec (abfd) != NULL \
&& obj_datasec (abfd) != NULL \
&& (sec)->vma >= (obj_textsec (abfd)->vma + \
obj_textsec (abfd)->size) \
&& ((sec)->vma + (sec)->size) <= obj_datasec (abfd)->vma \
&& ((abfd)->flags & D_PAGED) != 0)
#endif /* ! defined (LIBAOUT_H) */
| {
"content_hash": "db8c5846f5a187cf6f8eb455a1975b0a",
"timestamp": "",
"source": "github",
"line_count": 668,
"max_line_length": 80,
"avg_line_length": 33.77994011976048,
"alnum_prop": 0.6514513627298915,
"repo_name": "timfel/squeakvm",
"id": "5b6424c7094a086b3f150b6383f55a063998ed0a",
"size": "23504",
"binary": false,
"copies": "7",
"ref": "refs/heads/Cog",
"path": "processors/ARM/gdb-8.3.1/bfd/libaout.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "AppleScript",
"bytes": "2412"
},
{
"name": "Assembly",
"bytes": "9991810"
},
{
"name": "Awk",
"bytes": "3027"
},
{
"name": "Batchfile",
"bytes": "248"
},
{
"name": "C",
"bytes": "151151341"
},
{
"name": "C#",
"bytes": "55625"
},
{
"name": "C++",
"bytes": "7199718"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "7489"
},
{
"name": "CSS",
"bytes": "1703"
},
{
"name": "DIGITAL Command Language",
"bytes": "43378"
},
{
"name": "DTrace",
"bytes": "1790"
},
{
"name": "Elixir",
"bytes": "4977"
},
{
"name": "Emacs Lisp",
"bytes": "718"
},
{
"name": "Groff",
"bytes": "95488"
},
{
"name": "HTML",
"bytes": "193071"
},
{
"name": "Lex",
"bytes": "14360"
},
{
"name": "M4",
"bytes": "622870"
},
{
"name": "Makefile",
"bytes": "2587923"
},
{
"name": "Mathematica",
"bytes": "51"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "9014"
},
{
"name": "Objective-C",
"bytes": "1117281"
},
{
"name": "OpenEdge ABL",
"bytes": "57017"
},
{
"name": "PAWN",
"bytes": "2172"
},
{
"name": "PHP",
"bytes": "50"
},
{
"name": "POV-Ray SDL",
"bytes": "82424"
},
{
"name": "Pascal",
"bytes": "69871"
},
{
"name": "Perl",
"bytes": "36181"
},
{
"name": "R",
"bytes": "306598"
},
{
"name": "Rebol",
"bytes": "405"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "1978997"
},
{
"name": "Smalltalk",
"bytes": "836115"
},
{
"name": "Yacc",
"bytes": "34115"
}
],
"symlink_target": ""
} |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-661
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2009.02.02 at 03:34:01 PM MST
//
package gov.loc.mods.v3;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for modsType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="modsType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <group ref="{http://www.loc.gov/mods/v3}modsGroup" maxOccurs="unbounded"/>
* <attribute name="ID" type="{http://www.w3.org/2001/XMLSchema}ID" />
* <attribute name="version" type="{http://www.loc.gov/mods/v3}versionType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "modsType", propOrder = {
"modsGroup"
})
@XmlRootElement(name = "mods")
public class ModsType {
@XmlElements({
@XmlElement(name = "part", type = PartType.class),
@XmlElement(name = "language", type = LanguageType.class),
@XmlElement(name = "note", type = NoteType.class),
@XmlElement(name = "identifier", type = IdentifierType.class),
@XmlElement(name = "classification", type = ClassificationType.class),
@XmlElement(name = "titleInfo", type = TitleInfoType.class),
@XmlElement(name = "extension", type = ExtensionType.class),
@XmlElement(name = "accessCondition", type = AccessConditionType.class),
@XmlElement(name = "typeOfResource", type = TypeOfResourceType.class),
@XmlElement(name = "physicalDescription", type = PhysicalDescriptionType.class),
@XmlElement(name = "tableOfContents", type = TableOfContentsType.class),
@XmlElement(name = "subject", type = SubjectType.class),
@XmlElement(name = "relatedItem", type = RelatedItemType.class),
@XmlElement(name = "genre", type = GenreType.class),
@XmlElement(name = "recordInfo", type = RecordInfoType.class),
@XmlElement(name = "originInfo", type = OriginInfoType.class),
@XmlElement(name = "location", type = LocationType.class),
@XmlElement(name = "name", type = NameType.class),
@XmlElement(name = "abstract", type = AbstractType.class),
@XmlElement(name = "targetAudience", type = TargetAudienceType.class)
})
protected List<Object> modsGroup;
@XmlAttribute(name = "ID")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute
protected String version;
/**
* Gets the value of the modsGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the modsGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getModsGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PartType }
* {@link LanguageType }
* {@link NoteType }
* {@link IdentifierType }
* {@link ClassificationType }
* {@link TitleInfoType }
* {@link ExtensionType }
* {@link AccessConditionType }
* {@link TypeOfResourceType }
* {@link PhysicalDescriptionType }
* {@link TableOfContentsType }
* {@link SubjectType }
* {@link RelatedItemType }
* {@link GenreType }
* {@link RecordInfoType }
* {@link OriginInfoType }
* {@link LocationType }
* {@link NameType }
* {@link AbstractType }
* {@link TargetAudienceType }
*
*
*/
public List<Object> getModsGroup() {
if (modsGroup == null) {
modsGroup = new ArrayList<Object>();
}
return this.modsGroup;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setID(String value) {
this.id = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
| {
"content_hash": "db1e5aecd51514da81a2c14eff6e9893",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 126,
"avg_line_length": 33.06703910614525,
"alnum_prop": 0.607704004054739,
"repo_name": "digital-antiquity/repo-metadata",
"id": "16faae3cf58cc514e148dcc45497cf85282e473d",
"size": "5919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/gov/loc/mods/v3/ModsType.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2028980"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4b8992e6f83b3093560ed21ff962aa8c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "5d66948aa9c4d3470a4fc40eada1dacbc3bfd219",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Ptilimnium/Ptilimnium capillaceum/ Syn. Ammi rubricaule/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.amazonaws.services.outposts.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/outposts-2019-12-03/GetSite" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetSiteResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
private Site site;
/**
* @param site
*/
public void setSite(Site site) {
this.site = site;
}
/**
* @return
*/
public Site getSite() {
return this.site;
}
/**
* @param site
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetSiteResult withSite(Site site) {
setSite(site);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSite() != null)
sb.append("Site: ").append(getSite());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetSiteResult == false)
return false;
GetSiteResult other = (GetSiteResult) obj;
if (other.getSite() == null ^ this.getSite() == null)
return false;
if (other.getSite() != null && other.getSite().equals(this.getSite()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSite() == null) ? 0 : getSite().hashCode());
return hashCode;
}
@Override
public GetSiteResult clone() {
try {
return (GetSiteResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| {
"content_hash": "10fbe612c7be2c1dac9d991eb4e63f0e",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 140,
"avg_line_length": 26.322916666666668,
"alnum_prop": 0.591610605461021,
"repo_name": "aws/aws-sdk-java",
"id": "2d45c6803cb4b679a9ab7eed7f65ab29036714a6",
"size": "3107",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-outposts/src/main/java/com/amazonaws/services/outposts/model/GetSiteResult.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
// php-export-data by Eli Dickinson, http://github.com/elidickinson/php-export-data
/**
* ExportData is the base class for exporters to specific file formats. See other
* classes below.
*/
abstract class ExportData {
protected $exportTo; // Set in constructor to one of 'browser', 'file', 'string'
protected $stringData; // stringData so far, used if export string mode
protected $tempFile; // handle to temp file (for export file mode)
protected $tempFilename; // temp file name and path (for export file mode)
public $filename; // file mode: the output file name; browser mode: file name for download; string mode: not used
public function __construct($exportTo = "browser", $filename = "exportdata") {
if(!in_array($exportTo, array('browser','file','string') )) {
throw new Exception("$exportTo is not a valid ExportData export type");
}
$this->exportTo = $exportTo;
$this->filename = $filename;
}
public function initialize() {
switch($this->exportTo) {
case 'browser':
$this->sendHttpHeaders();
break;
case 'string':
$this->stringData = '';
break;
case 'file':
$this->tempFilename = tempnam(sys_get_temp_dir(), 'exportdata');
$this->tempFile = fopen($this->tempFilename, "w");
break;
}
$this->write($this->generateHeader());
}
public function addRow($row) {
$this->write($this->generateRow($row));
}
public function finalize() {
$this->write($this->generateFooter());
switch($this->exportTo) {
case 'browser':
flush();
break;
case 'string':
// do nothing
break;
case 'file':
// close temp file and move it to correct location
fclose($this->tempFile);
rename($this->tempFilename, $this->filename);
break;
}
}
public function getString() {
return $this->stringData;
}
abstract public function sendHttpHeaders();
protected function write($data) {
switch($this->exportTo) {
case 'browser':
echo $data;
break;
case 'string':
$this->stringData .= $data;
break;
case 'file':
fwrite($this->tempFile, $data);
break;
}
}
protected function generateHeader() {
// can be overridden by subclass to return any data that goes at the top of the exported file
}
protected function generateFooter() {
// can be overridden by subclass to return any data that goes at the bottom of the exported file
}
// In subclasses generateRow will take $row array and return string of it formatted for export type
abstract protected function generateRow($row);
}
/**
* ExportDataTSV - Exports to TSV (tab separated value) format.
*/
class ExportDataTSV extends ExportData {
function generateRow($row) {
foreach ($row as $key => $value) {
// Escape inner quotes and wrap all contents in new quotes.
// Note that we are using \" to escape double quote not ""
$row[$key] = '"'. str_replace('"', '\"', $value) .'"';
}
return implode("\t", $row) . "\n";
}
function sendHttpHeaders() {
header("Content-type: text/tab-separated-values");
header("Content-Disposition: attachment; filename=".basename($this->filename));
}
}
/**
* ExportDataCSV - Exports to CSV (comma separated value) format.
*/
class ExportDataCSV extends ExportData {
function generateRow($row) {
foreach ($row as $key => $value) {
// Escape inner quotes and wrap all contents in new quotes.
// Note that we are using \" to escape double quote not ""
$row[$key] = '"'. str_replace('"', '\"', $value) .'"';
}
return implode(",", $row) . "\n";
}
function sendHttpHeaders() {
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".basename($this->filename));
}
}
/**
* ExportDataExcel exports data into an XML format (spreadsheetML) that can be
* read by MS Excel 2003 and newer as well as OpenOffice
*
* Creates a workbook with a single worksheet (title specified by
* $title).
*
* Note that using .XML is the "correct" file extension for these files, but it
* generally isn't associated with Excel. Using .XLS is tempting, but Excel 2007 will
* throw a scary warning that the extension doesn't match the file type.
*
* Based on Excel XML code from Excel_XML (http://github.com/oliverschwarz/php-excel)
* by Oliver Schwarz
*/
class ExportDataExcel extends ExportData {
const XmlHeader = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
const XmlFooter = "</Workbook>";
public $encoding = 'UTF-8'; // encoding type to specify in file.
// Note that you're on your own for making sure your data is actually encoded to this encoding
public $title = 'Sheet1'; // title for Worksheet
function generateHeader() {
// workbook header
$output = stripslashes(sprintf(self::XmlHeader, $this->encoding)) . "\n";
// Set up styles
$output .= "<Styles>\n";
$output .= "<Style ss:ID=\"sDT\"><NumberFormat ss:Format=\"Short Date\"/></Style>\n";
$output .= "</Styles>\n";
// worksheet header
$output .= sprintf("<Worksheet ss:Name=\"%s\">\n <Table>\n", htmlentities($this->title));
return $output;
}
function generateFooter() {
$output = '';
// worksheet footer
$output .= " </Table>\n</Worksheet>\n";
// workbook footer
$output .= self::XmlFooter;
return $output;
}
function generateRow($row) {
$output = '';
$output .= " <Row>\n";
foreach ($row as $k => $v) {
$output .= $this->generateCell($v);
}
$output .= " </Row>\n";
return $output;
}
private function generateCell($item) {
$output = '';
$style = '';
// Tell Excel to treat as a number. Note that Excel only stores roughly 15 digits, so keep
// as text if number is longer than that.
if(preg_match("/^-?\d+(?:[.,]\d+)?$/",$item) && (strlen($item) < 15)) {
$type = 'Number';
}
// Sniff for valid dates; should look something like 2010-07-14 or 7/14/2010 etc. Can
// also have an optional time after the date.
//
// Note we want to be very strict in what we consider a date. There is the possibility
// of really screwing up the data if we try to reformat a string that was not actually
// intended to represent a date.
elseif(preg_match("/^(\d{1,2}|\d{4})[\/\-]\d{1,2}[\/\-](\d{1,2}|\d{4})([^\d].+)?$/",$item) &&
($timestamp = strtotime($item)) &&
($timestamp > 0) &&
($timestamp < strtotime('+500 years'))) {
$type = 'DateTime';
$item = strftime("%Y-%m-%dT%H:%M:%S",$timestamp);
$style = 'sDT'; // defined in header; tells excel to format date for display
}
else {
$type = 'String';
}
$item = str_replace(''', ''', htmlspecialchars($item, ENT_QUOTES));
$item = str_replace('&#13;', ' ', $item);
$item = str_replace('&#10;', ' ', $item);
$output .= " ";
$output .= $style ? "<Cell ss:StyleID=\"$style\">" : "<Cell>";
$output .= sprintf("<Data ss:Type=\"%s\">%s</Data>", $type, $item);
$output .= "</Cell>\n";
return $output;
}
function sendHttpHeaders() {
header("Content-Type: application/vnd.ms-excel; charset=" . $this->encoding);
header("Content-Disposition: inline; filename=\"" . basename($this->filename) . "\"");
}
} | {
"content_hash": "b93239b5eac3fa5c7c53016585d5ce62",
"timestamp": "",
"source": "github",
"line_count": 244,
"max_line_length": 285,
"avg_line_length": 30.299180327868854,
"alnum_prop": 0.6381712430677668,
"repo_name": "benohead/kanban_board",
"id": "fe3746e097224c93c5ca0458793c33c5d01be53f",
"size": "7393",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "php-export-data.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "83610"
},
{
"name": "JavaScript",
"bytes": "95419"
},
{
"name": "PHP",
"bytes": "740453"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="design-24.1.1">
<ANNOTATIONS>
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/design/24.1.1/annotations.zip!/" />
</ANNOTATIONS>
<CLASSES>
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/design/24.1.1/jars/classes.jar!/" />
<root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/design/24.1.1/res" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://G:/android/Sdk/extras/android/m2repository/com/android/support/design/24.1.1/design-24.1.1-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "fb2a5202d777bca4299290f1a096afcf",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 131,
"avg_line_length": 47.4,
"alnum_prop": 0.6765119549929677,
"repo_name": "yinhuagithub/MaleAmbry",
"id": "b8273197dd90be6a1e14f754ffcb105144539fbe",
"size": "711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/design_24_1_1.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "279368"
}
],
"symlink_target": ""
} |
/*
* @author max
*/
package com.intellij.codeInsight.daemon.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.daemon.DaemonBundle;
import com.intellij.codeInsight.daemon.GutterIconNavigationHandler;
import com.intellij.codeInsight.navigation.ListBackgroundUpdaterTask;
import com.intellij.ide.util.*;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.impl.FindSuperElementsHelper;
import com.intellij.psi.presentation.java.ClassPresentationUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.PsiElementProcessorAdapter;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.search.searches.FunctionalExpressionSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Function;
import com.intellij.util.NullableFunction;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.text.MessageFormat;
import java.util.*;
public class MarkerType {
private final GutterIconNavigationHandler<PsiElement> handler;
private final Function<PsiElement, String> myTooltip;
@NotNull private final String myDebugName;
/**
* @deprecated use {@link #MarkerType(String, Function, LineMarkerNavigator)} instead
*/
public MarkerType(@NotNull Function<PsiElement, String> tooltip, @NotNull final LineMarkerNavigator navigator) {
this("Unknown", tooltip, navigator);
}
public MarkerType(@NotNull String debugName, @NotNull Function<PsiElement, String> tooltip, @NotNull final LineMarkerNavigator navigator) {
myTooltip = tooltip;
myDebugName = debugName;
handler = (e, elt) -> DumbService.getInstance(elt.getProject()).withAlternativeResolveEnabled(() -> navigator.browse(e, elt));
}
@Override
public String toString() {
return myDebugName;
}
@NotNull
public GutterIconNavigationHandler<PsiElement> getNavigationHandler() {
return handler;
}
@NotNull
public Function<PsiElement, String> getTooltip() {
return myTooltip;
}
public static final MarkerType OVERRIDING_METHOD = new MarkerType("OVERRIDING_METHOD", (NullableFunction<PsiElement, String>)element -> {
PsiElement parent = getParentMethod(element);
if (!(parent instanceof PsiMethod)) return null;
PsiMethod method = (PsiMethod)parent;
return calculateOverridingMethodTooltip(method, method != element.getParent());
}, new LineMarkerNavigator() {
@Override
public void browse(MouseEvent e, PsiElement element) {
PsiElement parent = getParentMethod(element);
if (!(parent instanceof PsiMethod)) return;
PsiMethod method = (PsiMethod)parent;
navigateToOverridingMethod(e, method, method != element.getParent());
}
});
public static final MarkerType SIBLING_OVERRIDING_METHOD = new MarkerType("SIBLING_OVERRIDING_METHOD",
(NullableFunction<PsiElement, String>)element -> {
PsiElement parent = getParentMethod(element);
if (!(parent instanceof PsiMethod)) return null;
PsiMethod method = (PsiMethod)parent;
return calculateOverridingSiblingMethodTooltip(method);
}, new LineMarkerNavigator() {
@Override
public void browse(MouseEvent e, PsiElement element) {
PsiElement parent = getParentMethod(element);
if (!(parent instanceof PsiMethod)) return;
PsiMethod method = (PsiMethod)parent;
navigateToSiblingOverridingMethod(e, method);
}
});
@Nullable
private static String calculateOverridingMethodTooltip(@NotNull PsiMethod method, boolean acceptSelf) {
PsiMethod[] superMethods = composeSuperMethods(method, acceptSelf);
if (superMethods.length == 0) return null;
PsiMethod superMethod = superMethods[0];
boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT);
final boolean sameSignature = superMethod.getSignature(PsiSubstitutor.EMPTY).equals(method.getSignature(PsiSubstitutor.EMPTY));
@NonNls final String key;
if (isSuperAbstract && !isAbstract){
key = sameSignature ? "method.implements" : "method.implements.in";
}
else{
key = sameSignature ? "method.overrides" : "method.overrides.in";
}
return composeText(superMethods, "", DaemonBundle.message(key), IdeActions.ACTION_GOTO_SUPER);
}
@Nullable
private static String calculateOverridingSiblingMethodTooltip(@NotNull PsiMethod method) {
FindSuperElementsHelper.SiblingInfo pair = FindSuperElementsHelper.getSiblingInfoInheritedViaSubClass(method);
if (pair == null) return null;
PsiMethod superMethod = pair.superMethod;
PsiClass subClass = pair.subClass;
boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT);
String postfix = MessageFormat.format(" via sub-class <a href=\"#javaClass/{0}\">{0}</a>", ClassPresentationUtil.getNameForClass(subClass, true));
@NonNls String pattern = DaemonBundle.message(isSuperAbstract && !isAbstract ?
"method.implements" :
"method.overrides") + postfix;
return composeText(new PsiElement[]{superMethod}, "", pattern, IdeActions.ACTION_GOTO_SUPER);
}
@NotNull
private static String composeText(@NotNull PsiElement[] methods, @NotNull String start, @NotNull String pattern, @NotNull String actionId) {
Shortcut[] shortcuts = ActionManager.getInstance().getAction(actionId).getShortcutSet().getShortcuts();
Shortcut shortcut = ArrayUtil.getFirstElement(shortcuts);
String postfix = "<br><div style='margin-top: 5px'><font size='2'>Click";
if (shortcut != null) postfix += " or press " + KeymapUtil.getShortcutText(shortcut);
postfix += " to navigate</font></div>";
return GutterIconTooltipHelper.composeText(Arrays.asList(methods), start, pattern, postfix);
}
private static void navigateToOverridingMethod(MouseEvent e, @NotNull PsiMethod method, boolean acceptSelf) {
PsiMethod[] superMethods = composeSuperMethods(method, acceptSelf);
if (superMethods.length == 0) return;
boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature(superMethods);
PsiElementListNavigator.openTargets(e, superMethods,
DaemonBundle.message("navigation.title.super.method", method.getName()),
DaemonBundle.message("navigation.findUsages.title.super.method", method.getName()),
new MethodCellRenderer(showMethodNames));
}
private static void navigateToSiblingOverridingMethod(MouseEvent e, @NotNull PsiMethod method) {
PsiMethod superMethod = FindSuperElementsHelper.getSiblingInheritedViaSubClass(method);
if (superMethod == null) return;
PsiElementListNavigator.openTargets(e, new NavigatablePsiElement[]{superMethod},
DaemonBundle.message("navigation.title.super.method", method.getName()),
DaemonBundle.message("navigation.findUsages.title.super.method", method.getName()),
new MethodCellRenderer(false));
}
@NotNull
private static PsiMethod[] composeSuperMethods(@NotNull PsiMethod method, boolean acceptSelf) {
PsiElement[] superElements = FindSuperElementsHelper.findSuperElements(method);
PsiMethod[] superMethods = ContainerUtil.map(superElements, element -> (PsiMethod)element, PsiMethod.EMPTY_ARRAY);
if (acceptSelf) {
superMethods = ArrayUtil.prepend(method, superMethods);
}
return superMethods;
}
private static PsiElement getParentMethod(@NotNull PsiElement element) {
final PsiElement parent = element.getParent();
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(parent);
return interfaceMethod != null ? interfaceMethod : parent;
}
public static final String SEARCHING_FOR_OVERRIDING_METHODS = "Searching for Overriding Methods";
public static final MarkerType OVERRIDDEN_METHOD = new MarkerType("OVERRIDDEN_METHOD", (NullableFunction<PsiElement, String>)element -> {
PsiElement parent = element.getParent();
if (!(parent instanceof PsiMethod)) return null;
PsiMethod method = (PsiMethod)parent;
return getOverriddenMethodTooltip(method);
}, new LineMarkerNavigator(){
@Override
public void browse(MouseEvent e, PsiElement element) {
PsiElement parent = element.getParent();
if (!(parent instanceof PsiMethod)) return;
navigateToOverriddenMethod(e, (PsiMethod)parent);
}
});
private static String getOverriddenMethodTooltip(@NotNull PsiMethod method) {
final PsiClass aClass = method.getContainingClass();
if (aClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) {
return DaemonBundle.message("method.is.implemented.too.many");
}
PsiElementProcessor.CollectElementsWithLimit<PsiMethod> processor = new PsiElementProcessor.CollectElementsWithLimit<>(5);
GlobalSearchScope scope = GlobalSearchScope.allScope(PsiUtilCore.getProjectInReadAction(method));
OverridingMethodsSearch.search(method, scope, true).forEach(new PsiElementProcessorAdapter<>(processor));
boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
if (processor.isOverflow()){
return DaemonBundle.message(isAbstract ? "method.is.implemented.too.many" : "method.is.overridden.too.many");
}
PsiMethod[] overridings = processor.toArray(PsiMethod.EMPTY_ARRAY);
if (overridings.length == 0) {
if (aClass != null && isAbstract && FunctionalExpressionSearch.search(aClass).findFirst() != null) {
return "Has functional implementations";
}
return null;
}
Comparator<PsiMethod> comparator = new MethodCellRenderer(false).getComparator();
Arrays.sort(overridings, comparator);
String start = DaemonBundle.message(isAbstract ? "method.is.implemented.header" : "method.is.overriden.header");
@NonNls String pattern = " <a href=\"#javaClass/{1}\">{1}</a>";
return composeText(overridings, start, pattern, IdeActions.ACTION_GOTO_IMPLEMENTATION);
}
private static void navigateToOverriddenMethod(MouseEvent e, @NotNull final PsiMethod method) {
if (DumbService.isDumb(method.getProject())) {
DumbService.getInstance(method.getProject()).showDumbModeNotification(
"Navigation to overriding classes is not possible during index update");
return;
}
PsiElementProcessor.CollectElementsWithLimit<PsiMethod> collectProcessor = new PsiElementProcessor.CollectElementsWithLimit<>(2, new THashSet<>());
PsiElementProcessor.CollectElementsWithLimit<PsiFunctionalExpression> collectExprProcessor = new PsiElementProcessor.CollectElementsWithLimit<>(2, new THashSet<>());
final boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
GlobalSearchScope scope = GlobalSearchScope.allScope(PsiUtilCore.getProjectInReadAction(method));
OverridingMethodsSearch.search(method, scope,true).forEach(new PsiElementProcessorAdapter<>(collectProcessor));
if (isAbstract && collectProcessor.getCollection().size() < 2) {
final PsiClass aClass = ReadAction.compute(method::getContainingClass);
if (aClass != null) {
FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(collectExprProcessor));
}
}
}, SEARCHING_FOR_OVERRIDING_METHODS, true, method.getProject(), (JComponent)e.getComponent())) {
return;
}
final PsiMethod[] methodOverriders = collectProcessor.toArray(PsiMethod.EMPTY_ARRAY);
final List<NavigatablePsiElement> overridings = new ArrayList<>();
overridings.addAll(collectProcessor.getCollection());
overridings.addAll(collectExprProcessor.getCollection());
if (overridings.isEmpty()) return;
boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature(methodOverriders);
MethodOrFunctionalExpressionCellRenderer renderer = new MethodOrFunctionalExpressionCellRenderer(showMethodNames);
Collections.sort(overridings, renderer.getComparator());
final OverridingMethodsUpdater methodsUpdater = new OverridingMethodsUpdater(method, renderer);
PsiElementListNavigator.openTargets(e, overridings.toArray(new NavigatablePsiElement[0]), methodsUpdater.getCaption(overridings.size()), "Overriding methods of " + method.getName(), renderer, methodsUpdater);
}
private static final String SEARCHING_FOR_OVERRIDDEN_METHODS = "Searching for Overridden Methods";
public static final MarkerType SUBCLASSED_CLASS = new MarkerType("SUBCLASSED_CLASS", (NullableFunction<PsiElement, String>)element -> {
PsiElement parent = element.getParent();
if (!(parent instanceof PsiClass)) return null;
PsiClass aClass = (PsiClass)parent;
return getSubclassedClassTooltip(aClass);
}, new LineMarkerNavigator() {
@Override
public void browse(MouseEvent e, PsiElement element) {
final PsiElement parent = element.getParent();
if (!(parent instanceof PsiClass)) return;
final PsiClass aClass = (PsiClass)parent;
navigateToSubclassedClass(e, aClass);
}
});
// Used in Kotlin, please don't make private
public static String getSubclassedClassTooltip(@NotNull PsiClass aClass) {
PsiElementProcessor.CollectElementsWithLimit<PsiClass> processor = new PsiElementProcessor.CollectElementsWithLimit<>(5,
new THashSet<>());
ClassInheritorsSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(processor));
if (processor.isOverflow()) {
return DaemonBundle.message(aClass.isInterface() ? "interface.is.implemented.too.many" : "class.is.subclassed.too.many");
}
PsiClass[] subclasses = processor.toArray(PsiClass.EMPTY_ARRAY);
if (subclasses.length == 0) {
final PsiElementProcessor.CollectElementsWithLimit<PsiFunctionalExpression> functionalImplementations =
new PsiElementProcessor.CollectElementsWithLimit<>(2, new THashSet<>());
FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(functionalImplementations));
if (!functionalImplementations.getCollection().isEmpty()) {
return "Has functional implementations";
}
return null;
}
Comparator<PsiClass> comparator = new PsiClassListCellRenderer().getComparator();
Arrays.sort(subclasses, comparator);
String start = DaemonBundle.message(aClass.isInterface() ? "interface.is.implemented.by.header" : "class.is.subclassed.by.header");
@NonNls String pattern = " <a href=\"#javaClass/{0}\">{0}</a>";
return composeText(subclasses, start, pattern, IdeActions.ACTION_GOTO_IMPLEMENTATION);
}
// Used in Kotlin, please don't make private
public static void navigateToSubclassedClass(MouseEvent e,
@NotNull final PsiClass aClass) {
navigateToSubclassedClass(e, aClass, new PsiClassOrFunctionalExpressionListCellRenderer());
}
// Used in Kotlin, please don't make private
public static void navigateToSubclassedClass(MouseEvent e,
@NotNull final PsiClass aClass,
PsiElementListCellRenderer<NavigatablePsiElement> renderer) {
if (DumbService.isDumb(aClass.getProject())) {
DumbService.getInstance(aClass.getProject()).showDumbModeNotification("Navigation to overriding methods is not possible during index update");
return;
}
final PsiElementProcessor.FindElement<PsiClass> collectProcessor = new PsiElementProcessor.FindElement<>();
final PsiElementProcessor.FindElement<PsiFunctionalExpression> collectExprProcessor = new PsiElementProcessor.FindElement<>();
if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
ClassInheritorsSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(collectProcessor));
if (collectProcessor.getFoundElement() == null) {
FunctionalExpressionSearch.search(aClass).forEach(new PsiElementProcessorAdapter<>(collectExprProcessor));
}
}, SEARCHING_FOR_OVERRIDDEN_METHODS, true, aClass.getProject(), (JComponent)e.getComponent())) {
return;
}
final List<NavigatablePsiElement> inheritors = new ArrayList<>();
ContainerUtil.addIfNotNull(inheritors, collectProcessor.getFoundElement());
ContainerUtil.addIfNotNull(inheritors, collectExprProcessor.getFoundElement());
if (inheritors.isEmpty()) return;
final SubclassUpdater subclassUpdater = new SubclassUpdater(aClass, renderer);
Collections.sort(inheritors, renderer.getComparator());
PsiElementListNavigator.openTargets(e, inheritors.toArray(new NavigatablePsiElement[0]), subclassUpdater.getCaption(inheritors.size()), CodeInsightBundle.message("goto.implementation.findUsages.title", aClass.getName()), renderer, subclassUpdater);
}
private static class SubclassUpdater extends ListBackgroundUpdaterTask {
private final PsiClass myClass;
private SubclassUpdater(@NotNull PsiClass aClass, @NotNull PsiElementListCellRenderer<NavigatablePsiElement> renderer) {
super(aClass.getProject(), SEARCHING_FOR_OVERRIDDEN_METHODS, createComparatorWrapper((Comparator)renderer.getComparator()));
myClass = aClass;
}
@Override
public String getCaption(int size) {
String suffix = isFinished() ? "" : " so far";
return myClass.isInterface()
? CodeInsightBundle.message("goto.implementation.chooserTitle", myClass.getName(), size, suffix)
: DaemonBundle.message("navigation.title.subclass", myClass.getName(), size, suffix);
}
@Override
public void onSuccess() {
super.onSuccess();
PsiElement oneElement = getTheOnlyOneElement();
if (oneElement instanceof NavigatablePsiElement) {
((NavigatablePsiElement)oneElement).navigate(true);
myPopup.cancel();
}
}
@Override
public void run(@NotNull final ProgressIndicator indicator) {
super.run(indicator);
ClassInheritorsSearch.search(myClass, ApplicationManager.getApplication().runReadAction(new Computable<SearchScope>() {
@Override
public SearchScope compute() {
return myClass.getUseScope();
}
}), true).forEach(new CommonProcessors.CollectProcessor<PsiClass>() {
@Override
public boolean process(final PsiClass o) {
if (!updateComponent(o)) {
indicator.cancel();
}
ProgressManager.checkCanceled();
return super.process(o);
}
});
FunctionalExpressionSearch.search(myClass).forEach(new CommonProcessors.CollectProcessor<PsiFunctionalExpression>() {
@Override
public boolean process(final PsiFunctionalExpression expr) {
if (!updateComponent(expr)) {
indicator.cancel();
}
ProgressManager.checkCanceled();
return super.process(expr);
}
});
}
}
private static class OverridingMethodsUpdater extends ListBackgroundUpdaterTask {
private final PsiMethod myMethod;
private OverridingMethodsUpdater(@NotNull PsiMethod method, @NotNull PsiElementListCellRenderer renderer) {
super(method.getProject(), SEARCHING_FOR_OVERRIDING_METHODS, createComparatorWrapper(renderer.getComparator()));
myMethod = method;
}
@Override
public String getCaption(int size) {
return DaemonBundle.message(myMethod.hasModifierProperty(PsiModifier.ABSTRACT) ?
"navigation.title.implementation.method" :
"navigation.title.overrider.method", myMethod.getName(), size);
}
@Override
public void onSuccess() {
super.onSuccess();
PsiElement oneElement = getTheOnlyOneElement();
if (oneElement instanceof NavigatablePsiElement) {
((NavigatablePsiElement)oneElement).navigate(true);
myPopup.cancel();
}
}
@Override
public void run(@NotNull final ProgressIndicator indicator) {
super.run(indicator);
GlobalSearchScope scope = GlobalSearchScope.allScope(PsiUtilCore.getProjectInReadAction(myMethod));
OverridingMethodsSearch.search(myMethod, scope, true).forEach(
new CommonProcessors.CollectProcessor<PsiMethod>() {
@Override
public boolean process(PsiMethod psiMethod) {
if (!updateComponent(psiMethod)) {
indicator.cancel();
}
ProgressManager.checkCanceled();
return super.process(psiMethod);
}
});
if (ReadAction.compute(() -> myMethod.hasModifierProperty(PsiModifier.ABSTRACT))) {
PsiClass psiClass = ReadAction.compute(myMethod::getContainingClass);
FunctionalExpressionSearch.search(psiClass).forEach(new CommonProcessors.CollectProcessor<PsiFunctionalExpression>() {
@Override
public boolean process(final PsiFunctionalExpression expr) {
if (!updateComponent(expr)) {
indicator.cancel();
}
ProgressManager.checkCanceled();
return super.process(expr);
}
});
}
}
}
}
| {
"content_hash": "f7772369b555a34dabb9075da54b1f81",
"timestamp": "",
"source": "github",
"line_count": 473,
"max_line_length": 252,
"avg_line_length": 48.71247357293869,
"alnum_prop": 0.7106896402065882,
"repo_name": "mglukhikh/intellij-community",
"id": "3607ad6a1dcf0b97a06b9c38ec20cb5d95a89fe9",
"size": "23641",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/java-impl/src/com/intellij/codeInsight/daemon/impl/MarkerType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "20665"
},
{
"name": "AspectJ",
"bytes": "182"
},
{
"name": "Batchfile",
"bytes": "60827"
},
{
"name": "C",
"bytes": "211435"
},
{
"name": "C#",
"bytes": "1264"
},
{
"name": "C++",
"bytes": "197674"
},
{
"name": "CMake",
"bytes": "1675"
},
{
"name": "CSS",
"bytes": "201445"
},
{
"name": "CoffeeScript",
"bytes": "1759"
},
{
"name": "Erlang",
"bytes": "10"
},
{
"name": "Groovy",
"bytes": "3243028"
},
{
"name": "HLSL",
"bytes": "57"
},
{
"name": "HTML",
"bytes": "1899088"
},
{
"name": "J",
"bytes": "5050"
},
{
"name": "Java",
"bytes": "165554704"
},
{
"name": "JavaScript",
"bytes": "570364"
},
{
"name": "Jupyter Notebook",
"bytes": "93222"
},
{
"name": "Kotlin",
"bytes": "4611299"
},
{
"name": "Lex",
"bytes": "147047"
},
{
"name": "Makefile",
"bytes": "2352"
},
{
"name": "NSIS",
"bytes": "51276"
},
{
"name": "Objective-C",
"bytes": "27861"
},
{
"name": "Perl",
"bytes": "903"
},
{
"name": "Perl 6",
"bytes": "26"
},
{
"name": "Protocol Buffer",
"bytes": "6680"
},
{
"name": "Python",
"bytes": "25439881"
},
{
"name": "Roff",
"bytes": "37534"
},
{
"name": "Ruby",
"bytes": "1217"
},
{
"name": "Scala",
"bytes": "11698"
},
{
"name": "Shell",
"bytes": "66341"
},
{
"name": "Smalltalk",
"bytes": "338"
},
{
"name": "TeX",
"bytes": "25473"
},
{
"name": "Thrift",
"bytes": "1846"
},
{
"name": "TypeScript",
"bytes": "9469"
},
{
"name": "Visual Basic",
"bytes": "77"
},
{
"name": "XSLT",
"bytes": "113040"
}
],
"symlink_target": ""
} |
package org.osgi.service.transaction.control;
import org.osgi.annotation.versioning.ProviderType;
/**
* An Exception indicating that there was a problem with starting, finishing,
* suspending or resuming a transaction
*/
@ProviderType
public class TransactionException extends RuntimeException {
/**
* Creates a new TransactionException with the supplied message
*
* @param message
*/
public TransactionException(String message) {
super(message);
}
/**
* Creates a new TransactionException with the supplied message and cause
*
* @param message
* @param cause
*/
public TransactionException(String message, Throwable cause) {
super(message, cause);
}
private static final long serialVersionUID = 5207030182661816993L;
}
| {
"content_hash": "59307bddea5fdce2003e3b4765234dc5",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 77,
"avg_line_length": 22.38235294117647,
"alnum_prop": 0.7503285151116952,
"repo_name": "osgi/osgi",
"id": "e41fc1153791f9b908a140066a743a37704ba786",
"size": "1580",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "org.osgi.service.transaction.control/src/org/osgi/service/transaction/control/TransactionException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "11308"
},
{
"name": "C",
"bytes": "11077"
},
{
"name": "CSS",
"bytes": "63392"
},
{
"name": "HTML",
"bytes": "1425271"
},
{
"name": "Java",
"bytes": "17327563"
},
{
"name": "JavaScript",
"bytes": "684425"
},
{
"name": "Makefile",
"bytes": "8343"
},
{
"name": "NewLisp",
"bytes": "4473"
},
{
"name": "Perl",
"bytes": "7202"
},
{
"name": "Python",
"bytes": "9377"
},
{
"name": "Roff",
"bytes": "64"
},
{
"name": "Ruby",
"bytes": "10888"
},
{
"name": "Shell",
"bytes": "48677"
},
{
"name": "SystemVerilog",
"bytes": "5465"
},
{
"name": "XSLT",
"bytes": "8082406"
}
],
"symlink_target": ""
} |
import React from 'react';
export default function SalesGraph() {
return (
<div className="box box-solid bg-teal-gradient">
<div className="box-header">
<i className="fa fa-th"></i>
<h3 className="box-title">Sales Graph</h3>
<div className="box-tools pull-right">
<button
type="button"
className="btn bg-teal btn-sm"
data-widget="collapse"
>
<i className="fa fa-minus"></i>
</button>
<button
type="button"
className="btn bg-teal btn-sm"
data-widget="remove"
>
<i className="fa fa-times"></i>
</button>
</div>
</div>
<div className="box-body border-radius-none">
<div className="chart" id="line-chart" style={{ height: 250 }}></div>
</div>
<div className="box-footer no-border">
<div className="row">
<div
className="col-xs-4 text-center"
style={{ borderRight: '1px solid #f4f4f4' }}
>
<input
type="text"
className="knob"
data-readonly="true"
value="20"
data-width="60"
data-height="60"
data-fgColor="#39CCCC"
/>
<div className="knob-label">Mail-Orders</div>
</div>
<div
className="col-xs-4 text-center"
style={{ borderRight: '1px solid #f4f4f4' }}
>
<input
type="text"
className="knob"
data-readonly="true"
value="50" data-width="60"
data-height="60"
data-fgColor="#39CCCC"
/>
<div className="knob-label">Online</div>
</div>
<div className="col-xs-4 text-center">
<input
type="text"
className="knob"
data-readonly="true"
value="30"
data-width="60"
data-height="60"
data-fgColor="#39CCCC"
/>
<div className="knob-label">In-Store</div>
</div>
</div>
</div>
</div>
);
}
| {
"content_hash": "95922c02ab1be36fd7515b24c60e6c7d",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 77,
"avg_line_length": 27.765432098765434,
"alnum_prop": 0.45042240995998223,
"repo_name": "ucokfm/admin-lte-react",
"id": "2909e20840383dc2a60ea578eca424ee49999002",
"size": "2249",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/app/containers/widgets/SalesGraph.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "4395"
},
{
"name": "JavaScript",
"bytes": "93505"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Sonata\AdminBundle\Filter;
use Symfony\Component\Form\Extension\Core\Type\TextType;
/**
* @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
*/
abstract class Filter implements FilterInterface
{
/**
* @var string|null
*/
protected $name = null;
/**
* @var mixed|null
*/
protected $value = null;
/**
* @var array
*/
protected $options = [];
/**
* @var string
*/
protected $condition;
public function initialize($name, array $options = []): void
{
$this->name = $name;
$this->setOptions($options);
}
public function getName()
{
return $this->name;
}
public function getFormName()
{
/*
Symfony default form class sadly can't handle
form element with dots in its name (when data
get bound, the default dataMapper is a PropertyPathMapper).
So use this trick to avoid any issue.
*/
return str_replace('.', '__', $this->name);
}
public function getOption($name, $default = null)
{
if (\array_key_exists($name, $this->options)) {
return $this->options[$name];
}
return $default;
}
public function setOption($name, $value): void
{
$this->options[$name] = $value;
}
public function getFieldType()
{
return $this->getOption('field_type', TextType::class);
}
public function getFieldOptions()
{
return $this->getOption('field_options', ['required' => false]);
}
public function getFieldOption($name, $default = null)
{
if (isset($this->options['field_options'][$name]) && \is_array($this->options['field_options'])) {
return $this->options['field_options'][$name];
}
return $default;
}
public function setFieldOption($name, $value): void
{
$this->options['field_options'][$name] = $value;
}
public function getLabel()
{
return $this->getOption('label');
}
public function setLabel($label): void
{
$this->setOption('label', $label);
}
public function getFieldName()
{
$fieldName = $this->getOption('field_name');
if (!$fieldName) {
throw new \RuntimeException(sprintf('The option `field_name` must be set for field: `%s`', $this->getName()));
}
return $fieldName;
}
public function getParentAssociationMappings()
{
return $this->getOption('parent_association_mappings', []);
}
public function getFieldMapping()
{
$fieldMapping = $this->getOption('field_mapping');
if (!$fieldMapping) {
throw new \RuntimeException(sprintf('The option `field_mapping` must be set for field: `%s`', $this->getName()));
}
return $fieldMapping;
}
public function getAssociationMapping()
{
$associationMapping = $this->getOption('association_mapping');
if (!$associationMapping) {
throw new \RuntimeException(sprintf('The option `association_mapping` must be set for field: `%s`', $this->getName()));
}
return $associationMapping;
}
/**
* Set options.
*/
public function setOptions(array $options): void
{
$this->options = array_merge(
['show_filter' => null, 'advanced_filter' => true],
$this->getDefaultOptions(),
$options
);
}
/**
* Get options.
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Set value.
*
* @param mixed $value
*/
public function setValue($value): void
{
$this->value = $value;
}
/**
* Get value.
*
* @return mixed
*/
public function getValue()
{
return $this->value;
}
public function isActive()
{
$values = $this->getValue();
return isset($values['value'])
&& false !== $values['value']
&& '' !== $values['value'];
}
public function setCondition($condition): void
{
$this->condition = $condition;
}
public function getCondition()
{
return $this->condition;
}
public function getTranslationDomain()
{
return $this->getOption('translation_domain');
}
}
| {
"content_hash": "806f48e26c74903ffefdbe623a99754a",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 131,
"avg_line_length": 21.385714285714286,
"alnum_prop": 0.5486528612781117,
"repo_name": "ARTACK/SonataAdminBundle",
"id": "e06a5a78bac8b1ccc8362ba17f005c351fa81b67",
"size": "4738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Filter/Filter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "20777"
},
{
"name": "HTML",
"bytes": "272717"
},
{
"name": "JavaScript",
"bytes": "33309"
},
{
"name": "Makefile",
"bytes": "1651"
},
{
"name": "PHP",
"bytes": "1817557"
},
{
"name": "Shell",
"bytes": "2678"
}
],
"symlink_target": ""
} |
package srebrinb.compress.sevenzip;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class CLI {
private static final byte[] BUF = new byte[8192];
private static enum Mode {
LIST("Analysing") {
@Override
public void takeAction(final SevenZFile archive, final SevenZArchiveEntry entry) {
System.out.print(entry.getName());
if (entry.isDirectory()) {
System.out.print(" dir");
} else {
System.out.print(" " + entry.getCompressedSize()
+ "/" + entry.getSize());
}
if (entry.getHasLastModifiedDate()) {
System.out.print(" " + entry.getLastModifiedDate());
} else {
System.out.print(" no last modified date");
}
if (!entry.isDirectory()) {
System.out.println(" " + getContentMethods(entry));
} else {
System.out.println("");
}
}
private String getContentMethods(final SevenZArchiveEntry entry) {
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (final SevenZMethodConfiguration m : entry.getContentMethods()) {
if (!first) {
sb.append(", ");
}
first = false;
sb.append(m.getMethod());
if (m.getOptions() != null) {
sb.append("(").append(m.getOptions()).append(")");
}
}
return sb.toString();
}
},
EXTRACT("Extracting") {
@Override
public void takeAction(final SevenZFile archive, final SevenZArchiveEntry entry)
throws IOException {
final File outFile = new File(entry.getName());
if (entry.isDirectory()) {
if (!outFile.isDirectory() && !outFile.mkdirs()) {
throw new IOException("Cannot create directory " + outFile);
}
System.out.println("created directory " + outFile);
return;
}
System.out.println("extracting to " + outFile);
final File parent = outFile.getParentFile();
if (parent != null && !parent.exists() && !parent.mkdirs()) {
throw new IOException("Cannot create " + parent);
}
try (final FileOutputStream fos = new FileOutputStream(outFile)) {
final long total = entry.getSize();
long off = 0;
while (off < total) {
final int toRead = (int) Math.min(total - off, BUF.length);
final int bytesRead = archive.read(BUF, 0, toRead);
if (bytesRead < 1) {
throw new IOException("reached end of entry "
+ entry.getName()
+ " after " + off
+ " bytes, expected "
+ total);
}
off += bytesRead;
fos.write(BUF, 0, bytesRead);
}
}
}
};
private final String message;
private Mode(final String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public abstract void takeAction(SevenZFile archive, SevenZArchiveEntry entry)
throws IOException;
}
public static void main(final String[] args) throws Exception {
if (args.length == 0) {
usage();
return;
}
final Mode mode = grabMode(args);
System.out.println(mode.getMessage() + " " + args[0]);
final File f = new File(args[0]);
if (!f.isFile()) {
System.err.println(f + " doesn't exist or is a directory");
}
try (final SevenZFile archive = new SevenZFile(f)) {
SevenZArchiveEntry ae;
while((ae=archive.getNextEntry()) != null) {
mode.takeAction(archive, ae);
}
}
}
private static void usage() {
System.out.println("Parameters: archive-name [list|extract]");
}
private static Mode grabMode(final String[] args) {
if (args.length < 2) {
return Mode.LIST;
}
return Enum.valueOf(Mode.class, args[1].toUpperCase());
}
}
| {
"content_hash": "0ec3c4ce6f7dde553a39ceb27c3bc682",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 94,
"avg_line_length": 37.89230769230769,
"alnum_prop": 0.45594803085667884,
"repo_name": "srebrinb/jSevenZip",
"id": "8e52208913d2491f885a46295d306a6297a80da2",
"size": "5742",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/srebrinb/compress/sevenzip/CLI.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "924"
},
{
"name": "Java",
"bytes": "532695"
}
],
"symlink_target": ""
} |
use super::Timestamp;
use std::os::unix::io::AsRawFd;
pub fn set_creation_time(_file: &File, _time: Timestamp) -> Result<(), ()>{
unimplemented!()
}
pub fn set_last_access_time(_file: &File, _time: Timestamp) -> Result<(), ()> {
unimplemented!()
}
pub fn set_last_modification_time(_file: &File, _time: Timestamp) -> Result<(), ()> {
unimplemented!()
}
| {
"content_hash": "85f0f009f57434636fc7cbd946286563",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 85,
"avg_line_length": 24.6,
"alnum_prop": 0.6178861788617886,
"repo_name": "DarkEld3r/filesystem_time",
"id": "3ee6609a2be508a35a32e6ab6fbfedd1ec233d2e",
"size": "369",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/timestamp/imp/unix.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "13515"
}
],
"symlink_target": ""
} |
title: Perl Profiler
date: 2014-05-11T11:01:20+00:00
layout: post
---
<pre class="brush: bash">cpanm Devel::NYTProf Devel::SizeMe
cpanm Devel::Cover DBI::Profile
perl -d:NYTProf split_chinese_word.pl d.txt m.txt2
nytprofhtml nytprof.out
cd nytprof
open index.html
</pre>
| {
"content_hash": "557beadef3fc0bd4e7fbbd743c169e64",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 59,
"avg_line_length": 22.75,
"alnum_prop": 0.7509157509157509,
"repo_name": "chengang/chengang.github.io",
"id": "d3287954e655e533fe19dacd31b9b284c946640b",
"size": "277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_draft/2014-05-11-perl-profiler.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "467"
}
],
"symlink_target": ""
} |
"""Excel Filelist.
Created 2015 Caleb Ely
<http://CodeTriangle.me/>
Licensed under The MIT License
<http://opensource.org/licenses/MIT/>
"""
import os
from cx_Freeze import (setup, Executable)
# Output folder
destfolder = "bin"
# Create the freeze path if it doesn't exist
if not os.path.exists(destfolder):
os.makedirs(destfolder)
build_exe_options = {
"build_exe": destfolder,
"create_shared_zip": True,
"optimize": 2,
"compressed": True
}
setup(
name="Excel Filelist",
version="1.0.0",
author="Caleb Ely",
description="Excel Filelist v1.0.0",
license="MIT",
options={"build_exe": build_exe_options},
executables=[Executable("main.py", targetName="ExcelFilelist.exe")]
)
| {
"content_hash": "ac9b31eeffee163b89eb4925b415326f",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 71,
"avg_line_length": 18.76923076923077,
"alnum_prop": 0.6734972677595629,
"repo_name": "le717/Excel-Filelist",
"id": "4d360048548ef65274e25a6958ebb8b0d4f577ea",
"size": "780",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Inno Setup",
"bytes": "2721"
},
{
"name": "Python",
"bytes": "6251"
}
],
"symlink_target": ""
} |
using System;
using NUnit.Framework;
using PicklesDoc.Pickles.ObjectModel;
using PicklesDoc.Pickles.TestFrameworks;
using NFluent;
namespace PicklesDoc.Pickles.Test.TestFrameworks
{
[TestFixture]
class WhenParsingCucumberJsonResultsFile : WhenParsingTestResultFiles<CucumberJsonResults>
{
public WhenParsingCucumberJsonResultsFile()
: base("results-example-json.json")
{
}
[Test]
public void ThenCanReadFeatureResultSuccesfully()
{
var results = ParseResultsFile();
var feature = new Feature { Name = "Test Feature" };
TestResult result = results.GetFeatureResult(feature);
Check.That(result.WasExecuted).IsTrue();
Check.That(result.WasSuccessful).IsFalse();
}
[Test]
public void ThenCanReadScenarioResultSuccessfully()
{
var results = ParseResultsFile();
var feature = new Feature { Name = "Test Feature" };
var scenario1 = new Scenario { Name = "Passing", Feature = feature };
TestResult result1 = results.GetScenarioResult(scenario1);
Check.That(result1.WasExecuted).IsTrue();
Check.That(result1.WasSuccessful).IsTrue();
var scenario2 = new Scenario { Name = "Failing", Feature = feature };
TestResult result2 = results.GetScenarioResult(scenario2);
Check.That(result2.WasExecuted).IsTrue();
Check.That(result2.WasSuccessful).IsFalse();
}
[Test]
public void ThenCanReadFeatureWithoutScenariosSuccessfully_ShouldReturnInconclusive()
{
var results = ParseResultsFile();
var feature = new Feature { Name = "Feature Without Scenarios" };
TestResult result = results.GetFeatureResult(feature);
Check.That(result).IsEqualTo(TestResult.Inconclusive);
}
}
}
| {
"content_hash": "69cd14a224da2ec6b3124414e5bc61cb",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 94,
"avg_line_length": 30.88888888888889,
"alnum_prop": 0.6336073997944501,
"repo_name": "irfanah/pickles",
"id": "2e9f6f94b6cb04146ca0a0982ceb682a59af591f",
"size": "1948",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Pickles/Pickles.Test/TestFrameworks/WhenParsingCucumberJsonResultsFile.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2397"
},
{
"name": "C#",
"bytes": "926193"
},
{
"name": "CSS",
"bytes": "20861"
},
{
"name": "Cucumber",
"bytes": "28999"
},
{
"name": "F#",
"bytes": "6547"
},
{
"name": "HTML",
"bytes": "4257280"
},
{
"name": "JavaScript",
"bytes": "274592"
},
{
"name": "PowerShell",
"bytes": "11006"
},
{
"name": "Shell",
"bytes": "1409"
}
],
"symlink_target": ""
} |
package org.sleuthkit.autopsy.contentviewers;
import java.awt.Component;
import java.awt.Cursor;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.stream.Stream;
import javax.swing.SwingWorker;
import org.apache.commons.lang3.StringUtils;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.openide.util.NbBundle.Messages;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.contentviewers.layout.ContentViewerHtmlStyles;
import org.sleuthkit.autopsy.contentviewers.utils.ViewerPriority;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataContentViewer;
import org.sleuthkit.autopsy.coreutils.EscapeUtil;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.TimeZoneUtils;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
import org.sleuthkit.datamodel.DataArtifact;
import org.sleuthkit.datamodel.DataSource;
import org.sleuthkit.datamodel.Image;
import org.sleuthkit.datamodel.FsContent;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData.TSK_DB_FILES_TYPE_ENUM;
/**
* Shows file metadata as a list to make it easy to copy and paste. Typically
* shows the same data that can also be found in the ResultViewer table, just a
* different order and allows the full path to be visible in the bottom area.
*/
@ServiceProvider(service = DataContentViewer.class, position = 4)
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
public class Metadata extends javax.swing.JPanel implements DataContentViewer {
private static final Logger LOGGER = Logger.getLogger(Metadata.class.getName());
private MetaDataWorker worker;
/**
* Creates new form Metadata
*/
public Metadata() {
initComponents();
customizeComponents();
ContentViewerHtmlStyles.setupHtmlJTextPane(jTextPane1);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPopupMenu1 = new javax.swing.JPopupMenu();
jScrollPane2 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setPreferredSize(new java.awt.Dimension(100, 52));
jScrollPane2.setPreferredSize(new java.awt.Dimension(610, 52));
jTextPane1.setEditable(false);
jTextPane1.setPreferredSize(new java.awt.Dimension(600, 52));
jScrollPane2.setViewportView(jTextPane1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration//GEN-END:variables
private void customizeComponents() {
/*
* jTextPane1.setComponentPopupMenu(rightClickMenu); ActionListener
* actList = new ActionListener(){ @Override public void
* actionPerformed(ActionEvent e){ JMenuItem jmi = (JMenuItem)
* e.getSource(); if(jmi.equals(copyMenuItem)) outputViewPane.copy();
* else if(jmi.equals(selectAllMenuItem)) outputViewPane.selectAll(); }
* }; copyMenuItem.addActionListener(actList);
* selectAllMenuItem.addActionListener(actList);
*/
}
private void setText(String str) {
ContentViewerHtmlStyles.setupHtmlJTextPane(jTextPane1);
jTextPane1.setText("<html><head></head><body>" + str + "</body></html>"); //NON-NLS
}
private void addHeader(StringBuilder sb, String header, boolean spaced) {
sb.append(MessageFormat.format("<div class=\"{0}\"><h1 class=\"{1}\">{2}</h1></div>",
(spaced) ? ContentViewerHtmlStyles.getSpacedSectionClassName() : "",
ContentViewerHtmlStyles.getHeaderClassName(),
header));
}
private void startTable(StringBuilder sb) {
sb.append(MessageFormat.format("<table class=\"{0}\" valign=\"top\" align=\"left\"><tbody>",
ContentViewerHtmlStyles.getIndentedClassName())); //NON-NLS
}
private void endTable(StringBuilder sb) {
sb.append("</tbody></table>"); //NON-NLS
}
private void addRow(StringBuilder sb, String key, String value) {
sb.append(MessageFormat.format("<tr><td class=\"{0}\"><span class=\"{1}\">{2}:</span></td><td class=\"{3}\">{4}</td></tr>",
ContentViewerHtmlStyles.getKeyColumnClassName(),
ContentViewerHtmlStyles.getTextClassName(),
EscapeUtil.escapeHtml(key),
ContentViewerHtmlStyles.getTextClassName(),
EscapeUtil.escapeHtml(value)
));
}
private void addMonospacedRow(StringBuilder sb, String key) {
sb.append(MessageFormat.format("<tr><td class=\"{0}\"><span class=\"{1}\">{2}</span></td></tr>",
ContentViewerHtmlStyles.getKeyColumnClassName(),
ContentViewerHtmlStyles.getMonospacedClassName(),
EscapeUtil.escapeHtml(key)
));
}
private void addRowWithMultipleValues(StringBuilder sb, String key, String[] values) {
String[] safeValues = values == null || values.length < 1 ? new String[]{""} : values;
addRow(sb, key, safeValues[0]);
Stream.of(safeValues)
.skip(1)
.filter(line -> line != null)
.forEach(line -> addRow(sb, "", EscapeUtil.escapeHtml(line)));
}
@Messages({
"Metadata.headerTitle=Metadata",
"Metadata.tableRowTitle.mimeType=MIME Type",
"Metadata.nodeText.truncated=(results truncated)",
"Metadata.tableRowTitle.sha1=SHA1",
"Metadata.tableRowTitle.sha256=SHA-256",
"Metadata.tableRowTitle.imageType=Type",
"Metadata.tableRowTitle.sectorSize=Sector Size",
"Metadata.tableRowTitle.timezone=Time Zone",
"Metadata.tableRowTitle.deviceId=Device ID",
"Metadata.tableRowTitle.acquisitionDetails=Acquisition Details",
"Metadata.tableRowTitle.downloadSource=Downloaded From",
"Metadata.nodeText.unknown=Unknown",
"Metadata.nodeText.none=None",
"Metadata.nodeText.loading=Metadata loading..."})
@Override
public void setNode(Node node) {
if (worker != null) {
worker.cancel(true);
worker = null;
}
if (node != null) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
setText(Bundle.Metadata_nodeText_loading());
worker = new MetaDataWorker(node) {
@Override
public void done() {
try {
if (!isCancelled()) {
setText(get());
jTextPane1.setCaretPosition(0);
}
} catch (InterruptedException | ExecutionException ex) {
LOGGER.log(Level.SEVERE, "Failed to get metaData for node " + node.getName(), ex);
}
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
};
worker.execute();
} else {
setText("");
}
}
/**
* Adds a row for download source from the given associated artifact, if the
* associated artifacts specifies a source.
*
* @param sb string builder.
* @param associatedArtifact
*
* @throws TskCoreException if there is an error
*/
private void addDownloadSourceRow(StringBuilder sb, BlackboardArtifact associatedArtifact) throws TskCoreException {
if (associatedArtifact != null
&& ((associatedArtifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_WEB_DOWNLOAD.getTypeID())
|| (associatedArtifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_WEB_CACHE.getTypeID()))) {
BlackboardAttribute urlAttr = associatedArtifact.getAttribute(new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_URL));
if (urlAttr != null) {
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.downloadSource"), urlAttr.getValueString());
}
}
}
/**
* Add the acquisition details to the results (if applicable)
*
* @param sb The output StringBuilder object
* @param dataSource The data source (may be null)
*/
private void addAcquisitionDetails(StringBuilder sb, DataSource dataSource) {
if (dataSource != null) {
try {
String details = dataSource.getAcquisitionDetails();
if (StringUtils.isEmpty(details)) {
details = Bundle.Metadata_nodeText_unknown();
}
String[] lines = (details != null) ? details.split("\n") : new String[]{""};
addRowWithMultipleValues(sb,
NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.acquisitionDetails"),
lines);
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Error reading acquisition details from case database", ex); //NON-NLS
}
}
}
@Override
public String getTitle() {
return getTitle(null);
}
@Messages({
"Metadata_dataArtifactTitle=Source File Metadata"
})
@Override
public String getTitle(Node node) {
if (node != null && !node.getLookup().lookupAll(DataArtifact.class).isEmpty()) {
return Bundle.Metadata_dataArtifactTitle();
} else {
return NbBundle.getMessage(this.getClass(), "Metadata.title");
}
}
@Override
public String getToolTip() {
return NbBundle.getMessage(this.getClass(), "Metadata.toolTip");
}
@Override
public DataContentViewer createInstance() {
return new Metadata();
}
@Override
public Component getComponent() {
return this;
}
@Override
public void resetComponent() {
setText("");
}
@Override
public boolean isSupported(Node node) {
Image image = node.getLookup().lookup(Image.class);
AbstractFile file = node.getLookup().lookup(AbstractFile.class);
return (file != null) || (image != null);
}
@Override
public int isPreferred(Node node) {
return ViewerPriority.viewerPriority.LevelOne.getFlag();
}
/**
* SwingWorker for gathering the file metadata.
*/
private class MetaDataWorker extends SwingWorker<String, Void> {
private final Node node;
MetaDataWorker(Node node) {
this.node = node;
}
@Messages("MetadataWorker.doInBackground.noDataMsg=No Data")
@Override
protected String doInBackground() throws Exception {
AbstractFile file = node.getLookup().lookup(AbstractFile.class);
Image image = node.getLookup().lookup(Image.class);
DataSource dataSource = node.getLookup().lookup(DataSource.class);
if (file == null && image == null) {
return NbBundle.getMessage(this.getClass(), "Metadata.nodeText.nonFilePassedIn");
}
StringBuilder sb = new StringBuilder();
addHeader(sb, Bundle.Metadata_headerTitle(), false);
startTable(sb);
if (file != null) {
try {
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.name"), file.getUniquePath());
} catch (TskCoreException ex) {
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.name"), file.getParentPath() + "/" + file.getName());
}
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.type"), file.getType().getName());
addRow(sb, Bundle.Metadata_tableRowTitle_mimeType(), file.getMIMEType());
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.size"), Long.toString(file.getSize()));
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.fileNameAlloc"), file.getDirFlagAsString());
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.metadataAlloc"), file.getMetaFlagsAsString());
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.modified"), TimeZoneUtils.getFormattedTime(file.getMtime()));
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.accessed"), TimeZoneUtils.getFormattedTime(file.getAtime()));
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.created"), TimeZoneUtils.getFormattedTime(file.getCrtime()));
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.changed"), TimeZoneUtils.getFormattedTime(file.getCtime()));
String md5 = file.getMd5Hash();
if (md5 == null) {
md5 = NbBundle.getMessage(this.getClass(), "Metadata.tableRowContent.md5notCalc");
}
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.md5"), md5);
String sha256 = file.getSha256Hash();
if (sha256 == null) {
sha256 = NbBundle.getMessage(this.getClass(), "Metadata.tableRowContent.md5notCalc");
}
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.sha256"), sha256);
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.hashLookupResults"), file.getKnown().toString());
addAcquisitionDetails(sb, dataSource);
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.internalid"), Long.toString(file.getId()));
if (file.getType().compareTo(TSK_DB_FILES_TYPE_ENUM.LOCAL) == 0) {
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.localPath"), file.getLocalAbsPath());
}
try {
List<BlackboardArtifact> associatedObjectArtifacts = file.getArtifacts(ARTIFACT_TYPE.TSK_ASSOCIATED_OBJECT);
if (!associatedObjectArtifacts.isEmpty()) {
BlackboardArtifact artifact = associatedObjectArtifacts.get(0);
BlackboardAttribute associatedArtifactAttribute = artifact.getAttribute(new BlackboardAttribute.Type(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT));
if (associatedArtifactAttribute != null) {
long artifactId = associatedArtifactAttribute.getValueLong();
BlackboardArtifact associatedArtifact = artifact.getSleuthkitCase().getBlackboardArtifact(artifactId);
addDownloadSourceRow(sb, associatedArtifact);
}
}
} catch (TskCoreException ex) {
sb.append(NbBundle.getMessage(this.getClass(), "Metadata.nodeText.exceptionNotice.text")).append(ex.getLocalizedMessage());
}
endTable(sb);
/*
* If we have a file system file, grab the more detailed
* metadata text too
*/
if (file instanceof FsContent) {
FsContent fsFile = (FsContent) file;
addHeader(sb, NbBundle.getMessage(this.getClass(), "Metadata.nodeText.text"), true);
List<String> istatStrings = Collections.emptyList();
try {
istatStrings = fsFile.getMetaDataText();
} catch (TskCoreException ex) {
istatStrings = Arrays.asList(NbBundle.getMessage(this.getClass(), "Metadata.nodeText.exceptionNotice.text") + ex.getLocalizedMessage());
}
if (istatStrings.isEmpty() || (istatStrings.size() == 1 && StringUtils.isEmpty(istatStrings.get(0)))) {
sb.append(MessageFormat.format("<div class=\"{0}\"><p class=\"{1}\">{2}</p><div>",
ContentViewerHtmlStyles.getIndentedClassName(),
ContentViewerHtmlStyles.getTextClassName(),
Bundle.MetadataWorker_doInBackground_noDataMsg()));
} else {
startTable(sb);
for (String str : istatStrings) {
addMonospacedRow(sb, str);
/*
* Very long results can cause the UI to hang before
* displaying, so truncate the results if necessary.
*/
if (sb.length() > 50000) {
addMonospacedRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.nodeText.truncated"));
break;
}
}
endTable(sb);
}
}
} else {
try {
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.name"), image.getUniquePath());
} catch (TskCoreException ex) {
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.name"), image.getName());
}
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.imageType"), image.getType().getName());
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.size"), Long.toString(image.getSize()));
try {
String md5 = image.getMd5();
if (md5 == null || md5.isEmpty()) {
md5 = NbBundle.getMessage(this.getClass(), "Metadata.tableRowContent.md5notCalc");
}
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.md5"), md5);
String sha1 = image.getSha1();
if (sha1 == null || sha1.isEmpty()) {
sha1 = NbBundle.getMessage(this.getClass(), "Metadata.tableRowContent.md5notCalc");
}
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.sha1"), sha1);
String sha256 = image.getSha256();
if (sha256 == null || sha256.isEmpty()) {
sha256 = NbBundle.getMessage(this.getClass(), "Metadata.tableRowContent.md5notCalc");
}
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.sha256"), sha256);
} catch (TskCoreException ex) {
sb.append(NbBundle.getMessage(this.getClass(), "Metadata.nodeText.exceptionNotice.text")).append(ex.getLocalizedMessage());
}
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.sectorSize"), Long.toString(image.getSsize()));
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.timezone"), image.getTimeZone());
addAcquisitionDetails(sb, dataSource);
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.deviceId"), image.getDeviceId());
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.internalid"), Long.toString(image.getId()));
// Add all the data source paths to the "Local Path" value cell.
String[] imagePaths = image.getPaths();
if (imagePaths.length > 0) {
addRowWithMultipleValues(sb,
NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.localPath"),
imagePaths);
} else {
addRow(sb, NbBundle.getMessage(this.getClass(), "Metadata.tableRowTitle.localPath"),
NbBundle.getMessage(this.getClass(), "Metadata.nodeText.none"));
}
endTable(sb);
}
if (isCancelled()) {
return "";
}
return sb.toString();
}
}
}
| {
"content_hash": "804449ad4e93faaece43d13ad392e549",
"timestamp": "",
"source": "github",
"line_count": 476,
"max_line_length": 186,
"avg_line_length": 45.96008403361345,
"alnum_prop": 0.6077158659779678,
"repo_name": "rcordovano/autopsy",
"id": "7087d86c926a455cbc5f66756543bbdcbf5edff7",
"size": "22563",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "Core/src/org/sleuthkit/autopsy/contentviewers/Metadata.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "578"
},
{
"name": "AutoIt",
"bytes": "27605"
},
{
"name": "Batchfile",
"bytes": "171962"
},
{
"name": "CSS",
"bytes": "193577"
},
{
"name": "HTML",
"bytes": "272271"
},
{
"name": "Java",
"bytes": "18367663"
},
{
"name": "JavaScript",
"bytes": "4412"
},
{
"name": "Perl",
"bytes": "12676"
},
{
"name": "Python",
"bytes": "765412"
},
{
"name": "Shell",
"bytes": "235268"
}
],
"symlink_target": ""
} |
package com.kotcrab.vis.editor.ui.scene.entityproperties.specifictable;
import com.artemis.Entity;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.utils.Array;
import com.kotcrab.vis.editor.proxy.EntityProxy;
import com.kotcrab.vis.editor.ui.scene.entityproperties.IndeterminateCheckbox;
import com.kotcrab.vis.editor.util.gdx.TableBuilder;
import com.kotcrab.vis.editor.util.vis.EntityUtils;
import com.kotcrab.vis.runtime.assets.PathAsset;
import com.kotcrab.vis.runtime.component.AssetComponent;
import com.kotcrab.vis.runtime.component.MusicComponent;
import com.kotcrab.vis.ui.widget.VisLabel;
import static com.kotcrab.vis.editor.util.vis.EntityUtils.setCommonCheckBoxState;
/**
* Specific table for MusicComponent
*/
public class MusicUITable extends SpecificUITable {
private VisLabel label;
private IndeterminateCheckbox loopingCheck;
private IndeterminateCheckbox playOnStartCheck;
@Override
protected void init () {
loopingCheck = new IndeterminateCheckbox("Loop");
playOnStartCheck = new IndeterminateCheckbox("Play on start");
loopingCheck.addListener(properties.getSharedCheckBoxChangeListener());
playOnStartCheck.addListener(properties.getSharedCheckBoxChangeListener());
label = new VisLabel();
label.setColor(Color.GRAY);
left();
defaults().left();
add(new VisLabel("Music:"));
add(label).width(240).row();
add(TableBuilder.build(loopingCheck, playOnStartCheck)).colspan(2);
}
@Override
public boolean isSupported (EntityProxy entity) {
return entity.hasComponent(MusicComponent.class);
}
@Override
public void updateUIValues () {
Array<EntityProxy> proxies = properties.getProxies();
label.setText(EntityUtils.getCommonString(proxies, "<?>", (Entity entity) -> {
return ((PathAsset) entity.getComponent(AssetComponent.class).asset).getPath();
}));
setCommonCheckBoxState(proxies, loopingCheck, (Entity entity) -> entity.getComponent(MusicComponent.class).isLooping());
setCommonCheckBoxState(proxies, playOnStartCheck, (Entity entity) -> entity.getComponent(MusicComponent.class).isPlayOnStart());
}
@Override
public void setValuesToEntities () {
for (EntityProxy proxy : properties.getProxies()) {
for (Entity entity : proxy.getEntities()) {
MusicComponent music = entity.getComponent(MusicComponent.class);
if (loopingCheck.isIndeterminate() == false) music.setLooping(loopingCheck.isChecked());
if (playOnStartCheck.isIndeterminate() == false) music.setPlayOnStart(playOnStartCheck.isChecked());
}
}
}
}
| {
"content_hash": "a9e476d721f908df68ea2d55b3669b41",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 130,
"avg_line_length": 35.166666666666664,
"alnum_prop": 0.7792259083728278,
"repo_name": "billy1380/VisEditor",
"id": "f7f8bf3dd859722573217426d1dde96a3f0f67d6",
"size": "3133",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Editor/src/com/kotcrab/vis/editor/ui/scene/entityproperties/specifictable/MusicUITable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "672251"
}
],
"symlink_target": ""
} |
package de.fau.cs.mad.yasme.android;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
/**
* Created by robert on 03.10.14.
*/
public class EditTextWithImage {
private EditText et;
private ImageView iv;
private Drawable button;
public EditTextWithImage(final Context context) {
et = new EditText(context);
iv = new ImageView(context);
iv.setVisibility(View.GONE);
button = context.getResources().getDrawable(R.drawable.ic_action_camera);
button.setBounds(0, 0, button.getIntrinsicWidth(), button.getIntrinsicHeight());
et.setCompoundDrawables(null, null, button, null);
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
et.setCompoundDrawables(null, null, button, null);
}
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
public ImageView getImageView() {
return iv;
}
public int getIntrinsicWidth() {
return button.getIntrinsicWidth();
}
public EditText getEditText() {
return et;
}
}
| {
"content_hash": "4e790a40b1f7ef1ecf925ab8a4746709",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 92,
"avg_line_length": 27.25,
"alnum_prop": 0.6461336828309305,
"repo_name": "FAU-Inf2/yasme-android",
"id": "b523b68e11db2a5f3875f4761e23989822900430",
"size": "1526",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yasme/src/main/java/de/fau/cs/mad/yasme/android/EditTextWithImage.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "5163"
},
{
"name": "Java",
"bytes": "559176"
}
],
"symlink_target": ""
} |
FROM balenalib/nuc-debian:buster-run
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu57 \
liblttng-ust0 \
libssl1.0.2 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
# Configure web servers to bind to port 80 when present
ENV ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core
ENV ASPNETCORE_VERSION 2.1.19
RUN curl -SL --output aspnetcore.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/aspnetcore/Runtime/$ASPNETCORE_VERSION/aspnetcore-runtime-$ASPNETCORE_VERSION-linux-x64.tar.gz" \
&& aspnetcore_sha512='4ca81b0dc1efcb8562a07f658461ce5caf976c93942af7549053f4f5c3da232964989fee2ea42537c1086b244950d8e6a1230d3486317af5108d203036c4bc0c' \
&& echo "$aspnetcore_sha512 aspnetcore.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf aspnetcore.tar.gz -C /usr/share/dotnet \
&& rm aspnetcore.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@dotnet.sh" \
&& echo "Running test-stack@dotnet" \
&& chmod +x test-stack@dotnet.sh \
&& bash test-stack@dotnet.sh \
&& rm -rf test-stack@dotnet.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Debian Buster \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 2.1-aspnet \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "7c7865c9e3ffe3a80482c2ff24313d3d",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 694,
"avg_line_length": 53.895833333333336,
"alnum_prop": 0.7039041360649401,
"repo_name": "nghiant2710/base-images",
"id": "f08cc74a3659ae2375c7e9a0ed430d6d2f324344",
"size": "2608",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/dotnet/nuc/debian/buster/2.1-aspnet/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
TEMPLATE_EXTENSIONS = [
".html",
".htm",
]
PYTHON_SOURCE_EXTENSIONS = [
".py",
]
TEMPLATE_ENCODING = "UTF-8"
PYTHON_ENCODING = "UTF-8"
# Method
# ======
# Find templates:
# - template dirs
# - installed apps
#
# Search for POST forms
# - Work out what the name of the template is, as it would appear in an
# 'include' or get_template() call. This can be done by comparing template
# filename to all template dirs. Some templates can have more than one
# 'name' e.g. if a directory and one of its child directories are both in
# TEMPLATE_DIRS. This is actually a common hack used for
# overriding-and-extending admin templates.
#
# For each POST form,
# - see if it already contains '{% csrf_token %}' immediately after <form>
# - work back to the view function(s):
# - First, see if the form is included in any other templates, then
# recursively compile a list of affected templates.
# - Find any code function that references that template. This is just a
# brute force text search that can easily return false positives
# and fail to find real instances.
import os
import sys
import re
from optparse import OptionParser
USAGE = """
This tool helps to locate forms that need CSRF tokens added and the
corresponding view code. This processing is NOT fool proof, and you should read
the help contained in the script itself. Also, this script may need configuring
(by editing the script) before use.
Usage:
python csrf_migration_helper.py [--settings=path.to.your.settings] /path/to/python/code [more paths...]
Paths can be specified as relative paths.
With no arguments, this help is printed.
"""
_POST_FORM_RE = \
re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
_FORM_CLOSE_RE = re.compile(r'</form\s*>')
_TOKEN_RE = re.compile('\{% csrf_token')
def get_template_dirs():
"""
Returns a set of all directories that contain project templates.
"""
from django.conf import settings
dirs = set()
if ('django.template.loaders.filesystem.load_template_source' in settings.TEMPLATE_LOADERS
or 'django.template.loaders.filesystem.Loader' in settings.TEMPLATE_LOADERS):
dirs.update(map(unicode, settings.TEMPLATE_DIRS))
if ('django.template.loaders.app_directories.load_template_source' in settings.TEMPLATE_LOADERS
or 'django.template.loaders.app_directories.Loader' in settings.TEMPLATE_LOADERS):
from django.template.loaders.app_directories import app_template_dirs
dirs.update(app_template_dirs)
return dirs
def make_template_info(filename, root_dirs):
"""
Creates a Template object for a filename, calculating the possible
relative_filenames from the supplied filename and root template directories
"""
return Template(filename,
[filename[len(d)+1:] for d in root_dirs if filename.startswith(d)])
class Template(object):
def __init__(self, absolute_filename, relative_filenames):
self.absolute_filename, self.relative_filenames = absolute_filename, relative_filenames
def content(self):
try:
return self._content
except AttributeError:
fd = open(self.absolute_filename)
try:
content = fd.read().decode(TEMPLATE_ENCODING)
except UnicodeDecodeError as e:
message = '%s in %s' % (
e[4], self.absolute_filename.encode('UTF-8', 'ignore'))
raise UnicodeDecodeError(*(e.args[:4] + (message,)))
fd.close()
self._content = content
return content
content = property(content)
def post_form_info(self):
"""
Get information about any POST forms in the template.
Returns [(linenumber, csrf_token added)]
"""
forms = {}
form_line = 0
for ln, line in enumerate(self.content.split("\n")):
if not form_line and _POST_FORM_RE.search(line):
# record the form with no CSRF token yet
form_line = ln + 1
forms[form_line] = False
if form_line and _TOKEN_RE.search(line):
# found the CSRF token
forms[form_line] = True
form_line = 0
if form_line and _FORM_CLOSE_RE.search(line):
# no token found by form closing tag
form_line = 0
return forms.items()
def includes_template(self, t):
"""
Returns true if this template includes template 't' (via {% include %})
"""
for r in t.relative_filenames:
if re.search(r'\{%\s*include\s+(\'|")' + re.escape(r) + r'(\1)\s*%\}', self.content):
return True
return False
def related_templates(self):
"""
Returns all templates that include this one, recursively. (starting
with this one)
"""
try:
return self._related_templates
except AttributeError:
pass
retval = set([self])
for t in self.all_templates:
if t.includes_template(self):
# If two templates mutually include each other, directly or
# indirectly, we have a problem here...
retval = retval.union(t.related_templates())
self._related_templates = retval
return retval
def __repr__(self):
return repr(self.absolute_filename)
def __eq__(self, other):
return self.absolute_filename == other.absolute_filename
def __hash__(self):
return hash(self.absolute_filename)
def get_templates(dirs):
"""
Returns all files in dirs that have template extensions, as Template
objects.
"""
templates = set()
for root in dirs:
for (dirpath, dirnames, filenames) in os.walk(root):
for f in filenames:
if len([True for e in TEMPLATE_EXTENSIONS if f.endswith(e)]) > 0:
t = make_template_info(os.path.join(dirpath, f), dirs)
# templates need to be able to search others:
t.all_templates = templates
templates.add(t)
return templates
def get_python_code(paths):
"""
Returns all Python code, as a list of tuples, each one being:
(filename, list of lines)
"""
retval = []
for p in paths:
if not os.path.isdir(p):
raise Exception("'%s' is not a directory." % p)
for (dirpath, dirnames, filenames) in os.walk(p):
for f in filenames:
if len([True for e in PYTHON_SOURCE_EXTENSIONS if f.endswith(e)]) > 0:
fn = os.path.join(dirpath, f)
fd = open(fn)
content = [l.decode(PYTHON_ENCODING) for l in fd.readlines()]
fd.close()
retval.append((fn, content))
return retval
def search_python_list(python_code, template_names):
"""
Searches python code for a list of template names.
Returns a list of tuples, each one being:
(filename, line number)
"""
retval = []
for tn in template_names:
retval.extend(search_python(python_code, tn))
retval = list(set(retval))
retval.sort()
return retval
def search_python(python_code, template_name):
"""
Searches Python code for a template name.
Returns a list of tuples, each one being:
(filename, line number)
"""
retval = []
for fn, content in python_code:
for ln, line in enumerate(content):
if ((u'"%s"' % template_name) in line) or \
((u"'%s'" % template_name) in line):
retval.append((fn, ln + 1))
return retval
def main(pythonpaths):
template_dirs = get_template_dirs()
templates = get_templates(template_dirs)
python_code = get_python_code(pythonpaths)
for t in templates:
# Logic
form_matches = t.post_form_info()
num_post_forms = len(form_matches)
form_lines_without_token = [ln for (ln, has_token) in form_matches if not has_token]
if num_post_forms == 0:
continue
to_search = [rf for rt in t.related_templates() for rf in rt.relative_filenames]
found = search_python_list(python_code, to_search)
# Display:
print t.absolute_filename
for r in t.relative_filenames:
print u" AKA %s" % r
print u" POST forms: %s" % num_post_forms
print u" With token: %s" % (num_post_forms - len(form_lines_without_token))
if form_lines_without_token:
print u" Without token:"
for ln in form_lines_without_token:
print "%s:%d:" % (t.absolute_filename, ln)
print
print u" Searching for:"
for r in to_search:
print u" " + r
print
print u" Found:"
if len(found) == 0:
print " Nothing"
else:
for fn, ln in found:
print "%s:%d:" % (fn, ln)
print
print "----"
parser = OptionParser(usage=USAGE)
parser.add_option("", "--settings", action="store", dest="settings", help="Dotted path to settings file")
if __name__ == '__main__':
options, args = parser.parse_args()
if len(args) == 0:
parser.print_help()
sys.exit(1)
settings = getattr(options, 'settings', None)
if settings is None:
if os.environ.get("DJANGO_SETTINGS_MODULE", None) is None:
print "You need to set DJANGO_SETTINGS_MODULE or use the '--settings' parameter"
sys.exit(1)
else:
os.environ["DJANGO_SETTINGS_MODULE"] = settings
main(args)
| {
"content_hash": "bd89d46d433a94941f52dc8dd4aa8599",
"timestamp": "",
"source": "github",
"line_count": 288,
"max_line_length": 105,
"avg_line_length": 33.920138888888886,
"alnum_prop": 0.5963762923533626,
"repo_name": "leereilly/django-1",
"id": "0e13163b4f7e82f208c7e591cba0bbe0e7020a18",
"size": "13031",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "extras/csrf_migration_helper.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "89027"
},
{
"name": "Python",
"bytes": "8027127"
},
{
"name": "Shell",
"bytes": "4234"
}
],
"symlink_target": ""
} |
<?xml version='1.0' encoding='UTF-8'?>
<project>
<actions/>
<description>Spring boot sample</description>
<keepDependencies>false</keepDependencies>
<properties>
<com.nirima.jenkins.plugins.docker.DockerJobProperty plugin="docker-plugin@0.10.0">
<tagOnCompletion>false</tagOnCompletion>
<additionalTag></additionalTag>
<pushOnSuccess>false</pushOnSuccess>
<cleanImages>true</cleanImages>
</com.nirima.jenkins.plugins.docker.DockerJobProperty>
<hudson.plugins.disk__usage.DiskUsageProperty plugin="disk-usage@0.25"/>
</properties>
<scm class="hudson.plugins.git.GitSCM" plugin="git@2.3.5">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<url>https://github.com/ThibautGery/spring-boot-sample.git</url>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches>
<hudson.plugins.git.BranchSpec>
<name>*/master</name>
</hudson.plugins.git.BranchSpec>
</branches>
<doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
<submoduleCfg class="list"/>
<extensions/>
</scm>
<assignedNode>mvn</assignedNode>
<canRoam>false</canRoam>
<disabled>false</disabled>
<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
<triggers>
<hudson.triggers.SCMTrigger>
<spec>* * * * *</spec>
<ignorePostCommitHooks>false</ignorePostCommitHooks>
</hudson.triggers.SCMTrigger>
</triggers>
<concurrentBuild>false</concurrentBuild>
<builders>
<hudson.tasks.Shell>
<command>mvn clean test</command>
</hudson.tasks.Shell>
</builders>
<publishers>
<hudson.tasks.BuildTrigger>
<childProjects>PUBLISH-spring-boot-sample</childProjects>
<threshold>
<name>SUCCESS</name>
<ordinal>0</ordinal>
<color>BLUE</color>
<completeBuild>true</completeBuild>
</threshold>
</hudson.tasks.BuildTrigger>
</publishers>
<buildWrappers/>
</project>
| {
"content_hash": "1e1ce2d36ae26c1b5a4053dae883afa0",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 87,
"avg_line_length": 35.083333333333336,
"alnum_prop": 0.7040380047505939,
"repo_name": "ThibautGery/software-factory",
"id": "c7702d5304b6859e3c359fb69e2167f53d72dd58",
"size": "2105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jenkins/jobs/BUILD-spring-boot-sample/config.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Shell",
"bytes": "7536"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>coinduction: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.0 / coinduction - 1.4</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
coinduction
<small>
1.4
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-23 11:02:22 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-23 11:02:22 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.5.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.04.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.04.2 Official 4.04.2 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "damien.pous@ens-lyon.fr"
homepage: "https://github.com/damien-pous/coinduction"
dev-repo: "git+https://github.com/damien-pous/coinduction.git"
bug-reports: "https://github.com/damien-pous/coinduction/issues"
license: "LGPL-3.0-or-later"
synopsis: "A library and plugin for doing proofs by (enhanced) coinduction"
description: """
Coinductive predicates are greatest fixpoints of monotone functions.
The `companion' makes it possible to enhance the associated coinduction scheme.
This library provides a formalisation on enhancements based on the companion, as well as tactics in making it straightforward to perform proofs by enhanced coinduction.
"""
build: [
[make "-j%{jobs}%" ]
]
install: [make "install"]
depends: [
"ocaml"
"coq" {>= "8.14" & < "8.15~"}
]
tags: [
"keyword:coinduction"
"keyword:up to techniques"
"keyword:companion"
"logpath:Coinduction"
]
authors: [
"Damien Pous"
]
url {
src:
"https://github.com/damien-pous/coinduction/archive/v1.4.tar.gz"
checksum: "sha512=6c82abfc6db1d0d51473d298037681cdae3e2a3a8090e00ad124f517314ca209ba3109fb853487de0f8b6511b293b940c8292e12124072131864b368c387fcb6"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-coinduction.1.4 coq.8.5.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.0).
The following dependencies couldn't be met:
- coq-coinduction -> coq >= 8.14 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-coinduction.1.4</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "41dae0f8bfd6476cfe0041ad2e76ffaf",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 168,
"avg_line_length": 40.810344827586206,
"alnum_prop": 0.5525982256020279,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "f64e7cbe2d0a9b9c6a786a8e10aafe8d37f36934",
"size": "7126",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.5.0/coinduction/1.4.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.