The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code: DatasetGenerationError
Exception: TypeError
Message: Couldn't cast array of type
struct<content_hash: string, timestamp: string, source: string, line_count: int64, max_line_length: int64, avg_line_length: double, alnum_prop: double, repo_name: string, id: string, size: string, binary: bool, copies: string, ref: string, path: string, mode: string, license: string, language: list<item: struct<name: string, bytes: string>>, symlink_target: string>
to
{'content_hash': Value(dtype='string', id=None), 'timestamp': Value(dtype='string', id=None), 'source': Value(dtype='string', id=None), 'line_count': Value(dtype='int64', id=None), 'max_line_length': Value(dtype='int64', id=None), 'avg_line_length': Value(dtype='float64', id=None), 'alnum_prop': Value(dtype='float64', id=None), 'repo_name': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'size': Value(dtype='string', id=None), 'binary': Value(dtype='bool', id=None), 'copies': Value(dtype='string', id=None), 'ref': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'mode': Value(dtype='string', id=None), 'license': Value(dtype='string', id=None), 'language': [{'name': Value(dtype='string', id=None), 'bytes': Value(dtype='string', id=None)}]}
Traceback: Traceback (most recent call last):
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2011, in _prepare_split_single
writer.write_table(table)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 585, in write_table
pa_table = table_cast(pa_table, self._schema)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast
return cast_table_to_schema(table, schema)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2261, in cast_table_to_schema
arrays = [cast_array_to_feature(table[name], feature) for name, feature in features.items()]
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2261, in <listcomp>
arrays = [cast_array_to_feature(table[name], feature) for name, feature in features.items()]
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1802, in wrapper
return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1802, in <listcomp>
return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2122, in cast_array_to_feature
raise TypeError(f"Couldn't cast array of type\n{_short_str(array.type)}\nto\n{_short_str(feature)}")
TypeError: Couldn't cast array of type
struct<content_hash: string, timestamp: string, source: string, line_count: int64, max_line_length: int64, avg_line_length: double, alnum_prop: double, repo_name: string, id: string, size: string, binary: bool, copies: string, ref: string, path: string, mode: string, license: string, language: list<item: struct<name: string, bytes: string>>, symlink_target: string>
to
{'content_hash': Value(dtype='string', id=None), 'timestamp': Value(dtype='string', id=None), 'source': Value(dtype='string', id=None), 'line_count': Value(dtype='int64', id=None), 'max_line_length': Value(dtype='int64', id=None), 'avg_line_length': Value(dtype='float64', id=None), 'alnum_prop': Value(dtype='float64', id=None), 'repo_name': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'size': Value(dtype='string', id=None), 'binary': Value(dtype='bool', id=None), 'copies': Value(dtype='string', id=None), 'ref': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'mode': Value(dtype='string', id=None), 'license': Value(dtype='string', id=None), 'language': [{'name': Value(dtype='string', id=None), 'bytes': Value(dtype='string', id=None)}]}
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
parquet_operations = convert_to_parquet(builder)
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
builder.download_and_prepare(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
self._download_and_prepare(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
self._prepare_split(split_generator, **prepare_split_kwargs)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
for job_id, done, content in self._prepare_split_single(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
raise DatasetGenerationError("An error occurred while generating the dataset") from e
datasets.exceptions.DatasetGenerationError: An error occurred while generating the datasetNeed help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
text
string | meta
dict |
|---|---|
using namespace cocos2d;
class TestObject : public Ref
{
public:
TestObject() : _name(""){}
TestObject(std::string name) : _name(name)
{
CCLOG("TestObject:%s is created", _name.c_str());
}
~TestObject()
{
if (_name.size() > 0)
CCLOG("TestObject:%s is destroyed", _name.c_str());
}
private:
std::string _name;
};
void ReleasePoolTestScene::runThisTest()
{
// title
auto label = Label::createWithTTF("AutoreasePool Test", "fonts/arial.ttf", 32);
addChild(label, 9999);
label->setPosition(Vec2(VisibleRect::center().x, VisibleRect::top().y - 30));
// reference count should be added when added into auto release pool
TestObject *obj = new TestObject("testobj");
obj->autorelease();
assert(obj->getReferenceCount() == 1);
// should retain first before invoking autorelease
obj->retain();
obj->autorelease();
assert(obj->getReferenceCount() == 2);
// create an autorelease pool in stack
{
AutoreleasePool pool1;
// can invoke autorelease more than once
obj->retain();
obj->autorelease();
assert(obj->getReferenceCount() == 3);
obj->retain();
obj->autorelease();
assert(obj->getReferenceCount() == 4);
// retain, release can work together with autorelease pool
obj->retain();
assert(obj->getReferenceCount() == 5);
obj->release();
assert(obj->getReferenceCount() == 4);
}
assert(obj->getReferenceCount() == 2);
// example of using temple autorelease pool
{
AutoreleasePool pool2;
char name[20];
for (int i = 0; i < 100; ++i)
{
snprintf(name, 20, "object%d", i);
TestObject *tmpObj = new TestObject(name);
tmpObj->autorelease();
}
}
// object in pool2 should be released
{
new AutoreleasePool;
PoolManager::destroyInstance();
}
Director::getInstance()->replaceScene(this);
}
|
{
"content_hash": "bc9e32ee02d4a599ba20d360b3d20dc4",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 83,
"avg_line_length": 25.265060240963855,
"alnum_prop": 0.5646161182641869,
"repo_name": "Jennal/cocos2dx-3.2-qt",
"id": "70e54dbc49b85888cb7229a40e6e0d77be752ee9",
"size": "2127",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/cpp-tests/Classes/ReleasePoolTest/ReleasePoolTest.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2395"
},
{
"name": "C",
"bytes": "1510543"
},
{
"name": "C#",
"bytes": "65894"
},
{
"name": "C++",
"bytes": "16649926"
},
{
"name": "CMake",
"bytes": "58041"
},
{
"name": "GLSL",
"bytes": "35375"
},
{
"name": "Java",
"bytes": "554280"
},
{
"name": "JavaScript",
"bytes": "6893"
},
{
"name": "Lua",
"bytes": "2302895"
},
{
"name": "Makefile",
"bytes": "45805"
},
{
"name": "Objective-C",
"bytes": "932927"
},
{
"name": "Objective-C++",
"bytes": "366395"
},
{
"name": "PowerShell",
"bytes": "18747"
},
{
"name": "Python",
"bytes": "75051"
},
{
"name": "Shell",
"bytes": "32584"
}
]
}
|
Maza Core
=============
Setup
---------------------
Maza Core is the original Maza client and it builds the backbone of the network. It downloads and, by default, stores the entire history of Maza transactions (which is currently more than 7 GBs); depending on the speed of your computer and network connection, the synchronization process can take anywhere from a few hours to a day or more.
To download Maza Core, visit [mazacoin.org](https://mazacoin.org).
Running
---------------------
The following are some helpful notes on how to run Maza on your native platform.
### Unix
Unpack the files into a directory and run:
- `bin/maza-qt` (GUI) or
- `bin/mazad` (headless)
### Windows
Unpack the files into a directory, and then run maza-qt.exe.
### OS X
Drag Maza-Core to your applications folder, and then run Maza-Core.
### Need Help?
* See the documentation at the [Maza homepage](https://mazacoin.org/)
for help and more information.
* Ask for help on [MAZAtribe](https://t.me/mazatribe) on Telegram.
Building
---------------------
The following are developer notes on how to build Maza on your native platform. They are not complete guides, but include notes on the necessary libraries, compile flags, etc.
- [Dependencies](dependencies.md)
- [OS X Build Notes](build-osx.md)
- [Unix Build Notes](build-unix.md)
- [Windows Build Notes](build-windows.md)
- [OpenBSD Build Notes](build-openbsd.md)
- [Gitian Building Guide](gitian-building.md)
Development
---------------------
The Maza repo's [root README](/README.md) contains relevant information on the development process and automated testing.
- [Developer Notes](developer-notes.md)
- [Release Notes](release-notes.md)
- [Release Process](release-process.md)
- [Translation Process](translation_process.md)
- [Translation Strings Policy](translation_strings_policy.md)
- [Travis CI](travis-ci.md)
- [Unauthenticated REST Interface](REST-interface.md)
- [Shared Libraries](shared-libraries.md)
- [BIPS](bips.md)
- [Dnsseed Policy](dnsseed-policy.md)
- [Benchmarking](benchmarking.md)
### Miscellaneous
- [Assets Attribution](assets-attribution.md)
- [Files](files.md)
- [Fuzz-testing](fuzzing.md)
- [Reduce Traffic](reduce-traffic.md)
- [Tor Support](tor.md)
- [Init Scripts (systemd/upstart/openrc)](init.md)
- [ZMQ](zmq.md)
License
---------------------
Distributed under the [MIT software license](/COPYING).
This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](https://www.openssl.org/). This product includes
cryptographic software written by Eric Young ([eay@cryptsoft.com](mailto:eay@cryptsoft.com)), and UPnP software written by Thomas Bernard.
|
{
"content_hash": "323b0189cce9e89c18e497d58b415107",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 340,
"avg_line_length": 34.34615384615385,
"alnum_prop": 0.7211646136618141,
"repo_name": "MazaCoin/maza",
"id": "3d3a848c30d1a3434e0dcd6912b8f60486422aab",
"size": "2679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "28453"
},
{
"name": "C",
"bytes": "4236272"
},
{
"name": "C++",
"bytes": "7018978"
},
{
"name": "HTML",
"bytes": "21860"
},
{
"name": "Java",
"bytes": "30290"
},
{
"name": "M4",
"bytes": "195177"
},
{
"name": "Makefile",
"bytes": "116362"
},
{
"name": "Objective-C++",
"bytes": "6747"
},
{
"name": "Python",
"bytes": "1298620"
},
{
"name": "QMake",
"bytes": "782"
},
{
"name": "Sage",
"bytes": "30188"
},
{
"name": "Shell",
"bytes": "69703"
}
]
}
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cloudera.sa</groupId>
<artifactId>mapreduce.sleepjob</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mapreduce.sleepjob</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.0.0-mr1-cdh4.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>2.0.0-mr1-cdh4.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven-hadoop</id>
<name>Hadoop Releases</name>
<url>https://repository.cloudera.com/content/repositories/releases/</url>
</repository>
</repositories>
</project>
|
{
"content_hash": "883f4439f580e89e1134a0f564107486",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 104,
"avg_line_length": 27.229166666666668,
"alnum_prop": 0.7084927314460597,
"repo_name": "tmalaska/MapReducer.SleepJob",
"id": "17a8d2369e5c18de82903f7745b11cba90997f51",
"size": "1307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "8736"
}
]
}
|
React JSON Viewer Component, Extracted from [redux-devtools](https://github.com/gaearon/redux-devtools). Supports [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) objects, such as [Immutable.js](https://facebook.github.io/immutable-js/).

### Usage
```js
import JSONTree from 'react-json-tree'
// If you're using Immutable.js: `npm i --save immutable`
import { Map } from 'immutable'
// Inside a React component:
const json = {
array: [1, 2, 3],
bool: true,
object: {
foo: 'bar'
}
immutable: Map({ key: 'value' })
}
<JSONTree data={ json } />
```
#### Result:

Check out [examples](examples) directory for more details.
### Theming
You can pass a `theme` prop containing [base16](http://chriskempson.github.io/base16) theme data to change the theme. [The example theme data can be found here](https://github.com/gaearon/redux-devtools/tree/75322b15ee7ba03fddf10ac3399881e302848874/src/react/themes).
(The theme data is also used by [redux-devtools](https://github.com/gaearon/redux-devtools), and extracting it to a separate npm package is a TODO).
```js
const theme = {
scheme: 'monokai',
author: 'wimer hazenberg (http://www.monokai.nl)',
base00: '#272822',
base01: '#383830',
base02: '#49483e',
base03: '#75715e',
base04: '#a59f85',
base05: '#f8f8f2',
base06: '#f5f4f1',
base07: '#f9f8f5',
base08: '#f92672',
base09: '#fd971f',
base0A: '#f4bf75',
base0B: '#a6e22e',
base0C: '#a1efe4',
base0D: '#66d9ef',
base0E: '#ae81ff',
base0F: '#cc6633'
};
<div style={{ backgroundColor: theme.base00 }}>
<JSONTree data={ data } theme={ theme } />
</div>
```
#### Result (Monokai theme, dark background):

### Customization
#### Customize CSS
You can pass the following properties to customize styling (all optional):
```js
<JSONTree getArrowStyle={(type, expanded) => ({})}
getItemStringStyle={(type, expanded) => ({})}
getListStyle={(type, expanded) => ({})}
getLabelStyle={(type, expanded) => ({})}
getValueStyle={(type, expanded) => ({})} />
```
Here `type` is a string representing type of data, `expanded` is a current state for expandable items. Each function returns a style object, which extends corresponding default style.
For example, if you pass the following function:
```js
const getStyle = (type, expanded) =>
(expanded ? { textTransform: 'uppercase' } :
{ textTransform: 'lowercase' });
```
Then expanded nodes will all be in uppercase:

#### Customize Labels for Arrays, Objects, and Iterables
You can pass `getItemString` to customize the way arrays, objects, and iterable nodes are displayed (optional).
By default, it'll be:
```js
<JSONTree getArrowStyle={(type, data, itemType, itemString)
=> <span>{itemType} {itemString}</span>}
```
But if you pass the following:
```js
const getItemString = (type, data, itemType, itemString)
=> (<span> // {type}</span>);
```
Then the preview of child elements now look like this:

#### Customize Rendering
You can pass the following properties to customize rendered labels and values:
```js
<JSONTree
labelRenderer={raw => <strong>{raw}</strong>}
valueRenderer={raw => <em>{raw}</em>}
/>
```
In this example the label and value will be rendered with `<strong>` and `<em>` wrappers respectively.
#### More Options
- Add `expandAll` property to expand all nodes.
- Add `hideRoot={true}` to hide a root node.
### Credits
- All credits to [Dave Vedder](http://www.eskimospy.com/) ([veddermatic@gmail.com](mailto:veddermatic@gmail.com)), who wrote the original code as [JSONViewer](https://bitbucket.org/davevedder/react-json-viewer/).
- Extracted from [redux-devtools](https://github.com/gaearon/redux-devtools), which contained ES6 + inline style port of [JSONViewer](https://bitbucket.org/davevedder/react-json-viewer/) by [Daniele Zannotti](http://www.github.com/dzannotti) ([dzannotti@me.com](mailto:dzannotti@me.com))
- [Iterable support](https://github.com/gaearon/redux-devtools/pull/79) thanks to [Daniel K](https://github.com/FredyC).
- npm package created by [Shu Uesugi](http://github.com/chibicode) ([shu@chibicode.com](mailto:shu@chibicode.com)) per [this issue](https://github.com/gaearon/redux-devtools/issues/85).
### Similar Libraries
- [react-treeview](https://github.com/chenglou/react-treeview)
- [react-json-inspector](https://github.com/Lapple/react-json-inspector)
- [react-object-inspector](https://github.com/xyc/react-object-inspector)
### License
MIT
|
{
"content_hash": "8a81e314278de64f010d22b64916f104",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 295,
"avg_line_length": 32.74666666666667,
"alnum_prop": 0.7015472312703583,
"repo_name": "Maxwelloff/react-football",
"id": "63b1c40c388ca4184d8cf240f6bf2c3b1630f9e8",
"size": "4931",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/react-json-tree/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "8877"
},
{
"name": "HTML",
"bytes": "876"
},
{
"name": "JavaScript",
"bytes": "54760"
}
]
}
|
package com.yz.service;
import com.yz.model.Clue;
import com.yz.model.UserRole;
import java.util.List;
public interface ClueService {
//添加对象
void add(Clue clue) throws Exception;
//删除对象
void delete(Clue clue);
//删除某个id的对象
void deleteById(int id);
//修改对象
void update(Clue clue);
//获取所有对象
List<Clue> getClues();
//加载一个id的对象
Clue loadById(int id);
//后台管理-页数获取
int getPageCount(int totalCount, int size);
//后台管理-获取总记录数
int getTotalCount(int con, String convalue, UserRole user, int type, int queryState, String starttime, String endtime);
//后台管理-获取符合条件的记录
List<Clue> queryList(int con, String convalue, UserRole user, int page,
int size, int type, int queryState, String starttime, String endtime);
List<Clue> getCluesByTypeAndHandleState(int con, String convalue,
String starttime, String endtime, int ctype, int state, UserRole userRole);
List<Clue> getOutOfTimeCluesByType(int con, String convalue,
String starttime, String endtime, int ctype, UserRole userRole);
List<Clue> getCluesByType(int con, String convalue,
String starttime, String endtime, int ctype, UserRole userRole);
List<Clue> getNewClueByUserRole(UserRole userRole);
}
|
{
"content_hash": "5fc9c16cee212739d44f2457980e9520",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 120,
"avg_line_length": 22.51851851851852,
"alnum_prop": 0.7327302631578947,
"repo_name": "yunzhikeji/dchc",
"id": "53311ca5a06f5fe77290f1a4fca0c2834d3fb6a6",
"size": "1342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/yz/service/ClueService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "381774"
},
{
"name": "HTML",
"bytes": "1635265"
},
{
"name": "Java",
"bytes": "1845138"
},
{
"name": "JavaScript",
"bytes": "5246948"
},
{
"name": "PHP",
"bytes": "15112"
}
]
}
|
[](https://travis-ci.org/zachwalton/truebpm/builds)
https://truebpm.dance
Pick a preferred read speed and select a song. You'll get a breakdown of BPM duration:

# Contributing
## Setup
### Requirements
- NodeJS 8+
- Yarn 1.22.4
- Python 3.6.11
- Using [pyenv](https://github.com/pyenv/pyenv) is probably the easiest way to do this.
Set up a virtual env and install dependencies:
```
pyenv install (This'll install 3.6.11 if you don't have it already)
pyenv virtualenv truebpm
pyenv activate truebpm
```
To serve the API + frontend, `./serve.sh`
This will serve the API + frontend on `http://127.0.0.1:5000`. If you just want to work on the frontend, you may want to use yarn to get the benefits of live reloading:
```
cd frontend/ && yarn run start
```
## Adding Simfiles
Simfiles live in the `simfiles/` directory, and the filenames are formatted as `<title> - <artist>`. To add a simfile, just run `./convert.py </path/to/simfile.sm>` and it will rename it for you. Drop it in the `simfiles/` directory and submit a PR.
CI will test to make sure that the simfile is valid. If pull request verification fails, check the build logs.
|
{
"content_hash": "06c4ebbb0bd6f7ae4ff456d5fe80582a",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 249,
"avg_line_length": 30.875,
"alnum_prop": 0.7230769230769231,
"repo_name": "zachwalton/truebpm",
"id": "40df18ab03e5adcc7b2b8455309f57a966e485ee",
"size": "1247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "30348"
},
{
"name": "CSS",
"bytes": "781"
},
{
"name": "GAP",
"bytes": "16053"
},
{
"name": "HTML",
"bytes": "1732"
},
{
"name": "JavaScript",
"bytes": "8575"
},
{
"name": "M",
"bytes": "18838"
},
{
"name": "Procfile",
"bytes": "25"
},
{
"name": "Python",
"bytes": "14871"
},
{
"name": "R",
"bytes": "88758"
},
{
"name": "Raku",
"bytes": "84159"
},
{
"name": "Roff",
"bytes": "144092"
},
{
"name": "Shell",
"bytes": "134"
}
]
}
|
require "chatify/engine"
module Chatify
mattr_accessor :chat_user_class
def self.chat_user_class
@@chat_user_class.constantize
end
end
|
{
"content_hash": "d645e8f9a6f7bba16a19e3494514b339",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 33,
"avg_line_length": 16.333333333333332,
"alnum_prop": 0.7414965986394558,
"repo_name": "railslauncher/chatify",
"id": "cd4dff4c6ae52118feb4192deb0fd70e2a660f8e",
"size": "147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/chatify.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1903"
},
{
"name": "JavaScript",
"bytes": "1280"
},
{
"name": "Ruby",
"bytes": "19779"
}
]
}
|
const EXIT_REASON_NMI: u64 = 0x0;
const EXIT_REASON_NMI_WINDOW: u64 = 0x8;
const EXIT_REASON_CPUID: u64 = 0xA;
#[path = "dispatch_vmexit_nmi_window.rs"]
#[doc(hidden)]
pub mod dispatch_vmexit_nmi_window;
pub use dispatch_vmexit_nmi_window::*;
#[path = "dispatch_vmexit_nmi.rs"]
#[doc(hidden)]
pub mod dispatch_vmexit_nmi;
pub use dispatch_vmexit_nmi::*;
#[path = "../dispatch_vmexit_cpuid.rs"]
#[doc(hidden)]
pub mod dispatch_vmexit_cpuid;
pub use dispatch_vmexit_cpuid::*;
/// <!-- description -->
/// @brief Dispatches the VMExit.
///
/// <!-- inputs/outputs -->
/// @param gs the gs_t to use
/// @param tls the tls_t to use
/// @param sys the bf_syscall_t to use
/// @param intrinsic the intrinsic_t to use
/// @param vp_pool the vp_pool_t to use
/// @param vs_pool the vs_pool_t to use
/// @param vsid the ID of the VS that generated the VMExit
/// @param exit_reason the exit reason associated with the VMExit
/// @return Returns bsl::errc_success on success, bsl::errc_failure
/// and friends otherwise
///
pub fn dispatch_vmexit(
gs: &crate::GsT,
tls: &crate::TlsT,
sys: &mut syscall::BfSyscallT,
intrinsic: &crate::IntrinsicT,
vp_pool: &crate::VpPoolT,
vs_pool: &crate::VsPoolT,
vsid: bsl::SafeU16,
exit_reason: bsl::SafeU64,
) -> bsl::ErrcType {
bsl::discard(vp_pool);
bsl::discard(vs_pool);
match exit_reason.get() {
EXIT_REASON_NMI => return dispatch_vmexit_nmi(gs, tls, sys, vsid),
EXIT_REASON_NMI_WINDOW => return dispatch_vmexit_nmi_window(gs, tls, sys, vsid),
EXIT_REASON_CPUID => return dispatch_vmexit_cpuid(gs, tls, sys, intrinsic, vsid),
_ => {}
}
error!("unsupported vmexit: {:#018x}\n", exit_reason);
syscall::bf_debug_op_dump_vs(vsid);
print_v!("{}", bsl::here());
return bsl::errc_failure;
}
|
{
"content_hash": "3aa19583786d75f93f63db9cb5e5dc86",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 89,
"avg_line_length": 29.285714285714285,
"alnum_prop": 0.6401084010840108,
"repo_name": "rianquinn/hypervisor",
"id": "9d52818bb449424137edce873d7d48e85629b015",
"size": "3057",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example/default_rust/src/x64/intel/dispatch_vmexit.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "62612"
},
{
"name": "C",
"bytes": "124043"
},
{
"name": "C++",
"bytes": "4157262"
},
{
"name": "CMake",
"bytes": "232658"
},
{
"name": "Makefile",
"bytes": "1846"
},
{
"name": "Shell",
"bytes": "16905"
}
]
}
|
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
namespace Archichect {
public interface ITransformer : IPlugin {
void Configure([NotNull] GlobalContext globalContext, [CanBeNull] string configureOptions, bool forceReload);
int Transform([NotNull] GlobalContext globalContext, [NotNull] [ItemNotNull] IEnumerable<Dependency> dependencies,
[CanBeNull] string transformOptionsString, [NotNull] List<Dependency> transformedDependencies,
Func<string, IEnumerable<Dependency>> findOtherWorkingGraph);
[NotNull]
IEnumerable<Dependency> CreateSomeTestDependencies(WorkingGraph transformingGraph);
}
}
|
{
"content_hash": "aebdb84029a7ef057a661703ada69812",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 122,
"avg_line_length": 43.125,
"alnum_prop": 0.7565217391304347,
"repo_name": "hmmueller/Archichect",
"id": "a75b74bae8fcbf98213fa3237332146bbef7bd51",
"size": "692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Archichect/ITransformer.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1289751"
},
{
"name": "PowerShell",
"bytes": "478"
}
]
}
|
package org.phynixx.hello.impl;
import akka.Done;
import akka.NotUsed;
import akka.japi.Pair;
import com.lightbend.lagom.javadsl.api.ServiceCall;
import com.lightbend.lagom.javadsl.api.broker.Topic;
import com.lightbend.lagom.javadsl.broker.TopicProducer;
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRef;
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry;
import java.util.Optional;
import javax.inject.Inject;
import org.phynixx.hello.api.GreetingMessage;
import org.phynixx.hello.api.HelloService;
import org.phynixx.hello.impl.HelloCommand.*;
/**
* Implementation of the HelloService.
*/
public class HelloServiceImpl implements HelloService {
private final PersistentEntityRegistry persistentEntityRegistry;
@Inject
public HelloServiceImpl(PersistentEntityRegistry persistentEntityRegistry) {
this.persistentEntityRegistry = persistentEntityRegistry;
persistentEntityRegistry.register(HelloEntity.class);
}
@Override
public ServiceCall<NotUsed, String> hello(String id) {
return request -> {
// Look up the hello world entity for the given ID.
PersistentEntityRef<HelloCommand> ref = persistentEntityRegistry.refFor(HelloEntity.class, id);
// Ask the entity the Hello command.
return ref.ask(new Hello(id));
};
}
@Override
public ServiceCall<GreetingMessage, Done> useGreeting(String id) {
return request -> {
// Look up the hello world entity for the given ID.
PersistentEntityRef<HelloCommand> ref = persistentEntityRegistry.refFor(HelloEntity.class, id);
// Tell the entity to use the greeting message specified.
return ref.ask(new UseGreetingMessage(request.message));
};
}
@Override
public Topic<org.phynixx.hello.api.HelloEvent> helloEvents() {
// We want to publish all the shards of the hello event
return TopicProducer.taggedStreamWithOffset(HelloEvent.TAG.allTags(), (tag, offset) ->
// Load the event stream for the passed in shard tag
persistentEntityRegistry.eventStream(tag, offset).map(eventAndOffset -> {
// Now we want to convert from the persisted event to the published event.
// Although these two events are currently identical, in future they may
// change and need to evolve separately, by separating them now we save
// a lot of potential trouble in future.
org.phynixx.hello.api.HelloEvent eventToPublish;
if (eventAndOffset.first() instanceof HelloEvent.GreetingMessageChanged) {
HelloEvent.GreetingMessageChanged messageChanged = (HelloEvent.GreetingMessageChanged) eventAndOffset.first();
eventToPublish = new org.phynixx.hello.api.HelloEvent.GreetingMessageChanged(
messageChanged.getName(), messageChanged.getMessage()
);
} else {
throw new IllegalArgumentException("Unknown event: " + eventAndOffset.first());
}
// We return a pair of the translated event, and its offset, so that
// Lagom can track which offsets have been published.
return Pair.create(eventToPublish, eventAndOffset.second());
})
);
}
}
|
{
"content_hash": "2ef98df6545d7c5701ad1b2ab1079bf3",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 118,
"avg_line_length": 38.292682926829265,
"alnum_prop": 0.7414012738853503,
"repo_name": "csc19601128/misc-examples",
"id": "559f1c5be705585a67026ce8a695aa547d182fd8",
"size": "3140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lagom/lightbend-logom-quickstart/hello-impl/src/main/java/org/phynixx/hello/impl/HelloServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "17973"
},
{
"name": "CSS",
"bytes": "137172"
},
{
"name": "Dockerfile",
"bytes": "4886"
},
{
"name": "Go",
"bytes": "8864"
},
{
"name": "Groovy",
"bytes": "745"
},
{
"name": "HCL",
"bytes": "470"
},
{
"name": "HTML",
"bytes": "27741"
},
{
"name": "Java",
"bytes": "965152"
},
{
"name": "JavaScript",
"bytes": "2304210"
},
{
"name": "Perl",
"bytes": "1432"
},
{
"name": "Python",
"bytes": "13020"
},
{
"name": "Rich Text Format",
"bytes": "810"
},
{
"name": "Roff",
"bytes": "2683772"
},
{
"name": "Ruby",
"bytes": "9372"
},
{
"name": "Scala",
"bytes": "276"
},
{
"name": "Shell",
"bytes": "96991"
},
{
"name": "TSQL",
"bytes": "15572"
},
{
"name": "TypeScript",
"bytes": "14500"
}
]
}
|
import sys
sys.path.append('../')
from WeatherConfig import*
from lucidatypes.ttypes import QuerySpec
from lucidaservice import LucidaService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import json
import urllib
class WeatherHandler(LucidaService.Iface):
def create(self, LUCID, spec):
"""
Do nothing
"""
return
def learn(self, LUCID, knowledge):
"""
Do nothing
"""
return
def infer(self, LUCID, query):
"""
Determine the weather based off input
Parameters:
- LUCID: ID of Lucida user
- query: query
"""
input_data = query.content[0].data[-1]
result = 'No weather found for %s' % input_data
url_location = urllib.quote_plus(input_data)
# weather from Weather Underground
try:
f = urllib.urlopen(WU_API_URL_BASE + \
'%s/conditions/q/%s.json' % (WU_API_KEY, url_location))
json_string = f.read()
parsed_json = json.loads(json_string)
if 'error' not in parsed_json['response'] \
and 'current_observation' in parsed_json:
weather = parsed_json['current_observation']['weather']
temp = parsed_json['current_observation']['temperature_string']
city = parsed_json['current_observation']['display_location']['full']
result = "Current weather in %s is %s %s" % (city, weather, temp)
print 'From Weather Underground: %s' % result
else:
# weather from Open Weather Map
f = urllib.urlopen(OWM_API_URL_BASE + \
'q=%s&appid=%s&units=imperial&type=like' % (url_location, OWM_API_KEY))
json_string = f.read()
parsed_json = json.loads(json_string)
if 'weather' in parsed_json and 'main' in parsed_json and 'name' in parsed_json:
weather = parsed_json['weather'][0]['main']
temp = parsed_json['main']['temp']
city = parsed_json['name']
if city in input_data:
result = 'Current weather in %s is %s, %s F' % (city, weather, temp)
print 'From Open Weather Map: %s' % result
f.close()
except IOError as err:
if 401 in err:
result = 'Unauthorized Weather API keys'
else:
result = 'Weather Service is broken!'
return result
# Set handler to our implementation
handler = WeatherHandler()
processor = LucidaService.Processor(handler)
transport = TSocket.TServerSocket(port=PORT)
tfactory = TTransport.TFramedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
print 'WE at port %d' % PORT
server.serve()
|
{
"content_hash": "2b718d530bcc86216ea6c07abae31a0c",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 96,
"avg_line_length": 35.89411764705882,
"alnum_prop": 0.5811209439528023,
"repo_name": "claritylab/sirius",
"id": "8ae390520eaf6f16a7cdbb742015196cdd651094",
"size": "3074",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lucida/weather/server/WeatherServer.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "1151"
},
{
"name": "Batchfile",
"bytes": "777"
},
{
"name": "C",
"bytes": "11598"
},
{
"name": "C++",
"bytes": "367354"
},
{
"name": "Cuda",
"bytes": "30380"
},
{
"name": "Java",
"bytes": "1175055"
},
{
"name": "JavaScript",
"bytes": "1356"
},
{
"name": "Makefile",
"bytes": "24290"
},
{
"name": "PHP",
"bytes": "531"
},
{
"name": "Pascal",
"bytes": "87"
},
{
"name": "Protocol Buffer",
"bytes": "1501"
},
{
"name": "Python",
"bytes": "19987"
},
{
"name": "Shell",
"bytes": "19289"
},
{
"name": "Thrift",
"bytes": "4220"
}
]
}
|
namespace parquet_cpp {
struct ByteArray {
uint32_t len;
const uint8_t* ptr;
};
struct FixedLenByteArray {
const uint8_t* ptr;
};
MANUALLY_ALIGNED_STRUCT(1) Int96 {
uint32_t value[3];
};
STRUCT_END(Int96, 12);
static inline std::string ByteArrayToString(const ByteArray& a) {
return std::string(reinterpret_cast<const char*>(a.ptr), a.len);
}
static inline std::string Int96ToString(const Int96& a) {
std::stringstream result;
for (int i = 0; i < 3; i++) {
result << a.value[i] << " ";
}
return result.str();
}
static inline std::string FixedLenByteArrayToString(const FixedLenByteArray& a, int len) {
const uint8_t *bytes = reinterpret_cast<const uint8_t*>(a.ptr);
std::stringstream result;
for (int i = 0; i < len; i++) {
result << (uint32_t)bytes[i] << " ";
}
return result.str();
}
static inline int ByteCompare(const ByteArray& x1, const ByteArray& x2) {
int len = std::min(x1.len, x2.len);
int cmp = memcmp(x1.ptr, x2.ptr, len);
if (cmp != 0) return cmp;
if (len < x1.len) return 1;
if (len < x2.len) return -1;
return 0;
}
template <int TYPE>
struct type_traits {
};
template <>
struct type_traits<parquet::Type::BOOLEAN> {
typedef bool value_type;
static constexpr parquet::Type::type parquet_type = parquet::Type::BOOLEAN;
static constexpr size_t value_byte_size = 1;
};
template <>
struct type_traits<parquet::Type::INT32> {
typedef int32_t value_type;
static constexpr parquet::Type::type parquet_type = parquet::Type::INT32;
static constexpr size_t value_byte_size = 4;
};
template <>
struct type_traits<parquet::Type::INT64> {
typedef int64_t value_type;
static constexpr parquet::Type::type parquet_type = parquet::Type::INT64;
static constexpr size_t value_byte_size = 8;
};
template <>
struct type_traits<parquet::Type::INT96> {
typedef Int96 value_type;
static constexpr parquet::Type::type parquet_type = parquet::Type::INT96;
static constexpr size_t value_byte_size = 12;
};
template <>
struct type_traits<parquet::Type::FLOAT> {
typedef float value_type;
static constexpr parquet::Type::type parquet_type = parquet::Type::FLOAT;
static constexpr size_t value_byte_size = 4;
};
template <>
struct type_traits<parquet::Type::DOUBLE> {
typedef double value_type;
static constexpr parquet::Type::type parquet_type = parquet::Type::DOUBLE;
static constexpr size_t value_byte_size = 8;
};
template <>
struct type_traits<parquet::Type::BYTE_ARRAY> {
typedef ByteArray value_type;
static constexpr parquet::Type::type parquet_type = parquet::Type::BYTE_ARRAY;
static constexpr size_t value_byte_size = sizeof(ByteArray);
};
template <>
struct type_traits<parquet::Type::FIXED_LEN_BYTE_ARRAY> {
typedef FixedLenByteArray value_type;
static constexpr parquet::Type::type parquet_type = parquet::Type::FIXED_LEN_BYTE_ARRAY;
static constexpr size_t value_byte_size = sizeof(FixedLenByteArray);
};
} // namespace parquet_cpp
#endif // PARQUET_TYPES_H
|
{
"content_hash": "95e069a21b96b1c1d518a8065abf8373",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 90,
"avg_line_length": 25.504273504273506,
"alnum_prop": 0.6980563002680965,
"repo_name": "knizhnik/parquet-cpp",
"id": "409e335aff9dfb0609d83f619a103d936a14e808",
"size": "4015",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/parquet/types.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2216"
},
{
"name": "C++",
"bytes": "124774"
},
{
"name": "CMake",
"bytes": "29247"
},
{
"name": "Perl",
"bytes": "4006"
},
{
"name": "Python",
"bytes": "13233"
},
{
"name": "Shell",
"bytes": "6857"
},
{
"name": "Thrift",
"bytes": "16891"
}
]
}
|
class NotificationQueue {
std::deque<std::function<void()>> q_{};
bool done_{false};
std::mutex mutex_{};
std::condition_variable ready_{};
public:
void done();
bool pop(std::function<void()> &x);
bool try_pop(std::function<void()> &x);
template <typename F>
void push(F &&f) {
{
std::unique_lock<std::mutex> lock{mutex_};
q_.emplace_back(std::forward<F>(f));
}
ready_.notify_one();
}
template <typename F>
bool try_push(F &&f) {
{
std::unique_lock<std::mutex> lock{mutex_, std::try_to_lock};
if (!lock) {
return false;
}
q_.emplace_back(std::forward<F>(f));
}
ready_.notify_one();
return true;
}
};
|
{
"content_hash": "31d2b3d5d2f9aa3fecc1de4e3abe6cb3",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 66,
"avg_line_length": 21.21212121212121,
"alnum_prop": 0.56,
"repo_name": "antaljanosbenjamin/miscellaneous",
"id": "b3eb003865f6f091855c1d9a5546e5b959a8e6f3",
"size": "801",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "experiments/task_systems/NotificationQueue.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "3190279"
},
{
"name": "CMake",
"bytes": "48708"
},
{
"name": "Python",
"bytes": "1752"
}
]
}
|
"""Tests for the PHDI image path specification implementation."""
import unittest
from dfvfs.path import phdi_path_spec
from tests.path import test_lib
class PHDIPathSpecTest(test_lib.PathSpecTestCase):
"""Tests for the PHDI image path specification implementation."""
def testInitialize(self):
"""Tests the path specification initialization."""
path_spec = phdi_path_spec.PHDIPathSpec(parent=self._path_spec)
self.assertIsNotNone(path_spec)
with self.assertRaises(ValueError):
phdi_path_spec.PHDIPathSpec(parent=None)
with self.assertRaises(ValueError):
phdi_path_spec.PHDIPathSpec(parent=self._path_spec, bogus='BOGUS')
def testComparable(self):
"""Tests the path specification comparable property."""
path_spec = phdi_path_spec.PHDIPathSpec(parent=self._path_spec)
self.assertIsNotNone(path_spec)
expected_comparable = '\n'.join([
'type: TEST',
'type: PHDI',
''])
self.assertEqual(path_spec.comparable, expected_comparable)
if __name__ == '__main__':
unittest.main()
|
{
"content_hash": "06e287754aed14eeeab120fd78bcf299",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 72,
"avg_line_length": 26.725,
"alnum_prop": 0.7043966323666978,
"repo_name": "joachimmetz/dfvfs",
"id": "01e90c17ca57b2e290a5660aa90f420664991ef1",
"size": "1115",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "tests/path/phdi_path_spec.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "14212"
},
{
"name": "Makefile",
"bytes": "122"
},
{
"name": "PowerShell",
"bytes": "1021"
},
{
"name": "Python",
"bytes": "2176548"
},
{
"name": "Shell",
"bytes": "19355"
}
]
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CulturalCuisine.Presenters;
namespace CulturalCuisine
{
/// <summary>
/// Interaction logic for Shell2.xaml
/// </summary>
public partial class Shell2 : Window
{
private ApplicationPresenter _appControl;
public Shell2(ApplicationPresenter appControl)
{
InitializeComponent();
_appControl = appControl;
}
}
}
|
{
"content_hash": "a81eb0f7111ec39ec0ad5e75b54692e1",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 54,
"avg_line_length": 24.866666666666667,
"alnum_prop": 0.6809651474530831,
"repo_name": "akiress/idt4243",
"id": "0eba409ab6c299df69a53279f15ba1e42dfbaa3b",
"size": "748",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "project_4/CulturalCuisine/CulturalCuisine/Shell2.xaml.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "6153"
},
{
"name": "C#",
"bytes": "119311"
},
{
"name": "C++",
"bytes": "4721"
},
{
"name": "CSS",
"bytes": "4697"
},
{
"name": "JavaScript",
"bytes": "14713"
},
{
"name": "Python",
"bytes": "19742"
}
]
}
|
package tech.sirwellington.alchemy.generator;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import kotlin.io.ByteStreamsKt;
import kotlin.text.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author SirWellington
*/
final class AlchemyResources
{
private static final Logger LOG = LoggerFactory.getLogger(AlchemyResources.class);
//===========================================
// PRIVATE FUNCTIONS
//===========================================
static List<String> readLinesFromResource(String path)
{
String file = tryToLoadResource(path);
if (file == null || file.isEmpty())
{
return Collections.emptyList();
}
String[] lines = file.split("\n");
LOG.trace("Successfully read [{}] lines from resource [{}]", lines.length, path);
return Arrays.asList(lines);
}
private static String tryToLoadResource(String path)
{
ClassLoader classLoader = AlchemyGenerator.class.getClassLoader();
if (classLoader == null)
{
return null;
}
URL url = classLoader.getResource(path);
if (url == null)
{
LOG.warn("Could not load resource at [$path]");
return null;
}
byte[] bytes = tryToReadBytes(url);
if (bytes == null)
{
return null;
}
return new String(bytes, Charsets.UTF_8);
}
private static byte[] tryToReadBytes(URL url)
{
try (InputStream istream = url.openStream())
{
byte[] bytes = ByteStreamsKt.readBytes(istream, 1024 * 8);
return bytes;
}
catch (IOException ex)
{
LOG.warn("Failed to read resource at {}", url, ex);
return null;
}
}
}
|
{
"content_hash": "3ff34c8cdda15f625f1a0c80df9b9327",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 89,
"avg_line_length": 23.085365853658537,
"alnum_prop": 0.554675118858954,
"repo_name": "SirWellington/alchemy-generator",
"id": "3d040b6f753a8ea3bce9bc8e29506b7bdce9f292",
"size": "2492",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/main/java/tech/sirwellington/alchemy/generator/AlchemyResources.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "7162"
},
{
"name": "Kotlin",
"bytes": "201908"
}
]
}
|
EWZTimeBundle
=============
This bundle provides easy time helper for Symfony applications.
## Installation
Installation depends on how your project is setup:
### Step 1: Installation using the `bin/vendors.php` method
If you're using the `bin/vendors.php` method to manage your vendor libraries,
add the following entry to the `deps` in the root of your project file:
```
[EWZTimeBundle]
git=http://github.com/excelwebzone/EWZTimeBundle.git
target=/bundles/EWZ/Bundle/TimeBundle
```
Next, update your vendors by running:
``` bash
$ ./bin/vendors
```
Great! Now skip down to *Step 2*.
### Step 1 (alternative): Installation with submodules
If you're managing your vendor libraries with submodules, first create the
`vendor/bundles/EWZ/Bundle` directory:
``` bash
$ mkdir -pv vendor/bundles/EWZ/Bundle
```
Next, add the necessary submodule:
``` bash
$ git submodule add git://github.com/excelwebzone/EWZTimeBundle.git vendor/bundles/EWZ/Bundle/TimeBundle
```
### Step2: Configure the autoloader
Add the following entry to your autoloader:
``` php
<?php
// app/autoload.php
$loader->registerNamespaces(array(
// ...
'EWZ' => __DIR__.'/../vendor/bundles',
));
```
### Step3: Enable the bundle
Finally, enable the bundle in the kernel:
``` php
<?php
// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
// ...
new EWZ\Bundle\TimeBundle\EWZTimeBundle(),
);
}
```
Congratulations! You're ready!
## Basic Usage
Here are 2 example to retrieve time from a given datetime, and the difference in seconds:
``` jinja
{{ ewz_time_ago(DateTimeObject) }}
{{ ewz_time_diff(DateTimeObject) }}
```
Or if you're using PHP templates:
``` php
<?php echo $view['ewz_time']->ago($dateTime); // returns something like "3 minutes ago" ?>
<?php echo $view['ewz_time']->diff($dateTime); // returns something like "180" seconds ?>
```
|
{
"content_hash": "4f92312b768228c8a4b47b4fa0475dbb",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 104,
"avg_line_length": 20.408602150537636,
"alnum_prop": 0.6928345626975764,
"repo_name": "excelwebzone/EWZTimeBundle",
"id": "345350ea72fbdd9bcabeedd21eadb86862dcc8b2",
"size": "1898",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "6783"
}
]
}
|
This perturbation adds noise to all types of text sources (sentence, paragraph, etc.).
Author name: Marco Di Giovanni
Author email: marco.digiovanni@polimi.it
Author Affiliation: Politecnico di Milano and University of Bologna
## What type of a transformation is this?
This transformation acts like a perturbation to test robustness.
It replaces some random spaces with underscores (or even other selected symbols).
This transformation mimics particular behaviours:
- names of folders, files, classes, functions (e.g., underscore_trick)
- trick word counters when there is a limited maximum number of words to insert in an online questionary/quiz.
Generated transformations display high similarity to the source sentences.
## What tasks does it intend to benefit?
This perturbation would benefit all tasks which have a sentence/paragraph/document as input like text classification, text generation, etc. Especially on tasks related to understanding/generating scripts.
## What are the limitations of this transformation?
The transformation's outputs are extremely simple to be used for data augmentation.
|
{
"content_hash": "3e05ff7903a9550a6480607b5d8befd1",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 204,
"avg_line_length": 58.36842105263158,
"alnum_prop": 0.8133453561767358,
"repo_name": "GEM-benchmark/NL-Augmenter",
"id": "6312ae57ecd867697740918849c70b34bbaa2249",
"size": "1128",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "nlaugmenter/transformations/underscore_trick/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "151288"
},
{
"name": "Makefile",
"bytes": "343"
},
{
"name": "Python",
"bytes": "1003016"
}
]
}
|
# BSD 3-Clause License
# =======
# Copyright (c) 2020, Xilinx
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
from finnthesizer import *
if __name__ == "__main__":
bnnRoot = "."
npzFile = bnnRoot + "/cifar10-1w-2a.npz"
targetDirBin = bnnRoot + "/cnvW1A2"
targetDirHLS = bnnRoot + "/cnvW1A2/hw"
#topology of convolutional layers (only for config.h defines)
ifm = [32, 30, 14, 12, 5, 3]
ofm = [30, 28, 12, 10, 3, 1]
ifm_ch = [ 3, 64, 64, 128, 128, 256]
ofm_ch = [64, 64, 128, 128, 256, 256]
filterDim = [ 3, 3, 3, 3, 3, 3]
WeightsPrecisions_integer = [1 , 1 , 1 , 1 , 1 , 1 , 1, 1, 1]
WeightsPrecisions_fractional = [0 , 0 , 0 , 0 , 0 , 0 , 0, 0, 0]
InputPrecisions_integer = [1 , 2 , 2 , 2 , 2 , 2 , 2, 2, 2]
InputPrecisions_fractional = [7 , 0 , 0 , 0 , 0 , 0 , 0, 0, 0]
ActivationPrecisions_integer = [2 , 2 , 2 , 2 , 2 , 2 , 2, 2, 16]
ActivationPrecisions_fractional = [0 , 0 , 0 , 0 , 0 , 0 , 0, 0, 0]
classes = ['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck']
#configuration of PE and SIMD counts
peCounts = [16, 32, 16, 16, 4, 1, 1, 1, 4]
simdCounts = [ 3, 32, 32, 32, 32, 32, 4, 8, 1]
if not os.path.exists(targetDirBin):
os.mkdir(targetDirBin)
if not os.path.exists(targetDirHLS):
os.mkdir(targetDirHLS)
#read weights
rHW = BNNWeightReader(npzFile, True)
config = "/**\n"
config+= " * Finnthesizer Config-File Generation\n";
config+= " *\n **/\n\n"
config+= "#ifndef __LAYER_CONFIG_H_\n#define __LAYER_CONFIG_H_\n\n"
# process convolutional layers
for convl in range(0, 6):
peCount = peCounts[convl]
simdCount = simdCounts[convl]
WPrecision_fractional = WeightsPrecisions_fractional[convl]
APrecision_fractional = ActivationPrecisions_fractional[convl]
IPrecision_fractional = InputPrecisions_fractional[convl]
WPrecision_integer = WeightsPrecisions_integer[convl]
APrecision_integer = ActivationPrecisions_integer[convl]
IPrecision_integer = InputPrecisions_integer[convl]
print("Using peCount = %d simdCount = %d for engine %d" % (peCount, simdCount, convl))
# use fixed point weights for the first layer
(usePopCount, numThresBits, numThresIntBits) = (False, 24, 16) if convl==0 else (False, 16, None)
(w,t) = rHW.readConvBNComplex(WPrecision_fractional, APrecision_fractional, IPrecision_fractional, \
WPrecision_integer, APrecision_integer, IPrecision_integer, \
usePopCount=usePopCount, numThresBits=numThresBits, numThresIntBits=numThresIntBits)
# compute the padded width and height
paddedH = padTo(w.shape[0], peCount)
paddedW = padTo(w.shape[1], simdCount)
# compute memory needed for weights and thresholds
neededWMem = (paddedW * paddedH) // (simdCount * peCount)
neededTMem = paddedH // peCount
print("Layer %d: %d x %d" % (convl, paddedH, paddedW))
print("WMem = %d TMem = %d" % (neededWMem, neededTMem))
print("IPrecision = %d.%d WPrecision = %d.%d APrecision = %d.%d" % (IPrecision_integer, IPrecision_fractional, \
WPrecision_integer,WPrecision_fractional, APrecision_integer, APrecision_fractional))
m = BNNProcElemMem(peCount, simdCount, neededWMem, neededTMem, WPrecision_integer, APrecision_integer, IPrecision_integer, \
WPrecision_fractional, APrecision_fractional, IPrecision_fractional, numThresBits=numThresBits, numThresIntBits=numThresIntBits)
m.addMatrix(w,t,paddedW,paddedH)
config += (printConvDefines("L%d" % convl, filterDim[convl], ifm_ch[convl], ifm[convl], ofm_ch[convl], ofm[convl], simdCount, \
peCount, neededWMem, neededTMem, WPrecision_integer, APrecision_integer, WPrecision_fractional, APrecision_fractional)) + "\n"
#generate HLS weight and threshold header file to initialize memory directly on bitstream generation
# m.createHLSInitFiles(targetDirHLS + "/memdata-" + str(convl) + ".h", str(convl))
#generate binary weight and threshold files to initialize memory during runtime
#because HLS might not work for very large header files
m.createBinFiles(targetDirBin, str(convl))
# process fully-connected layers
for fcl in range(6,9):
peCount = peCounts[fcl]
simdCount = simdCounts[fcl]
WPrecision_fractional = WeightsPrecisions_fractional[fcl]
APrecision_fractional = ActivationPrecisions_fractional[fcl]
IPrecision_fractional = InputPrecisions_fractional[fcl]
WPrecision_integer = WeightsPrecisions_integer[fcl]
APrecision_integer = ActivationPrecisions_integer[fcl]
IPrecision_integer = InputPrecisions_integer[fcl]
print("Using peCount = %d simdCount = %d for engine %d" % (peCount, simdCount, fcl))
if fcl == 8:
(w,t) = rHW.readFCBNComplex_no_thresholds(WPrecision_fractional, APrecision_fractional, IPrecision_fractional, \
WPrecision_integer, APrecision_integer, IPrecision_integer)
paddedH = padTo(w.shape[0], 64)
useThresholds = False
else:
(w,t) = rHW.readFCBNComplex(WPrecision_fractional, APrecision_fractional, IPrecision_fractional, \
WPrecision_integer, APrecision_integer, IPrecision_integer)
paddedH = padTo(w.shape[0], peCount)
useThresholds = True
# compute the padded width and height
paddedW = padTo(w.shape[1], simdCount)
# compute memory needed for weights and thresholds
neededWMem = (paddedW * paddedH) // (simdCount * peCount)
neededTMem = paddedH // peCount
print("Layer %d: %d x %d" % (fcl, paddedH, paddedW))
print("WMem = %d TMem = %d" % (neededWMem, neededTMem))
print("IPrecision = %d.%d WPrecision = %d.%d APrecision = %d.%d" % (IPrecision_integer, IPrecision_fractional, WPrecision_integer,\
WPrecision_fractional, APrecision_integer, APrecision_fractional))
m = BNNProcElemMem(peCount, simdCount, neededWMem, neededTMem, WPrecision_integer, APrecision_integer, IPrecision_integer, \
WPrecision_fractional, APrecision_fractional, IPrecision_fractional)
m.addMatrix(w,t,paddedW,paddedH)
config += (printFCDefines("L%d" % fcl, simdCount, peCount, neededWMem, neededTMem, paddedW, paddedH, \
WPrecision_integer, APrecision_integer, WPrecision_fractional, APrecision_fractional)) + "\n"
#generate HLS weight and threshold header file to initialize memory directly on bitstream generation
# m.createHLSInitFiles(targetDirHLS + "/memdata-" + str(fcl) + ".h", str(fcl), useThresholds)
#generate binary weight and threshold files to initialize memory during runtime
#because HLS might not work for very large header files
m.createBinFiles(targetDirBin, str(fcl), useThresholds)
config+="#endif //__LAYER_CONFIG_H_\n"
configFile = open(targetDirHLS+"/config.h", "w")
configFile.write(config)
configFile.close()
with open(targetDirBin + "/classes.txt", "w") as f:
f.write("\n".join(classes))
|
{
"content_hash": "6499a84c8b16c87c1082e23192442b34",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 140,
"avg_line_length": 53.40963855421687,
"alnum_prop": 0.666704263478457,
"repo_name": "Xilinx/BNN-PYNQ",
"id": "f8689dec5ad564574cb891a8bc4834ab2b61f4b1",
"size": "8866",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bnn/src/training/cifar10-gen-weights-W1A2.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "15377"
},
{
"name": "C++",
"bytes": "144353"
},
{
"name": "Dockerfile",
"bytes": "5626"
},
{
"name": "Jupyter Notebook",
"bytes": "7698409"
},
{
"name": "Python",
"bytes": "158919"
},
{
"name": "Shell",
"bytes": "14256"
},
{
"name": "Tcl",
"bytes": "520413"
}
]
}
|
goog.provide('todomvc.listcontrol');
goog.require('goog.dom');
goog.require('goog.events.KeyCodes');
goog.require('goog.string');
goog.require('mvc.Control');
goog.require('todomvc.templates');
goog.require('todomvc.todocontrol');
/**
* the control for the todo list, handles the page as well
*
* @constructor
* @param {mvc.Collection} list model for todo items.
* @extends {mvc.Control}
*/
todomvc.listcontrol = function( list ) {
goog.base( this, list );
this.filter_ = todomvc.listcontrol.Filter.ALL;
};
goog.inherits( todomvc.listcontrol, mvc.Control );
/**
* @enum {Function}
*/
todomvc.listcontrol.Filter = {
ALL: function() {
return true
},
ACTIVE: function( model ) {
return !model.get('completed')
},
COMPLETED: function( model ) {
return model.get('completed')
}
};
/**
* setup for event listeners.
*
* @inheritDoc
*/
todomvc.listcontrol.prototype.enterDocument = function() {
goog.base( this, 'enterDocument' );
var list = /** @type {Object} */(this.getModel());
// Create new model from text box
var input = this.getEls('input')[0];
this.on( goog.events.EventType.KEYUP, function( e ) {
// On return get trimmed text
if ( e.keyCode !== goog.events.KeyCodes.ENTER ) {
return;
}
var text = goog.string.trim( input.value );
if ( !text) {
return;
}
// Create new model
list.newModel({
'title': text
});
input.value = '';
}, 'todo-entry' );
// Clear completed
this.click(function( e ) {
goog.array.forEach( list.get('completed'), function( model ) {
model.dispose();
});
}, 'clear-completed' );
// Toggle completed
this.click(function( e ) {
var checked = e.target.checked;
goog.array.forEach( list.getModels(), function( model ) {
model.set( 'completed', checked );
});
}, 'toggle-all' );
// Refresh the view on changes that effect the models order
this.anyModelChange(function() {
this.refresh();
list.save();
}, this );
// Toggle footer and main body
this.modelChange(function() {
this.showMainFooter( !!list.getLength() );
}, this );
this.showMainFooter( !!list.getLength() );
// Update counts
this.bind( 'completed', function( completedModels ) {
// Update "left" count
soy.renderElement(goog.dom.getElement('todo-count'),
todomvc.templates.itemsLeft, {
left: list.getLength() - completedModels.length
});
// Update clear button
var clearButton = goog.dom.getElement('clear-completed');
goog.dom.setTextContent( clearButton,
'Clear completed (' + completedModels.length + ')' );
goog.style.showElement( clearButton, completedModels.length );
// Update checkbox
var checkBox = this.getEls('.toggle-all')[0];
checkBox.checked = completedModels.length === list.getLength();
});
// Get the saved todos
list.fetch();
};
/**
* show or hide the footer.
*
* @param {boolean=} opt_hide whether to hide the footer.
*/
todomvc.listcontrol.prototype.showMainFooter = function( opt_hide ) {
var main = goog.dom.getElement('main');
var footer = goog.dom.getElementsByTagNameAndClass('footer')[0];
goog.style.showElement( main, opt_hide );
goog.style.showElement( footer, opt_hide );
};
/**
* sets the function to determine which children are returned by the control.
*
* @param {Function} filter to decide models returned.
*/
todomvc.listcontrol.prototype.setFilter = function( filter ) {
this.filter_ = filter;
this.refresh();
};
/**
* refreshes the view of the childen.
*/
todomvc.listcontrol.prototype.refresh = function() {
// Dispose and remove all the children.
this.forEachChild(function( child ) {
child.dispose();
});
this.removeChildren( true );
// Create new controls for the models
goog.array.forEach( this.getModel().getModels(this.filter_),
function( model ) {
var newModelControl = new todomvc.todocontrol( model );
this.addChild( newModelControl );
newModelControl.render( goog.dom.getElement('todo-list') );
}, this );
};
|
{
"content_hash": "491ded93a67c7c5278f5277ece7a9010",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 77,
"avg_line_length": 22.786127167630056,
"alnum_prop": 0.6745306950786403,
"repo_name": "1manStartup/todomvc",
"id": "b85fddfc92aa8fb31fa4afba0fbdc203535da887",
"size": "3942",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "labs/architecture-examples/plastronjs/js/controllers/listcontrol.js",
"mode": "33188",
"license": "mit",
"language": []
}
|
<?php
namespace Google\AdsApi\AdManager\v202208;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class RichMediaStudioCreative extends \Google\AdsApi\AdManager\v202208\BaseRichMediaStudioCreative
{
/**
* @var string $lockedOrientation
*/
protected $lockedOrientation = null;
/**
* @var boolean $isInterstitial
*/
protected $isInterstitial = null;
/**
* @param int $advertiserId
* @param int $id
* @param string $name
* @param \Google\AdsApi\AdManager\v202208\Size $size
* @param string $previewUrl
* @param string[] $policyLabels
* @param \Google\AdsApi\AdManager\v202208\AppliedLabel[] $appliedLabels
* @param \Google\AdsApi\AdManager\v202208\DateTime $lastModifiedDateTime
* @param \Google\AdsApi\AdManager\v202208\BaseCustomFieldValue[] $customFieldValues
* @param \Google\AdsApi\AdManager\v202208\ThirdPartyDataDeclaration $thirdPartyDataDeclaration
* @param int $studioCreativeId
* @param string $creativeFormat
* @param string $artworkType
* @param int $totalFileSize
* @param string[] $adTagKeys
* @param string[] $customKeyValues
* @param string $surveyUrl
* @param string $allImpressionsUrl
* @param string $richMediaImpressionsUrl
* @param string $backupImageImpressionsUrl
* @param string $overrideCss
* @param string $requiredFlashPluginVersion
* @param int $duration
* @param string $billingAttribute
* @param \Google\AdsApi\AdManager\v202208\RichMediaStudioChildAssetProperty[] $richMediaStudioChildAssetProperties
* @param string $sslScanResult
* @param string $sslManualOverride
* @param string $lockedOrientation
* @param boolean $isInterstitial
*/
public function __construct($advertiserId = null, $id = null, $name = null, $size = null, $previewUrl = null, array $policyLabels = null, array $appliedLabels = null, $lastModifiedDateTime = null, array $customFieldValues = null, $thirdPartyDataDeclaration = null, $studioCreativeId = null, $creativeFormat = null, $artworkType = null, $totalFileSize = null, array $adTagKeys = null, array $customKeyValues = null, $surveyUrl = null, $allImpressionsUrl = null, $richMediaImpressionsUrl = null, $backupImageImpressionsUrl = null, $overrideCss = null, $requiredFlashPluginVersion = null, $duration = null, $billingAttribute = null, array $richMediaStudioChildAssetProperties = null, $sslScanResult = null, $sslManualOverride = null, $lockedOrientation = null, $isInterstitial = null)
{
parent::__construct($advertiserId, $id, $name, $size, $previewUrl, $policyLabels, $appliedLabels, $lastModifiedDateTime, $customFieldValues, $thirdPartyDataDeclaration, $studioCreativeId, $creativeFormat, $artworkType, $totalFileSize, $adTagKeys, $customKeyValues, $surveyUrl, $allImpressionsUrl, $richMediaImpressionsUrl, $backupImageImpressionsUrl, $overrideCss, $requiredFlashPluginVersion, $duration, $billingAttribute, $richMediaStudioChildAssetProperties, $sslScanResult, $sslManualOverride);
$this->lockedOrientation = $lockedOrientation;
$this->isInterstitial = $isInterstitial;
}
/**
* @return string
*/
public function getLockedOrientation()
{
return $this->lockedOrientation;
}
/**
* @param string $lockedOrientation
* @return \Google\AdsApi\AdManager\v202208\RichMediaStudioCreative
*/
public function setLockedOrientation($lockedOrientation)
{
$this->lockedOrientation = $lockedOrientation;
return $this;
}
/**
* @return boolean
*/
public function getIsInterstitial()
{
return $this->isInterstitial;
}
/**
* @param boolean $isInterstitial
* @return \Google\AdsApi\AdManager\v202208\RichMediaStudioCreative
*/
public function setIsInterstitial($isInterstitial)
{
$this->isInterstitial = $isInterstitial;
return $this;
}
}
|
{
"content_hash": "a9c7f05ecaac9d68a9a83376f6dec218",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 785,
"avg_line_length": 41.416666666666664,
"alnum_prop": 0.7079979879275654,
"repo_name": "googleads/googleads-php-lib",
"id": "ebebd3b943d7a62c414c4407a5071ee786ab20f5",
"size": "3976",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Google/AdsApi/AdManager/v202208/RichMediaStudioCreative.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "11415914"
}
]
}
|
define({
"commonMedia": {
"mediaSelector": {
"lblSelect1": "Mídia",
"lblSelect2": "Conteúdo",
"lblMap": "Mapa",
"lblImage": "Imagem",
"lblVideo": "Vídeo",
"lblExternal": "Página da web",
"lblUpload": "Carregar",
"lblLink": "Vincular",
"disabled": "Este recurso foi desabilitado pelo Administrador",
"userLookup": "Carregar álbuns",
"notImplemented": "Não implementado ainda.",
"noData": "Nenhum álbum público localizado",
"thirdPartyTerms": "Ao utilizar um serviço de terceiros, você concorda com seus termos de serviço: "
},
"imageSelector": {
"lblStep1": "Escolha o serviço",
"lblStep2": "Selecione sua mídia",
"lblStep3": "Configurar"
},
"imageSelectorHome": {
"explain": "Carregue imagens da mídia social, <br /> ou diretamente de uma URL"
},
"imageSelectorUpload": {
"lblUploadButton": "procurar por uma imagem",
"lblDrop": "Baixar uma imagem aqui ou",
"infoUpload": "As imagens serão armazenadas na sua conta do ArcGIS e acessíveis somente dentro da sua história.",
"warningFileTypes": "A imagem pode ser .jpg, .png, .gif, ou .bmp",
"warningOneFile": "Um arquivo aceito de cada vez.",
"warningFileSize": "O arquivo excede o tamanho de transferência máximo permitido. Escolha outro arquivo.",
"tooltipRemove": "Exclua esta imagem não utilizada da sua conta do ArcGIS. <br> (Você precisará carregá-la novamente se você decidir utilizá-la posteriormente.)"
},
"imageSelectorFlickr": {
"userInputLbl": "Nome de usuário",
"signInMsg2": "Usuário não encontrado",
"loadingFailed": "Falha ao carregar"
},
"imageSelectorPicasa": {
"userInputLbl": "E-mail ou ID do Google",
"signInMsg2": "Conta não encontrada",
"howToFind": "Como encontrar um ID do Picasa",
"howToFind2": "Copie dígitos entre a primeira e segunda '/' de qualquer página do Picasa"
},
"videoSelectorCommon": {
"check": "Verificar",
"notFound": "Vídeo não encontrado",
"found": "Vídeo encontrado",
"select": "Selecionar este vídeo"
},
"videoSelectorHome": {
"other": "Outro"
},
"videoSelectorYoutube": {
"url": "Link de vídeo do YouTube",
"pageInputLbl": "Nome de usuário",
"lookupMsgError": "Usuário não encontrado",
"howToFind": "Como encontrar um nome de usuário do YouTube",
"howToFind2": "O nome de usuário é exibido abaixo dos vídeos",
"found": "Localizado",
"noData": "Nenhum vídeo público localizado",
"videoNotChecked": "O vídeo não foi verificado no YouTube, mas seu endereço parece bom.",
"checkFailedAPI": "Falha ao verificar o YouTube, verifique a chave de API do YouTube."
},
"videoSelectorVimeo": {
"url": "Link de vídeo do Vimeo"
},
"videoSelectorOther": {
"explain1": "Este mapa histórico não pode reproduzir arquivos de vídeo brutos (ex: AVI, mpeg), mas pode reproduzir vídeos hospedados com tocadores embutidos (ex: YouTube ou Vimeo).",
"explain2": "A maioria dos serviços de hospedagem de vídeo oferece este recurso. Encontre a opção para embutir o vídeo, copie o código fornecido e adicione-o à sua história utilizando a opção de conteúdo % WEBPAGE%.",
"explain3": "Alternativamente, você pode hospedar o vídeo com uma página de HTML que utiliza um tocador de vídeo como %EXAMPLE%. Você então adicionará a URL desta página de HTML na sua história como um %WEBPAGE%.",
"webpage": "Página da web"
},
"webpageSelectorHome": {
"lblUrl": "Link de página da web",
"lblEmbed": "Código embutido",
"lblMustUseHTTPS": "Os links para conteúdo da web devem iniciar com HTTPS",
"lblOR": "OU",
"lblError1": "Erro, limpe um dos dois campos de entrada.",
"lblError2": "O código embutido pode conter somente um %IFRAMETAG%",
"configure": "Configurar"
},
"mediaConfigure": {
"lblURL": "Link de imagem",
"lblURLPH": "O link pode terminar com .jpg, .png, .gif, ou .bmp",
"lblURLPHHTTPS": "https://www.example.com/image.jpg",
"lblURLError": "Esta imagem parece não ser válida. Especifique um link direto para um arquivo de imagem (sua URL geralmente terminará com .jpg ou .png). Links para uma página da web que contêm uma imagem não funcionarão.",
"lblURLErrorHTTPS": "Este link de imagem não é válido. A URL deve iniciar com HTTPS e finalizar com uma extensão de arquivo de imagem suportada (.jpg, .png, .gif, .bmp).",
"lblURLCheck": "Verificando imagem...",
"lblLabel": "Legenda da imagem",
"lblLabel1": "Legenda",
"lblLabel2": "Pairar texto",
"lblLabel3": "Nenhum",
"lblLabelPH": "Inserir algum texto...",
"lblMaximize": "Incluir um botão de maximizar no canto da imagem",
"lblMaximizeHelp": "Recomendado somente para fotos de alta qualidade",
"lblPosition": "Posição",
"lblPosition1": "Centralizar",
"lblPosition2": "Preencher",
"lblPosition3": "Ajustar",
"lblPosition4": "Esticar",
"lblPosition5": "Personalizar",
"lblURLHelp": "O link de imagem deve iniciar com HTTPS.<br><br>Para melhores resultados, as imagens devem ter menos que 400 KB. Utilize imagens JPG compactadas na qualidade de 80% e estas larguras de imagem recomendadas: 2000 pixels para a camada principal ou painel narrativo com botão maximizar, 1000 pixels para painel narrativo sem botão maximizar.<br><br>Se uma imagem vinculada desenhar lentamente, carregue-a na sua história para obter melhores resultados.",
"tooltipDimension": "O valor pode ser especificado em 'px' ou '%'",
"tooltipDimension2": "O valor tem que ser especificado em 'px'",
"lblPosition2Explain": "(pode recortar)",
"lblPosition3Explain": "(não cortará)",
"lblPosition3Explain2": "(a largura sempre se ajustará no painel)",
"lblPosition4Explain": "(pode distorcer)",
"unloadLbl": "Descarregar quando o leitor navegar",
"unloadHelp": "Se a página da web tiver mídia de áudio ou de vídeo, mantenha esta opção marcada para interromper a execução do conteúdo quando o leitor navegar fora da página. Desmarque isto, por exemplo, para manter uma trilha sonora tocando quando o leitor avançar pela história.<br />Se a página da web for um aplicativo, desmarque esta opção de forma que a história não recarregue se o leitor retornar a ela.",
"embedProtocolLabel": "Carregar página ao longo de uma conexão segura (HTTPS)",
"embedProtocolWarning1": "Se esta página não for carregada na sua história, ela não poderá ser embutida por razões de segurança da web. Como alternativa, adicione um link na sua narrativa para abrir a página em uma nova guia do navegador. <a href='http://links.esri.com/storymaps/blogs_mixed_content/' target='_blank'>Mais informações</a>",
"embedProtocolWarning2": "Se esta página não for carregada na sua história, desmarque esta opção e tente novamente. Se a página ainda não estiver carregada, ela não poderá ser embutida por razões de segurança da web. Como alternativa, adicione um link na sua narrativa para abrir a página em uma nova guia do navegador. <a href='http://links.esri.com/storymaps/blogs_mixed_content/' target='_blank'>Mais informações</a>",
"learn": "Mais informações",
"lblAltText": "Texto Alternativo",
"placeholderAltText": "Insira uma descrição desta mídia para leitores com deficiência visual ...",
"tooltipAltText": "Forneça uma descrição deste conteúdo de mídia que será utilizado pelas tecnologias assistidas, como o software leitor de tela. Uma descrição é opcional, mas recomendado para atender às diretrizes de acessibilidade da web, como WCAG e Seção 508."
},
"editorActionGeocode": {
"lblTitle": "Localizar um endereço ou lugar",
"mapMarkerExplain": "Usuários visualizarão um marcador de mapa ao clicar no link"
},
"editorActions": {
"navigate": "Navegar por outra entrada",
"remove": "Remover ação",
"preview": "Visualizar ação"
},
"editorActionMedia": {
"lblTitle": "Altere o conteúdo do Nível Principal"
},
"editorInlineMedia": {
"lblTitle": "Insira uma imagem, vídeo ou página da web"
}
}
});
|
{
"content_hash": "e8d81e04b01ed9df889a47a69be9d174",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 471,
"avg_line_length": 60.481751824817515,
"alnum_prop": 0.6830798937967656,
"repo_name": "pmacMaps/shortlist-storytelling-template-js",
"id": "705737df81615da89932daff9f6ee9a88151a003",
"size": "8456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/common/nls/pt-br/media.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "50802"
},
{
"name": "HTML",
"bytes": "25569"
},
{
"name": "JavaScript",
"bytes": "1881339"
}
]
}
|
package com.datasift.client.pylon;
import com.datasift.client.BaseDataSiftResult;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PylonTaskResult extends BaseDataSiftResult {
public PylonTaskResult() {
}
@JsonProperty
protected String id;
@JsonProperty("identity_id")
protected String identityId;
@JsonProperty("subscription_id")
protected String subscriptionId;
@JsonProperty
protected String name;
@JsonProperty
protected String type;
@JsonProperty
protected PylonTaskParameters parameters;
@JsonProperty
protected PylonTaskResultResult result;
@JsonProperty
protected String status;
@JsonProperty("created_at")
protected int createdAt;
@JsonProperty("updated_at")
protected int updatedAt;
public String getId() {
return id;
}
public String getIdentityId() {
return identityId;
}
public String getSubscriptionId() {
return subscriptionId;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public PylonTaskParameters getParameters() {
return parameters;
}
public PylonTaskResultResult getResult() {
return result;
}
public String getStatus() {
return status;
}
public int getCreatedAt() {
return createdAt;
}
public int getUpdatedAt() {
return updatedAt;
}
}
|
{
"content_hash": "fa528d77f0e54acd6759fbc3cd28d3f9",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 57,
"avg_line_length": 18.333333333333332,
"alnum_prop": 0.6579124579124579,
"repo_name": "datasift/datasift-java",
"id": "249e663dc4bd1e2cef049937d813b368b11fa371",
"size": "1485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/datasift/client/pylon/PylonTaskResult.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "538033"
},
{
"name": "Shell",
"bytes": "5123"
}
]
}
|
package stun
import (
"github.com/pkg/errors"
)
// https://tools.ietf.org/html/rfc5389#section-15.9
// The UNKNOWN-ATTRIBUTES attribute is present only in an error response
// when the response code in the ERROR-CODE attribute is 420.
//
// The attribute contains a list of 16-bit values, each of which
// represents an attribute type that was not understood by the server.
//
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Attribute 1 Type | Attribute 2 Type |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Attribute 3 Type | Attribute 4 Type ...
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
//
// Figure 8: Format of UNKNOWN-ATTRIBUTES Attribute
//
// Note: In [RFC3489], this field was padded to 32 by duplicating the
// last attribute. In this version of the specification, the normal
// padding rules for attributes are used instead.
// UnknownAttributes has several attrTypes
type UnknownAttributes struct {
Attributes []AttrType
}
const (
unknownAttributesMax = 4
)
// Pack AttrUnknownAttributes
func (u *UnknownAttributes) Pack(message *Message) error {
if len(u.Attributes) > unknownAttributesMax {
return errors.Errorf("UnknownAttributes only supports up to 4 attributes")
}
var v [8]byte
for i, attr := range u.Attributes {
enc.PutUint16(v[i*2:], uint16(attr))
}
message.AddAttribute(AttrUnknownAttributes, v[0:])
return nil
}
// Unpack always returns error
func (u *UnknownAttributes) Unpack(message *Message, rawAttribute *RawAttribute) error {
return errors.Errorf("stun.UnknownAttributes Unpack not implemented")
}
|
{
"content_hash": "24c56a59501bbcf3de53075bdfdf554b",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 88,
"avg_line_length": 33.17857142857143,
"alnum_prop": 0.5909580193756727,
"repo_name": "nobonobo/ssh-p2p",
"id": "e12aae4ac678c110ffd9f103675bece2a950686b",
"size": "1858",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/github.com/pions/pkg/stun/attr_unknown_attributes.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "9195"
},
{
"name": "Makefile",
"bytes": "292"
}
]
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>generic-environments: 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.2~camlp4 / generic-environments - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
generic-environments
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-14 05:12:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-14 05:12:06 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp4 4.02+7 Camlp4 is a system for writing extensible parsers for programming languages
conf-findutils 1 Virtual package relying on findutils
conf-which 1 Virtual package relying on which
coq 8.5.2~camlp4 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlbuild 0 Build system distributed with the OCaml compiler since OCaml 3.10.0
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/generic-environments"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/GenericEnvironments"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: generic environments" "keyword: typing" "keyword: type theory" "category: Mathematics/Logic/Type theory" ]
authors: [ "Emmanuel Polonowski <emmanuel.polonowski@u-pec.fr> [http://lacl.u-pec.fr/polonowski/]" ]
bug-reports: "https://github.com/coq-contribs/generic-environments/issues"
dev-repo: "git+https://github.com/coq-contribs/generic-environments.git"
synopsis: "Generic_Environments"
description: """
http://lacl.u-pec.fr/polonowski/Develop/Generic_Env/gen-env.html
Generic_Environments is a library which provides an abstract data type of environments, as a functor parameterized by a module defining variables, and a function which builds environments for such variables with any Type of type. Usual operations over environments are defined, along with an extensive set of basic and more advanced properties. Moreover, an implementation using lists satisfying and all the required properties is provided."""
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/generic-environments/archive/v8.7.0.tar.gz"
checksum: "md5=22f39ec272161c7c322e521682b1d9ae"
}
</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-generic-environments.8.7.0 coq.8.5.2~camlp4</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.2~camlp4).
The following dependencies couldn't be met:
- coq-generic-environments -> coq >= 8.7 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-generic-environments.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
|
{
"content_hash": "01c051c94758a587183347c42805e2d1",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 458,
"avg_line_length": 46.17751479289941,
"alnum_prop": 0.5716299333675039,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "0d34f0762899dfc2541e8040bfa9a425b5b6f240",
"size": "7829",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.5.2~camlp4/generic-environments/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": []
}
|
#define PNG_INTERNAL
#include "png.h"
#if defined(PNG_READ_SUPPORTED)
/* Create a PNG structure for reading, and allocate any memory needed. */
png_structp PNGAPI
png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn)
{
#ifdef PNG_USER_MEM_SUPPORTED
return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
}
/* Alternate create PNG structure for reading, and allocate any memory needed. */
png_structp PNGAPI
png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
png_malloc_ptr malloc_fn, png_free_ptr free_fn)
{
#endif /* PNG_USER_MEM_SUPPORTED */
png_structp png_ptr;
#ifdef PNG_SETJMP_SUPPORTED
#ifdef USE_FAR_KEYWORD
jmp_buf jmpbuf;
#endif
#endif
int i;
png_debug(1, "in png_create_read_struct\n");
#ifdef PNG_USER_MEM_SUPPORTED
png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
(png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
#else
png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
#endif
if (png_ptr == NULL)
return (NULL);
/* added at libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
#endif
#ifdef PNG_SETJMP_SUPPORTED
#ifdef USE_FAR_KEYWORD
if (setjmp(jmpbuf))
#else
if (setjmp(png_ptr->jmpbuf))
#endif
{
png_free(png_ptr, png_ptr->zbuf);
png_ptr->zbuf=NULL;
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)png_ptr,
(png_free_ptr)free_fn, (png_voidp)mem_ptr);
#else
png_destroy_struct((png_voidp)png_ptr);
#endif
return (NULL);
}
#ifdef USE_FAR_KEYWORD
png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
#endif
#endif
#ifdef PNG_USER_MEM_SUPPORTED
png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
#endif
png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
i=0;
do
{
if(user_png_ver[i] != png_libpng_ver[i])
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
} while (png_libpng_ver[i++]);
if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
{
/* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
* we must recompile any applications that use any older library version.
* For versions after libpng 1.0, we will be compatible, so we need
* only check the first digit.
*/
if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
(user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
(user_png_ver[0] == '0' && user_png_ver[2] < '9'))
{
#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
char msg[80];
if (user_png_ver)
{
png_snprintf(msg, 80,
"Application was compiled with png.h from libpng-%.20s",
user_png_ver);
png_warning(png_ptr, msg);
}
png_snprintf(msg, 80,
"Application is running with png.c from libpng-%.20s",
png_libpng_ver);
png_warning(png_ptr, msg);
#endif
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
png_ptr->flags=0;
#endif
png_error(png_ptr,
"Incompatible libpng version in application and library");
}
}
/* initialize zbuf - compression buffer */
png_ptr->zbuf_size = PNG_ZBUF_SIZE;
png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zstream.zfree = png_zfree;
png_ptr->zstream.opaque = (voidpf)png_ptr;
switch (inflateInit(&png_ptr->zstream))
{
case Z_OK: /* Do nothing */ break;
case Z_MEM_ERROR:
case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
default: png_error(png_ptr, "Unknown zlib error");
}
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
#ifdef PNG_SETJMP_SUPPORTED
/* Applications that neglect to set up their own setjmp() and then encounter
a png_error() will longjmp here. Since the jmpbuf is then meaningless we
abort instead of returning. */
#ifdef USE_FAR_KEYWORD
if (setjmp(jmpbuf))
PNG_ABORT();
png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
#else
if (setjmp(png_ptr->jmpbuf))
PNG_ABORT();
#endif
#endif
return (png_ptr);
}
#if defined(PNG_1_0_X) || defined(PNG_1_2_X)
/* Initialize PNG structure for reading, and allocate any memory needed.
This interface is deprecated in favour of the png_create_read_struct(),
and it will disappear as of libpng-1.3.0. */
#undef png_read_init
void PNGAPI
png_read_init(png_structp png_ptr)
{
/* We only come here via pre-1.0.7-compiled applications */
png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
}
void PNGAPI
png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
png_size_t png_struct_size, png_size_t png_info_size)
{
/* We only come here via pre-1.0.12-compiled applications */
if(png_ptr == NULL) return;
#if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
if(png_sizeof(png_struct) > png_struct_size ||
png_sizeof(png_info) > png_info_size)
{
char msg[80];
png_ptr->warning_fn=NULL;
if (user_png_ver)
{
png_snprintf(msg, 80,
"Application was compiled with png.h from libpng-%.20s",
user_png_ver);
png_warning(png_ptr, msg);
}
png_snprintf(msg, 80,
"Application is running with png.c from libpng-%.20s",
png_libpng_ver);
png_warning(png_ptr, msg);
}
#endif
if(png_sizeof(png_struct) > png_struct_size)
{
png_ptr->error_fn=NULL;
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
png_ptr->flags=0;
#endif
png_error(png_ptr,
"The png struct allocated by the application for reading is too small.");
}
if(png_sizeof(png_info) > png_info_size)
{
png_ptr->error_fn=NULL;
#ifdef PNG_ERROR_NUMBERS_SUPPORTED
png_ptr->flags=0;
#endif
png_error(png_ptr,
"The info struct allocated by application for reading is too small.");
}
png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
}
#endif /* PNG_1_0_X || PNG_1_2_X */
void PNGAPI
png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
png_size_t png_struct_size)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp; /* to save current jump buffer */
#endif
int i=0;
png_structp png_ptr=*ptr_ptr;
if(png_ptr == NULL) return;
do
{
if(user_png_ver[i] != png_libpng_ver[i])
{
#ifdef PNG_LEGACY_SUPPORTED
png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
#else
png_ptr->warning_fn=NULL;
png_warning(png_ptr,
"Application uses deprecated png_read_init() and should be recompiled.");
break;
#endif
}
} while (png_libpng_ver[i++]);
png_debug(1, "in png_read_init_3\n");
#ifdef PNG_SETJMP_SUPPORTED
/* save jump buffer and error functions */
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
#endif
if(png_sizeof(png_struct) > png_struct_size)
{
png_destroy_struct(png_ptr);
*ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
png_ptr = *ptr_ptr;
}
/* reset all variables to 0 */
png_memset(png_ptr, 0, png_sizeof (png_struct));
#ifdef PNG_SETJMP_SUPPORTED
/* restore jump buffer */
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
#endif
/* added at libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
#endif
/* initialize zbuf - compression buffer */
png_ptr->zbuf_size = PNG_ZBUF_SIZE;
png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)png_ptr->zbuf_size);
png_ptr->zstream.zalloc = png_zalloc;
png_ptr->zstream.zfree = png_zfree;
png_ptr->zstream.opaque = (voidpf)png_ptr;
switch (inflateInit(&png_ptr->zstream))
{
case Z_OK: /* Do nothing */ break;
case Z_MEM_ERROR:
case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
default: png_error(png_ptr, "Unknown zlib error");
}
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
}
#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
/* Read the information before the actual image data. This has been
* changed in v0.90 to allow reading a file that already has the magic
* bytes read from the stream. You can tell libpng how many bytes have
* been read from the beginning of the stream (up to the maximum of 8)
* via png_set_sig_bytes(), and we will only check the remaining bytes
* here. The application can then have access to the signature bytes we
* read if it is determined that this isn't a valid PNG file.
*/
void PNGAPI
png_read_info(png_structp png_ptr, png_infop info_ptr)
{
if(png_ptr == NULL) return;
png_debug(1, "in png_read_info\n");
/* If we haven't checked all of the PNG signature bytes, do so now. */
if (png_ptr->sig_bytes < 8)
{
png_size_t num_checked = png_ptr->sig_bytes,
num_to_check = 8 - num_checked;
png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
png_ptr->sig_bytes = 8;
if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
{
if (num_checked < 4 &&
png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
png_error(png_ptr, "Not a PNG file");
else
png_error(png_ptr, "PNG file corrupted by ASCII conversion");
}
if (num_checked < 3)
png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
}
for(;;)
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_CONST PNG_IHDR;
PNG_CONST PNG_IDAT;
PNG_CONST PNG_IEND;
PNG_CONST PNG_PLTE;
#if defined(PNG_READ_bKGD_SUPPORTED)
PNG_CONST PNG_bKGD;
#endif
#if defined(PNG_READ_cHRM_SUPPORTED)
PNG_CONST PNG_cHRM;
#endif
#if defined(PNG_READ_gAMA_SUPPORTED)
PNG_CONST PNG_gAMA;
#endif
#if defined(PNG_READ_hIST_SUPPORTED)
PNG_CONST PNG_hIST;
#endif
#if defined(PNG_READ_iCCP_SUPPORTED)
PNG_CONST PNG_iCCP;
#endif
#if defined(PNG_READ_iTXt_SUPPORTED)
PNG_CONST PNG_iTXt;
#endif
#if defined(PNG_READ_oFFs_SUPPORTED)
PNG_CONST PNG_oFFs;
#endif
#if defined(PNG_READ_pCAL_SUPPORTED)
PNG_CONST PNG_pCAL;
#endif
#if defined(PNG_READ_pHYs_SUPPORTED)
PNG_CONST PNG_pHYs;
#endif
#if defined(PNG_READ_sBIT_SUPPORTED)
PNG_CONST PNG_sBIT;
#endif
#if defined(PNG_READ_sCAL_SUPPORTED)
PNG_CONST PNG_sCAL;
#endif
#if defined(PNG_READ_sPLT_SUPPORTED)
PNG_CONST PNG_sPLT;
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
PNG_CONST PNG_sRGB;
#endif
#if defined(PNG_READ_tEXt_SUPPORTED)
PNG_CONST PNG_tEXt;
#endif
#if defined(PNG_READ_tIME_SUPPORTED)
PNG_CONST PNG_tIME;
#endif
#if defined(PNG_READ_tRNS_SUPPORTED)
PNG_CONST PNG_tRNS;
#endif
#if defined(PNG_READ_zTXt_SUPPORTED)
PNG_CONST PNG_zTXt;
#endif
#endif /* PNG_USE_LOCAL_ARRAYS */
png_byte chunk_length[4];
png_uint_32 length;
png_read_data(png_ptr, chunk_length, 4);
length = png_get_uint_31(png_ptr,chunk_length);
png_reset_crc(png_ptr);
png_crc_read(png_ptr, png_ptr->chunk_name, 4);
png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
length);
/* This should be a binary subdivision search or a hash for
* matching the chunk name rather than a linear search.
*/
if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
if(png_ptr->mode & PNG_AFTER_IDAT)
png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
png_handle_IHDR(png_ptr, info_ptr, length);
else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
png_handle_IEND(png_ptr, info_ptr, length);
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
{
if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
png_ptr->mode |= PNG_HAVE_IDAT;
png_handle_unknown(png_ptr, info_ptr, length);
if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
png_ptr->mode |= PNG_HAVE_PLTE;
else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
{
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before IDAT");
else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
!(png_ptr->mode & PNG_HAVE_PLTE))
png_error(png_ptr, "Missing PLTE before IDAT");
break;
}
}
#endif
else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
png_handle_PLTE(png_ptr, info_ptr, length);
else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
{
if (!(png_ptr->mode & PNG_HAVE_IHDR))
png_error(png_ptr, "Missing IHDR before IDAT");
else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
!(png_ptr->mode & PNG_HAVE_PLTE))
png_error(png_ptr, "Missing PLTE before IDAT");
png_ptr->idat_size = length;
png_ptr->mode |= PNG_HAVE_IDAT;
break;
}
#if defined(PNG_READ_bKGD_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
png_handle_bKGD(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_cHRM_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
png_handle_cHRM(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_gAMA_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
png_handle_gAMA(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_hIST_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
png_handle_hIST(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_oFFs_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
png_handle_oFFs(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_pCAL_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
png_handle_pCAL(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_sCAL_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
png_handle_sCAL(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_pHYs_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
png_handle_pHYs(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_sBIT_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
png_handle_sBIT(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
png_handle_sRGB(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_iCCP_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
png_handle_iCCP(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_sPLT_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
png_handle_sPLT(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_tEXt_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
png_handle_tEXt(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_tIME_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
png_handle_tIME(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_tRNS_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
png_handle_tRNS(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_zTXt_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
png_handle_zTXt(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_iTXt_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
png_handle_iTXt(png_ptr, info_ptr, length);
#endif
else
png_handle_unknown(png_ptr, info_ptr, length);
}
}
#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
/* optional call to update the users info_ptr structure */
void PNGAPI
png_read_update_info(png_structp png_ptr, png_infop info_ptr)
{
png_debug(1, "in png_read_update_info\n");
if(png_ptr == NULL) return;
if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
png_read_start_row(png_ptr);
else
png_warning(png_ptr,
"Ignoring extra png_read_update_info() call; row buffer not reallocated");
png_read_transform_info(png_ptr, info_ptr);
}
#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
/* Initialize palette, background, etc, after transformations
* are set, but before any reading takes place. This allows
* the user to obtain a gamma-corrected palette, for example.
* If the user doesn't call this, we will do it ourselves.
*/
void PNGAPI
png_start_read_image(png_structp png_ptr)
{
png_debug(1, "in png_start_read_image\n");
if(png_ptr == NULL) return;
if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
png_read_start_row(png_ptr);
}
#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
void PNGAPI
png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_CONST PNG_IDAT;
PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
0xff};
PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
#endif
int ret;
if(png_ptr == NULL) return;
png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
png_ptr->row_number, png_ptr->pass);
if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
png_read_start_row(png_ptr);
if (png_ptr->row_number == 0 && png_ptr->pass == 0)
{
/* check for transforms that have been set but were defined out */
#if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
if (png_ptr->transformations & PNG_INVERT_MONO)
png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
if (png_ptr->transformations & PNG_FILLER)
png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
if (png_ptr->transformations & PNG_PACKSWAP)
png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
if (png_ptr->transformations & PNG_PACK)
png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
if (png_ptr->transformations & PNG_SHIFT)
png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
if (png_ptr->transformations & PNG_BGR)
png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
#endif
#if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
if (png_ptr->transformations & PNG_SWAP_BYTES)
png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
#endif
}
#if defined(PNG_READ_INTERLACING_SUPPORTED)
/* if interlaced and we do not need a new row, combine row and return */
if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
{
switch (png_ptr->pass)
{
case 0:
if (png_ptr->row_number & 0x07)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 1:
if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 2:
if ((png_ptr->row_number & 0x07) != 4)
{
if (dsp_row != NULL && (png_ptr->row_number & 4))
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 3:
if ((png_ptr->row_number & 3) || png_ptr->width < 3)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 4:
if ((png_ptr->row_number & 3) != 2)
{
if (dsp_row != NULL && (png_ptr->row_number & 2))
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 5:
if ((png_ptr->row_number & 1) || png_ptr->width < 2)
{
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
png_read_finish_row(png_ptr);
return;
}
break;
case 6:
if (!(png_ptr->row_number & 1))
{
png_read_finish_row(png_ptr);
return;
}
break;
}
}
#endif
if (!(png_ptr->mode & PNG_HAVE_IDAT))
png_error(png_ptr, "Invalid attempt to read row data");
png_ptr->zstream.next_out = png_ptr->row_buf;
png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
do
{
if (!(png_ptr->zstream.avail_in))
{
while (!png_ptr->idat_size)
{
png_byte chunk_length[4];
png_crc_finish(png_ptr, 0);
png_read_data(png_ptr, chunk_length, 4);
png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
png_reset_crc(png_ptr);
png_crc_read(png_ptr, png_ptr->chunk_name, 4);
if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
png_error(png_ptr, "Not enough image data");
}
png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_in = png_ptr->zbuf;
if (png_ptr->zbuf_size > png_ptr->idat_size)
png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
png_crc_read(png_ptr, png_ptr->zbuf,
(png_size_t)png_ptr->zstream.avail_in);
png_ptr->idat_size -= png_ptr->zstream.avail_in;
}
ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
if (ret == Z_STREAM_END)
{
if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
png_ptr->idat_size)
png_error(png_ptr, "Extra compressed data");
png_ptr->mode |= PNG_AFTER_IDAT;
png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
break;
}
if (ret != Z_OK)
png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
"Decompression error");
} while (png_ptr->zstream.avail_out);
png_ptr->row_info.color_type = png_ptr->color_type;
png_ptr->row_info.width = png_ptr->iwidth;
png_ptr->row_info.channels = png_ptr->channels;
png_ptr->row_info.bit_depth = png_ptr->bit_depth;
png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
png_ptr->row_info.width);
if(png_ptr->row_buf[0])
png_read_filter_row(png_ptr, &(png_ptr->row_info),
png_ptr->row_buf + 1, png_ptr->prev_row + 1,
(int)(png_ptr->row_buf[0]));
png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
png_ptr->rowbytes + 1);
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
(png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
{
/* Intrapixel differencing */
png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
}
#endif
if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
png_do_read_transformations(png_ptr);
#if defined(PNG_READ_INTERLACING_SUPPORTED)
/* blow up interlaced rows to full size */
if (png_ptr->interlaced &&
(png_ptr->transformations & PNG_INTERLACE))
{
if (png_ptr->pass < 6)
/* old interface (pre-1.0.9):
png_do_read_interlace(&(png_ptr->row_info),
png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
*/
png_do_read_interlace(png_ptr);
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row,
png_pass_dsp_mask[png_ptr->pass]);
if (row != NULL)
png_combine_row(png_ptr, row,
png_pass_mask[png_ptr->pass]);
}
else
#endif
{
if (row != NULL)
png_combine_row(png_ptr, row, 0xff);
if (dsp_row != NULL)
png_combine_row(png_ptr, dsp_row, 0xff);
}
png_read_finish_row(png_ptr);
if (png_ptr->read_row_fn != NULL)
(*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
}
#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
/* Read one or more rows of image data. If the image is interlaced,
* and png_set_interlace_handling() has been called, the rows need to
* contain the contents of the rows from the previous pass. If the
* image has alpha or transparency, and png_handle_alpha()[*] has been
* called, the rows contents must be initialized to the contents of the
* screen.
*
* "row" holds the actual image, and pixels are placed in it
* as they arrive. If the image is displayed after each pass, it will
* appear to "sparkle" in. "display_row" can be used to display a
* "chunky" progressive image, with finer detail added as it becomes
* available. If you do not want this "chunky" display, you may pass
* NULL for display_row. If you do not want the sparkle display, and
* you have not called png_handle_alpha(), you may pass NULL for rows.
* If you have called png_handle_alpha(), and the image has either an
* alpha channel or a transparency chunk, you must provide a buffer for
* rows. In this case, you do not have to provide a display_row buffer
* also, but you may. If the image is not interlaced, or if you have
* not called png_set_interlace_handling(), the display_row buffer will
* be ignored, so pass NULL to it.
*
* [*] png_handle_alpha() does not exist yet, as of this version of libpng
*/
void PNGAPI
png_read_rows(png_structp png_ptr, png_bytepp row,
png_bytepp display_row, png_uint_32 num_rows)
{
png_uint_32 i;
png_bytepp rp;
png_bytepp dp;
png_debug(1, "in png_read_rows\n");
if(png_ptr == NULL) return;
rp = row;
dp = display_row;
if (rp != NULL && dp != NULL)
for (i = 0; i < num_rows; i++)
{
png_bytep rptr = *rp++;
png_bytep dptr = *dp++;
png_read_row(png_ptr, rptr, dptr);
}
else if(rp != NULL)
for (i = 0; i < num_rows; i++)
{
png_bytep rptr = *rp;
png_read_row(png_ptr, rptr, png_bytep_NULL);
rp++;
}
else if(dp != NULL)
for (i = 0; i < num_rows; i++)
{
png_bytep dptr = *dp;
png_read_row(png_ptr, png_bytep_NULL, dptr);
dp++;
}
}
#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
/* Read the entire image. If the image has an alpha channel or a tRNS
* chunk, and you have called png_handle_alpha()[*], you will need to
* initialize the image to the current image that PNG will be overlaying.
* We set the num_rows again here, in case it was incorrectly set in
* png_read_start_row() by a call to png_read_update_info() or
* png_start_read_image() if png_set_interlace_handling() wasn't called
* prior to either of these functions like it should have been. You can
* only call this function once. If you desire to have an image for
* each pass of a interlaced image, use png_read_rows() instead.
*
* [*] png_handle_alpha() does not exist yet, as of this version of libpng
*/
void PNGAPI
png_read_image(png_structp png_ptr, png_bytepp image)
{
png_uint_32 i,image_height;
int pass, j;
png_bytepp rp;
png_debug(1, "in png_read_image\n");
if(png_ptr == NULL) return;
#ifdef PNG_READ_INTERLACING_SUPPORTED
pass = png_set_interlace_handling(png_ptr);
#else
if (png_ptr->interlaced)
png_error(png_ptr,
"Cannot read interlaced image -- interlace handler disabled.");
pass = 1;
#endif
image_height=png_ptr->height;
png_ptr->num_rows = image_height; /* Make sure this is set correctly */
for (j = 0; j < pass; j++)
{
rp = image;
for (i = 0; i < image_height; i++)
{
png_read_row(png_ptr, *rp, png_bytep_NULL);
rp++;
}
}
}
#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
/* Read the end of the PNG file. Will not read past the end of the
* file, will verify the end is accurate, and will read any comments
* or time information at the end of the file, if info is not NULL.
*/
void PNGAPI
png_read_end(png_structp png_ptr, png_infop info_ptr)
{
png_byte chunk_length[4];
png_uint_32 length;
png_debug(1, "in png_read_end\n");
if(png_ptr == NULL) return;
png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
do
{
#ifdef PNG_USE_LOCAL_ARRAYS
PNG_CONST PNG_IHDR;
PNG_CONST PNG_IDAT;
PNG_CONST PNG_IEND;
PNG_CONST PNG_PLTE;
#if defined(PNG_READ_bKGD_SUPPORTED)
PNG_CONST PNG_bKGD;
#endif
#if defined(PNG_READ_cHRM_SUPPORTED)
PNG_CONST PNG_cHRM;
#endif
#if defined(PNG_READ_gAMA_SUPPORTED)
PNG_CONST PNG_gAMA;
#endif
#if defined(PNG_READ_hIST_SUPPORTED)
PNG_CONST PNG_hIST;
#endif
#if defined(PNG_READ_iCCP_SUPPORTED)
PNG_CONST PNG_iCCP;
#endif
#if defined(PNG_READ_iTXt_SUPPORTED)
PNG_CONST PNG_iTXt;
#endif
#if defined(PNG_READ_oFFs_SUPPORTED)
PNG_CONST PNG_oFFs;
#endif
#if defined(PNG_READ_pCAL_SUPPORTED)
PNG_CONST PNG_pCAL;
#endif
#if defined(PNG_READ_pHYs_SUPPORTED)
PNG_CONST PNG_pHYs;
#endif
#if defined(PNG_READ_sBIT_SUPPORTED)
PNG_CONST PNG_sBIT;
#endif
#if defined(PNG_READ_sCAL_SUPPORTED)
PNG_CONST PNG_sCAL;
#endif
#if defined(PNG_READ_sPLT_SUPPORTED)
PNG_CONST PNG_sPLT;
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
PNG_CONST PNG_sRGB;
#endif
#if defined(PNG_READ_tEXt_SUPPORTED)
PNG_CONST PNG_tEXt;
#endif
#if defined(PNG_READ_tIME_SUPPORTED)
PNG_CONST PNG_tIME;
#endif
#if defined(PNG_READ_tRNS_SUPPORTED)
PNG_CONST PNG_tRNS;
#endif
#if defined(PNG_READ_zTXt_SUPPORTED)
PNG_CONST PNG_zTXt;
#endif
#endif /* PNG_USE_LOCAL_ARRAYS */
png_read_data(png_ptr, chunk_length, 4);
length = png_get_uint_31(png_ptr,chunk_length);
png_reset_crc(png_ptr);
png_crc_read(png_ptr, png_ptr->chunk_name, 4);
png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
png_handle_IHDR(png_ptr, info_ptr, length);
else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
png_handle_IEND(png_ptr, info_ptr, length);
#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
{
if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
{
if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
png_error(png_ptr, "Too many IDAT's found");
}
png_handle_unknown(png_ptr, info_ptr, length);
if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
png_ptr->mode |= PNG_HAVE_PLTE;
}
#endif
else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
{
/* Zero length IDATs are legal after the last IDAT has been
* read, but not after other chunks have been read.
*/
if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
png_error(png_ptr, "Too many IDAT's found");
png_crc_finish(png_ptr, length);
}
else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
png_handle_PLTE(png_ptr, info_ptr, length);
#if defined(PNG_READ_bKGD_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
png_handle_bKGD(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_cHRM_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
png_handle_cHRM(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_gAMA_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
png_handle_gAMA(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_hIST_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
png_handle_hIST(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_oFFs_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
png_handle_oFFs(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_pCAL_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
png_handle_pCAL(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_sCAL_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
png_handle_sCAL(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_pHYs_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
png_handle_pHYs(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_sBIT_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
png_handle_sBIT(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_sRGB_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
png_handle_sRGB(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_iCCP_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
png_handle_iCCP(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_sPLT_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
png_handle_sPLT(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_tEXt_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
png_handle_tEXt(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_tIME_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
png_handle_tIME(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_tRNS_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
png_handle_tRNS(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_zTXt_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
png_handle_zTXt(png_ptr, info_ptr, length);
#endif
#if defined(PNG_READ_iTXt_SUPPORTED)
else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
png_handle_iTXt(png_ptr, info_ptr, length);
#endif
else
png_handle_unknown(png_ptr, info_ptr, length);
} while (!(png_ptr->mode & PNG_HAVE_IEND));
}
#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
/* free all memory used by the read */
void PNGAPI
png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
png_infopp end_info_ptr_ptr)
{
png_structp png_ptr = NULL;
png_infop info_ptr = NULL, end_info_ptr = NULL;
#ifdef PNG_USER_MEM_SUPPORTED
png_free_ptr free_fn = NULL;
png_voidp mem_ptr = NULL;
#endif
png_debug(1, "in png_destroy_read_struct\n");
if (png_ptr_ptr != NULL)
{
png_ptr = *png_ptr_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
free_fn = png_ptr->free_fn;
mem_ptr = png_ptr->mem_ptr;
#endif
}
if (info_ptr_ptr != NULL)
info_ptr = *info_ptr_ptr;
if (end_info_ptr_ptr != NULL)
end_info_ptr = *end_info_ptr_ptr;
png_read_destroy(png_ptr, info_ptr, end_info_ptr);
if (info_ptr != NULL)
{
#if defined(PNG_TEXT_SUPPORTED)
png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
#endif
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
(png_voidp)mem_ptr);
#else
png_destroy_struct((png_voidp)info_ptr);
#endif
*info_ptr_ptr = NULL;
}
if (end_info_ptr != NULL)
{
#if defined(PNG_READ_TEXT_SUPPORTED)
png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
#endif
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
(png_voidp)mem_ptr);
#else
png_destroy_struct((png_voidp)end_info_ptr);
#endif
*end_info_ptr_ptr = NULL;
}
if (png_ptr != NULL)
{
#ifdef PNG_USER_MEM_SUPPORTED
png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
(png_voidp)mem_ptr);
#else
png_destroy_struct((png_voidp)png_ptr);
#endif
*png_ptr_ptr = NULL;
}
}
/* free all memory used by the read (old method) */
void /* PRIVATE */
png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
{
#ifdef PNG_SETJMP_SUPPORTED
jmp_buf tmp_jmp;
#endif
png_error_ptr error_fn;
png_error_ptr warning_fn;
png_voidp error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_free_ptr free_fn;
#endif
png_debug(1, "in png_read_destroy\n");
if (info_ptr != NULL)
png_info_destroy(png_ptr, info_ptr);
if (end_info_ptr != NULL)
png_info_destroy(png_ptr, end_info_ptr);
png_free(png_ptr, png_ptr->zbuf);
png_free(png_ptr, png_ptr->big_row_buf);
png_free(png_ptr, png_ptr->prev_row);
#if defined(PNG_READ_DITHER_SUPPORTED)
png_free(png_ptr, png_ptr->palette_lookup);
png_free(png_ptr, png_ptr->dither_index);
#endif
#if defined(PNG_READ_GAMMA_SUPPORTED)
png_free(png_ptr, png_ptr->gamma_table);
#endif
#if defined(PNG_READ_BACKGROUND_SUPPORTED)
png_free(png_ptr, png_ptr->gamma_from_1);
png_free(png_ptr, png_ptr->gamma_to_1);
#endif
#ifdef PNG_FREE_ME_SUPPORTED
if (png_ptr->free_me & PNG_FREE_PLTE)
png_zfree(png_ptr, png_ptr->palette);
png_ptr->free_me &= ~PNG_FREE_PLTE;
#else
if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
png_zfree(png_ptr, png_ptr->palette);
png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
#endif
#if defined(PNG_tRNS_SUPPORTED) || \
defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
#ifdef PNG_FREE_ME_SUPPORTED
if (png_ptr->free_me & PNG_FREE_TRNS)
png_free(png_ptr, png_ptr->trans);
png_ptr->free_me &= ~PNG_FREE_TRNS;
#else
if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
png_free(png_ptr, png_ptr->trans);
png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
#endif
#endif
#if defined(PNG_READ_hIST_SUPPORTED)
#ifdef PNG_FREE_ME_SUPPORTED
if (png_ptr->free_me & PNG_FREE_HIST)
png_free(png_ptr, png_ptr->hist);
png_ptr->free_me &= ~PNG_FREE_HIST;
#else
if (png_ptr->flags & PNG_FLAG_FREE_HIST)
png_free(png_ptr, png_ptr->hist);
png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
#endif
#endif
#if defined(PNG_READ_GAMMA_SUPPORTED)
if (png_ptr->gamma_16_table != NULL)
{
int i;
int istop = (1 << (8 - png_ptr->gamma_shift));
for (i = 0; i < istop; i++)
{
png_free(png_ptr, png_ptr->gamma_16_table[i]);
}
png_free(png_ptr, png_ptr->gamma_16_table);
}
#if defined(PNG_READ_BACKGROUND_SUPPORTED)
if (png_ptr->gamma_16_from_1 != NULL)
{
int i;
int istop = (1 << (8 - png_ptr->gamma_shift));
for (i = 0; i < istop; i++)
{
png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
}
png_free(png_ptr, png_ptr->gamma_16_from_1);
}
if (png_ptr->gamma_16_to_1 != NULL)
{
int i;
int istop = (1 << (8 - png_ptr->gamma_shift));
for (i = 0; i < istop; i++)
{
png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
}
png_free(png_ptr, png_ptr->gamma_16_to_1);
}
#endif
#endif
#if defined(PNG_TIME_RFC1123_SUPPORTED)
png_free(png_ptr, png_ptr->time_buffer);
#endif
inflateEnd(&png_ptr->zstream);
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
png_free(png_ptr, png_ptr->save_buffer);
#endif
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED
#ifdef PNG_TEXT_SUPPORTED
png_free(png_ptr, png_ptr->current_text);
#endif /* PNG_TEXT_SUPPORTED */
#endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
/* Save the important info out of the png_struct, in case it is
* being used again.
*/
#ifdef PNG_SETJMP_SUPPORTED
png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
#endif
error_fn = png_ptr->error_fn;
warning_fn = png_ptr->warning_fn;
error_ptr = png_ptr->error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
free_fn = png_ptr->free_fn;
#endif
png_memset(png_ptr, 0, png_sizeof (png_struct));
png_ptr->error_fn = error_fn;
png_ptr->warning_fn = warning_fn;
png_ptr->error_ptr = error_ptr;
#ifdef PNG_USER_MEM_SUPPORTED
png_ptr->free_fn = free_fn;
#endif
#ifdef PNG_SETJMP_SUPPORTED
png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
#endif
}
void PNGAPI
png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
{
if(png_ptr == NULL) return;
png_ptr->read_row_fn = read_row_fn;
}
#ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
#if defined(PNG_INFO_IMAGE_SUPPORTED)
void PNGAPI
png_read_png(png_structp png_ptr, png_infop info_ptr,
int transforms,
voidp params)
{
int row;
if(png_ptr == NULL) return;
#if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
/* invert the alpha channel from opacity to transparency
*/
if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
png_set_invert_alpha(png_ptr);
#endif
/* png_read_info() gives us all of the information from the
* PNG file before the first IDAT (image data chunk).
*/
png_read_info(png_ptr, info_ptr);
if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
png_error(png_ptr,"Image is too high to process with png_read_png()");
/* -------------- image transformations start here ------------------- */
#if defined(PNG_READ_16_TO_8_SUPPORTED)
/* tell libpng to strip 16 bit/color files down to 8 bits per color
*/
if (transforms & PNG_TRANSFORM_STRIP_16)
png_set_strip_16(png_ptr);
#endif
#if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
/* Strip alpha bytes from the input data without combining with
* the background (not recommended).
*/
if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
png_set_strip_alpha(png_ptr);
#endif
#if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
/* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
* byte into separate bytes (useful for paletted and grayscale images).
*/
if (transforms & PNG_TRANSFORM_PACKING)
png_set_packing(png_ptr);
#endif
#if defined(PNG_READ_PACKSWAP_SUPPORTED)
/* Change the order of packed pixels to least significant bit first
* (not useful if you are using png_set_packing).
*/
if (transforms & PNG_TRANSFORM_PACKSWAP)
png_set_packswap(png_ptr);
#endif
#if defined(PNG_READ_EXPAND_SUPPORTED)
/* Expand paletted colors into true RGB triplets
* Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
* Expand paletted or RGB images with transparency to full alpha
* channels so the data will be available as RGBA quartets.
*/
if (transforms & PNG_TRANSFORM_EXPAND)
if ((png_ptr->bit_depth < 8) ||
(png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
(png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
png_set_expand(png_ptr);
#endif
/* We don't handle background color or gamma transformation or dithering.
*/
#if defined(PNG_READ_INVERT_SUPPORTED)
/* invert monochrome files to have 0 as white and 1 as black
*/
if (transforms & PNG_TRANSFORM_INVERT_MONO)
png_set_invert_mono(png_ptr);
#endif
#if defined(PNG_READ_SHIFT_SUPPORTED)
/* If you want to shift the pixel values from the range [0,255] or
* [0,65535] to the original [0,7] or [0,31], or whatever range the
* colors were originally in:
*/
if ((transforms & PNG_TRANSFORM_SHIFT)
&& png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
{
png_color_8p sig_bit;
png_get_sBIT(png_ptr, info_ptr, &sig_bit);
png_set_shift(png_ptr, sig_bit);
}
#endif
#if defined(PNG_READ_BGR_SUPPORTED)
/* flip the RGB pixels to BGR (or RGBA to BGRA)
*/
if (transforms & PNG_TRANSFORM_BGR)
png_set_bgr(png_ptr);
#endif
#if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
/* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
*/
if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
png_set_swap_alpha(png_ptr);
#endif
#if defined(PNG_READ_SWAP_SUPPORTED)
/* swap bytes of 16 bit files to least significant byte first
*/
if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
png_set_swap(png_ptr);
#endif
/* We don't handle adding filler bytes */
/* Optional call to gamma correct and add the background to the palette
* and update info structure. REQUIRED if you are expecting libpng to
* update the palette for you (i.e., you selected such a transform above).
*/
png_read_update_info(png_ptr, info_ptr);
/* -------------- image transformations end here ------------------- */
#ifdef PNG_FREE_ME_SUPPORTED
png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
#endif
if(info_ptr->row_pointers == NULL)
{
info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
info_ptr->height * png_sizeof(png_bytep));
#ifdef PNG_FREE_ME_SUPPORTED
info_ptr->free_me |= PNG_FREE_ROWS;
#endif
for (row = 0; row < (int)info_ptr->height; row++)
{
info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
png_get_rowbytes(png_ptr, info_ptr));
}
}
png_read_image(png_ptr, info_ptr->row_pointers);
info_ptr->valid |= PNG_INFO_IDAT;
/* read rest of file, and get additional chunks in info_ptr - REQUIRED */
png_read_end(png_ptr, info_ptr);
transforms = transforms; /* quiet compiler warnings */
params = params;
}
#endif /* PNG_INFO_IMAGE_SUPPORTED */
#endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
#endif /* PNG_READ_SUPPORTED */
|
{
"content_hash": "e5ce327965e020f82d6b83a721518d36",
"timestamp": "",
"source": "github",
"line_count": 1463,
"max_line_length": 82,
"avg_line_length": 33.1203007518797,
"alnum_prop": 0.6048498606954906,
"repo_name": "hgl888/TeamTalk",
"id": "1f3da3f97d1b936d0ed8e815bffab1ca699b14ce",
"size": "48912",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "win-client/3rdParty/src/cxImage/png/pngread.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "954"
},
{
"name": "C",
"bytes": "6876692"
},
{
"name": "C++",
"bytes": "6166474"
},
{
"name": "CMake",
"bytes": "18145"
},
{
"name": "CSS",
"bytes": "130576"
},
{
"name": "GLSL",
"bytes": "122436"
},
{
"name": "Groff",
"bytes": "3850"
},
{
"name": "HTML",
"bytes": "31811"
},
{
"name": "Java",
"bytes": "1838380"
},
{
"name": "JavaScript",
"bytes": "240007"
},
{
"name": "M4",
"bytes": "1876"
},
{
"name": "Makefile",
"bytes": "219138"
},
{
"name": "Matlab",
"bytes": "4296"
},
{
"name": "Objective-C",
"bytes": "21065461"
},
{
"name": "Objective-C++",
"bytes": "90309"
},
{
"name": "PHP",
"bytes": "1387624"
},
{
"name": "Protocol Buffer",
"bytes": "401345"
},
{
"name": "Python",
"bytes": "92019"
},
{
"name": "Ruby",
"bytes": "8845"
},
{
"name": "Shell",
"bytes": "82354"
}
]
}
|
import { MotionSubmitter } from './motion-submitter';
import { MotionLog } from './motion-log';
import { MotionComment } from './motion-comment';
import { AgendaBaseModel } from '../base/agenda-base-model';
import { SearchRepresentation } from '../../../core/services/search.service';
import { MotionPoll } from './motion-poll';
/**
* Representation of Motion.
*
* Slightly Defined cause heavy maintaince on server side.
*
* @ignore
*/
export class Motion extends AgendaBaseModel {
public id: number;
public identifier: string;
public title: string;
public text: string;
public reason: string;
public amendment_paragraphs: string[];
public modified_final_version: string;
public parent_id: number;
public category_id: number;
public motion_block_id: number;
public origin: string;
public submitters: MotionSubmitter[];
public supporters_id: number[];
public comments: MotionComment[];
public workflow_id: number;
public state_id: number;
public state_extension: string;
public state_required_permission_to_see: string;
public statute_paragraph_id: number;
public recommendation_id: number;
public recommendation_extension: string;
public tags_id: number[];
public attachments_id: number[];
public polls: MotionPoll[];
public agenda_item_id: number;
public log_messages: MotionLog[];
public weight: number;
public sort_parent_id: number;
public constructor(input?: any) {
super('motions/motion', 'Motion', input);
}
/**
* returns the motion submitters userIDs
*/
public get submitterIds(): number[] {
return this.submitters
.sort((a: MotionSubmitter, b: MotionSubmitter) => {
return a.weight - b.weight;
})
.map((submitter: MotionSubmitter) => submitter.user_id);
}
public getTitle(): string {
if (this.identifier) {
return this.identifier + ': ' + this.title;
} else {
return this.title;
}
}
public getAgendaTitle(): string {
// if the identifier is set, the title will be 'Motion <identifier>'.
if (this.identifier) {
return 'Motion ' + this.identifier;
} else {
return this.getTitle();
}
}
public getAgendaTitleWithType(): string {
// Append the verbose name only, if not the special format 'Motion <identifier>' is used.
if (this.identifier) {
return 'Motion ' + this.identifier;
} else {
return this.getTitle() + ' (' + this.getVerboseName() + ')';
}
}
/**
* Formats the category for search
*
* @override
*/
public formatForSearch(): SearchRepresentation {
let searchValues = [this.title, this.text, this.reason];
if (this.amendment_paragraphs) {
searchValues = searchValues.concat(this.amendment_paragraphs.filter(x => !!x));
}
return searchValues;
}
public getDetailStateURL(): string {
return `/motions/${this.id}`;
}
public deserialize(input: any): void {
Object.assign(this, input);
this.log_messages = [];
if (input.log_messages instanceof Array) {
input.log_messages.forEach(logData => {
this.log_messages.push(new MotionLog(logData));
});
}
this.comments = [];
if (input.comments instanceof Array) {
input.comments.forEach(commentData => {
this.comments.push(new MotionComment(commentData));
});
}
}
}
|
{
"content_hash": "2580d35ebc0a72da5c8fcf596e869e44",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 97,
"avg_line_length": 30.508333333333333,
"alnum_prop": 0.6039333515432942,
"repo_name": "boehlke/OpenSlides",
"id": "4690acea80e45d2bef675a21393959c920c85956",
"size": "3661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/app/shared/models/motions/motion.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "43810"
},
{
"name": "Dockerfile",
"bytes": "855"
},
{
"name": "HTML",
"bytes": "210347"
},
{
"name": "JavaScript",
"bytes": "86897"
},
{
"name": "Python",
"bytes": "894871"
},
{
"name": "Smarty",
"bytes": "3818"
},
{
"name": "TypeScript",
"bytes": "1230305"
}
]
}
|
'use strict';
import { module } from 'angular';
export const CORE_PRESENTATION_ISVISIBLE_ISVISIBLE_DIRECTIVE = 'spinnaker.core.presentation.isVisible.directive';
export const name = CORE_PRESENTATION_ISVISIBLE_ISVISIBLE_DIRECTIVE; // for backwards compatibility
module(CORE_PRESENTATION_ISVISIBLE_ISVISIBLE_DIRECTIVE, []).directive('isVisible', function () {
return function (scope, element, attr) {
scope.$watch(attr.isVisible, function (visible) {
element.css('visibility', visible ? 'visible' : 'hidden');
});
};
});
|
{
"content_hash": "38cd6f90975080b04680d8d9834f68e1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 113,
"avg_line_length": 41.53846153846154,
"alnum_prop": 0.7314814814814815,
"repo_name": "ajordens/deck",
"id": "62c684e27ef9f2f1c4294bd474d2ac6eabe02403",
"size": "540",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/scripts/modules/core/src/presentation/isVisible/isVisible.directive.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "174302"
},
{
"name": "Dockerfile",
"bytes": "328"
},
{
"name": "HTML",
"bytes": "1467416"
},
{
"name": "JavaScript",
"bytes": "2086572"
},
{
"name": "Shell",
"bytes": "16819"
},
{
"name": "TypeScript",
"bytes": "4276533"
}
]
}
|
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package com.cloud.network.bigswitch;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.SerializedName;
/**
* AttachmentData contains information expected by Big Switch Controller
* in CreateBcfAttachmentCommand
*/
public class AttachmentData {
@SerializedName("port") final private Attachment attachment;
public Attachment getAttachment() {
return this.attachment;
}
public AttachmentData() {
this.attachment = new Attachment();
}
public class Attachment {
@SerializedName("id") private String id;
@SerializedName("tenant_name") private String tenantName;
@SerializedName("vlan") private Integer vlan;
@SerializedName("fixed_ips") final private List<IpAddress> fixedIps;
@SerializedName("mac_address") private String macAddress;
@SerializedName("bound_segment") final private BoundSegment boundSegment;
@SerializedName("binding:host_id") private String hostId;
public Attachment(){
this.boundSegment = new BoundSegment();
this.fixedIps = new ArrayList<IpAddress>();
}
public class BoundSegment {
@SerializedName("segmentation_id") private Integer segmentationId;
public Integer getSegmentationId() {
return segmentationId;
}
public void setSegmentationId(Integer segmentationId) {
this.segmentationId = segmentationId;
}
}
public class IpAddress {
@SerializedName("ip_address") private String address;
public IpAddress(final String ipAddr) {
this.address = ipAddr;
}
public String getIpAddress(){
return address;
}
}
private String state;
public String getTenantName() {
return tenantName;
}
public void setTenantName(final String tenantName) {
this.tenantName = tenantName;
}
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getHostId() {
return hostId;
}
public void setHostId(final String hostId) {
this.hostId = hostId;
}
public Integer getVlan() {
return vlan;
}
public void setVlan(final Integer vlan) {
this.vlan = vlan;
this.boundSegment.setSegmentationId(vlan);
}
public List<IpAddress> getIpv4List() {
return fixedIps;
}
public void addIpv4(final String ipv4) {
this.fixedIps.add(new IpAddress(ipv4));
}
public String getMac() {
return macAddress;
}
public void setMac(final String mac) {
this.macAddress = mac;
}
public BoundSegment getBoundSegment() {
return boundSegment;
}
public String getState() {
return state;
}
public void setState(final String state) {
this.state = state;
}
}
}
|
{
"content_hash": "bf5b2f0c4690e7f5ec9dd7ec42c4419d",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 81,
"avg_line_length": 28.153846153846153,
"alnum_prop": 0.61351217088922,
"repo_name": "wido/cloudstack",
"id": "40d99e3204e3703deb4a5aa069673dea2327c40f",
"size": "4026",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "plugins/network-elements/bigswitch/src/main/java/com/cloud/network/bigswitch/AttachmentData.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "10890"
},
{
"name": "C#",
"bytes": "2356211"
},
{
"name": "CSS",
"bytes": "358651"
},
{
"name": "Dockerfile",
"bytes": "2374"
},
{
"name": "FreeMarker",
"bytes": "4887"
},
{
"name": "Groovy",
"bytes": "146420"
},
{
"name": "HTML",
"bytes": "149088"
},
{
"name": "Java",
"bytes": "36088724"
},
{
"name": "JavaScript",
"bytes": "7976318"
},
{
"name": "Python",
"bytes": "13363686"
},
{
"name": "Ruby",
"bytes": "37714"
},
{
"name": "Shell",
"bytes": "784058"
},
{
"name": "XSLT",
"bytes": "58008"
}
]
}
|
<style>
.note::before {
content: 'Note: ';
font-variant: small-caps;
font-style: italic;
}
.doc h1 {
margin: 0;
}
</style>
# Creating WebUI Interfaces in `components/`
To create a WebUI interface in `components/` you need to follow different steps from [Creating WebUI Interfaces in `chrome/`](https://www.chromium.org/developers/webui). This guide is specific to creating a WebUI interface in `src/components/`. It is based on the steps I went through to create the WebUI infrastructure for chrome://safe-browsing in 'src/components/safe_browsing/content/web_ui/'.
[TOC]
<a name="creating_webui_page"></a>
## Creating the WebUI page
WebUI resources in `components/` will be added in your specific project folder. Create a project folder `src/components/hello_world/`. When creating WebUI resources, follow the [Web Development Style Guide](https://chromium.googlesource.com/chromium/src/+/master/styleguide/web/web.md). For a sample WebUI page you could start with the following files:
`src/components/hello_world/hello_world.html:`
```html
<!DOCTYPE HTML>
<html dir="$i18n{textdirection}">
<head>
<meta charset="utf-8">
<title>$i18n{helloWorldTitle}</title>
<link rel="stylesheet" href="hello_world.css">
<script src="chrome://resources/js/cr.js"></script>
<script src="chrome://resources/js/load_time_data.js"></script>
<script src="chrome://resources/js/util.js"></script>
<script src="strings.js"></script>
<script src="hello_world.js"></script>
</head>
<body style="font-family:$i18n{fontfamily};font-size:$i18n{fontSize}">
<h1>$i18n{helloWorldTitle}</h1>
<p id="welcome-message"></p>
</body>
</html>
```
`src/components/hello_world/hello_world.css:`
```css
p {
white-space: pre-wrap;
}
```
`src/components/hello_world/hello_world.js:`
```js
cr.define('hello_world', function() {
'use strict';
/**
* Be polite and insert translated hello world strings for the user on loading.
*/
function initialize() {
$('welcome-message').textContent = loadTimeData.getStringF('welcomeMessage',
loadTimeData.getString('userName'));
}
// Return an object with all of the exports.
return {
initialize: initialize,
};
});
document.addEventListener('DOMContentLoaded', hello_world.initialize);
```
## Adding the resources
Resource files are specified in a `.grdp` file. Here's our
`components/resources/hello_world_resources.grdp`:
```xml
<?xml version="1.0" encoding="utf-8"?>
<grit-part>
<include name="IDR_HELLO_WORLD_HTML" file="../../components/hello_world/hello_world.html" type="BINDATA" />
<include name="IDR_HELLO_WORLD_CSS" file="../../components/hello_world/hello_world.css" type="BINDATA" />
<include name="IDR_HELLO_WORLD_JS" file="../../components/hello_world/hello_world.js" type="BINDATA" />
</grit-part>
```
Add the created file in `components/resources/dev_ui_components_resources.grd`:
```xml
+<part file="hello_world_resources.grdp" />
```
## Adding URL constants for the new chrome URL
Create the `constants.cc` and `constants.h` files to add the URL constants. This is where you will add the URL or URL's which will be directed to your new resources.
`src/components/hello_world/constants.cc:`
```c++
const char kChromeUIHelloWorldURL[] = "chrome://hello-world/";
const char kChromeUIHelloWorldHost[] = "hello-world";
```
`src/components/hello_world/constants.h:`
```c++
extern const char kChromeUIHelloWorldURL[];
extern const char kChromeUIHelloWorldHost[];
```
## Adding localized strings
We need a few string resources for translated strings to work on the new resource. The welcome message contains a variable with a sample value so that it can be accurately translated. Create a new file `components/hello_world_strings.grdp`. You can add the messages as follow:
```xml
<message name="IDS_HELLO_WORLD_TITLE" desc="A happy message saying hello to the world">
Hello World!
</message>
<message name="IDS_HELLO_WORLD_WELCOME_TEXT" desc="Message welcoming the user to the hello world page">
Welcome to this fancy Hello World page <ph name="WELCOME_NAME">$1<ex>Chromium User</ex></ph>!
</message>
```
Add the created file in `components/components_strings.grd`:
```xml
+<part file="hello_world_strings.grdp" />
```
## Adding a WebUI class for handling requests to the chrome://hello-world/ URL
Next we need a class to handle requests to this new resource URL. Typically this will subclass `ChromeWebUI` (but WebUI dialogs should subclass `HtmlDialogUI` instead).
`src/components/hello_world/hello_world_ui.h:`
```c++
#ifndef COMPONENTS_HELLO_WORLD_HELLO_WORLD_UI_H_
#define COMPONENTS_HELLO_WORLD_HELLO_WORLD_UI_H_
#pragma once
#include "base/macros.h"
#include "content/public/browser/web_ui_controller.h"
// The WebUI for chrome://hello-world
class HelloWorldUI : public content::WebUIController {
public:
explicit HelloWorldUI(content::WebUI* web_ui);
~HelloWorldUI() override;
private:
DISALLOW_COPY_AND_ASSIGN(HelloWorldUI);
};
#endif // COMPONENTS_HELLO_WORLD_HELLO_WORLD_UI_H_
```
`src/components/hello_world/hello_world_ui.cc:`
```c++
#include "components/hello_world/hello_world_ui.h"
#include "components/grit/components_scaled_resources.h"
#include "components/grit/dev_ui_components_resources.h"
#include "components/hello_world/constants.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
HelloWorldUI::HelloWorldUI(content::WebUI* web_ui)
: content::WebUIController(web_ui) {
// Set up the chrome://hello-world source.
content::WebUIDataSource* html_source =
content::WebUIDataSource::Create(chrome::kChromeUIHelloWorldHost);
// Localized strings.
html_source->AddLocalizedString("helloWorldTitle", IDS_HELLO_WORLD_TITLE);
html_source->AddLocalizedString("welcomeMessage", IDS_HELLO_WORLD_WELCOME_TEXT);
// As a demonstration of passing a variable for JS to use we pass in the name "Bob".
html_source->AddString("userName", "Bob");
html_source->UseStringsJs();
// Add required resources.
html_source->AddResourcePath("hello_world.css", IDR_HELLO_WORLD_CSS);
html_source->AddResourcePath("hello_world.js", IDR_HELLO_WORLD_JS);
html_source->SetDefaultResource(IDR_HELLO_WORLD_HTML);
content::BrowserContext* browser_context =
web_ui->GetWebContents()->GetBrowserContext();
content::WebUIDataSource::Add(browser_context, html_source);
}
HelloWorldUI::~HelloWorldUI() {
}
```
## Adding new sources to Chrome
In order for your new class to be built and linked, you need to update the `BUILD.gn` and DEPS files. Create
`src/components/hello_world/BUILD.gn:`
```
sources = [
"hello_world_ui.cc",
"hello_world_ui.h",
...
```
and `src/components/hello_world/DEPS:`
```
include_rules = [
"+components/strings/grit/components_strings.h",
"+components/grit/components_scaled_resources.h"
"+components/grit/dev_ui_components_resources.h",
]
```
## Adding your WebUI request handler to the Chrome WebUI factory
The Chrome WebUI factory is where you setup your new request handler.
`src/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc:`
```c++
+ #include "components/hello_world/hello_world_ui.h"
+ #include "components/hello_world/constants.h"
...
+ if (url.host() == chrome::kChromeUIHelloWorldHost)
+ return &NewWebUI<HelloWorldUI>;
```
## Testing
You're done! Assuming no errors (because everyone gets their code perfect the first time) you should be able to compile and run chrome and navigate to `chrome://hello-world/` and see your nifty welcome text!
## Adding a callback handler
You probably want your new WebUI page to be able to do something or get information from the C++ world. For this, we use message callback handlers. Let's say that we don't trust the Javascript engine to be able to add two integers together (since we know that it uses floating point values internally). We could add a callback handler to perform integer arithmetic for us.
`src/components/hello_world/hello_world_ui.h:`
```c++
#include "content/public/browser/web_ui.h"
+
+ namespace base {
+ class ListValue;
+ } // namespace base
// The WebUI for chrome://hello-world
...
// Set up the chrome://hello-world source.
content::WebUIDataSource* html_source = content::WebUIDataSource::Create(hello_world::kChromeUIHelloWorldHost);
+
+ // Register callback handler.
+ RegisterMessageCallback("addNumbers",
+ base::BindRepeating(&HelloWorldUI::AddNumbers,
+ base::Unretained(this)));
// Localized strings.
...
virtual ~HelloWorldUI();
+
+ private:
+ // Add two numbers together using integer arithmetic.
+ void AddNumbers(const base::ListValue* args);
DISALLOW_COPY_AND_ASSIGN(HelloWorldUI);
};
```
`src/components/hello_world/hello_world_ui.cc:`
```c++
#include "components/hello_world/hello_world_ui.h"
+
+ #include "base/values.h"
#include "content/public/browser/browser_context.h"
...
HelloWorldUI::~HelloWorldUI() {
}
+
+ void HelloWorldUI::AddNumbers(const base::ListValue* args) {
+ int term1, term2;
+ if (!args->GetInteger(0, &term1) || !args->GetInteger(1, &term2))
+ return;
+ base::FundamentalValue result(term1 + term2);
+ AllowJavascript();
+ std::string callback_id;
+ args->GetString(0, &callback_id);
+ ResolveJavascriptCallback(base::Value(callback_id), result);
+ }
```
`src/components/hello_world/hello_world.js:`
```c++
function initialize() {
+ cr.sendWithPromise('addNumbers', [2, 2]).then((result) =>
+ addResult(result));
}
+
+ function addResult(result) {
+ alert('The result of our C++ arithmetic: 2 + 2 = ' + result);
+ }
return {
initialize: initialize,
};
```
You'll notice that the call is asynchronous. We must wait for the C++ side to call our Javascript function to get the result.
## Creating a WebUI Dialog
Some pages have many messages or share code that sends messages. To make possible message handling and/or to create a WebUI dialogue `c++->js` and `js->c++`, follow the guide in [WebUI Explainer](https://chromium.googlesource.com/chromium/src/+/master/docs/webui_explainer.md).
## DevUI Pages
DevUI pages are WebUI pages intended for developers, and unlikely used by most users. An example is `chrome://bluetooth-internals`. On Android Chrome, these pages are moved to a separate [Dynamic Feature Module (DFM)](https://chromium.googlesource.com/chromium/src/+/master/docs/android_dynamic_feature_modules.md) to reduce binary size. Most WebUI pages are DevUI. This is why in this doc uses `dev_ui_components_resources.{grd, h}` in its examples.
`components/` resources that are intended for end users are associated with `components_resources.{grd, h}` and `components_scaled_resorces.{grd, h}`. Use these in place of or inadditional to `dev_ui_components_resources.{grd, h}` if needed.
<script>
let nameEls = Array.from(document.querySelectorAll('[id], a[name]'));
let names = nameEls.map(nameEl => nameEl.name || nameEl.id);
let localLinks = Array.from(document.querySelectorAll('a[href^="#"]'));
let hrefs = localLinks.map(a => a.href.split('#')[1]);
hrefs.forEach(href => {
if (names.includes(href))
console.info('found: ' + href);
else
console.error('broken href: ' + href);
})
</script>
|
{
"content_hash": "049f6810926ef8f97cc29c91069aaf7d",
"timestamp": "",
"source": "github",
"line_count": 328,
"max_line_length": 450,
"avg_line_length": 34.73780487804878,
"alnum_prop": 0.7216956292785677,
"repo_name": "endlessm/chromium-browser",
"id": "006f3f72eff70e3da03a64b7935fcbf76df18ada",
"size": "11394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/webui_in_components.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": []
}
|
<?xml version="1.0" encoding="UTF-8"?>
<rootTag>
<Award>
<AwardTitle>Finescale Dynamics of the Double-Diffusive Thermocline</AwardTitle>
<AwardEffectiveDate>09/15/2013</AwardEffectiveDate>
<AwardExpirationDate>09/30/2017</AwardExpirationDate>
<AwardAmount>432056</AwardAmount>
<AwardInstrument>
<Value>Interagency Agreement</Value>
</AwardInstrument>
<Organization>
<Code>06040300</Code>
<Directorate>
<LongName>Directorate For Geosciences</LongName>
</Directorate>
<Division>
<LongName>Division Of Ocean Sciences</LongName>
</Division>
</Organization>
<ProgramOfficer>
<SignBlockName>Eric C. Itsweire</SignBlockName>
</ProgramOfficer>
<AbstractNarration/>
<MinAmdLetterDate>08/14/2013</MinAmdLetterDate>
<MaxAmdLetterDate>08/14/2013</MaxAmdLetterDate>
<ARRAAmount/>
<AwardID>1334914</AwardID>
<Investigator>
<FirstName>Timour</FirstName>
<LastName>Radko</LastName>
<EmailAddress>tradko@nps.edu</EmailAddress>
<StartDate>08/14/2013</StartDate>
<EndDate/>
<RoleCode>Principal Investigator</RoleCode>
</Investigator>
<Institution>
<Name>Naval Postgraduate School</Name>
<CityName>Monterey</CityName>
<ZipCode>939435000</ZipCode>
<PhoneNumber>8316562271</PhoneNumber>
<StreetAddress>1 University Circle</StreetAddress>
<CountryName>United States</CountryName>
<StateName>California</StateName>
<StateCode>CA</StateCode>
</Institution>
<ProgramElement>
<Code>1610</Code>
<Text>PHYSICAL OCEANOGRAPHY</Text>
</ProgramElement>
</Award>
</rootTag>
|
{
"content_hash": "f579f372b4a0dac54cd04cf72b4b88c7",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 83,
"avg_line_length": 32.36538461538461,
"alnum_prop": 0.6815210932857991,
"repo_name": "jallen2/Research-Trend",
"id": "6f64f13b34c590fad0c8f710fb1efc8cffd47cd6",
"size": "1683",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CU_Funding/2013/1334914.xml",
"mode": "33261",
"license": "mit",
"language": []
}
|
'use strict';
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const MessageParser = require('intl-messageformat-parser').default;
const {collectAllCustomElementsFromICU} = require('../../lib/i18n/i18n.js');
/** @typedef {Record<string, {message: string}>} LhlMessages */
/**
* Returns whether the string `lhlMessage` has ICU arguments matching the
* already extracted `goldenArgumentIds`. Assumes `goldenArgumentIds` is sorted.
* @param {Array<string>} goldenArgumentIds
* @param {string} lhlMessage
* @return {boolean}
*/
function equalArguments(goldenArgumentIds, lhlMessage) {
const parsedMessage = MessageParser.parse(lhlMessage);
const lhlArgumentElements = collectAllCustomElementsFromICU(parsedMessage.elements);
const lhlArgumentIds = [...lhlArgumentElements.keys()];
if (goldenArgumentIds.length !== lhlArgumentIds.length) return false;
lhlArgumentIds.sort();
for (let i = 0; i < goldenArgumentIds.length; i++) {
if (goldenArgumentIds[i] !== lhlArgumentIds[i]) {
return false;
}
}
return true;
}
/**
* Logs a message as removed if it hasn't been logged before.
* @param {Set<string>} alreadyLoggedPrunes
* @param {string} messageId
* @param {string} reason
*/
function logRemoval(alreadyLoggedPrunes, messageId, reason) {
if (alreadyLoggedPrunes.has(messageId)) return;
// eslint-disable-next-line no-console
console.log(`Removing message\n\t'${messageId}'\nfrom translations: ${reason}.`);
alreadyLoggedPrunes.add(messageId);
}
/**
* Returns a copy of `localeLhl` with only messages matching those from the golden locale.
* `goldenLocaleArgumentIds` values are assumed to be sorted.
* @param {Record<string, Array<string>>} goldenLocaleArgumentIds
* @param {LhlMessages} localeLhl
* @param {Set<string>} alreadyLoggedPrunes Set of prunes that have been logged and shouldn't be logged again.
* @return {LhlMessages}
*/
function pruneLocale(goldenLocaleArgumentIds, localeLhl, alreadyLoggedPrunes) {
/** @type {LhlMessages} */
const remainingMessages = {};
for (const [messageId, {message}] of Object.entries(localeLhl)) {
const goldenArgumentIds = goldenLocaleArgumentIds[messageId];
if (!goldenArgumentIds) {
logRemoval(alreadyLoggedPrunes, messageId, 'it is no longer found in Lighthouse');
continue;
}
if (!equalArguments(goldenArgumentIds, message)) {
logRemoval(alreadyLoggedPrunes, messageId,
'its ICU arguments don\'t match the current version of the message');
continue;
}
remainingMessages[messageId] = {message};
}
return remainingMessages;
}
/**
* Returns a copy of `goldenLhl` with the messages replaced with a sorted list of
* argument ids found in each message.
* @param {LhlMessages} goldenLhl
* @return {Record<string, Array<string>>}
*/
function getGoldenLocaleArgumentIds(goldenLhl) {
/** @type {Record<string, Array<string>>} */
const goldenLocaleArgumentIds = {};
for (const [messageId, {message}] of Object.entries(goldenLhl)) {
const parsedMessage = MessageParser.parse(message);
const goldenArgumentElements = collectAllCustomElementsFromICU(parsedMessage.elements);
const goldenArgumentIds = [...goldenArgumentElements.keys()].sort();
goldenLocaleArgumentIds[messageId] = goldenArgumentIds;
}
return goldenLocaleArgumentIds;
}
/**
* For every locale LHL file, remove any messages that don't have a matching
* message in `en-US.json`. There is a matching golden message if:
* - there is a golden message with the same message id and
* - that message has the same ICU arguments (by count and argument ids).
*
* If a new `en-US.json` message is sufficiently different so that existing
* translations should no longer be used, it's up to the author to remove them
* (e.g. by picking a new message id).
*/
function pruneObsoleteLhlMessages() {
const goldenLhl = require('../../lib/i18n/locales/en-US.json');
const goldenLocaleArgumentIds = getGoldenLocaleArgumentIds(goldenLhl);
// Find all locale files, ignoring self-generated en-US, en-XL, and ctc files.
const ignore = [
'**/.ctc.json',
'**/en-US.json',
'**/en-XL.json',
];
const globPattern = 'lighthouse-core/lib/i18n/locales/**/+([-a-zA-Z0-9]).json';
const lhRoot = `${__dirname}/../../../`;
const localePaths = glob.sync(globPattern, {
ignore,
cwd: lhRoot,
});
/** @type {Set<string>} */
const alreadyLoggedPrunes = new Set();
for (const localePath of localePaths) {
const absoluteLocalePath = path.join(lhRoot, localePath);
// readFileSync so that the file is pulled again once updated by a collect-strings run
const localeLhl = JSON.parse(fs.readFileSync(absoluteLocalePath, 'utf-8'));
const prunedLocale = pruneLocale(goldenLocaleArgumentIds, localeLhl, alreadyLoggedPrunes);
const stringified = JSON.stringify(prunedLocale, null, 2) + '\n';
fs.writeFileSync(absoluteLocalePath, stringified);
}
}
module.exports = {
pruneObsoleteLhlMessages,
// Exported for testing.
getGoldenLocaleArgumentIds,
pruneLocale,
};
|
{
"content_hash": "bfe5f6024cc98e35426c1b6e02e937f9",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 110,
"avg_line_length": 34.261744966442954,
"alnum_prop": 0.7177277179236043,
"repo_name": "wardpeet/lighthouse",
"id": "33e002a921eed9d96806bd5ba3321036c9610696",
"size": "5696",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lighthouse-core/scripts/i18n/prune-obsolete-lhl-messages.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "54123"
},
{
"name": "HTML",
"bytes": "119934"
},
{
"name": "JavaScript",
"bytes": "3323926"
},
{
"name": "Python",
"bytes": "1269"
},
{
"name": "Ruby",
"bytes": "7024"
},
{
"name": "Shell",
"bytes": "24123"
}
]
}
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// import { FormsModule } from '@angular/forms';
import { RoomService } from './services/room.service';
import { RoomListComponent } from './components/room-list/room-list.component';
@NgModule({
imports: [
CommonModule,
// FormsModule,
],
declarations: [
RoomListComponent,
],
providers: [
RoomService
]
})
export class RoomModule {
}
|
{
"content_hash": "693cd9a92e4398c3462e639d9df08abe",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 79,
"avg_line_length": 20.727272727272727,
"alnum_prop": 0.6732456140350878,
"repo_name": "Obelixx/AASmartHouse",
"id": "b3db5b9d1be430759c05cecaa740c2c1457dc414",
"size": "456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AAWebSmartHouse_WebClient/app/room/room.module.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "116"
},
{
"name": "C#",
"bytes": "122657"
},
{
"name": "CSS",
"bytes": "86"
},
{
"name": "HTML",
"bytes": "20355"
},
{
"name": "JavaScript",
"bytes": "13709"
},
{
"name": "TypeScript",
"bytes": "51075"
}
]
}
|
package org.apache.directory.fortress.rest;
import org.apache.directory.fortress.core.ConfigMgr;
import org.apache.directory.fortress.core.ConfigMgrFactory;
import org.apache.directory.fortress.core.model.Configuration;
import org.apache.directory.fortress.core.model.Props;
import org.apache.directory.fortress.core.model.FortRequest;
import org.apache.directory.fortress.core.model.FortResponse;
import org.apache.directory.fortress.core.rest.RestUtils;
import org.apache.directory.fortress.core.SecurityException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
/**
* Utility for Fortress Rest Server. This class is thread safe.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
class ConfigMgrImpl extends AbstractMgrImpl
{
private static final Logger LOG = LoggerFactory.getLogger( ConfigMgrImpl.class.getName() );
/**
*
* @param request
* @return
*/
/* No qualifier */ FortResponse addConfig(FortRequest request)
{
FortResponse response = createResponse();
try
{
ConfigMgr configMgr = ConfigMgrFactory.createInstance();
Configuration inCfg = (Configuration)request.getEntity();
Configuration outCfg = configMgr.add( inCfg );
if ( outCfg != null )
{
response.setEntity( outCfg );
}
}
catch ( SecurityException se )
{
createError( response, LOG, se );
}
return response;
}
/**
*
* @param request
* @return
*/
/* No qualifier */ FortResponse updateConfig(FortRequest request)
{
FortResponse response = createResponse();
try
{
ConfigMgr configMgr = ConfigMgrFactory.createInstance();
Configuration inCfg = (Configuration)request.getEntity();
Configuration outCfg = configMgr.update( inCfg );
if ( outCfg != null )
{
response.setEntity( outCfg );
}
}
catch ( SecurityException se )
{
createError( response, LOG, se );
}
return response;
}
/**
*
* @param request
* @return
*/
/* No qualifier */ FortResponse deleteConfig(FortRequest request)
{
FortResponse response = createResponse();
try
{
ConfigMgr configMgr = ConfigMgrFactory.createInstance();
if ( request.getEntity() == null )
{
configMgr.delete( request.getValue() );
}
else
{
Properties inProperties = RestUtils.getProperties( (Props)request.getEntity() );
configMgr.delete( request.getValue(), inProperties );
}
}
catch ( SecurityException se )
{
createError( response, LOG, se );
}
return response;
}
/**
*
* @param request
* @return
*/
/* No qualifier */ FortResponse readConfig(FortRequest request)
{
FortResponse response = createResponse();
try
{
ConfigMgr configMgr = ConfigMgrFactory.createInstance();
Configuration outCfg = configMgr.read( request.getValue() );
if ( outCfg != null )
{
response.setEntity( outCfg );
}
}
catch ( SecurityException se )
{
createError( response, LOG, se );
}
return response;
}
}
|
{
"content_hash": "8d40fa86e4e4ec09ba9a90f43898b493",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 96,
"avg_line_length": 27.08888888888889,
"alnum_prop": 0.5706863549357397,
"repo_name": "apache/directory-fortress-enmasse",
"id": "f180e067a19da6b0a8938d3c0d04e4f030d5acb5",
"size": "4495",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/apache/directory/fortress/rest/ConfigMgrImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1592"
},
{
"name": "HTML",
"bytes": "9857"
},
{
"name": "Java",
"bytes": "546577"
}
]
}
|
module RUser
# This module defines the RandomUser.me API constants used by classes.
# @author Joshua Kendall
module Api
# The URL for the API.
URL = 'https://api.randomuser.me'.freeze
# The version of the API that is used.
VERSION = '0.7'.freeze
end
end
|
{
"content_hash": "7ea1fb1d4e4fd28cc226e97d46a811b0",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 72,
"avg_line_length": 25.363636363636363,
"alnum_prop": 0.6774193548387096,
"repo_name": "kendallshq/ruser",
"id": "1226172d41a13436d257d6f0e0e5e669dc2b10b2",
"size": "309",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/ruser/api.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "12359"
}
]
}
|
package com.ceph.rados.exceptions;
/**
* Contains all native error codes with appropriate names and messages.
*/
public enum ErrorCode {
EPERM(-1, "Operation not permitted"),
ENOENT(-2, "No such file or directory"),
ESRCH(-3, "No such process"),
EINTR(-4, "Interrupted system call"),
EIO(-5, "I/O error"),
ENXIO(-6, "No such device or address"),
E2BIG(-7, "Argument list too long"),
ENOEXEC(-8, "Exec format error"),
EBADF(-9, "Bad file number"),
ECHILD(-10, "No child processes"),
EAGAIN(-11, "Try again"),
ENOMEM(-12, "Out of memory"),
EACCES(-13, "Permission denied"),
EFAULT(-14, "Bad address"),
ENOTBLK(-15, "Block device required"),
EBUSY(-16, "Device or resource busy"),
EEXIST(-17, "File exists"),
EXDEV(-18, "Cross-device link"),
ENODEV(-19, "No such device"),
ENOTDIR(-20, "Not a directory"),
EISDIR(-21, "Is a directory"),
EINVAL(-22, "Invalid argument"),
ENFILE(-23, "File table overflow"),
EMFILE(-24, "Too many open files"),
ENOTTY(-25, "Not a typewriter"),
ETXTBSY(-26, "Text file busy"),
EFBIG(-27, "File too large"),
ENOSPC(-28, "No space left on device"),
ESPIPE(-29, "Illegal seek"),
EROFS(-30, "Read-only file system"),
EMLINK(-31, "Too many links"),
EPIPE(-32, "Broken pipe"),
EDOM(-33, "Argument out of range"),
ERANGE(-34, "Result too large"),
EDEADLK(-35, "Resource deadlock would occur"),
ENAMETOOLONG(-36, "Name too long"),
ENOLCK(-37, "No record locks available"),
ENOSYS(-38, "Function not implemented"),
ENOTEMPTY(-39, "Directory not empty"),
ELOOP(-40, "Too many symbolic links"),
ENOMSG(-42, "No errorMessage of desired type"),
EIDRM(-43, "Identifier removed"),
ECHRNG(-44, "Channel number out of range"),
EL2NSYNC(-45, "Level 2 not synchronized"),
EL3HLT(-46, "Level 3 halted"),
EL3RST(-47, "Level 3 reset"),
ELNRNG(-48, "Link number out of range"),
EUNATCH(-49, "Protocol driver not attached"),
ENOCSI(-50, "No CSI structure available"),
EL2HLT(-51, "Level 2 halted"),
EBADE(-52, "Invalid exchange"),
EBADR(-53, "Invalid request descriptor"),
EXFULL(-54, "Exchange full"),
ENOANO(-55, "No anode"),
EBADRQC(-56, "Invalid request errorCode"),
EBADSLT(-57, "Invalid slot"),
EBFONT(-59, "Bad font file format"),
ENOSTR(-60, "Not a stream"),
ENODATA(-61, "No data available"),
ETIME(-62, "Stream timeout"),
ENOSR(-63, "Out of streams resources"),
ENONET(-64, "Machine is not on the network"),
ENOPKG(-65, "Package not installed"),
EREMOTE(-66, "Object is remote"),
ENOLINK(-67, "Link has been severed"),
EADV(-68, "Advertise error"),
ESRMNT(-69, "Srmount error"),
ECOMM(-70, "Communication error on send"),
EPROTO(-71, "Protocol error"),
EMULTIHOP(-72, "Multihop attempted"),
EDOTDOT(-73, "RFS specific error"),
EBADMSG(-74, "Not a data errorMessage"),
EOVERFLOW(-75, "Value too large for defined data type"),
ENOTUNIQ(-76, "Name not unique on network"),
EBADFD(-77, "File descriptor in bad state"),
EREMCHG(-78, "Remote address changed"),
ELIBACC(-79, "Can not access a needed shared library"),
ELIBBAD(-80, "Accessing a corrupted shared library"),
ELIBSCN(-81, ".lib section in a.out corrupted"),
ELIBMAX(-82, "Attempting to link in too many shared libraries"),
ELIBEXEC(-83, "Cannot exec a shared library directly"),
EILSEQ(-84, "Illegal byte sequence"),
ERESTART(-85, "Interrupted system call should be restarted"),
ESTRPIPE(-86, "Streams pipe error"),
EUSERS(-87, "Too many users"),
ENOTSOCK(-88, "Socket operation on non-socket"),
EDESTADDRREQ(-89, "Destination address required"),
EMSGSIZE(-90, "errorMessage too long"),
EPROTOTYPE(-91, "Protocol wrong type for socket"),
ENOPROTOOPT(-92, "Protocol not available"),
EPROTONOSUPPORT(-93, "Protocol not supported"),
ESOCKTNOSUPPORT(-94, "Socket type not supported"),
EOPNOTSUPP(-95, "Operation not supported on transport endpoint"),
EPFNOSUPPORT(-96, "Protocol family not supported"),
EAFNOSUPPORT(-97, "Address family not supported by protocol"),
EADDRINUSE(-98, "Address already in use"),
EADDRNOTAVAIL(-99, "Cannot assign requested address"),
ENETDOWN(-100, "Network is down"),
ENETUNREACH(-101, "Network is unreachable"),
ENETRESET(-102, "Network dropped connection because of reset"),
ECONNABORTED(-103, "Software caused connection abort"),
ECONNRESET(-104, "Connection reset by peer"),
ENOBUFS(-105, "No buffer space available"),
EISCONN(-106, "Transport endpoint is already connected"),
ENOTCONN(-107, "Transport endpoint is not connected"),
ESHUTDOWN(-108, "Cannot send after transport endpoint shutdown"),
ETOOMANYREFS(-109, "Too many references: cannot splice"),
ETIMEDOUT(-110, "Connection timed out"),
ECONNREFUSED(-111, "Connection refused"),
EHOSTDOWN(-112, "Host is down"),
EHOSTUNREACH(-113, "No route to host"),
EALREADY(-114, "Operation already in progress"),
EINPROGRESS(-115, "Operation now in progress"),
ESTALE(-116, "Stale NFS file handle"),
EUCLEAN(-117, "Structure needs cleaning"),
ENOTNAM(-118, "Not a XENIX named type file"),
ENAVAIL(-119, "No XENIX semaphores available"),
EISNAM(-120, "Is a named type file"),
EREMOTEIO(-121, "Remote I/O error"),
EDQUOT(-122, "Quota exceeded"),
ENOMEDIUM(-123, "No medium found"),
EMEDIUMTYPE(-124, "Wrong medium type"),
ECANCELED(-125, "Operation Canceled"),
ENOKEY(-126, "Required key not available"),
EKEYEXPIRED(-127, "Key has expired"),
EKEYREVOKED(-128, "Key has been revoked"),
EKEYREJECTED(-129, "Key was rejected by service"),
EOWNERDEAD(-130, "Owner died"),
ENOTRECOVERABLE(-131, "State not recoverable");
private final int errorCode;
private final String errorMessage;
ErrorCode(int errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
/**
* @param errorCode the error code
* @return appropriate name of the error depending on the code
*/
public static String getErrorName(int errorCode) {
ErrorCode error = ErrorCode.getEnum(errorCode);
if (error != null) {
return error.name();
}
return "UNKNOWN_ERROR";
}
/**
* @param errorCode the error code
* @return appropriate message containing an explanation of the code
*/
public static String getErrorMessage(int errorCode) {
ErrorCode error = ErrorCode.getEnum(errorCode);
if (error != null) {
return error.getErrorMessage();
}
return String.format("Unknown error code: %d", errorCode);
}
/**
* @param errorCode the error code
* @return the ErrorCode enum representing the error code
*/
public static ErrorCode getEnum(int errorCode) {
for (ErrorCode value : values()) {
if(value.errorCode == errorCode) {
return value;
}
}
return null;
}
}
|
{
"content_hash": "4ca4065c23efef1febe670e7904444e7",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 72,
"avg_line_length": 38.130208333333336,
"alnum_prop": 0.6393935254746619,
"repo_name": "ceph/rados-java",
"id": "b1f5d40e1e2b257a091f241e5664d9918b158a27",
"size": "7996",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/ceph/rados/exceptions/ErrorCode.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "629"
},
{
"name": "Java",
"bytes": "204639"
},
{
"name": "Shell",
"bytes": "11516"
}
]
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Trash
* This is the class for the trash can that appears when dragging an app.
*/
cr.define('ntp', function() {
'use strict';
/**
* @constructor
* @extends {HTMLDivElement}
* @implements {cr.ui.DragWrapperDelegate}
*/
function Trash(trash) {
trash.__proto__ = Trash.prototype;
trash.initialize();
return trash;
}
Trash.prototype = {
__proto__: HTMLDivElement.prototype,
initialize: function(element) {
this.dragWrapper_ = new cr.ui.DragWrapper(this, this);
},
/**
* Determines whether we are interested in the drag data for |e|.
* @param {Event} e The event from drag enter.
* @return {boolean} True if we are interested in the drag data for |e|.
*/
shouldAcceptDrag: function(e) {
var tile = ntp.getCurrentlyDraggingTile();
if (!tile)
return false;
return tile.firstChild.canBeRemoved();
},
/** @override */
doDragOver: function(e) {
ntp.getCurrentlyDraggingTile().dragClone.classList.add(
'hovering-on-trash');
ntp.setCurrentDropEffect(e.dataTransfer, 'move');
e.preventDefault();
},
/** @override */
doDragEnter: function(e) {
this.doDragOver(e);
},
/** @override */
doDrop: function(e) {
e.preventDefault();
var tile = ntp.getCurrentlyDraggingTile();
tile.firstChild.removeFromChrome();
tile.landedOnTrash = true;
},
/** @override */
doDragLeave: function(e) {
ntp.getCurrentlyDraggingTile().dragClone.classList.remove(
'hovering-on-trash');
},
};
return {
Trash: Trash,
};
});
|
{
"content_hash": "a3ee753155b4d366763ae15b9de86a7a",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 76,
"avg_line_length": 24.06578947368421,
"alnum_prop": 0.6172772006560963,
"repo_name": "Samsung/ChromiumGStreamerBackend",
"id": "510348a10f1ec200f9c6b41fb6ba4f9661b31008",
"size": "1829",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "chrome/browser/resources/ntp4/trash.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": []
}
|
"""empty message
Revision ID: 298bbf22bdb8
Revises: b976e7a7dc35
Create Date: 2017-04-02 13:11:00.655727
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '298bbf22bdb8'
down_revision = 'b976e7a7dc35'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('person', sa.Column('is_admin', sa.Boolean()))
op.add_column('person', sa.Column('is_brewer', sa.Boolean()))
op.add_column('person', sa.Column('is_manager', sa.Boolean()))
op.execute('UPDATE person SET is_admin=False, is_brewer=False, is_manager=False')
op.alter_column('person', 'is_admin', nullable=False)
op.alter_column('person', 'is_brewer', nullable=False)
op.alter_column('person', 'is_manager', nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('person', 'is_manager')
op.drop_column('person', 'is_brewer')
op.drop_column('person', 'is_admin')
# ### end Alembic commands ###
|
{
"content_hash": "7476f4516b02309e2aaf39009ca6d8da",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 85,
"avg_line_length": 31.166666666666668,
"alnum_prop": 0.6737967914438503,
"repo_name": "CapitalD/taplist",
"id": "25f1970b18bcd9b8f90cffabbd29a6cbd65cf459",
"size": "1122",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "migrations/versions/298bbf22bdb8_.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1628"
},
{
"name": "HTML",
"bytes": "51309"
},
{
"name": "JavaScript",
"bytes": "1871"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "45741"
}
]
}
|
#include "sdl_rpc_plugin/commands/mobile/subscribe_button_response.h"
namespace sdl_rpc_plugin {
using namespace application_manager;
namespace commands {
SDL_CREATE_LOG_VARIABLE("Commands")
SubscribeButtonResponse::SubscribeButtonResponse(
const application_manager::commands::MessageSharedPtr& message,
ApplicationManager& application_manager,
app_mngr::rpc_service::RPCService& rpc_service,
app_mngr::HMICapabilities& hmi_capabilities,
policy::PolicyHandlerInterface& policy_handler)
: CommandResponseImpl(message,
application_manager,
rpc_service,
hmi_capabilities,
policy_handler) {}
SubscribeButtonResponse::~SubscribeButtonResponse() {}
void SubscribeButtonResponse::Run() {
SDL_LOG_AUTO_TRACE();
// check if response false
if (true == (*message_)[strings::msg_params].keyExists(strings::success)) {
if ((*message_)[strings::msg_params][strings::success].asBool() == false) {
SDL_LOG_ERROR("Success = false");
SendResponse(false);
return;
}
}
// TODO(DK): Some logic
SendResponse(true);
}
} // namespace commands
} // namespace sdl_rpc_plugin
|
{
"content_hash": "3d690c9e1ab76c1fed39334139df6f71",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 79,
"avg_line_length": 27.954545454545453,
"alnum_prop": 0.6634146341463415,
"repo_name": "smartdevicelink/sdl_core",
"id": "216d1e186df77f5dcf9dd38f3cd779c8f3287d26",
"size": "2743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/application_manager/rpc_plugins/sdl_rpc_plugin/src/commands/mobile/subscribe_button_response.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "27115"
},
{
"name": "C++",
"bytes": "22338348"
},
{
"name": "CMake",
"bytes": "435397"
},
{
"name": "M4",
"bytes": "25347"
},
{
"name": "Makefile",
"bytes": "139997"
},
{
"name": "Python",
"bytes": "566738"
},
{
"name": "Shell",
"bytes": "696186"
}
]
}
|
import MySQLdb
import Apriori
# get tags data from db
db = MySQLdb.connect( "localhost", "", "", "" )
cursor = db.cursor()
sql = "SELECT * FROM article_tags LIMIT 0,50000"
tagsdata = {}
try:
cursor.execute( sql )
result = cursor.fetchall()
for row in result:
tags = []
id = row[0]
articleid = row[1]
tagid = row[2]
if articleid not in tagsdata:
tagsdata[articleid] = []
tagsdata[articleid].append(tagid)
#print "id is %d, article_id is %s, tag_id is %d" % ( id, articleid, tagid )
except MySQLdb.Error,e:
print "Error: unable to fecht db! %d: %s" % (e.args[0],e.args[1])
print "data count is ", len( tagsdata )
apriori = Apriori.Apriori( tagsdata )
apriori.main()
db.close()
|
{
"content_hash": "6ec2701ac81a68c3d04f19fbf77c533a",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 78,
"avg_line_length": 24.928571428571427,
"alnum_prop": 0.6547277936962751,
"repo_name": "jjyoung/Apriori",
"id": "57b338d3e57a1c4e2cb7cd574c2f5005ebcc5bf3",
"size": "788",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tool_tagsRelation.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "6521"
}
]
}
|
import {WPlus} from "../../1_lexer/tokens";
import {regex as reg, Expression, tok, seq} from "../combi";
import {IStatementRunnable} from "../statement_runnable";
export class WithName extends Expression {
public getRunnable(): IStatementRunnable {
return seq(tok(WPlus), reg(/^\w+$/));
}
}
|
{
"content_hash": "a895e604e0e2bcfc198d1e5a5b328a08",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 60,
"avg_line_length": 33.22222222222222,
"alnum_prop": 0.68561872909699,
"repo_name": "larshp/abapOpenChecksJS",
"id": "be81def7385edfdd33811231d2b5978360486939",
"size": "299",
"binary": false,
"copies": "2",
"ref": "refs/heads/hvam/upd0910",
"path": "packages/core/src/abap/2_statements/expressions/with_name.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ABAP",
"bytes": "7026"
},
{
"name": "CSS",
"bytes": "51"
},
{
"name": "HTML",
"bytes": "1211"
},
{
"name": "JavaScript",
"bytes": "1049"
},
{
"name": "TypeScript",
"bytes": "122500"
}
]
}
|
End of preview.